:- module(epf,
          [ term//4,             % +Kind, :Cond, +Keys, ?Node
            copy//3,             % +NewKey, +SrcKey, +Var
            model/2,             % +Options, -Model
            search/4,            % +Strategy, :Grammar, +Model, -Score
            replay/3,            % :Grammar, +Model, -Score
            fit/4,               % :Grammar, +Model, +Options, -Fit
            search_expansions/1  % -N
          ]).
:- use_module(library(lists)).
:- use_module(library(apply)).
:- use_module(library(option)).
:- use_module(library(error)).
:- use_module(library(debug)).
:- use_module(library(array)).
:- use_module(library(array/api)).
:- use_module(library(array/grad), [vjp/4]).
:- use_module(library(array/buffer), [buffer_from_data/4]).
:- use_module(pclp).
:- use_module(best_first, [search/4 as driver_search, depth_first/1]).
:- reexport(best_first, [search_expansions/1]).

/** <module> Grammars of terms over a belief, searched, replayed and learned on the device

The vocabulary of the EPF of DMOS as the pclp port has it: a grammar is a DCG over a state
holding a belief, a Gaussian over named variables, and a pool of detections, Id-Term, and
a term of the grammar is a step of the filter, term//4: a cond, a predicate on the step dict
of pclp, predicts a detection from the belief and the step ends on a detection of the pool
that the prediction matches (consume) or without one (synth). copy//3 adds a key to the
belief as a copy of another. The grammar is written once; the engine it runs under is the
entry point called on it, with a model, model/2, that holds what the grammar does not say:
the prior, the pool, the noises Q and R of each kind of term, the kinds and the detections
they consume, the detection probabilities and the clutter costs, the device.

  - search/4 runs the grammar nondeterministically under a strategy of best_first.pl: every
    alternative of a term, a detection in the gate or the detection missed, announces to
    the driver a lower bound of the final score and an estimate of it, and the strategy
    picks the branch to resume. The variables of the grammar are bound to the parse found:
    the nodes of the terms, N-Det or synth-Det, and the choices of the conds.
  - replay/3 runs the grammar with the parse bound, the priorities ignored: the same score.
  - fit/4 learns the noises on a parse by gradient descent: the score of the grammar along
    the parse, as a function of the noises of each kind, descended along its gradient.

What the device does. The program of a term, built once per kind of term by a tabled
builder on input names, the belief of the node and the detections of the pool its kind
matches, scores every detection at once under every value of the discrete variables of
the cond, belief_observe/6, and predicts the step without one, belief_close/2. A node holds
a belief realized on the device, Mu[1, N] and P[1, N, N]; a term runs its program on it
through the cache of handles, run_all/4, reads the scores back, and enumerates the
candidates in the gate; the belief of the child taken is a gather out of the realized
beliefs of the pairs, belief_select/4, another small program run the same way, so that
nothing is computed for a child the search never resumes. The discrete choices of the
grammar are the discrete/4 variables of pclp, leading axes of hypotheses scored at once:
the variables of the cond of a term are its choices, unified with their values at the
candidate taken, left unbound on a synth, which makes no choice. An argument bound
already, in the replay of a parse or a parse learned from, is an input of the program,
given to the step as a hypothesis axis of one value, so that one program serves every
value, cond_key/3. The noises Q and R are inputs too, realized once per matrix: new noises
run the handles compiled, nothing is built again. The filter is the unscented one, late:
one prediction per node, every candidate compared with it.

Learning the noises. The parse being known, the score of the grammar along it is a
differentiable function of the noises Q and R of each kind of term, and fit/4 descends its
gradient. The gradient is by reverse mode through the step of pclp, the Cholesky
factorizations and the inverses by their rules, one term at a time: a kind of step, a
detection consumed, a synthesis or a copy of a key, is one program on the belief it starts
from, the log of the diagonals of its Q and R, its parameters, and the detection, extended
by vjp/4 with the cotangents of its outputs as inputs and the gradients in its inputs as
outputs. The grammar runs along the parse on a state of the fit engine, which runs the
program of each step on the belief realized and keeps the step on a tape. The tape is then
walked backwards, the cotangent of the belief each step gives passed to the one before it,
the gradients in the parameters summed, the way reverse mode goes through a program, at the
granularity of the terms: the whole parse as one program with its backward is too large for
the compiler to take. The gate is off along the parse, since every detection of it is
scored.

The state the grammar runs on is a dict epf{engine, model, belief, l, score, synth_run,
tape, thetas}: the engine, search or fit; the model; the belief so far, belief(Keys,
Mu[1, N], P[1, N, N]) realized on the device; the pool left; the score so far, the negative
log-likelihoods of the detections consumed, the detection probabilities and the misses;
the syntheses in a row; and for the fit, the tape, latest step first, and the parameters
of each kind realized on the device.

The score of a parse is -log p(Z | path), an MHT likelihood of the detections given the
path: the choices of the grammar, the consume/synth decisions. Paths are ranked by maximum
likelihood, there is no prior over the choices. The clutter of the detections left unused
is added at the end, and bounds the priorities along the way: every unused detection will
cost at least its clutter cost, left unused, or the floor of the score of a term that
consumes it.
*/

