## A.7 clpfd.pl -- Constraint Logic Programming over Finite Domains

author
Markus Triska

Constraint programming is a declarative formalism that lets you describe conditions a solution must satisfy. This library provides CLP(FD), Constraint Logic Programming over Finite Domains. It can be used to model and solve various combinatorial problems such as planning, scheduling and allocation tasks.

Most predicates of this library are finite domain constraints, which are relations over integers. They generalise arithmetic evaluation of integer expressions in that propagation can proceed in all directions. This library also provides enumeration predicates, which let you systematically search for solutions on variables whose domains have become finite. A finite domain expression is one of:

 an integer Given value a variable Unknown value -Expr Unary minus Expr + Expr Addition Expr * Expr Multiplication Expr - Expr Subtraction min(Expr,Expr) Minimum of two expressions max(Expr,Expr) Maximum of two expressions Expr mod Expr Remainder of integer division abs(Expr) Absolute value Expr / Expr Integer division

The most important finite domain constraints are:

 Expr1 `#>=` Expr2 Expr1 is larger than or equal to Expr2 Expr1 `#=<` Expr2 Expr1 is smaller than or equal to Expr2 Expr1 `#=` Expr2 Expr1 equals Expr2 Expr1 `#\=` Expr2 Expr1 is not equal to Expr2 Expr1 `#>` Expr2 Expr1 is strictly larger than Expr2 Expr1 `#<` Expr2 Expr1 is strictly smaller than Expr2

The constraints in/2, #=/2, #\=/2, #</2, #>/2, #=</2, and #>=/2 can be reified, which means reflecting their truth values into Boolean values represented by the integers 0 and 1. Let P and Q denote reifiable constraints or Boolean variables, then:

 `#\` Q True iff Q is false P `#\/` Q True iff either P or Q P `#/\` Q True iff both P and Q P `#<==>` Q True iff P and Q are equivalent P `#==>` Q True iff P implies Q P `#<==` Q True iff Q implies P

The constraints of this table are reifiable as well. If a variable occurs at the place of a constraint that is being reified, it is implicitly constrained to the Boolean values 0 and 1. Therefore, the following queries all fail: `?-` `#\` 2., `?-` `#\` `#\` 2. etc.

As an example of a constraint satisfaction problem, consider the cryptoarithmetic puzzle SEND + MORE = MONEY, where different letters denote distinct integers between 0 and 9. It can be modeled in CLP(FD) as follows:

```:- use_module(library(clpfd)).

puzzle([S,E,N,D] + [M,O,R,E] = [M,O,N,E,Y]) :-
Vars = [S,E,N,D,M,O,R,Y],
Vars ins 0..9,
all_different(Vars),
S*1000 + E*100 + N*10 + D +
M*1000 + O*100 + R*10 + E #=
M*10000 + O*1000 + N*100 + E*10 + Y,
M #> 0, S #> 0.
```

Sample query and its result:

```?- puzzle(As+Bs=Cs).
As = [9, _G10107, _G10110, _G10113],
Bs = [1, 0, _G10128, _G10107],
Cs = [1, 0, _G10110, _G10107, _G10152],
_G10107 in 4..7,
1000*9+91*_G10107+ -90*_G10110+_G10113+ -9000*1+ -900*0+10*_G10128+ -1*_G10152#=0,
all_different([_G10107, _G10110, _G10113, _G10128, _G10152, 0, 1, 9]),
_G10110 in 5..8,
_G10113 in 2..8,
_G10128 in 2..8,
_G10152 in 2..8.
```

Here, the constraint solver could deduce more stringent bounds for many variables. Labeling can be used to search for solutions:

```?- puzzle(As+Bs=Cs), label(As).
As = [9, 5, 6, 7],
Bs = [1, 0, 8, 5],
Cs = [1, 0, 6, 5, 2] ;
fail.
```

This library also provides reflection predicates (like fd_dom/2, fd_size/2 etc.) with which you can inspect a variable's current domain. Use call_residue_vars/2 and copy_term/3 to inspect residual goals and the constraints in which a variable is involved.

It is perfectly reasonable to use CLP(FD) constraints instead of ordinary integer arithmetic with is/2. This can make programs more general. For example:

```:- use_module(library(clpfd)).

fac(0, 1).
fac(N, F) :- N #> 0, N1 #= N - 1, F #= N * F1, fac(N1, F1).
```

This predicate can be used in all directions. For example:

```?- fac(47, F).
F = 258623241511168180642964355153611979969197632389120000000000 ;
fail.

?- fac(N, 1).
N = 0 ;
N = 1 ;
fail.

?- fac(N, 3).
fail.
```

To make the predicate terminate if any argument is instantiated, add the (implied) constraint F `#\=` 0 before the recursive call. Otherwise, the query fac(N, 0) is the only non-terminating case of this kind.

