:- module(omr,
          [ omr_grammar//2,      % ?StaffLines, ?Notes
            omr_model/1,         % -Model
            detections/1,        % -Detections
            omr_device/1,        % ?Device
            q_r/3,               % ?Kind, ?Q, ?R
            run_omr/0,
            run_omr/1,           % +Strategy
            run_omr_k/2,         % +Strategy, +K
            set_noises/1,        % +Noises
            reset_noises/0,
            learn_omr/0,
            learn_omr/1          % +Options
          ]).
:- use_module(library(dcg/high_order)).
:- use_module(library(lists)).
:- use_module(library(apply)).
:- use_module(library(solution_sequences)).
:- use_module(pclp, [belief/4, discrete/4, {}/1]).
:- use_module(epf).

/** <module> The staff and notes grammar of pclp_omr.pl, on the device

A port of ~/prog/pclp/pclp_omr.pl to the vocabulary of epf.pl: the grammar is written once,
with term//4 and copy//3 over the beliefs and detections of pclp, and runs under the engine
called on it, search/4, replay/3 or fit/4, with the model of omr_model/1.

The grammar finds five staff lines, each a segment spaced two staff units below the one
before it, then the notes, noteheads spaced by a margin, the pitch of each a discrete
choice of its term, a hypothesis per staff position scored at once. The intent:

  - deduce as fast as possible the correct values for unit and tr (18 and 0.25);
  - order lines vertically from top to bottom when consuming;
  - find stafflines spaced by 2*unit;
  - track the correct horizontal start and end of the staff;
  - find notes spaced by margin;
  - find pitch of each note based on the bottom staffline y in unit.

Ported as the original has it: the keys, the noises q_r/3, the priors and detections, the
detection probabilities, the clutter cost, and the strategies and the replay of run_omr/1.

    run_omr, run_omr(+Strategy), run_omr_k(+Strategy, +K)
        the first parse found by Strategy (ordered by default), then its replay; the first
        K parses.
    omr_device(?Device)
        the device the terms run on, a dynamic fact, pocl by default.
    learn_omr, learn_omr(+Options)
        the noises learned on the parse the search finds, printed, and the search run again
        with them; the wall time of each stage printed, and of each step of the descent
        under debug(epf(fit)).
*/

:- dynamic omr_device/1.
omr_device(pocl).

                 /*******************************
                 *          THE GRAMMAR         *
                 *******************************/

first_line_cond(S, S, seg(point(S.left_margin, S.top_y), point(EX, S.top_y), Th)) :-
   { Th is S.unit*S.tr,
     EX is S.left_margin + S.line_length
   }.

stafflines([FirstLine | RestLines]) -->
   term(first, first_line_cond, [unit, tr, top_y, left_margin, line_length], FirstLine),
   copy(sx, left_margin, 1),
   sequence(staffline_chain, RestLines).

chain_line_cond(S0, S, Seg) :-
   S1 = S0.put(top_y, TopY),
   { TopY is S0.top_y + 2*S0.unit },
   first_line_cond(S1, S, Seg).

staffline_chain(Line) -->
   term(chain, chain_line_cond, [unit, tr, left_margin, line_length, top_y], Line).

% The pitch is a discrete variable of the step, every value a hypothesis scored at once,
% and the choice of the term: its value at the candidate taken; given, a constant.
note_cond(Pitch, S0, S, ccx(X, Y, notehead)) :-
   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(note(Note, Pitch)) -->
   term(note, note_cond(Pitch), [unit, top_y, sx, margin], Note).

%!  omr_grammar(?StaffLines, ?Notes)//
%
%   The staff lines, five nodes, then the notes, note(Node, Pitch), as many as the search
%   decides.

omr_grammar(StaffLines, Notes) -->
   stafflines(StaffLines),
   sequence(note, Notes).

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

%!  omr_model(-Model) is det.
%
%   The model of the grammar, on the device of omr_device/1: the prior over the page and
%   the detections of the original, the noises of q_r/3, the kinds of terms and the
%   detections they consume, the detection probabilities of 0.95, the clutter cost of a
%   detection in the dimensions of its measurement space, 5 for a segment and 2 for a
%   notehead, at a tau of 3.0 per coordinate over the reference scale of the page, the
%   prior mean of unit; a gate at 0.95 and one synthesis in a row.

