:- module(pclp,
          [ belief/4,             % ?Keys, ?Mu, ?P, ?B
            belief_keys/2,        % +B, -Keys
            belief_mean/3,        % +B, +Key, -Mean
            belief_var/3,         % +B, +Key, -Var
            belief_marginal/4,    % +B, +Keys, -Mu, -P
            belief_add/5,         % +Key, +Mean, +Var, +B0, -B
            belief_copy/5,        % +NewKey, +SrcKey, +Var, +B0, -B
            belief_drop/3,        % +Keys, +B0, -B
            belief_select/4,      % +B0, +Indices, -B, -Labels
            belief_request/4,     % +B0, +Keys, +Q, -S0
            belief_request/5,     % +B0, +Keys, +Q, -S0, +Options
            discrete/4,           % +S0, -D, +Lo, +Hi
            {}/1,                 % +Constraints
            belief_predict/1,     % +Z
            belief_predict/3,     % +Z, -ZMu, -ZCov
            belief_observe/6,     % +S, +Z, +ZDet, +R, -Post, -Nll
            belief_close/2        % +S, -B
          ]).
:- use_module(library(array)).
:- use_module(library(array/api)).
:- use_module(library(lists)).
:- use_module(library(apply)).
:- use_module(library(pairs)).
:- use_module(library(ordsets)).
:- use_module(library(option)).
:- use_module(library(error)).

/** <module> Filtering a forward arithmetic program, on a batch of beliefs, as arrays

The API of pclp (~/prog/pclp) on a batch: a belief is a Gaussian N(Mu, P) over Keys for each
of B states, Mu a name of shape [B, N] and P one of [B, N, N], and a step scores every state
against every one of D detections, under every value of its discrete variables. Everything
is a program of the array library, written with the functions of library(array/api):
nothing runs here. The names a step gives, the scores and the new belief, are run by run/4
or eval/3 on the data of the inputs, or realized, and the belief of the next step may be
built on them.

A step is opened on a subset of the keys with belief_request/4,5, which returns a dict of
fresh names, one per key: the values of that key at the 2N sigma points of every state, a
name of shape [B, 2N]. The program of the step is written with {}/1 in the dialect of pclp,
`X is E` (single assignment) with E in standard arithmetic; every assignment is the
expression over the sigma points, so that the filter is the unscented one: the moments of
the names the step ends with are the prediction. Comparisons need a solver, which this
version has none of, and are refused.

A discrete choice of the step, the pitch of a note, is a variable declared by discrete/4
with its domain Lo..Hi: a name holding the domain along a leading axis of its own, V = Hi -
Lo + 1 values, a hypothesis per value. The axes of the hypotheses lead the batch, and a
shape broadcasts from the right with an extent of 1 stretched: a name that depends on the
variable grows its axis, `Y is S0.top_y + Pitch*S0.unit` has the shape [V, B, 2N], and a
name that does not stays [B, 2N], computed once. Several variables make the product of
their domains, every combination a hypothesis, each variable declared an axis outside the
ones declared before it, so that a name in some of them alone still aligns from the right. Nothing is enumerated: the device scores every hypothesis, and the gate keeps
the plausible ones.

The step is finished with belief_observe/6 on a batch of D detections, or belief_close/2
without one. Before that, belief_predict/1,3 computes the moments of the perfect
observation Z once, kept for belief_observe/6 on the same Z. belief_observe/6 gives the
score of every hypothesis, state and detection, Nll[V1, ..., Vn, B, D], the negative
log-likelihood of the detection under the predicted observation, inf outside the gate, and
the belief of these tuples: a posterior mean per tuple, Mu[V1, ..., Vn, B, D, N'], and the
covariance per hypothesis and state, P[V1, ..., Vn, B, N', N'], since it does not depend on
the detection taken. belief_close/2 gives the prediction, the same without the detections'
axis, and a belief of states when there is no discrete variable. belief_select/4 picks
tuples out of a belief of hypotheses as the states of the next step, with the value of each
discrete variable per tuple: the search over the hypotheses is a sort of the scores and a
selection, and the choice of a tuple includes the discrete values. The keys outside the
step are corrected through their correlation with its input, as pclp does, exactly when the
transition is invertible; the new state must be a distinct name per key, each derived from
the input (resets are done between steps).

The only confidence parameter is the step option threshold(P): the gate is the chi-square
quantile at P with as many degrees of freedom as the observation.
*/

                 /*******************************
                 *            BELIEFS           *
                 *******************************/

%!  belief(?Keys, ?Mu, ?P, ?B)
%
%   B is the Gaussian belief N(Mu, P) over Keys, a list of distinct atoms in the order of
%   the last axis of Mu and of the last two of P. Mu and P are names, of shapes [B, N] and
%   [B, N, N], or nested lists of numbers, constants of the program. A belief of hypotheses,
%   as belief_observe/6 and belief_close/2 give, is belief(Keys, Mu, P, Domains), Mu of
%   shape [V1, ..., Vn, B, D, N] or [V1, ..., Vn, B, N] and P of [V1, ..., Vn, B, N, N],
%   Domains the lower bound of each discrete variable in the order of its axis.

belief(Keys, Mu, P, B), nonvar(B) =>
   parts(B, Keys, Mu, P).