:- meta_predicate
   term(+, 3, +, ?, +, -),
   search(+, //, +, -),
   replay(//, +, -),
   fit(//, +, +, -),
   timed(0, -).

                 /*******************************
                 *          THE MODEL           *
                 *******************************/

%!  model(+Options, -Model) is det.
%
%   The model a grammar runs with, from Options:
%
%     - prior(+Belief)
%       The belief the grammar starts from, belief(Keys, Mu, P) of belief/4 over one state;
%       its names are realized on the device here. Required.
%     - detections(+Pool)
%       The pool of detections, Id-Term. Required.
%     - noises(+Noises)
%       The noises of each kind of term, Kind-q_r(Q, R), Q and R as lists of rows in the
%       order of the keys of the term and of the coordinates of its observation. A kind is
%       an atom. Default none.
%     - kinds(+Kinds)
%       The detections each kind consumes, Kind-Pattern: the bound of a priority counts
%       the floor of the score of a detection under every kind whose pattern subsumes it.
%       Default none, the bound counts the clutter alone.
%     - detection_prob(+Probs)
%       The probability that the detector finds a symbol that is there, Pattern-P, the
%       first pattern that subsumes the term. Required for every term of the grammar.
%     - clutter(+Dims)
%       The dimension of the measurement space of a detection, Pattern-K: its cost left
%       unused is K*(Tau + log(RefUnit)), -log of a uniform density. Required for every
%       detection of the pool.
%     - clutter_tau(+Tau)
%       Default 3.0.
%     - ref_unit(+RefUnit)
%       The reference scale of the page the clutter is measured in. Default 1.0.
%     - threshold(+Thr)
%       The gate of the search, the probability of belief_request/5. Default 0.95.
%     - max_synth_run(+N)
%       The syntheses allowed in a row; a detection consumed resets the count. Default 1.
%     - device(+Device)
%       The device the programs run on. Default pocl.

model(Options, Model) :-
   must_be(list, Options),
   option(device(Dev), Options, pocl),
   required(prior(belief(Keys, Mu, P)), Options),
   required(detections(Pool), Options),
   must_be(list, Pool),
   option(noises(NoiseList), Options, []),
   maplist(noise_pair, NoiseList, NoisePairs),
   dict_pairs(Noises, noises, NoisePairs),
   option(kinds(Kinds), Options, []),
   must_be(list, Kinds),
   option(detection_prob(Probs), Options, []),
   option(clutter(Dims), Options, []),
   option(clutter_tau(Tau), Options, 3.0),
   option(ref_unit(U), Options, 1.0),
   option(threshold(Thr), Options, 0.95),
   option(max_synth_run(Max), Options, 1),
   realize([Mu, P], [], [device(Dev)]),
   Model = model{device: Dev, prior: belief(Keys, Mu, P), detections: Pool, noises: Noises,
                 kinds: Kinds, detection_prob: Probs, clutter: Dims, clutter_tau: Tau,
                 ref_unit: U, threshold: Thr, max_synth_run: Max}.

required(Option, Options) :-
   (  option(Option, Options)
   -> true
   ;  functor(Option, Name, _),
      existence_error(option, Name)
   ).

noise_pair(Kind-q_r(Q, R), Pair) =>
   must_be(atom, Kind),
   Pair = Kind-(Q-R).
noise_pair(Noise, _) =>
   type_error(noise, Noise).

% kind_noises(+Model, +Kind, -Q, -R): the noises of Kind, rows.
kind_noises(Model, Kind, Q, R) :-
   Noises = Model.noises,
   noises_of(Noises, Kind, Q, R).

noises_of(Noises, Kind, Q, R), get_dict(Kind, Noises, QR) =>
   QR = Q-R.
noises_of(_, Kind, _, _) =>
   existence_error(noises, Kind).

% detection_prob(+Model, +Term, -PD): the probability of the detection of Term, a
% detection or the pattern of an observation.
detection_prob(Model, Term, PD) :-
   Probs = Model.detection_prob,
   (  member(Pattern-PD0, Probs),
      subsumes_term(Pattern, Term)
   -> PD = PD0
   ;  existence_error(detection_prob, Term)
   ).

% clutter_cost(+Model, +Det, -C): the cost of the detection Det left unused.
clutter_cost(Model, Det, C) :-
   Dims = Model.clutter,
   (  member(Pattern-K, Dims),
      subsumes_term(Pattern, Det)
   -> C is K * (Model.clutter_tau + log(Model.ref_unit))
   ;  existence_error(clutter, Det)
   ).

% initial_state(+Engine, +Model, -State): the state a grammar starts from under Engine.
initial_state(Engine, Model, State) :-
   Prior = Model.prior,
   Pool = Model.detections,
   State = epf{engine: Engine, model: Model, belief: Prior, l: Pool, score: 0.0,
               synth_run: 0, tape: [], thetas: thetas{}}.

                 /*******************************
                 *            TERMS             *
                 *******************************/

% pattern(+Term, -Pattern, -Slots): the pattern of a detection or observation term, its
% numbers and names replaced by fresh variables, and those in order; the other leaves, a
% label, must be equal between an observation and the detections it matches.
pattern(Term, Pattern, Slots) :-
   pattern_(Term, Pattern, Slots, []).

pattern_(T, P, S0, S), var(T) =>
   P = _, S0 = [T | S].
pattern_(T, P, S0, S), number(T) =>
   P = _, S0 = [T | S].
pattern_(T, P, S0, S), compound(T) =>
   compound_name_arguments(T, F, Args),
   foldl([A, Pa, L0, L]>>pattern_(A, Pa, L0, L), Args, Pargs, S0, S),
   compound_name_arguments(P, F, Pargs).
pattern_(T, P, S0, S) =>
   P = T, S0 = S.

% cond_key(+Cond, -Key, -Values): the cond, M:Goal, with each choice made, an argument
% bound to an integer, replaced by `given`, and the values of those in order: the key of
% the programs of a term, one for every value of its choices.
cond_key(M:Cond, M:Key, Values) :-
   Cond =.. [F | Args],
   foldl(choice_key, Args, KeyArgs, Values, []),
   Key =.. [F | KeyArgs].

choice_key(A, K, Vs0, Vs), integer(A) => K = given, Vs0 = [A | Vs].
choice_key(A, K, Vs0, Vs) => K = A, Vs0 = Vs.

% cond_instance(+Key, -Cond, -Vs, -Givens, -Pairs): a copy of Key to call, its free choices
% the fresh variables Vs, and each `given` a fresh variable paired in Pairs with an int
% name of one element, Givens in order, the value the program takes as an input.
cond_instance(M:Key, M:Cond, Vs, Givens, Pairs) :-
   copy_term(Key, Key1),
   term_variables(Key1, Vs),
   Key1 =.. [F | Args0],
   foldl(given_arg, Args0, Args, Givens-Pairs, []-[]),
   Cond =.. [F | Args].

given_arg(given, V, Acc0, Acc) => Acc0 = [G | Gs]-[V-G | Ps], Acc = Gs-Ps.
given_arg(A, A1, Acc0, Acc) => A1 = A, Acc = Acc0.

% term_program(+AllKeys, +Keys, +Key, +Thr, +Observe, -Prog): the program of a term on the
% belief of a node, Mu[1, NA] and P[1, NA, NA], its inputs, with the noises Q[N, N] and
% R[M, M], the values of the choices made, Givens, and with Observe the detections
% ZDet[D, M], D free: prog(Mu, P, Q, R, Givens, ZDet, Outs, Pattern, Lead, Los, Choices),
% Outs the names run, [Nll, MuPost, PPost, MuPred, PPred, ZMu], or [MuPred, PPred, ZMu]
% without the detections; Pattern the pattern of the observation, Lead the extents of the
% hypothesis axes and Los the lower bound of each; Choices, for each free choice of Key
% in order, the hypothesis axis its discrete variable is, or none. Key is the cond with
% its choices made replaced by `given`, cond_key/3. Tabled: built once per kind of term
% and choices made, every call after gets a copy, run through the cache of handles.
:- table term_program/6.
term_program(AllKeys, Keys, Key, Thr, Observe, prog(Mu, P, Q, R, Givens, ZDet, Outs, Pattern, Lead, Los, Choices)) :-
   length(AllKeys, NA),
   shape(Mu, [1, NA]),
   shape(P, [1, NA, NA]),
   belief(AllKeys, Mu, P, B0),
   length(Keys, N),
   shape(Q, [N, N]),
   observation_length(Keys, Key, M),
   shape(R, [M, M]),
   step_program(B0, Keys, Q, R, Key, Thr, Observe, Givens, ZDet, Outs, Pattern, Lead, Los, Choices).

% step_program(+B0, +Keys, +Q, +R, +Key, +Thr, +Observe, -Givens, -ZDet, -Outs, -Pattern,
% -Lead, -Los, -Choices): the step of a term on the belief B0, see term_program/6.
step_program(B0, Keys, Q, R, Key, Thr, Observe, Givens, ZDet, Outs, Pattern, Lead, Los, Choices) :-
   cond_instance(Key, Cond1, Vs1, Givens, Pairs),
   belief_request(B0, Keys, Q, S0, [threshold(Thr), given(Pairs)]),
   call(Cond1, S0, S, Obs),
   pattern(Obs, Pattern, Z),
   length(Z, M),
   belief_predict(Z, ZMu, _),
   belief_close(S, Closed),
   belief(Keys1, MuPred, PPred, Closed),
   length(Keys1, NA),
   shape(MuPred, PredShape),
   length(PredShape, Rank),
   H is Rank - 2,
   length(Lead, H),
   append(Lead, [_, NA], PredShape),
   (  Closed = belief(_, _, _, Los0)
   -> Los = Los0
   ;  Los = []
   ),
   maplist(choice_axis(H), Vs1, Choices),
   (  Observe == true
   -> shape(ZDet, [_, M]),
      belief_observe(S, Z, ZDet, R, Post, Nll),
      belief(_, MuPost, PPost, Post),
      Outs = [Nll, MuPost, PPost, MuPred, PPred, ZMu]
   ;  Outs = [MuPred, PPred, ZMu]
   ).

% choice_axis(+H, +V, -Choice): the hypothesis axis, of H, of the discrete variable V, the
% I-th declared, of shape [V, 1, ..., 1] with I + 2 ones, the last declared outermost.
choice_axis(H, V, Choice) :-
   (  var(V),
      get_attr(V, pclp, def(_, [])),
      shape(V, Shape)
   -> length(Shape, Rank),
      I is Rank - 3,
      Choice is H - 1 - I
   ;  Choice = none
   ).

% observation_length(+Keys, +Key, -M): the length of the observation of the cond of Key,
% by a step of its own on a belief of Keys, built and dropped.
observation_length(Keys, Key, M) :-
   length(Keys, N),
   fit_belief(Keys, _, _, B0),
   Q @= zeros([N, N]),
   cond_instance(Key, Cond1, _, _, Pairs),
   belief_request(B0, Keys, Q, S0, [threshold(1), given(Pairs)]),
   call(Cond1, S0, _, Obs),
   pattern(Obs, _, Z),
   length(Z, M).

% select_program(+AllKeys, +Lead, +Los, -Prog): the belief of a pair out of the realized
% beliefs of the pairs of a term: prog(MuPost, PPost, Ivs, Id, Mu, P), the inputs MuPost
% [Lead.., 1, D, NA] and PPost[Lead.., 1, NA, NA], D free, the value of each discrete
% variable Ivs, int names of one element, and the detection Id, the outputs Mu[1, NA] and
% P[1, NA, NA].
:- table select_program/4.
select_program(AllKeys, Lead, Los, prog(MuPost, PPost, Ivs, Id, Mu, P)) :-
   length(AllKeys, NA),
   append(Lead, [1, D, NA], MuShape),
   shape(MuPost, MuShape),
   append(Lead, [1, NA, NA], PShape),
   shape(PPost, PShape),
   maplist(index_name, Lead, Ivs),
   index_name(D, Id),
   append(Ivs, [[0], Id], Indices),
   belief_select(belief(AllKeys, MuPost, PPost, Los), Indices, Sel, _),
   belief(_, Mu, P, Sel).

% closed_program(+AllKeys, +Lead, +Los, -Prog): the belief of the first hypothesis out of the
% realized prediction of a term, prog(MuPred, PPred, Mu, P), when the term has discrete
% variables; the prediction is the belief itself without one.
:- table closed_program/4.
closed_program(AllKeys, Lead, Los, prog(MuPred, PPred, Mu, P)) :-
   Lead = [_ | _],
   length(AllKeys, NA),
   append(Lead, [1, NA], MuShape),
   shape(MuPred, MuShape),
   append(Lead, [1, NA, NA], PShape),
   shape(PPred, PShape),
   maplist([_, [0]]>>true, Lead, Zeros),
   append(Zeros, [[0]], Indices),
   belief_select(belief(AllKeys, MuPred, PPred, Los), Indices, Sel, _),
   belief(_, Mu, P, Sel).

% index_name(+Extent, -I): an int name of one element in 0..Extent-1.
index_name(Extent, I) :-
   shape(I, [1]),
   kind(I, int),
   elements(I, 0-(Extent - 1)).

%!  term(+Kind, :Cond, +Keys, ?Node)// is nondet.
%
%   One term of the grammar: a step on Keys with the noises of Kind, Cond called as
%   call(Cond, S0, S, Obs) on the step dict S0, S the new state and Obs the detection term
%   it predicts; the step finished on a detection of the pool, Node = N-Det, or without
%   one, Node = synth-Det, Det the prediction, its coordinates unbound when they wait on a
%   discrete variable. The arguments of Cond are its choices: each a discrete variable of
%   the step, unified with its value at the candidate taken, left unbound on a synth, which
%   makes no choice and takes the belief of the first hypothesis; an argument bound already
%   is an input of the step's program, its value.
%
%   Under the search engine, the alternatives come by backtracking, each announced to the
%   driver with shift(priority(F, H)) as soon as its score is known: a candidate detection
%   in the gate, or the detection missed, at most max_synth_run in a row. With Node or the
%   choices bound, the alternatives are the ones that unify: the replay of a parse. Under
%   the fit engine, see fit/4, Node and the choices are bound, and the term runs the
%   program of the step on the belief of the state and puts the step on the tape.

term(Kind, Cond, Keys, Node, In, Out) :-
   must_be(atom, Kind),
   step(In.engine, Kind, Cond, Keys, Node, In, Out).

step(search, Kind, Cond, Keys, Node, In, Out) =>
   Model = In.model,
   Dev = Model.device,
   Thr = Model.threshold,
   In.belief = belief(AllKeys, MuR, PR),
   L = In.l,
   kind_noises(Model, Kind, Q, R),
   cond_key(Cond, Key, Values),
   term_program(AllKeys, Keys, Key, Thr, true, prog(_, _, _, _, _, _, _, Pattern, Lead, Los, Choices)),
   include(matching(Pattern), L, Matching),
   (  Matching == []
   -> Observe = false,
      Detections = []
   ;  Observe = true,
      maplist([_-Det, Row]>>pattern(Det, _, Row), Matching, Rows),
      append(Rows, Flat),
      Detections = [ZDet-Flat]
   ),
   term_program(AllKeys, Keys, Key, Thr, Observe, prog(Mu, P, QIn, RIn, Givens, ZDet, Outs, _, _, _, _)),
   noise_name(Dev, Q, QR),
   noise_name(Dev, R, RR),
   maplist(given_name(Dev), Values, GivenR),
   pairs_keys_values(GivenData, Givens, GivenR),
   append([[Mu-MuR, P-PR, QIn-QR, RIn-RR], GivenData, Detections], Data),
   run_all(Outs, Data, Results, [device(Dev)]),
   term_variables(Cond, CondVars),
   (  Observe == true,
      Results = [RNll, RMuPost, RPPost, _, _, _],
      run(RNll, [], Nlls, []),
      length(Matching, D),
      candidates(Lead, D, Nlls, Candidates),
      member(cand(Vs, K, Nll0), Candidates),
      nth0(K, Matching, Node),
      maplist([V, Lo, Label]>>(Label is V + Lo), Vs, Los, Labels),
      maplist(chosen(Labels), CondVars, Choices),
      consumed(In, Node, Pattern, Nll0, Score, L1, Run),
      announce(In, Score, L1),
      select_program(AllKeys, Lead, Los, prog(MuPostIn, PPostIn, Ivs, Id, Mu1, P1)),
      maplist([I, V, I-[V]]>>true, Ivs, Vs, IvData),
      run_all([Mu1, P1], [MuPostIn-RMuPost, PPostIn-RPPost, Id-[K] | IvData], [MuR1, PR1], [device(Dev)])
   ;  Node = synth-Det,
      missed(In, Pattern, Score, L1, Run),
      announce(In, Score, L1),
      append(_, [RMuPred, RPPred, RZMu], Results),
      (  Lead == []
      -> synthesized(Pattern, RZMu, Det),
         MuR1 = RMuPred,
         PR1 = RPPred
      ;  Det = Pattern,
         closed_program(AllKeys, Lead, Los, prog(MuPredIn, PPredIn, Mu1, P1)),
         run_all([Mu1, P1], [MuPredIn-RMuPred, PPredIn-RPPred], [MuR1, PR1], [device(Dev)])
      )
   ),
   Out = In.put(_{belief: belief(AllKeys, MuR1, PR1), l: L1, score: Score, synth_run: Run}).
step(fit, Kind, Cond, Keys, Node, In, Out) =>
   must_be(nonvar, Node),
   (  ground(Cond)
   -> true
   ;  throw(error(instantiation_error, context(term//4, 'the choices of a parse learned from are known')))
   ),
   Node = N-Det,
   Model = In.model,
   Dev = Model.device,
   MaxRun = Model.max_synth_run,
   Thetas = In.thetas,
   thetas_of(Thetas, Kind, VQ, VR),
   B0 = In.belief,
   belief_keys(B0, AllKeys),
   cond_key(Cond, Key, Values),
   maplist(given_name(Dev), Values, GivenR),
   (  N == synth
   -> Step = synth(AllKeys, Keys, Kind, Key),
      append([VQ, VR], GivenR, Data),
      fit_run(In, Step, Data, Pattern, [MuR1, PR1]),
      (  missed(In, Pattern, Score, L, Run)
      -> true
      ;  domain_error(synth_run(MaxRun), Node)
      )
   ;  Step = consume(AllKeys, Keys, Kind, Key),
      pattern(Det, _, Row),
      length(Row, M),
      constant(Dev, [1, M], float, Row, ZDetR),
      append([VQ, VR, ZDetR], GivenR, Data),
      fit_run(In, Step, Data, Pattern, [RNll, MuR1, PR1]),
      run(RNll, [], [Nll0], []),
      (  consumed(In, Node, Pattern, Nll0, Score, L, Run)
      -> true
      ;  existence_error(detection, Node)
      )
   ),
   Tape = In.tape,
   Out = In.put(_{belief: belief(AllKeys, MuR1, PR1), l: L, score: Score, synth_run: Run,
                  tape: [entry(Step, B0, Data, Kind) | Tape]}).

% consumed(+In, +Node, +Pattern, +Nll0, -Score, -L, -Run): the accounts of a step that
% consumes Node, an observation of Pattern, at the negative log-likelihood Nll0: the score,
% the pool without it, the syntheses in a row reset.
consumed(In, Node, Pattern, Nll0, Score, L, Run) :-
   detection_prob(In.model, Pattern, PD),
   Score is In.score + Nll0 - log(PD),
   selectchk(Node, In.l, L),
   Run = 0.

% missed(+In, +Pattern, -Score, -L, -Run): the accounts of a step without a detection, one
% more synthesis in a row, allowed max_synth_run of them.
missed(In, Pattern, Score, L, Run) :-
   Model = In.model,
   detection_prob(Model, Pattern, PD),
   Score is In.score - log(1 - PD),
   L = In.l,
   Run is In.synth_run + 1,
   Run =< Model.max_synth_run.

% announce(+In, +Score, +L): the alternative at Score with the pool L given to the driver.
announce(In, Score, L) :-
   priority(Score, L, In, Pr, Est),
   shift(priority(Pr, Est)).

thetas_of(Thetas, Kind, VQ, VR), get_dict(Kind, Thetas, V) =>
   V = VQ-VR.
thetas_of(_, Kind, _, _) =>
   existence_error(noises, Kind).

matching(Pattern, _-Det) :-
   pattern(Det, P, _),
   P =@= Pattern.

% noise_name(+Dev, +Rows, -Name): the matrix Rows realized on Dev, once per matrix.
noise_name(Dev, Rows, Name) :-
   length(Rows, N),
   append(Rows, Flat),
   constant(Dev, [N, N], float, Flat, Name).

% given_name(+Dev, +Value, -Name): the value of a choice made realized on Dev, an int name
% of one element, once per value.
given_name(Dev, Value, Name) :-
   constant(Dev, [1], int, [Value], Name).

% chosen(+Labels, ?V, +Choice): the variable V of the cond takes the label of its axis.
chosen(Labels, V, Choice), integer(Choice) => nth0(Choice, Labels, V).
chosen(_, _, _) => true.

% candidates(+Lead, +D, +Nlls, -Candidates): the pairs in the gate, cand(Vs, K, Nll), Vs the
% index along each hypothesis axis and K the detection, out of the scores Nll[Lead.., 1, D],
% row-major.
candidates(Lead, D, Nlls, Candidates) :-
   append(Lead, [D], Shape),
   findall(cand(Vs, K, Nll),
           ( nth0(I, Nlls, Nll),
             Nll < inf,
             subscripts(Shape, I, Is),
             once(append(Vs, [K], Is)) ),
           Candidates).

% subscripts(+Shape, +Flat, -Is): the subscripts of the row-major offset Flat in Shape.
subscripts(Shape, Flat, Is) :-
   reverse(Shape, Rev),
   foldl([E, I, F0, F]>>( I is F0 mod E, F is F0 // E ), Rev, Rs, Flat, _),
   reverse(Rs, Is).

% synthesized(+Pattern, +RZMu, -Det): the detection a synth predicts, when the term has no
% discrete variable: the pattern with the predicted observation; with one, the prediction
% waits on a choice the synth does not make, and the detection keeps its variables.
synthesized(Pattern, RZMu, Det) :-
   run(RZMu, [], Zs, []),
   copy_term(Pattern, Det),
   pattern(Det, _, Slots),
   length(Slots, M),
   length(Prefix, M),
   append(Prefix, _, Zs),
   Slots = Prefix.

%!  copy(+NewKey, +SrcKey, +Var)// is det.
%
%   The key NewKey added to the belief as a copy of SrcKey, belief_copy/5, run on the
%   device; under the fit engine, a step of the tape like a term.

copy(NewKey, SrcKey, Var, In, Out) :-
   copy_(In.engine, NewKey, SrcKey, Var, In, Out).

copy_(search, NewKey, SrcKey, Var, In, Out) =>
   In.belief = belief(Keys, MuR, PR),
   Dev = In.model.device,
   copy_program(Keys, NewKey, SrcKey, Var, prog(Mu, P, Keys1, Mu1, P1)),
   run_all([Mu1, P1], [Mu-MuR, P-PR], [MuR1, PR1], [device(Dev)]),
   Out = In.put(belief, belief(Keys1, MuR1, PR1)).
copy_(fit, NewKey, SrcKey, Var, In, Out) =>
   B0 = In.belief,
   belief_keys(B0, AllKeys),
   Step = copy(AllKeys, NewKey, SrcKey, Var),
   fit_run(In, Step, [], _, [MuR1, PR1]),
   append(AllKeys, [NewKey], Keys1),
   Tape = In.tape,
   Out = In.put(_{belief: belief(Keys1, MuR1, PR1), tape: [entry(Step, B0, [], none) | Tape]}).

:- table copy_program/5.
copy_program(Keys, NewKey, SrcKey, Var, prog(Mu, P, Keys1, Mu1, P1)) :-
   length(Keys, NA),
   shape(Mu, [1, NA]),
   shape(P, [1, NA, NA]),
   belief(Keys, Mu, P, B0),
   belief_copy(NewKey, SrcKey, Var, B0, B),
   B = belief(Keys1, Mu1, P1).

                 /*******************************
                 *          PRIORITIES          *
                 *******************************/

% F, a lower bound of the final score: every unused detection will cost at least its clutter
% cost (left unused) or the floor of the score of a term that consumes it. Est, an estimate:
% the final score if the parse stopped here (every unused detection is clutter).
priority(Score, L, State, F, Est) :-
   Model = State.model,
   foldl(detection_bound(Model), L, Score, F),
   pool_clutter(Model, L, C),
   Est is Score + C.

detection_bound(Model, _-Det, F0, F) :-
   clutter_cost(Model, Det, C),
   nll_floor(Model, Det, Floor),
   F is F0 + min(C, Floor).

% nll_floor(+Model, +Det, -Floor): the floor of the score of Det consumed, 1/2 log det(2 pi
% S_z) with S_z = ZCov + R >= R, minus log PD, over the kinds that consume it; inf when
% none is declared.
nll_floor(Model, Det, Floor) :-
   detection_prob(Model, Det, PD),
   Kinds = Model.kinds,
   findall(G,
           ( member(Kind-Pattern, Kinds),
             subsumes_term(Pattern, Det),
             kind_noises(Model, Kind, _, R),
             log_det(R, LogDet),
             length(R, K),
             G is 0.5*LogDet + 0.5*K*log(2*pi) - log(PD) ),
           Gs),
   (  Gs == []
   -> Floor = inf
   ;  min_list(Gs, Floor)
   ).

% log_det(+A, -LogDet): the log-determinant of the positive definite matrix A, rows of
% numbers, twice the log of the diagonal of its Cholesky factor.
log_det(A, LogDet) :-
   foldl(cholesky_row, A, Rows, [], _),
   foldl([Row, S0, S]>>( last(Row, Lii), S is S0 + 2*log(Lii) ), Rows, 0.0, LogDet).

% cholesky_row(+ARow, -LRow, +Done, -Done1): the row of L of the row ARow, after the rows
% Done, up to its diagonal.
cholesky_row(ARow, LRow, Done, Done1) :-
   foldl(cholesky_elem(ARow), Done, [], Pre),
   length(Pre, I),
   nth0(I, ARow, Aii),
   dot(Pre, Pre, S),
   Lii is sqrt(Aii - S),
   append(Pre, [Lii], LRow),
   append(Done, [LRow], Done1).

cholesky_elem(ARow, LRowJ, Acc0, Acc) :-
   length(Acc0, J),
   nth0(J, ARow, Aij),
   last(LRowJ, Ljj),
   length(Prefix, J),
   append(Prefix, _, LRowJ),
   dot(Acc0, Prefix, S),
   Lij is (Aij - S) / Ljj,
   append(Acc0, [Lij], Acc).

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

% pool_clutter(+Model, +Pool, -Sum): the clutter cost of a pool of Id-Det detections.
pool_clutter(Model, Pool, Sum) :-
   foldl(pool_clutter_(Model), Pool, 0.0, Sum).
pool_clutter_(Model, _-Det, S0, S) :-
   clutter_cost(Model, Det, C),
   S is S0 + C.

% final_score(+State, -Score): the score of the parse: the score of the terms and the
% clutter of the detections left.
final_score(State, Score) :-
   pool_clutter(State.model, State.l, Clutter),
   Score is State.score + Clutter.

                 /*******************************
                 *         THE ENGINES          *
                 *******************************/

%!  search(+Strategy, :Grammar, +Model, -Score) is nondet.
%
%   The parses of the DCG body Grammar from the prior of Model over its pool, found by
%   Strategy, see best_first.pl: depth_first, ordered (the greedy descent first), lds(K),
%   branch_and_bound, best_first. The variables of Grammar are bound to each parse and
%   Score is its score; search_expansions/1 counts the nodes expanded since the call.

search(Strategy, Grammar, Model, Score) :-
   initial_state(search, Model, S0),
   term_variables(Grammar, Vars),
   driver_search(Strategy, parse(Grammar, S0, Score), Score, Vars).

%!  replay(:Grammar, +Model, -Score) is det.
%
%   The score of the parse bound in Grammar: the grammar run in Prolog order, the
%   priorities ignored, as search/4 ran it.

replay(Grammar, Model, Score) :-
   initial_state(search, Model, S0),
   once(depth_first(parse(Grammar, S0, Score))).

parse(Grammar, S0, Score) :-
   call_dcg(Grammar, S0, S),
   final_score(S, Score).

                 /*******************************
                 *       LEARNING THE NOISES    *
                 *******************************/

% fit_program(+Step, +Dev, -Prog): the program of a step of the fit on Dev, compiled,
% prog(Exe, Order, NOuts, BarShapes, Pattern): the handle of the outputs of fit_step/5 and
% the gradients as one, compile_all/3; for each slot of the handle in order, the position
% of its value among the values of a call, the belief in, the inputs after it, then the
% cotangents, or self(Name) for a slot of a constant of the step, a name realized once by
% filled/4 or constant/5, its own argument; the number of outputs; the shapes of the
% cotangents; and the pattern of the observation of the step, none for a copy. Tabled:
% built and compiled once per step, and nothing of the program in the table but its
% constants, whose answers are copied at every call. The steps: consume(AllKeys, Keys, Kind,
% Key), synth(AllKeys, Keys, Kind, Key) and copy(AllKeys, NewKey, SrcKey, Var), Key the
% cond with its choices made replaced by `given`, cond_key/3, their values inputs after the
% parameters.
:- table fit_program/3.
fit_program(Step, Dev, prog(Exe, Order, NOuts, BarShapes, Pattern)) :-
   fit_step(Step, Inputs, Outs, Bars, Grads, Pattern),
   append(Outs, Grads, All),
   compile_all(All, [device(Dev)], Exe),
   signature_all(All, Slots, _, _),
   append(Inputs, Bars, Values),
   maplist(slot_position(Values), Slots, Order),
   length(Outs, NOuts),
   maplist(shape, Bars, BarShapes).

slot_position(Values, slot(Name, _, _, _), I), nth0(I0, Values, V), V == Name => I = I0.
slot_position(_, slot(Name, _, _, _), I), core:realized(Name) => I = self(Name).
slot_position(_, slot(Name, _, _, _), _) => existence_error(fit_input, Name).

% fit_step(+Step, -Inputs, -Outs, -Bars, -Grads, -Pattern): the program of a step of the
% fit: the names of its inputs, the belief in, Mu[1, NA] and P[1, NA, NA], the parameters
% ThQ and ThR, and ZDet[1, M] when a detection is consumed; its outputs, the negative
% log-likelihood Nll[1, 1] of the detection, then the belief out, Mu1 and P1; the
% cotangents of the outputs, inputs of the backward, and the gradients in the inputs the
% outputs depend on, its outputs, by vjp/4, which refuses a name they do not: a synthesis
% reads no R, so its gradients are in Mu, P and ThQ alone; and the pattern of the
% observation. The noises are the diagonal matrices of the exponentials of the parameters.
fit_step(consume(AllKeys, Keys, _, Key), [Mu, P, ThQ, ThR, ZDet | Givens], [Nll, Mu1, P1], Bars, Grads, Pattern) :-
   fit_belief(AllKeys, Mu, P, B0),
   noises(Keys, Key, ThQ, ThR, Q, R),
   step_program(B0, Keys, Q, R, Key, 1, true, Givens, ZDet, [Nll, MuPost, PPost | _], Pattern, Lead, Los, _),
   shape(ZDet, [1, _]),
   first_hypothesis(Lead, [[0], [0]], Indices),
   belief_select(belief(AllKeys, MuPost, PPost, Los), Indices, Sel, _),
   belief(_, Mu1, P1, Sel),
   vjp([Nll, Mu1, P1], [Mu, P, ThQ, ThR, ZDet], Bars, Grads).
fit_step(synth(AllKeys, Keys, _, Key), [Mu, P, ThQ, ThR | Givens], [Mu1, P1], Bars, Grads, Pattern) :-
   fit_belief(AllKeys, Mu, P, B0),
   noises(Keys, Key, ThQ, ThR, Q, R),
   step_program(B0, Keys, Q, R, Key, 1, false, Givens, _, [MuPred, PPred, _], Pattern, Lead, Los, _),
   (  Lead == []
   -> Mu1 = MuPred,
      P1 = PPred
   ;  first_hypothesis(Lead, [[0]], Indices),
      belief_select(belief(AllKeys, MuPred, PPred, Los), Indices, Sel, _),
      belief(_, Mu1, P1, Sel)
   ),
   vjp([Mu1, P1], [Mu, P, ThQ], Bars, Grads).
fit_step(copy(AllKeys, NewKey, SrcKey, Var), [Mu, P], [Mu1, P1], Bars, Grads, none) :-
   fit_belief(AllKeys, Mu, P, B0),
   belief_copy(NewKey, SrcKey, Var, B0, B),
   B = belief(_, Mu1, P1),
   vjp([Mu1, P1], [Mu, P], Bars, Grads).

% first_hypothesis(+Lead, +Rest, -Indices): the indices of belief_select/4 taking the first
% hypothesis of every axis of Lead, the choices made, then Rest: the state, the detection.
first_hypothesis(Lead, Rest, Indices) :-
   maplist([_, [0]]>>true, Lead, Zeros),
   append(Zeros, Rest, Indices).

% fit_call(+Prog, +Values, -Results): the handle of Prog called on Values, realized names
% in the order of fit_program/3; Results the realized names of the outputs then the
% gradients.
fit_call(prog(Exe, Order, _, _, _), Values, Results) :-
   maplist(nth0_of(Values), Order, Args),
   run(Exe, Args, Results).

nth0_of(_, self(Name), X) => X = Name.
nth0_of(List, I, X) => nth0(I, List, X).

% uploaded(+Dev, +Shape, +Kind, +List, -Name): List realized on Dev, of Shape, floats or
% ints as Kind says. Each upload is a copy program of its own, compiled through the cache
% of handles: once per descent step for the parameters; the constants go through filled/4
% and constant/5, tabled, realized once.
uploaded(Dev, Shape, Kind, List, Name) :-
   length(List, N),
   storage(Kind, Storage),
   maplist(element(Kind), List, Elements),
   compound_name_arguments(Data, data, Elements),
   buffer_from_data(Buffer, Storage, N, Data),
   shape(H, Shape), kind(H, Kind), value(H, Buffer),
   copy(H, Name, Dev),
   realize([Name], [], []).

storage(float, Storage) => Storage = float32.
storage(int, Storage) => Storage = int32.

element(float, X, F) => F is float(X).
element(int, X, I) => must_be(integer, X), I = X.

fit_belief(AllKeys, Mu, P, B0) :-
   length(AllKeys, NA),
   shape(Mu, [1, NA]),
   shape(P, [1, NA, NA]),
   belief(AllKeys, Mu, P, B0).

% noises(+Keys, +Key, -ThQ, -ThR, -Q, -R): the parameters of a step on Keys with the cond
% of Key, ThQ[N] and ThR[M], M the length of the observation of the cond, and the noises Q
% and R they give, diag(exp(ThQ)) and diag(exp(ThR)).
noises(Keys, Key, ThQ, ThR, Q, R) :-
   length(Keys, N),
   diagonal_of(N, ThQ, Q),
   observation_length(Keys, Key, M),
   diagonal_of(M, ThR, R).

diagonal_of(N, Theta, M) :-
   shape(Theta, [N]),
   M @= eye(N) * exp(Theta)[new, _].

% fit_run(+In, +Step, +Data, -Pattern, -Results): the program of Step run forward on the
% belief of In and Data, the realized inputs after the belief; the cotangents zero, the
% gradients unread; Pattern the pattern of its observation, Results the realized outputs.
fit_run(In, Step, Data, Pattern, Results) :-
   Dev = In.model.device,
   fit_program(Step, Dev, Prog),
   Prog = prog(_, _, NOuts, BarShapes, Pattern),
   In.belief = belief(_, MuR, PR),
   maplist(zeros_on(Dev), BarShapes, Zeros),
   append([[MuR, PR], Data, Zeros], Values),
   fit_call(Prog, Values, All),
   length(Results, NOuts),
   append(Results, _, All).

zeros_on(Dev, Shape, Zeros) :-
   filled(Dev, Shape, 0.0, Zeros).

% filled(+Dev, +Shape, +Fill, -Name): the float Fill at every element of Shape, realized on
% Dev; constant(+Dev, +Shape, +Kind, +List, -Name): List realized on Dev, of Kind. Tabled:
% realized once per process, kept.
:- table filled/4, constant/5.
filled(Dev, Shape, Fill, Name) :-
   foldl([E, S0, S]>>(S is S0*E), Shape, 1, N),
   length(List, N),
   maplist(=(Fill), List),
   uploaded(Dev, Shape, float, List, Name).

constant(Dev, Shape, Kind, List, Name) :-
   uploaded(Dev, Shape, Kind, List, Name).

% backward(+Tape, +Dev, +Grads0, -Grads): the tape walked backwards, the cotangent of the
% belief out of a step, MuBar and PBar realized on Dev, zero at the end of the parse,
% passed to the step before it as the handle gives it, nothing read back; that of a score
% 1; Grads a dict Kind: GQ-GR, the gradients in the parameters of each kind summed over
% its steps, from Grads0.
backward(Tape, Dev, Grads0, Grads) :-
   Tape = [entry(Step, _, _, _) | _],
   fit_program(Step, Dev, prog(_, _, _, BarShapes, _)),
   append(_, [MuShape, PShape], BarShapes),
   filled(Dev, MuShape, 0.0, MuBar0),
   filled(Dev, PShape, 0.0, PBar0),
   foldl(backward_step(Dev), Tape, MuBar0-PBar0-Grads0, _-_-Grads).

backward_step(Dev, entry(Step, belief(_, MuR, PR), Data, Kind), MuBar0-PBar0-Grads0, MuBar-PBar-Grads) :-
   fit_program(Step, Dev, Prog),
   Prog = prog(_, _, NOuts, BarShapes, _),
   cotangents(Dev, Step, BarShapes, MuBar0, PBar0, Bars),
   append([[MuR, PR], Data, Bars], Values),
   fit_call(Prog, Values, All),
   length(Skip, NOuts),
   append(Skip, [MuBar, PBar | RGs], All),
   parameter_grads(Kind, Step, RGs, Grads0, Grads).

% cotangents(+Dev, +Step, +BarShapes, +MuBar, +PBar, -Bars): the cotangents of the outputs
% of a step: 1 on the negative log-likelihood of a detection consumed, then those of the
% belief out.
cotangents(Dev, consume(_, _, _, _), [NllShape | _], MuBar, PBar, Bars) =>
   filled(Dev, NllShape, 1.0, One),
   Bars = [One, MuBar, PBar].
cotangents(_, _, _, MuBar, PBar, Bars) =>
   Bars = [MuBar, PBar].

% parameter_grads(+Kind, +Step, +RGs, +Grads0, -Grads): the gradients in the parameters of
% a step of Kind, the realized names after those in the belief, read back and added to
% Kind's: in Q and R of a detection consumed, in Q alone of a synthesis, which reads no R.
parameter_grads(none, _, _, Grads0, Grads) =>
   Grads = Grads0.
parameter_grads(Kind, synth(_, _, _, _), [RGQ | _], Grads0, Grads) =>
   run(RGQ, [], GQ, []),
   get_dict(Kind, Grads0, GQ0-GR0),
   maplist([A, B, C]>>(C is A + B), GQ0, GQ, GQ1),
   put_dict(Kind, Grads0, GQ1-GR0, Grads).
parameter_grads(Kind, _, [RGQ, RGR | _], Grads0, Grads) =>
   run(RGQ, [], GQ, []),
   run(RGR, [], GR, []),
   get_dict(Kind, Grads0, GQ0-GR0),
   maplist([A, B, C]>>(C is A + B), GQ0, GQ, GQ1),
   maplist([A, B, C]>>(C is A + B), GR0, GR, GR1),
   put_dict(Kind, Grads0, GQ1-GR1, Grads).

%!  fit(:Grammar, +Model, +Options, -Fit) is det.
%
%   The noises of the terms learned on the parse bound in Grammar, the nodes and the
%   choices as search/4 gives them: the score of the parse as a function of the noises,
%   the log of the diagonal of each Q and R of Model its parameters (a zero from 1e-4),
%   descended along its gradient for steps(N) steps, 100 by default, at the rate
%   rate(Eta), 0.01 by default, on the device of Model. Fit is fit(Scores, Noises): the
%   score of the parse at each step, the first before any, and the noises learned,
%   Kind-q_r(Q, R) as lists of rows, to give a model. The likelihood of a parse has no
%   floor where a residual vanishes, so a rate too high runs a noise down until the step
%   fails: the descent stops at the first score that is not finite, with the parameters
%   before it. The wall time of each step is printed under debug(epf(fit)).

fit(Grammar, Model, Options, fit(Scores, Noises)) :-
   must_be(list, Options),
   option(steps(Steps), Options, 100),
   must_be(nonneg, Steps),
   option(rate(Eta), Options, 0.01),
   initial_state(fit, Model, S0),
   dict_pairs(Model.noises, _, NoisePairs),
   maplist(log_pair, NoisePairs, Pairs),
   dict_pairs(Thetas0, thetas, Pairs),
   descend(Steps, Eta, Grammar, S0, Thetas0, Thetas0, Scores, Thetas),
   dict_pairs(Thetas, _, Learned),
   maplist(noises_of_pair, Learned, Noises).

log_pair(Kind-(Q-R), Kind-(VQ-VR)) :-
   log_diagonal(Q, VQ),
   log_diagonal(R, VR).

noises_of_pair(Kind-(VQ-VR), Kind-q_r(Q, R)) :-
   exp_diagonal(VQ, Q),
   exp_diagonal(VR, R).

% descend(+Steps, +Eta, :Grammar, +S0, +Thetas0, +Prev, -Scores, -Thetas): Steps steps of
% gradient descent from the parameters Thetas0, a dict Kind: VQ-VR of lists of floats: the
% parameters uploaded, the grammar run along the parse from S0, its score, the tape walked
% backwards, the parameters moved against the gradients by Eta; Scores the score at every
% step, the last after the last move, Thetas the parameters then; a score that is not
% finite ends the descent at Prev, the parameters before the last move.
descend(Steps, Eta, Grammar, S00, Thetas0, Prev, Scores, Thetas) :-
   Dev = S00.model.device,
   dict_pairs(Thetas0, _, Pairs),
   maplist(upload_pair(Dev), Pairs, Uploads),
   dict_pairs(UploadDict, thetas, Uploads),
   S0 = S00.put(thetas, UploadDict),
   timed(call_dcg(Grammar, S0, S), TForward),
   final_score(S, Score),
   (  finite(Score)
   -> Scores = [Score | Scores1],
      descent_step(Steps, Eta, Grammar, S00, Thetas0, S, Score-TForward, Scores1, Thetas)
   ;  print_message(warning, format("fit/4: the score is ~w, the descent stops", [Score])),
      Scores = [],
      Thetas = Prev
   ).

finite(X) :-
   X =\= inf, X =\= -inf, X =:= X.

% upload_pair(+Dev, +Kind-(VQ-VR), -Kind-(RQ-RR)): the parameters of a kind realized on Dev.
upload_pair(Dev, Kind-(VQ-VR), Kind-(RQ-RR)) :-
   length(VQ, NQ),
   uploaded(Dev, [NQ], float, VQ, RQ),
   length(VR, NR),
   uploaded(Dev, [NR], float, VR, RR).

% descent_step(+Steps, +Eta, :Grammar, +S0, +Thetas0, +S, +Score-TForward, -Scores,
% -Thetas): one step of the descent after the forward run from S0 to S under Thetas0, when
% Steps are left: the backward, the move, and the descent from the parameters moved.
descent_step(0, _, _, _, Thetas0, _, _, Scores, Thetas) =>
   Scores = [],
   Thetas = Thetas0.
descent_step(Steps, Eta, Grammar, S0, Thetas0, S, Score-TForward, Scores, Thetas) =>
   Dev = S0.model.device,
   dict_pairs(Thetas0, _, Pairs),
   maplist(zero_pair, Pairs, ZeroPairs),
   dict_pairs(Grads0, grads, ZeroPairs),
   timed(backward(S.tape, Dev, Grads0, Grads), TBackward),
   debug(epf(fit), "step ~w: score ~4f, forward ~3f s, backward ~3f s",
         [Steps, Score, TForward, TBackward]),
   maplist(moved(Eta, Grads), Pairs, Moved),
   dict_pairs(Thetas1, thetas, Moved),
   Steps1 is Steps - 1,
   descend(Steps1, Eta, Grammar, S0, Thetas1, Thetas0, Scores, Thetas).

zero_pair(Kind-(VQ-VR), Kind-(ZQ-ZR)) :-
   zeros_of(VQ, ZQ),
   zeros_of(VR, ZR).

zeros_of(Vs, Zs) :-
   maplist([_, 0.0]>>true, Vs, Zs).

moved(Eta, Grads, Kind-(VQ-VR), Kind-(VQ1-VR1)) :-
   get_dict(Kind, Grads, GQ-GR),
   maplist({Eta}/[V, G, V1]>>(V1 is V - Eta*G), VQ, GQ, VQ1),
   maplist({Eta}/[V, G, V1]>>(V1 is V - Eta*G), VR, GR, VR1).

log_diagonal(Rows, Logs) :-
   diagonal(Rows, Diag),
   maplist([D, Lg]>>(Lg is log(max(D, 1.0e-4))), Diag, Logs).

% diagonal(+Rows, -Diag): the diagonal of a matrix of rows.
diagonal(Rows, Diag) :-
   foldl([Row, D, I, I1]>>( nth0(I, Row, D), I1 is I + 1 ), Rows, Diag, 0, _).

% exp_diagonal(+Logs, -Rows): the diagonal matrix of the exponentials of Logs, as rows.
exp_diagonal(Logs, Rows) :-
   length(Logs, N),
   foldl(exp_row(N), Logs, Rows, 0, _).

exp_row(N, Lg, Row, I, I1) :-
   I1 is I + 1,
   X is exp(Lg),
   length(Before, I),
   maplist(=(0), Before),
   After is N - I1,
   length(Zeros, After),
   maplist(=(0), Zeros),
   append([Before, [X], Zeros], Row).

% timed(:Goal, -Seconds): Goal, once, and the wall time it took.
timed(Goal, Seconds) :-
   statistics(walltime, [T0, _]),
   once(Goal),
   statistics(walltime, [T1, _]),
   Seconds is (T1 - T0) / 1000.
