__________________________________________________________________
Version 3.0, September 2, 2010
Copyright ©2002 and 2010 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 [10].
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, 15, 4, 14]. 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. 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 variables (FDVs) and constraints over these variables. JaCoP support both finite domain variables (integer variables) and set variables. Both variables and constraints are stored in the store (Store). The store has to be created before variables 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 (cllaed IntervalDomain) 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 finite domain 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 variables 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. Since the search
method is used both for finite domain variables and set variables it is recommended to specify
the type of variables that are used in search. For finite domain variables, this type is usually
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.
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 [11]. Finally, constraint Alldistinct implements a generalized arc consistency as proposed by Régin [12].
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.
NOTE! The position for parameters in constraints Min and Max is changed comparing to previous versions (i.e., parameters are swapped).
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} .
NOTE! The position for parameters in constraint Count is changed comparing to previous versions.
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.
NOTE! The position for parameters in constraint Values is changed comparing to previous versions.
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] and published in [9]. 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 [13]. 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.
NetworkFlow constraint defines a minimum-cost network flow problem. An instance of this problem is defined on a directed graph by a tuple (N,A,l,u,c,b), where
A flow is a function x : A → ℤ≥0. The minimum-cost flow problem asks to find a flow that satisfies all arc capacity and node balance conditions, while minimizing total cost. It can be stated as follows:
The network is built with NetworkBuilder class using node, defined by class JaCoP.net.Node and arcs. Each node is defined by its name and node mass balance b. For example, node A with balance 0 is defined using network net as follows.
Source node producing flow of capacity 5 and sin node consuming flow of capacity 5 are defined using similar constructs but different value of node mass balance, as indicated below.
Arc of the network are defined always between two nodes. They define connection between given nodes, the lower and upper capacity values assigned to the arc (values l and u) as well as the flow cost-per-unit function on the arc (value c). This can be defined using different methods with either integers or finite domain variables. For example, an arc from source to node A with l = 0 and u = 5 and c = 3 can be defined as follows.
or
It can be noted, that cost-per-unit value can also be defined as a finite domain variable.
The constraint has also the flow cost, defined as z(x) in 3.4. It is defined as follows.
Note that the NetworkFlow only ensures that cost z(x) ≤ Zmax, where z(x) is the total cost of the flow (see equation (3.4)). In our code it is defined as varibale cost.
The constraint is finally posed using the following method.
For example, Figure 3.5 presnts the code for network flow problem depicted in Figure 3.6. The minimal flow, found by the solver, is 10 that is indicated in the figure.
Network builder has a special attribute handlerList that makes it possible to specify structural rules connected to the network. Each structural rule must implement VarHandler interface, which allows network flow constraint to cooperate with the structural rule. An important, already implemented rule, is available in the class DomainStructure. It specifies, for each structural variable sv, a list of arcs that the structural rule influence. This structural rule makes it possible to enforce minimum or maximum amount of flow on a given arc depending on the relationship between the domain of variable sv and domain d, specified within a structural rule. The domain of variable sv and domain d do not intersect if and only if the flow on a given arc is minimal as specified by initial value x.min(), denoted as xmin. Moreover, the domain of varibale sv is contained within domain d if and only if the actual flow on a given arc is maximal as specified by initial value x.max(), denoted as xmax. It is enforced by the following rules.
![]() | (3.7) |
![]() | (3.8) |
For example, creation of structural rule for arc between node source and B will enforce that this arc will have maximal flow if variable s is zero and minimal flow otherwise. The rule works also in the other direction, i.e. if the flow will be maximal variable s=0 and if the flow will be minimal this variable will be 1.
SoftAlldifferent constraint as well as SoftGCC constraint use DomainStructure rules to enforce flow from variable nodes to value nodes according the actual domain/value of variables represented by variable nodes. It is crucial functionality for the implementation of those soft global constraints.
Decomposed constraints do not define any new constraints and related pruning algorithms. They are translated into existing JaCoP constraints. Sequence and Stretch constraints are decomposed using Regular constraint.
Decomposed constraints are imposed using imposeDecomposition method instead of ordinary impose method.
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]
Soft-alldifferent makes it possible to violate to some degree the alldifferent relation. The violations will come at a cost which is represented by cost variable. This constraint is decomposed with the help of network flow constraint.
There are two violation measures supported, decomposition based, where violation of any inequality relation between any pair contributes one unit of cost to the cost metric. The other violation measure is called variable based, which simply states how many times a variable takes value that is already taken by another variable.
The code below imposes a soft-alldifferent constraint over five variables with cost defined as being between 0 and 20.
Soft-GCC constraint makes it possible to violate to some degree GCC constraint. The Soft-GCC constraint requires number of arguments. In the code example below, vars specify the list of variables, which values are being counted, and the list of integers countedValues specifies the values that are counted. Values are counted in two counters specified by a programmer. The first list of counter variables, denoted by hardCounters in our example, specifies the hard limits that can not be violated. The second list, softCounters, specifies preferred values for counters and can be violated. Each position of a variable on these lists corresponds to the position of the value being counted on list countedValues. In practice, domains of variables on list hardCounters should be larger than domains of corresponding variables on list hardCounters.
Soft-GCC accepts only value based violation metric that, for each counted value, sums up the shortage or the excess of a given value among vars. There are other constructors of Soft-GCC constraint that allows to specify hard and soft counting constraints in multitude of different ways.
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 the first version has been implemented 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, is introduced in section 4.3.
Set is defined as an ordered collection of integers using class JaCoP.core.IntervalDomain and a set domain as abstract clss JaCoP.set.core.SetDomain. Currently, there exist only one implementation of set domain as a set interval, called BoundSetDomain. The set interval for BoundSetDomain 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.
The following statement defines set variable s for the set domain discussed above.
BoundSetDomain 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 IntervalDomain and BoundSetDomain 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 AinS, AeqB and AinB 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 a set or it does not belong to this set.
JaCoP still uses DepthFirsysearch but needs different methods for set variable selection implementing ComparatorVariable and a method for value selection implementing Indomain. The special methods are specified in appendix B.2. In addition, variable selection methods MostConstrainedStatic and MostConstrainedDynamic will work also.
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 variable selection and assignment of a selected value to variable. 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 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 T is type of variables we are using for this search (usually IntVar or SetVar), 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, for varibales
of type IntVar 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. For variables of type SetVar the coice is made between val
xi or
val
xi.
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 the 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 of 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.