belief(Keys, Mu, P, B) =>
   must_be(list(atom), Keys),
   distinct_keys(Keys),
   length(Keys, N),
   operand(Mu, Mu1),
   operand(P, P1),
   shape(Mu1, MuShape),
   shape(P1, PShape),
   (  MuShape = [Bt, N], PShape = [Bt, N, N]
   -> true
   ;  domain_error(belief_shapes(N), MuShape-PShape)
   ),
   B = belief(Keys, Mu1, P1).

% parts(+B, -Keys, -Mu, -P): the keys and the names of a belief of either kind.
parts(belief(Keys, Mu, P), Keys1, Mu1, P1) => Keys1 = Keys, Mu1 = Mu, P1 = P.
parts(belief(Keys, Mu, P, _), Keys1, Mu1, P1) => Keys1 = Keys, Mu1 = Mu, P1 = P.
parts(B, _, _, _) => type_error(belief, B).

% operand(+X, -A): the name A of X: a name, or a nested list of numbers made a constant of
% floats. indices(+X, -A): the same for a list of ints, a constant of ints.
operand(X, A), var(X), get_attr(X, core, _) => A = X.
operand(X, A), is_list(X) => floats(X, F), A @= asarray(F).
operand(X, _) => type_error(array_or_list, X).

floats(X, F), is_list(X) => maplist(floats, X, F).
floats(X, F), number(X) => F is float(X).
floats(X, _) => type_error(number, X).

indices(X, A), var(X), get_attr(X, core, _) => A = X.
indices(X, A), is_list(X) => A @= asarray(X).
indices(X, _) => type_error(array_or_list, X).

distinct_keys(Keys) :-
   msort(Keys, Sorted),
   (   append(_, [K, K | _], Sorted)
   ->  domain_error(distinct_keys, K)
   ;   true
   ).

belief_keys(B, Keys) :-
   parts(B, Keys, _, _).

%!  belief_mean(+B, +Key, -Mean)
%!  belief_var(+B, +Key, -Var)
%
%   The mean of Key and its variance, names of the shape of B without its last axis, or
%   its last two.

belief_mean(B, Key, Mean) :-
   parts(B, Keys, Mu, _),
   key_index(Key, Keys, I),
   Mean @= Mu[..., I].

belief_var(B, Key, Var) :-
   parts(B, Keys, _, P),
   key_index(Key, Keys, I),
   Var @= P[..., I, I].

%!  belief_marginal(+B, +Keys, -Mu, -P)
%
%   The marginal of a belief of states on Keys: Mu[B, K], P[B, K, K].

belief_marginal(B, Keys, Mu, P) :-
   state_belief(B, Keys0, Mu0, P0),
   key_indices(Keys, Keys0, Indices),
   gather_keys(Mu0, P0, Indices, Mu, P).

% gather_keys(+Mu, +P, +Indices, -Mu1, -P1): the keys at Indices of every state, the names
% themselves when Indices is every key in order.
gather_keys(Mu, P, Indices, Mu1, P1) :-
   shape(Mu, [_, N]),
   (  numlist_(N, Indices)
   -> Mu1 = Mu, P1 = P
   ;  Idx @= asarray(Indices),
      Mu1 @= Mu[..., Idx],
      P1 @= P[..., Idx[_, new], Idx[new, _]]
   ).

numlist_(0, L) => L = [].
numlist_(N, L) => N1 is N - 1, numlist(0, N1, L).

%!  belief_add(+Key, +Mean, +Var, +B0, -B)
%
%   New key, independent of the others, appended to B0, the same for every state.

belief_add(Key, Mean, Var, B0, B) :-
   must_be(atom, Key),
   must_be(number, Mean),
   must_be(number, Var),
   (   Var > 0
   ->  true
   ;   domain_error(positive_variance, Var)
   ),
   state_belief(B0, Keys, Mu, P),
   new_key(Key, Keys),
   append(Keys, [Key], Keys1),
   shape(Mu, [Bt, N]),
   Mu1 @= concat([Mu, full([Bt, 1], Mean)], [axis(1)]),
   P1 @= concat([concat([P, zeros([Bt, N, 1])], [axis(2)]),
                 concat([zeros([Bt, 1, N]), full([Bt, 1, 1], Var)], [axis(2)])], [axis(1)]),
   B = belief(Keys1, Mu1, P1).

%!  belief_copy(+NewKey, +SrcKey, +Var, +B0, -B)
%
%   New key as a copy of SrcKey: same mean, same covariance with every other key, plus an
%   independent variance Var, floored so that the covariance stays positive definite.

belief_copy(NewKey, SrcKey, Var, B0, B) :-
   must_be(atom, NewKey),
   must_be(number, Var),
   state_belief(B0, Keys, Mu, P),
   new_key(NewKey, Keys),
   key_index(SrcKey, Keys, I),
   I1 is I + 1,
   V is max(Var, 1.0e-6),
   append(Keys, [NewKey], Keys1),
   Mu1 @= concat([Mu, Mu[_, I:I1]], [axis(1)]),
   P1 @= concat([concat([P, P[_, _, I:I1]], [axis(2)]),
                 concat([P[_, I:I1, _], P[_, I:I1, I:I1] + V], [axis(2)])], [axis(1)]),
   B = belief(Keys1, Mu1, P1).

%!  belief_drop(+Keys, +B0, -B)
%
%   Removes Keys: the marginal on the other keys.

belief_drop(Drop, B0, B) :-
   state_belief(B0, Keys, Mu, P),
   key_indices(Drop, Keys, DropIndices),
   length(Keys, N),
   complement_indices(N, DropIndices, Keep),
   slice_keys(Keys, Keep, Keys1),
   gather_keys(Mu, P, Keep, Mu1, P1),
   B = belief(Keys1, Mu1, P1).

