:- module(answer_tests, []).

:- use_module(library(array)).
:- use_module(library(array/buffer)).
:- use_module(library(clpBNR)).
:- use_module(library(process)).
:- use_module(library(readutil)).

:- prolog_load_context(directory, Dir),
   file_directory_name(Dir, Root),
   asserta(root(Root)).

:- begin_tests(answer).

matmul(A, B, C, N, M, P) :-
   shape(A, [N, M]), shape(B, [M, P]), shape(C, [N, P]),
   over([I:N, J:P], [C[I, J] := 0]),
   over([I:N, J:P, K:M], [C[I, J] := C[I, J] + A[I, K] * B[K, J]]).

% mlp(-X, -Y, -N): Y = relu(X W1) W2, X of N rows, W1 and W2 inputs not in the bindings.
mlp(X, Y, N) :-
   N::integer(1, 64),
   shape(X, [N, 4]),
   matmul(X, _, H, N, 4, 8),
   shape(R, [N, 8]),
   over([I:N, J:8], [R[I, J] := max(0, H[I, J])]),
   matmul(R, _, Y, N, 8, 2).

tensor(Type, Shape, Values, Name) :-
   foldl([E, P0, P]>>(P is P0*E), Shape, 1, N),
   compound_name_arguments(Data, data, Values),
   buffer_from_data(Buffer, Type, N, Data),
   shape(Name, Shape),
   type_kind(Type, Kind),
   kind(Name, Kind),
   value(Name, Buffer).

type_kind(float32, float).
type_kind(int32, int).

printed(Goal, Text) :-
   with_output_to(string(Text), Goal).

test(short_input_and_computed, [timeout(10), true(T == Expected)]) :-
   matmul(A, B, C, 2, 3, N),
   printed(print_array(C-A, [mode(short), variable_names(['A'=A, 'B'=B, 'C'=C, 'N'=N])]), T),
   Expected = "N::integer(0, inf),\n\c
               C: float[2, N]  C[I, J] += A[I, K]*_[K, J],\n\c
               A: float[2, 3].\n".

test(full_declares_at_first_mention, [timeout(10), true(T == Expected)]) :-
   matmul(A, B, C, 2, 3, 4),
   printed(print_array(C, [mode(full), variable_names(['A'=A, 'B'=B, 'C'=C])]), T),
   Expected = "shape(C, [2, 4]), kind(C, float),\n\c
               over([I:2, J:4], [C[I, J]:=0]),\n\c
               shape(A, [2, 3]), kind(A, float),\n\c
               shape(B, [3, 4]), kind(B, float),\n\c
               over([I:2, J:4, K:3], [C[I, J]:=C[I, J]+A[I, K]*B[K, J]]).\n".

test(full_order_by_names, [timeout(10), true(T == Expected)]) :-
   mlp(X, Y, N),
   printed(print_array(Y, [mode(full), variable_names(['X'=X, 'Y'=Y, 'N'=N])]), T),
   Expected = "N::integer(1, 64),\n\c
               shape(_A, [N, 8]), kind(_A, float),\n\c
               over([I:N, J:8], [_A[I, J]:=0]),\n\c
               shape(X, [N, 4]), kind(X, float),\n\c
               shape(_B, [4, 8]), kind(_B, float),\n\c
               over([I:N, J:8, K:4], [_A[I, J]:=_A[I, J]+X[I, K]*_B[K, J]]),\n\c
               shape(_C, [N, 8]), kind(_C, float),\n\c
               over([I:N, J:8], [_C[I, J]:=max(0, _A[I, J])]),\n\c
               shape(Y, [N, 2]), kind(Y, float),\n\c
               over([I:N, J:2], [Y[I, J]:=0]),\n\c
               shape(_D, [8, 2]), kind(_D, float),\n\c
               over([I:N, J:2, K:8], [Y[I, J]:=Y[I, J]+_C[I, K]*_D[K, J]]).\n".

test(kinds_resolved, [timeout(10), true(T == "B: bool[3]  B[J] := I[J]<2,\nI: int[3].\n")]) :-
   shape(I, [3]), kind(I, int), shape(B, [3]),
   over([J:3], [B[J] := I[J] < 2]),
   printed(print_array(B-I, [mode(short), variable_names(['I'=I, 'B'=B])]), T).

