:- module(pclp_tests, []).

:- use_module(library(array)).
:- use_module('../examples/pclp').
:- use_module(library(array/opencl), [opencl_device/2]).
:- use_module(test_devices, [test_device/2]).
:- use_module(library(clpfd), [transpose/2]).

% 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 of pclp on a batch is checked against a reference on lists: the same model run
% with is/2 at the sigma points of one state, the moments by hand, and, the observation
% being 2-dimensional, the closed forms of the inverse and the determinant of Szz. The batch
% is the states one after the other.

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

% A list Cholesky, row by row (Cholesky-Banachiewicz).
chol_ref(A, L) :-
   foldl(chol_row, A, L, [], _).

chol_row(ARow, LRow, Done, Done1) :-
   foldl(chol_elem(ARow), Done, [], Pre),
   length(Pre, I), nth0(I, ARow, Aii), dot_prefix(Pre, Pre, S), Lii is sqrt(Aii - S),
   length(ARow, N), Z is N - I - 1, length(Zeros, Z), maplist(=(0.0), Zeros),
   append([Pre, [Lii], Zeros], LRow), append(Done, [LRow], Done1).

chol_elem(ARow, LRowJ, Acc0, Acc) :-
   length(Acc0, J), nth0(J, ARow, Aij), nth0(J, LRowJ, Ljj),
   dot_prefix(Acc0, LRowJ, S),
   Lij is (Aij - S) / Ljj, append(Acc0, [Lij], Acc).

dot_prefix(Xs, Ys, S) :-
   same_length(Xs, Pre), append(Pre, _, Ys),
   foldl([X, Y, S0, S1]>>(S1 is S0 + X*Y), Xs, Pre, 0.0, S).

vec_add(X, Y, Z) :- maplist([A, B, C]>>(C is A + B), X, Y, Z).
vec_sub(X, Y, Z) :- maplist([A, B, C]>>(C is A - B), X, Y, Z).
vec_dot(X, Y, D) :- foldl([A, B, S0, S]>>(S is S0 + A*B), X, Y, 0.0, D).
mat_vec(M, V, R) :- maplist([Row, X]>>vec_dot(Row, V, X), M, R).
mat_mul(A, B, C) :- transpose(B, Bt), maplist([Row, CRow]>>mat_vec(Bt, Row, CRow), A, C).
mat_sub(A, B, C) :- maplist(vec_sub, A, B, C).
mat_scale(S, A, B) :- maplist([Row, Row1]>>maplist([X, Y]>>(Y is S*X), Row, Row1), A, B).
mean(Rows, Mu) :- length(Rows, K), transpose(Rows, Cols), maplist([Col, M]>>(sum_list(Col, S), M is S / K), Cols, Mu).

% cov(+As, +Bs, -C): the K rows of As and Bs are paired samples, C their covariance with
% weights 1/K.
cov(As, Bs, C) :-
   mean(As, MA), mean(Bs, MB), length(As, K),
   maplist({MA}/[A, D]>>vec_sub(A, MA, D), As, DAs),
   maplist({MB}/[B, D]>>vec_sub(B, MB, D), Bs, DBs),
   transpose(DAs, DAt), transpose(DBs, DBt),
   maplist({DBt, K}/[Ai, Row]>>maplist({Ai, K}/[Bj, X]>>(vec_dot(Ai, Bj, S), X is S / K), DBt, Row), DAt, C).

inv2([[A, B], [C, D]], [[IA, IB], [IC, ID]]) :-
   Det is A*D - B*C, IA is D/Det, IB is -B/Det, IC is -C/Det, ID is A/Det.
logdet2([[A, B], [C, D]], L) :- L is log(A*D - B*C).

% cv_range_model(+Xs, -Ys, -Zs): a constant-velocity track (x, y, vx, vy) over a half-unit
% step, observed as its range and its y, on lists, for the reference.
cv_range_model([X, Y, Vx, Vy], [X + 0.5 * Vx, Y + 0.5 * Vy, Vx, Vy], [sqrt(X * X + Y * Y), Y]).

