:- module(ekf_tests, []).

:- use_module(library(array)).
:- use_module('../examples/ekf').
:- use_module('../examples/ukf', [cv_range_model/3]).
:- use_module(library(array/opencl), [opencl_device/2]).
:- use_module(test_devices, [test_device/2]).
:- use_module(library(clpfd), [transpose/2]).
:- use_module(library(clpBNR)).
:- use_module('../examples/train', [tensor/3]).

% The references are evaluated once for every program and data, then read from the disk:
% see reference.pl.
:- set_prolog_flag(eval_cache, true).

% The step against an extended Kalman filter in plain Prolog, on lists, the Jacobians of the
% constant-velocity model written by hand.

near(Xs, Ys) :-
   maplist([X, Y]>>(abs(X - Y) < 1.0e-3 * (1 + abs(Y))), Xs, Ys).

mat_mul(A, B, C) :-
   transpose(B, Bt),
   maplist({Bt}/[Row, Out]>>maplist({Row}/[Col, V]>>dot(Row, Col, V), Bt, Out), A, C).

dot(Xs, Ys, V) :-
   foldl([X, Y, S0, S]>>(S is S0 + X*Y), Xs, Ys, 0.0, V).

mat_add(A, B, C) :- maplist([Ra, Rb, Rc]>>maplist([X, Y, Z]>>(Z is X + Y), Ra, Rb, Rc), A, B, C).
mat_sub(A, B, C) :- maplist([Ra, Rb, Rc]>>maplist([X, Y, Z]>>(Z is X - Y), Ra, Rb, Rc), A, B, C).
mat_vec(A, X, Y) :- maplist({X}/[Row, V]>>dot(Row, X, V), A, Y).

inv2([[A, B], [C, D]], [[A1, B1], [C1, D1]]) :-
   Det is A*D - B*C,
   A1 is D/Det, B1 is -B/Det, C1 is -C/Det, D1 is A/Det.

% ekf_ref(+Mu, +P, +Q, +R, +Zobs, -Out): one state of the constant-velocity model.
ekf_ref(Mu, P, Q, R, Zobs, out(MuPred, PPred, F, H, MuPost, PPost)) :-
   cv_range_model(Mu, YE, _),
   maplist([E, V]>>(V is E), YE, MuPred),
   F = [[1.0, 0.0, 0.5, 0.0], [0.0, 1.0, 0.0, 0.5], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]],
   transpose(F, Ft),
   mat_mul(F, P, FP), mat_mul(FP, Ft, FPFt), mat_add(FPFt, Q, PPred),
   cv_range_model(MuPred, _, ZE),
   maplist([E, V]>>(V is E), ZE, Z),
   MuPred = [X, Y | _], Rg is sqrt(X*X + Y*Y), Hx is X/Rg, Hy is Y/Rg,
   H = [[Hx, Hy, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]],
   transpose(H, Ht),
   mat_mul(PPred, Ht, PHt), mat_mul(H, PHt, HPHt), mat_add(HPHt, R, S),
   inv2(S, Sinv),
   mat_mul(PHt, Sinv, K),
   maplist([Zo, Zp, E]>>(E is Zo - Zp), Zobs, Z, Innov),
   mat_vec(K, Innov, KE),
   maplist([A, B, C]>>(C is A + B), MuPred, KE, MuPost),
   transpose(PHt, HP), mat_mul(K, HP, KHP), mat_sub(PPred, KHP, PPost).

% Two tracks and their observations.
case(dims(2, 4, 2), Data, in(Mu, P, Q, R, Zobs), Refs) :-
   Mus = [[10, 5, 1, 0.5], [3, 8, -1, 0.2]],
   Ps = [[[1, 0.2, 0, 0], [0.2, 1, 0, 0], [0, 0, 0.5, 0.1], [0, 0, 0.1, 0.5]],
         [[0.8, 0, 0.1, 0], [0, 1.2, 0, 0.1], [0.1, 0, 0.4, 0], [0, 0.1, 0, 0.3]]],
   Qs = [[0.01, 0, 0, 0], [0, 0.01, 0, 0], [0, 0, 0.02, 0], [0, 0, 0, 0.02]],
   Rs = [[0.5, 0.1], [0.1, 0.5]],
   Zs = [[11.9, 5.4], [8.3, 8.2]],
   maplist({Qs, Rs}/[M1, P1, Z1, O]>>ekf_ref(M1, P1, Qs, Rs, Z1, O), Mus, Ps, Zs, Refs),
   flatten(Mus, MuL), flatten(Ps, PL), flatten(Qs, QL), flatten(Rs, RL), flatten(Zs, ZL),
   Data = [Mu-MuL, P-PL, Q-QL, R-RL, Zobs-ZL].

% expected(+Field, +Refs, -Flat): the field of every state's reference, flattened in order.
expected(Field, Refs, Flat) :-
   maplist({Field}/[Ref, V]>>arg(Field, Ref, V), Refs, Vs), flatten(Vs, Flat).

fields([1-mu_pred, 2-p_pred, 3-f, 4-h, 5-mu_post, 6-p_post]).

:- begin_tests(ekf).

test(step_matches_the_filter, [timeout(120)]) :-
   case(Dims, Data, In, Refs),
   ekf_step(cv_range_model, Dims, In, Out),
   fields(Fields),
   forall(member(K-_, Fields),
          ( arg(K, Out, Name), eval(Name, Data, Vs), expected(K, Refs, Want), near(Vs, Want) )).

test(step_on_devices, [timeout(300), forall(test_device(D, _))]) :-
   case(Dims, Data, In, Refs),
   ekf_step(cv_range_model, Dims, In, Out),
   forall(member(K, [3, 4, 5, 6]),
          ( arg(K, Out, Name), run(Name, Data, Vs, [device(D)]), expected(K, Refs, Want), near(Vs, Want) )).

% The batch stays symbolic: one handle of the posterior, its mean and covariance, for every
% number of tracks, its inputs names on host copied to the device.
test(one_handle_every_batch, [timeout(300), forall(test_device(D, _))]) :-
   B::integer(1, 64),
   Shapes = [[B, 4], [B, 4, 4], [4, 4], [2, 2], [B, 2]],
   maplist([S, Hn]>>( shape(Hn, S), device(Hn, host) ), Shapes, Hosts),
   maplist({D}/[Hn, Dn]>>copy(Hn, Dn, D), Hosts, [Mu, P, Q, R, Zobs]),
   ekf_step(cv_range_model, dims(B, 4, 2), in(Mu, P, Q, R, Zobs), out(_, _, _, _, MuPost, PPost)),
   compile_all([MuPost, PPost], [], Exe),
   signature_all([MuPost, PPost], Slots, _, _),
   case(_, Data, in(Mu0, P0, Q0, R0, Z0), Refs),
   maplist({Data}/[N0, S, Arg]>>( member(N1-Vs, Data), N1 == N0, !, tensor(S, Vs, Arg) ),
           [Mu0, P0, Q0, R0, Z0], [[2, 4], [2, 4, 4], [4, 4], [2, 2], [2, 2]], Given),
   pairs_keys_values(Bound, Hosts, Given),
   maplist({Bound}/[slot(N, _, _, _), A]>>( member(N1-A, Bound), N1 == N, ! ), Slots, Args),
   run(Exe, Args, [RMu, RP]),
   run(RMu, [], VMu, []), run(RP, [], VP, []),
   expected(5, Refs, WMu), expected(6, Refs, WP),
   near(VMu, WMu), near(VP, WP),
   var(B),
   release(Exe).

:- end_tests(ekf).