test(nested_box_layout, [timeout(10), true(T == Expected)]) :-
   shape(L, [N, N]), shape(C, [N]),
   over([I:N, J:N], [L[I, J] := 0]),
   over([K:N], [over([I:N], [C[I] := where(I =:= K, sqrt(L[K, K]), where(K < I, L[I, K] / sqrt(L[K, K]), 0))]),
                over([I:N, J:N], [L[I, J] := where(K < J, where(J =< I, L[I, J] - C[I] * C[J], L[I, J]), L[I, J])])]),
   printed(print_array(L, [mode(full), variable_names(['L'=L, 'C'=C, 'N'=N])]), T),
   atomic_list_concat(
      [ "N::integer(0, inf),",
        "shape(L, [N, N]), kind(L, float),",
        "over([I:N, J:N], [L[I, J]:=0]),",
        "shape(C, [N]), kind(C, float),",
        "over([K:N],",
        "     [ over([I:N], [C[I]:=where(I=:=K, sqrt(L[K, K]), where(K<I, L[I, K]/sqrt(L[K, K]), 0))]),",
        "       over([I:N, J:N], [L[I, J]:=where(K<J, where(J=<I, L[I, J]-C[I]*C[J], L[I, J]), L[I, J])]) ]).",
        "" ], "\n", Atom),
   atom_string(Atom, Expected).

% A name a copy writes shows the copy, with its device, in both views.
test(copy_short, [timeout(10), true(T == "B: float[2]  copy(_, B, host).\n")]) :-
   shape(H, [2]), copy(H, W, D), copy(W, B, host),
   printed(print_array(B, [mode(short), variable_names(['H'=H, 'W'=W, 'B'=B, 'D'=D])]), T).

test(copy_full, [timeout(10), true(T == Expected)]) :-
   shape(H, [2]), copy(H, W, D), copy(W, B, host),
   printed(print_array(B, [mode(full), variable_names(['H'=H, 'W'=W, 'B'=B, 'D'=D])]), T),
   Expected = "shape(H, [2]), kind(H, float),\n\c
               shape(W, [2]), kind(W, float),\n\c
               copy(H, W, D),\n\c
               shape(B, [2]), kind(B, float), device(B, host),\n\c
               copy(W, B, host).\n".

test(realized_values, [timeout(10), true(T == "W: float32[2, 3] = [[0.0, 1.0, 2.5], [3.0, 4.0, 5.0]].\n")]) :-
   tensor(float32, [2, 3], [0, 1, 2.5, 3, 4, 5], W),
   printed(print_array(W, [variable_names(['W'=W])]), T).

test(realized_values_summarized, [timeout(10), true(T == Expected)]) :-
   numlist(0, 24, Vs),
   tensor(int32, [5, 5], Vs, W),
   printed(print_array(W, [variable_names(['W'=W])]), T),
   Expected = "W: int32[5, 5] = [[0, 1, 2, 3, 4], ..., [20, 21, 22, 23, 24]].\n".

test(realized_values_long_row, [timeout(10), true(T == "W: int32[20] = [0, 1, 2, ..., 17, 18, 19].\n")]) :-
   numlist(0, 19, Vs),
   tensor(int32, [20], Vs, W),
   printed(print_array(W, [variable_names(['W'=W])]), T).

% Printing changes nothing: the attributes, the boxes and the open kinds are as they were.
test(print_array_is_pure, [timeout(10)]) :-
   mlp(X, Y, _),
   copy_term(Y, _, Gs0),
   printed(print_array(Y, [mode(full)]), _),
   printed(print_array(X-Y, [mode(short)]), _),
   copy_term(Y, _, Gs),
   assertion(Gs0 =@= Gs),
   core:name_kind(Y, K),
   assertion(var(K)).