%!  belief_select(+B0, +Indices, -B, -Labels)
%
%   The states of B are tuples of the belief of hypotheses B0: Indices holds an int name,
%   or a list of ints, per leading axis of its mean, the hypothesis axes, the state and, on
%   a belief of pairs, the detection, all of one shape [B1]; B is the belief of states
%   belief(Keys, Mu, P), Mu[B1, N] and P[B1, N, N]. Labels is the value of each discrete
%   variable at every tuple, in the order of the axes, int names of shape [B1]. An int name
%   without a declared range takes the one of its axis.

belief_select(B0, Indices, B, Labels) :-
   (   B0 = belief(Keys, Mu, P, Los)
   ->  true
   ;   type_error(belief_of_hypotheses, B0)
   ),
   must_be(list, Indices),
   shape(Mu, MuShape),
   shape(P, PShape),
   leading(MuShape, 1, Lead),
   leading(PShape, 2, LeadP),
   length(Lead, L),
   (   length(Indices, L)
   ->  true
   ;   domain_error(indices_per_axis(L), Indices)
   ),
   maplist(indices, Indices, Is),
   maplist(ranged, Is, Lead),
   append(Is, [_], MuIs),
   compound_name_arguments(MuIndex, [], [MuIs, Mu]),
   Mu1 @= MuIndex,
   length(LeadP, Lp),
   length(PIs, Lp),
   append(PIs, _, Is),
   append(PIs, [_, _], PIs1),
   compound_name_arguments(PIndex, [], [PIs1, P]),
   P1 @= PIndex,
   length(Los, H),
   length(His, H),
   append(His, _, Is),
   maplist(label, His, Los, Labels),
   B = belief(Keys, Mu1, P1).

label(I, Lo, Label) :-
   Label @= I + Lo.

% leading(+Shape, +N, -Lead): Shape without its last N extents.
leading(Shape, N, Lead) :-
   length(Shape, R),
   L is R - N,
   length(Lead, L),
   append(Lead, _, Shape).

ranged(Idx, Extent) :-
   (  core:bounds(Idx, _)
   -> true
   ;  Hi = Extent - 1,
      ( ground(Hi) -> Hi1 is Hi ; Hi1 = Hi ),
      elements(Idx, 0-Hi1)
   ).

% state_belief(+B, -Keys, -Mu, -P): B, a belief of states, Mu of shape [B, N].
state_belief(B, Keys, Mu, P) :-
   (   B = belief(Keys, Mu, P)
   ->  true
   ;   B = belief(_, _, _, _)
   ->  domain_error(belief_of_states, B)
   ;   type_error(belief, B)
   ).

new_key(Key, Keys) :-
   (   memberchk(Key, Keys)
   ->  throw(error(pclp(key_exists(Key)), _))
   ;   true
   ).

key_index(Key, Keys, I) :-
   (   nth0(I0, Keys, Key)
   ->  I = I0
   ;   existence_error(belief_key, Key)
   ).

key_indices(Keys, AllKeys, Indices) :-
   maplist(key_index_in(AllKeys), Keys, Indices).

key_index_in(Keys, Key, I) :-
   key_index(Key, Keys, I).

slice_keys(Keys, Indices, Slice) :-
   maplist(nth0_of(Keys), Indices, Slice).

nth0_of(List, I, X) :-
   nth0(I, List, X).

% complement_indices(+N, +Keep, -Comp): 0..N-1 not in Keep, in order.
complement_indices(N, Keep, Comp) :-
   numlist_(N, All),
   exclude(in_list(Keep), All, Comp).

in_list(List, X) :-
   memberchk(X, List).

                 /*******************************
                 *             STEPS            *
                 *******************************/

% A step record step(Id, B0, Keys, Indices, Mu0, Pi, X, Ins, Thr, Predicted, Hyps, Given)
% is shared by all the names of one request: Mu0[B, N] and Pi[B, N, N] the input's
% moments, X[B, 2N, N] its sigma points, Ins the N names of the inputs. Predicted is
% unbound, or bound by belief_predict/3 to pred(Z, SZ, Dz, ZMu, ZCov), the moments of Z (a
% cache: belief_observe/6 computes them when it is missing). Hyps is hyps(Domains),
% Domains a Lo-V per discrete variable declared, in the order of their axes, the last
% declared first, set by discrete/4. Given is given(Pairs), the option of the request.
% Nothing else in the record changes after the request.
%
% Attribute pclp, on every name of a step: def(Step, Deps), Deps the ordered set of the input
% indices the name depends on, none for a discrete variable.

%!  belief_request(+B0, +Keys, +Q, -S0) is det.
%!  belief_request(+B0, +Keys, +Q, -S0, +Options) is det.
%
%   Opens a step on the subset Keys of B0 with process noise Q, a name of shape [N, N] or a
%   list of rows, added to the input: Pi = P0 + Q. S0 is a dict Key: Name, each name the
%   values of its key at the 2N sigma points of every state, of shape [B, 2N]. Options:
%     - filter(Name): ukf, the only one
%     - threshold(P), default 0.95: the probability of the gate (chi-square quantile at P);
%       1 for no gate, every detection scored, as learning from a parse needs
%     - given(Pairs), default []: Var-Name pairs, the choices made already: a discrete
%       variable Var declared later, see discrete/4, takes the value of Name, an int name
%       of one element, an input of the program, as a hypothesis axis of extent one; so
%       that one program serves every value, as the replay of a parse, or a parse learned
%       from, wants.

