Home

An Introduction to Constraint (Logic) Programming Using ECLiPSe

image

Contents

1. Constraint ordered xs x S5 X2 DE Ao wexwlexed lis X X 51 In the first case ECL P S enforces variable integrality and cor rectly propagates the constraints 1 lt X lt 3and3 Y 5 thereby inferring X 2 Y 4 In the second case we have a delayed goal that is a goal that cannot be solved at the moment ECL PsS propagates inequalities and infers X 2 3 Y 3 4 How to Write a Problem Model CSP in ECI PS solve problem Variables Constraint Satisfaction with ecL PS How to Write a Problem Model CSP in EcL P s Constraint Satisfaction with ECL PS solve_problem Variables declare domains Variables setup constraints Variables This part comprises model definition How to Write a Problem Model CSP in EcL ps Constraint Satisfaction with ECL PS solve_problem Variables search Variables This is the actual search How to Write a Problem Model CSP in ECI PS solve problem Variables Constraint Satisfaction with ECL Ps declare domains Variables setup constraints Variables search Variables Modeling and search are independent phases in the resolu tion of a problem How to Write a Problem Model Stefano Benedettini solve_problem Variables declare domains Variables setup constraints Variables search Variables e Do notleave choice points during constraint setup 9 If you do the
2. pis 3 summation 0 Sulmmercsloim Ns S s Sunmmciloa i Sil S ele SI 4 ie ge 10 ie 7 MEO CHE ge 19 lt stimmeiciom Tl Z 3 4 15 Structure Notation An easy way to declare and access arguments of a Pro log structure e Declare a structure using local struct functorName fieldNames e Can refer to fields by name instead of index e Use fieldName of structName to obtain field index Declaring and using a structure local struct student name surname exam mark student name john surname doe student N SN _ N john SN doe S student name jane arg 4 S 30 S student Jaren z M M 39 O di I il Mil p 5 Scope and Motivations Solver ECL ps Extensions to Prolog Constraint Enumerations ECL PS does not support directly enumerations but they can be emulated via structures e Encode each value of your enumeration with an integer e Declare a structure whose field names are the enumer ation values Use operator of to map a value to an integer e You should never instantiate a structure of that kind e The inverse mapping is not as easy Example A color example local struct colors black white red green blue DE ge X black Gut colors gt dl ge X Sh mailce Oi cells ed oe coloes lt 5 amp useless but still Arrays 9 Arrays in ECL PS are really a synta
3. 99 Prolog as a Constraint Solver During this course a good understanding of Prolog will be assumed tures e You all followed Viroli s course so you ll probably know Prolog better than me anyway e We will use fancy stuff like custom operators and struc We won t use fancier stuff like metaprogramming e Though you re free to explore by yourselves Prolog as a Constraint Solver At this point any Prolog implementation will do But we will abandon the usual Prolog fairly soon 9 You d better start with EcL P S right away http eclipse clp org Prolog as a Constraint Solver scL Ps main site http eclipse clp org nttp eclipse clp org examples Keep your friends close but your documentation closer http eclipse clp org doc we will use that in due time Introductory book on CP using ECL PS Constraint Logic Programming Using ECL Ps Prolog as a Constraint Solver Resources for Constraint Programming in General 9 CS problems and models in various languages http www csplib org Gecode THE C library for CP not for the faint of heart Guido Tack s Ph D dissertation for a challenge e Java library http jacop osolpro com e Python library proprietary http www eveutilities com products emma Python library GPL http l abix org python constraint a e E E DNAS Prolog as a Constraint Solver Resources for Constraint Programming
4. An Introduction to Constraint Logic Programming Using ECL PS Stefano Benedettini DEIS Dipartimento di Elettronica Informatica e Sistemistica University Bologna Second Faculty of Engineering Artificial Intelligence 2010 Q Prolog as a Constraint Solver ECL PS Extensions to Prolog Syntactic Facilities 9 Iteration Constructs Modules Qo Constraint Satisfaction with EcL Ps 9 The Interval Constraints Library ic Search and Optimization with EcL P S 9 Other Constraint Libraries Scope and Motivations Constraint Logic Programming CLP ECL PS constraint solver Search methods for CLP hints Scope and Motivations Re discover Prolog as a constraint solver Prolog 9 Familiarize with ECL P 29 and its extensions to standard 9 Get a grasp of Constraint Logic Programming Learn how to model problems in ECL Ps Use constraint libraries Scope and Motivations Re discover Prolog as a constraint solver Prolog 9 Familiarize with ECL P 29 and its extensions to standard 9 Get a grasp of Constraint Logic Programming Learn how to model problems in ECL Ps Use constraint libraries 9 have fun with the solver D Scope and Motivations Laboratory lessons will follow a hands on approach During lessons you are supposed to experiment with tools and techniques e Few novel theoretical concepts will be introduced 9e In order to make the most out of th
5. Executes iteration body After each iteration checks whether Last Out and breaks if unification succeeds Otherwise unifies a fresh n variable with Out and re peats from step 2 rallo Evanu 1m g a amp eweexe cin Ih EEE b Hin Que Li co a cem 2 gt ma pear quus We mm RO ta 0 is No reverse L R a amp eweexexenm m 159 E Eome CE ial 13 cle ia s D Prolog a s a Constraint Solver ECL PS Extensions to Prolog Syntactic Facilities Iteration Constructs Modules atisfaction with The Interval Constraints Librar Search and Optimization with E Other Constraint Libr Constraint S a J v Stefano Benedettini Modules ECL PS Modules in a Nutshell Group functionally related predicates in the same place Usually one module for each file 9 Control naming access e Modules form a namespace structure 9 use lib ModuleName to compile an EC1 Ps library and import exported names 9 use use module ModuleName to compile a module and import its exported names 9 use operator to disambiguate a name ModuleName predicate Stefano Benedettini Modules ECL PS Modules in a Nutshell use directive module ModuleName at the top of a source file to define a module 9 export directive states which predicates to export Example module my little module ge ego prime matii 1L e print row Row foreachelem E Row
6. do write E write nl joie aume meves ON foreacharg Row M param M do print_row Row print_matrix is available when this module is imported but print_row is not a Constraint Solver Extensions to Prolog Syntactic Facilities Iteration Constructs Constraint Modules Satisfacti with ECL Q Constraint Satisfaction with EcL Ps The Interval Constraints Library Search and Optimization with E Other Constraint Librari Overcoming Prolog Limitations Stefano Benedettini Variables in arithmetic constraints must be instantiated Constraint predicates are mostly used for testing and cannot instantiate variables except the simplest like or and etc No constraint propagation Every goal i e constraint that is not fully instantiated is suspended and put into the constraint store Propagation is applied to variable domains at different strength Before the Cure ordered_list _ ordered Iasi xs xa se XL exeo labe IIT EI SI ge ordered _list i 2 9 4 Sil with Ect ps ge once Lush S5 amp s be integral variables works as expected we suppose x XY 2 9 6 The second goal raises an instantiation error a S DAG After the Cure Scope and Motivations Prolog as a y A Constraint pe JisUg aue s 6 Loar a Solver IUTE Solver U Extensions to ordered list lL P exeelexevel Jeep x1 se X is x eselesee lise a
7. in General Comet language http dynadec com support downloads keep an eye on this e On line guide to CP by Roman Bartak and much more 9 A blog on CP serious stuff Mapping CSPs in Prolog Stefano Benedettini Setup variables and domains State constraints 9 Specify a search strategy Logic variables and closed world assumption Predicates can be seen as very basic form of constraint Backtracking for free e Constraint propagation Efficiency Constraints and variables are not first class citizens Prolog asa Constraint Solver Constraints in Prolog Any predicate is really a constraint member X X _ member X _ T member X T p X X Kz 3 Se menberi O 4E 2 3 Sli X m Zo yields X 3 X 4 while melee EE EE EA menier a m Z3 Sil p X Y yields X Y 1 3 2 2 2 3 8 3 8 3 4 3 4 4 Prolog as a Constraint Example S How about these olver j go X X 354 X lt Da Al shy de ae Sho Do Constraints in Prolog Really Work clearly inconsistent clearly X fea DAG Do Constraints in Prolog Really Work 7 Scope and Motivations Prolog as a Constraint Solver How about these EcL ps Be X gt Sg X 2 amp Clearly inconsilstceae Extensions to Be 4 i ap So edlearsiy x sa dl Both raise an Instantiation fault error Non log
8. solver will miss an opportunity do con straint propagation You are actually splitting a CSP into multiple CSPs mak ing choices before propagation not after But it doesn t mean you can t use Prolog non determin ism Scope and Motivations Prolog as a Constraint tensions to Prolog Constraint Satisfaction with ECL Ps An Overview of the Libraries We ll mostly use only the more recent ic library and briefly touch its derivatives ic_global very useful global constraints ic_sets supports set variables ic_symbolic handles not so conveniently symbolic domains Don t use old fd libraries stick with ic Basic searching strategies and B amp B optimization Many more constraints available look them up in the documentation Bin packing e Knapsack e Scheduling 9 Generalized Propagation and Constraint Handling Rules CHR will be barely mentioned rr aaa nf nnetenint Cahar Prolog as a Constraint Solver s to Prolog Q Constraint Satisfaction with EcL Ps The Interval BITS n Le ation with Search a Other C lotivations Introduction Powerful hybrid solver that works on intervals of inte gers and reals Variable domains are unions of disjoint intervals It enforces bound consistency e Weaker than arc consistency lteratively squeezes a variable domain x y lt 0 5 N Z x lt y x 0 4 y 1 5 Cannot propagate holes Handles li
9. IterationSpecifiers do Body P e IterationSpecifiers is a comma separated sequence of G iteration specifiers Each specifier introduces an iteration variable visible only in Body Constraint Body can access only variables provided by iteration specifiers but see param Each iteration step iterations variables in Body are uni fied with iteration values 9 All iteration specifiers step in parallel and the whole loop stops when one of the specifiers completes Iteration Constructs foreach 9 foreach E List do Body executes goal Body iteratively unifying E to each element in list List Has invertible semantics can be used to scan a list or to construct a list foreach 2 3 foreach X L FK WO 3 co REE GERT foreach RE R 10 Z5 Bi lt primes 1 1 207 ODE ONE MES Er D DAG Iteration Constructs param and count Tare param Variables makes Variables visible in side iteration body 9 count Index MinExpr MaxExpr unifies Index to each integer in MinExpr MaxExpr muito iy Ip Que s foreach E L foreach X Out param K do X is K s Ba my lengtaliy 2 Save ae ETIE EIT bum tan Corcach D Counti h Ado true ge ceuiae ur i 4 co waelteilin i amp jgwsumES Id 2 3 d D di i il Mil I p D Scope and Motivations Prolog as a Constraint Solver ID pg Extensions to Prolog Constra
10. asible solution s and impose the con straint f s lt f s for the remainder of the search Restarts or continues the search Xe Xr Z eo Wash N 42 100 X 10 Y Z C N GS sb X ce A AS ue IN minimize labeling X Y Scope and Motivations Prolog as a Constraint Solver EcL ps Extensions to Prolog Constraint Satisfaction with EcL ps Optimization by Branch and Bound 9 ECL PS comes also with a ready made B amp B implemen tation to tackle constraint optimization problems 9 You must also provide an objective function f 9 ECL Ps B amp B works as follows for minimization prob lems Generates a feasible solution s and impose the con straint f s lt f s for the remainder of the search Restarts or continues the search Convert a maximization into a minimization problem pe JD xo All sss Os N F 100 vs OX sc 30 c N wb WD C N S dK AK St NP minimize labeling X Y Scope and Motivations Prolog asa Constraint Solver Extensions to Prolog Constraint Satisfaction _ with ECL Ps Optimization by Branch and Bound 9 ECI PS comes also with a ready made B amp B implemen tation to tackle constraint optimization problems You must also provide an objective function f 9 ECL PS B amp B works as follows for minimization prob Which is the largest integer n lt 1000 such that the cube of the sum of its digits equals the number its
11. ctic convenience to indi Scope and cate structures of structures Motivations G Functor name is irrelevant 9 matrix row 1 2 3 row 4 5 6 isa2x3 array and soisa b 1 2 3 c 4 5 6 9 dim A D unifies a new array A with functor name and its dimensions D 9 Use subscript 3 to access individual elements or array slices 9 Usual C like subscription operator available in expression con text provides same behaviour as subscript 3 Example g chim A 2 SI A Mali gt db DI DI ge ct ld De Dl 2 5 5 Day m 25 2 g gum 2 Sil suloseript A 2 1 53 RI m sts AXE TacS p Ri S RE Prolog as a Constraint Solver Q ECL PS Extensions to Prolog Syntactic Facilities Iteration Constructs Modules Constraint Sati ction with The Interval Constraints Library Search and Optimiz Other Constraint Libra Although every form of iteration can be expressed by a recursion this bring some disadvantages Code bloat every iteration requires you to write an ad ditional predicate Readability those predicates are coded far away in your code and impact readability Non locality if your iteration has to access many local variables you have to write a predicate with that many parameters Iteration in ECL PS is as powerful as recursion and of ten more concise Iteration Constructs Generalities Scope and Motivations 9 All iteration constructs have the form pae
12. elf It s 512 lems Generates a feasible solution s and impose the con straint f s lt f s for the remainder of the search Restarts or continues the search Xe Xr AERE C Wash N 42 100 X 10 Y Z C N GS sb Mc m AS se IN minimize labeling X Y roiog as 1 Constraint Sol s to Proloc Q Constraint Satisfaction with ECL P S The Int dA 1 St rc al Constraints Library id O ptim ization with E 9 Other Constraint Libraries Scope and Motivations Prolog as a Constraint Solver T Extensions to Prolog Constraint Symbolic Domains With ic_symbolic Sometimes it s more natural to work with a finite domain other than an interval of integers e Colors e Days of the week 9 ic symbolic permits this kind of symbolic domains 9 This library is implemented on top of ic 9 Every value in a symbolic domain is mapped to an inte ger Define a new symbolic domain with domain declaration local domain domainName values local domain weekday mo tu we il ie few SW o X amp weekday X amp tu X amp lt fr Note the implicit ordering of values Scope and Motivations Prolog as a Constraint Solver rer ps Extensions to Prolog Constraint Satisfaction with Ecr Ps Set Variables With ic sets This library manipulates integer set variables 9 Asetis simply a sorted list of integers wit
13. ese lessons you should e Have a fair theoretical background i e study stuff you saw during classes e Explore new technologies on your own documentations tutorials websites Be productive as soon as possible Scope and Motivations 9 Laboratory lessons will follow a hands on approach During lessons you are supposed to experiment with tools and techniques e Few novel theoretical concepts will be introduced 9e In order to make the most out of these lessons you should e Have a fair theoretical background i e study stuff you saw during classes e Explore new technologies on your own documentations tutorials websites Be productive as soon as possible anything else Scope and Motivations 9 Laboratory lessons will follow a hands on approach During lessons you are supposed to experiment with tools and techniques e Few novel theoretical concepts will be introduced e In order to make the most out of these lessons you should e Have a fair theoretical background i e study stuff you saw during classes Explore new technologies on your own documentations tutorials websites e Be productive as soon as possible 9 Ah of course You should have fun E Prolog as a Constraint Solver Constraint Solver S Extensions to Prolog Constraint Satisfaction with The Interval Constraints Library Search and Optimization with E Other Constraint Librari D di I il Mil
14. hout repetitions Much like ic it provides bound consistency on set vari able domains e But what is a range of sets 9 A set variable c is a triple Sp Sub C Sp is a set containing all the elements which are cer tainly in c e Sy is a set containing all the elements that might be in o obviously Sp C Sup e Cis an integer variable equal to c See also the concept of Lattice ge X G T 25 S p dasecconallia a ce do Finds 1 2 3 1 2 1 3 19
15. ical predicates and closed world assumption are Prolog greatest weaknesses Variables in arithmetic predicates must be instantiated else error For which values the second query is satisfied For none because you never told Prolog that 1 3 is true The Answer Is So So Stefano Benedettini 9 Constraints can only be tested for satisfiability e There is no constraint propagation domain reduction 9 Prolog natively supports only generate and test Solve problem Variables declare domains Variables search Variables test constraints Variables First generate a complete assignment to the decision variables 9 Then test satisfiability Prolog as a Constraint Solver The Simplest Prolog Constraint Solver That Can Possibly Work Define domains for a list of variables coma flo U domami IDsti ar DD Clon Dese se conta ID Ras DES Define integral domains for a list of variables imes Os Mim Mex We g int range Min Max R domain Xs R Vs Simple labeling label label V dom D T member V D label T DAG D di i il Mil Prolog as a Constraint Solver IM Gomes ia ID g memoer OX Dhs oo x oo Not in constraint moana ls MONE sue Mew sexe Shin Der E o All different ciiid erent I aLi ekhi rereme Petar g all different T Fl Moe ila D Ordered ordered oweleweewel Py well ge x amp xL ce
16. int Satis s M CH 27 3 I7 5 6 7 foreacheVemi H Iteration Constructs foreacharg and foreachelem 9 foreacharg 2 iterates on a structure array arguments 9 foreachelem 2 works only for arrays functor name must be Flattens the array and iterate on its ele ments Both support an optional third argument that is unified to element index M co wsssseedhm m prince 1 2 S 45 6 foreacharg Row M do writeln Row Z prints 1 2 3 Li By Sy 6 forca chic Eris gy ee swsatecxlbiotat 9r 18 5 mec primes dl l 1 1 2 2 ET 2 1 4 2 2 5 2 3 6 Eom easi REM MEETS MEIN Wists EET BESSER ns ted 2 3 Sd S Scope and Motivations Prolog as a Constraint Solver Extensions to Iteration Constructs for and multifor 9 for Index MinExpr MaxExpr work like its im perative counterpart Q9 multifor IndexList MinList MaxList con cisely describes multiply nested fors 9 Both constructs support an optional fourth argument to provide an iteration step evens L rori 2 LOU 2 woreacla it 15 Clo yess 5 mutliplication_table T SIDE LO LON medie bo Yi ue Ll 10 10 also quiis RT Sal Sha D foreachelem E T do Im Sher SC OW Iteration Constructs fromto Most general construct ele 9 fromto Init In Out Last do Body intro PP duces local variables n and Out in Body and behaves trair as follows First Init In
17. is translate into having delayed goals 9 The simples strategy consists in Recursively considering all unassigned variables in some order Q Try all values in its domain in ascending order Q Return a feasible assignment or backtrack and try another value 9 this is called labeling Pythagorean Triplets gw pi By lp Ww ses douzddQSL dee Wh x2 E dg C 2 findall V labeling V L 9 There are 52 unique Pythagorean triplets of integers in 1 100 9 Note the use of ordered to remove symmetries 9 ECL PS provides a general mechanism to customize a search in the form of predicate ic search You must specify Variable selection strategy Value selection strategy Some heuristics are already defined Variable selection input order anti first fail most constrai dle min value Value selection ascending order starting from max mid Search strategy can have a huge impact on efficiency Scope and Motivations Prolog asa Constraint Solver Extensions to Prolog Constraint Satisfaction _ with ECL Ps Optimization by Branch and Bound 9 ECI PS comes also with a ready made B amp B implemen tation to tackle constraint optimization problems You must also provide an objective function f 9 ECL PS B amp B works as follows for minimization prob Which is the largest integer n lt 1000 such that the cube of the sum of its digits equals the number itself lems Generates a fe
18. lldifferent is nothing more than manually set ting pairwise inequalities We need a better way to model global constraints than separating them in binary constraints e Propagation strength is lower e That is we cannot rule out as many values as a we could Enteric_global 9 Lots of high level constraints Minimum maximum of a list occurrences 9 astronger alldifferent 9 ordered useful for symmetry breaking Also check ac_eqinic e Provides an arc consistent and not only bound consis tent version of x 4 Y c Cisan integer constant zi S 29930 length V 100 V lengthit LOO Wass H L MM co T INS alldifferent V Lengen SD W ERO oxclerecl lt W ge x WI Ss2 1 10 X Pe 7 X Se X S33 go DES Mil 88 dosl0 X pie 7 euo SOG Ww Be 16 99 sese eli sese OW s Clearly inconsistent but no propagation is performed Immediately returns No as answer Q Correctly infers X i i 1 5 X e 8 6 U 8 10 and Y e 1 8 but cannot propagate the hole at X 7 Q X e 3 6 u 8 10 and Y e 1 4 U 6 8 now it is arc consistent Q Constraint Satisfaction with EcL Ps The Interval Constraints Library Search and Optimization with EcL Ps O her C r Constraint Libraries Scope and Motivations Prolog asa Constraint Solver rerips Extensions to Labeling 9 Propagation is insufficient to prove satisfiability in all but the simplest CSPs 9 In ECL PS th
19. near arithmetic and non linear constraints Issues with real variables How do we cope with limited precision How do we represent holes in a real domain Does this make sense x c 0 1 x 0 5 O di i il Mil p 5 Variable Domains naa Constrains integer as well real domains with SR and operators e ListOfVariables RangeSpecification specify either an integer or a real domain depending on Jii the range specification ACKER e enforces real domains Prolog enforces integer domain suggest to employ only or to clearly state variable type These operators work also with multidimensional arrays See documentation for further details Bes Neto xem file 4 En Gas NO amen aly susie Be elim Si u oF v u Qv Arithmetic Constraints ic support every arithmetic and comparison operator of Scope and Motivations standard Prolog Prolog as a e qualified use ic X op Y where op is one of gt lt Constraint m a Pico Solver 3 Ti SI iced 7 US e Prepend to comparison predicates to avoid qualifica Extensions to tion N a Prolog e Prepend to comparison predicates to also enforce in tegrality gt lt lt New variables spawn into existence as soon they are used Be p Sell SS diese yee xe ap al aes s e eu g den esa W 2 W 88 0 5 reomco es WIT et l
20. o Ld ee tes wj 9 2 X 1 3 AN Y 2 5 Z 2 4 N Vi 1 4 Xx E N XxX 0 2 x2 E 1 3 xg 2 4 xa 3 5 Boolean Constraints 9 ic supports basic boolean operators 9 or and xor gt all infix and neg for negation 9 They automatically enforce a boolean domain that is 0 1 How to solve a SAT without really trying X and Y or Z and X or neg Y X and neg X Q Infers X 1 Q Infers inconsistency D di I il Mil p Q Reified Constraints e How can we conditionally enforce a constraint FRE e How can express if x 1 3 then y lt z nola e Remember that we cannot leave choice points so for Constraint instance operator gt is out of question Solver Reified constraints come to the rescue Domain comparison and boolean constraints all have a reified version If the original constraint is op X Y its reified version is op X Y B where B is a boolean variable e If B 1 the constraint holds otherwise holds its nega tion e Thanks to function like predicate facility we can chain reified constraints in expression context ce Es Yo Dil sog 15 132 DI cs 32 xtensions to becomes Mt OICR D di U il Mil 5 p Scope and Motivations Prolog asa Constraint Solver rerips Extensions to Prolog Global Constraints and Propagation Strength Most of constraints in ic are binary e Also a
21. sse D 91 c Dae 5 ECLPS Extensions to 3 Constraint Solver Prolog ECL PS Extensions to Prolog Syntactic Facilities lteration Construct Modt Wes U Constraint Satisfaction with The Interval Constraints Librar Search and Op J 9timization with Other Consti aint Librari rarv ECL Ps Extensions to Prolog ECL PS supports a number of extensions that facilitate Prolog programming Structures and arrays Q Function like predicates Iteration constructs Modules For more information please refer to the User Manual ECL PS is a mature piece of software We won t have time to cover everything You are encouraged to explore by yourselves O di I il Mil DAG a Constraint S ECL PS Extensions to Prolog Syntactic Facilities lrer T 1 Constructs Search and C otimization wit Other Constraint Libra Function like Predicates Unofficial name to refer to a syntactic facility that allows Scope and you to use custom predicates in expression context Dues Expression Context is wherever ECL PS expects arith pile dae metic operations that are subsequently evaluated Solya Usually indicated with metavariable Expr in documenta S to tion Prolog 9 You can use a n ary predicate p X1 Xn as a func tion that expects X X4 4 as arguments and returns Xn as result Constraint Satisfaction with ECU 6 S5

Download Pdf Manuals

image

Related Search

Related Contents

Honeywell 10500 User's Manual  Philips FCV-552 User's Manual    取扱説明書  Manual de Instrucciones Manual de instruções  Owner's Manual RPRMSR Series Controller  Eglo ILANIE  Knape & Vogt WMUB-11-4-R-ASP Installation Guide  Amana UXT4036AYW Owner's Manual  "取扱説明書"  

Copyright © All rights reserved.
Failed to retrieve file