omr_model(Model) :-
   omr_device(Dev),
   prior(Prior),
   detections(Detections),
   findall(Kind-q_r(Q, R), q_r(Kind, Q, R), Noises),
   model([ device(Dev),
           prior(Prior),
           detections(Detections),
           noises(Noises),
           kinds([first-seg(_, _, _), chain-seg(_, _, _), note-ccx(_, _, _)]),
           detection_prob([seg(_, _, _)-0.95, ccx(_, _, _)-0.95]),
           clutter([seg(_, _, _)-5, ccx(_, _, _)-2]),   % sx, sy, ex, ey, th; x, y
           clutter_tau(3.0),
           ref_unit(20),
           threshold(0.95),
           max_synth_run(1)
         ],
         Model).

% prior(-B): the prior over the page, a belief of one state, constants of a program. One
% change from the original: the prior of top_y is 200 with a variance of 400, where the
% original had 0 with 100000. The device computes in single precision, and the first
% line's update subtracts almost the whole prior variance from it, through the inverse of
% an innovation covariance whose condition number is that variance, since both ends of the
% line observe top_y with a noise of 1: a variance of 100000 leaves a posterior variance of
% -136, one of 1000 leaves 0.42 for 0.50, one of 400 leaves 0.51. The original with this
% prior finds the same parse, with the score 119.97940247326369.
prior(B) :-
   belief([unit, tr, top_y, margin, left_margin, line_length],
          [[20, 0.2, 200, 20, 100, 404]],
          [[[25.0, 0, 0, 0, 0, 0],
            [0, 0.01, 0, 0, 0, 0],
            [0, 0, 400, 0, 0, 0],
            [0, 0, 0, 25, 0, 0],
            [0, 0, 0, 0, 100, 0],
            [0, 0, 0, 0, 0, 100]]],
          B0),
   B = B0.                      % built on a fresh variable: belief/4 reads a bound one

%!  detections(-Detections) is det.
%
%   The detections of the original, Id-Term, with a staff line missing (5) and a clutter
%   line (1) and notehead (13).

detections([ 0-seg(point(100.0, 208.0), point(504.4, 208.0), 4.5),
             1-seg(point(50.0, 50.0), point(50.4, 50.0), 6.5),
             2-seg(point(100.0, 352.0), point(504.4, 352.0), 4.5),
             3-seg(point(100.0, 316.0), point(504.4, 316.0), 4.5),
             4-seg(point(100.0, 280.0), point(504.4, 280.0), 4.5),
             % 5-seg(point(100.0, 244.0), point(504.4, 244.0), 4.5),
             6-ccx(118.0, 208.4, notehead),
             7-ccx(141.0, 226.2, notehead),
             8-ccx(159.0, 243.8, notehead),
             9-ccx(183.0, 262.1, notehead),
             13-ccx(170.0, 235.0, notehead),
             10-ccx(204.0, 280.3, notehead),
             11-ccx(227.0, 297.9, notehead),
             12-ccx(246.0, 316.2, notehead)
           ]).

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

% Q / R, in the order of the keys of each term. They start fully neutral / un-opinionated:
%   R = I          -- "1 px" measurement noise on every coordinate, both stages.
%   Q(chain) = I   -- no opinion on the process/measurement ratio; equal weight.
%   Q(first)  = 0  -- the init step predicts with the identity, so it carries no process
%                    transition and no process noise.
%   Q(note) = keep a high noise on margin to maintain flexibility

%!  q_r(?Kind, -Q, -R) is nondet.
%
%   The noises of the terms of Kind, rows: the ones learned, set_noises/1, else the
%   initial ones, initial_q_r/3. The learned ones are facts of their own, learned_q_r/3,
%   asserted, so that a reload of this file, which brings its clauses back, leaves one
%   pair per kind; reset_noises/0 forgets them.

:- dynamic learned_q_r/3.

q_r(Kind, Q, R) :-
   initial_q_r(Kind, Q0, R0),
   (  learned_q_r(Kind, Q1, R1)
   -> Q = Q1, R = R1
   ;  Q = Q0, R = R0
   ).