% The toplevel's own path: expand_answer, then translate_bindings with the collectors. Only
% the items of this module remain, and an interval of the query that no shape holds keeps
% its own clpBNR goal.
test(toplevel_residuals, [timeout(10)]) :-
   mlp(X, Y, N),
   V::integer(1, 5),
   Bindings = ['X'=X, 'Y'=Y, 'N'=N, 'V'=V],
   findall(Rs, ( prolog:expand_answer(true, Bindings, B1),
                 '$toplevel':translate_bindings(B1, _, [], user:Rs-_) ), [Rs]),
   partition([R]>>subsumes_term('$array'(_), R), Rs, Items, Others),
   assertion(Items = ['$array'(goals(['$VAR'('N')::integer(1, 64)])),
                      '$array'(input('$VAR'('X'), float, ['$VAR'('N'), 4])),
                      '$array'(computed('$VAR'('Y'), float, ['$VAR'('N'), 2], _, update(_, _)))]),
   assertion(Others = [_::integer(1, 5)]).

% raw leaves the answer to the attributes.
test(toplevel_raw, [timeout(10), setup(set_prolog_flag(array_answer, raw)),
                    cleanup(set_prolog_flag(array_answer, short))]) :-
   matmul(A, B, C, 2, 3, 4),
   Bindings = ['A'=A, 'B'=B, 'C'=C],
   findall(Rs, ( ( prolog:expand_answer(true, Bindings, B1) -> true ; B1 = Bindings ),
                 '$toplevel':translate_bindings(B1, _, [], user:Rs-_) ), [Rs]),
   assertion(\+ ( member(R, Rs), subsumes_term('$array'(_), R) )),
   assertion(memberchk(shape(_, [2, 4]), Rs)).

% The answer as a terminal shows it, from a toplevel reading the query on its input.
test(toplevel_classifier, [timeout(60), true(Out == Expected)]) :-
   root(Root),
   directory_file_path(Root, prolog, Library),
   current_prolog_flag(arch, Arch),
   atomic_list_concat([Root, lib, Arch], /, Foreign),
   directory_file_path(Root, 'examples/classifier.pl', Classifier),
   atom_concat('library=', Library, L),
   atom_concat('foreign=', Foreign, F),
   current_prolog_flag(executable, Swipl),
   process_create(Swipl, ['-q', '-p', L, '-p', F, Classifier],
                  [stdin(pipe(In)), stdout(pipe(StdOut)), stderr(null)]),
   format(In, "weights(pocl, Net), classifier(Net, X, Y, D).~n", []),
   close(In),
   read_string(StdOut, _, Out),
   close(StdOut),
   atomic_list_concat(
      [ "Net = _{fc1:_{bias:_B, weight:_A}, fc2:_{bias:_D, weight:_C}, fc3:_{bias:_F, weight:_E}},",
        "D = pocl,",
        "_G::integer(1, 1024),",
        "_A: float32[256, 784] = [[-0.0002674, 0.01916, -0.02939, ..., 0.02194, 0.003733, 0.00206], ..., [-0.02199, 0.01826, 0.006697, ..., 0.009257, -0.02576, -0.01413]],",
        "_B: float32[256] = [-0.01172, 0.01327, -0.002469, ..., 0.002638, -0.009203, 0.01348],",
        "_C: float32[128, 256] = [[-0.01537, 0.009676, 0.04446, ..., -0.05938, -0.05945, -0.05039], ..., [-0.05137, 0.04692, -0.04826, ..., 0.03983, 0.007215, 0.01474]],",
        "_D: float32[128] = [-0.06006, 0.04479, -0.05435, ..., 0.04721, 0.04235, 0.03167],",
        "_E: float32[10, 128] = [[0.0604, -0.01351, 0.07773, ..., -0.06933, -0.04642, -0.0834], ..., [0.05227, -0.04146, -0.05195, ..., -0.0304, -0.03817, 0.046]],",
        "_F: float32[10] = [-0.07716, -0.03697, 0.08152, 0.04447, 0.04182, -0.06845, -0.07639, 0.05606, 0.03022, -0.08212],",
        "X: float[_G, 784],",
        "Y: float[_G, 10]  copy(_, Y, host).",
        "", "", "" ], "\n", Atom),
   atom_string(Atom, Expected).

:- end_tests(answer).