belief_request(B0, Keys, Q, S0) :-
   belief_request(B0, Keys, Q, S0, []).

belief_request(B0, Keys, Q, S0, Options) :-
   state_belief(B0, AllKeys, Mu, P),
   must_be(list(atom), Keys),
   (   Keys == []
   ->  domain_error(non_empty_list, Keys)
   ;   true
   ),
   must_be(list, Options),
   distinct_keys(Keys),
   key_indices(Keys, AllKeys, Indices),
   length(Keys, N),
   gather_keys(Mu, P, Indices, Mu0, P0),
   operand(Q, Q1),
   shape(Q1, QShape),
   (   QShape = [N, N]
   ->  true
   ;   domain_error(matrix(N, N), Q)
   ),
   option(filter(Filter), Options, ukf),
   (   Filter == ukf
   ->  true
   ;   throw(error(pclp(unknown(filter, Filter)), _))
   ),
   option(threshold(Thr), Options, 0.95),
   (   number(Thr), Thr > 0, Thr =< 1
   ->  true
   ;   domain_error(probability, Thr)
   ),
   % Sigma points: X[b, s*N + j, i] = Mu0[b, i] + (1 - 2s) L[b, i, j], L L^T = N Pi.
   Pi @= P0 + Q1,
   Nf is float(N),
   Lt @= matrix_transpose(cholesky(Pi * Nf)),
   X @= concat([Mu0[_, new, _] + Lt, Mu0[_, new, _] - Lt], [axis(1)]),
   option(given(Given), Options, []),
   must_be(list, Given),
   flag(pclp_step, Id, Id + 1),
   Step = step(Id, B0, Keys, Indices, Mu0, Pi, X, Ins, Thr, _Predicted, hyps([]), given(Given)),
   numlist_(N, Is),
   maplist(input(Step, X), Is, Ins),
   pairs_keys_values(Pairs, Keys, Ins),
   dict_pairs(S0, _, Pairs).

input(Step, X, I, V) :-
   V @= X[_, _, I],
   put_attr(V, pclp, def(Step, [I])).

attr_unify_hook(_, Other) :-
   throw(error(permission_error(bind, name, Other), _)).

%!  discrete(+S0, ?D, +Lo, +Hi) is det.
%
%   D is a discrete variable of the step of S0 with the domain Lo..Hi, integers: a name of
%   ints holding the domain along a leading axis of its own, of shape [V, 1, ..., 1] with
%   V = Hi - Lo + 1 and as many trailing 1s as the axes declared before it and the two of
%   the states and the sigma points, so that an expression of the step in D has a
%   hypothesis per value, see the module. The last variable declared is the outermost axis.
%   An integer D in the domain, a choice made already, as a parse replayed or learned from
%   makes it, is left as it is: a constant of the step, no axis. A D given to the request,
%   given(Pairs), is a hypothesis axis of extent one holding the value of its name, an int
%   of one element, an input of the program; the axis has the domain Lo-1, its label the
%   lower bound, since the value is the input's.

discrete(S0, D, Lo, Hi) :-
   must_be(dict, S0),
   must_be(integer, Lo),
   must_be(integer, Hi),
   (   Hi >= Lo
   ->  true
   ;   domain_error(domain(Lo, Hi), D)
   ),
   (   integer(D)
   ->  (   D >= Lo, D =< Hi
       ->  true
       ;   domain_error(between(Lo, Hi), D)
       )
   ;   var(D), \+ attvar(D), given_name(S0, D, G)
   ->  shape(G, [1]),
       kind(G, int),
       elements(G, Lo-Hi),
       declare_axis(S0, D, G, Lo, 1)
   ;   var(D), \+ attvar(D)
   ->  V is Hi - Lo + 1,
       Stop is Hi + 1,
       declare_axis(S0, D, arange(Lo, Stop), Lo, V)
   ;   throw(error(pclp(already_defined(D, discrete(D, Lo, Hi))), _))
   ).

% given_name(+S0, +D, -G): D is given to the step of S0 as the name G.
given_name(S0, D, G) :-
   term_step(S0, S0, Step),
   arg(12, Step, given(Pairs)),
   member(D1-G, Pairs),
   D1 == D,
   !.

% declare_axis(+S0, -D, +Values, +Lo, +V): D is the next hypothesis axis of the step of S0,
% of extent V, holding Values, a name or an expression of one axis of V elements, from the
% label Lo.
declare_axis(S0, D, Values, Lo, V) :-
   term_step(S0, S0, Step),
   arg(11, Step, hyps(Domains)),
   length(Domains, I),
   Inner is I + 2,
   length(After, Inner),
   maplist(=(new), After),
   compound_name_arguments(Index, [], [[_ | After], Values]),
   D @= Index,
   shape(D, [V | _]),
   put_attr(D, pclp, def(Step, [])),
   setarg(11, Step, hyps([Lo-V | Domains])).

% hypotheses(+Step, -Lead, -Domains): the extents of the hypothesis axes of Step, and its
% domains.
hypotheses(Step, Lead, Domains) :-
   arg(11, Step, hyps(Domains)),
   pairs_values(Domains, Lead).

                 /*******************************
                 *            PROGRAM           *
                 *******************************/