initial_q_r(first,
    [[0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0]],
    [[1, 0, 0, 0, 0],
     [0, 1, 0, 0, 0],
     [0, 0, 1, 0, 0],
     [0, 0, 0, 1, 0],
     [0, 0, 0, 0, 1]]).
initial_q_r(chain,
    [[1, 0, 0, 0, 0],
     [0, 1, 0, 0, 0],
     [0, 0, 1, 0, 0],
     [0, 0, 0, 1, 0],
     [0, 0, 0, 0, 1]],
    [[1, 0, 0, 0, 0],
     [0, 1, 0, 0, 0],
     [0, 0, 1, 0, 0],
     [0, 0, 0, 1, 0],
     [0, 0, 0, 0, 1]]).
initial_q_r(note,
    [[0.0001, 0, 0, 0],
     [0, 0.001, 0, 0],
     [0, 0, 0.001, 0],
     [0, 0, 0, 4]],
    [[9, 0], [0, 1]]).

%!  set_noises(+Noises) is det.
%
%   The noises of the terms set to Noises, Kind-q_r(Q, R), as fit/4 learns them; they
%   stay through a reload of this file, until reset_noises/0.

set_noises(Noises) :-
   forall(member(Kind-q_r(Q, R), Noises),
          ( retractall(learned_q_r(Kind, _, _)), assertz(learned_q_r(Kind, Q, R)) )).

%!  reset_noises is det.
%
%   The noises of the terms back to the initial ones.

reset_noises :-
   retractall(learned_q_r(_, _, _)).

                 /*******************************
                 *          THE DRIVERS         *
                 *******************************/

%!  run_omr is det.
%!  run_omr(+Strategy) is det.
%
%   The first parse found by Strategy (see best_first.pl; default ordered, the greedy
%   descent), then its replay: the same grammar with the parse bound, the priorities
%   ignored, must give the same score.

run_omr :-
   run_omr(ordered).

run_omr(Strategy) :-
   length(StaffLines, 5),
   omr_model(Model),
   search(Strategy, omr_grammar(StaffLines, Notes), Model, Score),
   !,
   search_expansions(Expansions),
   print_term(StaffLines, []), nl,
   print_term(Notes, []), nl,
   format('score: ~w (~w expansions)~n', [Score, Expansions]),
   replay(omr_grammar(StaffLines, Notes), Model, Score2),
   format('score2: ~w~n', [Score2]).

%!  run_omr_k(+Strategy, +K) is det.
%
%   The first K parses found by Strategy (in ascending score for best_first, improving for
%   branch_and_bound).

run_omr_k(Strategy, K) :-
   omr_model(Model),
   forall(limit(K, search(Strategy, omr_grammar(StaffLines, Notes), Model, Score)),
          format('~w ~w ~w~n', [Score, StaffLines, Notes])).

%!  learn_omr is det.
%!  learn_omr(+Options) is det.
%
%   The noises learned on the parse the greedy descent finds, with the options of fit/4:
%   the score before and after, the noises, and the search run again with them. The wall
%   time of each stage is printed: the search, which compiles the programs of the terms on
%   its way, the fit, and the search again under the learned noises, new constants of the
%   terms, so new programs compiled.

learn_omr :-
   learn_omr([]).

learn_omr(Options) :-
   length(StaffLines, 5),
   omr_model(Model),
   timed(once(search(ordered, omr_grammar(StaffLines, Notes), Model, Score)), TSearch),
   format('parse found, score ~w (search ~3f s)~n', [Score, TSearch]),
   timed(fit(omr_grammar(StaffLines, Notes), Model, Options, fit(Scores, Noises)), TFit),
   Scores = [First | _],
   last(Scores, Last),
   length(Scores, NScores),
   format('score along the parse: ~w before, ~w after (fit ~3f s, ~w scores)~n',
          [First, Last, TFit, NScores]),
   forall(member(Kind-q_r(Q, R), Noises),
          ( diagonal(Q, Dq), diagonal(R, Dr),
            format('~w: diag Q ~w~n       diag R ~w~n', [Kind, Dq, Dr]) )),
   set_noises(Noises),
   timed(run_omr, TAgain),
   format('search under the learned noises ~3f s~n', [TAgain]).

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

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