% ukf_ref(+Model, +Crit, +Mu, +P, +Q, +R, +Zdets, -Out): one state against every detection.
ukf_ref(Model, Crit, Mu, P0, Q, R, Zdets, out(MuPred, PPred, MuZ, Czz, Scores, MuPosts, PPost)) :-
   length(Mu, N), K is 2*N,
   maplist(vec_add, P0, Q, P),
   mat_scale(N, P, S), chol_ref(S, L), transpose(L, Cols),
   maplist({Mu}/[Col, X]>>vec_add(Mu, Col, X), Cols, Plus),
   maplist({Mu}/[Col, X]>>vec_sub(Mu, Col, X), Cols, Minus),
   append(Plus, Minus, Xs), length(Xs, K),
   maplist({Model}/[X, Y, Z]>>( call(Model, X, YE, ZE), maplist([E, V]>>(V is E), YE, Y), maplist([E, V]>>(V is E), ZE, Z) ),
           Xs, Ys, Zs),
   mean(Ys, MuPred), mean(Zs, MuZ),
   cov(Ys, Ys, PPred), cov(Zs, Zs, Czz), cov(Ys, Zs, Pyz),
   maplist(vec_add, Czz, R, Szz),
   inv2(Szz, Sinv), logdet2(Szz, LogDet), length(MuZ, M), C0 is 0.5*M*log(2*pi),
   maplist({MuZ}/[Zd, E]>>vec_sub(Zd, MuZ, E), Zdets, Es),
   maplist({Sinv, LogDet, C0, Crit}/[E, Sc]>>( mat_vec(Sinv, E, SE), vec_dot(E, SE, D2),
                                                ( D2 =< Crit -> Sc is 0.5*D2 + 0.5*LogDet + C0 ; Sc is inf ) ),
           Es, Scores),
   mat_mul(Pyz, Sinv, G),
   maplist({G, MuPred}/[E, MuPost]>>( mat_vec(G, E, GE), vec_add(MuPred, GE, MuPost) ), Es, MuPosts),
   mat_mul(G, Szz, GS), transpose(G, Gt), mat_mul(GS, Gt, GSGt), mat_sub(PPred, GSGt, PPost).

% The step on the dict of the keys x, y, vx, vy: the constant-velocity track, observed as
% its range and its y.
cv_step(S0, S, [Rg, Y0]) :-
   Y0 = S0.y,
   { X is S0.x + 0.5*S0.vx,
     Y is S0.y + 0.5*S0.vy,
     Vx is S0.vx,
     Vy is S0.vy,
     Rg is sqrt(S0.x*S0.x + S0.y*S0.y)
   },
   S = _{x: X, y: Y, vx: Vx, vy: Vy}.

% Two tracks, four-dimensional, two detections near their predicted observations and one
% far away; the gate at 0.99 has Crit = -2 log(0.01).
case(Mus, Ps, Q, R, Zdets, 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]]],
   Q = [[0.1, 0, 0, 0], [0, 0.1, 0, 0], [0, 0, 0.05, 0], [0, 0, 0, 0.05]],
   R = [[0.5, 0.1], [0.1, 0.5]],
   Zdets = [[11.5, 5.3], [8.4, 8.0], [30, 30]],
   Crit is -2*log(0.01),
   maplist({Q, R, Zdets, Crit}/[M1, P1, O]>>ukf_ref(cv_range_model, Crit, M1, P1, Q, R, Zdets, O), Mus, Ps, Refs).

keys([x, y, vx, vy]).

% 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).

% step(+B, -S, -Z, -Post, -Nll, -Closed, -ZMu, -ZCov): the step of the case on the belief B.
step(B, S, Z, Post, Nll, Closed, ZMu, ZCov) :-
   keys(Keys),
   case(_, _, Q, R, Zdets, _),
   belief_request(B, Keys, Q, S0, [threshold(0.99)]),
   cv_step(S0, S, Z),
   belief_predict(Z, ZMu, ZCov),
   belief_observe(S, Z, Zdets, R, Post, Nll),
   belief_close(S, Closed).

% outputs(-Names, -Data, -Refs): the names of the step on the constant belief of the case,
% paired with the field of the reference they must equal.
outputs(Names, [], Refs) :-
   case(Mus, Ps, _, _, _, Refs),
   keys(Keys),
   belief(Keys, Mus, Ps, B),
   step(B, _, _, Post, Nll, Closed, ZMu, ZCov),
   belief(_, MuPost, PPost, Post), belief(_, MuPred, PPred, Closed),
   Names = [1-MuPred, 2-PPred, 3-ZMu, 4-ZCov, 5-Nll, 6-MuPost, 7-PPost].

