:- module(omr_tests, []).

:- use_module(library(array)).
:- use_module('../examples/omr').
:- use_module('../examples/epf').
:- use_module(library(array/opencl), [opencl_device/2]).
:- use_module(test_devices, [test_device/2]).

% The OMR grammar, its terms run on a device, is checked against the parse the original,
% ~/prog/pclp/pclp_omr.pl, finds on the same data under the same prior (see omr_model/1):
% the staff lines 0, a synthesized one, 4, 3 and 2, the notes 6 to 12 at the pitches -8 to
% -2 below the bottom line, the score 119.97940247326369 in 17 expansions of the greedy
% descent; the device computes in single precision, so the score agrees to 1e-4.

near(X, Y) :-
   abs(X - Y) < 1.0e-4 * (1 + abs(X)).

near(X, Y, Tol) :-
   abs(X - Y) < Tol.

expected_ids([0, synth, 4, 3, 2], [6-(-8), 7-(-7), 8-(-6), 9-(-5), 10-(-4), 11-(-3), 12-(-2)]).

% parse(+Strategy, -Lines, -Pitches, -Score, -Expansions, -Model): the first parse Strategy
% finds, as ids and pitches, and the model it ran with.
parse(Strategy, Lines, Pitches, Score, Expansions, Model) :-
   length(StaffLines, 5),
   omr_model(Model),
   once(search(Strategy, omr_grammar(StaffLines, Notes), Model, Score)),
   search_expansions(Expansions),
   maplist([Id-_, Id]>>true, StaffLines, Lines),
   maplist([note(Id-_, Pitch), Id-Pitch]>>true, Notes, Pitches).

:- meta_predicate on_device(+, 0).
on_device(D, Goal) :-
   setup_call_cleanup(( retractall(omr_device(_)), assertz(omr_device(D)) ),
                      Goal,
                      ( retractall(omr_device(_)), assertz(omr_device(pocl)) )).

:- begin_tests(omr).

% The greedy descent finds the original's parse on every device, and the replay of the
% parse found, the grammar run with the nodes bound, gives its score again.
test(greedy_descent_finds_the_original_parse, [timeout(600), forall(test_device(D, _))]) :-
   on_device(D, ( parse(ordered, Lines, Pitches, Score, Expansions, Model),
                  expected_ids(ExpectedLines, ExpectedPitches),
                  Lines == ExpectedLines,
                  Pitches == ExpectedPitches,
                  near(Score, 119.97940247326369),
                  Expansions == 17,
                  maplist([Id, Id-_]>>true, Lines, StaffLines),
                  maplist([Id-Pitch, note(Id-_, Pitch)]>>true, Pitches, Notes),
                  replay(omr_grammar(StaffLines, Notes), Model, Score2),
                  near(Score, Score2) )).

% Branch and bound and limited discrepancy search find it too.
test(other_strategies_find_the_same_parse, [timeout(600), forall(member(S, [branch_and_bound, lds(1)]))]) :-
   parse(S, Lines, Pitches, Score, _, _),
   expected_ids(ExpectedLines, ExpectedPitches),
   Lines == ExpectedLines,
   Pitches == ExpectedPitches,
   near(Score, 119.97940247326369).

% A synthesized staff line is the prediction, two staff spaces below the line before it; a
% synthesized note keeps its coordinates and its pitch unbound, since they wait on the
% pitch, a choice the synth does not make.
test(a_synth_is_the_prediction, [timeout(600)]) :-
   length(StaffLines, 5),
   omr_model(Model),
   once(search(ordered, omr_grammar(StaffLines, _), Model, _)),
   StaffLines = [0-seg(_, point(_, Y0), _), synth-seg(point(X1, Y1), point(X2, Y2), Th) | _],
   Y0 =:= 208.0,
   near(Y1, 248.82, 0.01),
   Y1 =:= Y2,
   near(X1, 100.0, 0.01),
   near(X2, 504.4, 0.01),
   near(Th, 4.257, 0.001),
   once(search(ordered, omr_grammar(_, [note(synth-ccx(X, Y, notehead), Pitch) | _]), Model, _)),
   var(X), var(Y), var(Pitch).

% The parse the search finds, as the ground truth the noises are learned on.
ground_truth(StaffLines, Notes) :-
   detections(Dets),
   maplist({Dets}/[Id, Id-Det]>>memberchk(Id-Det, Dets), [0, 4, 3, 2], [L0, L4, L3, L2]),
   StaffLines = [L0, synth-_, L4, L3, L2],
   maplist({Dets}/[Id-P, note(Id-Det, P)]>>memberchk(Id-Det, Dets),
           [6-(-8), 7-(-7), 8-(-6), 9-(-5), 10-(-4), 11-(-3), 12-(-2)], Notes).

% fitted(-Scores, -Noises): the fit of the noises on the ground truth, 30 steps, run once
% for the tests that read it.
:- dynamic fitted_/2.

fitted(Scores, Noises), fitted_(Scores0, Noises0) => Scores = Scores0, Noises = Noises0.
fitted(Scores, Noises) =>
   ground_truth(StaffLines, Notes),
   omr_model(Model),
   fit(omr_grammar(StaffLines, Notes), Model, [steps(30), rate(0.01)], fit(Scores, Noises)),
   assertz(fitted_(Scores, Noises)).

% Gradient descent on the noises lowers the score along the parse at every step, from the
% score of the search; the noises stay positive.
test(descent_lowers_the_score_along_the_parse, [timeout(900)]) :-
   fitted(Scores, Noises),
   Scores = [First | _],
   near(First, 119.97940247326369),
   forall(append(_, [S1, S2 | _], Scores), S2 < S1),
   forall(member(_-q_r(Q, R), Noises),
          ( omr:diagonal(Q, Dq), omr:diagonal(R, Dr), forall(member(D, Dq), D > 0), forall(member(D, Dr), D > 0) )).

% With the noises learned, the search finds the same parse, at a lower score.
test(the_search_finds_the_parse_under_the_learned_noises, [timeout(900), setup(findall(K-Q-R, omr:learned_q_r(K, Q, R), Saved)), cleanup(restore(Saved))]) :-
   fitted(Scores, Noises),
   last(Scores, Learned),
   set_noises(Noises),
   parse(ordered, Lines, Pitches, Score, _, _),
   expected_ids(ExpectedLines, ExpectedPitches),
   Lines == ExpectedLines,
   Pitches == ExpectedPitches,
   Score < 119.0,
   near(Score, Learned).

restore(Saved) :-
   reset_noises,
   forall(member(K-Q-R, Saved), assertz(omr:learned_q_r(K, Q, R))).

:- end_tests(omr).
