__________________________________________________________________
Version 2.4, September 30, 2009
Copyright ©2002 and 2009 Krzysztof Kuchcinski and Radosław Szymanek. All rights reserved.
JaCoP library provides constraint programming paradigm implemented in Java. It provides primitives to define finite domain (FD) variables, constraints and search methods. The user should be familiar with constraint (logic) programming (CLP) to be able to use this library. A good introduction to CLP can be found, for example, in [9].
JaCoP library provides most commonly used primitive constraints, such as equality, inequality as well as logical, reified and conditional constraints. It contains also number of global constraints. These constraints can be found in most commercial CP systems [3, 14, 4, 13]. Finally, JaCoP defines also decomposable constraints, i.e., constraints that are defined using other constraints and possibly auxiliary variables.
JaCoP library can be used by providing it as a JAR file or by specifying access to a directory containing all JaCoP classes. Currently, JaCoP uses JDOM1 library that needs to be provided for both compilation and execution. The path to this library has to be specified explicitly. An example how program Main.java, which uses JaCoP, can be compiled and executed in the Linux like environment is provided below.
or
Alternatively one can specify the class path variable.
In Java application which uses JaCoP it is required to specify import statements for all used classes from JaCoP library. An example of the import statements that import the whole subpackages of JaCoP at once is shown below.
Obviously, different Java IDE (Eclipse, NetBeans, etc.) and pure Java build tools (e.g., Ant) can be used for JaCoP based application development.
Consider the problem of graph coloring as depicted in Fig. 1.1. Below, we provide a simplistic program with hard-coded constraints and specification of the search method to solve this particular graph coloring problem.
This program produces the following output indicating that vertices v0, v1 and v3 get different colors (1, 2 and 3 respectively), while vertex v3 is assigned color number 1.
The problem is specified with the help of finite domain variables (FDVs) and constraints over these variables. Both FDVs and constraints are stored in the store (Store). The store has to be created before FDVs and constraints. Typically, it is created using the following statement.
The store has large number of responsibilities. In short, it knits together all components required to model and solve the problem using JaCoP (CP methodology). One often abused functionality is printing method. The store has redefined the method toString(), but use it with care as printing large stores can be a very slow/memory consuming process.
In the next sections we will describe how to define FDVs and constraints.
Variable X :: 1..100 is specified in JaCoP using the following general statement (assuming that we have defined store with name store). Clerly, we required to have created store before we can create variables as any constructor for variable will require providing the reference to store in which the variable is created.
One can access the actual domain of FDV using the method dom(). The minimal and maximal values in the domain can be accessed using min() and max() methods respectively. The domain can contain “holes”. This type of the domain can be obtained by adding intervals to FDV domain, as provided below:
which represents a variable X with the domain 1..100 ∨ 120..160.
FDVs can be defined without specifying their identifiers. In this case, a system will use an identifier that starts with “_” followed by a generated unique sequential number of this variable, for example “_123”. This is illustrated by the following code snippet.
FDVs can be printed using Java primitives since the method toString() is redefined for class Variable. The following code snippet will first create a variable with the domain containing values 1, 2, 14, 15, and 16.
The last line of code prints a variable, which produces the following output.
One special variable class is a BooleanVariable. They have been added to JaCoP as they can be handled more efficiently than FDVs with multiple elements in their domain. They can be used as any other variable. However, some constraints may require BooleanVariables as parameters. An example of Boolean variable definition is shown below.
In the previous section we have defined FDVs with domains without considering domain representation. JaCoP default domain is represented as an ordered list of intervals. Each interval is represented by a pair of integers denoting the minimal and the maximal value. This representation makes it possible to define all possible finite domains of integers but it is not always computationally efficient. For some problems other representations might be more computationally efficient. Therefore, JaCoP also offers domain that is restricted to represent only one interval with its minimal and maximal value. This domain is called BoundDomain and can be used by a variable in a same way as interval domain. The only difference is that any attempt to remove values from inside the interval of this domain will have no effect.
The following code creates variable v with bound domain 1..10.
In JaCoP, there are three major types of constraints:
Primitive constraints and global constraints can be imposed using impose method, while decomposable constraints are imposed using imposeDecomposition method. An example that imposes a primitive constraint XneqY is defined below. Again, in order to impose a constraint a store object must be available.
Alternatively, one can define first a constraint and then impose it, as shown below.
Both methods are equivalent.
The methods impose(constraint) and constraint.impose(store) often create additional data structures within the constraint store as well as constraint itself. Do note that constraint imposition does not involve checking if the constraint is consistent. Both methods of constraint imposition does not check whether the store remains consistent. If checking consistency is needed, the method imposeWithConsistency(constraint) should be used instead. This method throws FailException if the store is inconsistent. Note, that similar functionality can be achieved by calling the procedure store.consistency() explicitly (see section 2.4).
Constraints can have another constraints as their arguments. For example, reified constraints of the form X = Y ⇔ B can be defined in JaCoP as follows.
In a similar way disjunctive constraints can be imposed. For example, the disjunction of three constraints can be defined as follows.
or
Note, that disjunction and other similar constraints accept only primitive constraints as parameters.
After specification of the model consisting of FDVs and constraints, a search for a solution can be started. JaCoP offers a number of methods for doing this. It makes it possible to search for a single solution or to try to find a solution which minimizes/maximizes given cost function. This is achieved by using the depth-first-search together with constraint consistency enforcement.
The consistency check of all imposed constrains is achieved calling the following method from class Store.
When the procedure returns false then the store is in inconsistent state and no solution exists. The result true only indicates that inconsistency cannot be found. In other words, since the finite domain solver is not complete it does not automatically mean that the store is consistent.
To find a single solution the DepthFirstSearch method can be used. A simple use of this method is shown below.
The depth-first-search method requires the following information:
Different classes can be used to implement SelectChoicePoint interface. They are summarized in Appendix B. The following example uses SimpleSelect that selects variables using the size of their domains, i.e., variable with the smallest domain is selected first.
In some situations it is better to group FDVs and assign the values to them one after the other. JaCoP supports this by another variable selection method called SimpleMatrixSelect. An example of its use is shown below. This choice point selection heuristic works on two-dimensional lists of FDVs.
The optimization requires specification of a cost function. The cost function is defined by a FDV that, with the help of attached (imposed) constraints, gets correct cost value. A typical minimization for defined constraints and a cost FDV is specified below.
JaCoP offers number of different search heuristics based on depth-first-search. For example, credit search and limited discrepancy search. They are implemented using plug-in listeners that modify the standard depth-first-serch. For more details, see section 5.
JaCoP offers a set of primitive constraints that include basic arithmetic operations (+,-,*,∕) as well as basic relations (=,≠,<,≤,>,≥). Subtraction and division are not provided explicitly, but since constraints define relations between variables, they are defined using addition and multiplication. For detail list of primitive constraint see appendix A.1.
Primitive constraints can be used as arguments in logical and conditional constraints. Predicate constraint can be used to easily combine several primitive constraints using functional XCSP format (for more information see section 3.4.1).
Logical and conditional constraints use primitive constraints as arguments. In addition, JaCoP allows specification of the reified constraints. For detailed list of these constraints see appendix A.3
Alldifferent constraint ensures that all FDVs from a given list have different values assigned. This constraint uses a simple consistency technique that removes a value, which is assigned to a given FDV from the domains of the other FDVs.
For example, a constraint
enforces that the FDVs a, b, and c have different values.
Alldifferent constraint is provided as three different implementations. Constraint Alldifferent uses a simple implementation described above, i.e., if the domain of a finite domain variable gets assigned a value, the propagation algorithm will remove this value from the other variables. Constraint Alldiff implements this basic pruning method and, in addition, bounds consistency [10]. Finally, constraint Alldistinct implements a generalized arc consistency as proposed by Régin [11].
The example below illustrates the difference in constraints pruning power for Alldifferent and Alldiff constraints. Assume the following variables:
The constraints will produce the following results after consistency enforcement.
and
Alldistinct constraint will prune domains of variables a, b and c in the same way as Alldiff constraints but, in addition, it can remove single inconsistent values as illustrated below. Assume the following domains for a, b and c.
The constraints will produce the following results after consistency enforcement.
Circuit constraint tries to enforce that FDVs which represent a directed graph will create a Hamiltonian circuit. The graph is represented by the FDV domains in the following way. Nodes of the graph are numbered from 1 to N. Each position in the list defines a node number. Each FDV domain represents a direct successors of this node. For example, if FDV x at position 2 in the list has domain 1, 3, 4 then nodes 1, 3 and 4 are successors of node x. Finally, if the i’th FDV of the list has value j then there is an arc from i to j.
For example, the constraint
can find a Hamiltonian circuit [2, 3, 1], meaning that node 1 is connected to 2, 2 to 3 and finally, 3 to 1.
Element constraint of the form Element(I, List, V ) enforces a finite relation between I and V , V = List[I]. The vector of values, List, defines this finite relation. For example, the constraint
imposes the relation on the index variable i :: {1..3}, and the value variable v. The initial domain of v will be pruned to v :: {3,10,44} after the intial consistency execution of this Element constraint. The change of one FDV propagates to another FDV. Imposing the constraint V < 44 results in change of I :: {1,3}.
This constraint can be used, for example, to define discrete cost functions of one variable or a relation between task delay and its implementation resources. The constraint is simply implemented as a program which finds values allowed both for the first FDV and third FDV and updating them respectively.
Distance constraint computes the absolute value between two FDVs. The result is another FDV, i.e., d = |x - y|.
The example below
produces result a::1..6, b::2..4, c::0..2 since a must be pruned to have distance lower than three.
Cumulative constraint was originally introduced to specify the requirements on tasks which needed to be scheduled on a number of resources. It expresses the fact that at any time instant the total use of these resources for the tasks does not exceed a given limit. It has, in our implementation, four parameters: a list of tasks’ starts Oi, a list of tasks’ durations Di, a list of amount of resources ARi required by each task, and the upper limit of the amount of used resources Limit. All parameters can be either domain variables or integers. The constraint is specified as follows.
Formally, it enforces the following constraint:
![]() | (3.1) |
In the above formulation, min and max stand for the minimum and the maximum values in the domain of each FDV respectively. The constraints ensures that at each time point, t, between the start of the first task (task selected by min(Oi)) and the end of the last task (task selected by max(Oi + Di)) the cumulative resource use by all tasks, k, running at this time point is not greater than the available resource limit. This is shown in Fig 3.1.
Diff2 constraint takes as an argument a list of 2-dimensional rectangles and assures that for each pair i,j (i≠j) of such rectangles, there exists at least one dimension k where i is after j or j is after i, i.e., the rectangles do not overlap. The rectangle is defined by a 4-tuple [O1, O2, L1, L2], where Oi and Li are respectively called the origin and the length in i-th dimension. The diff2 constraint is specified as follows.
The Diff2 constraint can be used to express requirements for packing and placement problems as well as define constraints for scheduling and resource assignment.
This constraint uses two different propagators. The first one tries to narrow Oi and Li FDV’s of each rectangle so that rectangles do not overlap. The second one is similar to the cumulative profile propagator but it is applied in both directions (in 2-dimensional space) for all rectangles. In addition, the constraint checks whether there is enough space to place all rectangles in the limits defined by each rectangle FDV’s domains.
These constraints enforce that a given FDV is minimal or maximal of all variables present on a defined list of FDVs.
For example, a constraint
will constraint FDV min to a minimal value of variables a, b and c.
These constraints enforce that a sum of elements of FDVs’ vector is equal to a given FDV
sum, that is x1 + x2 +
+ xn = sum. The weighted sum is provided by the constraint
SumWeight and imposes the following constraint w1 ⋅x1 + w2 ⋅x2 +
+ wn ⋅xn = sum.
For example, the constraint
will constraint FDV sum to the sum of a, b and c.
There exist several implementation of these constraint distinguished by their suffixes. The base implementation with suffix VA tries to balance the usage of memory versus time efficiency. ExtensionalSupportMDD uses multi-valued decision diagram (MDD) as internal representation and algorithms proposed in [2] while ExtensionalSupportSTR uses simple tabular reduction (STR) and the method proposed in [8].
Extensional support and extensional conflict constraints define relations between n FDVs. Both constraints are defined by a vector of n FDVs and a vector of n-tuples of integer values. The n-tuples define the relation between variables defined in the first vector.
The tuples of extensional support constraint define all combinations of values that can be assigned to variables specified in the vector of FDVs. Extensional conflict, on the other hand specifies the combinations of values that are not allowed in any assignment to variables.
The example below specifies the XOR logical relation of the form a ⊕ b = c using both constraints.
Assignment constraint implements the following relation between two vectors of FDVs Xi = j ∧ Y j = i.
For example, the constraint
produces the following assignment to FDVs when x[1] = 3.
The constraint has possibility to define the minimal index for vectors of FDVs. Therefore constraint Assignment(x, y, 1) will index variables from 1 instead of default value 0.
Count constraint counts number of occurrences of value Val on the list List in FDV Var.
For example, the constraint
produces Var :: {1..2}.
If variable Var will be constrained to 1 then JaCoP will produce produces List_1 :: {0..1} .
Values constraint takes as arguments a list of variables and a counting variable. It counts a number of different values on the list of variables in the counting variable. For example, consider the following code.
Constraint Values will remove value 2 from variable x3 to assure that are only two different values (1 and 3) on the list of variables as specified by variable count.
Global cardinality constraint (GCC) is defined using two lists of variables. The first list is the value list and the second list is the counter list. The constraint counts number of occurrences of different values in the variables from the value list. The counter list is used to counter occurrences of a specific value. It can also specify the number of allowed occurrences of a specific value on the value list. Variables on the counter list are assigned to values as follows. The lowest value in the domain of all variables from the value list is counted by the first variable on the counters list. The next value (+1) is counted by the next variable and so on.
For example, the following code counts number of values -1, 0, 1 and 2 on value list x. The values are counted using counter list y using the following mapping. -1 is counted in y0, 0 is counted in y1, 1 is counted in y2 and 2 is counted in y3.
The GCC constraint will allow only the following five combinations of x variables [x0=-1, x1=0, x2=2], [x0=-1, x1=1, x2=2], [x0=-1, x1=2, x2=0], [x0=-1, x1=2, x2=1], and [x0=-1, x1=2, x2=2].
Among constraint is specified using three parameters. The first parameter is the value list, the second one is a set of values specified as IntervalDomain, and finally the third parameter, the counter, counts the number of variables from the value list that get assigned values from the set of values. The constraint assures that exactly the number of variables defined by count variable is equal to one value from the set of values.
The following example constraints that either 2 or 4 variables from value list numbers are equal either 1 or 3. There exist 2880 such assignments.
AmongVar constraint is a generalization of Among constraint. Instead of specifying a set of values it uses a list of variables as the second parameter. It counts how many variables from the value list are equal to at least one variable from list of variables (second parameter).
The example below specifies the same conditions as the Among constraint in the above example.
Regular constraint accepts only the assignment to variables that are accepted by an automaton. The automaton is specified as the first parameter of this constraint and a list of variable is the second parameter. This constraint implements a polynomial algorithm to establish GAC.
The automaton is specified by its states and transitions. There are three types of states: initial state, intermediate states, and final states. Each transition has associated domain containing all values which can trigger this transition. Values assigned to transitions must be present in the domains of assigned constraint variable. Each value may cause firing of the related transition. The automaton eventually reaches a final state after taking the last transition as specified by the value of the last variable.
Each state can be assigned a level by topologically sorting states of the automaton. The variables from the list (second parameters) are assigned to these levels. All states at the same level are assigned the same variable (see Figure 3.2). If necessary, the automaton, containing cycles, is unrolled to match a list of variables. Each transitions has assigned values that are allowed for a variable when the transition in the automaton is selected. This is specified as the interval domain.
The example below implements the automaton from Figure 3.2. This automaton defines condition for three variables to be different values 0, 1 or 2.
Knapsack constraint specifies knapsack problem. This implementation1 was inspired by the paper [7]. The major extensions of that paper are the following. The quantity variables do not have to be binary. The profit and capacity of the knapsacks do not have to be integers. In both cases, the constraint accepts any finite domain variable.
The constraint specify number of categories of items. Each item has a given weight and profit. Both weight and profit are specified as integers. The problem is to select a number of items in each category to satisfy capacity constraint, i.e. the total weight must be in the limits specified by the capacity variable. Each such solution is then characterized by by a given profit. It is defined in JaCoP as follows.
It can be formalize using the following constraints.
![]() | (3.2) (3.3) |
Geost is a geometrical constraint, which means that it applies to geometrical objects. It models placement problems under geometrical constraints, such as non overlapping constraints. Geost consistency algorithm was proposed by Beldiceanu et al [12]. The implementation of Geost in JaCoP is a result of a master thesis by Marc-Olivier Fleury.
In order to describe the constraint, we will introduce several definitions and relate them to JaCoP implementation.
Definition 1 A shifted box b is a pair (b.t[],b.l[]) of vectors of integers of length k, where k is the number of dimensions of the problem. The origin of the box relative to a given reference is b.t[], and b.l[] contains the length of the box, for each dimension.
Shifted box is defined in JaCoP using class DBox. For example, a two dimensional shifted box starting at coordinates (0,0) and having length 2 in first dimension and 1 in second direction is specified as follows.
Definition 2 A shape s is a set of shifted boxes. It has a unique identifier s.sid.
In JaCoP, we can define n shapes as collection of shifted boxes. Shape identifiers start at 0 and must be assigned consecutive integers. Therefore we have shapes with identifiers in interval 0..n-1. The following JaCoP example defines a shape with identifier 0, consisting of three sboxs, depicted in Figure 3.4.
Definition 3 An object o is a tuple (o.id,o.sid,o.x[], o.start,o.duration,o.end). o.id is a unique identifier, o.sid is a variable that stores all shapes that o can take. o.x[] is a k-dimensional vector of variables which represent the origin of o. o.start, o.duration and o.end define the interval of time in which o is present.
An object in JaCoP is defined by class GeostObject. It specifies basically all parameters of an object. An example below specifies object 0 that can take shapes 0, 1, 2 and 3. The object can be placed using coordinates (X_o1, Y_o1). The object is present during time 2 to 14.
Note that since object shapes are defined in terms of collections of shifted boxes, and since shifted boxes have a fixed size, Geost is not suited to solve problems in which object sizes can vary. Polymorphism provides some flexibility (shape variable having multiple values in their domain), but it is essentially intended to allow the modeling of objects that can take a small amount of different shapes. Typically objects that can be rotated. The duration of an object can be useful in cases where objects have variable sizes, because it is a variable, which means that some more flexibility is available. However, this feature is only available for one dimension. These restrictions are design choices made by the authors of Geost, probably because it fits well their primary field of application, which consists in packing goods in trucks. Using fixed sized shapes is also useful because it allows more deductions concerning possible placements.
When all shapes and objects are defined it is possible to specify geometrical constraints that must be fulfilled when placing these objects. Implemented geometrical constraints include in-area and non-overlapping constraints. In-area constraint enforces that objects have to lie inside a given k-dimensional sbox. Non-overlapping constraints require that no two objects can overlap.
The code below specifies two geometrical constraint, non-overlapping and in-area. They are specified by classes NonOverlapping and InArea. It must be noted that non-overlapping constraint in the code below specifies that all objects must not overlap in its two dimensions and time dimension (the time dimension is implemented as one additional dimension and therefore we specify dimensions 0, 1 and 2). In-area constraint requires that all object must be included in the sbox of dimensions 5x4.
Finally, the Geost constraint is imposed using the following code.
Decomposed constraints do not define any new constraints and related pruning algorithms. They are translated into existing JaCoP constraints. Predicate constraint is decomposed into primitive constraints while Sequence and Stretch constraints are decomposed using Regular constraint.
Decomposed constraints are imposed using imposeDecomposition method instead of ordinary impose method.
Predicate constraint is a wrapper around primitive constraints that translate an expression from XCSP format (XML CSP) into constraints available in JaCoP. It accepts only functional XCSP representation and operators specified in Table 3.1. The translation process might generate additional auxiliary variables. These variables can be fetched as a list of variables using auxiliaryVariables method defined for this constraint.
| Operation | Arity | Syntax | Semantics |
| Arithmetic (operands are integers)
| |||
| Absolute Value | 1 | abs(x) | |x| |
| Addition | 2 | add(x,y) | x + y |
| Subtraction | 2 | sub(x,y) | x - y |
| Multiplication | 2 | mul(x,y) | x * y |
| Integer Division | 2 | div(x,y) | x ÷ y |
| Remainder | 2 | mod(x,y) | x mody |
| Power | 2 | pow(x,y) | xy |
| Relational (operands are integers)
| |||
| Equal to | 2 | eq(x,y) | x = y |
| Different from | 2 | ne(x,y) | x≠y |
| Greater than or equal | 2 | ge(x,y) | x ≥ y |
| Greater than | 2 | gt(x,y) | x > y |
| Less than or equal | 2 | le(x,y) | x ≤ y |
| Less than | 2 | lt(x,y) | x < y |
| Logic (operands are Booleans)
| |||
| Logical not | 1 | not(x) | ¬x |
| Logical and | 2 | and(x,y) | x ∧ y |
| Logical or | 2 | or(x,y) | x ∨ y |
| Logical xor | 2 | xor(x,y) | x ⊕ y |
The following code defines a predicate constraints that specifies constraint z = x mody. The first parameter is a string of variables used in this constraint, the second string defines names for these variables (used in the formula). Finally, current store is defined.
The constraint is decomposed into the following primitive constraints with three auxiliary variables (_0, _1, and _2).
Sequence constraint restricts values assigned to variables from a list of variables in such a way that any sub-sequence of length q contains N values from a specified set of values. Value N is further restricted by specifying min and max allowed values. Value q, min and max must be integer.
The following code defines restrictions for a list of five variables. Each sub-sequence of size 3 must contain 2 (min = 2 and max = 2) values 1.
There exist ten following solutions: [01101, 01121, 10110, 10112, 11011, 11211, 12110, 12112, 21101, 21121]
Stretch constraint defines what values can be taken by variables from a list and how sub-sequences of these values are formed. For each possible value it specifies a minimum (min) and maximum (max) length of the sub-sequence of these values.
For example, consider a list of five variables that can be assigned values 1 or 2. Moreover we constraint that the sub-sequence of value 1 must have length 1 or 2 and the sub-sequence of value 2 must have length either 2 or 3. The following code specifies this restrictions.
This program produces six solutions: [11221, 11222, 12211, 12221, 22122, 22211]
JaCoP provides a library of set constraints in library JaCoP.set. This implementation is based on set intervals and related operations as originally presented in [5] and has been carried out as a diploma project1 . JaCoP definition of set intervals, set domains and set variables is presented in section 4.1. Available constraints are discussed in section 4.2. Search using set variables requires special methods that are introduced in section 4.3.
Set is defined as a ordered collection of integers using class JaCoP.Set and a set domain (JaCoP.SetDomain) is defined as a set interval. The set interval for SetDomain d is defined by its greatest lower bound (glb(d)) and its least upper bound (lub(d)). For example, set domain d = {{1}..{1..3}} is defined with glb(d) = {1}, set containing element 1, and lub(d) = {1..3}, set containing elements 1, 2 and 3. This set domain represent a set of sets {{1},{1..2},{1,3},{1..3}}. Each set domain to be correct must have glb(d) ⊆ lub(d). glb(d) can be considered as a set of all elements that are members of the set and lub(d) specifes the largsest possible set.
SetDomain extends abstract class Domain and therefore it can be used as a domain of a JaCoP finite domain variable. The following statement defines set variable s for the set domain discussed above.
SetDomain can specify a typical set domain, such as d = {{}..{1..3}}, in a simple way as
and an empty set domain as
Set domain can be created using Set and SetDomain class methods. They make it possible to form different sets by adding elements to sets.
JaCoP implements number of set constraints specified in appendix A.2. Constraints EInS, XeqY and XinY are primitive constraints and can be reified and used in other constraints, such conditional and logical. Other constraints are treated as ordinary JaCoP constraints.
Consider the following code that uses union constraint.
It performs operation {{1}..{1..4}}⋃ {{2}..{2..5}} = {{}..{1..10}} and produces {{1}..{1..4}}⋃ {{2}..{2..5}} = {{1..2}..{1..5}}. This represents 108 possible solutions.
Set variables will require different search organization. Basically, during search the decisions will be made whether an element belongs to set or it does not belong to this set. It is implemented as imposing either constraint EInS or the negated constraint. JaCoP still uses DepthFirsysearch but needs different SelectChoicePoint. it uses specially developed for this purpose SetSimpleSelect. Additionally, one need to specify special method for set variable selection implementing ComparatorVariable. The special methods are specified in appendix B.2. In addition, variable selection methods MostConstrainedStatic and MostConstrainedDynamic will work also.
Search requires also special method for a solution listener. In JaCoP.set.search exist a method SetSimpleSolutionListener that can be use for this purpose.
An example search can be specified as follows.
JaCoP offers methods for finding a single solution, all solutions and a solution that minimizes a given cost function. These methods are used together with methods defining FDV selection and assignment of a selected value to FDV. Both complete search methods and heuristic search methods can be defined in JaCoP.
JaCoP offers a powerful methods for search modification, called search plug-ins. Search plug-ins can be used both for collecting information about search as well as for changing search behaviour. For more information on search plug-ins see section 5.2.
A solution satisfying all constraints can be found using a depth first search algorithm. This algorithm searches for a possible solution by organizing the search space as a search tree. In every node of this tree a value is assigned to a domain variable and a decision whether the node will be extended or the search will be cut in this node is made. The search is cut if the assignment to the selected domain variable does not fulfill all constraints. Since assignment of a value to a domain variable triggers the constraint propagation and possible adjustment of the domain variable representing the cost function, the decision can easily be made to continue or to cut the search at this node of the search tree.
Typical search method for a single solution, for a list of variables, is specified as follows.
where var is a list of variables, varSelect is a comparator method for selecting variable and tieBreakerV arSelect is a tie breaking comparator method. The tie breaking method is used when the varSelect method cannot decide ordering of two variables. Finally, indomain method is used to select a value that will be assigned to a selected variable. Different variable selection and indomain methods are specified in appendix B. This search creates choice points xi = val and xi≠val where xi is variable identified by variable selection comparators and val is the value determined by indomain method.
The standard method can be further modified to create search for all solutions. This is achieved by adopting the standard solution listener as specified below.
In the first line the flag that changes search to find all solutions is set. It is set in the default solution listener. In this example, we also set a flag that informs search to record all found solutions. If this flag is not set the search will only count solutions without storing them. The values for found solutions can be printed using label.getSolutionListener().printAllSolutions() method or the following piece of code.
Even if the solutions are not recorded, they are counted and number of found solutions can be retrieved using method label.getSolutionListener().solutionsNo().
The minimization in JaCoP is achieved by defining variable for cost and using branch-and-bound (B&B) search, as specified below.
B&B search uses depth-first-search to find a solution. Each time a solution with cost costV aluei is found a constraint cost < costV aluei is imposed. Therefore the search finds solutions with lower cost until it eventually fails to find any solution that proves that the last found solution is optimal, i.e., there is no better solution.
Sometimes we want to interrupt search and report the best solution found in a given time. For this purpose, the search time-out functionality can used. For example, 10s time-out can be set with the following statement.
Moreover, one can define own time-out listener to perform specific actions.
In some situation classical B&B algorithm is not best suited for optimization and so called restart search is used. This optimization search method finds a solution and then start search from the beginning but with additional constraint restricting cost variable in the same way as B&B search. JaCoP does not support directly this kind of search but it can be easily implemented using the following code (use to maximize cost defined by variable cost).
The search iteratively calls depth-first-search until no better solution is found. It also rises the store level before search and returns to “fresh” store to make it possible to operate on it later. This code requires access to value CostV alue that can be retrieved by providing a customized version on solution listener and its method executeAfterSolution. This method simply stores the value of the cost variable when a solution is found. See the code below for details.
The search-plugin is an object, which is informed about the current state of the search and may influence the behavior of the search. They are divided into search-plugins that change the search behavior and plugins used for collecting and sharing information. Table 5.1 lists the search-plugins available in JaCoP and their membership in a respective group.
| changing search | cannot change search |
| (information sharing) | |
| solution listener | exit listener |
| exit child listener | time-out listener |
| consistency listener | initialize listener |
The search plug-ins are called during search when they reach a specific state, as specified below.
Changing search plug-ins can override the status of the search by returning true or false status. For example, exit child listener method leftChild can override the status of the search by returning true or false status. If it returns true then the search continues and enters the right child to keep looking for a solution. Returning false instructs the search to skip exploring the right subtree
JaCoP makes it possible to combine several plugins hierarchically. Each listener may have multiple children listeners attached to it, which have potential to influence the behaviour of the parent. A very simple example of using this behavior, is using one listener to remember solution and another one to print it. This two different functionalities may be provided by two different listeners. In general, if search calls several children listeners the parent listener decides how to treat the results returned by them. The listeners already implemented in JaCoP use the following default rule to combine the return codes from different listeners. They combine their own return code with the return code of a child listener using conjunction of return codes. Several child listeners combine their return codes using disjunction of return codes.
Credit search combines credit based exhaustive search at the beginning of the tree with local search in the rest of the tree [1]. In JaCoP, the credit search is controlled by three parameters: number of credits, number of backtracks during local search and maximum depth of search. In Figure 5.1 there is an example of the credit search tree. The search has initially 8 credits. The number of possible backtracks is three. During search half of the credits is distributed to the selected choice. The rest of the credits is distributed using the same principle for the next choice point. The first part of the search is based on the credits and makes it possible to investigate many possible assignments to domain variables while the other part is supposed to lead to a solution and can use a number of backtracks specified for this search. Moreover, the maximal depth of the search cannot be exceeded. Since we control the search it is possible to partially explore the whole tree and avoid situations when the search is stuck at one part of the tree which is a common problem of B&B algorithm when a depth first search strategy is used.
An example of the command which produces the search tree depicted in Fig. 5.1 is as follows.
Limited discrepancy search (LDS) uses the partial search method proposed in [6]. It basically allows only a number of different decisions along a search path, called discrepancies. If the number of discrepancies is exhausted backtracking is initiated. The number of discrepancies is specified as a parameter for LDS.
An example of LDS with one discrepancy is as follows.
JaCoP offers, through its plug-ins, possibility to combine several search methods into a single complex search. For example, the following code presents a search that is build as consecutive invocation of two search methods.
| Constraint | JaCoP specification |
| X = Const | XeqC(X, Const) |
| X = Y | XeqY(X, Y) |
| X≠Const | XneqC(X, Const) |
| X≠Y | XneqY(X, Y) |
| X > Const | XgtC(X, Const) |
| X > Y | XgtY(X, Y) |
| X ≥ Const | XgteqC(X, Const) |
| X ≥ Y | XgteqY(X, Y) |
| X < Const | XltC(X, Const) |
| X < Y | XltY(X, Y) |
| X ≤ Const | XlteqC(X, Const) |
| X ≤ Y | XlteqY(X, Y) |
| X ⋅ Const = Z | XmulCeqZ(X, Const, Z) |
| X ⋅ Y = Z | XmulYeqZ(X, Y, Z) |
| X ÷ Y = Z | XdivYeqZ(X, Y, Z) |
| X modY = Z | XmodYeqZ(X, Y, Z) |
| X + Const = Z | XplusCeqZ(X, Const, Z) |
| X + Y = Z | XplusYeqZ(X, Y, Z) |
| X + Y + Const = Z | XplusYplusCeqZ(X, Y, Const, Z) |
| X + Y + Q = Z | XplusYplusQeqZ(X, Y, Q, Z) |
| X + Const ≤ Z | XplusClteqZ(X, Const, Z) |
| X + Y ≤ Z | XplusYlteqZ(X, Y, Z) |
| X + Y > Const | XplusYgtC(X, Y, Const) |
| X + Y + Q > Const | XplusYplusQgtC(X, Y, Q, Const) |
| XY = Z | XexpYeqZ(X, Y, Z) |
| Constraint | JaCoP specification |
e S | EInS(e, S) |
| S1 = S2 | JaCoP.set.constraints.XeqY(S1, S2) |
| S1 ⊆ S2 | XinY(S1, S2) |
| S1 ⋃ S2 = S3 | XunionYeqZ(S1, S2, S3) |
| S1 ⋂ S2 = S3 | XintersectYeqZ(S1, S2, S3) |
| S1 \ S2 = S3 | XdiffYeqZ(S1, S2, S3) |
| S1 <> S2 | DisjointSets(S1, S2) |
| Match | Match(Set, VarArray) |
| #S1 = X | Card(S, n) |
| Weighted sum < S, W > = X | SumWeightedSet(S, W, X) |
| Set[X] = Y | ElementSet(X, Set, Y) |
| Constraint | JaCoP specification |
| ¬c | Not(c); |
| c1 ⇔ c2 | Eq(c1, c2); |
c1 ∧ c2 ∧ ∧ cn | Constraint[] c = {c1, c2, …cn}; |
| And(c); | |
| or | |
| ArrayList |
|
| c.add(c1); c.add(c2); …c.add(cn); | |
| And(c); | |
c1 ∨ c2 ∨ ∨ cn | Constraint[] c = {c1, c2, …cn}; |
| Or(c); | |
| or | |
| ArrayList |
|
| c.add(c1); c.add(c2); …c.add(cn); | |
| Or(c); | |
| X in Dom | In(X, Dom); |
| c ⇔ B | Reified(c, B); |
| c ⇔¬B | Xor(c, B); |
| if c1 then c2 | IfThen(c1, c2); |
| if c1 then c2 else c3 | IfThenElse(c1, c2, c3); |
| Boolean operations on variables | |
| BooleanVariable[] b = {b1, b2, …, bn}; | |
| or | |
| ArrayList |
|
| b.add(b1); b.add(b2); …b.add(bn); | |
| BoolanVariable result = new BooleanVariable(store, "result"); | |
result = b1 ∧ b2 ∧ ∧ bn | AndBool(b, result) |
result = b1 ∨ b2 ∨ ∨ bn | OrBool(b, result) |
| result = b1 ⊕ b2 | XorBool(b1, b2, result) |
| result = b1 → b2 | IfThenBool(b1, b2, result) |
result = b1 == b2 == == bn | EqBool(b, result) |
+ xn = sum Variable[] x = {x1, x2, …, xn};
Variable sum = new Variable(…)
Sum(x, sum);
or
ArrayList
x.add(x1); x.add(x2); …x.add(xn);
Variable sum = new Variable(…)
Sum(x, sum);
+ wn ⋅ xn = sum Variable[] x = {x1, x2, …, xn};
Variable sum = new Variable(…)
int[] w = {w1, w2, …, wn};
SumWeight(x, w, sum);
or
ArrayList
x.add(x1); x.add(x2); …x.add(xn);
Variable sum = new Variable(…)
ArrayList
w.add(w1); w.add(w1); …w.add(wn);
SumWeight(x, w, sum);