This library uses goal_expansion/2 to rewrite constraints at compilation time. The expansion's aim is to transparently bring the performance of CLP(FD) constraints close to that of conventional arithmetic predicates (</2, =:=/2, is/2 etc.) when the constraints are used in modes that can also be handled by built-in arithmetic. To disable the expansion, set the flag clpfd_goal_expansion to false.

?Var in +Domain
Var is an element of Domain. Domain is one of:
Integer
Singleton set consisting only of Integer.
Lower .. Upper
All integers I such that Lower `=<` I `=<` Upper. The atoms inf and sup denote negative and positive infinity, respectively.
Domain1 `\/` Domain2
The union of Domain1 and Domain2.
+Vars ins +Domain
The variables in the list Vars are elements of Domain.
indomain(?Var)
Bind Var to all feasible values of its domain on backtracking. The domain of Var must be finite.
label(+Vars)
Equivalent to labeling([], Vars).
labeling(+Options, +Vars)
Labeling means systematically trying out values for the finite domain variables Vars until all of them are ground. The domain of each variable in Vars must be finite. Options is a list of options that let you exhibit some control over the search process. Several categories of options exist:

The variable selection strategy lets you specify which variable of Vars should be labeled next and is one of:

leftmost
Label the variables in the order they occur in Vars. This is the default.
ff
First fail. Label the leftmost variable with smallest domain next, in order to detect infeasibility early. This is often a good strategy.
ffc
Of the variables with smallest domains, the leftmost one participating in most constraints is labeled next.
min
Label the leftmost variable whose lower bound is the lowest next.
max
Label the leftmost variable whose upper bound is the highest next.

The value order is one of:

up
Try the elements of the chosen variable's domain in ascending order. This is the default.
down
Try the domain elements in descending order.

The branching strategy is one of:

step
For each variable X, a choice is made between X = V and X `#\=` V, where V is determined by the value ordering options. This is the default.
enum
For each variable X, a choice is made between X = V_1, X = V_2 etc., for all values V_i of the domain of X. The order is determined by the value ordering options.
bisect
For each variable X, a choice is made between X `#=<` M and X `#>` M, where M is the midpoint of the domain of X.

At most one option of each category can be specified, and an option must not occur repeatedly.

The order of solutions can be influenced with:

min(Expr)
max(Expr)

This generates solutions in ascending/descending order with respect to the evaluation of the arithmetic expression Expr. Labeling Vars must make Expr ground. If several such options are specified, they are interpreted from left to right, e.g.:

```?- [X,Y] ins 10..20, labeling([max(X),min(Y)],[X,Y]).
```

This generates solutions in descending order of X, and for each binding of X, solutions are generated in ascending order of Y. To obtain the incomplete behaviour that other systems exhibit with "maximize(Expr)" and "minimize(Expr)", use once/1, e.g.:

```once(labeling([max(Expr)], Vars))
```

Labeling is always complete, always terminates, and yields no redundant solutions.

all_different(+Vars)
Vars are pairwise distinct.
sum(+Vars, +Rel, +Expr)
The sum of elements of the list Vars is in relation Rel to Expr. For example:
```?- [A,B,C] ins 0..sup, sum([A,B,C], #=, 100).
A in 0..100,
A+B+C#=100,
B in 0..100,
C in 0..100.
```
?X #>= ?Y
X is greater than or equal to Y.
?X #=< ?Y
X is less than or equal to Y.
?X #= ?Y
X equals Y.
?X #\= ?Y
X is not Y.
?X #> ?Y
X is greater than Y.
?X #< ?Y
X is less than Y.
#\ +Q
The reifiable constraint Q does not hold.
?P #<==> ?Q
P and Q are equivalent.
?P #==> ?Q
P implies Q.
?P #<== ?Q
Q implies P.
?P #/\ ?Q
P and Q hold.
?P #\/ ?Q
P or Q holds.
lex_chain(+Lists)
Lists are lexicographically non-decreasing.
tuples_in(+Tuples, +Relation)
Relation must be a ground list of lists of integers. The elements of the list Tuples are constrained to be elements of Relation. Arbitrary finite relations, such as compatibility tables, can be modeled in this way. For example, if 1 is compatible with 2 and 5, and 4 is compatible with 0 and 3:
```?- tuples_in([[X,Y]], [[1,2],[1,5],[4,0],[4,3]]), X = 4.
X = 4,
Y in 0\/3.
```
all_distinct(+Ls)
Like all_different/1, with stronger propagation.
serialized(+Starts, +Durations)
Constrain a set of intervals to a non-overlapping sequence. Starts = [S_1,...,S_n], is a list of variables or integers, Durations = [D_1,...,D_n] is a list of non-negative integers. Constrains Starts and Durations to denote a set of non-overlapping tasks, i.e.: S_i + D_i `=<` S_j or S_j + D_j `=<` S_i for all 1 `=<` i < j `=<` n.