% Exact knot scoring for rail-cube2.pl, which includes this file.
% Do not load this file on its own.
% The Alexander matrix calculations stay here so the search is easier to read.

% The rail paths and both ways to separate the paths at X follow the article
% and the C solver.
% An Alexander polynomial that is not a unit earns the knot bonus.
% Knots with a unit Alexander polynomial go undetected, as in the article.
% The final decision uses exact integer arithmetic.
% It uses no sampled determinant threshold or modular identity test.
%
%    ^ ^
%  =(o.o)=
%    m m
% ~byakuren

% ------ rail polygon ------

rc_knot(Placed, Knot) :-
    rc_rail_polygon(Placed, 1, Over),
    rc_polygon_knot(Over, First),
    (   First == true
    ->  Knot = true
    ;   rc_rail_polygon(Placed, -1, Under),
        rc_polygon_knot(Under, Knot)
    ).

rc_rail_polygon(Placed, Resolution, Polygon) :-
    rc_rail_points(Placed, 0, Resolution, Points, []),
    Points = [First|_],
    rc_last(Points, Last),
    rc_corners(Points, Last, First, Polygon).

rc_rail_points([], _, _, Tail, Tail).
rc_rail_points([placed(P,Position-Orientation,_,_)|Ps], I, Resolution, Points, Tail) :-
    rc_frame(Orientation, Frame),
    ( P == x, I > 0 -> Lift = Resolution ; Lift = 0 ),
    rc_samples(0, P, Position, Frame, Lift, Points, Rest),
    J is I+1,
    rc_rail_points(Ps, J, Resolution, Rest, Tail).

rc_samples(8, _, _, _, _, Tail, Tail).
rc_samples(N, P, Position, Frame, Lift, [Point|Points], Tail) :-
    N < 8,
    T is N/8,
    rc_rail_local(P, T, Forward, Left, Up),
    Height is Up+Lift*2*sin(3.14159265358979323846*T),
    rc_transform(Frame, [Forward,Left,Height], Offset),
    rc_scale(Position, 20, Origin),
    rc_add(Origin, Offset, Point),
    M is N+1,
    rc_samples(M, P, Position, Frame, Lift, Points, Tail).

rc_rail_local(s, T, F, 0, 8) :-
    F is -10+20*T.
rc_rail_local(x, T, F, 0, 8) :-
    F is -10+20*T.
rc_rail_local(l, T, F, L, 8) :-
    A is T*3.14159265358979323846/2,
    F is -10+30*sin(A),
    L is 30-30*cos(A).
rc_rail_local(r, T, F, L, 8) :-
    A is T*3.14159265358979323846/2,
    F is -10+30*sin(A),
    L is -30+30*cos(A).
rc_rail_local(i, T, F, 0, U) :-
    A is T*3.14159265358979323846/2,
    F is -10+22*sin(A),
    U is 30-22*cos(A).
rc_rail_local(o, T, F, 0, U) :-
    S is T*(14+11*3.14159265358979323846/2),
    Corner is 7+11*3.14159265358979323846/2,
    (   S =< 7
    ->  F is -10+S,
        U = 8
    ;   S =< Corner
    ->  A is (S-7)/11,
        F is -3+11*sin(A),
        U is -3+11*cos(A)
    ;   F = 8,
        U is -3-(S-Corner)
    ).

rc_last([X], X).
rc_last([_|Xs], X) :-
    rc_last(Xs, X).

rc_corners([], _, _, []).
rc_corners([P|Ps], Previous, First, Corners) :-
    ( Ps = [Next|_] -> true ; Next = First ),
    rc_subtract(P, Previous, A),
    rc_subtract(Next, P, B),
    rc_cross(A, B, C),
    rc_dot(C, C, Norm),
    ( Norm > 1.0e-16 -> Corners = [P|Rest] ; Corners = Rest ),
    rc_corners(Ps, P, First, Rest).


% ------ planar projection ------

