1 / 89

Sistemi con Vincoli ( Laboratorio )

This laboratory program teaches students how to use the JaCoP library for constraint programming. It covers topics such as variables, domains, constraints, search methods, and debugging. The program includes exercises and an optional oral exam.

antoniod
Download Presentation

Sistemi con Vincoli ( Laboratorio )

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Sistemi con Vincoli (Laboratorio)

  2. Programmalaboratorio Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • Introduzione • Usare la libreria JaCoP • Store • Variabili e domini • Vincoli • Primitivi • Logici, condizionali e reificati • Globali • Decomposti • Su insiemi • Metodi di ricerca • Debugging in JaCoP • Esercitazioni

  3. Esame Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini EOL +orale (facoltativo)

  4. Materiale Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini Slide presentate a lezione Survey http://ktiml.mff.cuni.cz/~bartak/downloads/WDS99.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.

  5. Altromateriale Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini sulla implementazione di risolutori: articolo "Finite domain constraint programming systems" di Christian Schulte e MatsCarlsson 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

  6. Altri solver Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini MiniZinc Minion Choco (Java) Comet Gecode (C++) Gecode/R (Ruby) ECLiPSE (Prolog) SICStus Prolog Tailor/Essence

  7. Installing JaCoP 3.1 Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • JaCoP - Java Constraint Programming solver http://jacop.osolpro.com/ • GNU Affero GPL • API online • Manual • Dowload, http://sourceforge.net/projects/jacop-solver/files/JaCoP-3.1/JaCoP-3.1.jar/download • How to compile and execute •    javac -classpath pathToJacop/JaCoP.jar Main.java   •    java -classpath  pathToJacop/JaCoP.jar Main

  8. Introduction Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • JaCoP 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 and analyzed (although approaches to non-linear problems do exist) • finite domains, where constraints are defined over finite sets • mixed domains, involving two or more of the above

  9. Introduction (2) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • An example of the import statements that import the whole subpackages of JaCoP at once is shown below. • importJaCoP.core.*; • importJaCoP.constraints.*;   • importJaCoP.search.*;

  10. Example  // search for a solution and print results         Search<IntVar> search = new DepthFirstSearch<IntVar>(); SelectChoicePoint<IntVar> select =             new InputOrderSelect<IntVar>(store, v,                                          new IndomainMin<IntVar>()); 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 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 IntVar[] v = new IntVar[size];         for (inti=0; i<size; i++)             v[i] = new IntVar(store, "v"+i, 1, size);         // define constraints store.impose( new XneqY(v[0], v[1]) ); store.impose( new XneqY(v[0], v[2]) ); store.impose( new XneqY(v[1], v[2]) ); store.impose( new XneqY(v[1], v[3]) ); store.impose( new XneqY(v[2], v[3]) ); 

  11. The store Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • It knits together all components required to model and solve the problem using JaCoP • 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.toString()); • USED WITH CARE

  12. Variables and Domains Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • How to declare • IntVar x = new IntVar(store, "X", 1,100); • A variable X with the domain 1..100 ∨ 120..160 • x.addDom(120, 160); • Methods min() and max() to know the current min and max values in the domain • BooleanVar: added to JaCoP as they can be handled more efficiently than FDVs with multiple elements in their domain. • BooleanVarbv = new BooleanVar(s, "bv"); • Some constraints may require BooleanVaras parameters • IfThen(c1, c2);

  13. Variables and Domains (2) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • public intsizeConstraints() • It returns current number of constraints which are associated with variable and are not yet satisfied. • public intgetSize() • It returns the size of the current domain. • public intvalue() • 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.

  14. Variables an Domains (3) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • JaCoP default domain (called IntervalDomain) • ordered list of intervals • pair of integers denoting the minimal and the maximal value IntVar x = new IntVar(store, "X", 1,100); • It is not always computationally efficient. • BoundDomain • 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 • IntVar v = new IntVar(s, "v", new BoundDomain(1, 10) );

  15. Primitive Constraints import JaCoP.constraints.*; JaCoP offers a set of primitive constraints that include basic arithmetic operations (+,-,*,∕) as well as basic relations Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini

  16. Primitive Constraints (1) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • Primitive constraints and global constraints can be imposed using imposemethod • store.impose( newXeqY(x1, x2)); • Alternatively, one can define first a constraint and then impose it, as shown below. • PrimitiveConstraint c = newXeqY(x1, x2); c.impose(store); • These methods create additional data structures within the constraint store as well as constraint itself.

  17. Primitive Constraints (2) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 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 imposeWithConsistency(constraint) should be used instead. This method throws FailException if the store is inconsistent.

  18. Primitive Constraints(3) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • Primitive constraints can be used as arguments in logical and conditional constraints • E.g. X = Y ⇔ B (reified) • IntVar x = new IntVar(store, "X", 1, 100); IntVar y = new IntVar(store, "Y", 1, 100); IntVar b = new IntVar(store, "B", 0, 1); store.impose( new Reified( new XeqY(x, y), b));

  19. Logical, conditional and reified constraints Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini

  20. Logical, conditional and reified constraints (2) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini

  21. Logical, conditional and reified constraints (3) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • Reified constraints of the form X = Y ⇔ B can be defined in JaCoP as follows. • IntVar x = new IntVar(store, "X", 1, 100); IntVar y = new IntVar(store, "Y", 1, 100); IntVar b = new IntVar(store, "B", 0, 1);store.impose( new Reified( new XeqY(x, y), b); • Decomposable constraints c1∨c2∨c3 • ArrayList<PrimitiveConstraint> c = newArrayList<PrimitiveConstraint>(); c.add(c1); c.add(c2); c.add(c3); store.impose( new Or(c) ); • accept only primitive constraints as parameters

  22. Global Constraints Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 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 JaCoP comes with its implementedconsistency technique 30 predefined global constraints in JaCoP

  23. AllDifferent Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • Alldifferent constraints • ensures that all FDVs from a given list have different values assigned • pairwise different • IntVar a = new IntVar(store, "a", 1, 3); IntVar b = new IntVar(store, "b", 1, 3); IntVar c = new IntVar(store, "c", 1, 3); IntVar[] v = {a, b, c}; Constraintctr = new Alldifferent(v); store.impose(ctr);

  24. AllDifferent (2) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • 3 implementation in JaCoP • 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

  25. Sum and SumWeight Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • x1 + x2+… + xn = sum • IntVar a = new IntVar(Store, "a", 1, 3); IntVar b = new IntVar(Store, "b", 1, 3); IntVar c = new IntVar(Store, "c", 1, 3); IntVar sum = new IntVar(Store, "sum", 1, 8); IntVar[] v = {a, b, c}; Constraintctr = new Sum(v, sum); Store.impose(ctr);

  26. Sum and SumWeight Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • w1 ⋅ x1 + w2 ⋅ x2 +… + wn ⋅ xn = sum • IntVar a = new IntVar(Store, "a", 1, 3); IntVar b = new IntVar(Store, "b", 1, 3); IntVar c = new IntVar(Store, "c", 1, 3); Int[] w = {wa, wb, wc};IntVar sum = new IntVar(Store, "sum", 1, 8); IntVar[] v = {a, b, c}; Constraintctr = new SumWeight(v, w, sum); Store.impose(ctr);

  27. Knapsack Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • The knapsackproblem or rucksackproblem • The problemoftenarises in resource allocationwherethere are financialconstraints • whichitem shouldbe chosen to maximize the amount of moneywhilestillkeeping the overallweight under or equalto a fixedvalue?

  28. Knapsack Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • The knapsackproblem or rucksackproblem • 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. • knapsackCapacity- finite domain variable specifying the capacity limit of the knapsack. • knapsackProfit – specifyin the total profit • Knapsack(int[] profits, int[] weights, IntVar[] quantity, IntVarknapsackCapacity, IntVarknapsackProfit)

  29. DecomposedConstraints Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • Decomposed constraints do not define any new constraints and related pruning algorithms. • They are translated into existing JaCoP constraints. • Imposed with method imposeDecomposition

  30. Sequence Constraint Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • 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

  31. Sequence Constraint Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • Example • IntVar[] var = new IntVar[5]; for (inti=0; i<var.length; i++) var[i] = new IntVar(store, "v"+i, 0, 2); store.imposeDecomposition(new Sequence(var, //variable list                         new IntervalDomain(1,1), //set of values                         3, // q, sequence length                         2, // min                         2  // max                       )); • Solutions: [01101, 01121, 10110, 10112, 11011, 11211, 12110, 12112, 21101, 21121]

  32. Stretch Constraint Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • 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.

  33. Stretch Constraint Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • IntVar[] var = new IntVar[5]; for (inti=0; i<var.length; i++) var[i] = new IntVar(store, "v"+i, 1, 2); store.imposeDecomposition(       new Stretch(new int[] {1, 2},  // values newint[] {1, 2},  // min for 1 & 2                 new int[] {2, 3},  // max for 1 & 2 var // variables                             )); • solutions: [11221, 11222, 12211, 12221, 22122, 22211]

  34. Lex Constraint Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini 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

  35. Lex Constraint [[0, 0], [1], [1, 0], [2]], [[0, 0], [1], [1, 1], [2]], [[0, 0], [1], [1, 2], [2]], [[0, 1], [1], [1, 0], [2]], [[0, 1], [1], [1, 1], [2]], [[0, 1], [1], [1, 2], [2]], [[0, 2], [1], [1, 0], [2]], [[0, 2], [1], [1, 1], [2]], [[0, 2], [1], [1, 2], [2]] Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • IntVar[] d = new IntVar[6]; for (inti = 0; i < d.length; i++) { d[i] = new IntVar(store, "d["+i+"]", 0, 2); }IntVar[][] x = { {d[0],d[1]}, {d[2]}, {d[3],d[4]}, {d[5]} }; store.imposeDecomposition(new Lex(x, true));

  36. Soft-Alldifferent Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • 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.

  37. Soft-Alldifferent Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • costdefinedasbeingbetween 0 and 20 • IntVar[] x = new IntVar[5]; for (inti=0; i< x.length; i++)       x[i] = new IntVar(store, "x"+i, 1, 4); IntVar cost = new IntVar(store, "cost", 0, 20); store.imposeDecomposition(new SoftAlldifferent(x, cost, ViolationMeasure.DECOMPOSITION_BASED);

  38. Set Constraints– Variables and Domains Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • 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}}

  39. Set Constraints– Variables and Domains Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • SetVar s = new SetVar(store, "s", newBoundSetDomain (new IntervalDomain(1,1),  newIntervalDomain(1,3))); • Set domain can be created using IntervalDomain and BoundSetDomain class methods • They make it possible to form different sets by adding elements to sets.

  40. Quiz Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • 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}

  41. Set Constraints (1) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini

  42. Set Constraints (2) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini SetVar s1 = new SetVar(store, "s1",                 new BoundSetDomain(new IntervalDomain(1,1),   new IntervalDomain(1,4))); SetVar s2 = new SetVar(store, "s2",                 new BoundSetDomain(new IntervalDomain(2,2),  newIntervalDomain(2,5))); SetVar s = new SetVar(store, "s", 1,10); Constraint c = new AunionBeqC(s1, s2, s); Performs {{1}..{1..4}} ⋃ {{2}..{2..5}} = {{1}..{1..10}}

  43. Set Constraints (3) Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • performs • {{1}..{1..4}} ⋃ {{2}..{2..5}} = {{1}..{1..10}} • Quiz: some examples of solutions? • s1={1} s2={2} s={1..2} or • s1={1..4} s2={2..5} s={1..5} • (108 possible solutions)

  44. Searchmethods Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini

  45. Search Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • 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. • 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.

  46. Depth First Search Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini A solutionsatisfyingallconstraints can be foundusing a depth first searchalgorithm. 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 research will continue

  47. Depth First Search Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • Search<T> label = new DepthFirstSearch<T>(); SelectChoicePoint<T> select = new SimpleSelect<T>(var, varSelect, tieBreakerVarSelectindomain);  • 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 • tieBreakerVarSelectis a tie breaking comparator method • used when the varSelect method cannot decide ordering of two variables • indomain method is used to select a value that will be assigned to a selected variable

  48. Value Selection for FDV Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini

  49. Depth First Search Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini • For IntVar it creates choice points xi = val and xi≠val • xiis variable identified by variable selection comparators • valis the value determined by indomainmethod • For variables of type SetVar the choice is made between val∈ xi or val∉ xi.

  50. Variable Selection for FDV Sistemi con Vincoli (Laboratorio) – F. Santini, A. Costantini

More Related