Chapter 13

Constraints

On this page

Picat provides four solver modules, including cp, sat, smt, and mip, for modeling and solving constraint satisfaction and optimization problems (CSPs). All four of these modules implement the same set of constraints on integer-domain variables. The mip module also supports real-domain variables. In order to use a solver, users must first import the module. In order to make the symbols defined in a module available to the top level of the interpreter, users can use the built-in import to import the module. The mip module requires Gurobi (https://www.gurobi.com/), Cbc (https://github.com/coin-or/Cbc), SCIP (https://github.com/scipopt/scip), or GLPK (https://www.gnu.org/software/glpk/). The smt module requires z3 (https://github.com/Z3Prover/z3/) or CVC4 (https://cvc4.github.io/). Users can specify, as a solving option, a solver to be used if the module is mip or smt.

As the four modules have the same interface, this chapter describes the four modules together. Table 13.1 shows the constraint operators that are provided by Picat. Unless it is explicitly specified otherwise, the built-ins that are described in this chapter appear in all four modules. In the built-ins that are presented in this chapter, an integer-domain variable can also be an integer, unless it is explicitly specified to only be a variable.

Table 13.1: Constraint operators in Picat

Precedence Operators
Highest ::, notin, #=, #!=, #<, #=<, #<=, #>, #>=
#~
#/'
#^
#' /
#=>
Lowest #<=>

A constraint program normally poses a problem in three steps: (1) generate variables; (2) generate constraints over the variables; and (3) call solve to find a valuation for the variables that satisfies the constraints and possibly optimizes an objective function.

Example

    import cp.

    queens(N) =>
        Qs = new_array(N),
        Qs :: 1..N,
        foreach (I in 1..N-1, J in I+1..N)
            Qs[I] #!= Qs[J],
            abs(Qs[I]-Qs[J]) #!= J-I
        end,
        solve(Qs),
        writeln(Qs).

Figure 13.1: A program for N-queens.

The program in Figure 13.1 imports the cp module in order to solve the N-queens problem. The same program runs with the SAT solver if sat is imported, runs with the SMT solver if smt is imported, and runs with the LP/MIP solver if mip is imported. The predicate Qs :: 1..N declares the domains of the variables. The operator #!= is used for inequality constraints. In arithmetic constraints, expressions are treated as terms, and it is unnecessary to enclose them with dollar-signs. The predicate solve(Qs) calls the solver in order to solve the array of variables Qs. For cp, solve([ff], Qs), which always selects a variable that has the smallest domain (the so-called first-fail principle), can be more efficient than solve(Qs).

13.1 Domain Variables

A domain variable is an attributed variable that has a domain attribute. The Boolean domain is treated as a special integer domain where 1 denotes true and 0 denotes false. Domain variables are declared with the built-in predicate V ars :: Exp.

Domain variables, when being created, are usually represented internally by using intervals. An interval representation changes to a bit-vector representation when a hole occurs in the interval. The following built-in predicate can be used to reset the range or access the current range.

The following built-ins are provided for domain variables.

13.2 Table Constraints

A table constraint, or an extensional constraint, over a tuple of variables specifies a set of tuples that are allowed (called positive) or disallowed (called negative) for the variables. A positive constraint takes the form table_in(DV ars, R), where DV ars is either a tuple of variables {X1 , … , Xn } or a list of tuples of variables, and R is a list of tuples in which each tuple takes the form {a1,…,an}, where ai is an integer or the don’t-care symbol ∗. A negative constraint takes the form table_notin(DV ars, R).

Example

The following example solves a toy crossword puzzle. One variable is used for each cell in the grid, so each slot corresponds to a tuple of variables. Each word is represented as a tuple of integers, and each slot takes on a set of words of the same length as the slot. Recall that the function ord(Char) returns the code of Char, and that the function chr(Code) returns the character of Code.

    import cp.

    crossword(Vars) =>
        Vars = [X1,X2,X3,X4,X5,X6,X7], 
        Words2 = [{ord('I'),ord('N')},
                  {ord('I'),ord('F')},
                  {ord('A'),ord('S')},
                  {ord('G'),ord('O')},
                  {ord('T'),ord('O')}],
        Words3 = [{ord('F'),ord('U'),ord('N')},
                  {ord('T'),ord('A'),ord('D')},
                  {ord('N'),ord('A'),ord('G')},
                  {ord('S'),ord('A'),ord('G')}],
        table_in([{X1,X2},{X1,X3},{X5,X7},{X6,X7}], Words2),
        table_in([{X3,X4,X5},{X2,X4,X6}], Words3),
        solve(Vars),
        writeln([chr(Code) : Code in Vars]).

13.3 Arithmetic Constraints

An arithmetic constraint takes the form

  Exp1 Rel Exp2

where Exp1 and Exp2 are arithmetic expressions, and Rel is one of the constraint operators: #=, #!=, #<, #=<, #<=, #>, or #>=. The operators #=< and #<= are the same, meaning less than or equal to. An arithmetic expression is made from integers, variables, arithmetic functions, and constraints. The following arithmetic functions are allowed: + (addition), - (subtraction), * (multiplication), / (truncated integer division), // (truncated integer division), count, div (floored integer division), mod, ** (power), abs, min, max, and sum. Except for index notations, array comprehensions and list comprehensions, which are interpreted as function calls as in normal expressions, expressions in arithmetic constraints are treated as terms, and it is unnecessary to enclose them with dollar-signs. In addition to the numeric operators, the following functions are allowed in constraints:3

When a constraint occurs in an arithmetic expression, it is evaluated to 1 if it is satisfied and 0 if it is not satisfied.

Example

    import mip.

    go =>
        M = {{0,3,2,3,0,0,0,0},
             {0,0,0,0,0,0,5,0},
             {0,1,0,0,0,1,0,0},
             {0,0,2,0,2,0,0,0},
             {0,0,0,0,0,0,0,5},
             {0,4,0,0,2,0,0,1},
             {0,0,0,0,0,2,0,3},
             {0,0,0,0,0,0,0,0}},
        maxflow(M, 1, 8).

    maxflow(M, Source, Sink) =>
        N = M.length,
        X = new_array(N, N),
        foreach (I in 1..N, J in 1..N)
            X[I, J] :: 0..M[I, J]
        end,
        foreach (I in 1..N, I != Source, I != Sink)
            sum([X[J,I] : J in 1..N]) 
              #= sum([X[I,J] : J in 1..N]) 
        end,
        Total #= sum([X[Source,I] : I in 1..N]),
        Total #= sum([X[I,Sink] : I in 1..N]),
        solve([$max(Total)], X),
        writeln(Total),
        writeln(X).

This program uses MIP to solve the maximum integer flow problem. Given the capacity matrix M of a directed graph, the start vertex Source, and the destination vertex Sink, the predicate maxflow(M, Source, Sink) finds a maximum flow from Source to Sink over the graph. When two vertices are not connected by an arc, the capacity is given as 0. The first foreach loop specifies the domains of the variables. For each variable X[I, J], the domain is restricted to integers between 0 and the capacity, M[I, J]. If the capacity is 0, then the variable is immediately instantiated to 0. The next foreach loop posts the conservation constraints. For each vertex I, if it is neither the source nor the sink, then its total incoming flow amount

    sum([X[J,I] : J in 1..N])

is equal to the total outgoing flow amount

    sum([X[I,J] : J in 1..N]).

The total flow amount is the total outgoing amount from the source, which is the same as the total incoming amount to the sink.

13.4 Boolean Constraints

A Boolean constraint takes one of the following forms:

  #~ BoolExp
  BoolExp #/' BoolExp
  BoolExp #^ BoolExp
  BoolExp #' / BoolExp
  BoolExp #=> BoolExp
  BoolExp #<=> BoolExp

BoolExp is either a Boolean constant (0 or 1), a Boolean variable (an integer-domain variable with the domain [0,1]), an arithmetic constraint, a domain constraint (in the form of V ar :: Domain or V ar notin Domain), or a Boolean constraint. As shown in Table 13.1, the operator #~ has the highest precedence among Boolean constraint operators, and the operator #<=> has the lowest precedence. Note that the Boolean constraint operators have lower precedence than the arithmetic constraint operators. So the constraint

     X #!= 3 #/\ X#!= 5 #<=> B

is interpreted as

     ((X #!= 3) #/\ (X#!= 5)) #<=> B.

The Boolean constraint operators are defined as follows.

13.5 Global Constraints

A global constraint is a constraint over multiple variables. A global constraint can normally be translated into a set of smaller constraints, such as arithmetic and Boolean constraints. If the cp module is used, then global constraints are generally not translated into smaller constraints; rather, they are compiled into special propagators that maintain a certain level of consistency for the constraints. In Picat, constraint propagators are encoded as action rules. If the sat module is used, then global constraints are translated into smaller constraints before being translated further into conjunctive normal form. If the mip module is used, then global constraints are decomposed into equality and disequality constraints.

Picat provides the following global constraints.

13.6 Bit-Vector Constraints (sat only)

The sat module supports bit-vector constraints, which enhance modeling capabilities, improve solving performance, and support large integers that exceed the bounds of domain values. A bit vector is an array representing the binary form of an unsigned integer. Let V be a bit vector of length N. The bit V [1] corresponds to the least significant bit, while V [N] represents the most significant bit. In a bit-vector constraint, a bit-vector argument may also be a binary variable or a non-negative integer. If the argument is a binary variable B, Picat converts it to {B}. If the argument is a non-negative integer, Picat automatically converts it to its binary representation.

13.7 Solver Invocation

13.7.1 Common Solving Options

The following options are shared by the solvers, subject to the restrictions noted below.5

13.7.2 Solving Options for cp

The cp module also accepts the following options:

13.7.3 Solving Options for sat

13.7.4 Solving Options for mip

13.7.5 Solving Options for smt

13.8 Posting and Solving Multiple Constraint Problems

To describe and solve multiple constraint satisfaction problems in Picat, model each problem by creating its variables, specifying their domains, posting its constraints, and calling solve to find a satisfying assignment. This process can be repeated using either a failure-driven loop or a normal loop.

A failure-driven loop deliberately fails after processing each problem, causing backtracking to undo its variable bindings and automatically clear the constraint store before the next problem.

A normal loop, such as a foreach loop, instead requires an explicit call to reset_store between problems to clear the constraint store. Its advantage is that results can be retained across iterations, making it convenient to collect, compare, or aggregate solutions from multiple problems.

Thus, a failure-driven loop offers automatic cleanup, while a normal loop offers straightforward access to results across problems.

1A collection can be either a list or an array, where elements can be collections.

2Note that incorrect results may be caused by overflows or underflows.

3Dot notation should not be used for functions in constraint expressions, as such functions are always evaluated eagerly.

4A nested collection is recursively defined. It can be a variable, a number, a list, or an array. If it is a list or an array, then the elements can be nested collections.

5Note that the preceding dollar sign indicates that it is followed by a term, not a function call.