View
246
Download
1
Embed Size (px)
Citation preview
11 November 2005 Foundations of Logic and Constraint Programming 1
Constraint (Logic) Programming
Anoverview
• ExamplesofConstraintDomains
• Constraint(Logic)Programming
• OperationalSemanticsofCLP
• ModellinginCLP
[Dech04]RinaDechter,ConstraintProcessing,
11 November 2005 Foundations of Logic and Constraint Programming 2
Constraints and Constraint Problems
- Formallyaconstraint(solving)problemcanberegardedasatuple<V,D,C>,
where
- X={X1,...,Xn}isasetofvariables
- D={D1,...,Dn}isasetofdomains(forthecorrespondingvariables)
- C={C1,...,Cm}isasetofconstraints(onthevariables)
- Solving a constraint problem consists of determining values xi Di for each
variableXi,satisfyingalltheconstraintsC.
- Intuitively,aconstraintCiisalimitationonthevaluesofitsvariables.
- More formally, a constraint Ci (with arity k) over variables Xi1, ..., Xik ranging
overdomainsDi1,...,DikisasubsetofthecartesiancartesianDj1...Djk.
CiDj1...Djk
11 November 2005 Foundations of Logic and Constraint Programming 3
Constraint Problems: Examples
- Examplesoftheseproblemsinclude
ModellingofDigitalCircuits
ProductionPlanning
NetworkManagement
Scheduling(QualitativeandQuantitative)
Assignment(Colouring,Latin/MagicSqaures,Sudoku,Circuits,...)
AssignmentandScheduling(Timetabling,Job-shop)
FillingandContainment
SceneInterpretation
11 November 2005 Foundations of Logic and Constraint Programming 4
Modeling of Digital Circuits
Goal(Example):Determineatestpatternthatdetectssomefaultygate
Variables: Signalsinthecircuit
Domain: Booleans:0/1(orTrue/False,orHigh/Low)
Constraints: Equality constraints between the output of a gate and its “boolean
operation”(e.g.and,or,not,nand,...)
A
C
D
B
E
F
G
H
I
G1
G2
G3
G4
G5
E = or(A,B) % G1 F = nand(B,C) % G2G = and(B,C) % G3 H = nand(E,F) % G4I = nand(F,G) % G5
11 November 2005 Foundations of Logic and Constraint Programming 5
Production Planning
Goal(Example):Determineaproductionplan
Variables: Quantitiesofgoodstoproduce
Domain: Rational/RealsorIntegers
Constraints: EqualityandInequality(linear)constraintstomodelresourcelimitations,
minimal quantities toproduce, costsnot to exceed, balance conditions,etc...
Find X, Y and Z such that 4x+ 3y + 6z 1500 % resources used do not exceed 1500 x + y + z >= 300 % production not less than 300 units x z + 20 % x units within z 20 units x z - 20 x, y, z 0 % non negative production
11 November 2005 Foundations of Logic and Constraint Programming 6
Network Management
Goal(Example):Determineacceptabletrafficonanetwok
Variables: Flowsineachedge
Domain: Rational/Reals(orIntegers)
Constraints: Equalityand Inequality (linear)constraints tomodelcapacity limitations,
flowmaintenance,costs,etc...
Find x,y,z, a,b,c,d,e such that x 6, z 10 % minimum flow a 5, ... , f 6 % capacity% flow maintenance x = a, y = b + c, a + b + d = e, c = d + f, e + f = z x, y ,z, a, b, c, d, e, f 0
5/a
2/d8/e
6/f
3/b
7/c
x
y
z
11 November 2005 Foundations of Logic and Constraint Programming 7
Schedulling (Quantitative)
Goal(Example):Assigntiming/precedencetotasks
Variables: StartTimingofTasks,DurationofTasks
Domain: Rational/RealsorIntegers
Constraints: PrecedenceConstraints,Non-overlappingconstraints,Deadlines,etc...
Find Sa ,..., Se, such that Sb Sa+Ta, % precedence .... (Sc Sb+Tb) (Sb Sc+Tc) % non overlap ..., 6 Sa+Ta % deadline Sa,..., Se 0
Sa
Sc
Sb
Se
SdTa
Ta
Tb
Tc
Td
11 November 2005 Foundations of Logic and Constraint Programming 8
Schedulling (Qualitative)
Goal(Example):Completeassignmentoftaskrelations
Variables: Relationsbetweentasks(qualitative;e.gTapreceedesTb)
Domain: 16relations(preceeds,meets,overlap,....)
Constraints: Partialassignments
? What relation between C and D, given that A preceeds B, B preceeds C,
C meets EA preceeds D, D meets E,B overlaps D
A
D
B
E
C
11 November 2005 Foundations of Logic and Constraint Programming 9
Assignment
Manyconstraintproblemscanbeclassifiedasassignmentproblems. Ingeneral
allthatcanbestatedisthattheseproblemsfollowthegeneralgoalCSPs:Assign
valuestothevariablestosatisfytherelevantconstraints.
– Variables:
Objects/Propertiesofobjects
– Domain:
Integer,enumeratedorRealValues(properties-colours,numbers,..)
Booleansfordecisions
– Constraints:
Compatibility(Equality,Difference,No-attack,ArithmeticRelations)
Someexamplesmayhelptoillustratethisclassofproblems
11 November 2005 Foundations of Logic and Constraint Programming 10
Assignment (2)
AB
CD
E
F
Graph Colouring (Booleans)
Assign values to A1,A2, .., F1,F2
s.t. A1,A2, .., F1,F2 {0,1}% different colours for A and B
A1 B1 or A2 B2....
E1 F1 or E2 F2
AB
CD
E
F
Graph Colouring (Finite Domains)
Assign values to A, .., F,
s.t. A, B, .., F {red, blue, green}A B, A C, A D,B C, B F, C D, C E, C FD E, E F
11 November 2005 Foundations of Logic and Constraint Programming 11
Assignment (3)
Q1
Q2
Q3
Q4
N-queens (Finite Domains):
Assign Values to Q1,..., Qn {1,.., n}
s.t. ij noattack (Qi, Qj)
Latin Squares (similarto Sudoku):
Assign Values to X11,..., X33 {1,.., 3}
s.t. i jk Xij Xik % same row
j ik Xij Xkj % same column
X11 X12 X13
X21 X22 X23
X31 X32 X33
Magic Squares:
Assign Values to X11,..., X33 {1,..,9}
s.t. ij k Xki = Xkj % same rows sum
ij Sk Xik = Xjk % same cols sum
ik jl Xij Xkl % all different
X11 X12 X13
X21 X22 X23
X31 X32 X33
11 November 2005 Foundations of Logic and Constraint Programming 12
Assignment (3)
Travelling Salesperson (Finite Domains)
Find values for A, B, C, D {1,..,4} s.t. A B, ..., C D % a permutation of [A,B,C,D] if A = B+1 then XA = Lab, ... if D = C+1 then XD = Lcd
Xa + Xb + Xc + Xd K
A B
C D
23
18
33
17 1321
Travelling Salesperson (Booleans)
Find decision values for Xab...Xdc {0,1}
s.t. a k Xak = 1
a Sk Xka = 1
no subcycle constraints
ab Xab Lab < k
A B
C D
23
18
33
17 1321
11 November 2005 Foundations of Logic and Constraint Programming 13
Mixed: Assignment and Scheduling
Goal(Example):Assignvaluestovariables
Variables: StartTimes,Durations,Resourcesused
Domain: Integers(typicaly)orRationals/Reals
Constraints: Compatibility(Disjunctive,Difference,ArithmeticRelations)
Job-Shop
Assign values to Sij {1,..,n} % time slots
and to Mij {1,..,m} % machines available
% precedence within job
j i < k Sij + Dij ≤ Skj
% either no-overlap or different machines
i,j,k,l (Mij ≠ Mkl) (Sij + Dij ≤ Skl) (Skl + Dkl ≤ Sij)
J 1
J 2
J 3
J 4
1 2 3
1 2 3
1 2 3
1 2 3
11 November 2005 Foundations of Logic and Constraint Programming 14
Filling and Containment
Goal(Example):Assignvaluestovariables
Variables: PointLocations
Domain: Integers(typicaly)orRationals/Reals
Constraints: Non-overlapping(Disjunctive,Inequality)
Fiiling
Assign values to Xi {1,.., Xmax} % X-dimension
Yi {1,.., Ymax} % Y-dimension
% no-overlapping rectangles
i,j (Xi+Lxi Xj) % I to the left of J
(Xj+Lxj Xi) % I to the right of J
(Yi+Lyi Yj) % I in front of J
(Yj+Lxj Xi) % I in back of J
D
G
I
BCA
JH
E
FK
11 November 2005 Foundations of Logic and Constraint Programming 15
Scene Interpretation
Goal(Example):Assignvaluestojunctions
Variables: Junctions
Domain: JunctionTypes
Constraints: Compatibilityofjunctions
11 November 2005 Foundations of Logic and Constraint Programming 16
Constraint Programming
ConstraintProgrammingandLanguagesisdrivenbyanumberofgoals
- Expressivity
- Constraint Languages should be able to easily specify the variables,
domainsandconstraints(e.g.conditional,global,etc...);
- DeclarativeNature
- Ideally,programsshouldspecify theconstraints tobesolved,not the
algorithmsusedtosolvethem
- Efficiency
- Solutions should be found as efficiently as possile, i.e. With the
minimumpossibleuseofresources(timeandspace).
These goals are partially conficting goals and have led to the various
developmentsinthisresearchanddevelopmentarea.
11 November 2005 Foundations of Logic and Constraint Programming 17
Complexity of Constraint Problems
Assuming that a potential
solution can be generated
and tested in 1 μs, the
approximatetimesrequiredto
searchthewholespaceofthe
kn possible solutions isgiven
inthetable
This complexity is in sharp
constrast with the complexity
of deterministic problems
(such as sorting of lists,
matrix multiplication, etc,
which are polinomial on the
sizenofthestructures
10 20 30 40 50 60
2 1.0E-03 1.0E+00 1.1E+03 1.1E+06 1.1E+09 1.2E+12
3 5.9E-02 3.5E+03 2.1E+08 1.2E+13 7.2E+17 4.2E+22
4 1.0E+00 1.1E+06 1.2E+12 1.2E+18 1.3E+24 1.3E+30
5 9.8E+00 9.5E+07 9.3E+14 9.1E+21 8.9E+28 8.7E+35
6 6.0E+01 3.7E+09 2.2E+17 1.3E+25 8.1E+32 4.9E+40
n
k
nk
10 20 30 40 50 60
2 1.0E-04 4.0E-04 9.0E-04 1.6E-03 2.5E-03 3.6E-03
3 1.0E-03 8.0E-03 2.7E-02 6.4E-02 1.3E-01 2.2E-01
4 1.0E-02 1.6E-01 8.1E-01 2.6E+00 6.3E+00 1.3E+01
5 1.0E-01 3.2E+00 2.4E+01 1.0E+02 3.1E+02 7.8E+02
6 1.0E+00 6.4E+01 7.3E+02 4.1E+03 1.6E+04 4.7E+04
n
k
nk
1 hour = 3.6*103 ; 1 day = 8.6*104 ; 1 year = 3.1*107 ; age of universe = 4.7*1023
11 November 2005 Foundations of Logic and Constraint Programming 18
Complexity of Constraint Problems
Amajorissueinconstraintsolvingproblemsistheircomplexity.Ingeneralthese
arecombinatorialproblemswithanexponentialsearchspace.
- Booleans- NumberofVariables:n- Domaincardinality:2- Numberofpotentialsolutions:2n
- FiniteDomains- NumberofVariables:n- Domaincardinality:d- Numberofpotentialsolutions:dn
- Real/RationalDomains- NumberofVariables:n- Domaincardinality:Theoreticallyinfinite.Inpracticefinite,D,dueto
rounding.- Numberofpotentialsolutions:Dn
11 November 2005 Foundations of Logic and Constraint Programming 19
Constraint Problems are NP
Notwithstandingtheexponentialnumberofthesearchspace,onecouldexpect
thatinpracticesolutionsarefoundmuchquickerbysome“cleaver”procedure.
Nevertheless,mostdecisionproblemsofinterest,(e.g.thosedescribedbefore)
are NP–complete, i.e. they are of the same complexity of the Satisfiability
problemforBooleanClauses(SAT).
ThisequivalenceofSATandaproblemProb
isproveningeneralbythetransformation(in
polinomialtime)ofSATintoProb,andofProb
intoSAT.
Given this equivalence, if there was a procedure to solve SAT in polinomial
time,allNPproblemswouldbesolvedinpolinomialtimeaswell.
Unfortunately,noonehasever foundsuchprocedure ingeneral.Foragiven
procedure,ithasalwaysbeenpossibletofindinstancesofSATthataresolved
inexponentialtime.
Prob SAT
11 November 2005 Foundations of Logic and Constraint Programming 20
Constraint Problems are NP
NoticethattheNPnatureofthesedecisionproblemsdoesnotpreventthatfor
many problem instances it is possible to find efficient procedures to solve
them.
Inpractice,aproblem isNP-complete if it ispossible tocheckasolution in
polinomialtime(tofindasolutionmaytakeexponentialtime).
Decisionproblemslieinthiscategory,sincegivensomepotentialsolutionone
hasonlytocheckonebyone,alltheconstraints(anumberusuallyintheorder
ofmagnitudeofthevariables).
Optimisation problems are usually harder than decision ones, hence their
classificationas NP-Hard.
Herecheckingasolutionusuallyrequiresexponentialtime,sinceitrequiresto
compareallsolutions(andhencefindthem,whichrequiresexponentialtime).
11 November 2005 Foundations of Logic and Constraint Programming 21
Declarative Programming
Programmingacombinatorialproblemrequires
thespecificationoftheconstraintsoftheproblem
Thespecificationofasearchalgorithm
Theseparationof these twoaspectshas fora long timebeenadvocatedby
several programming paradigms, namely functional programming and logic
programming..
Logic programming in particular has a built in mechanism for search
(backtracking)thatmakesitagoodcandidatetoconstraintprogramming.
Maintaining its search mechanism, all that is required is to extend its
underlyingresolutiontoconstraint solving.
This is in factquitenatural,since resolutionmaybe regardedasaparticular
typeofconstraintsolving,namelytheequalityofHerbrandterms(trees),which
isperformedintheunificationofagoalandaclausehead.
11 November 2005 Foundations of Logic and Constraint Programming 22
Operational Semantics of CLP
TheoperationalsemanticsofConstraintLogicProgrammingcanbedescribed
asatransitionsystemonstates.
Thestateofaconstraintsolvingsystemcanbeabstractedbyatuple
< G, CS > where
Gisasetofconstraintsstilltosolve
CSistheConstraint Store:asetofconstraintsalreadyexamined
InLP,Gisthequery, i.e. thesetofgoalsstill tosolve.SetCSmaintainsthe
compositionofalltheunificationsperformedinthepreviousresolutionsteps.
Aderivationisjustasequenceoftransitions.
Astatethatcannotberewrittenisafinalstate.
An executor of (C)LP aims at finding successful final states of derivations
startingwithaquery.
11 November 2005 Foundations of Logic and Constraint Programming 23
State Transitions of CLP
Aderivationisfailedifitisfiniteanditsfinalstateisfail.
Aderivationissuccessfulifitisfiniteandprocessesalltheconstraints,i.e.it
endsinastatewithform<Ø, S >
Thestatetransitionsarethefollowing
S(elect): Selectagoal(constraint)
Itisassumedthat
A computation rule selects some goal g, among those still to be
consideredthatrequiressolvingofsomeconstraintc.
The set of unsolved goals is eventually augmented with set G’, with
additionalgoalstobefurtherconsidered.
g requires solving c and other goals G’
< G {g}, CS > s < G G’, CS {c} >
11 November 2005 Foundations of Logic and Constraint Programming 24
State Transitions of CLP
Theothertransitionrulesrequiretheexistenceoftwofunctions,infer(C,S)and
consistent(C),adequatetothedomainsthatareconsidered.
I(nfer): Processaconstraint,inferringitsconsequences
C(heck): ChecktheconsistencyoftheStore
CS’ = infer(CS {c})
< G, CS {c}) > i < G, CS’ >
consistent (CS)
< G, CS > c < G, CS >
¬ consistent (CS)
< G, CS > c fail
11 November 2005 Foundations of Logic and Constraint Programming 25
State Transitions of LP
InLogic Programming
HandlingagoalgissimplycheckingwhetherthereisaclauseH←Bwhose
head h matches the goal. In this case, the equality constraint between
Herbrandtermsg=hisaddedtothepassivestore.
Functioninfer(C,c)performsunificationofthetermsincludedingandh,after
applyingallsubstitutionsincludedinC
function infer(, g=h) if unify(g,h , ) then infer = (success, )
else infer = (fail,_); end function
Checking consistency is a simple check on whether the previous unification
hasreturnedsuccessorfailure(inpracticethetwofunctionsaremerged).
g is a goal h B < G {g}, CS > s < G B, CS {h = g} >
11 November 2005 Foundations of Logic and Constraint Programming 26
State Transitions of LP: Example
Forexample,assumingthat
CS = {X / f(Z), Y / g(Z,W)} % a solved form
G includesgoal p(Z,W)
thereisaclause p(a,b) :- B.
thenthefollowingtransitionstakeplace,whengoalp(Z,W) is“called”
< G , {X/f(Z), Y/g(Z,W)} >
→s %goalselection
< G \ {g} B, {X/f(Z), Y/g(Z,W)} {p(Z,W) = p(a,b)}} >
→i,c %unification(inferenceandconsistencycheck)
< G \ {g} B, {X/f(a), Y/g(a,b), Z/a, W/b} >
11 November 2005 Foundations of Logic and Constraint Programming 27
State Transitions of CLP
InConstraint Logic Programming
Handling a goal g is as before. Handling a constraint in a certain domain,usuallybuilt-in,simplyplacestheconstraintinsetCS.
.
Function infer(C,S) propagates the constraint in the Constraint Store, bymethodsthatdependontheconstraintsystemused.Tipically,
Itattemptstoreducethevaluesinthedomainsofthevariables;or
obtainanewsolvedform(likeinunification)
Checkingconsistencyalsodependsontheconstraintsystem.
Itcheckswhetheradomainhasbecomeempty;or
Whetheritwasnotpossibletoobtainasolvedform.
g is a constraint< G {g}, CS > s < G, CS {g} >
11 November 2005 Foundations of Logic and Constraint Programming 28
State Transitions of CLP: Example (1)
A positive example
Assuming thatvariablesAandBcan takevalues in1..3, then theconstraint
storemayberepresentedas
CS = {A in 1..3, B in 1..3}
Rule S:IftheconstraintselectedbyruleSisA > B,thenthestorebecomes
CS = {A in 1..3, B in 1..3} {A > B}
Rule I:TheInferrulepropagatesthisconstraint intheconstraintstore,which
becomes
C,S = {A in 2..3, B in 1..2, A > B}
Rule C:Thesystemdoesnotfindanyinconsitencyintheactivestore,sothe
systemdoesnotchange.
11 November 2005 Foundations of Logic and Constraint Programming 29
State Transitions of CLP: Example (2)
A negative example
Assuming that variables A and B can take, respectively values in the sets
{1,3,5}and{2,4,6}.Theconstraintstoremayberepresentedas
CS = { A in {1,3,5} B in {2,4,6} }
Rule S:IftheconstraintselectedbyruleSisA = B,thestorebecomes
CS = { A in {1,3,5} B in {2,4,6} } { A = B }
Rule I:Therulepropagatesthisconstrainttotheactivestore.Sincenovalues
arecommontoAandB,theirdomainsbecomeempty
CS = {A in {}, B in {} }
Rule C: This rule finds the empty domains and makes the transition to fail
(signaling the system to backtrack in order to find alternative successful
derivations).
11 November 2005 Foundations of Logic and Constraint Programming 30
Solutions in (C)LP
InLPandCLP,solutionsareobtained,byinspectingtheconstraintstoreofthe
finalstateofasuccessfulderivation.
Insystems thatmaintainasolved form, (likeLP,butalsoconstraintsystems
CLP(B) for booleans, and CLP(Q), for rationals), solutions are obtained by
projectionofthestoretotherelevantvariables.
Forexampleiftheinitialgoalwasp(X,Y)andthefinalstoreis
{X/f(Z,a), Y/g(a,b), W/c}
thenthesolutionistheprojectiontovariablesXandY
{X/f(Z,a), Y/g(a,b), W/c}
In systems where a solved form is not maintained, solutions require some
formofenumeration.Forexample,from
C = {X in 2..3, Y in 1..2, X > Y},
the solutions <X=2;Y=1>, <X=3;Y=1> and <X=3;Y=1>, are obtained by
enumeration.
11 November 2005 Foundations of Logic and Constraint Programming 31
The CLP approach to Constraint Solving
ToprogramaconstraintsolvingprobleminCLPanumberof issuesmustbe
takenintoaccount
• Whatisthepurposeoftheprogram?
• Any(first)solution?
• Allsolutions?(decisionmakingwithuncertainty)
• BestSolution?(optimisation)
• Whatkindofmodeling?
• VariablesandDomains?(FiniteDomains?Booleans?Sets?Mixed?)
• Constraints?(Global?Redundant?)
• Whatsolvershouldbeused?
• CompleteSolver?(Allsolutions,inneficiency?)
• Incompletesolvers?(Singlesolutions,Heuristics?)
Anexample,N-queens,willillustratesomeoftheseissues.
11 November 2005 Foundations of Logic and Constraint Programming 32
N-Queens
TheN-queensproblemconsistsoffindingpositionsforN
queensinaNNchess-board,sothatno2queensattack
eachother.
Modeling:
BooleanVariables:One0/1variableforeachpositionoftheboard
SATorarithmeticconstraints?
FiniteDomains:One1..Nvariableforeachrowintheboard
Solvers:
Complete(onlyforBooleans):
maintainsallsolutions
Incomplete:Booleans/FiniteDomains:
Onesolutionatatime
Inthiscasethereisnoclearoptimisationpurpose(functiontooptimise)
11 November 2005 Foundations of Logic and Constraint Programming 33
N-Queens Models
AssumingBooleanvariables,Xij(i,j1..n),oneperposition
• Constraints
• OneperRow(Onepercolumnissimilar)
• SAT: Xij \/ ...\/ Xin foralli1..n
• Xij \/ Xikforalli,jk1..n
• Arithmetic: Xij + ...+ Xin = 1 foralli1..n
• Diagonals
• SAT: Xij \/ Xklforalli+j=k+landalli-j=k-l
• Arithmetic: ij Xij 1 forallij=k-2n-1..2n+1
• AssumingFiniteDomainvariables,Xi(i1..n),),oneperrow
• Constraints(oneperrowisimplicit)
• OneperColumn Xi Xjforallij1..n
• Diagonals: Xi Xj foralli+j=k-2n-1..2n+1
11 November 2005 Foundations of Logic and Constraint Programming 34
CLP Programs
CLPprogramshaveingeneralthefollowingstructure
Program
• VariableDeclaration%notneededincompletesolvers
• ConstraintDeclaration
• Search % optional in all solutions/complete
solvers
In general, CLP systems require the addition of modules that implement the
intendedsolvers.ForexampleinSICStus
:- use_module(library(clpb)). thecompletesolverforbooleans
:- use_module(library(clpfd)). Thesolverforfinitedomains
Suchsolversidentifyconstraintsandgoalswithadifferentsyntax sat(X+Y =:= 1)implementsan“OR”ofbooleanvariablesXandY X+Y #= 3enforcesthesumofFDvariablesXandYtobe3
Intherest,CLPprogramsadoptthesyntaxofLP(Prolog)
11 November 2005 Foundations of Logic and Constraint Programming 35
Boolean N-Queens: Complete Solver
Forsimplicity,weshowthe3-queensprogram.Itcanbeeasily
adaptedforlargerboards(3-queenshasnosolutions).
:- clpb.
queens_3(Q):- Q = [Q11, Q12, Q13, Q21, Q22, Q23, Q31, Q32, Q33],
% one and only one queen per row sat(Q11+Q12+Q13 =:= 1),sat(Q11*Q12=:=0),sat(Q11*Q13=:=0),sat(Q12*Q13=:=0), sat(Q21+Q22+Q23 =:= 1),sat(Q21*Q22=:=0),sat(Q21*Q23=:=0),sat(Q22*Q23=:=0), sat(Q31+Q32+Q33 =:= 1),sat(Q31*Q32=:=0),sat(Q31*Q33=:=0),sat(Q32*Q33=:=0),
% one and only one queen per column sat(Q11+Q21+Q31 =:= 1),sat(Q11*Q21=:=0),sat(Q11*Q31=:=0),sat(Q21*Q31=:=0), sat(Q12+Q22+Q32 =:= 1),sat(Q12*Q22=:=0),sat(Q12*Q32=:=0),sat(Q22*Q32=:=0), sat(Q13+Q23+Q33 =:= 1),sat(Q13*Q23=:=0),sat(Q13*Q33=:=0),sat(Q23*Q33=:=0),
% no two queens in \ diagonals sat(Q11*Q22=:=0),sat(Q11*Q33=:=0),sat(Q22*Q32=:=0), sat(Q12*Q23=:=0),sat(Q21*Q32=:=0),
% no two queens in \ diagonals sat(Q13*Q22=:=0),sat(Q13*Q31=:=0),sat(Q22*Q31=:=0), sat(Q12*Q21=:=0),sat(Q23*Q32=:=0).
11 November 2005 Foundations of Logic and Constraint Programming 36
Boolean N-Queens: SAT Solver
The3-queensprograminSATisshownwithuser-defined
operators(“\/”and“~”),implementedintheFDsolver.
:- op(300,fy,~).:- op(400,xfy,\/).
:- clpfd.
queens_3(Q):-
% variable declaration Q = [Q11, Q12, Q13, Q21, Q22, Q23, Q31, Q32, Q33], domain(Q,0,1),
% one and only one queen per row Q11 \/ Q12\/ Q13, ~Q11 \/ ~Q12, ~Q11 \/ ~Q13, ~Q12 \/ ~Q13, Q21 \/ Q22\/ Q23, ~Q21 \/ ~Q22, ~Q21 \/ ~Q23, ~Q22 \/ ~Q23, Q31 \/ Q32\/ Q33, ~Q31 \/ ~Q32, ~Q31 \/ ~Q33, ~Q32 \/ ~Q33,
% one and only one queen per column Q11 \/ Q21\/ Q31, ~Q11 \/ ~Q21, ~Q11 \/ ~Q31, ~Q21 \/ ~Q31, Q12 \/ Q22\/ Q32, ~Q12 \/ ~Q22, ~Q12 \/ ~Q32, ~Q22 \/ ~Q32, Q13 \/ Q23\/ Q33, ~Q13 \/ ~Q23, ~Q13 \/ ~Q33, ~Q23 \/ ~Q33,
% no two queens in \ diagonals ~Q11 \/ ~Q22, ~Q11 \/ ~Q33, ~Q22 \/ ~Q33, ~Q12 \/ ~Q23, ~Q21 \/ ~Q32,
% no two queens in / diagonals ~Q13 \/ ~Q22, ~Q13 \/ ~Q31, ~Q22 \/ ~Q31, ~Q12 \/ ~Q21, ~Q23 \/ ~Q32,
% enumeration (search) labeling([], Q).
11 November 2005 Foundations of Logic and Constraint Programming 37
Boolean N-Queens: Arithmetic Solver
The3-queensprogramwithbooleanvariablesmaybemore
easilyexpressedwitharithmeticconstraints.
:- op(300,fy,~).:- op(400,xfy,\/).:- clpfd. queens_3(Q):-
% variable declaration Q = [Q11, Q12, Q13, Q21, Q22, Q23, Q31, Q32, Q33], domain(Q,0,1),
% one and only one queen per row Q11 + Q12 + Q13 #= 1, Q21 + Q22 + Q23 #= 1, Q31 + Q32 + Q33 #= 1,
% one and only one queen per column Q11 + Q21 + Q31 #= 1, Q12 + Q22 + Q32 #= 1, Q13 + Q23 + Q33 #= 1,
% no two queens in \ diagonals Q11+Q21 #=<1, Q11+Q33 #=<1, Q22+Q33 #=<1, Q12+Q23 #=<1, Q21+Q32 #=<1,
% no two queens in / diagonals Q13+Q22 #=<1, Q13+Q31 #=<1, Q22+Q31 #=<1, Q12+Q21 #=<1, Q23+Q32 #=<1,
% enumeration (search) labeling([], Q).
11 November 2005 Foundations of Logic and Constraint Programming 38
Finite Domains N-Queens
The3-queensprograminFDismuchsimpler,since
withmuchlessvariables.
:- clpfd.
queens_3(Q):-
% declaration of variables Q = [Q1,Q2,Q3], % only one queen in each row domain(Q,1,3),
% one and only queen in each column Q1 #\= Q2, Q2 #\=Q3, Q1 #\= Q3,
% no two queens in \ diagonals Q1+1 #\= Q2+2, Q1+1 #\= Q3+3, Q2+2 #\= Q3+3,
% no two queens in / diagonals Q1-1 #\= Q2-2, Q1-1 #\= Q3-3, Q2-2 #\= Q3-3,
% enumeration (search) labeling([],Q).
11 November 2005 Foundations of Logic and Constraint Programming 39
Finite Domains N-Queens
Ofcourse,alltheseproblemsmaybegeneralisedforanarbitrary.
sizeoftheboard,usingalltheconstructsofProlog,namelylists.
ThisisthecasewiththeFDmodel,shownbelow.
:-clpfd.
queens_fd(N,Future):- create_vars(N,Future-[]), domainQ(N,Future), compatible([],Future), enumerate(Futuras).
create_vars(0,Z-Z):- !.create_vars(N,L-Z):- M is N-1, create_vars(M,L-[N-_|Z]).
domainQ(_,[]).domainQ(N,[_-C|Variables]):- C in 1 .. N, domainQ(N,Variables).
compatible(_,[]).compatible(Past,[L-C|Future]):- compatible_1(L-C,Future), compatible([L-C|Past], Future).
compatible_1(_,[]).compatible_1(L1-C1,[L2-C2|T]):- no_atack(L1,C1,L2,C2), compatible_1(L1-C1,T).
no_atack(L1,C1,L2,C2):- C1 #\= C2, L1 + C1 #\= L2 + C2, L1 + C2 #\= L2 + C1.
enumerate(Future):- clean(Future,L), labeling([ff],L).
clean([],[]).clean([_-C|T1],[C|T]):- clean(T1,T).