fields([1-mu_pred, 2-p_pred, 3-mu_z, 4-z_cov, 5-nll, 6-mu_post, 7-p_post]).

% The note term of the OMR grammar: the state unit, top_y, sx, margin; the pitch a discrete
% choice in -20..20; the note at the next x, its y the pitch in units below the top line.
note_cond(Pitch, S0, S, [X, Y]) :-
   discrete(S0, Pitch, -20, 20),
   S = S0.put(sx, X),
   { X is S0.sx + S0.margin,
     Y is S0.top_y + Pitch*S0.unit
   }.

note_model(Pitch, [U, T, Sx, M], [U, T, Sx + M, M], [Sx + M, T + Pitch*U]).

% Two choices: the pitch, and whether the note is one or two margins away.
two_cond(P, Q, S0, S, [X, Y]) :-
   discrete(S0, P, -2, 2),
   discrete(S0, Q, 0, 1),
   S = S0.put(sx, X),
   { X is S0.sx + (1 + Q)*S0.margin,
     Y is S0.top_y + P*S0.unit
   }.

two_model(P, Q, [U, T, Sx, M], [U, T, Sx + (1 + Q)*M, M], [Sx + (1 + Q)*M, T + P*U]).

note_keys([unit, top_y, sx, margin]).

note_case(Mus, Ps, Q, R, Zdets) :-
   Mus = [[20, 100, 118, 23], [18, 102, 140, 22]],
   Ps = [[[25, 0, 0, 0], [0, 100, 0, 0], [0, 0, 100, 0], [0, 0, 0, 25]],
         [[4, 0, 0, 0], [0, 9, 0, 0], [0, 0, 16, 0], [0, 0, 0, 4]]],
   Q = [[0.0001, 0, 0, 0], [0, 0.001, 0, 0], [0, 0, 0.001, 0], [0, 0, 0, 4]],
   R = [[9, 0], [0, 1]],
   Zdets = [[141.0, 226.2], [159.0, 243.8], [400, 400]].

% note_refs(+Model, +Values, -Refs): the reference of the note case under Model at each
% discrete value, for each state, in that order: the order of the hypothesis axis, then
% of the batch.
note_refs(Model, Values, Refs) :-
   note_case(Mus, Ps, Q, R, Zdets),
   Crit is -2*log(0.01),
   findall(Ref, ( member(V, Values), nth0(I, Mus, Mu), nth0(I, Ps, P),
                  Goal =.. [Model | V], ukf_ref(Goal, Crit, Mu, P, Q, R, Zdets, Ref) ),
           Refs).

note_step(Post, Nll, Closed, Pitch) :-
   note_keys(Keys), note_case(Mus, Ps, Q, R, Zdets),
   belief(Keys, Mus, Ps, B),
   belief_request(B, Keys, Q, S0, [threshold(0.99)]),
   note_cond(Pitch, S0, S, Z),
   belief_observe(S, Z, Zdets, R, Post, Nll),
   belief_close(S, Closed).

:- begin_tests(pclp).

test(eval_matches_reference, [timeout(60), forall((fields(Fs), member(I-Name, Fs)))]) :-
   outputs(Names, Data, Refs),
   memberchk(I-Out, Names), expected(I, Refs, Expected),
   eval(Out, Data, V),
   (  near(Expected, V)
   -> true
   ;  format("~w~n expected ~w~n got      ~w~n", [Name, Expected, V]), fail
   ).

test(run_matches_reference, [timeout(300), forall((test_device(D, _), member(I-Name, [5-nll, 6-mu_post, 7-p_post])))]) :-
   outputs(Names, Data, Refs),
   memberchk(I-Out, Names), expected(I, Refs, Expected),
   run(Out, Data, V, [device(D)]),
   (  near(Expected, V)
   -> true
   ;  format("~w ~w~n expected ~w~n got      ~w~n", [D, Name, Expected, V]), fail
   ).

% The far detection is outside the gate of both states, the near ones inside their own.
test(gate, [timeout(60), true(Open == [1, 0, 0, 0, 1, 0])]) :-
   outputs(Names, Data, _),
   memberchk(5-Nll, Names),
   eval(Nll, Data, V),
   maplist([S, O]>>( S =:= inf -> O = 0 ; O = 1 ), V, Open).