% Project the path onto a plane. Skip degenerate projections.
% Choose a diagram with few crossings to reduce the cost of the exact
% determinant calculation.
% A diagram with fewer than three crossings proves that the path is unknotted.
rc_views([[ 1.123,  2.371,  3.719],
          [ 3.119, -1.733,  2.431],
          [-2.193,  3.417,  1.571],
          [ 0.713, -2.173,  4.319],
          [ 4.217,  1.139, -2.513],
          [-1.117, -3.193,  2.713],
          [ 2.313,  4.171, -0.917],
          [ 3.719, -2.219, -1.317],
          [ 0.319,  1.731, -2.137],
          [-3.117,  0.719,  1.913],
          [ 2.917, -4.131,  0.317],
          [-1.937, -2.719, -3.113]]).

rc_polygon_knot(Points, Knot) :-
    rc_views(Views),
    rc_best_diagram(Views, Points, none, Best),
    (   Best = diagram(N,Crossings)
    ->  ( N < 3 -> Knot = false ; rc_alexander(Crossings, N, Knot) )
    ;   throw(error(evaluation_error(knot_projection), rc_knot/2))
    ).

rc_best_diagram([], _, Best, Best).
rc_best_diagram([View|Views], Points, Best0, Best) :-
    (   rc_project_diagram(Points, View, Crossings),
        rc_length(Crossings, N)
    ->  (   N < 3
        ->  Best = diagram(N,Crossings)
        ;   (   Best0 = diagram(M,_), M =< N
            ->  Next = Best0
            ;   Next = diagram(N,Crossings)
            ),
            rc_best_diagram(Views, Points, Next, Best)
        )
    ;   rc_best_diagram(Views, Points, Best0, Best)
    ).

rc_normalize(V, U) :-
    rc_dot(V, V, N),
    N > 1.0e-16,
    K is 1/sqrt(N),
    rc_scale(V, K, U).

rc_project_diagram(Points, View, Crossings) :-
    rc_normalize(View, V),
    V = [_,_,Z],
    ( abs(Z) < 0.8 -> Ref = [0,0,1] ; Ref = [1,0,0] ),
    rc_cross(V, Ref, U0),
    rc_normalize(U0, U),
    rc_cross(V, U, W),
    rc_project_points(Points, frame(U,W,V), Projected),
    Projected = [First|_],
    rc_segments(Projected, First, 0, Segments),
    rc_length(Segments, N),
    Last is N-1,
    rc_intersections(Segments, Last, Crossings, []).

rc_project_points([], _, []).
rc_project_points([P|Ps], frame(U,W,V), [[X,Y,Z]|Projected]) :-
    rc_dot(P, U, X),
    rc_dot(P, W, Y),
    rc_dot(P, V, Z),
    rc_project_points(Ps, frame(U,W,V), Projected).

rc_segments([], _, _, []).
rc_segments([[X,Y,Z]|Ps], First, I, [Segment|Segments]) :-
    ( Ps = [Next|_] -> true ; Next = First ),
    Next = [A,B,C],
    Dx is A-X,
    Dy is B-Y,
    Dz is C-Z,
    rc_min(X, A, LoX),
    rc_max(X, A, HiX),
    rc_min(Y, B, LoY),
    rc_max(Y, B, HiY),
    Segment = segment(I,X,Y,Z,Dx,Dy,Dz,LoX,HiX,LoY,HiY),
    J is I+1,
    rc_segments(Ps, First, J, Segments).


% ------ crossings ------

rc_intersections([], _, Tail, Tail).
rc_intersections([Segment|Segments], Last, Crossings, Tail) :-
    (   Segments = [_|Rest]
    ->  rc_segment_pairs(Rest, Segment, Last, Crossings, More)
    ;   Crossings = More
    ),
    rc_intersections(Segments, Last, More, Tail).

rc_segment_pairs([], _, _, Tail, Tail).
rc_segment_pairs([B|Bs], A, Last, Crossings, Tail) :-
    A = segment(I,_,_,_,_,_,_,_,_,_,_),
    B = segment(J,_,_,_,_,_,_,_,_,_,_),
    (   I =:= 0, J =:= Last
    ->  Crossings = Rest
    ;   rc_segment_crossing(A, B, Result),
        ( Result == none -> Crossings = Rest ; Crossings = [Result|Rest] )
    ),
    rc_segment_pairs(Bs, A, Last, Rest, Tail).

