:- module(detector_tests, []).

:- use_module(library(array)).
:- use_module('../examples/detector').
:- use_module('../examples/example_data', [example_file_present/1]).

% The detector of examples/detector.pl against torch, in two units. The first needs no data: a
% detector of the same structure, of random weights, 2 layers of 2 heads of 8 on patches of
% 8 x 8, 4 symbol classes, 3 line classes and 2 shapes, and two random pages of 20 x 27
% pixels, one grey, one of three channels, each with two flat patches the variance drops and a
% last row and column of patches the padding completes; test/detector_tiny_weights.safetensors
% and test/detector_tiny_pages.safetensors, written with torch's outputs for each page by
% `examples/detector.py --tiny`. Torch computes in float32 on the CPU; the outputs, up to ~20,
% agree to 1e-4.

tiny_file(Name, File) :-
   module_property(detector_tests, file(Here)),
   file_directory_name(Here, Dir),
   directory_file_path(Dir, Name, File).

tiny(Model, Pages, Refs) :-
   tiny_file('detector_tiny_weights.safetensors', Weights),
   tiny_file('detector_tiny_pages.safetensors', File),
   detector_model(pocl, Model, [weights(Weights)]),
   detector_pages(Pages, Refs, [pages(File)]).

:- begin_tests(detector_tiny).

test(the_model_is_the_one_of_the_fixture, [timeout(120)]) :-
   tiny(Model, Pages, _),
   assertion(Model.patch == 8),
   assertion(Model.heads-Model.dim_head == 2-8),
   assertion(Model.shapes == 2),
   assertion(Model.symbols == [dot, bar, hook, ring]),
   assertion(Model.lines == [rule, arc, tie]),
   maplist(shape, Pages, Shapes),
   assertion(Shapes == [[20, 27], [20, 27, 3]]).

test(a_grey_page_keeps_torchs_patches_and_gives_its_outputs, [timeout(120)]) :-
   tiny(Model, [Page, _], [Ref, _]),
   against_torch(Model, Page, Ref, 8, 10, 1.0e-4).

test(an_rgb_page_keeps_torchs_patches_and_gives_its_outputs, [timeout(120)]) :-
   tiny(Model, [_, Page], [_, Ref]),
   against_torch(Model, Page, Ref, 8, 10, 1.0e-4).

test(the_channels_of_an_rgb_page_are_not_one_grey, [timeout(120)]) :-
   tiny_file('detector_tiny_pages.safetensors', File),
   detector_pages(_, [Grey, Rgb], [pages(File)]),
   elements_of(Grey.sym_logits, float32, Gs),
   elements_of(Rgb.sym_logits, float32, Rs),
   foldl([A, B, E0, E]>>(E is max(E0, abs(A - B))), Gs, Rs, 0, Err),
   assertion(Err > 0.1).

test(every_shape_of_a_kept_patch_is_a_detection_at_no_score, [timeout(120)]) :-
   tiny(Model, [Page, _], _),
   detect(Model, Page, Ds, [min_score(0.0)]),
   partition([D]>>functor(D, symbol, 6), Ds, Syms, Lines),
   append(Syms, Lines, Ds),
   length(Syms, Ns), length(Lines, Nl),
   assertion(Ns-Nl == 20-20),
   forall(member(D, Syms), ( arg(1, D, C), assertion(memberchk(C, Model.symbols)) )),
   forall(member(D, Lines), ( arg(1, D, C), assertion(memberchk(C, Model.lines)) )),
   forall(member(D, Ds), assertion(within(D, 0.0, 20, 27))),
   best_first(Syms),
   best_first(Lines),
   detect(Model, Page, Best, [min_score(0.0), max_symbols(3), max_lines(1)]),
   length(Syms3, 3), append(Syms3, _, Syms),
   Lines = [Line | _],
   append(Syms3, [Line], Expected),
   assertion(Best == Expected).

:- end_tests(detector_tiny).

% against_torch(+Model, +Page, +Ref, +P, +N, +Tol): the page keeps the N patches of P pixels
% torch keeps, and the outputs of the network on them are torch's within Tol.
against_torch(Model, Page, Ref, P, N, Tol) :-
   against_torch(Model, Page, Ref, P, N, Tol, _).

% against_torch(+Model, +Page, +Ref, +P, +N, +Tol, -Outs): Outs those outputs, of the one run.
against_torch(Model, Page, Ref, P, N, Tol, Outs) :-
   kept_patches(Model, Page, Gy, Gx),
   shape(Page, [_, W | _]),
   Gw is (W + P - 1) // P,
   maplist({Gw}/[Y, X, I]>>(I is Y*Gw + X), Gy, Gx, Kept),
   length(Kept, Count),
   assertion(Count == N),
   elements_of(Ref.kept, int32, Theirs),
   assertion(Kept == Theirs),
   detector_outputs(Model, Page, Gy, Gx, Outs),
   maplist(output_against_torch(Outs, Ref, Tol), [sym_logits, sym_boxes, line_logits, line_keypoints]).