% The batch and the detections are extent variables until the data fixes them: the step is
% built once on input names, and run at two states and three detections, then at one and two.
test(symbolic_batch_and_detections, [timeout(60)]) :-
   keys(Keys),
   case(Mus, Ps, Q, R, Zdets, Refs),
   shape(Mu, [B, 4]), shape(P, [B, 4, 4]), shape(ZDet, [D, 2]),
   belief(Keys, Mu, P, Belief),
   belief_request(Belief, Keys, Q, S0, [threshold(0.99)]),
   cv_step(S0, S, Z),
   belief_observe(S, Z, ZDet, R, Post, Nll), belief(_, MuPost, _, Post),
   flatten(Mus, MuL), flatten(Ps, PL), flatten(Zdets, ZL),
   eval(Nll, [Mu-MuL, P-PL, ZDet-ZL], V), expected(5, Refs, E5), near(E5, V),
   Mus = [Mu1 | _], Ps = [P1 | _], Zdets = [Z1, Z2 | _], Refs = [Ref1 | _],
   flatten(P1, PL1), append(Z1, Z2, ZL2),
   eval(MuPost, [Mu-Mu1, P-PL1, ZDet-ZL2], V2),
   arg(6, Ref1, [MuPost1, MuPost2 | _]), append(MuPost1, MuPost2, E2), near(E2, V2),
   var(B), var(D).

% A belief of pairs selected: the states are the pairs named, their covariance the state's.
test(select_gathers_pairs, [timeout(60)]) :-
   case(Mus, Ps, _, _, _, Refs), keys(Keys), belief(Keys, Mus, Ps, B),
   step(B, _, _, Post, _, _, _, _),
   belief_select(Post, [[1, 0, 1], [0, 1, 2]], Sel, []),
   belief_mean(Sel, x, X), belief_var(Sel, vy, Vy),
   eval(X, [], Xs), eval(Vy, [], Vys),
   Refs = [Ref1, Ref2],
   arg(6, Ref1, Pairs1), arg(6, Ref2, Pairs2),
   nth0(0, Pairs2, [X10 | _]), nth0(1, Pairs1, [X01 | _]), nth0(2, Pairs2, [X12 | _]),
   near([X10, X01, X12], Xs),
   arg(7, Ref1, PP1), arg(7, Ref2, PP2),
   nth0(3, PP1, Row1), nth0(3, Row1, V0), nth0(3, PP2, Row2), nth0(3, Row2, V1),
   near([V1, V0, V1], Vys).

% A belief over extra keys: the keys outside the step follow through their correlation with
% its input. With a linear model the unscented transform is exact, so the step on four keys
% with the global update equals the step on all five with the fifth carried through.
linear_step(S0, S, [X, Y]) :-
   { X is S0.x + 0.5*S0.vx,
     Y is S0.y + 0.5*S0.vy,
     Vx is S0.vx,
     Vy is S0.vy
   },
   S = _{x: X, y: Y, vx: Vx, vy: Vy}.

% w first in the belief, so that the step's keys are not a prefix of it.
five_keys(B) :-
   Mus = [[2, 10, 5, 1, 0.5], [-1, 3, 8, -1, 0.2]],
   Ps = [[[2, 0.3, 0, 0.2, 0], [0.3, 1, 0.2, 0, 0], [0, 0.2, 1, 0, 0], [0.2, 0, 0, 0.5, 0.1], [0, 0, 0, 0.1, 0.5]],
         [[1.5, 0, 0.4, 0, 0.1], [0, 0.8, 0, 0.1, 0], [0.4, 0, 1.2, 0, 0.1], [0, 0.1, 0, 0.4, 0], [0.1, 0, 0.1, 0, 0.3]]],
   belief([w, x, y, vx, vy], Mus, Ps, B).

