Constraint Satisfaction Problems The ECLi PSe Constraint Logic Programming System

Albert-Ludwigs-Universität Freiburg

Christian Becker-Asano, Bernhard Nebel and Stefan Wölfl January 26, 2015 Motivation

Problem modeling

Prolog & ECLi PSe

Programming Motivation in Prolog ECLi PSe Pro- gramming

Interval Constraints Library

Example

Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 2 / 100 What is ECLiPSe ?

Motivation

Problem modeling

Prolog & i e i e “ECL PS is designed for solving combinatorial optimization ECL PS problems, for the development of new constraint solver Programming in Prolog technology and their hybrids, and for the teaching of modelling, ECLi PSe Pro- solving and search techniques.” gramming

(http://sourceforge.net/projects/eclipse-clp/) Interval Constraints Library

Example

Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 4 / 100 What is ECLiPSe ?

Motivation i e ECL PS : Problem modeling 1 is a declarative language Prolog & ECLi PSe 2 is a Constraint Programming toolkit Programming 3 is available open source (Mozilla Public License) in Prolog

4 has been applied to areas of planning, scheduling, resource ECLi PSe Pro- allocation, timetabling, transport. . . gramming Interval 5 provides bindings for Python, /C++, Tcl/Tk, Java (Eclipse Constraints Library IDE plugin), SQL, . . . Example

6 can be interfaced to remotely (RPC) Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 5 / 100 Why ECLiPSe ?

Motivation

Problem modeling

The TPK (Trabb Pardo-Knuth) of and Prolog & ECLi PSe Luis Trabb Pardo (1976) (the “Hello World!” of ): Programming in Prolog “The algorithm prompts for 11 real numbers (a0 ...a10) and for p 3 i e each ai computes bi = f(ai ), where f(t) = |t| + 5t . After that for ECL PS Pro- gramming i = 10...0 (in that order) the algorithm outputs a pair (i,bi ) if Interval bi ≤ 400, or (i,TOO LARGE) otherwise.” (Dymchenko & Mykhailova, 2014) Constraints Library

Example

Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 6 / 100 Declarative programming with logic

The TPK algorithm in ECLi PSe / Prolog: Motivation Problem 1 f(T,Y):- modeling 2 Y is sqrt(abs(T)) + 5*T^3. Prolog & 3 main:- ECLi PSe 4 read(As), Programming 5 length(As,N), reverse(As, Rs), in Prolog 6 ( foreach(Ai, Rs), for(I,N - 1, 0, -1) do 7 Bi isf(Ai), ECLi PSe Pro- 8 ( Bi > 400 -> gramming 9 printf("%wTOOLARGE\n",I) Interval 10 ; Constraints 11 printf("%w%w\n",[I, Bi]) Library 12 ) Example 13 ). Summary

(Dymchenko & Mykhailova, 2014) Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 7 / 100 Declarative programming with functions

Motivation The TPK algorithm in python 3: Problem modeling

1 >>> deff(x): return abs(x) ** 0.5 + 5 *x**3 Prolog & 2 ECLi PSe 3 >>> print(’,’.join(’%s:%s’% Programming 4 (x,v ifv<=400 else"TOOLARGE!") in Prolog 5 forx,v in((y,f(float(y))) 6 fory in input(’\nnumbers:’) ECLi PSe Pro- 7 .strip.split()[:11][::-1]))) gramming Interval (http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm#Python) Constraints Library Is the logical Prolog version “easier/better” than the functional Example

Python version? Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 8 / 100 Python binding for ECLiPSe

The “Search Solution” example of pyclp:

1 from pyclp import* Motivation 2 init()# Init ECLiPSe engine Problem 3 Compound("lib",Atom("ic")).post_goal()# Load ic library modeling 4 A_var=Var()# Create variableA Prolog & 5 B_var=Var()# Create variableB ECLi PSe 6 #[A,B]#::1..10 Programming 7 Compound("#::",PList([A_var,B_var]),\ in Prolog 8 Compound("..",1,10)).post_goal() 9 Compound("#<",A_var,B_var).post_goal()#A#

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 9 / 100 So again, why ECLiPSe ?

Motivation

Problem modeling

⇒ Because it can be considered more elegant and even easier Prolog & ECLi PSe to (only) declare a problem logically and then use all the power Programming of standard reasoning and search algorithms to find a solution. in Prolog

i e ECL PS contains all major CLP algorithms as libraries and ECLi PSe Pro- gramming provides the full power of the Prolog language for problem Interval modeling. Constraints Library

Example

Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 10 / 100 Suitable problems for ECLiPSe

Motivation

i e Problem Characteristics of problems suitable for ECL PS : modeling

1 There are no general methods or algorithms Prolog & ECLi PSe NP-completeness Programming Different strategies and heuristics have to be tested in Prolog 2 Requirements are quickly changing ECLi PSe Pro- Programs should be flexible enough to adapt gramming 3 Interval Decision support required Constraints Co-operate with user Library Friendly interfaces Example Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 11 / 100 Motivation

Problem modeling Issues CLP and ECLi PSe

Prolog & Problem modeling ECLi PSe Programming in Prolog

ECLi PSe Pro- gramming

Interval Constraints Library

Example

Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 12 / 100 Logic programming

Constraint Programming can be characterized by two pseudo-equations: Motivation Problem modeling Solution = Logic + Control (1) Issues CLP and ECLi PSe

Prolog & Control = Reasoning + Search (2) ECLi PSe

Programming Equation (1): a solution can be found by: in Prolog

1 a , declarative description of the problem, and logical ECLi PSe Pro- gramming 2 control information for the computer to deduce it. Interval Equation (2): control is a combination of: Constraints Library

1 reasoning to (efficiently) limit the search space, and Example

2 subsequent (inefficient) search through that space Summary Literature Problem modeling deals with the Logic part of Equation (1).

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 14 / 100 Issues in Problem Modeling

A good formalism should fulfill the following criteria: Motivation 1 Expressive power: Problem modeling formal model of real world problem possible? Issues CLP and ECLi PSe

2 Clarity for humans: Prolog & i e ease of use of formalism (read, write, understand, modify) ECL PS Programming 3 Solvability for computers: in Prolog

Good methods available to solve problem? ECLi PSe Pro- Higher-level models gramming Interval + closer to the user and the problem Constraints Library

+ easier to understand and trust, to debug and modify, but Example - difficult to see how they can be solved Summary Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 15 / 100 Issues in Problem Modeling

Motivation

Classical source of error in application development: Problem ⇒ Transition from formal description to final program modeling Issues ⇒ Can the final program be trusted? CLP and ECLi PSe Prolog & CLP solution: ECLi PSe Programming Keep initial formal model as part of the final program in Prolog Enhance rather than rewrite: ECLi PSe Pro- Add control annotations (e.g., algorithmic or heuristic gramming information) Interval Constraints Transform higher-level (problem) constraints into Library low-level (solver) constraints Example

Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 16 / 100 Modeling with CLP and ECLiPSe

Built-in language constructs used in modeling: Motivation

Build-in constraints: X #> Y Problem modeling Abstraction: Issues CLP and ECLi PSe bef(task(Si,Di,),task(Sj,Dj)) :- Si+Dj #<= Sj. Prolog & i e Conjunction: betw(X,Y,Z) :- X #< Y, Y #< Z. ECL PS Programming Disjunction: neighb(X,Y) :- ( X #= Y+1 ; Y #= X+1 ). in Prolog

Iteration: ECLi PSe Pro- not_among(X,L) :- gramming Interval ( foreach(Y,L), param(X) do X #\= Y ). Constraints Library Recursion: Example not_among(X,[]). Summary not_among(X,[Y|Ys]) :- X #\= Y, not_among(X,Ys). Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 17 / 100 CLP and ECLiPSe

An example constraint network (Cheadle et al., 2014): Motivation Problem modeling Issues CLP and ECLi PSe

Prolog & ECLi PSe

Programming in Prolog

ECLi PSe Pro- gramming

Interval Constraints Library

Example

But, of course, one problem can be modeled in multiple ways.. Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 18 / 100 Same Problem – Different Model

1 sendmore(Digits):- 2 Digits=[S,E,N,D,M,O,R,Y], Motivation 3 Digits :: [0..9], 4 alldifferent(Digits), Problem modeling 5 S #\= 0,M #\= 0, Issues 6 1000*S + 100*E + 10*N+D CLP and ECLi PSe 7 + 1000*M + 100*O + 10*R+E Prolog & 8 #= 10000*M + 1000*O + 100*N + 10*E+Y. ECLi PSe

Programming 1 sendmore(Digits):- in Prolog 2 Digits=[S,E,N,D,M,O,R,Y], 3 Digits :: [0..9], ECLi PSe Pro- 4 Carries=[C1,C2,C3,C4], gramming 5 Carries :: [0..1], Interval 6 alldifferent(Digits), Constraints 7 S #\= 0,M #\= 0, Library 8 C1 #=M, Example 9 C2+S+M #=O + 10*C1, Summary 10 C3+E+O #=N + 10*C2, 11 C4+N+R #=E + 10*C3, Literature 12 D+E #=Y + 10*C4.

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 19 / 100 Modeling rules

Both models work fine, but involve different variables and constraints. Motivation Problem ⇒ “Finding good models [..] requires substantial expertise and modeling Issues experience.” (Cheadle et al., 2014) CLP and ECLi PSe

Prolog & Declarative model is constraint setup code ⇒ should be ECLi PSe deterministic and terminating, so general rules: Programming in Prolog Careful with disjunctions: Don’t leave choice points (i.e., ECLi PSe Pro- alternatives for backtracking); should be deferred until gramming

search phase Interval Constraints Use only simple conditionals: Conditions Library (...->...;...) must be true or false at modeling time! Example Summary Use only structural recursion and loops: Termination Literature conditions must be known at modeling time!

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 20 / 100 Preliminary summary

Motivation

Problem i e ECL PS : modeling Issues is a declarative constraint programming framework CLP and ECLi PSe Prolog & interfaces with many programming languages ECLi PSe Programming is based on the paradigm: in Prolog Solution = Logic + Control ECLi PSe Pro- uses Prolog for problem modeling gramming Interval Constraints ⇒ Next, introduction to Prolog.. Library

Example

Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 21 / 100 Motivation

Problem modeling

Prolog & ECLi PSe Terms and their i e data types Predicates, Goals, Prolog & ECL PS and Queries Conjunctions & Disjunctions Unification and Logical Variables

Programming in Prolog

ECLi PSe Pro- gramming

Interval Constraints Library

Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 22 / 100 Literature Introduction: Terms and their data types

Motivation

Problem Prolog data (terms) and programs are built from the following modeling data types: Prolog & ECLi PSe Numbers Terms and their data types Predicates, Goals, Strings and Queries Conjunctions & Disjunctions Atoms Unification and Logical Variables

Lists Programming in Prolog Structures

ECLi PSe Pro- They are introduced next.. gramming

Interval Constraints Library

Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 24 / 100 Literature Numbers

Numbers in ECLi PSe come in several flavors:

1 Integers can be as large as fits into memory, e.g.: Motivation Problem 123 0 -27 393423874981724 modeling 2 Floating point number (repr. as IEEE double floats), e.g.: Prolog & ECLi PSe 0.0 3.141592653589793 6.02e23 -35e-12 -1.0Inf Terms and their data types Predicates, Goals, 3 Also available: rationals and bounded reals and Queries Conjunctions & Disjunctions Beware: Performing arithmetic requires is/2 predicate: Unification and Logical Variables 1 ?-X is3+4. Programming 2 X=7 in Prolog 3 Yes

ECLi PSe Pro- Predicate =/2 constructs term corresp. to arithmetic expression: gramming Interval 1 ?-X=3+4. Constraints 2 X=3+4 Library 3 Yes Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 25 / 100 Literature Strings

Strings represent arbitrary sequences of bytes: Motivation 1 "I ama string!" 2 "string witha newline\n anda null \000 character" Problem modeling

Prolog & Strings versus Atoms: ECLi PSe Terms and their data types 1 many predicates accept both strings and atoms Predicates, Goals, and Queries 2 internally, the data types are quite different: Conjunctions & Disjunctions Unification and string stored as character sequence Logical Variables

atom mapped into internal constant via dictionary table Programming –> Copying and comparing: in Prolog

atoms in unit time ECLi PSe Pro- strings in time proportional to string length gramming Interval –> However, recollection of freed dictionary memory needs Constraints Library garbage collection Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 26 / 100 Literature Strings versus Atoms

Consider the following example:

1 [eclipse 1]: [user]. Motivation 2 afather(john, george). Problem 3 afather(sue, harry). modeling

4 afather(george, edward). Prolog & 5 sfather("john","george"). ECLi PSe 6 sfather("sue","harry"). Terms and their data types 7 sfather("george","edward"). Predicates, Goals, and Queries 8 yes. Conjunctions & 9 Disjunctions Unification and 10 [eclipse 2]: afather(sue,X). Logical Variables 11 X= harry Programming 12 yes. in Prolog 13

14 [eclipse 3]: sfather("sue",X). ECLi PSe Pro- 15 X="harry" More?(;) gramming

16 no(more) solution. Interval Constraints ⇒ Atoms should always be preferred when they are involved in Library unification and matching. Example Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 27 / 100 Literature Atoms

Motivation

Problem Atoms are simple symbolic constants: modeling

Prolog & 1 similar to enumeration type constants in other languages ECLi PSe Terms and their 2 no special meaning attached to them by the language data types Predicates, Goals, 3 and Queries syntactically: Conjunctions & Disjunctions all words starting with a lower case letter are atoms Unification and sequences of symbols are atoms Logical Variables Programming anything in single quotes is an atom in Prolog

4 E.g.: atom quark i5 -*- ??? ’Atom’ ’an atom’ ECLi PSe Pro- gramming

Interval Constraints Library

Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 28 / 100 Literature Lists

Lists are:

1 ordered sequences of (any number of) elements, each of Motivation which is itself a term Problem modeling

2 delimited by square brackets ([]) and its elements comma Prolog & ECLi PSe separated Terms and their data types Examples: [1,2,3], [berlin, tokyo, freiburg], Predicates, Goals, and Queries Conjunctions & ["csp1415", 42, [1,2,3], freiburg] Disjunctions Unification and More notation: Logical Variables Programming 1 empty list: [] in Prolog 2 head and tail: [Head|Tail], with ECLi PSe Pro- Head a single element gramming Tail a (possibly empty) list Interval Constraints –> Equivalent lists: [1,2,3], [1|[2,3]], [1|[2|[3]]], Library [1|[2|[3|[]]]] Example Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 29 / 100 Literature Structures

Structures correspond to structs or records in other languages:

Motivation 1 always has a name, which looks like an atom Problem 2 aggregates a fixed number of components, i.e. arguments modeling that themselves are terms Prolog & ECLi PSe Terms and their 3 general structure: (1, ...n) data types Predicates, Goals, 4 and Queries arity is the number of arguments Conjunctions & Disjunctions 5 name and arity together is called functor, often written as Unification and Logical Variables

name/arity, e.g., flight/4 Programming in Prolog Examples:

ECLi PSe Pro- date(december, 25, "Christmas") gramming Interval element(hydrogen, composition(1,0)) Constraints flight(london, new_york, 12.05, 17.55) Library Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 30 / 100 Literature Operator syntax (structures)

Prefix, infix, and postfix notation: Motivation 1 Unary structures also possible in prefix or postfix notation, Problem modeling e.g., the same as old berta. old(berta). Prolog & ECLi PSe 2 Binary structures also possible in prefix or infix notation, Terms and their data types e.g., 1 plus 5. the same as plus(1, 5). Predicates, Goals, and Queries Conjunctions & 3 these notations need to be declared with Disjunctions Unification and :- op(+Precedence, +Associativity, ++Name) Logical Variables Programming 4 if in doubt, use display/1 to check parsing of term: in Prolog

[eclipse]: display(a+b*c). ECLi PSe Pro- +(a, *(b, c)) gramming Interval yes. Constraints Library

Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 31 / 100 Literature Summary of data types

Motivation i e 1 Numbers: ECL PS has intergers, floats, rationals, Problem and bounded reals modeling Prolog & 2 Strings: character sequences in double quotes ECLi PSe Terms and their data types 3 Atoms: symbolic constants, usually lower case or in single Predicates, Goals, and Queries quotes Conjunctions & Disjunctions Unification and 4 Lists: constructed from cells that have an arbitrary head Logical Variables

and a tail, which is again a (possibly empty) list Programming in Prolog 5 Structures: have a name and a certain number (arity) of ECLi PSe Pro- arbitrary arguments, this characteristic is called the gramming

functor, and written name/arity Interval Constraints Library

Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 32 / 100 Literature Predicates

Motivation

Problem modeling Other programming languages have procedures and Prolog & functions ECLi PSe Terms and their data types i e Predicates, Goals, ⇒ Prolog and ECL PS have predicates: and Queries Conjunctions & 1 a predicate is something that has a truth value Disjunctions Unification and Logical Variables 2 a predicate definition defines what is true Programming 3 a predicate invocation or call checks its truth value in Prolog

ECLi PSe Pro- gramming

Interval Constraints Library

Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 33 / 100 Literature Goals and queries

Predicate examples for integer/1: Motivation integer(123) is true Problem integer(atom) is false modeling Prolog & integer([1,2]) is false ECLi PSe Terms and their data types These predicate calls are goals. Predicates, Goals, and Queries Conjunctions & If supplied by a user as a starting goal, the goal becomes a Disjunctions Unification and query, e.g.: Logical Variables

Programming ?- integer(123). in Prolog

Yes. ECLi PSe Pro- ?- integer(atom). gramming Interval No. Constraints Library Queries always return either Yes. or No. Example Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 34 / 100 Literature Conjunctions

Goals are often combined to form conjunctions (AND) or Motivation disjunctions (OR). Problem modeling Conjunctions: Prolog & ECLi PSe Terms and their 1 are built using commas data types Predicates, Goals, 2 are only true if all conjuncts are true and Queries Conjunctions & Disjunctions Examples: Unification and Logical Variables

Programming ?- integer(5), integer(7), integer(9). in Prolog Yes. ECLi PSe Pro- ?- integer(5), integer(hello). gramming No. Interval Constraints Library

Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 35 / 100 Literature Disjunctions

Motivation Disjunctions: Problem modeling 1 are built using semicolons Prolog & 2 are true if at least one disjunct is true ECLi PSe Terms and their data types Examples: Predicates, Goals, and Queries Conjunctions & Disjunctions ?- ( integer(5); integer(hello); integer(world) ). Unification and Yes. Logical Variables Programming ?- ( integer(hello); integer(world) ). in Prolog No. ECLi PSe Pro- gramming

Use parentheses with disjunctions to clarify the structure. Interval Constraints Library

Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 36 / 100 Literature Disjunctions

Motivation

Problem Special case: multiple answers in case of disjunctions! modeling i e ⇒ ECL PS gives separate Yes answers for every way in which Prolog & ECLi PSe a disjunctive query can be satisfied. Terms and their data types 1 Predicates, Goals, ?-( integer(5) ; integer(7) ). and Queries 2 Yes (0.00s cpu, solution 1, maybe more) Conjunctions & Disjunctions 3 Yes (0.02s cpu, solution 2) Unification and Logical Variables

1 ?-( integer(5) ; integer(hello)). Programming in Prolog 2 Yes (0.00s cpu, solution 1, maybe more) 3 No (0.02s cpu) ECLi PSe Pro- gramming

Interval Constraints Library

Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 37 / 100 Literature Symbolic Equality

Equality in Prolog:

–> structural equality by pattern matching Motivation Problem two terms only equal, if they have exactly same structure modeling No evaluation of any kind involved Prolog & ECLi PSe Terms and their Examples: data types Predicates, Goals, 1 ?- 3 = 3. and Queries Conjunctions & 2 Yes. Disjunctions 3 Unification and ?- 3 = 4. Logical Variables 4 No. Programming 5 ?- foo(a,2) = foo(a,2). in Prolog 6 Yes. 7 ?- foo(a,2) = foo(b,2). ECLi PSe Pro- 8 No. gramming 9 ?- +(3,4) = 7. Interval 10 No. Constraints 11 ?- 3 + 4 = 7. Library 12 No. Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 38 / 100 Literature Logical Variables

Logical variables: Motivation

1 are variables in the mathematical sense (not in the usual Problem sense) modeling Prolog & i e 2 are placeholders for values which are not yet known, not ECL PS Terms and their labels for storage locations data types Predicates, Goals, and Queries 3 are aliases for logical values and refer to terms Conjunctions & Disjunctions Unification and 4 keep their value once assigned to them Logical Variables Programming 5 are written beginning with an upper-case letter or an in Prolog underscore, e.g.: ECLi PSe Pro- X Var Quark _123 R2D2 Wumpus gramming

6 same identifier multiple times in input term denotes the Interval Constraints same variable Library Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 39 / 100 Literature Unification

With logical variables equality test become much more interesting: Unification Motivation

Problem Unification: modeling 1 is an extension of pattern matching of two terms Prolog & ECLi PSe 2 also causes binding (instantiation, aliasing) of variables in Terms and their data types Predicates, Goals, the two terms and Queries Conjunctions & 3 Idea: instantiate variables such that terms become equal Disjunctions Unification and Examples: Logical Variables Programming X = 7 is true with X instantiated to 7 in Prolog X = Y is true with X aliased to Y (or vice versa) foo(X) = foo(7) is true with X instantiated to 7 ECLi PSe Pro- foo(X,Y) = foo(3,4) is true with X instantiated to 3 and Y to 4 gramming foo(X,4) = foo(3,Y) is true with X instantiated to 3 and Y to 4 Interval foo(X) = foo(Y) is true with X aliased to Y (or vice versa) Constraints foo(X,X) = foo(3,4) is false because no possible value for X Library foo(X,4) = foo(3,X) is false because no possible value for X Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 40 / 100 Literature Summary: Basic Terminology

Predicate: Something that is true or false, depending on its Motivation

definition and its arguments. Defines a relationship between Problem its arguments. modeling Prolog & Goal: A logical formula whose truth value we want to know. ECLi PSe Terms and their data types A goal can be a conjunction or disjunction of other Predicates, Goals, and Queries (sub-)goals. Conjunctions & Disjunctions Unification and Query: The initial Goal given to a computation. Logical Variables Unification: An extension of pattern matching which can Programming in Prolog bind logical variables (placeholders) in the matched terms ECLi PSe Pro- to make them equal. gramming

Clause: One alternative definition for when a predicate is Interval Constraints true. A clause is logically an implication rule. Library

Example

Summary January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 41 / 100 Literature Motivation

Problem modeling

Prolog & ECLi PSe

Programming Programming in Prolog in Prolog Defining your own predicates Execution scheme Control structures Using Cut

ECLi PSe Pro- gramming

Interval Constraints Library

Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 42 / 100 Comments

Motivation

Problem modeling

Prolog & Comments can be: ECLi PSe 1 Block comments enclosed between /* and */ Programming in Prolog Defining your own 2 Line comments anything following % in a line (unless ‘%’ predicates Execution scheme character is part of a quoted atom or string) Control structures Using Cut (Nothing more to say..) ECLi PSe Pro- gramming

Interval Constraints Library

Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 44 / 100 Clauses and facts

In Prolog a program is a collection of predicates, and a predicate is a collection of clauses. Motivation

So, what is a clause: Problem modeling 1 defines that something is true Prolog & ECLi PSe 2 simplest form is a fact, which syntactically is a structure Programming or an atom terminated by a full stop, e.g.: in Prolog Defining your own predicates capital(london, england). Execution scheme Control structures brother(fred, jane). Using Cut

3 General form of a clause: ECLi PSe Pro- gramming

Head :- Body Interval Constraints Where Head is a structure (or atom) and Body is a Goal, Library

e.g.: Example uncle(X,Z) :- brother(X,Y), parent(Y,Z). Summary Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 45 / 100 Clauses and logical implication

The example clause: Motivation uncle(X,Z) :- brother(X,Y), parent(Y,Z). Problem modeling

Prolog & is equivalent to the following reverse implication: ECLi PSe

Programming uncle(X,Z) ← brother(X,Y) ∧ parent(Y,Z) in Prolog Defining your own predicates Execution scheme or more precisely: Control structures Using Cut

∀X∀Z : uncle(X,Z) ← ∃Y : brother(X,Y) ∧ parent(Y,Z) ECLi PSe Pro- gramming

Interval A fact is equivalent to a clause with its Body being true: Constraints Library brother(fred, jane) :- true. Example Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 46 / 100 Clauses and predicates

One or multiple clauses with the same head define(s) a functor Motivation

predicate, e.g. (with facts): Problem modeling 1 parent(abe, homer). 2 parent(abe, herbert). Prolog & ECLi PSe 3 parent(homer, bart). 4 parent(marge, bart). Programming in Prolog Defining your own Logically, multiple clauses: predicates Execution scheme Control structures are read as disjunctions Using Cut define multiple alternative ways a predicate can be true ECLi PSe Pro- gramming

Another example, the ancestor/2 predicate: Interval Constraints 1 ancestor(X,Y):- parent(X,Y). Library 2 ancestor(X,Y):- parent(Z,Y), ancestor(X,Z). Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 47 / 100 Execution scheme ⇒ resolution

Motivation

Problem modeling

Prolog & Resolution: ECLi PSe Programming Given: set of facts and rules as a program in Prolog Defining your own Starting point: a query as an initial goal to be resolved predicates Execution scheme Control structures Resolvent: set of goals that still have to be resolved Using Cut

ECLi PSe Pro- gramming

Interval Constraints Library

Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 48 / 100 Execution scheme ⇒ resolution

Execution mechanism: Motivation

1 Pick one goal from the resolvent. If resolvent is empty, stop. Problem modeling 2 Find all clauses whose head successfully unifies with goal. Prolog & If no such clause, go to step 6. ECLi PSe Programming 3 Select first of these clauses. If more exist, remember in Prolog Defining your own remaining ones. (choice point) predicates Execution scheme 4 Unify goal with head of the selected clause. (may instantiate Control structures Using Cut variables both in the goal and in the clause’s body). ECLi PSe Pro- 5 Prefix this clause body to the resolvent and go to 1. gramming

6 Backtrack: Reset whole computation state to how it was Interval Constraints when the most recent choice point was created. Take the Library clauses remembered in this choice point and go to 3. Example Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 49 / 100 Execution scheme example

1 ancestor(X,Y):- parent(X,Y).% clause1 Motivation 2 ancestor(X,Y):- parent(Z,Y), ancestor(X,Z).% clause2 Problem 3 parent(abe, homer).% clause3 modeling 4 parent(abe, herbert).% clause4 Prolog & 5 parent(homer, bart).% clause5 ECLi PSe 6 parent(marge, bart).% clause6 Programming in Prolog With query ?- ancestor(X, bart). we get: Defining your own predicates Execution scheme 1. both ancestor/2 predicates can unify the goal Control structures 1. but the textually first clause (1) is selected first: Using Cut

Goal (Query): ancestor(X,bart) ECLi PSe Pro- Selected: clause 1 gramming

Unifying: ancestor(X,bart) = ancestor(X1,Y1) Interval results in: X=X1, Y1=bart Constraints New resolvent: parent(X, bart) Library More choices: clause 2 Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 50 / 100 Execution scheme example

1 ancestor(X,Y):- parent(X,Y).% clause1 2 ancestor(X,Y):- parent(Z,Y), ancestor(X,Z).% clause2 Motivation 3 parent(abe, homer).% clause3 4 parent(abe, herbert).% clause4 Problem modeling 5 parent(homer, bart).% clause5 6 parent(marge, bart).% clause6 Prolog & ECLi PSe

Programming 2. body of clause 1 parent(X, bart) is added to resolvent, in Prolog Defining your own i.e. a choice point is generated predicates Execution scheme 2. parent(X, bart) is next selected for unification Control structures Using Cut ⇒ possible matches are clause 5 and 6, try 5 first 2. no body goals to add, the resolvent is now empty ECLi PSe Pro- gramming Goal: parent(X, bart) Interval Selected: clause 5 Constraints Unifying: parent(X,bart) = parent(homer,bart) Library results in: X = homer Example New resolvent: More choices: clause 6, then clause 2 Summary Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 51 / 100 Execution scheme example

1 ancestor(X,Y):- parent(X,Y).% clause1 2 ancestor(X,Y):- parent(Z,Y), ancestor(X,Z).% clause2 Motivation 3 parent(abe, homer).% clause3 4 parent(abe, herbert).% clause4 Problem modeling 5 parent(homer, bart).% clause5 6 parent(marge, bart).% clause6 Prolog & ECLi PSe 3. empty resolvent ⇒ execution completes successfully, Programming in Prolog found first solution Defining your own X = homer predicates 3. ECLi PSe returns solution and asks if more solutions wanted Execution scheme Control structures 3. If yes, backtrack to most recent choice point Using Cut 3. any variable bindings done after choice point are undone, ECLi PSe Pro- here binding of X to homer is undone gramming

Goal: parent(X, bart) Interval Selected: clause 6 Constraints Unifying: parent(X,bart) = parent(marge,bart) Library results in: X = marge Example New resolvent: Summary More choices: clause 2 Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 52 / 100 Execution scheme example

1 ancestor(X,Y):- parent(X,Y).% clause1 2 ancestor(X,Y):- parent(Z,Y), ancestor(X,Z).% clause2 Motivation 3 parent(abe, homer).% clause3 4 parent(abe, herbert).% clause4 Problem modeling 5 parent(homer, bart).% clause5 6 parent(marge, bart).% clause6 Prolog & ECLi PSe

Programming 4. empty resolvent ⇒ execution completes successfully, in Prolog Defining your own found second solution X = marge predicates Execution scheme 4. If still more solutions wanted, backtrack to most recent Control structures Using Cut choice point 4. no further alternatives for ⇒ check ECLi PSe Pro- parent/2 ancestor/2 gramming Goal: ancestor(X,bart) Interval Selected: clause 2 Constraints Unifying: ancestor(X,bart) = ancestor(X1,Y1) Library

results in: Y1 = bart, X1 = X Example New resolvent: parent(Z1, bart), ancestor(X1, Z1) More choices: Summary Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 53 / 100 Execution scheme example

1 ancestor(X,Y):- parent(X,Y).% clause1 2 ancestor(X,Y):- parent(Z,Y), ancestor(X,Z).% clause2 Motivation 3 parent(abe, homer).% clause3 4 parent(abe, herbert).% clause4 Problem modeling 5 parent(homer, bart).% clause5 6 parent(marge, bart).% clause6 Prolog & ECLi PSe

Programming 5. new resolvent contains two goals: parent(Z1, bart), in Prolog Defining your own ancestor(X1, Z1) predicates Execution scheme 5. Check leftmost first, parent(Z1, bart) ⇒ new choice Control structures Using Cut point 5. Select clause 5 first ECLi PSe Pro- gramming Goal: parent(Z1, bart) Interval Selected: clause 5 Constraints Unifying: parent(Z1, bart) = parent(homer, bart) Library

results in: Z1 = homer Example New resolvent: ancestor(X1, homer) More choices: clause 6 Summary Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 54 / 100 Execution scheme example

Motivation 1 ancestor(X,Y):- parent(X,Y).% clause1 Problem 2 ancestor(X,Y):- parent(Z,Y), ancestor(X,Z).% clause2 modeling 3 parent(abe, homer).% clause3 Prolog & 4 parent(abe, herbert).% clause4 ECLi PSe 5 parent(homer, bart).% clause5 6 parent(marge, bart).% clause6 Programming in Prolog Defining your own predicates 6. Via finding the ancestor of homer a few steps later: Execution scheme ?- ancestor(X,bart). Control structures Using Cut X = abe More? (;)

ECLi PSe Pro- 6. Finally, Z1 would be bound to marge for whom no ancestors gramming

are found ⇒ False. Interval Constraints Here, the execution terminates. Library Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 55 / 100 More control structures

Disjunction: Motivation 1 at_part(X):-(X=proton;X=neutron;X=electron). Problem is logically equivalent to: modeling Prolog & 1 at_part(proton). ECLi PSe 2 at_part(neutron). Programming 3 at_part(electron). in Prolog Defining your own Conditional: predicates Execution scheme specified by the ->/2 operator Control structures combined with ;/2, a conditional similar to ‘if-then-else’ can Using Cut

be constructed: X->Y;Z ECLi PSe Pro- only first solution of X is explored ⇒ no new solutions are gramming tried on backtracking! Interval Constraints Library 1 max(X,Y, Max):- 2 number(X), number(Y), Example

3 (X>Y -> Max=X; Max=Y). Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 56 / 100 More control structures

Call: in Prolog: data == programs Motivation

both are represented as terms Problem use predicate call to treat terms as goals modeling Prolog & call(X): at runtime X has to be instiantiated, but not at ECLi PSe compile time! Programming possible definition of disjunction (;): in Prolog Defining your own 1 X;Y:- call(X). predicates Execution scheme 2 X;Y:- call(Y). Control structures Using Cut All solutions: Alternative to one-by-one solution computation: ECLi PSe Pro- gramming 1 ?- findall(X, weekday(X), List). Interval 2 X=X Constraints 3 List=[mo, tu, we, th, fr, sa, su] Library 4 Yes Example See also setof/3 and bagof/3 predicates Summary Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 57 / 100 Using cut: Overview

Motivation

Problem Use cut (!) to prune away part of the Prolog search-space. modeling Prolog & Powerful mechanism to improve program performance ECLi PSe Suppresses unwanted solutions Programming in Prolog Defining your own BUT: easily mis- or overused! predicates Execution scheme Cut does two things: Control structures Using Cut 1 commit: disregard later clauses for a predicate 2 prune: Throw away alternative solutions to the goal to the ECLi PSe Pro- left of the cut gramming Interval Constraints Library

Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 58 / 100 Commit to current clause

Consider the following encoding of the “minimum” predicate:

1 min(X,Y, Min):-X

2 min(X,Y, Min):-Y=

Problems: Prolog & ECLi PSe logically correct, but non-optimal performance Programming with :- min(2,3,M). Prolog leaves an open choice point in Prolog Defining your own predicates ⇒ during backtracking another minimum would be Execution scheme searched for unnecessarily! Control structures Using Cut unnecessary choice point: ECLi PSe Pro- 1 consumes memory gramming

2 costs execution time Interval Constraints Solution, use cut: Library Example 1 min(X,Y, Min):-X

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 59 / 100 Prune alternative solutions

Motivation

A cut may occur anywhere where a goal may occur: Problem modeling 1 first_prime(X,P):- Prolog & 2 prime(X,P),!. ECLi PSe

Programming first_prime/2: in Prolog Defining your own returns the first prime number smaller than X predicates Execution scheme calls predicate prime/2, which generates prime numbers Control structures Using Cut smaller than X in descending order ECLi PSe Pro- ! (cut) prunes away all remaining solutions gramming Interval –> on backtracking no alternatives are tried Constraints Library

Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 60 / 100 Motivation

Problem modeling

Prolog & ECLi PSe i e Programming ECL PS Programming in Prolog ECLi PSe Pro- gramming Control & data structures Input and Output More functions Modules

Interval Constraints Library

Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 61 / 100 Structure Notation

Names for structures (so-called declared structures) make them Motivation Problem more readable and maintainable, e.g. with: modeling

1 :- local struct( book(author, title, year, publisher)). Prolog & ECLi PSe Structures with the functor book/4 can be written as: Programming in Prolog 1 book{} 2 book{title:’tom sawyer’} ECLi PSe Pro- 3 book{title:’tom sawyer’, year:1876, author:twain} gramming Control & data structures which correspond to: Input and Output More functions Modules 1 book(_,_,_,_) 2 book(_,’tom sawyer’,_,_) Interval Constraints 3 book(twain,’tom sawyer’, 1876,_) Library

Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 63 / 100 Structure Notation

Motivation

Problem Properties of declared structure notation: modeling Prolog & the arguments can be written in any order ECLi PSe Programming “dummy” arguments with anonymous variables do not need in Prolog to be written ECLi PSe Pro- the arity of the structure is not implied gramming Control & data structures the of-syntax can be used to return index of argument, e.g.: Input and Output More functions arg(year of book, B, Y) is equiv. to arg(3, B, Y) Modules

Interval Constraints Library

Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 64 / 100 Loops

To reduce the need for auxiliary predicates ⇒ iteration construct: ( IterationSpecs do Goals ) Motivation Problem For example, iteration over a list: modeling

1 ?-( foreach(X,[1,2,3]) do writeln(X)) Prolog & ECLi PSe 2 1 3 2 Programming in Prolog 4 3 5 Yes (0.00s cpu) ECLi PSe Pro- If a parameter remains constant across all loop iterations ⇒ gramming Control & data structures must be specified explicitly (via param): Input and Output More functions 1 ?- Array = [](4,3,6,7,8), Modules 2 ( Interval 3 for(I,1,5), Constraints 4 fromto(0,In,Out,Sum), Library 5 param(Array) Example 6 do Summary 7 Out is In+ Array[I] 8 ). Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 65 / 100 Loops

Possible IterationSpecs: fromto(First,In,Out,Last): iterate Goals starting with Motivation In=First until Out=Last. Problem modeling

foreach(X,List): iterate Goals with X ranging over all Prolog & i e elements of List. ECL PS Programming foreacharg(X,StructOrArray): iterate Goals with X in Prolog

ranging over all arguments of StructOrArray. ECLi PSe Pro- gramming foreacharg(X,StructOrArray,Idx): same as before, Control & data structures but Idx is set to the argument position of X in StructOrArray. Input and Output More functions ... Modules Interval for(I,MinExpr,MaxExpr,[Increment]): iterate Goals Constraints with I ranging over integers from MinExpr to MaxExpr with Library Example optional increment. Summary ... (see http://eclipseclp.org/doc/tutorial/tutorial025.html) Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 66 / 100 Arrays

Arrays can be of any dimension, indices start at 1, and they are

declared with the dim/2 predicate: Motivation

1 ?- dim(M,[3,4]). Problem 2 M = []([](_131, _132, _133, _134), modeling 3 [](_126, _127, _128, _129), Prolog & i e 4 [](_121, _122, _123, _124)) ECL PS 5 yes. Programming in Prolog To query dimensions: ECLi PSe Pro- 1 ?- dim(M,[3,4]), dim(M,D). gramming 2 ... Control & data 3 D = [3, 4] structures Input and Output 4 yes. More functions Modules

To access specific elements, specify its index: Interval Constraints 1 ?-M = []([](2, 3, 5), Library 2 [](1, 4, 7)),X isM[1, 2] +M[2, 3]. 3 X = 10 Example 4 M = []([](2, 3, 5), [](1, 4, 7)) Summary 5 yes. Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 67 / 100 Printing

i e Printing ECL PS terms: Motivation

Problem write(+Stream, ?Term): write one term in a default modeling

format Prolog & ECLi PSe write_term(+Stream, ?Term, +Options): write one Programming term, format options can be selected in Prolog

printf(+Stream, +Format, +ArgList): write a string ECLi PSe Pro- gramming with embedded terms, according to a format string Control & data structures writeq(+Stream, ?Term), Input and Output More functions write_canonical(+Stream, ?Term): write one term so Modules Interval that it can be read back Constraints put(+Stream, +Char): write one character Library Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 68 / 100 Reading

Reading ECLi PSe terms: Motivation

read(+Stream, -Term, [Options]): read one Problem fullstop-terminated ECLi PSe term. modeling Prolog & get(+Stream, -Char): read one character ECLi PSe

Programming read_string(+Stream, +Terminator, -Length, in Prolog -String): read a string up to a certain terminator character ECLi PSe Pro- read_token(+Stream, -Token, -Class): read one gramming Control & data syntactic token (e.g. a number, an atom, a bracket, etc) structures Input and Output More functions Example: Modules

1 [eclipse 1]: read(X). Interval Constraints 2 [3,X,foo(bar),Y]. Library 3 X = [3,X, foo(bar),Y] 4 yes. Example Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 69 / 100 Matching (one-way unification)

Clauses can use matching (or one-way unification) instead of head unification: Motivation

Problem written with ?- functor instead of :- modeling No variables in the caller will be bound Prolog & ECLi PSe

1 [eclipse 1]: [user]. Programming in Prolog 2 p(f(a,X))?- writeln(X). 3 ?-p(F). i e 4 Query failed:?-p(F) ECL PS Pro- gramming 5 ?-p(f(A,B)). Control & data 6 Query failed:?-p(f(A,B)) structures Input and Output 7 ?-p(f(a,b)). More functions 8 b Modules

Interval 1 [eclipse 2]: [user]. Constraints Library 2 p(f(a,X)):- writeln(X). 3 ?-p(f(A,B)). Example 4 B Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 70 / 100 List processing

ECLi PSe provides append/3, length/2, member/2, and sort/2: Motivation Problem append/3: append or split lists, e.g. modeling

1 ?- append([1, 2], [3, 4],L). Prolog & ECLi PSe 2 L = [1, 2, 3, 4] 3 ?- append(A, [3, 4], [1, 2, 3, 4]). Programming in Prolog 4 A = [1, 2] 5 ?- append([1, 2],B, [1, 2, 3, 4]). ECLi PSe Pro- 6 B = [3, 4] gramming Control & data structures length/2: compute the length of a list or construct list of Input and Output More functions given length, e.g. Modules

1 ?- length([1, 2, 3, 4],N). Interval Constraints 2 N=4 Library 3 ?- length(List, 4). Example 4 List=[_1693, _1695, _1697, _1699] Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 71 / 100 List processing

ECLi PSe provides append/3, length/2, member/2, and sort/2: Motivation member/2: check membership in a list (but memberchk/2 Problem modeling

should be preferred), or backtrack over all list members, e.g. Prolog & ECLi PSe 1 ?- memberchk(2, [1, 2, 3]). 2 Yes (0.00s cpu) Programming in Prolog 3 ?- member(X, [1, 2, 3]). 4 X=1 ECLi PSe Pro- 5 More (0.00s cpu) gramming 6 X=2 Control & data structures 7 More (0.01s cpu) Input and Output 8 X=3 More functions 9 Yes (0.01s cpu) Modules Interval Constraints sort/2: sort any list and remove duplicates, e.g. Library

1 ?- sort([5, 3, 4, 3, 2], Sorted). Example

2 Sorted = [2, 3, 4, 5] Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 72 / 100 Term processing

Motivation

Problem Generic built-in predicates: modeling =..: converts structures into lists and vice versa Prolog & ECLi PSe

arg/3: extracts an argument from a structure Programming in Prolog functor/3: extracts functor name and arity from structured term ECLi PSe Pro- gramming Control & data term_variables/2: extracts all variables from arbitrarily structures Input and Output complex terms More functions Modules copy_term/2: creates a copy of a term with fresh variables Interval Constraints Library

Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 73 / 100 Making a module

With module directive a new module is declared, e.g.: Motivation 1 :- module(greeting). Problem 2 :- export hello/0. modeling 3 hello:- Prolog & 4 who(X), ECLi PSe 5 printf("Hello%w!%n",[X]). Programming 6 who(world). in Prolog 7 who(friend). ECLi PSe Pro- and with export a predicate is exported. gramming Control & data One can now import the module and call its exported predicate, structures Input and Output e.g.: More functions Modules

1 :- module(main). Interval 2 :- import greeting.% or‘import hello/0 from greeting.’ Constraints 3 main:- Library 4 hello.% or(without‘import’)‘greeting:hello.’ Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 74 / 100 Exporting items other than predicates

Motivation

Problem modeling

Most commonly exported items (apart from predicates) are Prolog & i e structure and operator declarations: ECL PS Programming 1 :- module(data). in Prolog 2 :- export struct(employee(name,age,salary)). i e 3 :- export op(500, xfx, reports_to). ECL PS Pro- gramming 4 ... Control & data structures Import declarations by importing module (import data.). Input and Output More functions Modules

Interval Constraints Library

Example

Summary

Literature January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 75 / 100 Motivation

Problem modeling

Prolog & ECLi PSe

Programming Interval Constraints Library in Prolog

ECLi PSe Pro- gramming

Interval Constraints Library Constraints Global Constraints

Example

Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 76 / 100 Interval Constraints Library

The IC (Interval Constraints) library provides a general interval Motivation propagation solver which can be used to solve problems over Problem both integer and real variables. modeling Prolog & Load the IC library using either of the following: ECLi PSe Programming 1 :- lib(ic). in Prolog 2 :- use_module(library(ic)).

ECLi PSe Pro- The typical top-level structure of a constraint program: gramming Interval 1 solve(Variables):- Constraints 2 read_data(Data), Library 3 setup_constraints(Data, Variables), Constraints Global Constraints 4 labeling(Variables). Example

The labeling/2 predicate is the search part of the program Summary

and part of the IC library. Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 78 / 100 Modeling

Your code must:

create variables with initial domains Motivation Problem setup constraints between variables modeling Example, SEND+MORE = MONEY: Prolog & ECLi PSe 1 :- lib(ic). Programming 2 sendmore(Digits):- in Prolog 3 Digits=[S,E,N,D,M,O,R,Y], 4 % Assign finite domain with each letter in list Digits ECLi PSe Pro- 5 Digits :: [0..9], gramming

6 % Constraints Interval 7 alldifferent(Digits), Constraints 8 S #\= 0, Library Constraints 9 M #\= 0, Global Constraints 10 1000*S + 100*E + 10*N+D Example 11 + 1000*M + 100*O + 10*R+E 12 #= 10000*M + 1000*O + 100*N + 10*E+Y, Summary 13 % Search Literature 14 labeling(Digits).

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 79 / 100 Built-in constraints

The ic library provides the following predicates:

Vars :: Domain Motivation

constrains Vars to take only integer or real values from the Problem domain specified by Domain modeling Prolog & Domain can be simple range Lo .. Hi, or a list of ECLi PSe subranges and/or individual elements (integer variables) Programming type of bounds determines type of the variable in Prolog also allowed: symbolic bound values inf, +inf and -inf ECLi PSe Pro- Vars $:: Domain gramming like ::/2, but for declaring real variables (never imposes Interval Constraints integrality, regardless of the types of bounds) Library Constraints Vars #:: Domain Global Constraints

like ::/2, but for declaring integer variables Example

reals(Vars) and integer(Vars) Summary declares that variables are IC variables / constraints Literature variables to integer values only

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 80 / 100 Built-in constraints: examples

1 ?-X :: -10 .. 10.% integer values from -10 to 10 2 X=X{-10 .. 10} Motivation 3 Yes 4 ?-X :: -10.0 .. 10.0.% real values from -10 to 10 Problem modeling 5 X=X{-10.0 .. 10.0} 6 Yes Prolog & ECLi PSe 7 ?-X #:: -10 .. 10.% explicitly declared integer values 8 X=X{-10 .. 10} Programming 9 Yes in Prolog 10 ?-X$:: -10 .. 10.% explicitly declared real values i e 11 X=X{-10.0 .. 10.0} ECL PS Pro- gramming 12 Yes 13 ?-X :: 0 .. 1.0Inf.% integers from zero to infinity Interval Constraints 14 X=X{0 .. 1.0Inf} Library 15 Yes Constraints 16 ?-X :: 0.0 .. 1.0Inf.% reals from zero to infinity Global Constraints 17 X=X{0.0 .. 1.0Inf} Example 18 Yes Summary 19 ?-X :: [1, 4 .. 6, 9, 10].% subranges(integers only) 20 X=X{[1, 4 .. 6, 9, 10]} Literature 21 Yes

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 81 / 100 Arithmetic constraints

Arithmetic constraints in integral (#) and non-integral ($) version: Motivation Problem #= & $=: equality of integer (#) or general ($) expressions modeling Prolog & #>= & $>=: greater than or equal ECLi PSe #=< & $=<: less than or equal Programming in Prolog #> & $>: greater than ECLi PSe Pro- #> & $>: less than gramming Interval #\= & $\=: not equal Constraints Library ac_eq(X,Y,C): arc-consistent implementation of X #= Y Constraints + C. X and Y are constrained to be integer variables and to Global Constraints Example have “reasonable” bounds. C must be an integer. Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 82 / 100 Arithmetic constraints

Further notes: X/2 + Y/2 #= 1 and X + Y #= 2 are different Motivation Problem constraints ⇒ the first constraints X and Y to be even modeling Except for disequality and ac_eq/3, all basic constraints Prolog & ECLi PSe propagate bound information (performing interval Programming reasoning), e.g.: in Prolog

1 ?-[X,Y] :: 0 .. 10,X #>=Y + 2. ECLi PSe Pro- 2 X=X{2 .. 10} gramming 3 Y=Y{0 .. 8} Interval 4 There is1 delayed goal. Constraints 5 Yes Library Constraints delayed goal indicates that still some combinations of Global Constraints Example values for X and Y violate the constraint constraint remains until no such violation is possible Summary anymore Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 83 / 100 Constraint Expression Connectives

The following connectives can be used to combine constraint Motivation expressions: Problem modeling 1 and: Constraint conjunction, e.g. ‘X $> 3 and X $< 8’ Prolog & 2 or: Constraint disjunction, e.g. ‘X $< 3 or X $> 8’ ECLi PSe Programming 3 =>: Constraint implication, e.g. ‘X $> 3 => X $< 8’ in Prolog

4 and: Constraint negation, e.g. ‘neg X $> 3’ ECLi PSe Pro- Example: gramming Interval 1 ?-[X,Y] :: 0..10,X #>=Y+6 orX #=

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 84 / 100 Constraint Expression Connectives

Motivation

Problem Once it is known that X #=< Y - 6 cannot be true, the modeling Prolog & constraint X #>= Y +6 is enforced. ECLi PSe

Programming Example: in Prolog

1 ?-[X,Y] :: 0..10,X #>=Y+6 orX #== 5. ECLi PSe Pro- 2 Y=Y{0 .. 4} gramming 3 X=X{6 .. 10} Interval 4 There is1 delayed goal. Constraints 5 Yes Library Constraints Global Constraints

Example

Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 85 / 100 Global constraints

Motivation The IC (Interval Constraints) has optional components, which Problem provide global constraints ⇒ high-level constraints that provide modeling more global reasoning than the ones in main IC library. Prolog & ECLi PSe

contained in ic_global, ic_cumulative, Programming ic_edge_finder, and ic_edge_finder3 in Prolog To use, e.g., ic_global: ECLi PSe Pro- gramming

1 :- lib(ic_global). Interval 2 :- use_module(library(ic_global)). Constraints Library Constraints Note: some predicates appear in more than one library, e.g., Global Constraints ic:alldifferent/1 and ic_global:alldifferent/1 Example Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 86 / 100 Different strength of propagation

Compare the ic:alldifferent/1 version:

1 ?-[X1, X2] :: 1 .. 2, [X3, X4] :: 1 .. 4, Motivation 2 ic:alldifferent([X1, X2, X3, X4]). Problem 3 X1= X1{[1, 2]} modeling 4 X2= X2{[1, 2]} Prolog & 5 X3= X3{1 .. 4} ECLi PSe 6 X4= X4{1 .. 4} Programming 7 There are4 delayed goals. in Prolog 8 Yes

ECLi PSe Pro- with the ic_global:alldifferent/1 version: gramming

1 ?-[X1, X2] :: 1 .. 2, [X3, X4] :: 1 .. 4, Interval 2 ic_global:alldifferent([X1, X2, X3, X4]). Constraints Library 3 X1= X1{[1, 2]} Constraints 4 X2= X2{[1, 2]} Global Constraints 5 X3= X3{[3, 4]} Example 6 X4= X4{[3, 4]} 7 There are2 delayed goals. Summary 8 Yes Literature Trade-off: longer propagation time for ic_global version January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 87 / 100 Motivation

Problem modeling

Prolog & ECLi PSe

Programming Example in Prolog

ECLi PSe Pro- gramming

Interval Constraints Library

Example

Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 88 / 100 N-Queens problem

Motivation

Problem N-Queens modeling Prolog & Place N queens on an N × N chessboard so that no queen ECLi PSe attacks another. A queen attacks all cells in horizontal, vertical Programming and diagonal direction. in Prolog

ECLi PSe Pro- gramming certain solutions for all sizes can be constructed Interval Constraints not a hard problem Library long history in AI and CP papers Example Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 90 / 100 N-Queens problem: Column based Model

A 1..N variable for each column, stating position of queen in Motivation the column Problem modeling

. . . because exactly one queen needed for each column Prolog & ECLi PSe 2 N variables ⇒ N /2 binary constraints Programming in Prolog assign [X ,X ,...,X ] so that: 1 2 N ECLi PSe Pro- gramming

∀1 ≤ i ≤ N : Xi ∈ 1..N Interval Constraints Library ∀1 ≤ i < j ≤ N : Xi =6 Xj Example ∀1 ≤ i < j ≤ N : Xi =6 Xj + i − j Summary

∀1 ≤ i < j ≤ N : Xi =6 Xj + j − i Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 91 / 100 Possible program

i e One possible ECL PS -program is: Motivation Problem 1 :-module(nqueen). modeling 2 :-export(top/0). Prolog & 3 :-lib(ic). ECLi PSe 4 top:- Programming 5 nqueen(8,L), writeln(L). in Prolog 6 nqueen(N,L):- 7 length(L,N), ECLi PSe Pro- 8 L :: 1..N, gramming

9 alldifferent(L), Interval 10 noattack(L), Constraints 11 labeling(L). Library Example (see: ) http://4c.ucc.ie/~hsimonis/ELearning/nqueen/slides.pdf Summary noattack/2 defines binary constraints Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 92 / 100 Binary constraints

Motivation

Definition of noattack/2: Problem modeling

1 noattack([]). Prolog & 2 noattack([H|T]):- ECLi PSe

3 noattack1(H,T,1), Programming 4 noattack(T). in Prolog 5 noattack1(_,[],_). 6 noattack1(X,[Y|R],N):- ECLi PSe Pro- 7 X #\=Y+N, gramming 8 Y #\=X+N, Interval 9 N1 isN+1, Constraints Library 10 noattack1(X,R,N1). Example

see: http://4c.ucc.ie/~hsimonis/ELearning/nqueen/slides.pdf) Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 93 / 100 Search improvement

The search predicate:

Motivation 1 [..] 2 top:- Problem modeling 3 nqueen(8,L), writeln(L). 4 nqueen(N,L):- Prolog & ECLi PSe 5 length(L,N), 6 L :: 1..N, Programming 7 alldifferent(L), in Prolog 8 noattack(L), i e 9 labeling(L).% <-- change this line ECL PS Pro- gramming

Interval last line can be changed to: Constraints Library 1 search(L,0,first_fail,indomain,complete,[]) Example packaged search library in ic constraint solver Summary Literature provides many alternative search methods just select the right keywords as arguments

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 94 / 100 search predicate parameters search(+L, ++Arg, ++Select, +Choice, ++Method, Motivation +Option): Problem modeling 1 L: List / collection of terms / domain variables Prolog & 2 Arg: 0 if list L is list of domain variables, greater than 0 if L ECLi PSe consists of terms with arity at least Arg Programming in Prolog 3 Select: name of variable selection method (input_order, ECLi PSe Pro- first_fail, smallest, largest,...) gramming

4 : name of value choice method ( , Interval Choice indomain Constraints indomain_min, indomain_max, indomain_middle,...) Library Example 5 Method: tree search method (complete, Summary bbs(Steps:integer), lds(Disc:integer),...) Literature 6 Option: list of option terms

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 95 / 100 search improvements

With first_fail strategy: Motivation 1 search(L,0,first_fail,indomain,complete,[]) Problem modeling

solution is different from naive input_order approach Prolog & ECLi PSe more solutions can be found Programming Further improvements: in Prolog

start from the middle of the board ECLi PSe Pro- gramming

use most_constraint instead of first_fail (tie break Interval Constraints based on number of constraints in which variable occurs) Library try multiple strategies in parallel (multi-core CPUs) Example limit number of backtracks for search attempt and use Summary Literature randomization (of value and/or variable choice) ...

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 96 / 100 Motivation

Problem modeling

Prolog & ECLi PSe

Programming Summary in Prolog

ECLi PSe Pro- gramming

Interval Constraints Library

Example

Summary

Literature

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 97 / 100 Summary

ECLi PSe : interfaces with many programming languages Motivation Problem provides a stand-alone and a command line user interface modeling Prolog & consists of a collection of libraries ECLi PSe

Programming is intended for problem solving in a declarative fashion in Prolog enabling rapid prototyping based on the CLP paradigm ECLi PSe Pro- Last but not least: gramming

Interval It is actively developed, Constraints Library but already mature enough, Example

and very well documented. Summary We only scratched its surface here. Literature Check out http://eclipseclp.org/, next. . .

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 99 / 100 Literature

Sergii Dymchenko & Mariia Mykhailova. Motivation Declaratively solving tricky Google Code Jam problems with Problem Prolog-based ECLiPSe CLP system. modeling

http://arxiv.org/abs/1412.2304 Prolog & ECLi PSe Andrew M. Cheadle, Warwick Harvey, Andrew J. Sadler, Joachim Programming Schimpf, Kish Shen, Mark G. Wallace. in Prolog ECLiPSe: A Tutorial Introduction. ECLi PSe Pro- http://eclipseclp.org/doc/tutorial/tutorial.html gramming Abderrahamane Aggoun et al. Interval Constraints ECLiPSe User Manual, Release 6.1. Library http://eclipseclp.org/doc/userman/umsroot.html Example Helmut Simonis. Summary ECLiPSE ELearning Website Literature http://4c.ucc.ie/~hsimonis/ELearning/index.htm

January 26, 2015 Becker-Asano, Nebel and Wölfl – Constraint Satisfaction Problems 100 / 100