output_against_torch(Outs, Ref, Tol, Key) :-
   detector:rows(Outs, Key, float32, Mine),
   get_dict(Key, Ref, Torch),
   elements_of(Torch, float32, Theirs),
   close_to(Mine, Theirs, Tol).

best_first(Ds) :-
   maplist(score, Ds, Ss),
   msort(Ss, Up),
   reverse(Up, Down),
   assertion(Ss == Down).

% The second unit: the music_deep detector against torch, on the pages of
% detector_pages.safetensors: the files are written by examples/detector.py from a checkpoint
% of ~/prog/music_deep, or downloaded once by the example; the unit runs only where they are,
% and never downloads them. Torch's outputs are float32 on
% its own device; the elements of the kept patches, the rows of padding left out, agree to
% 1e-3, logits up to ~20 and patch coordinates up to ~115.
%
% Each test is one model, one compilation and one run of the network: the outputs are compared
% with torch's and the detections read from the same outputs. The first page, a crop of a
% Trompa page with 117 patches kept, two tiles of rows, runs on pocl: part of a system, an F
% clef, flats, black noteheads and their stems, its staff lines cut by the crop. The second,
% the whole page of 891 patches, fourteen tiles, runs on a GPU, where there is one: on a CPU
% runtime its compilation and run are minutes. The times are the drivers' compilations, which
% their caches keep: the crop on pocl 6 s warm and 2 minutes cold, the page on a Quadro M1200
% 4 s warm and 2 to 3 minutes cold, 10 on a loaded machine.

data_files :-
   example_file_present('detector_weights.safetensors'),
   example_file_present('detector_pages.safetensors').

% gpu(-Device): the first OpenCL device that is a GPU.
gpu(Device) :-
   once(( opencl:opencl_device(Device, D), opencl:cl_device_info(D, type, gpu) )).

:- begin_tests(detector, [condition(data_files)]).

test(the_crop_gives_torchs_outputs_and_its_detections_best_first, [timeout(600)]) :-
   detector_model(pocl, Model),
   detector_pages([Page | _], [Ref | _]),
   against_torch(Model, Page, Ref, 64, 117, 1.0e-3, Outs),
   detector:detections(Model, Page, Outs, Ds, [min_score(0.5)]),
   in_the_page_best_first(Page, Ds, Syms, Lines),
   assertion(memberchk(symbol(fClef, _, _, _, _, _), Syms)),
   assertion(memberchk(symbol(noteheadBlack, _, _, _, _, _), Syms)),
   assertion(memberchk(line(stem, _, _, _, _, _), Lines)).

test(the_whole_page_gives_torchs_outputs_and_its_detections_best_first,
     [condition(gpu(Device)), timeout(900)]) :-
   detector_model(Device, Model),
   detector_pages([_, Page | _], [_, Ref | _]),
   against_torch(Model, Page, Ref, 64, 891, 1.0e-3, Outs),
   detector:detections(Model, Page, Outs, Ds, [min_score(0.5)]),
   in_the_page_best_first(Page, Ds, Syms, Lines),
   length(Syms, Ns), length(Lines, Nl),
   assertion(Ns >= 50),
   assertion(Nl >= 150),
   forall(member(C, [gClef, fClef, brace, noteheadBlack]),
          assertion(memberchk(symbol(C, _, _, _, _, _), Syms))),
   forall(member(C, [staff, barLine, stem, beam]),
          assertion(memberchk(line(C, _, _, _, _, _), Lines))).

:- end_tests(detector).

% in_the_page_best_first(+Page, +Ds, -Syms, -Lines): the detections Ds of Page are its symbols
% then its lines, each of a score of 0.5 at least, within the page and best first.
in_the_page_best_first(Page, Ds, Syms, Lines) :-
   shape(Page, [H, W | _]),
   partition([D]>>functor(D, symbol, 6), Ds, Syms, Lines),
   assertion(append(Syms, Lines, Ds)),
   forall(member(D, Ds), assertion(within(D, 0.5, H, W))),
   best_first(Syms),
   best_first(Lines).

score(D, S) :-
   arg(2, D, S).

within(D, Min, H, W) :-
   D =.. [_, _, S, X1, Y1, X2, Y2],
   S >= Min, S =< 1.0,
   forall(member(X, [X1, X2]), ( X >= 0, X =< W )),
   forall(member(Y, [Y1, Y2]), ( Y >= 0, Y =< H )).

elements_of(Name, Type, Values) :-
   detector:host_elements(Name, Type, Values).

% close_to(+As, +Bs, +Tol): lists of one length, within Tol of each other.
close_to(As, Bs, Tol) :-
   assertion(same_length(As, Bs)),
   foldl([A, B, E0, E]>>(E is max(E0, abs(A - B))), As, Bs, 0, Err),
   assertion(Err < Tol).
