Search code examples
prologeclipse-clp

ECLiPSe CLP : Pause between subresults found by search/6 in ic library


(This question regards search/6.)

I was wondering if there is a way -rather than manual tracing- to pause the execution of search/6 every time a new solution for a single variable was found?

I would like to accomplish this to further investigate what is happening during search in constrained models.

For example, if you are trying to solve the classic sudoku problem, and you have written a set of constraints and a print method for your board, it can be useful to print the board after setting the constraints, but before searching, in order to evaluate the strongness of your constraints. However, once search is called to solve the sudoku, you don't really have an overview of the single results being built underneath unless you do a trace.

It would be very useful if something was possible in the likes of:

(this is just an abstract example)

% Let's imagine this is a (very poorly) constrained sudoku board
?- problem(Sudoku),constraint(Sudoku),print(Sudoku).
    [[1,3,_,2,_,_,7,4,_],
     [_,2,5,_,1,_,_,_,_],
     [4,8,_,_,6,_,_,5,_],
     [_,_,_,7,8,_,2,1,_],
     [5,_,_,_,9,_,3,7,_],
     [9,_,_,_,3,_,_,_,5],
     [_,4,_,_,_,6,8,9,_],
     [_,5,3,_,_,1,4,_,_],
     [6,_,_,_,_,_,_,_,_]]

Now for the search:

?- problem(Sudoku),constraint(Sudoku),search_pause(Sudoku,BT),print(Sudoku,BT).
    [[1,3,6,2,_,_,7,4,_],
     [_,2,5,_,1,_,_,_,_],
     [4,8,_,_,6,_,_,5,_],
     [_,_,_,7,8,_,2,1,_],
     [5,_,_,_,9,_,3,7,_],
     [9,_,_,_,3,_,_,_,5],
     [_,4,_,_,_,6,8,9,_],
     [_,5,3,_,_,1,4,_,_],
     [6,_,_,_,_,_,_,_,_]]
     Board[1,3] = 6
     Backtracks = 1

   more ;

Solution

  • Using existing Visualization tools

    Have a look at the Visualization Tools Manual. You can get the kind of matrix display you want by adding a viewable_create/2 annotation to your code, and launching a Visualisation Client from TkECLiPSe's Tools-menu.

    Using your own instrumented search routine

    You can replace the indomain_xxx choice methods in search/6 with a user-defined one where you can print information before and/or after propagation.

    If that is not enough, you can replace the whole built-in search/6 with your own, which is not too difficult, see e.g. the ECLiPSe Tutorial chapter on tree search or my answer to this question.

    Tracing using data-driven facilities

    Using ECLiPSe's data-driven control facilities, you can quite easily display information when certain things happen to your variables. In the simplest case you do something on variable instantiation:

    ?- suspend(printf("X was instantiated to %w%n",[X]), 1, X->inst),
       writeln(start), X=3, writeln(end).
    
    start
    X was instantiated to 3
    end
    

    Based on this idea, you can write code that allows you to follow labeling and propagation steps even when they happen inside a black-box search routine. See the link for details.