%!  {+Constraints}
%
%   Constraints is a conjunction of `X is E` in the dialect: E is built from numbers, names
%   of the step, pi, e and + - * / ** ^ (binary), - + (unary), sqrt, exp, log, sin, cos, tan,
%   abs, min, max. Every assignment is the expression over the sigma points of every state,
%   and over every value of the discrete variables it mentions.
%
%   `X is E` is a single assignment: X is a fresh variable, made a name of shape
%   [..., B, 2N]. Every variable of E is a name of the step. A comparison is refused: it
%   needs a solver, which this version has none of.

{Block} :-
   conj_list(Block, Cs),
   maplist(assignment(Block), Cs).

conj_list(Block, Cs) :-
   phrase(conj(Block), Cs).

conj(C) -->
   (   { nonvar(C), C = (A, B) }
   ->  conj(A),
       conj(B)
   ;   [C]
   ).

assignment(Block, C), var(C) =>
   throw(error(pclp(not_dialect(C, Block)), _)).
assignment(Block, X is E0) =>
   expr(Block, E0, E, []-[], Deps-Steps),
   one_step(Steps, Block, Step),
   (   var(X), \+ attvar(X)
   ->  true
   ;   throw(error(pclp(already_defined(X, Block)), _))
   ),
   X @= E,
   (   var(X), \+ get_attr(X, pclp, _)
   ->  put_attr(X, pclp, def(Step, Deps))
   ;   true
   ).
assignment(_, C), compound(C), compound_name_arity(C, Op, 2), memberchk(Op, [=:=, =\=, <, =<, >, >=]) =>
   throw(error(pclp(unsupported(comparison, C)), _)).
assignment(Block, C) =>
   throw(error(pclp(not_dialect(C, Block)), _)).

% expr(+Block, +E0, -E, +Deps0-Steps0, -Deps-Steps): E0 checked against the dialect, E the
% expression of the array API, with the input indices the names of E0 depend on and their
% steps collected.
expr(Block, V, E, D0-S0, Acc), var(V) =>
   (   get_attr(V, pclp, def(Step, Deps))
   ->  E = V,
       ord_union(D0, Deps, D),
       add_step(Step, S0, S),
       Acc = D-S
   ;   throw(error(pclp(used_before_defined(V, Block)), _))
   ).
expr(_, N, E, Acc0, Acc), number(N) =>
   E = N, Acc = Acc0.
expr(_, C, E, Acc0, Acc), memberchk(C, [pi, e]) =>
   E is C, Acc = Acc0.
expr(Block, +A, E, Acc0, Acc) =>
   expr(Block, A, E, Acc0, Acc).
expr(Block, E0, E, Acc0, Acc), compound(E0), compound_name_arity(E0, F, A), function(F/A, F1) =>
   compound_name_arguments(E0, F, Args0),
   foldl(expr(Block), Args0, Args, Acc0, Acc),
   compound_name_arguments(E, F1, Args).
expr(Block, E0, _, _, _) =>
   throw(error(pclp(not_dialect(E0, Block)), _)).

% function(?F/A, -Name): the function of the dialect and its name in the array API.
function((+)/2, F) => F = (+).
function((-)/2, F) => F = (-).
function((*)/2, F) => F = (*).
function((/)/2, F) => F = (/).
function((**)/2, F) => F = pow.
function((^)/2, F) => F = pow.
function((-)/1, F) => F = (-).
function(sqrt/1, F) => F = sqrt.
function(exp/1, F) => F = exp.
function(log/1, F) => F = log.
function(sin/1, F) => F = sin.
function(cos/1, F) => F = cos.
function(tan/1, F) => F = tan.
function(abs/1, F) => F = abs.
function(min/2, F) => F = minimum.
function(max/2, F) => F = maximum.
function(_, _) => fail.

add_step(Step, Steps0, Steps) :-
   (   member(S, Steps0),
       same_step(S, Step)
   ->  Steps = Steps0
   ;   Steps = [Step | Steps0]
   ).

same_step(S1, S2) :-
   arg(1, S1, Id),
   arg(1, S2, Id).

one_step(Steps, Culprit, Step) :-
   (   Steps = [Step0]
   ->  Step = Step0
   ;   Steps == []
   ->  throw(error(pclp(no_step(Culprit)), _))
   ;   throw(error(pclp(mixed_steps(Culprit)), _))
   ).

% term_step(+Culprit, +T, -Step): the one step of the names of T.
term_step(Culprit, T, Step) :-
   term_variables(T, Vars),
   foldl(var_step, Vars, [], Steps),
   one_step(Steps, Culprit, Step).

var_step(V, Steps0, Steps) :-
   (   get_attr(V, pclp, def(Step, _))
   ->  add_step(Step, Steps0, Steps)
   ;   Steps = Steps0
   ).

                 /*******************************
                 *       FINISHING A STEP       *
                 *******************************/

%!  belief_predict(+Z) is det.
%!  belief_predict(+Z, -ZMu, -ZCov) is det.
%
%   The moments of the perfect observation Z, a list of names of the step (or numbers):
%   ZMu[..., B, M] and ZCov[..., B, M, M], under every hypothesis, without the detector
%   noise. They are kept for belief_observe/6 on the same list Z; the step stays unfinished.

belief_predict(Z) :-
   belief_predict(Z, _, _).

belief_predict(Z, ZMu, ZCov) :-
   must_be(list, Z),
   term_step(Z, Z, Step),
   predicted(Step, Z, pred(_, _, _, ZMu, ZCov)).

