Sistemi con Vincoli Laboratorio 1 Programma laboratorio Introduzione
Sistemi con Vincoli (Laboratorio) 1
Programma laboratorio � Introduzione � Usare la libreria Ja. Co. P � Store � Variabili e domini � Vincoli ◦ ◦ ◦ Primitivi Logici, condizionali e reificati Globali Decomposti Su insiemi � Metodi di ricerca � Debugging in Ja. Co. P � Esercitazioni Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 2
Esame EOL + orale (facoltativo) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 3
Materiale �Slide presentate a lezione �Survey http: //ktiml. mff. cuni. cz/~bartak/downloads/WD S 99. pdf �Principles of Constraint Programming, Krzysztof Apt, Cambridge University Press, 2003 ~ 66$ �Constraint processing, R. Dechter, Morgan Kaufmann, 2003. �Handbook of Constraint Programming, F. Rossi, P. Van Beek, T. Walsh, editors, Elsevier, 2006. �Constraint networks: Techniques and Algorithms, C, Lecoutre, Wiley, 2009. Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 4
Altro materiale �sulla implementazione di risolutori: articolo "Finite domain constraint programming systems" di Christian Schulte e Mats Carlsson �sul vincolo globale "all-different": articolo "The alldifferent constraint: a survey" di W. -J. van Hoeve �sulla propagazione con vincoli: articolo di Christian Bessiere che descrive in modo preciso vari algoritmi di propagazione di vincoli �sui vincoli soft: articolo sulle basi algebriche dei vincoli soft Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 5
Altri solver �Mini. Zinc �Minion �Choco (Java) �Comet �Gecode (C++) �Gecode/R (Ruby) �ECLi. PSE (Prolog) �SICStus Prolog �Tailor/Essence Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 6
Installing Ja. Co. P 3. 1 �Ja. Co. P - Java Constraint Programming solver http: //jacop. osolpro. com/ �GNU Affero GPL �API online �Manual �Dowload, http: //sourceforge. net/projects/jacopsolver/files/Ja. Co. P-3. 1/Ja. Co. P 3. 1. jar/download �How to compile and execute ◦ javac classpath. To. Jacop/Ja. Co. P. jar Main. java ◦ java Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 7
Introduction � Ja. Co. P library provides constraint programming paradigm implemented in Java. � It provides primitives to define finite domain (FD) variables, constraints and search methods. � Different domains: ◦ boolean domains, where only true/false constraints apply (SAT problem) ◦ integer domains, rational domains ◦ linear domains, where only linear functions are described analyzed (although approaches to nonlinear problems do exist) ◦ finite domains, where constraints are defined over finite sets ◦ mixed domains, involving two or more of the above Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 8
Introduction (2) �An example of the import statements that import the whole subpackages of Ja. Co. P at once is shown below. ◦ import Ja. Co. P. core. *; ◦ import Ja. Co. P. constraints. *; ◦ import Ja. Co. P. search. *; Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 9
Example public class Main { static Main m = new Main (); public static void main (String[] args) { Store store = new Store(); // define FD store int size = 4; // define finite domain variables Int. Var[] v = new Int. Var[size]; for (int i=0; i<size; i++) v[i] = new Int. Var(store, "v"+i, 1, size); // search for a solution and print results // define constraints Search<Int. Var> search = new Depth. First. Search<Int. Va store. impose( new Xneq. Y(v[0], v[1]) ); r>(); store. impose( new Xneq. Y(v[0], v[2]) ); Select. Choice. Point<Int. Var> select = store. impose( new Xneq. Y(v[1], v[2]) ); new Input. Order. Select<Int. Var>(store, v, store. impose( new Xneq. Y(v[1], v[3]) ); new Indomain. Min<Int. Var>()); store. impose( new Xneq. Y(v[2], v[3]) ); boolean result = search. labeling(store, select); if ( result ) System. out. println("Solution: " + v[0]+", "+v[1] +", "+ v[2] +", "+v[3]); else System. out. println("*** No"); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 10 }
The store �It knits together all components required to model and solve the problem using Ja. Co. P ◦ Both variables and constraints are stored in the store �The store must be created before constraints and variables ◦ Store store = new Store(); ◦ System. out. println(store. to. String()); �USED WITH CARE Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 11
Variables and Domains �How to declare ◦ Int. Var x = new Int. Var(store, "X", 1, 100); �A variable X with the domain 1. . 100 ∨ 120. . 160 ◦ x. add. Dom(120, 160); �Methods min() and max() to know the current min and max values in the domain �Boolean. Var: added to Ja. Co. P as they can be handled more efficiently than FDVs with multiple elements in their domain. ◦ Boolean. Var bv = new Boolean. Var(s, "bv"); ◦ Some constraints may require Boolean. Var as parameters �If. Then(c 1, c 2); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 12
Variables and Domains (2) �public int size. Constraints() ◦ It returns current number of constraints which are associated with variable and are not yet satisfied. �public int get. Size() ◦ It returns the size of the current domain. �public int value() ◦ This function returns current value in the domain of the variable. If current domain of variable is not singleton then warning is printed and minimal value is returned. Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 13
Variables an Domains (3) �Ja. Co. P default domain (called Interval. Domain) ◦ ordered list of intervals ◦ pair of integers denoting the minimal and the maximal value Int. Var x = new Int. Var(store, "X", 1, 100); ◦ It is not always computationally efficient. �Bound. Domain ◦ restricted to represent only one interval (min, max value) ◦ used by a finite domain variable in a same way as interval domain ◦ any attempt to remove values from inside the interval of this domain will have no effect ◦ Int. Var v = new Int. Var(s, "v", new Bound. Domain(1, Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 14
Primitive Constraints import Ja. Co. P. constraints. *; Ja. Co. P offers a set of primitive constraints that include basic arithmetic operations (+, -, *, ∕) as well as basic relations Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 15
Primitive Constraints (1) �Primitive constraints and global constraints can be imposed using impose method ◦ store. impose( new Xeq. Y(x 1, x 2)); �Alternatively, one can define first a constraint and then impose it, as shown below. ◦ Primitive. Constraint c = new Xeq. Y(x 1, x 2); c. impose(store); �These methods create additional data structures within the constraint store as Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 16
Primitive Constraints (2) �Constraint imposition does not involve checking constraint consistency. Both methods of constraint imposition does not check whether the store remains consistent. �If checking consistency is needed, the method impose. With. Consistency(constraint) should be used instead. This method throws Fail. Exception if the store is inconsistent. Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 17
Primitive Constraints (3) �Primitive constraints can be used as arguments in logical and conditional constraints ◦ E. g. X = Y ⇔ B (reified) �Int. Var x = new Int. Var(store, "X", 1, 100); Int. Var y = new Int. Var(store, "Y", 1, 100); Int. Var b = new Int. Var(store, "B", 0, 1); store. impose( new Reified( new Xeq. Y(x, y), b)); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 18
Logical, conditional and reified constraints Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 19
Logical, conditional and reified constraints (2) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 20
Logical, conditional and reified constraints (3) �Reified constraints of the form X = Y ⇔ can be defined in Ja. Co. P as follows. B ◦ Int. Var x = new Int. Var(store, "X", 1, 100); Int. Var y = new Int. Var(store, "Y", 1, 100); Int. Var b = new Int. Var(store, "B", 0, 1); store. impose( new Reified( new Xeq. Y(x, y), b ); �Decomposable constraints c 1∨c 2∨c 3 ◦ Array. List<Primitive. Constraint> c = new Array. List<Primitive. Constraint>(); c. add(c 1); c. add(c 2); c. add(c 3); store. impose( new Or(c) ); ◦ accept only primitive constraints as parameters Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 21
Global Constraints �A global constraint is a constraint that captures a relation between a non-fixed number of variables. �A global constraint is semantically redundant: the same relation as the conjunction of several simpler constraints. �To facilitate the work of the constraint solver by providing it with a better view of the structure of the problem. �A global constraint in Ja. Co. P comes with its implemented consistency technique � 30 predefined global constraints in Ja. Co. P Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 22
All. Different �Alldifferent constraints ◦ ensures that all FDVs from a given list have different values assigned ◦ pairwise different ◦ Int. Var a = new Int. Var(store, "a", 1, 3); Int. Var b = new Int. Var(store, "b", 1, 3); Int. Var c = new Int. Var(store, "c", 1, 3); Int. Var[] v = {a, b, c}; Constraint ctr = new Alldifferent(v); store. impose(ctr); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 23
All. Different (2) � 3 implementation in Ja. Co. P ◦ Alldifferent �if the domain of a finite domain variable gets assigned a value, the propagation algorithm will remove this value from the other variables ◦ Alldiff �basic pruning method and, in addition, bounds consistency ◦ Alldistinct �Alldiff method removing single inconsistent values Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 24
Sum and Sum. Weight �x 1 + x 2 +… + xn = sum ◦ Int. Var a = new Int. Var(Store, "a", 1, 3); Int. Var b = new Int. Var(Store, "b", 1, 3); Int. Var c = new Int. Var(Store, "c", 1, 3); Int. Var sum = new Int. Var(Store, "sum", 1, 8); Int. Var[] v = {a, b, c}; Constraint ctr = new Sum(v, sum); Store. impose(ctr); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 25
Sum and Sum. Weight �w 1 ⋅ x 1 + w 2 ⋅ x 2 +… + wn ⋅ xn = sum ◦ Int. Var a = new Int. Var(Store, "a", 1, 3); Int. Var b = new Int. Var(Store, "b", 1, 3); Int. Var c = new Int. Var(Store, "c", 1, 3); Int [] w = {wa, wb, wc}; Int. Var sum = new Int. Var(Store, "sum", 1, 8); Int. Var[] v = {a, b, c}; Constraint ctr = new Sum. Weight(v, w, sum); Store. impose(ctr); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 26
Knapsack �The knapsack problem or rucksack problem ◦ The problem often arises in resource allocation where there are financial constraints ◦ which item should be chosen to maximize the amount of money while still keeping the overall weight under or equal to a fixed value? Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 27
Knapsack �The knapsack problem or rucksack ◦ profits - the list of profits, each for the corresponding item no. ◦ weights - the list of weights, each for the corresponding item no. ◦ quantity - finite domain variable specifying allowed values for the vars. ◦ knapsack. Capacity - finite domain variable specifying the capacity limit of the knapsack. ◦ knapsack. Profit – specifyin the total profit �Knapsack(int[] profits, int[] weights, Int. Var[] q uantity, Int. Var knapsack. Capacity, Int. Var knapsa Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 28
Decomposed Constraints �Decomposed constraints do not define any new constraints and related pruning algorithms. ◦ They are translated into existing Ja. Co. P constraints. ◦ Imposed with method impose. Decomposition Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 29
Sequence Constraint �Sequence constraint restricts values assigned to variables from a list of variables �in such a way 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 Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 30
Sequence Constraint �Example ◦ Int. Var[] var = new Int. Var[5]; for (int i=0; i<var. length; i++) var[i] = new Int. Var(store, "v"+i, 0, 2); store. impose. Decomposition(new Sequence(var, / /variable list new Interval. Domain(1, 1), //set of v alues 3, // q, sequence length 2, // min 2 // max )); ◦ Solutions: [01101, 01121, 10110, 10112, 11011, 11211, 12110, 12112, 21101, 21121] Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 31
Stretch Constraint �Stretch constraint defines ◦ what values can be taken by variables from a list ◦ 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. Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 32
Stretch Constraint ◦ Int. Var[] var = new Int. Var[5]; for (int i=0; i<var. length; i++) var[i] = new Int. Var(store, "v"+i, 1, 2); store. impose. Decomposition( new Stretch(new int[] {1, 2}, // values new int[] {1, 2}, // min for 1 & 2 new int[] {2, 3}, // max for 1 & 2 var // variables )); ◦ solutions: [11221, 11222, 12211, 12221, 22122, 22211] Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 33
Lex Constraint �The Lex constraint enforces ascending (or descending) lexicographic order between n vectors that can be of different size. �The constraints makes it possible to enforce strict ascending lexicographic order, that is vector i must be always before vector i + 1 in the lexicographical order, or it can allow equality between consecutive vectors Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 34
Lex Constraint ◦ Int. Var[] d = new Int. Var[6]; for (int i = 0; i < d. length; i++) { [[0, 0], [1, 0], [2]], d[i] = new Int. Var(store, "d["+i+"]", 0, 2 [[0, 0], [1, 1], [2]], ); } [[0, 0], [1, 2], [2]], [[0, 1], [1, 0], [2]], [[0, 1], [1, 1], [2]], [[0, 1], [1, 2], [2]], Int. Var[][] x = { {d[0], d[1]}, {d[2]}, {d[3], d[4]}, {d[5]} }; [[0, 2], [1, 0], [2]], [[0, 2], [1, 1], [2]], [[0, 2], [1, 2], [2]] store. impose. Decomposition(new Lex(x, tr ue)); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 35
Soft-Alldifferent �It makes it possible to violate to some degree the alldifferent relation. The violations will come at a cost which is represented by cost variable. ◦ decomposition based, where violation of any inequality relation between any pair contributes one unit of cost ◦ variable based, which simply states how many times a variable takes value that is already taken by another variable. Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 36
Soft-Alldifferent �cost defined as being between 0 and 20 �Int. Var[] x = new Int. Var[5]; for (int i=0; i< x. length; i++) x[i] = new Int. Var(store, "x"+i, 1, 4); Int. Var cost = new Int. Var(store, "cost", 0, 20); store. impose. Decomposition(new Soft. Alldifferen t(x, cost, Violation. Measure. DECOMPOSITION_BA SED); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 37
Set Constraints – Variables and Domains �A Set is defined as an ordered collection of integers ◦ ◦ d = {{1}. . {1. . 3}} greatest lower bound glb(d) and least upper bound lub(d) Must be glb(d) ⊆ lub(d) �glb(d) = {1} �lub(d) = {1, 2, 3} = {{1}, {1, 2}, {1, 3}, {1, 2, 3}} Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 38
Set Constraints – Variables and Domains ◦ Set. Var s = new Set. Var(store, "s", new Bound. Set. Domain (new Interval. Domain(1, 1), new Interval. Domain(1, 3))); �Set domain can be created using Interval. Domain and Bound. Set. Domain class methods �They make it possible to form different sets by adding elements to sets. Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 39
Quiz �glb = {1}, lub = {1. . 4} ◦ {1. . 4}, {1. . 3}, {1. . 2, 4}, {1. . 2}, {1, 3. . 4}, {1, 3}, {1, 4}, {1} �glb= {2}, lub= {2. . 5} ◦ {2. . 5}, {2. . 4}, {2. . 3, 5}, {2. . 3}, {2, 4. . 5}, {2, 4}, {2, 5}, {2} Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 40
Set Constraints (1) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 41
Set Constraints (2) � Set. Var s 1 = new Set. Var(store, "s 1", new Bound. Set. Domain(new Interval. Doma in(1, 1), new Interval. Domain(1, 4))); Set. Var s 2 = new Set. Var(store, "s 2", new Bound. Set. Domain(new Interval. Doma in(2, 2), new Interval. Domain(2, 5))); Set. Var s = new Set. Var(store, "s", 1, 10); Constraint c = new Aunion. Beq. C(s 1, s 2, s); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini � Performs {{1}. . {1. . 4}} ⋃ {{2}. . {2. . 5}} = {{1}. . {1. . 10}} 42
Set Constraints (3) �performs ◦ {{1}. . {1. . 4}} ⋃ {{2}. . {2. . 5}} = {{1}. . {1. . 10}} �Quiz: some examples of solutions? ◦ s 1={1} s 2={2} s={1. . 2} or ◦ s 1={1. . 4} s 2={2. . 5} s={1. . 5} �(108 possible solutions) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 43
Search methods Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 44
Search �After specification of the model consisting of variables and constraints, a search for a solution can be started. Ja. Co. P offers a number of methods for doing this. �Consistency check ◦ boolean result = store. consistency(); ◦ If 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. Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 45
Depth First Search �A solution satisfying all constraints can be found using a depth first search 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 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 of the Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 46
Depth First Search ◦ Search<T> label = new Depth. First. Search<T>(); Select. Choice. Point<T> select = new Simple. Select<T>(var, var. Select, tie. Breaker. Var. Select indomain); � where T is type of variables we are using for this search (usually Int. Var or Set. Var) � var is a list of variables � var. Select is a comparator method for selecting variable � tie. Breaker. Var. Select is a tie breaking comparator method ◦ used when the var. Select method cannot decide ordering of two variables � indomain method is used to select a value that will be assigned to a selected variable Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 47
Value Selection for FDV Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 48
Depth First Search �For Int. Var it creates choice points xi = val and xi≠val ◦ xi is variable identified by variable selection comparators ◦ val is the value determined by indomain method �For variables of type Set. Var the choice is made between val ∈ xi or val ∉ xi. Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 49
Variable Selection for FDV Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 50
Val-Var Selection for Set. Var Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 51
Depth First Search �The standard method can be further modified to create search for all solutions � label. get. Solution. Listener(). search. All(true); label. get. Solution. Listener(). record. Solutions(true); ◦ first line informs search to find all solutions ◦ Second line informs search to record all found solutions ◦ If this flag is not set the search will only count solutions without storing them Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 52
Depth First Search – B&B �The minimization in Ja. Co. P is achieved by defining variable for cost and using branch-and-bound (B&B) search ◦ B&B search uses depth-first-search to find a solution ◦ If a solution with cost. Valuei is found a constraint cost < cost. Valuei is imposed ◦ Continue until no new solutions are found (last is optimal) � Int. Var cost; . . . boolean result = labeling(store, select, cost); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 53
Depth First Search-Restart search �Used if B&B is not best siuted for optimization ◦ finds a solution ◦ start search from the beginning but with additional constraint ◦ restricting the cost variable every iteration (as B&B) ◦ not supported directly but it can be easily implemented Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 54
Depth First Search-Restart search ◦ label. set. Solution. Listener(new Cost. Listener<Int. Va r>()); store. set. Level(store. level+1); boolean Result = true, optimal. Result = false; while (Result) { Result = labeling(store, select); store. impose(new Xgt. C(cost, Cost. Value)); optimal. Result = optimal. Result || Result; } store. remove. Level(store. level); store. set. Level(store. level-1); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 55
Depth First Search - print �To be able to print found solutions during search ◦ label. set. Solution. Listener(new Print. Out. Listener<I nt. Var>()); �The found solutions can also be printed after search is completed using the following statement ◦ label. print. All. Solutions(); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 56
Search plug-ins �search-plugin is an object �is informed about the current state of the search �may influence the behavior of the search �divided in ◦ search-plugins that change the search behavior ◦ plugins used for collecting and sharing information Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 57
Search plug-ins � Solution listener plug-in is called by search when a solution is found � Exit child listener plug-in is called every time the search exits the search subtree (it has four different methods; two methods, which are called when the search has exited the left subtree and two methods for the right subtree). � Consistency listener plug-in is called after consistency method at the current search node. � Exit listener plug-in is called each time the search is about to exit (it can used to collect relevant search information). � Time-out listener plug-in is called when the time-out occurs (if specified). � Initialize listener plug-in is called at the beginning of the search. Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 58
Search plug-ins �search plug-ins can override the status of the search by returning true or false status �Example ◦ exit child listener method left. Child can override the status of the search ◦ TRUE �the search continues and enters the right child to keep looking for a solution ◦ FALSE �instructs the search to skip exploring the right subtree Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 59
Search plug-ins �solution listener – Simple. Solution. Listener ◦ methods �print. All. Solutions() �get. Solutions() �solutions. No() �record. Solutions(boolean status) �search. All(boolean status) �execute. After. Solution(Search search, Select. Choice. Point select) �set. Children. Listeners(Solution. Listener child) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 60
Search plug-ins �time-out listener – Time. Out. Listener ◦ performs specific actions at time-out �Print information �executed. At. Time. Out (int solutions. No) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 61
Example import Ja. Co. P. core. *; import Ja. Co. P. search. *; import Ja. Co. P. constraints. *; import Ja. Co. P. set. constraints. Aunion. Beq. C; import Ja. Co. P. set. core. Bound. Set. Domain; import Ja. Co. P. set. core. Set. Var; import Ja. Co. P. set. search. Indomain. Set. Random; public class Main { public static void main(String[] args) { Store store = new Store(); Set. Var s 1 = new Set. Var(store, "s 1", new Bound. Set. Domain(new Interval. Domain(1, 1), new Interval. Domain(1, 4))); Set. Var s 2 = new Set. Var(store, "s 2", new Bound. Set. Domain(new Interval. Domain(2, 2), new Interval. Domain(2, 5))); Set. Var s = new Set. Var(store, "s", 1, 10); Constraint c = new Aunion. Beq. C(s 1, s 2, s); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 62
Example (2) Set. Var[] v= new Set. Var[3]; v[0] = s 1; v[1] = s 2; v[2] = s; Search<Set. Var> search = new Depth. First. Search<Set. Var>(); Select. Choice. Point<Set. Var> select = new Simple. Select<Set. Var>( v, new Min. Lub. Card<Set. Var>(), new Max. Glb. Card<Set. Var>(), new Indomain. Set. Min<Set. Var>()); search. set. Solution. Listener(new Simple. Solution. Listener<Set. Var>()); search. get. Solution. Listener(). search. All(true); search. get. Solution. Listener(). record. Solutions(true); boolean result = search. labeling(store, select); search. print. All. Solutions(); } } Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 63
Output Depth First Search DFS 0 [s 1 = {1}, s 2 = {2}, s = {1. . 2}]No of solutions : 64 Last Solution : [s 1={1}, s 2={2}, s={1. . 2}] Nodes : 63 Decisions : 63 Wrong Decisions : 0 Backtracks : 63 Max Depth : 6 Number of Solutions: 64 {1. . 4} {2. . 5} {1. . 4} {2. . 4} {1. . 4} {2. . 3, 5} {1. . 5} … {1} {2, 5} {1. . 2, 5} {1} {2} {1. . 2} Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 64
Limited Discrepancy Search � general tree-search algorithm ◦ used when the entire tree is too large to search exhaustively ◦ Assume that the left branch is more likely to lead to a solution than the right branch � LDS then proceeds in a series of depth-first iterations ◦ first iteration explores just the left-most path in the tree ◦ second iteration explores those root-to-leaf paths with exactly one right branch (discrepancy) ◦ … ◦ last iteration explores just the right most branch � each iteration explores those paths with exactly k discrepancies, with k ranging from zero to the depth of the tree Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 65
Limited Discrepancy Search Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 66
LDS Search � 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. ◦ Search<Int. Var> label = new Depth. First. Search<Int. Var >(); Select. Choice. Point<Int. Var> select=new Simple. Select <Int. Var (var, new Smallest. Domain<Int. Var> (), new Indomain. Middle<Int. Var>( )); LDS<Int. Var> lds = new LDS<Int. Var>(2); label. get. Exit. Child. Listener(). set. Children. Listeners(lds); boolean result = labeling(store, select); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 67
Credit Search � public Credit. Calculator(int credit, int backtracks, int max. Depth) ◦ Credits are divided equally among children ◦ As soon a node has only one credit, there is a restriction how many backtracks can be performed in search ◦ If nodes are at max. Depth then the credits are not splitted among children but sent back to the parent for use in other parts of the tree. �Can or cannot be declared � 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. Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 68
Credit Search (2) 2 1 4 credits 1 backtrack 3 depth 2 1 2 2 1 backtrack! Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 69
Credit Search (3) � Select. Choice. Point<Int. Var> select = new Simple. Select<I nt. Var>(vars, new Smallest. Domain<Int. Var>(), new Indomain. Min<Int. Var>()); int credits=4, backtracks=1, max. Depth=3; Credit. Calculator<Int. Var> credit = new Credit. Calculator< Int. Var>( credits, backtracks, max. Depth); Search<Int. Var> search = new Depth. First. Search<Int. Var >(); search. set. Consistency. Listener(credit); search. set. Exit. Child. Listener(credit); search. set. Time. Out. Listener(credit); boolean result = search. labeling(store, select); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 70
Combining search �possibility to combine several search methods into a single complex search. ◦ plug-ins �Example ◦ consecutive invocation of two search methods �Master �Slave Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 71
Combining search ◦ Search<Int. Var> slave = new Depth. First. Search<Int. Var>(); Select. Choice. Point<Int. Var> select. Slave = new Simple. Select<Int. Var>(vars 2, new Smallest. Min<Int. Var>(), new Smallest. Domain<Int. Var>(), new Indomain. Min<Int. Var>()); slave. set. Select. Choice. Point(select. Slave); Search<Int. Var> master = new Depth. First. Search<Int. Var> (); Select. Choice. Point<Int. Var> master = new Simple. Select<Int. Var>(vars 1, new Smallest. Min<Int. Var>(), new Smallest. Domain<Int. Var>(), new Indomain. Min<Int. Var>()); master. add. Child. Search(slave); boolean result = master. labeling(store, select. Master); Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 72
Debugging in Ja. Co. P �debugging facility is made available through the Boolean variables of the Switch class ◦ specially compiled Ja. Co. P library �Ja. Co. P can generate trace in a format accepted by CPviz ◦ open-source visualization toolkit for finite domain constraint programming (http: //sourceforge. net/projects/cpviz/) ◦ class Ja. Co. P. search. Trace. Generator. java ◦ Trace. Generator<Int. Var> select = new Trace. Generator<Int. Var>(search, var. Sel ect, vars); ◦ tree. xml and vis. xml Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 73
Debugging in Ja. Co. P ◦ mkdir viz. out java -cp <path to CPviz>/viz/ bin/ ie. ucc. cccc. viz. Viz config. xml tree. xml vis. xml ◦ config. xml �xml version="1. 0" encoding="UTF-8"? > <configuration version="1. 0" directory="viz. out" > <tool show="tree" fileroot="tree" repeat="all"/ > <tool show="viz" fileroot="viz"/> configuration> Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 74
Debugging in Ja. Co. P (2) �In the case of this configuration, the files will be generated in directory viz. out �java cp batik. jar: jhall. jar: <path to cpviz>/viz tool/src components. Internal. Frame �batik. jar and jhall. jar are separate software packages that must be installed separately �Once the visualization tool is started Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 75
Esercizi svolti Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 76
Esercitazioni 1. 2. 3. 4. 5. Esempio a lezione su colorazione grafo con colori diversi Simple Scheduling SEND + MORE = MONEY N-Queen Sudoku Sistemi con Vincoli (Laboratorio) - Francesco Santini 77
Esempio Graph Coloring �Primo esempio a pagina http: //jacopguide. osolpro. com/guide. Ja Co. P. html ◦ Riscrivere e compilare ◦ Una variabile in piu’ ◦ Solver per tutte le soluzioni V 4 Sistemi con Vincoli (Laboratorio) - Francesco Santini 78
Very Simple Scheduling �You need to wake up 1 hour before taking a bus to work, The bus trip takes at least 1 hour. You leave work not earlier than after 8 hours, after which it takes you more than 1 hour on a bus before being able to turn on the TV at home. You always watch TV more than 3 ours after which you go to bed. You need to sleep 6 hours at least. �Make a scheduler for you day! Sistemi con Vincoli (Laboratorio) - Francesco Santini 79
Simple Scheduling (2) �Use variables Wake. Up, Take. Bus 1, Start. Work, Take. Bu s 2, Turn. TVOn, Fall. ASleep. � Let the variables be in range 1. . 24. Sistemi con Vincoli (Laboratorio) - Francesco Santini 80
SEND + MORE = MONEY �Assign ciphers 0, . . . 9 to letters S, E, N, D, M, O, R, Y such that �Different letters have assigned different ciphers �S and M are not 0 Sistemi con Vincoli (Laboratorio) - Francesco Santini 81
SEND + MORE = MONEY (2) �Unique solution �Variables: S, E, N, D, M, O, R, Y �Domains: ◦ domain([S, M], 1, 9) ◦ domain([E, N, D, O, R, Y], 0, 9) Sistemi con Vincoli (Laboratorio) - Francesco Santini 82
SEND + MORE = MONEY (2) all_different([S, E, N, D, M, O, R, Y]) Sistemi con Vincoli (Laboratorio) - Francesco Santini 83
Some hints �Reason at a higher level w. r. t. imperative programming �Try to use already defined global constraints when possible �System. out. println("La variabile si chiama" + v[0]. id); Sistemi con Vincoli (Laboratorio) - Francesco Santini 84
N-Queen: the problem �The well-known N -queens problem is to place N queens on an N × N chess board, so that no queen can take another. Sistemi con Vincoli (Laboratorio) - Francesco Santini 85
Sudoku �Sudoku is a puzzle played on a partially filled 9 x 9 grid. The task is to complete the assignment using numbers from 1 to 9 such that the entries in each row, each column and each major 3 x 3 block are pairwise different. Sistemi con Vincoli (Laboratorio) - Francesco Santini 86
Sudoku(2) Sistemi con Vincoli (Laboratorio) - Francesco Santini 87
Sudoku(3) Sistemi con Vincoli (Laboratorio) - Francesco Santini 88
Newspaper problem � There are four students, Algy, Bertie, Charlie, and Digby, who share a flat. Four newspapers are delivered to the house: the Financial Times, the Guardian, the Daily Express, and the Sun. Each of the students reads all of the newspapers, in particular order and for a specified amount of time (see below). Given that Algy gets up at 8: 30, Bertie and Charlie at 8: 45, and Digby at 9: 30, what is the earliest that they can all set off for college? Sistemi con Vincoli (Laboratorio) - Francesco Santini 89
- Slides: 89