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.
| 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).
The program in Figure 13.1 imports the cp module in order to solve the -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 :: .
- :: : This predicate restricts the domain or domains of to . can be either a single variable or a collection of variables.1 For integer-domain variables, must result in a list of integer values. For real-domain variables for the mip module, must be an interval in the form .., where and are real values.
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.
- fd_vector_min_max(, ): When the arguments are integers, this predicate resets the range of bit vectors to min(Min, -3200)..max(Max, 3200); when the arguments are variables, this predicate binds them to the current bounds of the range. The default range is -3200..3200, and it can only be expanded.
The following built-ins are provided for domain variables.
- notin : This predicate excludes values from the domain or domains of , where and are the same as in :: . This constraint cannot be applied to real-domain variables.
- fd_degree() = : This function returns the number of propagators that are attached to . This built-in is only provided by cp.
- fd_disjoint(, ): This predicate is true if ’s domain and ’s domain are disjoint.
- fd_dom() = : This function returns the domain of as a list, where is an integer-domain variable. If is an integer, then the returned list contains the integer itself.
- fd_false(, ): This predicate is true if the integer is not an element in the domain of .
- fd_max() = : This function returns the upper bound of the domain of , where is an integer-domain variable.
- fd_min() = : This function returns the lower bound of the domain of , where is an integer-domain variable.
- fd_min_max(, , ): This predicate binds to the lower bound of the domain of , and binds to the upper bound of the domain of , where is an integer-domain variable.
- fd_next(, ) = : This function returns the element following in ’s domain. It throws an exception if has no next element in ’s domain.
- fd_prev(, ) = : This function returns the element preceding in ’s domain. It throws an exception if has no previous element in ’s domain.
- fd_set_false(, ): This predicate excludes the element from the domain of . If this operation results in a hole in the domain, then the domain changes from an interval representation into a bit-vector representation, no matter how big the domain is. This built-in is only provided by cp.
- fd_size() = : This function returns the size of the domain of , where is an integer-domain variable.
- fd_true(, ): This predicate is true if the integer is an element in the domain of .
- new_dvar() = : This function creates a new domain variable with the default domain, which has the bounds -72057594037927935..72057594037927935 on 64-bit computers and -268435455..268435455 on 32-bit computers.2
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(, ), where is either a tuple of variables or a list of tuples of variables, and is a list of tuples in which each tuple takes the form , where is an integer or the don’t-care symbol . A negative constraint takes the form table_notin(, ).
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() returns the code of , and that the function chr() returns the character of .
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
where and are arithmetic expressions, and 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
- cond(,
,
):
This expression is the same as
*+(1-)*. - count(, ): The number of times occurs in , where is a nested collection of domain variables.4
- max(): The maximum of , where is a nested collection of domain variables.
- max(, ): The maximum of and .
- min(): The minimum of , where is a nested collection of domain variables.
- min(, ): The minimum of and .
- prod(): The product of , where is a nested collection of domain variables.
- sum(): The sum of , where is a nested collection of domain variables.
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:
#~
#/'
#^
#' /
#=>
#<=>
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 :: or notin ), 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.
- #~ : This constraint is 1 iff is equal to 0.
- #/' : This constraint is 1 iff both and are 1.
-
#^ :
This constraint is 1 iff exactly one of
and
is 1. - #' / : This constraint is 1 iff or is 1.
- #=> : This constraint is 1 iff implies .
- #<=> : This constraint is 1 iff and are equivalent.
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.
- acyclic(, ): This constraint ensures that the undirected graph represented by and contains no cycles, where is a list of pairs of the form and is a list of triplets of the form . A pair in , where is a ground term and is a Boolean variable, denotes that is in the graph if and only if . A triplet denotes that is connected with by an edge in the graph if and only if and both and are in the graph. Note that the graph to be constructed is assumed to be undirected. If there exists a triplet in , then the triplet will be added to if it is not specified.
- acyclic_d(, ): This constraint ensures that the directed graph represented by and contains no cycles, where and are the same as those in acyclic(, ), except that the graph is directed.
- all_different(): This constraint ensures that each pair of variables in the list or array is different. This constraint is compiled into a set of inequality constraints. For each pair of variables and in , all_different() generates the constraint #!= .
- all_different_except_0(): This constraint is true if all non-zero values in are different.
- all_distinct(): This constraint is the same as all_different, but for the cp module it maintains a higher level of consistency. For some problems, this constraint is faster and requires fewer backtracks than all_different, and, for some other problems, this constraint is slower due to the overhead of consistency checking.
-
assignment(, ): This constraint ensures that is a dual assignment of , i.e., if the th element of is , then the th element of is . The constraint can be defined as:
assignment(Xs, Ys) => N = Xs.length, (var(Ys) -> Ys = new_list(N); true), Xs :: 1..N, Ys :: 1..N, foreach (I in 1..N, J in 1..N) Xs[I] #= J #<=> Ys[J] #= I end. - at_least(, , ): This constraint succeeds if there are at least elements in that are equal to , where and must be integer-domain variables, and must be a list of integer-domain variables.
- at_most(, , ): This constraint succeeds if there are at most elements in that are equal to , where and must be integer-domain variables, and must be a list of integer-domain variables.
-
circuit(): Let be a list of variables [], where each has the domain . A valuation , , , satisfies the constraint if 1 -> , 2 -> , ..., n -> forms a Hamiltonian cycle. This constraint ensures that each variable has a different value, and that the graph that is formed by the assignment does not contain any sub-cycles. For example, for the constraint
circuit([X1,X2,X3,X4])[3,4,2,1] is a solution, but [2,1,4,3] is not, because the graph 1 -> 2, 2 -> 1, 3 -> 4, 4 -> 3 contains two sub-cycles.
-
count(, , , ): In this constraint, and are integer-domain variables, is a list of integer-domain variables, and is an arithmetic constraint operator (#=, #!=, #>, #>=, #<, #=<, or #<=). Let be the number of elements in that are equal to . The constraint is true iff is true. This constraint can be defined as follows:
count(V, L, Rel, N) => sum([V #= E : E in L]) #= Count, call(Rel, Count, N). - count(, , ): This constraint is the same as count(, , #=, ).
- cumulative(, , , ): This constraint is useful for describing and solving scheduling problems. The arguments , , and are lists of integer-domain variables of the same length, and is an integer-domain variable. Let be [, , , ], be [, , , ], and be [, , , ]. For each job , represents the start time, represents the duration, and represents the units of resources needed. is the limit on the units of resources available at any time. This constraint ensures that the limit cannot be exceeded at any time.
- decreasing(): The sequence (an array or a list) is in (non-strictly) decreasing order.
- decreasing_strict(): The sequence (an array or a list) is in strictly decreasing order.
- diffn(): This constraint ensures that no two rectangles in overlap with each other. A rectangle in an -dimensional space is represented by a list of elements [, , , , , , , ], where is the starting coordinate of the edge in the th dimension, and is the size of the edge.
- disjunctive_tasks() (cp only): is a list of terms. Each term has the form disj_tasks(, , , ), where and are two integer-domain variables, and and are two positive integers. This constraint is equivalent to posting the disjunctive constraint + #=< #' / + #=< for each term in ; however, the constraint may be more efficient, because it converts the disjunctive tasks into global constraints.
- element(, , ): This constraint is true if the element at index in is , where and are integer-domain variables, and is a list of integer-domain variables.
- element0(, , ): This constraint is the same as element(, , ), except that 0-based, rather than 1-based, indexing is used.
- exactly(, , ): This constraint succeeds if there are exactly elements in that are equal to , where and must be integer-domain variables, and must be a list of integer-domain variables.
-
global_cardinality(, ): Let be a list of integer-domain variables [, , ], and be a list of pairs [-, , -], where each key is a unique integer, and each is an integer-domain variable. The constraint is true if every element of is equal to some key, and, for each pair -, exactly elements of are equal to . This constraint can be defined as follows:
global_cardinality(List, Pairs) => Keys = [Key : $(Key-_) in Pairs], List :: Keys, foreach ($Key-V in Pairs) sum([B : E in List, B#<=>(E#=Key)]) #= V end. -
hcp(, ): This constraint ensures that the directed graph represented by and forms a Hamiltonian cycle, where is a list of pairs of the form , and is a list of triplets of the form . A pair in , where is a ground term and is a Boolean variable, denotes that is in the graph if and only if . A triplet denotes that is connected to by an edge in the graph if and only if . The circuit and subcircuit constraints can be implemented as follows by using hcp:
circuit(L) => N = len(L), L :: 1..N, Vs = [{I,1} : I in 1..N], Es = [{I,J,B} : I in 1..N, J in fd_dom(L[I]), J !== I, B #<=> L[I] #= J], hcp(Vs, Es). subcircuit(L) => N = len(L), L :: 1..N, Vs = [{I,B} : I in 1..N, B #<=> L[I] #!= I], Es = [{I,J,B} : I in 1..N, J in fd_dom(L[I]), J !== I, B #<=> L[I] #= J], hcp(Vs, Es). - hcp(, , ): This constraint is the same as hcp(, ), except that it also constrains the number of vertices in the graph to be .
-
hcp_grid(): This constraint ensures that the grid graph represented by , which is a two-dimensional array of Boolean (0/1) variables, forms a Hamiltonian cycle. In a grid graph, each cell is directly connected horizontally and vertically, but not diagonally, to its neighbors. Only cells labeled 1 are considered as vertices of the graph. This constraint is implemented as follows by using hcp:
hcp_grid(A) => NRows = len(A), NCols = len(A[1]), Vs = [{(R,C), A[R,C]} : R in 1..NRows, C in 1..NCols], Es = [{(R,C), (R1,C1), _} : R in 1..NRows, C in 1..NCols, (R1,C1) in neibs(A,NRows,NCols,R,C)], hcp(Vs, Es). neibs(A, NRows, NCols, R, C) = [(R1,C1) : (R1,C1) in [(R-1,C), (R+1,C), (R,C-1), (R,C+1)], R1 >= 1, R1 =< NRows, C1 >= 1, C1 =< NCols, A[R1,C1] !== 0]. - hcp_grid(, ): This constraint is the same as hcp_grid(), except that it also restricts the edges to , which consists of triplets of the form . In a triplet in , and take the form , where is a row number and is a column number, and is a Boolean variable, which denotes that is connected to by an edge in the graph if and only if . If is a variable, then it is bound to the edges of the grid graph.
- hcp_grid(, , ): This constraint is the same as hcp_grid(, ), except that it also constrains the number of vertices in the graph to be .
- increasing(): The sequence (an array or a list) is in (non-strictly) increasing order.
- increasing_strict(): The sequence (an array or a list) is in strictly increasing order.
- lex_le(, ): The sequence (an array or a list) is lexicographically less than or equal to .
- lex_lt(, ): The sequence (an array or a list) is lexicographically less than .
- matrix_element(, , , ): This constraint is true if the entry at , in is , where , , and are integer-domain variables, and is a two-dimensional array of integer-domain variables.
- matrix_element0(, , , ): This constraint is the same as the above, except that it uses 0-based, rather than 1-based, indexing for the entries of the matrix.
- neqs() (cp only): is a list of inequality constraints of the form #!= , where and are integer-domain variables. This constraint is equivalent to the conjunction of the inequality constraints in , but it extracts all_distinct constraints from the inequality constraints.
- nvalue(, ): The number of distinct values in is , where is a list of integer-domain variables.
- path(, , , ): This constraint ensures that the undirected graph represented by and is a path from to , where is a list of pairs of the form , is a list of triplets of the form , is a vertex, and is a vertex or a list of vertices. A pair in , where is a ground term representing a vertex and is a Boolean variable, denotes that is in the graph if and only if . A triplet denotes that is connected with by an edge in the graph if and only if and both and are in the graph. Note that the graph to be constructed is assumed to be undirected. If there exists a triplet in , then the triplet will be added to if it is not specified.
- path_d(, , , ): This constraint ensures that the directed graph represented by and is a path from to , where and are the same as those in path(, , , ), except that the graph is directed.
- regular(, , , , , ): Given a finite automaton (DFA or NFA) of states numbered 1, 2, , with input , transition matrix , initial state (1 ), and a list of accepting states , this constraint is true if the list is accepted by the automaton. The transition matrix represents a mapping from to , where denotes the error state. For a DFA, every entry in is an integer representing a state, and for an NFA, each entry can be a list of integers representing possible next states.
- scalar_product(, , ): The scalar product of and is , where and are lists or arrays of integer-domain variables, and is an integer-domain variable. and must have the same length.
- scalar_product(, , , ): The scalar product of and has the relation with , where is one of the following operators: #=, #!=, #>=, #>, #=< (#<=), and #<.
- scc(, ): This constraint ensures that the undirected graph represented by and is connected, where is a list of pairs of the form , and is a list of triplets of the form . A pair in , where is a ground term and is a Boolean variable, denotes that is in the graph if and only if . A triplet denotes that is connected with by an edge in the graph if and only if and both and are in the graph. Note that the graph to be constructed is assumed to be undirected. If there exists a triplet in , then the triplet will be added to if it is not specified.
- scc(, , ): This constraint is the same as scc(, ), except that it also constrains the number of vertices in the graph to be .
- scc_d(, ): This constraint ensures that the directed graph represented by and is strongly connected, where and are the same as those in scc(, ), except that the graph is directed.
- scc_d(, , ): This constraint is the same as scc_d(, ), except that it also constrains the number of vertices in the graph to be .
-
scc_grid(): This constraint ensures that the grid graph represented by , which is a two-dimensional array of Boolean variables, forms a connected undirected graph. In a grid graph, each cell is directly connected horizontally and vertically, but not diagonally, to its neighbors. Only cells labeled 1 are considered as vertices of the graph. This constraint is implemented as follows by using scc:
scc_grid(A) => NRows = len(A), NCols = len(A[1]), Vs = [{(R,C), A[R,C]} : R in 1..NRows, C in 1..NCols], Es = [{(R,C), (R1,C1), _} : R in 1..NRows, C in 1..NCols, (R1,C1) in neibs(A,NRows,NCols,R,C), (R,C) @< (R1,C1)], scc(Vs, Es). neibs(A, NRows, NCols, R, C) = [(R1,C1) : (R1,C1) in [(R-1,C), (R+1,C), (R,C-1), (R,C+1)], R1 >= 1, R1 =< NRows, C1 >= 1, C1 =< NCols, A[R1,C1] !== 0].Note that there is an edge between each pair of neighboring cells in the resulting graph as long as the cells are in the graph.
- scc_grid(, ): This constraint is the same as scc_grid(), except that it also constrains the number of vertices in the graph to be .
- serialized(, ): This constraint describes a set of non-overlapping tasks, where and are lists of integer-domain variables, and the lists have the same length. Let be a list of 1s that has the same length as . This constraint is equivalent to cumulative(, , , 1).
- subcircuit(): This constraint is the same as circuit(), except that not all of the vertices are required to be in the circuit. If the th element of is , then the vertex is not part of the circuit.
- subcircuit_grid(): This constraint ensures that the grid graph represented by , which is a two-dimensional array of Boolean (0/1) variables, forms a Hamiltonian cycle. In a grid graph, each cell is directly connected horizontally and vertically, but not diagonally, to its neighbors. Only non-zero cells are considered as vertices of the graph.
- subcircuit_grid(, ): This constraint is the same as subcircuit_grid(), except that it also constrains the number of vertices in the graph to be .
- tree(, ): This constraint ensures that the undirected graph represented by and is a tree, where is a list of pairs of the form , and is a list of triplets of the form . A pair in , where is a ground term and is a Boolean variable, denotes that is in the tree if and only if . A triplet denotes that is connected with by an edge in the tree if and only if and both and are in the tree. Note that the graph to be constructed is assumed to be undirected. If there exists a triplet in , then the triplet will be added to if it is not specified.
- tree(, , ): This constraint is the same as tree(, ), except that it also constrains the number of vertices in the tree to be .
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 be a bit vector of length . The bit corresponds to the least significant bit, while 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 , Picat converts it to . If the argument is a non-negative integer, Picat automatically converts it to its binary representation.
- bv_add(, , ): Forces bit-vector to be the sum of bit-vectors and .
- bv_and(, , ): Forces bit-vector to be the bitwise and of bit-vectors and .
- bv_div(, , ): Forces bit-vector to be the quotient of divided by ().
- bv_drop(, ) = : Returns a bit vector containing the remaining bits of bit-vector after dropping the lowest bits.
- bv_eq(, ): Forces equality between bit-vector and bit-vector .
- bv_ge(, ): Forces bit-vector to be greater than or equal to bit-vector ().
- bv_gt(, ): Forces bit-vector to be greater than bit-vector ().
- bv_le(, ): Forces bit-vector to be greater than or equal to bit-vector (). This is the same as bv_ge(, ).
- bv_lt(, ): Forces bit-vector to be greater than bit-vector (). This is the same as bv_gt(, ).
- bv_mod(, , ): Forces bit-vector to be the remainder of divided by ().
- bv_mul(, , ): Forces bit-vector to be the product of multiplying and .
- bv_neq(, ): Forces inequality between bit-vector and bit-vector ().
- bv_or(, , ): Forces bit-vector to be the bitwise or of bit-vectors and .
- bv_pow(, , ): Forces bit-vector to be raised to the power of ().
- bv_sum(, ): Constrains the sum of the terms in the list to equal the bit vector . Each term in is either a bit vector or a pair (, ) representing , where is a non-negative integer and is an integer, a binary variable, or a bit vector.
- bv_take(, ) = : Returns a bit vector containing the lowest bits of bit-vector .
- bv_to_int() = : Returns an integer represented by bit-vector . This function throws an exception if is not ground.
- bv_xor(, , ): Forces bit-vector to be the bitwise xor of bit-vectors and .
- int_to_bv() = : Returns the binary representation of integer as a bit vector.
- new_bv() = : Returns a bit vector of length .
13.7 Solver Invocation
- solve(, ): This predicate calls the imported solver to label the variables with values, where is a list of options for the solver. The options will be detailed below. This predicate can backtrack in order to find multiple solutions. The cp module allows incremental labeling of variables, and some variables that occur in constraints but are not passed to solve may remain uninstantiated after a call to solve. The user is responsible for having all the variables that need to be instantiated passed to solve. In contrast, the sat, mip, and smt modules do not support incremental labeling of variables.
- solve(): This predicate is the same as solve([], ).
- indomain(): This predicate is only accepted by cp. It is the same as solve([], []).
- indomain_down():
This predicate is only accepted by cp. It is the same as
solve([down], []). - solve_all(, ) = : This function returns all the solutions that satisfy the constraints.
- solve_all() = : This function is the same as solve_all([], ).
- solve_suspended(): After solve() has successfully labeled , some constraints may remain suspended and not completely checked because not all of the decision variables are included in . The solve_suspended() predicate labels all remaining variables in the suspended constraints. This predicate is only provided by the cp module.
- solve_suspended: This predicate is the same as solve_suspended([]).
13.7.1 Common Solving Options
The following options are shared by the solvers, subject to the restrictions noted below.5
- $limit(): Search for up to solutions.
- $max(): Maximize the variable .
- $min(): Minimize the variable .
- $report(): Execute each time a better answer is found while searching for an optimal answer. This option cannot be used if the mip module is used.
13.7.2 Solving Options for cp
The cp module also accepts the following options:
- backward: The list of variables is reversed first.
- constr: Variables are first ordered by the number of attached constraints.
- degree: Variables are first ordered by degree, i.e., the number of connected variables.
- down: Values are assigned to variables from the largest to the smallest.
- ff: The first-fail principle is used: the leftmost variable with the smallest domain is selected.
- ffc: The same as with the two options: ff and constr.
- ffd: The same as with the two options: ff and degree.
- forward: Choose variables in the given order, from left to right.
- inout: The variables are reordered in an inside-out fashion. For example, the variable list [X1,X2,X3,X4,X5] is rearranged into the list [X3,X2,X4,X1,X5].
- $label(): This option informs the CP solver that once a variable is selected, the user-defined call () is used to label , where must be defined in the same module, an imported module, or the global module.
- leftmost: The same as forward.
- max: First, select a variable whose domain has the largest upper bound, breaking ties by selecting a variable with the smallest domain.
- min: First, select a variable whose domain has the smallest lower bound, breaking ties by selecting a variable with the smallest domain.
- rand: Both variables and values are randomly selected when labeling.
- rand_var: Variables are randomly selected when labeling.
- rand_val: Values are randomly selected when labeling.
- reverse_split: Bisect the variable’s domain, excluding the lower half first.
- split: Bisect the variable’s domain, excluding the upper half first.
- updown: Values are assigned to variables from the values that are nearest to the middle of the domain.
13.7.3 Solving Options for sat
- dump: Dump the CNF code to stdout.
- $dump(): Dump the CNF code to .
- $ext(): Save the CNF code to a temporary file, then solve it using the external solver specified by the OS command . For example, ext("cadical -quiet").
- seq: Use sequential search to find an optimal answer.
- split: Use binary search to find an optimal answer (default).
- $nvars: The number of variables in the CNF code is .
- $ncls: The number of clauses in the CNF code is .
13.7.4 Solving Options for mip
-
cbc: Instruct Picat to use the Cbc MIP solver. Picat uses the following command to call the Cbc solver:
cbc -solve -solution
where is a file for the solution, and is a file that stores the CPLEX-format constraints. Picat throws existence_error if the command cbc is not available.
- dump: Dump the constraints in CPLEX format to stdout.
- $dump(): Dump the CPLEX format to .
-
glpk: Instruct Picat to use the GLPK MIP solver. Picat uses the following command to call the GLPK solver:
glpsol -lp -o
where is a solution file, and is a file that stores the CPLEX-format constraints. Picat throws existence_error if the command glpsol is not available.
-
gurobi: Instruct Picat to use the Gurobi MIP solver. Picat uses the following command to call the Gurobi solver:
gurobi_cl ResultFile=
where is a file for the solution, and is a file that stores the CPLEX-format constraints. Picat throws existence_error if the command gurobi_cl is not available.
-
scip: Instruct Picat to use the SCIP MIP solver. Picat uses the following command to call the SCIP solver:
scip -q -c ’read ’ -c optimize
-c ’write solution ’ -c quitwhere is a file for the solution, and is a file that stores the CPLEX-format constraints. Picat throws existence_error if the command scip is not available.
13.7.5 Solving Options for smt
-
cvc4: Instruct Picat to use the CVC4 SMT solver. Picat uses the following command to call the CVC4 solver:
cvc4
where is a file that stores the SMT-LIB2-format constraints, and is a solution file. Picat throws existence_error if the command cvc4 is not available in the path.
- dump: Dump the constraints in SMT-LIB2 format to stdout.
- $dump(): Dump the SMT-LIB2 format to .
- $logic(): Instruct the SMT solver to use when solving, where must be an atom or a string, and the specified logic must be available in the SMT solver. The default logic for z3 is “LIA”, and the default logic for CVC4 is “NIA”.
- $tmp(): Dump the SMT-LIB2 format to rather than the default file “__tmp<pid>.smt2”, before calling the smt solver. The name must be a string or an atom that has the extension name “.smt2”. When this file name is specified, the smt solver will save the solution into a file name that has the same main name as but the extension name “.sol”.
- z3: Instruct Picat to use the z3 SMT solver. When no SMT solver is specified, Picat first searches for the command z3, and when z3 cannot be found it continues to search for the command cvc4.
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.
- reset_store: Reset the constraint store. Memory occupied by constraints from the previous problem may not be reclaimed by garbage collection.
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.