% predicted(+Step, +Z, -Pred): the moments of Z, computed once per step.
predicted(Step, Z, Pred) :-
   arg(10, Step, Predicted),
   (   var(Predicted)
   ->  predict(Step, Z, Pred),
       Predicted = Pred
   ;   Predicted = pred(Z1, _, _, _, _),
       Z1 == Z
   ->  Pred = Predicted
   ;   throw(error(pclp(predicted_twice(Z)), _))
   ).

predict(Step, Z, pred(Z, SZ, Dz, ZMu, ZCov)) :-
   moments(Step, Z, SZ, Dz, ZMu, ZCov).

% moments(+Step, +Vs, -S, -D, -Mu, -Cov): the names Vs, each broadcast to the hypotheses,
% the states and the sigma points, stacked as S[..., B, K, M], their deviations D from their
% mean Mu[..., B, M] over the sigma points, with weights 1/K, and their covariance
% Cov[..., B, M, M].
moments(Step, Vs, S, D, Mu, Cov) :-
   full_shape(Step, Full, K),
   maplist(sigma_values(Full), Vs, Names),
   S @= stack(Names, [axis(-1)]),
   Mu @= mean(S, [axis(-2)]),
   D @= S - Mu[..., new, _],
   Cov @= matrix_transpose(D) @ D / K.

% full_shape(+Step, -Full, -K): the shape of a name of Step over every hypothesis, state
% and sigma point, [V1, ..., Vn, B, K].
full_shape(Step, Full, K) :-
   Step = step(_, _, _, _, _, _, X, _, _, _, _, _),
   shape(X, [Bt, K, _]),
   hypotheses(Step, Lead, _),
   append(Lead, [Bt, K], Full).

% sigma_values(+Full, +V, -Name): V as a name of the shape Full: itself stretched, or a
% number at every point.
sigma_values(Full, V, Name), var(V) => Name @= broadcast_to(V, Full).
sigma_values(Full, V, Name), number(V) => Name @= full(Full, V).
sigma_values(_, V, _) => type_error(name_or_number, V).

