:- module(tracking, [track/4, detections/3, best_track/3, demo/1]).
:- use_module(library(array)).
:- use_module(library(array/buffer)).
:- use_module(library(clpBNR)).

/** <module> Tracking by association: the detections on the device once, the state kept there

A target moves along a line at constant velocity, and at each time several detections are
seen, one of them the target, the others clutter. Which detection is the target's at each
time is a choice, and the track is the sequence of choices of least cost: the search
backtracks over the choices, a Kalman filter scores each.

The style of this example is the one a grammar with full backtracking needs:

  - the detections of the whole sequence are realized on the device once, an input of
    every step given as they are, no copy;
  - the state of the filter, mean and covariance, is a name realized on the device, and a
    step gives a new one, so that two branches of the search hold two states and a branch
    abandoned leaves nothing to undo;
  - a step is a small program, built by a tabled predicate that compiles it at the end,
    compile/2: the first call builds and compiles, every call after gets a copy of the
    program from the table, its handle on it, and run/4 is a launch. Nothing holds a
    handle.

    track(+Obs, +Times, -Track, -Cost)
        Obs the detections realized on the device, Times the times of the sequence, each a
        list of the indices of its detections; Track a detection index per time, Cost the
        sum of the steps' costs, a negative log-likelihood up to a constant, each step's
        under the gate. Nondeterministic: the tracks come by backtracking.
    best_track(+Obs, +Times, -Track-Cost)
        The track of least cost.
    detections(+Positions, +Device, -Obs)
        Positions realized on Device.
    demo(+Device)
        A target among clutter at six times, every track searched twice, for the best and
        for the count, the steps run counted against the one program compiled.

The state is one name of seven floats, x, v, P00, P01, P10, P11 and the cost of the step
that made it, and a step on a detection z: predict x' = x + v, P' = F P F' + Q; innovate
y = z - x', S = P'00 + R; update by the gain K = P'[:, 0] / S; its cost y^2 / S + log S.
*/

% Process and measurement noise, and the gate on a step's cost.
noise(0.01, 0.25).
gate(4.0).

% step(+Device, +M, -Obs, -S0, -K, -S1): the program of one step on Device: on the state S0
% and the detection K[0] of Obs, M detections, S1 the new state, its cost last. Obs, S0 and
% K are the inputs, given at the run, so that the program holds no name of the search and a
% table may hold the program: built once, every call after gets a copy of it from the
% table, its handle on it, compiled at the end.
:- table step/6.
step(Device, M, Obs, S0, K, S1) :-
   noise(Q, R),
   shape(Obs, [M]), device(Obs, Device),
   shape(S0, [7]), device(S0, Device),
   shape(K, [1]), kind(K, int), Last is M - 1, elements(K, 0-Last),
   shape(S1, [7]),
   over([], [Z := Obs[K[0]],
             Xp := S0[0] + S0[1],
             P00 := S0[2] + S0[3] + S0[4] + S0[5] + Q,
             P01 := S0[3] + S0[5],
             P10 := S0[4] + S0[5],
             P11 := S0[5] + Q,
             Y := Z - Xp,
             S := P00 + R,
             K0 := P00 / S,
             K1 := P10 / S,
             S1[0] := Xp + K0 * Y,
             S1[1] := S0[1] + K1 * Y,
             S1[2] := (1 - K0) * P00,
             S1[3] := (1 - K0) * P01,
             S1[4] := P10 - K1 * P00,
             S1[5] := P11 - K1 * P01,
             S1[6] := Y * Y / S + log(S)]),
   compile(S1, [device(Device)]).

% detections(+Positions, +Device, -Obs): the positions, floats, realized on Device.
detections(Positions, Device, Obs) :-
   length(Positions, M),
   compound_name_arguments(Data, data, Positions),
   buffer_from_data(Buffer, float32, M, Data),
   shape(H, [M]), kind(H, float), value(H, Buffer),
   copy(H, Obs, Device),
   realize([Obs], [], []).

% initial(+X, +Device, -S): the state at x, at rest, uncertain, on Device.
initial(X, Device, S) :-
   buffer_from_data(Buffer, float32, 7, data(X, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0)),
   shape(H, [7]), kind(H, float), value(H, Buffer),
   copy(H, S, Device),
   realize([S], [], []).

track(Obs, Times, Track, Cost) :-
   shape(Obs, [M]),
   device(Obs, Device),
   Times = [First | _],
   First = [K0 | _],
   run(Obs, [], Positions, []),
   nth0(K0, Positions, X0),
   initial(X0, Device, S0),
   foldl(associate(Obs, M, Device), Times, Track, S0-0.0, _-Cost).

% associate(+Obs, +M, +Device, +Candidates, -K, +S0-Cost0, -S1-Cost): the detection K of the
% time, one of its Candidates, by backtracking; the step on it must pass the gate.
associate(Obs, M, Device, Candidates, K, S0-Cost0, S1-Cost) :-
   member(K, Candidates),
   flag(tracking_steps, Steps, Steps + 1),
   step(Device, M, ObsIn, In, Kin, Out),
   run(Out, [ObsIn-Obs, In-S0, Kin-[K]], S1, [result(name)]),
   run(S1, [], State, []),
   last(State, StepCost),
   gate(Gate),
   StepCost < Gate,
   Cost is Cost0 + StepCost.

best_track(Obs, Times, Best) :-
   aggregate_all(min(Cost, Track), track(Obs, Times, Track, Cost), min(C, T)),
   Best = T-C.

% demo(+Device): a target at x = 10 + 2 t with noisy detections, two clutter detections per
% time; the detections are indices 0.. in order of time.
demo(Device) :-
   numlist(0, 5, Ts),
   foldl(observations, Ts, []-[], Positions-Times),
   reverse(Positions, Ps), reverse(Times, Tm),
   detections(Ps, Device, Obs),
   flag(tracking_steps, _, 0),
   statistics(cputime, T0), get_time(W0),
   best_track(Obs, Tm, Track-Cost),
   aggregate_all(count, track(Obs, Tm, _, _), Tracks),
   statistics(cputime, T1), get_time(W1),
   Cpu is T1 - T0, Wall is W1 - W0,
   flag(tracking_steps, Steps, Steps),
   format("best track ~w, cost ~3f; ~d tracks pass the gate, ~d steps run, one program compiled; ~3f s cpu, ~3f s wall~n",
          [Track, Cost, Tracks, Steps, Cpu, Wall]).

observations(T, Ps0-Ts0, Acc) :-
   length(Ps0, I0),
   X is 10 + 2*T + 0.1*sin(7*T),
   C1 is X + 3 + T, C2 is X - 4 + 0.5*T,
   I1 is I0 + 1, I2 is I0 + 2,
   Acc = [C2, C1, X | Ps0]-[[I0, I1, I2] | Ts0].