rc_segment_crossing(segment(_,_,_,_,_,_,_,Lx,Hx,Ly,Hy),
                    segment(_,_,_,_,_,_,_,Lu,Hu,Lv,Hv), Result) :-
    ( Hx < Lu ; Hu < Lx ; Hy < Lv ; Hv < Ly ),
    !,
    Result = none.

rc_segment_crossing(segment(I,X,Y,Z,Ax,Ay,Az,_,_,_,_),
                    segment(J,U,V,W,Bx,By,Bz,_,_,_,_), Result) :-
    Det is Ax*By-Ay*Bx,
    Dx is U-X,
    Dy is V-Y,
    (   abs(Det) < 1.0e-10
    ->  abs(Dx*Ay-Dy*Ax) >= 1.0e-8,
        Result = none
    ;   S is (Dx*By-Dy*Bx)/Det,
        T is (Dx*Ay-Dy*Ax)/Det,
        (   ( S < -1.0e-8 ; S > 1.00000001
            ; T < -1.0e-8 ; T > 1.00000001
            )
        ->  Result = none
        ;   S > 1.0e-8,
            S < 0.99999999,
            T > 1.0e-8,
            T < 0.99999999,
            Depth is Z+S*Az-W-T*Bz,
            abs(Depth) > 1.0e-8,
            ( Depth > 0 -> Over = true, Signed = Det
            ; Over = false, Signed is -Det
            ),
            ( Signed > 0 -> Sign = 1 ; Sign = -1 ),
            Result = crossing(I,J,S,T,Over,Sign)
        )
    ).


% ------ Alexander matrix ------

% Each crossing gives one row of the Alexander matrix.
% The row uses the incoming and outgoing under-arcs and the over-arc.
% Delete one row and one column to form a minor.
rc_alexander(Crossings, N, Knot) :-
    rc_events(Crossings, 0, Events),
    keysort(Events, Sorted),
    A is N-1,
    rc_arcs(Sorted, N, A, 0, Under, Over),
    rc_rows(Crossings, 0, Under, Over, N, Rows),
    keysort(Rows, Ordered),
    rc_matrix(Ordered, N, -1, Small),
    rc_determinant(Small, Det),
    Abs is abs(Det),
    (   Abs > 1
    ->  Knot = true
    ;   Abs =:= 1
    ->  Bits is 2*(N-1)+2,
        rc_power(2, Bits, Base),
        rc_matrix(Ordered, N, Base, Matrix),
        rc_determinant(Matrix, Value),
        Positive is abs(Value),
        (   Positive =:= 0
        ->  throw(error(evaluation_error(knot_matrix), rc_knot/2))
        ;   rc_power_of(Positive, Base)
        ->  Knot = false
        ;   Knot = true
        )
    ;   throw(error(evaluation_error(knot_matrix), rc_knot/2))
    ).

rc_events([], _, []).
rc_events([crossing(I,J,S,T,IsOver,_)|Cs], Id,
          [A-event(Id,P),B-event(Id,Q)|Events]) :-
    A is I+S,
    B is J+T,
    ( IsOver == true -> P = over, Q = under ; P = under, Q = over ),
    Next is Id+1,
    rc_events(Cs, Next, Events).

rc_arcs([], _, _, _, [], []).
rc_arcs([_-event(Id,Kind)|Events], N, Arc, Row, Under, Over) :-
    (   Kind == over
    ->  Over = [Id-Arc|Os],
        Under = Us,
        NewArc = Arc,
        NewRow = Row
    ;   NewArc is (Arc+1) mod N,
        NewRow is Row+1,
        Under = [Id-Row|Us],
        Over = Os
    ),
    rc_arcs(Events, N, NewArc, NewRow, Us, Os).