test(extra_keys_follow_the_step, [timeout(120)]) :-
   five_keys(B),
   Q4 = [[0.1, 0, 0, 0], [0, 0.1, 0, 0], [0, 0, 0.05, 0], [0, 0, 0, 0.05]],
   Q5 = [[0, 0, 0, 0, 0], [0, 0.1, 0, 0, 0], [0, 0, 0.1, 0, 0], [0, 0, 0, 0.05, 0], [0, 0, 0, 0, 0.05]],
   R = [[0.5, 0.1], [0.1, 0.5]],
   Zdets = [[10.6, 5.2], [2.4, 8.3]],
   belief_request(B, [x, y, vx, vy], Q4, S0), linear_step(S0, S, Z),
   belief_observe(S, Z, Zdets, R, Post4, Nll4), belief_close(S, Closed4),
   belief_request(B, [w, x, y, vx, vy], Q5, T0), linear_step(T0, T, Zt), { W is T0.w },
   belief_observe(T.put(w, W), Zt, Zdets, R, Post5, Nll5), belief_close(T.put(w, W), Closed5),
   belief(_, Mu4, P4, Post4), belief(_, Mu5, P5, Post5),
   belief(_, Mc4, Pc4, Closed4), belief(_, Mc5, Pc5, Closed5),
   forall(member(A-E, [Nll4-Nll5, Mu4-Mu5, P4-P5, Mc4-Mc5, Pc4-Pc5]),
          ( eval(A, [], Va), eval(E, [], Ve), near(Ve, Va) )).

% A discrete variable is a leading axis: a hypothesis per value, scored against every state
% and every detection, equal to the reference at that value.
test(discrete_variable_is_a_leading_axis, [timeout(120)]) :-
   note_step(Post, Nll, Closed, Pitch),
   shape(Pitch, Sp), Sp == [41, 1, 1],
   shape(Nll, Sn), Sn == [41, 2, 3],
   numlist(-20, 20, Values), findall([V], member(V, Values), Vs),
   note_refs(note_model, Vs, Refs),
   expected(5, Refs, E5), eval(Nll, [], V5), near(E5, V5),
   belief(_, MuPost, PPost, Post), shape(MuPost, Sm), Sm == [41, 2, 3, 4], shape(PPost, Spp), Spp == [41, 2, 4, 4],
   expected(6, Refs, E6), eval(MuPost, [], V6), near(E6, V6),
   expected(7, Refs, E7), eval(PPost, [], V7), near(E7, V7),
   belief(_, MuPred, _, Closed), shape(MuPred, Sc), Sc == [41, 2, 4],
   expected(1, Refs, E1), eval(MuPred, [], V1), near(E1, V1).

test(discrete_runs_on_every_device, [timeout(300), forall(test_device(D, _))]) :-
   note_step(_, Nll, _, _),
   eval(Nll, [], Ref), run(Nll, [], V, [device(D)]), near(Ref, V).

% Tuples selected out of the hypotheses: the state of each, and the pitch it chose.
test(selection_labels_the_discrete_variable, [timeout(120)]) :-
   note_step(Post, _, Closed, _),
   belief_select(Post, [[6, 20], [0, 1], [0, 2]], Sel, [PitchL]),
   eval(PitchL, [], Ls), Ls == [-14, 0],
   belief_mean(Sel, sx, Sx), eval(Sx, [], Sxs),
   note_refs(note_model, [[-14], [0]], [Ref0, _, _, Ref1]),
   arg(6, Ref0, Pairs0), nth0(0, Pairs0, [_, _, Sx0 | _]),
   arg(6, Ref1, Pairs1), nth0(2, Pairs1, [_, _, Sx1 | _]),
   near([Sx0, Sx1], Sxs),
   belief_var(Sel, margin, Vm), eval(Vm, [], Vms),
   arg(7, Ref0, PP0), nth0(3, PP0, R0), nth0(3, R0, M0),
   arg(7, Ref1, PP1), nth0(3, PP1, R1), nth0(3, R1, M1),
   near([M0, M1], Vms),
   belief_select(Closed, [[40, 0], [1, 1]], SelC, [PitchC]),
   eval(PitchC, [], Lc), Lc == [20, -20],
   belief(_, MuC, _, SelC), shape(MuC, Smc), Smc == [2, 4],
   belief_mean(SelC, top_y, Ty), eval(Ty, [], Tys),
   note_refs(note_model, [[20], [-20]], [_, RefA, _, RefB]),
   arg(1, RefA, [_, TyA | _]), arg(1, RefB, [_, TyB | _]), near([TyA, TyB], Tys).