%!  belief_observe(+S, +Z, +ZDet, +R, -Post, -Nll) is det.
%
%   Finishes the step of S on a batch of D detections ZDet, a name of shape [D, M] or a list
%   of rows, of the perfect observation Z, a list of M names of the step, with noise R, a
%   name of shape [M, M] or a list of rows. S has the requested keys, its values the new
%   state. Nll[..., B, D] is the negative log-likelihood of each detection under the
%   predicted observation of each state, under each hypothesis, inf outside the gate. Post
%   is the belief of the tuples, see the module: Mu[..., B, D, N'] over every key,
%   P[..., B, N', N'] per hypothesis and state.

belief_observe(S, Z, ZDet, R, Post, Nll) :-
   must_be(list, Z),
   length(Z, M),
   (   M > 0
   ->  true
   ;   domain_error(non_empty_list, Z)
   ),
   close_step(S, Z, Step, Keys, Outs),
   check_transition(Keys, Outs),
   operand(ZDet, ZDet1),
   shape(ZDet1, ZShape),
   (   ZShape = [_, M]
   ->  true
   ;   domain_error(observations_of_length(M), ZDet)
   ),
   operand(R, R1),
   shape(R1, RShape),
   (   RShape = [M, M]
   ->  true
   ;   domain_error(matrix(M, M), R)
   ),
   Step = step(_, _, _, _, _, _, _, _, Thr, _, _, _),
   window_crit(Thr, M, Crit),
   predicted(Step, Z, pred(_, _, Dz, ZMu, ZCov)),
   prediction(Step, Outs, Dy, MuPred, PPred, Cpf, K),
   % The innovation covariance, its inverse and log-determinant, and every state against
   % every detection: innovation, Mahalanobis distance, score.
   Pyz @= matrix_transpose(Dy) @ Dz / K,
   Szz @= ZCov + R1,
   Sinv @= inv(Szz),
   LogDet @= 2.0 * sum(log(diagonal(cholesky(Szz))), [axis(-1)]),
   E @= ZDet1[new, _, _] - ZMu[..., new, _],
   D2 @= vecdot(E @ Sinv, E),
   C0 is 0.5*M*log(2*pi),
   Inf is inf,
   Nll @= where(D2 =< Crit, 0.5*D2 + 0.5*LogDet[..., new] + C0, Inf),
   % The update: gain G = Pyz Szz^-1, a mean per pair, the covariance per state.
   G @= Pyz @ Sinv,
   Gt @= matrix_transpose(G),
   MuPost @= MuPred[..., new, _] + E @ Gt,
   PPost @= PPred - G @ Szz @ Gt,
   global_update(Step, Cpf, PPred, MuPost, PPost, moved(MuPred), Mu1, P1),
   hypotheses(Step, _, Domains),
   pairs_keys(Domains, Los),
   arg(2, Step, B0),
   parts(B0, AllKeys, _, _),
   Post = belief(AllKeys, Mu1, P1, Los).

%!  belief_close(+S, -B) is det.
%
%   Finishes the step of S without a detection: B is the prediction, a belief of states, or
%   of hypotheses when the step has discrete variables, Mu[..., B, N'].

belief_close(S, B) :-
   close_step(S, [], Step, Keys, Outs),
   check_transition(Keys, Outs),
   prediction(Step, Outs, _, MuPred, PPred, Cpf, _),
   global_update(Step, Cpf, PPred, MuPred, PPred, none, Mu1, P1),
   hypotheses(Step, _, Domains),
   arg(2, Step, B0),
   parts(B0, AllKeys, _, _),
   (   Domains == []
   ->  B = belief(AllKeys, Mu1, P1)
   ;   pairs_keys(Domains, Los),
       B = belief(AllKeys, Mu1, P1, Los)
   ).

% prediction(+Step, +Outs, -Dy, -MuPred, -PPred, -Cpf, -K): the moments of the new state:
% MuPred[..., B, N], PPred[..., B, N, N], Cpf[..., B, N, N] its cross-covariance with the
% input, K the number of sigma points.
prediction(Step, Outs, Dy, MuPred, PPred, Cpf, K) :-
   Step = step(_, _, _, _, Mu0, _, X, _, _, _, _, _),
   shape(X, [_, K, _]),
   moments(Step, Outs, _, Dy, MuPred, PPred),
   Cpf @= matrix_transpose(X - Mu0[_, new, _]) @ Dy / K.

% The step of S, and the values of S in the order of the requested keys.
close_step(S, Z, Step, Keys, Outs) :-
   must_be(dict, S),
   dict_pairs(S, _, Pairs),
   pairs_values(Pairs, Values),
   term_step(S, Values-Z, Step),
   arg(3, Step, Keys),
   pairs_keys(Pairs, SKeys),
   msort(Keys, Sorted),
   (   SKeys == Sorted
   ->  true
   ;   throw(error(pclp(keys_differ(Sorted, SKeys)), _))
   ),
   maplist(dict_value(S), Keys, Outs).

dict_value(Dict, Key, Value) :-
   get_dict(Key, Dict, Value).

% The transition S0 -> S must be invertible: every value of S is a distinct name of the step
% and the values can be matched one to one with the input keys they derive from.
check_transition(Keys, Outs) :-
   pairs_keys_values(Pairs, Keys, Outs),
   forall(member(K-V, Pairs),
          (   nonvar(V)
          ->  throw(error(pclp(not_invertible(K, constant)), _))
          ;   true
          )),
   forall(( append(_, [K1-V1 | Rest], Pairs), member(K2-V2, Rest), V1 == V2 ),
          throw(error(pclp(not_invertible(K2, same_as(K1))), _))),
   maplist(out_deps, Keys, Outs, Depss),
   (   match(Depss, [])
   ->  true
   ;   foldl(ord_union, Depss, [], Used),
       length(Keys, N),
       numlist_(N, All),
       ord_subtract(All, Used, Lost),
       (   Lost = [I | _]
       ->  nth0(I, Keys, Key),
           throw(error(pclp(not_invertible(Key, dropped)), _))
       ;   throw(error(pclp(not_invertible(Keys, rank)), _))
       )
   ).

out_deps(Key, V, Deps) :-
   (   get_attr(V, pclp, def(_, Deps0))
   ->  Deps = Deps0
   ;   throw(error(pclp(not_determined(Key)), _))
   ).

match([], _) :- !.
match([Deps | Depss], Used) :-
   member(I, Deps),
   \+ memberchk(I, Used),
   match(Depss, [I | Used]),
   !.

% global_update(+Step, +Cpf, +PPred, +MuPost, +PPost, +Mode, -Mu1, -P1): the new belief over
% every key: the update of the requested keys, MuPost[..., B, N] or [..., B, D, N] and
% PPost[..., B, N, N], written back into B0, the other keys corrected through their
% correlation with the input. The requested sub-state moved from Pi to PPred (Cpf its
% cross-covariance with the input) and was corrected to PPost; the other keys do not move:
% their links are re-pointed to the moved sub-state, G0 = Cross Pi^-1 Cpf, then corrected
% through G = G0 PPred^-1 by what the correction moved, moved(MuPred), or not at all, none.
global_update(Step, Cpf, PPred, MuPost, PPost, Mode, Mu1, P1) :-
   Step = step(_, B0, _, Indices, _, Pi, _, _, _, _, _, _),
   parts(B0, AllKeys, MuIn, SigmaIn),
   length(AllKeys, NA),
   complement_indices(NA, Indices, Comp),
   (   Comp == []
   ->  MuPerm = MuPost,
       SigmaPerm = PPost
   ;   length(Comp, C),
       CompIdx @= asarray(Comp),
       Idx @= asarray(Indices),
       CrossCS @= SigmaIn[_, CompIdx[_, new], Idx[new, _]],
       SigmaCC @= SigmaIn[_, CompIdx[_, new], CompIdx[new, _]],
       G0 @= CrossCS @ inv(Pi) @ Cpf,
       MuC0 @= MuIn[_, CompIdx],
       (   Mode == none
       ->  shape(MuPost, MuShape), leading(MuShape, 1, LeadMu), append(LeadMu, [C], CShape),
           MuC @= broadcast_to(MuC0, CShape),
           CrossSC @= matrix_transpose(G0),
           shape(PPost, PShape), leading(PShape, 2, LeadP), append(LeadP, [C, C], CCShape),
           SigmaCC1 @= broadcast_to(SigmaCC, CCShape)
       ;   Mode = moved(MuPred),
           G @= G0 @ inv(PPred),
           Gt @= matrix_transpose(G),
           Dm @= PPred - PPost,
           MuC @= MuC0[_, new, _] + (MuPost - MuPred[..., new, _]) @ Gt,
           CrossSC @= matrix_transpose(G0) - Dm @ Gt,
           SigmaCC1 @= SigmaCC - G @ Dm @ Gt
       ),
       MuPerm @= concat([MuPost, MuC], [axis(-1)]),
       SigmaPerm @= concat([concat([PPost, CrossSC], [axis(-1)]),
                            concat([matrix_transpose(CrossSC), SigmaCC1], [axis(-1)])], [axis(-2)])
   ),
   append(Indices, Comp, Perm),
   (   numlist_(NA, Perm)
   ->  Mu1 = MuPerm,
       P1 = SigmaPerm
   ;   inverse_permutation(Perm, InvPerm),
       Inv @= asarray(InvPerm),
       Mu1 @= MuPerm[..., Inv],
       P1 @= SigmaPerm[..., Inv[_, new], Inv[new, _]]
   ).

% inverse_permutation(+Perm, -Inv): Inv[Perm[k]] = k.
inverse_permutation(Perm, Inv) :-
   length(Perm, N),
   numlist_(N, Ks),
   pairs_keys_values(Pairs, Perm, Ks),
   keysort(Pairs, Sorted),
   pairs_values(Sorted, Inv).

                 /*******************************
                 *           THE GATE           *
                 *******************************/

% window_crit(+P, +K, -Crit): the chi-square quantile at P with K degrees of freedom: exact
% for 1 and 2, Wilson-Hilferty with the Acklam normal quantile above; inf at 1, no gate.
window_crit(P, _, X) :-
   P >= 1,
   !,
   X is inf.
window_crit(P, 1, X) :-
   !,
   P1 is (1 + P) / 2,
   norm_quantile(P1, Z),
   X is Z * Z.
window_crit(P, 2, X) :-
   !,
   X is -2 * log(1 - P).
window_crit(P, K, X) :-
   norm_quantile(P, Z),
   Inv9K is 1.0 / (9.0 * float(K)),
   C is 1.0 - 2.0 * Inv9K + Z * sqrt(2.0 * Inv9K),
   X is K * C * C * C.

norm_quantile(P, X) :-
   (   P < 0.02425
   ->  Q is sqrt(-2.0 * log(P)),
       norm_tail(Q, X)
   ;   P =< 0.97575
   ->  Q is P - 0.5,
       R is Q * Q,
       horner([-3.969683028665376e+01, 2.209460984245205e+02,
               -2.759285104469687e+02, 1.383577518672690e+02,
               -3.066479806614716e+01, 2.506628277459239e+00], R, Num),
       horner([-5.447609879822406e+01, 1.615858368580409e+02,
               -1.556989798598866e+02, 6.680131188771972e+01,
               -1.328068155288572e+01, 1.0], R, Den),
       X is Q * Num / Den
   ;   Q is sqrt(-2.0 * log(1.0 - P)),
       norm_tail(Q, X0),
       X is -X0
   ).

norm_tail(Q, X) :-
   horner([-7.784894002430293e-03, -3.223964580411365e-01,
           -2.400758277161838e+00, -2.549732539343734e+00,
           4.374664141464968e+00, 2.938163982698783e+00], Q, Num),
   horner([7.784695709041462e-03, 3.224671290700398e-01,
           2.445134137142996e+00, 3.754408661907416e+00, 1.0], Q, Den),
   X is Num / Den.

horner(Coeffs, X, Val) :-
   foldl(horner_step(X), Coeffs, 0.0, Val).

horner_step(X, C, Acc, Out) :-
   Out is Acc * X + C.

                 /*******************************
                 *           MESSAGES           *
                 *******************************/

:- multifile prolog:error_message//1.

prolog:error_message(pclp(E)) -->
   pclp_message(E).

pclp_message(mixed_steps(T)) -->
   [ 'pclp: ~p mixes names of two steps'-[T] ].
pclp_message(no_step(S)) -->
   [ 'pclp: ~p holds no name of a step'-[S] ].
pclp_message(predicted_twice(Z)) -->
   [ 'pclp: the step of ~p was already predicted on another observation'-[Z] ].
pclp_message(not_dialect(C, Block)) -->
   [ 'pclp: ~p is not in the dialect (X is E, standard arithmetic), in ~p'-[C, Block] ].
pclp_message(unsupported(comparison, C)) -->
   [ 'pclp: ~p needs a solver, which this version has none of'-[C] ].
pclp_message(already_defined(X, Block)) -->
   [ 'pclp: ~p is already defined (single assignment), in ~p'-[X, Block] ].
pclp_message(used_before_defined(V, Block)) -->
   [ 'pclp: ~p is used before it is defined, in ~p'-[V, Block] ].
pclp_message(unknown(Kind, Name)) -->
   [ 'pclp: unknown ~w ~p'-[Kind, Name] ].
pclp_message(keys_differ(Requested, Given)) -->
   [ 'pclp: the step was requested on ~w, the new state has ~w'-[Requested, Given] ].
pclp_message(not_determined(Name)) -->
   [ 'pclp: ~p is not determined by the input'-[Name] ].
pclp_message(not_invertible(Key, constant)) -->
   [ 'pclp: ~w is set to a constant; resets are done between steps'-[Key] ].
pclp_message(not_invertible(Key, same_as(Key1))) -->
   [ 'pclp: ~w is the same value as ~w; resets are done between steps'-[Key, Key1] ].
pclp_message(not_invertible(Key, dropped)) -->
   [ 'pclp: the new state no longer depends on the input ~w; resets are done between steps'-[Key] ].
pclp_message(not_invertible(Keys, rank)) -->
   [ 'pclp: the transition on ~w is not invertible'-[Keys] ].
pclp_message(key_exists(Key)) -->
   [ 'pclp: the belief already has the key ~w'-[Key] ].
