:- module(best_first,
          [ search/4,               % +Strategy, :Goal, ?Score, ?Template
            best_first/3,           % :Goal, ?Score, ?Template
            depth_first/1,          % :Goal
            search_children/3,      % :Goal, ?Template, -Children
            search_expansions/1,    % -N
            best_first_expansions/1 % -N
          ]).
:- use_module(library(heaps)).
:- use_module(library(apply)).
:- use_module(library(lists)).

/** <module> Search strategies over a nondeterministic goal

The goal announces each choice it makes with shift(priority(F, H)): F is a
lower bound of the score of every completion of the branch, never
decreasing along a branch (used to prune and by best_first), and H an
estimate of the final score (used to order the children of a node). A driver runs the goal up to the next shift on
every branch (by backtracking inside findall/3): each suspended branch is a
node, a copy of the branch's continuation and of the variables it shares
with the template; resuming a node continues on the copy. A branch that
runs to completion has its exact score as both F and H.

Strategies (search/4):
  - depth_first: plain Prolog order, priorities ignored; all solutions.
  - ordered: depth-first, the children of each node sorted by estimate;
    all solutions, the first one is the greedy descent.
  - lds(K): limited discrepancy search: the ordered descent, allowing up
    to K discrepancies on a path. A discrepancy is a child taken after a
    sibling that had a solution (the ordering is overruled); a child taken
    after siblings without solution (pruned by the goal itself) costs
    nothing, so lds(0) is the greedy descent with its backtracking on dead
    ends. One depth-first pass: each path once, in ordered order.
  - branch_and_bound: ordered depth-first, a node is skipped when its
    bound is not below the best complete score found so far; yields the
    improving solutions, the last one is the optimum.
  - best_first: the node of the whole frontier with the lowest bound
    first (A*); solutions in ascending score, the first one is the
    optimum.

Rules for the goal: no shift between the driver and an enclosing findall/3,
forall/2, catch/3, \+/1 or the condition of an if-then-else; the choices
are plain disjunctions and backtracking.
*/

:- meta_predicate
    search(+, 0, ?, ?),
    best_first(0, ?, ?),
    depth_first(0),
    search_children(0, ?, -).

%!  search(+Strategy, :Goal, ?Score, ?Template) is nondet.
%
%   Solutions of Goal under Strategy (see the module doc). Score must be
%   bound by Goal when it completes; Template is what each solution
%   returns (a copy, except for depth_first).

search(Strategy, Goal, Score, Template) :-
    flag(search_expansions, _, 0),
    search_(Strategy, Goal, Score, Template).

search_(depth_first, Goal, _, _) :-
    depth_first(Goal).
search_(ordered, Goal, Score, T) :-
    search_children(Goal, Score-T, Cs),
    ordered(Cs, Score-T).
search_(lds(K), Goal, Score, T) :-
    search_children(Goal, Score-T, Cs),
    lds(Cs, K, Score-T).
search_(branch_and_bound, Goal, Score, T) :-
    Inc = incumbent(inf),
    search_children(Goal, Score-T, Cs),
    bb(Cs, Inc, Score-T).
search_(best_first, Goal, Score, T) :-
    empty_heap(H0),
    search_children(Goal, Score-T, Cs),
    foldl(add_child, Cs, H0, H),
    pop(H, Score-T).

add_child(_-c(F, Node), H0, H) :-
    add_to_heap(H0, F, Node, H).

%!  search_children(:Goal, ?Template, -Children) is det.
%
%   Children: the branches of Goal up to their next shift, as
%   H-c(F, Node) sorted by estimate H; Node is node(Cont, Template) or
%   done(Template) (completed: F = H = its score). Template is
%   Score-Rest.

search_children(Goal, T, Sorted) :-
    flag(search_expansions, N, N + 1),
    findall(H-c(F, Node),
            ( reset(Goal, priority(F0, H0), Cont),
              (   Cont == 0
              ->  T = Score-_,
                  must_be(number, Score),
                  F = Score,
                  H = Score,
                  Node = done(T)
              ;   F = F0,
                  H = H0,
                  Node = node(Cont, T)
              ) ),
            Children),
    keysort(Children, Sorted).

ordered(Cs, T) :-
    member(_-c(_, Node), Cs),
    ordered_node(Node, T).

ordered_node(done(T0), T) :-
    T = T0.
ordered_node(node(Cont, T0), T) :-
    search_children(Cont, T0, Cs),
    ordered(Cs, T).

% D: the discrepancies still allowed on this path. Seen records (across
% backtracking) whether a sibling already gave a solution.
lds(Cs, D, T) :-
    lds_(Cs, D, seen(false), T).

lds_([_-c(_, Node) | Cs], D, Seen, T) :-
    (   arg(1, Seen, true)
    ->  D1 is D - 1
    ;   D1 = D
    ),
    (   D1 >= 0,
        lds_node(Node, D1, T),
        nb_setarg(1, Seen, true)
    ;   lds_(Cs, D, Seen, T)
    ).

lds_node(done(T0), _, T) :-
    T = T0.
lds_node(node(Cont, T0), D, T) :-
    search_children(Cont, T0, Cs),
    lds(Cs, D, T).

% Children in estimate order; each is skipped if its bound is not below
% the incumbent at the time it is reached.
bb(Cs, Inc, T) :-
    member(_-c(F, Node), Cs),
    arg(1, Inc, Best),
    F < Best,
    bb_node(Node, Inc, T).

bb_node(done(T0), Inc, T) :-
    T0 = Score-_,
    nb_setarg(1, Inc, Score),
    T = T0.
bb_node(node(Cont, T0), Inc, T) :-
    search_children(Cont, T0, Cs),
    bb(Cs, Inc, T).

pop(H, T) :-
    get_from_heap(H, _, Node, H1),
    (   Node = done(T1)
    ->  (   T = T1
        ;   pop(H1, T)
        )
    ;   Node = node(Cont, T1),
        search_children(Cont, T1, Cs),
        foldl(add_child, Cs, H1, H2),
        pop(H2, T)
    ).

%!  best_first(:Goal, ?Score, ?Template) is nondet.
%
%   search(best_first, Goal, Score, Template).

best_first(Goal, Score, Template) :-
    search(best_first, Goal, Score, Template).

%!  depth_first(:Goal) is nondet.
%
%   Runs Goal ignoring the priorities, in plain Prolog order: the replay
%   of a decided solution, or an exhaustive enumeration of a small input.

depth_first(Goal) :-
    reset(Goal, _, Cont),
    (   Cont == 0
    ->  true
    ;   depth_first(Cont)
    ).

%!  search_expansions(-N) is det.
%
%   Number of nodes expanded since the last search/4 call started.

search_expansions(N) :-
    flag(search_expansions, N, N).

best_first_expansions(N) :-
    search_expansions(N).
