:- module(epf_tests, []).

:- use_module(library(array)).
:- use_module('../examples/epf').
:- use_module('../examples/pclp', [belief/4, {}/1]).
:- use_module(library(array/opencl), [opencl_device/2]).
:- use_module(test_devices, [test_device/2]).

% A grammar of two terms over a point moving at a constant speed: the belief over x and v,
% a term predicts the next position, pt(X), and consumes the detection that matches it. The
% pool holds the two positions of the track and a clutter point far from both.

move_cond(S0, S, pt(X)) :-
   S = S0.put(x, X),
   { X is S0.x + S0.v }.

track([A, B]) -->
   term(move, move_cond, [x, v], A),
   term(move, move_cond, [x, v], B).

prior(B) :-
   belief([x, v], [[0.0, 1.0]], [[[1.0, 0], [0, 0.25]]], B0),
   B = B0.

pool([0-pt(1.0), 1-pt(2.1), 2-pt(7.0)]).

noises([move-q_r([[0.01, 0], [0, 0.01]], [[1.0]])]).

% track_model(+Dev, -Model): the model of the track on Dev.
track_model(Dev, Model) :-
   prior(Prior),
   pool(Pool),
   noises(Noises),
   model([ device(Dev), prior(Prior), detections(Pool), noises(Noises),
           kinds([move-pt(_)]), detection_prob([pt(_)-0.9]), clutter([pt(_)-1]),
           clutter_tau(3.0) ],
         Model).

near(X, Y) :-
   abs(X - Y) < 1.0e-4 * (1 + abs(X)).

:- begin_tests(epf).

% The greedy descent consumes the two positions of the track, leaving the clutter point,
% and the replay of the parse gives its score again.
test(search_finds_the_track_and_replay_gives_its_score, [timeout(600)]) :-
   track_model(pocl, Model),
   once(search(ordered, track(Parse), Model, Score)),
   Parse == [0-pt(1.0), 1-pt(2.1)],
   replay(track(Parse), Model, Score2),
   near(Score, Score2).

% The search leaves the variables of the grammar unbound where it makes no choice: a synth
% predicts the position.
test(a_synth_is_the_prediction, [timeout(600)]) :-
   track_model(pocl, Model),
   once(search(ordered, track([synth-pt(X) | _]), Model, _)),
   near(X, 1.0).

% The fit scores the parse as the search does, before any step, and the descent lowers the
% score at every step, on every device.
test(the_fit_starts_at_the_score_of_the_search_and_lowers_it, [timeout(600), forall(test_device(D, _))]) :-
   track_model(D, Model),
   once(search(ordered, track(Parse), Model, Score)),
   fit(track(Parse), Model, [steps(2), rate(0.01)], fit(Scores, Noises)),
   Scores = [S0, S1, S2],
   near(S0, Score),
   S1 < S0, S2 < S1,
   Noises = [move-q_r([[Q0, _], [_, Q1]], [[R0]])],
   Q0 > 0, Q1 > 0, R0 > 0.

% The gradients of one step of the fit, a detection consumed, against finite differences
% in double precision by eval/3: with a cotangent on every output, the gradient in the
% process noise of v, in the measurement noise and in the mean of x of the belief in.
test(a_step_of_the_fit_has_the_gradients_of_its_outputs, [timeout(600)]) :-
   epf:fit_step(consume([x, v], [x, v], move, epf_tests:move_cond), Inputs, Outs, Bars, Grads, Pattern),
   Pattern = pt(_),
   Data0 = [[0.0, 1.0], [1.0, 0.0, 0.0, 0.25], [0.0, 0.0], [0.0], [1.2]],
   maplist([O, B, B-L]>>( shape(O, S), foldl([E, A0, A]>>(A is A0*E), S, 1, N), numlist(1, N, Is),
                          maplist([I, X]>>(X is 0.5 + sin(I*1.7)), Is, L) ), Outs, Bars, BarData),
   maplist([I, D, I-D]>>true, Inputs, Data0, Given),
   append(Given, BarData, All),
   weighted(Outs, Given, BarData, F0),
   H = 1.0e-5,
   forall(member(Ii-J, [2-1, 3-0, 0-0]),
          ( nth0(Ii, Grads, G), eval(G, All, GL), nth0(J, GL, Gj),
            nth0(Ii, Data0, D), nth0(J, D, X, Rest), Xp is X + H, nth0(J, Dp, Xp, Rest),
            nth0(Ii, Given, _, Others), nth0(Ii, Inputs, In), nth0(Ii, Givenp, In-Dp, Others),
            weighted(Outs, Givenp, BarData, Fp),
            FD is (Fp - F0) / H,
            abs(Gj - FD) < 1.0e-3 * (1 + abs(Gj)) )).

% weighted(+Outs, +Given, +BarData, -F): the sum over the outputs of their elements by the
% cotangents, on the data Given.
weighted(Outs, Given, BarData, F) :-
   foldl({Given}/[O, _-B, A0, A]>>( eval(O, Given, L), foldl([X, Y, S0, S]>>(S is S0 + X*Y), L, B, 0.0, D), A is A0 + D ),
         Outs, BarData, 0.0, F).

% A kind without noises in the model is an error of the term, under either engine.
test(a_kind_without_noises_is_an_error, [timeout(600), error(existence_error(noises, move))]) :-
   prior(Prior),
   pool(Pool),
   model([prior(Prior), detections(Pool), detection_prob([pt(_)-0.9]), clutter([pt(_)-1])], Model),
   once(search(ordered, track(_), Model, _)).

:- end_tests(epf).