rc_rows([], _, _, _, _, []).
rc_rows([crossing(_,_,_,_,_,Sign)|Cs], Id, Under, Over, N,
        [Row-row(Above,Prev,Row,Sign)|Rows]) :-
    rc_member(Id-Row, Under),
    rc_member(Id-Above, Over),
    Prev is (Row+N-1) mod N,
    Next is Id+1,
    rc_rows(Cs, Next, Under, Over, N, Rows).

rc_matrix([], _, _, []).
rc_matrix([R-Row|Rows], N, T, Matrix) :-
    Limit is N-1,
    (   R < Limit
    ->  Matrix = [Cells|Rest],
        rc_matrix_row(0, Limit, Row, T, Cells)
    ;   Matrix = Rest
    ),
    rc_matrix(Rows, N, T, Rest).

rc_matrix_row(Col, N, _, _, []) :-
    Col >= N.
rc_matrix_row(Col, N, row(Above,Prev,Current,Sign), T, [Cell|Cells]) :-
    Col < N,
    ( Col =:= Above -> A is 1-T ; A = 0 ),
    ( Sign > 0 -> B = T, C = -1 ; B = -1, C = T ),
    ( Col =:= Prev -> D = B ; D = 0 ),
    ( Col =:= Current -> E = C ; E = 0 ),
    Cell is A+D+E,
    Next is Col+1,
    rc_matrix_row(Next, N, row(Above,Prev,Current,Sign), T, Cells).


% ------ Bareiss determinant ------

% Bareiss elimination avoids fractions. Every division is exact.
% The matrix shrinks at each step. This avoids arrays that change in place
% and updates to individual elements by index.
rc_determinant(Matrix, Det) :-
    rc_bareiss(Matrix, 1, Det).

rc_bareiss([], _, 1).
rc_bareiss([[D]], _, D).
rc_bareiss([Row,Next|Rows], Previous, Det) :-
    (   rc_pivot([Row,Next|Rows], [Pivot|Top], Others, Sign)
    ->  rc_eliminate_rows(Others, Top, Pivot, Previous, Reduced),
        rc_bareiss(Reduced, Pivot, D),
        Det is Sign*D
    ;   Det = 0
    ).

rc_pivot([[P|Ps]|Rows], [P|Ps], Rows, 1) :-
    P =\= 0,
    !.
rc_pivot([Row|Rows], Pivot, [Row|Rest], Sign) :-
    rc_pivot(Rows, Pivot, Rest, S),
    Sign is -S.

rc_eliminate_rows([], _, _, _, []).
rc_eliminate_rows([[Left|Cells]|Rows], Top, Pivot, Previous, [New|Rest]) :-
    rc_eliminate_cells(Cells, Top, Left, Pivot, Previous, New),
    rc_eliminate_rows(Rows, Top, Pivot, Previous, Rest).

rc_eliminate_cells([], [], _, _, _, []).
rc_eliminate_cells([Cell|Cells], [T|Top], Left, Pivot, Previous, [New|Rest]) :-
    Numerator is Pivot*Cell-Left*T,
    (   0 is Numerator mod Previous
    ->  New is Numerator//Previous
    ;   throw(error(evaluation_error(non_exact_division), rc_determinant/2))
    ),
    rc_eliminate_cells(Cells, Top, Left, Pivot, Previous, Rest).


% ------ polynomial unit test ------

% Each coefficient of this minor has absolute value <= 4^(N-1).
% Multiply the row polynomial 1-norms (sums of absolute coefficients).
% The result bounds the determinant's coefficient 1-norm.
% B=2^(2*(N-1)+2) is larger than twice this bound.
% Balanced base-B digits then identify a unit (+/-t^k) exactly:
% abs(det(B)) must be B^k.
rc_power(_, 0, 1).
rc_power(Base, N, Value) :-
    N > 0,
    Half is N//2,
    rc_power(Base, Half, P),
    Square is P*P,
    ( 0 is N mod 2 -> Value = Square ; Value is Square*Base ).

rc_power_of(1, _) :- !.
rc_power_of(N, Base) :-
    N > 1,
    0 is N mod Base,
    Next is N//Base,
    rc_power_of(Next, Base).