% Two discrete variables are the product of their domains, the last declared the outer
% axis; a name in the other alone keeps an extent of 1 on it.
test(two_discrete_variables_are_a_product, [timeout(120)]) :-
   note_keys(Keys), note_case(Mus, Ps, Q, R, Zdets),
   belief(Keys, Mus, Ps, B),
   belief_request(B, Keys, Q, S0, [threshold(0.99)]),
   two_cond(P, Qd, S0, S, [X, Y]),
   shape(P, Sp), Sp == [5, 1, 1], shape(Qd, Sq), Sq == [2, 1, 1, 1],
   shape(X, Sx), Sx == [2, 1, 2, 8], shape(Y, Sy), Sy == [5, 2, 8],
   belief_observe(S, [X, Y], Zdets, R, Post, Nll),
   shape(Nll, Sn), Sn == [2, 5, 2, 3],
   findall([Pv, Qv], ( between(0, 1, Qv), between(-2, 2, Pv) ), Vs),
   note_refs(two_model, Vs, Refs),
   expected(5, Refs, E5), eval(Nll, [], V5), near(E5, V5),
   belief_select(Post, [[1, 0], [0, 4], [0, 1], [0, 1]], Sel, [Ql, Pl]),
   eval(Pl, [], [-2, 2]), eval(Ql, [], [1, 0]),
   belief_mean(Sel, sx, Sxm), eval(Sxm, [], Sxs),
   note_refs(two_model, [[-2, 1], [2, 0]], [RefA, _, _, RefB]),
   arg(6, RefA, PairsA), nth0(0, PairsA, [_, _, SxA | _]),
   arg(6, RefB, PairsB), nth0(1, PairsB, [_, _, SxB | _]),
   near([SxA, SxB], Sxs).

% A choice made already: an integer in the domain is a constant of the step, no axis.
test(discrete_given_is_a_constant, [timeout(60)]) :-
   note_keys(Keys), note_case(Mus, Ps, Q, R, Zdets),
   belief(Keys, Mus, Ps, B),
   belief_request(B, Keys, Q, S0, [threshold(0.99)]),
   note_cond(-14, S0, S, Z),
   belief_observe(S, Z, Zdets, R, Post, Nll),
   shape(Nll, Sn), Sn == [2, 3],
   Post = belief(_, _, _, Los), Los == [],
   note_refs(note_model, [[-14]], Refs),
   expected(5, Refs, E5), eval(Nll, [], V5), near(E5, V5).

% A choice given to the request by a name: a hypothesis axis of one value, the input's.
test(discrete_given_by_a_name, [timeout(60)]) :-
   note_keys(Keys), note_case(Mus, Ps, Q, R, Zdets),
   belief(Keys, Mus, Ps, B),
   belief_request(B, Keys, Q, S0, [threshold(0.99), given([Pitch-G])]),
   note_cond(Pitch, S0, S, Z),
   shape(G, SG), SG == [1], kind(G, KG), KG == int,
   belief_observe(S, Z, Zdets, R, Post, Nll),
   shape(Nll, Sn), Sn == [1, 2, 3],
   Post = belief(_, _, _, Los), Los == [-20],
   note_refs(note_model, [[-14]], Refs),
   expected(5, Refs, E5), eval(Nll, [G-[-14]], V5), near(E5, V5),
   note_refs(note_model, [[3]], Refs3),
   expected(5, Refs3, E3), eval(Nll, [G-[3]], V3), near(E3, V3).

test(discrete_given_out_of_the_domain, [timeout(10), error(domain_error(between(-20, 20), 25))]) :-
   belief([a], [[1]], [[[1]]], B),
   belief_request(B, [a], [[0]], S0),
   discrete(S0, 25, -20, 20).

% No gate at a threshold of 1: the far detection is scored.
test(threshold_one_is_no_gate, [timeout(60)]) :-
   keys(Keys), case(Mus, Ps, Q, R, Zdets, _),
   belief(Keys, Mus, Ps, B),
   belief_request(B, Keys, Q, S0, [threshold(1)]),
   cv_step(S0, S, Z),
   belief_observe(S, Z, Zdets, R, _, Nll),
   eval(Nll, [], V),
   forall(member(X, V), X < inf).

test(discrete_already_defined, [timeout(10), error(pclp(already_defined(_, _)))]) :-
   belief([a], [[1]], [[[1]]], B),
   belief_request(B, [a], [[0]], S0),
   { X is S0.a + 1 },
   discrete(S0, X, 0, 1).

% Beliefs edited: a key added, copied, dropped, and a marginal.
test(belief_edits, [timeout(60)]) :-
   belief([a, b], [[1, 2]], [[[1, 0.5], [0.5, 2]]], B0),
   belief_add(c, 3, 4, B0, B1),
   belief_marginal(B1, [c, a], Mu, P),
   eval(Mu, [], [3.0, 1.0]), eval(P, [], [4.0, 0.0, 0.0, 1.0]),
   belief_copy(d, b, 0.1, B1, B2),
   belief_keys(B2, Keys2), Keys2 == [a, b, c, d],
   belief_mean(B2, d, Md), eval(Md, [], [2.0]),
   belief_var(B2, d, Vd), eval(Vd, [], [Vd1]), near([Vd1], [2.1]),
   belief_marginal(B2, [d, a, b], _, Pd), eval(Pd, [], Vs), near(Vs, [2.1, 0.5, 2, 0.5, 1, 0.5, 2, 0.5, 2]),
   belief_drop([a, c], B2, B3),
   belief_keys(B3, Keys3), Keys3 == [b, d],
   belief(_, Mu3, P3, B3), eval(Mu3, [], [2.0, 2.0]), eval(P3, [], V3), near(V3, [2, 2, 2, 2.1]).

% The errors of the dialect and of the transition.
test(keys_differ, [timeout(10), error(pclp(keys_differ(_, _)))]) :-
   belief([a, b], [[1, 2]], [[[1, 0], [0, 1]]], B),
   belief_request(B, [a, b], [[0, 0], [0, 0]], S0),
   { X is S0.a + 1 },
   belief_close(_{a: X}, _).

test(mixed_steps, [timeout(10), error(pclp(mixed_steps(_)))]) :-
   belief([a, b], [[1, 2]], [[[1, 0], [0, 1]]], B),
   belief_request(B, [a], [[0]], S0),
   belief_request(B, [b], [[0]], T0),
   { _ is S0.a + T0.b }.

test(used_before_defined, [timeout(10), error(pclp(used_before_defined(_, _)))]) :-
   belief([a], [[1]], [[[1]]], B),
   belief_request(B, [a], [[0]], S0),
   { _ is S0.a + _ }.

test(already_defined, [timeout(10), error(pclp(already_defined(_, _)))]) :-
   belief([a], [[1]], [[[1]]], B),
   belief_request(B, [a], [[0]], S0),
   { X is S0.a + 1, X is S0.a + 2 }.

test(comparison_needs_a_solver, [timeout(10), error(pclp(unsupported(comparison, _)))]) :-
   belief([a], [[1]], [[[1]]], B),
   belief_request(B, [a], [[0]], S0),
   { S0.a > 0 }.

test(not_invertible_constant, [timeout(10), error(pclp(not_invertible(a, constant)))]) :-
   belief([a, b], [[1, 2]], [[[1, 0], [0, 1]]], B),
   belief_request(B, [a, b], [[0, 0], [0, 0]], S0),
   { X is S0.b + 1 },
   belief_close(_{a: 5, b: X}, _).

test(not_invertible_same, [timeout(10), error(pclp(not_invertible(b, same_as(a))))]) :-
   belief([a, b], [[1, 2]], [[[1, 0], [0, 1]]], B),
   belief_request(B, [a, b], [[0, 0], [0, 0]], S0),
   { X is S0.a + S0.b },
   belief_close(_{a: X, b: X}, _).

test(not_invertible_dropped, [timeout(10), error(pclp(not_invertible(b, dropped)))]) :-
   belief([a, b], [[1, 2]], [[[1, 0], [0, 1]]], B),
   belief_request(B, [a, b], [[0, 0], [0, 0]], S0),
   { X is S0.a + 1, Y is S0.a * 2 },
   belief_close(_{a: X, b: Y}, _).

test(predicted_twice, [timeout(10), error(pclp(predicted_twice(_)))]) :-
   belief([a], [[1]], [[[1]]], B),
   belief_request(B, [a], [[0]], S0),
   { X is S0.a + 1, Y is S0.a + 2 },
   belief_predict([X]),
   belief_predict([Y]).

:- end_tests(pclp).
