1% BEGIN LICENSE BLOCK
2% Version: CMPL 1.1
3%
4% The contents of this file are subject to the Cisco-style Mozilla Public
5% License Version 1.1 (the "License"); you may not use this file except
6% in compliance with the License.  You may obtain a copy of the License
7% at www.eclipse-clp.org/license.
8% 
9% Software distributed under the License is distributed on an "AS IS"
10% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.  See
11% the License for the specific language governing rights and limitations
12% under the License. 
13% 
14% The Original Code is  The ECLiPSe Constraint Logic Programming System. 
15% The Initial Developer of the Original Code is  Cisco Systems, Inc. 
16% Portions created by the Initial Developer are
17% Copyright (C) 2006 Cisco Systems, Inc.  All Rights Reserved.
18% 
19% Contributor(s): 
20% 
21% END LICENSE BLOCK
22
23%\documentstyle[11pt,html,a4wide,epsf,ae,aecompl]{book}
24\documentclass[11pt,a4paper]{book}
25\usepackage{hevea}
26\usepackage{alltt}
27\usepackage{graphics}
28%\usepackage{html}
29\usepackage{ae}
30\usepackage{aecompl}
31\usepackage{makeidx}
32\usepackage{tocbibind}
33
34% Don't use a style file for sepiachip because latex2html ignores it
35
36\usepackage{../texinputs/eclipse}
37\input{../texinputs/sepiachiphtml}
38
39
40\makeindex
41
42\title{{\Huge \eclipse\ Obsolete Libraries Manual}\\
43	\vspace{1cm}
44	Release \eclipseversion
45    }
46\author{
47Pascal Brisset
48\and Hani El Sakkout
49\and Thom Fr\"{u}hwirth
50\and Carmen Gervet
51\and Warwick Harvey
52\and Micha Meier
53\and Stefano Novello
54\and Thierry Le Provost
55\and Joachim Schimpf
56\and Kish Shen
57\and Mark Wallace}
58
59\begin{document}
60
61\maketitle
62
63% Needed to adjust left/right pages properly
64\setcounter{page}{2}
65% Suppress printing of the page number on this page
66\pagestyle{empty}
67
68\vfill
69
70\copyright\ 1990 -- 2006 Cisco Systems, Inc.
71
72\bigskip\bigskip\bigskip\bigskip\bigskip\bigskip
73
74%--------------------------------------------------------------
75\cleardoublepage
76\pagestyle{plain}
77\pagenumbering{roman}
78
79\begin{latexonly}
80\tableofcontents
81\end{latexonly}
82
83%--------------------------------------------------------------
84\cleardoublepage
85\pagenumbering{arabic}
86
87\chapter{Introduction}
88This manual contains documentation for libraries which are still part
89of the \eclipse\ distribution, but whose use is deprecated.
90Typically, the libraries have been replaced by newer implementation which
91provide similar or extended functionality.
92The old documentation is provided here mainly to ease the task of porting
93existing code to the newer libraries. Documentation for the new libraries
94can be found in the {\em Constraint Library Manual} and the {\em Reference Manual}.
95Here is a short overview of the obsolete libraries and where to find
96replacement functionality:
97\begin{description}
98\item[fd] The numeric functionality of the finite-domain library is
99    subsumed by the {\bf ic} interval solver library.
100    The symbolic domain constraints are provided by the {\bf ic_symbolic}
101    library.
102    The branch-and-bound functionality can now be found in more generic
103    form in the {\bf branch_and_bound} library.
104\item[conjunto] Most of this set solver's functionality is available in the
105    new {\bf ic_sets} library.
106\item[ic_eplex, range_eplex] These libraries have now been removed and
107  replaced by standalone eplex. Chapter@\ref{eplexstandalone} describes how
108  to port your existing code from ic/range eplex to standalone eplex. 
109
110\end{description}
111
112\input{extfd}
113
114\input{extconjunto}
115
116\chapter{Porting to Standalone Eplex}
117\label{eplexstandalone}
118\input{eplexdiff}
119
120
121\newpage
122\printindex
123\newpage
124\bibliography{sepiachip}
125\bibliographystyle{plain}
126\end{document}
127%
128% W% 96/01/08 
129%
130% Author:        Micha Meier
131%
132
133\addtocounter{secnumdepth}{2}
134\chapter{The Finite Domains Library}
135\label{chapdomains}
136\index{library!fd.pl|(}
137
138The library {\bf fd.pl}
139implements constraints over finite domains that can contain
140integer as well as atomic (i.e.\ atoms, strings, floats, etc.)
141and ground compound (e.g.\ {\it f(a, b)})
142elements.
143Modules that use the library must start with the directive
144\begin{quote}
145{\bf :- use_module(library(fd)).}
146\end{quote}
147
148\section{Terminology}
149Some of the terms frequently used in this chapter are explained below.
150\begin{description}
151\item[domain variable]
152\index{domain variable!definition}
153A domain variable is a variable which can be instantiated only
154to a value from a given finite set.
155Unification with a term outside of this domain fails.
156The domain can be associated with the variable using the predicate 
157\biptxtref{::/2}{fd:(::)/2}{../bips/lib/fd/NN-2.html}.
158Built-in predicates that expect domain variables
159treat atomic and other ground terms as variables with singleton domains.
160
161\item[integer domain variable]
162\index{domain variable!integer}
163An integer domain variable is a domain variable
164whose domain contains only integer numbers.
165Only such variables are accepted in inequality constraints
166and in rational terms.
167Note that a non-integer domain variable can become
168an integer domain variable when the non-integer values
169are removed from its domain.
170
171\item[integer interval]
172An integer interval is written as
173\begin{center}
174{\it Min .. Max}
175\end{center}
176with integer expressions
177{\it $Min \leq Max$}
178and it represents
179the set
180\begin{center}
181\{Min, Min + 1, \ldots, Max\}.
182\end{center}
183
184\item[linear term]
185A linear term is a linear integer combination of integer domain variables.
186The constraint predicates accept linear terms even in a non-canonical form,
187containing functors +, - and *,
188e.g.\
189\begin{center}
190$5*(3+(4-6)*Y-X*3)$.
191\end{center}
192If the constraint predicates encounter 
193a variable without a domain, they
194give it a default domain -10000000..10000000.
195\index{domain!default}
196Note that arithmetic operations on linear terms are performed
197with standard machine word integers without any overflow checks.
198If the domain ranges or coefficients are too large,
199the operation will not yield correct results.
200Both the maximum and minimum value of a linear term must
201be representable in a machine word, and so must
202the maximum and minimum value of every
203\begin{latexonly}
204\enableunderscores
205${\it c_i x_i}$
206\disableunderscores
207\end{latexonly}
208\begin{htmlonly}
209${\it c_i x_i}$
210\end{htmlonly}
211term.
212
213\item[rational term]
214A rational term is a term constructed from integers and integer
215domain variables using the arithmetic operations
216${\bf +, -, *, /}$.
217Besides that, every subexpression of the form {\it VarA/VarB} must have
218an integer value in the solution.
219The system replaces such a subexpression by a new variable {\it X}
220and adds a new constraint {\it VarA \#= VarB * X}.
221Similarly, all subexpressions of the form {\it VarA*VarB}
222are replaced by a new variable {\it X}
223and a new constraint {\it X \#= VarA * VarB} is added,
224so that in the internal representation, the term is converted
225to a linear term.
226
227\item[constraint expression]
228A constraint expression is either an arithmetic constraint
229or a combination of constraint expressions using the
230logical FD connectives
231{\bf \#\andsy/2, \#\orsy/2, \#=\gt/2, \#\lt=\gt/2, \#\bsl+/1}.
232%\begin{latexonly}
233%${\bf \#/\backslash/2, \#\backslash//2,
234%\#=>/2, \#<=>/2, \#\backslash+/1}$.
235%\end{latexonly}
236%\html{
237%{\bf #/\verb+\+/2, #\verb+\/+/2,
238%#=>/2, #<=>/2, #\verb+\++/1}.
239%}
240%{\bf \#/\verb+\+/2, \#\verb+\/+/2,
241%\#=>/2, \#<=>/2, \#\verb+\++/1}.
242\end{description}
243
244%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
245\section{Constraint Predicates}
246\begin{description}
247\item[] \biptxtref{?Vars :: ?Domain}{fd:(::)/2}{../bips/lib/fd/NN-2.html}\ \\
248\index{::/2!fd}
249\index{domain variable!creation}
250{\it Vars} is a variable or a list of variables
251with the associated domain {\it Domain}.
252{\it Domain} can be a closed integer interval denoted as {\it Min .. Max},
253or a list of intervals and/or atomic or ground elements.
254Although the domain can contain any compound terms that contain
255no variable,
256the functor {\it ../2} is reserved to denote integer intervals
257and thus {\it 1..10} always means an interval and {\it a..b}
258is not accepted as a compound domain element.
259
260If {\it Vars} is already a domain variable, its domain will be updated
261according to the new domain; if it is instantiated, the predicate checks
262if the value lies in the domain.
263Otherwise, if {\it Vars} is a free variable, it is converted to a domain
264variable.
265If {\it Vars} is a domain variable and {\it Domain} is free,
266it is bound to the list of elements and integer intervals
267representing the domain of the variable
268(see also \bipref{dvar_domain/2}{../bips/lib/fd/dvar_domain-2.html} which returns the actual domain).
269
270When a free variable obtains a finite domain or when the domain
271of a domain variable is updated, the {\bf constrained}
272list of its {\bf suspend} attribute is woken, if it has one.
273\index{suspension list!constrained}
274
275\item[] \biptxtref{integers(+Vars)}{fd:integers/1}{../bips/lib/fd/integers-1.html}\ \\
276\index{integers/1!fd}
277This constrains the list of variables Vars to have integer domains. Any
278non-domain variables in Vars will be given the default integer domain.
279
280\item[] \biptxtref{::(?Var, ?Domain, ?B)}{fd:(::)/3}{../bips/lib/fd/NN-3.html}\ \\
281\index{::/3!fd}
282{\it B} is equal to 1 iff the domain of the finite domain variable {\it Var}
283is a subset of {\it Domain} and 0 otherwise.
284
285\item[] \biptxtref{atmost(+Number, ?List, +Val)}{fd:atmost/3}{../bips/lib/fd/atmost-3.html}\ \\
286\index{atmost/3}
287At most {\it Number} elements of the list {\it List} of domain variables
288and ground terms are equal to the ground value {\it Val}.
289
290\item[] \biptxtref{constraints_number(+DVar, -Number)}{constraints_number/2}{../bips/lib/fd/constraints_number-2.html}\ \\
291\index{constraints_number/2}
292{\it Number} is the number of constraints and suspended goals
293currently attached to the variable {\it DVar}.
294Note that this number may not correspond to the exact number
295of {\it different} constraints attached to {\it DVar}, as goals
296in different suspending lists are counted separately.
297This predicate is often used when looking for the most or least constrained
298variable from a set of domain variables (see also \bipref{deleteffc/3}{../bips/lib/fd/deleteffc-3.html}).
299
300\item[] \biptxtref{element(?Index, +List, ?Value)}{fd:element/3}{../bips/lib/fd/element-3.html}\ \\
301\index{element/3}
302The {\it Index}'th element of the ground list {\it List}
303is equal to {\it Value}.
304{\it Index} and {\it Value} can be either plain variables,
305in which case a domain will be associated to them, or domain variables.
306Whenever the domain of {\it Index} or {\it Value} is updated,
307the predicate is woken and the domains are updated accordingly.
308
309\item[] \biptxtref{fd\_eval(+E)}{fd:fd_eval/1}{../bips/lib/fd/fd_eval-1.html}\ \\
310\index{fd\_eval/1}
311The constraint expression {\it E} is evaluated on runtime
312and no compile-time processing is performed.
313This might be necessary in the situations where the
314default compile-time transformation of the given expression
315is not suitable, e.g.\ because it would require type or mode information.
316
317\item[] \biptxtref{indomain(+DVar)}{fd:indomain/1}{../bips/lib/fd/indomain-1.html}\ \\
318\index{indomain/1}
319This predicate instantiates the domain variable {\it DVar} to 
320an element of its domain; on backtracking the subsequent values are taken.
321It is used, for example, to find a value of {\it DVar} which is consistent
322with all currently imposed constraints.
323If {\it DVar} is a ground term, it succeeds.
324Otherwise, if it is not a domain variable, an error is raised.
325
326\item[] \biptxtref{is_domain(?Term)}{fd:is_domain/1}{../bips/lib/fd/is_domain-1.html}\ \\
327\index{is_domain/1}
328Succeeds if {\it Term} is a domain variable.
329
330\item[] \biptxtref{is_integer_domain(?Term)}{fd:is_integer_domain/1}{../bips/lib/fd/is_integer_domain-1.html}\ \\
331\index{is_integer_domain/1}
332Succeeds if {\it Term} is an integer domain variable.
333
334\item[] \biptxtref{min_max(+Goal, ?C)}{fd:min_max/2}{../bips/lib/fd/min_max-2.html}\ \\
335\index{min_max/2}
336If {\it C} is a linear term,
337a solution of the goal {\it Goal} is found that minimises the
338value of {\it C}.
339If {\it C} is a list of linear terms, the returned solution
340minimises the maximum value of terms in the list.
341The solution is found using the {\it branch and bound} method;
342as soon as a partial solution is found that is worse than a previously
343found solution, failure is forced and a new solution is searched for.
344When a new better solution is found, the bound is updated and
345the search restarts from the beginning.
346Each time a new better solution is found, the event 280 is raised.
347If a solution does not make {\it C} ground, an error is raised,
348unless exactly one variable in the list {\it C} remains free,
349in which case the system tries to instantiate it to its minimum.
350
351\item[] \biptxtref{minimize(+Goal, ?Term)}{fd:minimize/2}{../bips/lib/fd/minimize-2.html}\ \\
352\index{minimize/2!fd}
353Similar to \bipref{min_max/2}{../bips/lib/fd/min_max-2.html}, but {\it Term} must be an integer domain variable.
354When a new better solution is found, the search does not restart
355from the beginning, but a failure is forced and the search continues.
356Each time a new better solution is found, the event 280 is raised.
357Often \bipref{minimize/2}{../bips/lib/fd/minimize-2.html} is faster than \bipref{min_max/2}{../bips/lib/fd/min_max-2.html}, sometimes
358\bipref{min_max/2}{../bips/lib/fd/min_max-2.html} might run faster, but it is difficult to predict 
359which one is more appropriate for a given problem.
360
361\item[] \biptxtref{min_max(+Goal, ?Template, ?Solution, ?C)}{fd:min_max/4}{../bips/lib/fd/min_max-4.html}
362\item[] \biptxtref{minimize(+Goal, ?Template, ?Solution, ?Term)}{fd:minimize/4}{../bips/lib/fd/minimize-4.html}\ \\
363\index{min_max/4}
364\index{minimize/4}
365Similar to \bipref{min_max/2}{../bips/lib/fd/min_max-2.html}
366and \bipref{minimize/2}{../bips/lib/fd/minimize-2.html},
367but the variables in {\it Goal} do not get
368instantiated to their optimum solutions. Instead, {\it Solutions} will
369be unified with a copy of {\it Template} where the variables are replaced
370with their minimized values.  Typically, the template will contain
371all or a subset of {\it Goal}'s variables.
372
373\item[] \biptxtref{min_max(+Goal, ?C, +Low, +High, +Percent)}{fd:min_max/5}{../bips/lib/fd/min_max-5.html}
374\item[] \biptxtref{minimize(+Goal, ?Term, +Low, +High, +Percent)}{fd:minimize/5}{../bips/lib/fd/minimize-5.html}\ \\
375\index{min_max/5}
376\index{minimize/5}
377Similar to \bipref{min_max/2}{../bips/lib/fd/min_max-2.html}
378and \bipref{minimize/2}{../bips/lib/fd/minimize-2.html},
379however the branch and bound method
380starts with the assumption that the value to be minimised is less than
381or equal to {\it High}.
382Moreover, as soon as a solution is found
383whose minimised value is less than {\it Low}, this solution is returned.
384Solutions within the range of {\it Percent} \% are considered
385equivalent and so the search for next better solution starts
386with a minimised value {\it Percent} \% less than the previously found one.
387{\it Low}, {\it High} and {\it Percent} must be integers.
388
389\item[] \biptxtref{min_max(+Goal, ?C, +Low, +High, +Percent, +Timeout)}{fd:min_max/6}{../bips/lib/fd/min_max-6.html}
390\item[] \biptxtref{minimize(+Goal, ?Term, +Low, +High, +Percent, +Timeout)}{fd:minimize/6}{../bips/lib/fd/minimize-6.html}\ \\
391\index{min_max/6}
392\index{minimize/6}
393Similar to \bipref{min_max/5}{../bips/lib/fd/min_max-5.html}
394and \bipref{minimize/5}{../bips/lib/fd/minimize-5.html},
395but after {\it Timeout} seconds
396the search is aborted and the best solution found so far is
397returned.
398
399\item[] \biptxtref{min_max(+Goal, ?Template, ?Solution, ?C, +Low, +High, +Percent, +Timeout)}{fd:min_max/8}{../bips/lib/fd/min_max-8.html}
400\item[] \biptxtref{minimize(+Goal, ?Template, ?Solution, ?Term, +Low, +High, +Percent, +Timeout)}{fd:minimize/8}{../bips/lib/fd/minimize-8.html}\ \\
401\index{min_max/8}
402\index{minimize/8}
403The most general variants of the above, with all the optinal parameters.
404
405\end{description}
406
407%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
408\section{Arithmetic Constraint Predicates}
409\begin{description}
410%\latex{
411%\item[?T1 \#$\backslash$= ?T2]
412%}\html{
413%\item[?T1 \#\verb+\+= ?T2]
414\item[?T1 \#\bsl= ?T2]
415%}
416\index{\#\bsl=/2}
417The value of the rational term {\it T1} is not equal to the value of the
418rational term {\it T2}.
419
420\item[?T1 \#$<$ ?T2]
421\index{\#$<$/2!fd}
422The value of the rational term {\it T1} is less than the value of the
423rational term {\it T2}.
424
425\item[?T1 \#$<$= ?T2]
426\index{\#$<$=/2!fd}
427The value of the rational term {\it T1} is less than or equal to the value of the
428rational term {\it T2}.
429
430\item[?T1 \#= ?T2]
431\index{\#=/2!fd}
432The value of the rational term {\it T1} is equal to the
433value of the rational term {\it T2}.
434
435\item[?T1 \#$>$ ?T2]
436\index{\#$>$/2!fd}
437The value of the rational term {\it T1} is greater than the
438value of the rational term {\it T2}.
439
440\item[?T1 \#$>$= ?T2]
441\index{\#$>$=/2!fd}
442The value of the rational term {\it T1} is greater than or equal to the
443value of the rational term {\it T2}.
444
445\end{description}
446
447%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
448\section{Logical Constraint Predicates}
449The logical constraints can be used to combine simpler constraints
450and to build complex logical constraint expressions.
451These constraints are preprocessed by the system and transformed
452into a sequence of evaluation constraints and arithmetic constraints.
453The logical operators are declared with the following precedences:
454\begin{quote}
455\begin{verbatim}
456:- op(750, fy, #\+).
457:- op(760, yfx, #/\).
458:- op(770, yfx, #\/).
459:- op(780, yfx, #=>).
460:- op(790, yfx, #<=>).
461\end{verbatim}
462\end{quote}
463
464\begin{description}
465
466%\latex{
467%\item[\#$\backslash$+ +E1]
468%\index{\#$\backslash$+/1}
469%}\html{
470\item[\#\bsl+ +E1]
471\index{\#\bsl+/1}
472%}
473{\it E1} is false, i.e.\ the logical negation of the constraint
474expression {\it E1} is imposed.
475
476%\latex{
477%\item[+E1 \#/$\backslash$ +E2]
478%\index{\#/$\backslash$/2}
479%}\html{
480\item[+E1 \#\andsy +E2]
481\index{\#\andsy/2}
482%}
483Both constraint expressions {\it E1} and {\it E2} are true.
484This is equivalent to normal conjunction {\it (E1, E2)}.
485
486%\latex{
487%\item[+E1 \#$\backslash$/ +E2]
488%\index{\#$\backslash$//2}
489%}
490%\html{
491%\item[+E1 \#\verb+\/+ +E2]
492%\index{\#\verb+\/+/2}
493\item[+E1 \#\orsy +E2]
494\index{\#\orsy/2}
495%}
496At least one of constraint expressions {\it E1} and {\it E2} is true.
497As soon as one of {\it E1} or {\it E2} becomes false, the other constraint
498is imposed.
499
500\item[+E1 \#=$>$ +E2]
501\index{\#=$>$/2}
502The constraint expression {\it E1} implies the
503constraint expression {\it E2}.
504If {\it E1} becomes true, then {\it E2} is imposed.
505If {\it E2} becomes false, then the negation of {\it E1}
506will be imposed.
507
508\item[+E1 \#$<$=$>$ +E2]
509\index{\#$<$=$>$/2}
510The constraint expression {\it E1} is equivalent to the
511constraint expression {\it E2}.
512If one expression becomes true, the other one will be imposed.
513If one expression becomes false, the negation of the other one will be imposed.
514\end{description}
515
516%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
517\section{Evaluation Constraint Predicates}
518These constraint predicates evaluate the given constraint expression
519and associate its truth value with a boolean variable.
520They can be very useful for defining more complex constraints.
521They can be used both to test entailment of a constraint
522and to impose a constraint or its negation on the current constraint store.
523
524\begin{description}
525\item[?B isd +Expr]
526\index{isd/2}
527{\it B} is equal to 1 iff
528the constraint expression {\it Expr} is true, 0 otherwise.
529This predicate is the constraint counterpart of \bipref{is/2}{../bips/kernel/arithmetic/is-2.html} ---
530it takes a constraint expression, transforms all its subexpressions
531into calls to predicates with arity one higher and combines
532the resulting boolean values to yield {\it B}.
533For instance,
534\begin{quote}
535{\bf B isd X \#= Y}
536\end{quote}
537is equivalent to
538\begin{quote}
539{\bf \#=(X, Y, B)}
540\end{quote}
541
542\item[\#$<$(?T1, ?T2, ?B)]
543\index{\#$<$/3!fd}
544{\it B} is equal to 1 iff
545the value of the rational term {\it T1} is less than the value of the
546rational term {\it T2}, 0 otherwise.
547
548\item[\#$<$=(?T1, ?T2, ?B)]
549\index{\#$<$=/3!fd}
550{\it B} is equal to 1 iff
551the value of the rational term {\it T1} is less than or equal to the value of the
552rational term {\it T2}, 0 otherwise.
553
554\item[\#=(?T1, ?T2, ?B)]
555\index{\#=/3!fd}
556{\it B} is equal to 1 iff
557the value of the rational term {\it T1} is equal to the
558value of the rational term {\it T2}, 0 otherwise.
559
560%\latex{
561%\item[\#$\backslash$=(?T1, ?T2, ?B)]
562%}
563%\html{
564\item[\#\bsl=(?T1, ?T2, ?B)]
565%}
566\index{\#\bsl=/3}
567{\it B} is equal to 1 iff
568the value of the rational term {\it T1} is different from the
569value of the rational term {\it T2}, 0 otherwise.
570
571\item[\#$>$(?T1, ?T2, ?B)]
572\index{\#$>$/3!fd}
573{\it B} is equal to 1 iff
574the value of the rational term {\it T1} is greater than the
575value of the rational term {\it T2}, 0 otherwise.
576
577\item[\#$>$=(?T1, ?T2, ?B)]
578\index{\#$>$=/3!fd}
579{\it B} is equal to 1 iff
580the value of the rational term {\it T1} is greater than or equal to the
581value of the rational term {\it T2}, 0 otherwise.
582
583
584%\latex{
585%\item[\#/$\backslash$(+E1, +E2, ?B)]
586%\index{\#/$\backslash$/3}
587%}\html{
588%\item[\#\verb+/\+(+E1, +E2, ?B)]
589%\index{\#\verb+/\+/3}
590\item[\#\andsy(+E1, +E2, ?B)]
591\index{\#\andsy/3}
592%}
593{\it B} is equal to 1 iff
594both constraint expressions {\it E1} and {\it E2} are true,
5950 otherwise.
596
597%\latex{
598%\item[\#$\backslash$/(+E1, +E2, ?B)]
599%\index{\#$\backslash$//3}
600%}\html{
601%\item[\#\verb+\/+(+E1, +E2, ?B)]
602%\index{\#\verb+\/+/3}
603\item[\#\orsy(+E1, +E2, ?B)]
604\index{\#\orsy/3}
605%}
606{\it B} is equal to 1 iff
607at least one of the constraint expressions {\it E1} and {\it E2} is true,
6080 otherwise.
609
610\item[\#$<=>$(+E1, +E2, ?B)]
611\index{\#$<$=$>$/3}
612{\it B} is equal to 1 iff
613the constraint expression {\it E1} is equivalent to the
614constraint expression {\it E2},
6150 otherwise.
616
617\item[\#=$>$(+E1, +E2, ?B)]
618\index{\#=$>$/3}
619{\it B} is equal to 1 iff
620the constraint expression {\it E1} implies the
621constraint expression {\it E2},
6220 otherwise.
623
624%\latex{
625%\item[\#$\backslash$+(+E1, ?B)]
626%\index{\#$\backslash$+/2}
627%}\html{
628%\item[\#\verb+\++(+E1, ?B)]
629%\index{\#\verb+\++/2}
630\item[\#\bsl+(+E1, ?B)]
631\index{\#\bsl+/2}
632%}
633{\it B} is equal to 1 iff
634{\it E1} is false,
6350 otherwise.
636
637\end{description}
638
639%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
640\section{CHIP Compatibility Constraints Predicates}
641These constraints, defined in the module {\bf fd\_chip},
642are provided for CHIP v.3 compatibility and they are defined using
643\index{CHIP}
644native \eclipse\ constraints.
645Their source is available in the file {\bf fd\_chip.pl}.
646
647\begin{description}
648\item[?T1 \#\# ?T2]
649\index{\#\#/2}
650The value of the rational term {\it T1} is not equal to the value of the
651rational term {\it T2}.
652
653\item[alldistinct(?List)]
654\index{alldistinct/1}
655All elements of {\it List} (domain variables and ground terms) are pairwise
656different.
657
658\item[deleteff(?Var, +List, -Rest)]
659\index{deleteff/3}
660This predicate is used to select a variable from a list of domain variables
661which has the smallest domain.
662{\it Var} is the selected variable from {\it List},
663{\it Rest} is the rest of the list without {\it Var}.
664
665\item[deleteffc(?Var, +List, -Rest)]
666\index{deleteffc/3}
667This predicate is used to select the most constrained variable from a list
668of domain variables.
669{\it Var} is the selected variable from {\it List} which has the least domain
670and which has the most constraints attached to it.
671{\it Rest} is the rest of the list without {\it Var}.
672
673\item[deletemin(?Var, +List, -Rest)]
674\index{deletemin/3}
675This predicate is used to select the domain variable with the smallest
676lower domain bound from a list of domain variables.
677{\it Var} is the selected variable from {\it List},
678{\it Rest} is the rest of the list without {\it Var}.
679
680{\it List} is a list of domain variables or integers. Integers are treated
681as if they were variables with singleton domains.
682
683\item[dom(+DVar, -List)]
684\index{dom/2}
685{\it List} is the list of elements in the domain of the domain variable
686{\it DVar}.
687The predicate {\bf ::/2} can also be used to query the domain
688of a domain variable, however it yields a list of intervals.
689
690{\bf NOTE:} This predicate 
691should not be used in \eclipse\ programs, because all intervals
692in the domain will be expanded into element lists which causes
693unnecessary space and time overhead.
694Unless an explicit list representation is required, finite
695domains should be processed by the family of the {\bf dom_*}
696predicates in sections \ref{domaccess} and \ref{dommodify}.
697
698\item[maxdomain(+DVar, -Max)]
699\index{maxdomain/2}
700{\it Max} is the maximum value in the domain of the integer domain
701variable {\it DVar}.
702
703\item[mindomain(+DVar, -Min)]
704\index{mindomain/2}
705{\it Min} is the minimum value in the domain of the integer domain
706variable {\it DVar}.
707
708\end{description}
709
710%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
711\section{Utility Constraints Predicates}
712These constraints are defined in the module {\bf fd\_util}
713and they consist of useful predicates that are often
714needed in constraint programs.
715Their source code is available in the file {\bf fd\_util.pl}.
716
717\begin{description}
718\item[\#(?Min, ?CstList, ?Max)]
719\index{\#/3}
720The cardinality operator.
721{\it CstList} is a list of constraint expressions and this operator
722states that at least {\it Min} and at most {\it Max} out of them
723are valid.
724
725\item[dvar\_domain\_list(?Var, ?List)]
726\index{dvar\_domain\_list/2}
727{\it List} is the list of elements in the domain of the domain variable
728or ground term {\it DVar}.
729The predicate {\bf ::/2} can also be used to query the domain
730of a domain variable, however it yields a list of intervals.
731
732\item[outof(?Var, +List)]
733\index{outof/2}
734The domain variable {\it Var} is different from all elements
735of the list {\it List}.
736
737\item[labeling(+List)]
738\index{labeling/1}
739\index{labeling!fd}
740The elements of the {\it List} are instantiated using the
741\bipref{indomain/1}{../bips/lib/fd/indomain-1.html} predicate.
742
743\end{description}
744
745\section{Search Methods}
746
747A library of different search methods for finite domain problems
748is available as
749\biptxtref{library(fd_search)}{fd_search:_/_}{../bips/lib/fd_search/index.html}.
750See the Reference Manual for details.
751
752
753\section{Domain Output}
754The library {\bf fd\_domain.pl} contains output macros which
755cause an {\bf fd} attribute as well as a domain to be printed
756as lists that represent the domain values.
757A domain variable is an attributed variable whose {\bf fd} attribute
758has a {\bf print} handler which prints it in the same format.
759For instance,
760\begin{quote}
761\begin{verbatim}
762[eclipse 4]: X::1..10, dvar_attribute(X, A), A = fd{domain:D}.
763
764X = X{[1..10]}
765D = [1..10]
766A = [1..10]
767yes.
768[eclipse 5]: A::1..10, printf("%mw", A).
769A{[1..10]}
770A = A{[1..10]}
771yes.
772\end{verbatim}
773\end{quote}
774
775\section{Debugging Constraint Programs}
776The \eclipse\ debugger is a low-level debugger which is
777suitable only to debug small constraint programs or to debug
778small parts of larger programs. Typically, one would use this debugger
779to debug user-defined constraints and Prolog data processing.
780When they are known to work properly, this debugger may
781not be helpful enough to find bugs (correctness debugging) or to speed up 
782a working program (performance debugging).
783For this, the {\bf display_matrix} tool from tkeclipse may be the
784appropriate tool. 
785
786
787\section{Debugger Support}
788The \eclipse\ debugger supports
789debugging and tracing of finite domain programs in various ways.
790First of all, the debugger commands that handle suspended
791goals can be used to display suspended constraints ({\bf d}, {\bf \verb+^+},
792{\bf u}) or
793to skip to a particular constraint ({\bf w}, {\bf i}).
794Note that most of the constraints are displayed using a write macro,
795\index{macro!write}
796their internal form is different. 
797
798Successive updates of a domain variable can be traced using the
799debug event {\bf Hd}.
800When used, the debugger prompts for a variable name and then it
801skips to the port at which the domain of this variable
802was reduced.
803When a newline is typed instead of a variable name, it skips
804to the update of the previously entered variable.
805
806A sequence of woken goals can be skipped using the debug event {\bf Hw}.
807\index{debug events}
808
809\section{Examples}
810A very simple example of using the finite domains is the {\it send
811more money} puzzle:
812\begin{quote}
813\begin{verbatim}
814
815:- use_module(library(fd)).
816
817send(List) :-
818    List = [S, E, N, D, M, O, R, Y],
819    List :: 0..9,
820    alldifferent(List),
821    1000*S+100*E+10*N+D + 1000*M+100*O+10*R+E #=
822        10000*M+1000*O+100*N+10*E+Y,
823    M #\= 0,
824    S #\= 0,
825    labeling(List).
826\end{verbatim}
827\end{quote}
828
829The problem is stated very simply, one just writes down the conditions
830that must hold for the involved variables and then uses the default
831{\it labeling} procedure, i.e.\ the order in which the variables
832\index{labeling!fd}
833will be instantiated.
834When executing {\bf send/1}, the variables {\it S}, {\it M}
835and {\it O} are instantiated even before the labeling
836procedure starts.
837When a consistent value for the variable {\it E} is found (5),
838and this value is propagated to the other variables, all
839variables become instantiated and thus the rest of the labeling
840procedure only checks groundness of the list.
841
842A slightly more elaborate example is the {\it eight queens}
843puzzle.
844Let us show a solution for this problem generalised to N queens
845and also enhanced by a cost function that evaluates
846every solution.
847
848The cost can be for example
849 {\it coli - rowi} 
850for the i-th queen.
851We are now looking for the solution with the smallest cost,
852i.e.\ one for which the maximum of all
853{\it coli - rowi} 
854is minimal:
855
856\begin{quote}
857\begin{verbatim}
858:- use_module(library(fd)).
859
860% Find the minimal solution for the N-queens problem
861cqueens(N, List) :-
862    make_list(N, List),
863    List :: 1..N,
864    constrain_queens(List),
865    make_cost(1, List, C),
866    min_max(labeling(List), C).
867
868% Set up the constraints for the queens
869constrain_queens([]).
870constrain_queens([X|Y]) :-
871    safe(X, Y, 1),
872    constrain_queens(Y).
873
874safe(_, [], _).
875safe(X, [Y|T], K) :-
876    noattack(X, Y, K) ,
877    K1 is K + 1 ,
878    safe(X, T, K1).
879
880% Queens in rows X and Y cannot attack each other
881noattack(X, Y, K) :-
882    X #\= Y,
883    X + K #\= Y,
884    X - K #\= Y.
885
886% Create a list with N variables
887make_list(0, []) :- !.
888make_list(N, [_|Rest]) :-
889    N1 is N - 1,
890    make_list(N1, Rest).
891
892% Set up the cost expression
893make_cost(_, [], []).
894make_cost(N, [Var|L], [N-Var|Term]) :-
895    N1 is N + 1,
896    make_cost(N1, L, Term).
897
898labeling([]) :- !.
899labeling(L) :-
900    deleteff(Var, L, Rest),
901    indomain(Var),
902    labeling(Rest).
903\end{verbatim}
904\end{quote}
905
906The approach is similar to the previous example: first we create
907the domain variables, one for each column of the board,
908whose values will be the rows.
909We state constraints which must hold between every pair
910of queens and finally
911we make the cost term in the format required for the
912\bipref{min_max/2}{../bips/lib/fd/min_max-2.html} predicate.
913The labeling predicate selects the most constrained variable
914for instantiation using the \bipref{deleteff/3}{../bips/lib/fd/deleteff-3.html} predicate.
915When running the example, we get the following result:
916\begin{quote}
917\begin{verbatim}
918[eclipse 19]: cqueens(8, X).
919Found a solution with cost 5
920Found a solution with cost 4
921
922X = [5, 3, 1, 7, 2, 8, 6, 4] 
923yes.
924\end{verbatim}
925\end{quote}
926The time needed to find the minimal solution is about five times
927shorter than the time to generate all solutions.
928This shows the advantage of the {\it branch and bound} method.
929Note also that the board for this `minimal' solution looks
930very nice.
931
932
933\section{General Guidelines to the Use of Domains}
934The {\it send more money} example already shows the general
935principle of solving problems
936using finite domain constraints:
937\begin{itemize}
938\item First the variables are defined and their domains are specified.
939
940\item Then the constraints are imposed on these variables.
941In the above example the constraints are simply built-in predicates.
942For more complicated problems it is often necessary to define
943Prolog predicates that process the variables and impose constraints
944on them.
945
946\item If stating the constraints alone did not solve the problem,
947one tries to assign values to the variables. Since every
948instantiation immediately wakes all constraints associated with the variable,
949and changes are propagated to the other variables, the search space
950is usually quickly reduced and either an early failure occurs
951or the domains of other variables are reduced or directly instantiated.
952This labeling procedure is therefore incomparably more efficient
953\index{labeling}
954than the simple {\it generate and test} algorithm.
955\end{itemize}
956
957The complexity of the program and the efficiency of the solving
958depends very much on the way these three points are performed.
959Quite frequently it is possible to state the same problem
960using different sets of variables with different domains.
961A guideline is that the search space should be as small as possible,
962and thus e.g.\ five variables with domain 1..10
963(i.e.\ search space size is $10^5$)
964are likely to be better than
965twenty variables with domain 0..1
966(space size $2^{20}$).
967
968The choice of constraints is also very important.
969Sometimes a redundant constraint, i.e.\ one that follows from the
970other constraints, can speed up the search considerably.
971This is because the system does not propagate {\it all}
972information it has to all concerned variables, because
973most of the time this would not bring anything, and thus it would
974slow down the search.
975Another reason is that the library performs no meta-level reasoning on
976constraints themselves (unlike the {\sf CHR} library).
977For example, the constraints
978\begin{quote}
979\begin{verbatim}
980X + Y #= 10, X + Y + Z #= 14
981\end{verbatim}
982\end{quote}
983allow only the value 4 for {\it Z}, however the system is not
984able to deduce this and thus it has to be provided
985as a redundant constraint.
986
987The constraints should be stated in such a way that allows the system
988to propagate all important domain updates to the appropriate variables.
989
990Another rule of thumb is that creation of choice points should be delayed
991as long as possible. Disjunctive constraints, if there are any,
992should be postponed as much as possible. Labeling, i.e.\ value
993choosing, should be done after all deterministic operations
994are carried out.
995
996The choice of the labeling procedure is perhaps the most
997\index{labeling}
998sensitive one.
999It is quite common that only a very minor change in the order
1000of instantiated variables can speed up or slow down the search
1001by several orders of magnitude.
1002There are very few common rules available.
1003If the search space is large, it usually pays off to spend
1004more time in selecting the next variable to instantiate.
1005The provided predicates \bipref{deleteff/3}{../bips/lib/fd/deleteff-3.html} and \bipref{deleteffc/3}{../bips/lib/fd/deleteffc-3.html}
1006can be used to select the most constrained variable, but in
1007many problems it is possible to extract even more information
1008about which variable to instantiate next.
1009
1010Often it is necessary to try out several approaches
1011and see how they work, if they do.
1012The profiler and the statistics package can be of a great help here,
1013it can point to predicates which are executed too often, or
1014choice points unnecessarily backtracked over.
1015
1016\section{User-Defined Constraints}
1017The {\bf fd.pl} library defines a set of low-level predicates
1018which
1019allow the user to process domain variables
1020and their domains, modify them and write new constraint
1021predicates.
1022
1023\subsection{The {\it fd} Attribute}
1024A domain variable is a metaterm.
1025\index{metaterm}
1026\index{domain variable!implementation}
1027The {\bf fd.pl} library defines a metaterm attribute
1028\begin{quote}
1029${\bf fd\{domain:D, min:Mi, max:Ma, any:A\}}$
1030\end{quote}
1031\label{fd:attribute}
1032which stores the domain information together with several suspension lists.
1033The attribute arguments have the following meaning:
1034\begin{itemize}
1035\item {\bf domain} - the representation of the domain itself.
1036Domains are treated as abstract data types, the users should not
1037access them directly, but only using access and modification
1038predicates listed below.
1039
1040\item {\bf min} - a suspension list that should be woken when the minimum
1041        of the domain is updated
1042
1043\item {\bf max} - a suspension list that should be woken when the maximum
1044        of the domain is updated
1045
1046\item {\bf any} - a suspension list that should be woken when the domain
1047        is reduced no matter how.
1048\end{itemize}
1049The suspension list names can be used in the predicate \bipref{suspend/3}{../bips/kernel/suspensions/suspend-3.html}
1050to denote an appropriate waking condition.
1051
1052The attribute of a domain variable can be accessed
1053with the predicate \bipref{dvar_attribute/2}{../bips/lib/fd/dvar_attribute-2.html}
1054or by unification in a matching clause:
1055\index{matching clause}
1056\begin{quote}
1057\begin{verbatim}
1058get_attribute(_{fd:Attr}, A) :-
1059    -?->
1060    Attr = A.
1061\end{verbatim}
1062\end{quote}
1063Note however, that this matching clause succeeds even if the first
1064argument is a metaterm but its {\bf fd} attribute is empty.
1065To succeed only for domain variables, the clause
1066must be
1067\begin{quote}
1068\begin{verbatim}
1069get_attribute(_{fd:Attr}, A) :-
1070    -?->
1071    nonvar(Attr),
1072    Attr = A.
1073\end{verbatim}
1074\end{quote}
1075or to access directly attribute arguments, e.g.\ the domain
1076\begin{quote}
1077\begin{verbatim}
1078get_domain(_{fd:fd{domain:D}}, Dom) :-
1079    -?->
1080    D = Dom.
1081\end{verbatim}
1082\end{quote}
1083The \bipref{dvar_attribute/2}{../bips/lib/fd/dvar_attribute-2.html} has the advantage that it returns
1084an attribute-like structure even if its argument is already
1085instantiated, which is quite useful when coding {\bf fd}
1086constraints.
1087
1088The attribute arguments can be accessed by macros from
1089the {\bf structures.pl} library,
1090if e.g.\ {\bf Attr} is the attribute of a domain variable, the max
1091list can be obtained as
1092
1093\begin{quote}
1094arg(max of fd, Attr, Max)
1095\end{quote}
1096or, using a unification
1097\begin{quote}
1098Attr = fd\{max:Max\}
1099\end{quote}
1100
1101\subsection{Domain Access}
1102\label{domaccess}
1103The domains are represented as abstract data types, the users are not
1104supposed to access them directly, instead a number of
1105predicates and macros are available to allow operations on domains.
1106
1107\begin{description}
1108\item[dom_check_in(+Element, +Dom)]
1109\index{dom_check_in/2}
1110Succeed if the integer {\it Element} is in the domain {\it Dom}.
1111
1112\item[dom_compare(?Res, +Dom1, +Dom2)]
1113\index{dom_compare/3}
1114Works like \bipref{compare/3}{../bips/kernel/termcomp/compare-3.html} for terms.
1115{\it Res} is unified with
1116\begin{itemize}
1117\item ${\bf =}$
1118iff {\it Dom1} is equal to {\it Dom2},
1119\item ${\bf <}$
1120iff {\it Dom1} is a proper subset of {\it Dom2},
1121\item ${\bf >}$
1122iff {\it Dom2} is a proper subset of {\it Dom1}.
1123\end{itemize}
1124Fails if neither domain is a subset of the other one.
1125
1126\item[dom_member(?Element, +Dom)]
1127\index{dom_member/2}
1128Successively instantiate {\it Element} to the values in the domain {\it Dom}
1129(similar to \bipref{indomain/1}{../bips/lib/fd/indomain-1.html}).
1130
1131\item[dom_range(+Dom, ?Min, ?Max)]
1132\index{dom_range/3}
1133Return the minimum and maximum value  in the integer domain {\it Dom}.
1134Fails if {\it Dom} is a domain containing non-integer 
1135elements.
1136This predicate can also be used to test if a given domain
1137is integer or not.
1138
1139\item[dom_size(+Dom, ?Size)]
1140\index{dom_size/2}
1141{\it Size} is the number of elements in the domain {\it Dom}.
1142
1143\end{description}
1144
1145\subsection{Domain Operations}
1146\label{dommodify}
1147The following predicates operate on domains alone, without modifying
1148domain {\it variables}.
1149Most of them return the size of the resulting domain which can be used
1150to test if any modification was done.
1151
1152\begin{description}
1153\item[dom_copy(+Dom1, -Dom2)]
1154\index{dom_copy/2}
1155{\it Dom2} is a copy of the domain {\it Dom1}.
1156Since the updates are done in-place, two domain variables must not share
1157the same physical domain and so when defining a new variable
1158with an existing domain, the domain has to be copied first.
1159
1160\item[dom_difference(+Dom1, +Dom2, -DomDiff, ?Size)]
1161\index{dom_difference/4}
1162The domain {\it DomDifference} is
1163%{\it Dom1 \latex{$\setminus$} \html{\verb+\+} Dom2}
1164{\it Dom1 \bsl\ Dom2}
1165%\index{\bsl/2}
1166and {\it Size} is the number of its elements.
1167Fails if {\it Dom1} is a subset of {\it Dom2}.
1168
1169\item[dom_intersection(+Dom1, +Dom2, -DomInt, ?Size)]
1170\index{dom_intersection/4}
1171The domain {\it DomInt} is the intersection of domains
1172{\it Dom1} and {\it Dom2} and {\it Size} is the number of its elements.
1173Fails if the intersection is empty.
1174
1175
1176%\item[dom_remove_element(+Dom, +El, -DomRem, ?Size)]
1177%\index{dom_remove_element/2}
1178%The domain {\it DomRem} is equal to {\it Dom} with the element
1179%{\it El} removed and {\it Size} is its size.
1180%If {\it Dom} does not contain this element, {\it DomRem}
1181%is identical to {\it Dom}.
1182
1183\item[dom_union(+Dom1, +Dom2, -DomUnion, ?Size)]
1184\index{dom_union/4}
1185The domain {\it DomUnion} is the union of domains
1186{\it Dom1} and {\it Dom2} and {\it Size} is the number of its elements.
1187Note that the main use of the predicate is to yield
1188the most specific generalisation of two domains, in the usual cases
1189the domains become smaller, not bigger.
1190
1191\item[list_to_dom(+List, -Dom)]
1192\index{list_to_dom/2}
1193Convert a list of ground terms and integer intervals into
1194a domain {\it Dom}.
1195It does not have to be sorted and integers and intervals
1196may overlap.
1197
1198\item[integer_list_to_dom(+List, -Dom)]
1199\index{integer_list_to_dom/2}
1200Similar to \bipref{list_to_dom/2}{../bips/lib/fd/list_to_dom-2.html} \index{list_to_dom/2}, but the input list should
1201contain only integers and integer intervals and it should be sorted.
1202This predicate will merge adjacent integers and intervals
1203into larger intervals whenever possible.
1204typically, this predicate should be used to convert
1205a sorted list of integers into a finite domain.
1206If the list is known to already contain proper intervals,
1207\bipref{sorted_list_to_dom/2}{../bips/lib/fd/sorted_list_to_dom-2.html} could be used instead.
1208
1209\item[sorted_list_to_dom(+List, -Dom)]
1210\index{sorted_list_to_dom/2}
1211Similar to \bipref{list_to_dom/2}{../bips/lib/fd/list_to_dom-2.html}, \index{list_to_dom/2} but the input list is assumed
1212to be already in the correct format, i.e.\ sorted and with correct integer
1213and interval values.
1214No checking on the list contents is performed.
1215
1216\end{description}
1217
1218\subsection{Accessing Domain Variables}
1219The following predicates perform various operations:
1220
1221\begin{description}
1222\item[dvar_attribute(+DVar, -Attrib)]
1223\index{dvar_attribute/2}
1224{\it Attrib} is the attribute of the domain variable {\it DVar}.
1225If {\it DVar} is instantiated, {\it Attrib} is bound to an attribute
1226with a singleton domain and empty suspension lists.
1227
1228\item[dvar_domain(+DVar, -Dom)]
1229\index{dvar_domain/2}
1230{\it Dom} is the domain of the domain variable {\it DVar}.
1231If {\it DVar} is instantiated, {\it Dom} is bound to
1232a singleton domain.
1233
1234\item[var_fd(?Var, +Dom)]
1235\index{var_fd/2}
1236If {\it Var} is a free variable,
1237it becomes a domain variable with the domain {\it Dom}
1238and with empty suspension lists.
1239The domain {\it Dom} is copied to make in-place updates
1240logically sound.
1241If {\it Var} is already a domain variable, its domain is intersected
1242with the domain {\it Dom}.
1243Fails if {\it Var} is not a variable.
1244
1245\item[dvar_msg(+DVar1, +DVar2, -MsgDVar)]
1246\index{dvar_msg/3}
1247{\it MsgVar} is a domain variable which is the most specific generalisation
1248of domain variables or ground values {\it Var1} and {\it Var2}.
1249
1250\end{description}
1251
1252\subsection{Modifying Domain Variables}
1253When the domain of a domain variable is reduced, some suspension
1254lists stored in the attribute have to be scheduled and woken.
1255
1256{\bf NOTE:} In the {\bf fd.pl} library the suspension lists
1257are woken precisely when the event associated with the
1258list occurs.
1259Thus e.g.\ the {\bf min} list is woken if and only if the minimum
1260value of the variable's domain is changed, but it is not
1261woken when the variable is instantiated to this minimum
1262or when another element from the domain is removed.
1263In this way, user-defined constraints can rely on the fact that
1264when they are executed, the domain was updated in the expected way.
1265On the other hand, user-defined constraints should also comply
1266with this rule and they should take care not to wake lists
1267when their waking condition did not occur.
1268Most predicates in this section actually do all the work themselves
1269so that the user predicates may ignore scheduling and waking completely.
1270
1271\begin{description}
1272\item[dvar_remove_element(+DVar, +El)]
1273\index{dvar_remove_element/2}
1274The element {\it El} is removed from the domain of {\it DVar} and all
1275concerned lists are woken.
1276If the resulting domain is empty, this predicate fails. If it is
1277a singleton, {\it DVar} is instantiated.
1278If the domain does not contain the element,
1279no updates are made.
1280
1281\item[dvar_remove_smaller(+DVar, +El)]
1282\index{dvar_remove_smaller/2}
1283Remove all elements in the domain of {\it DVar} which are smaller than
1284the integer {\it El} and wake all concerned lists.
1285If the resulting domain is empty, this predicate fails; if it is
1286a singleton, {\it DVar} is instantiated.
1287
1288\item[dvar_remove_greater(+DVar, +El)]
1289\index{dvar_remove_greater/2}
1290Remove all elements in the domain of {\it DVar} which are greater than
1291the integer {\it El} and wake all concerned lists.
1292If the resulting domain is empty, this predicate fails; if it is
1293a singleton, {\it DVar} is instantiated.
1294
1295\item[dvar_update(+DVar, +NewDom)]
1296\index{dvar_update/2}
1297If the size of the domain {\it NewDom} is 0, the predicate fails.
1298If it is 1,
1299the domain variable {\it DVar}
1300is instantiated to the value in the domain.
1301Otherwise,
1302if the size of the new domain is smaller than the size of
1303the domain variable's domain,
1304the domain of {\it DVar} is replaced by {\it NewDom},
1305the appropriate suspension lists in its attribute are passed
1306to the waking scheduler and so is the {\bf constrained} list
1307in the {\bf suspend} attribute of the domain variable.
1308If the size of the new domain is equal to the old one, no
1309updates and no waking is done, i.e.\ this predicate does not
1310check an explicit equality of both domains.
1311If the size of the new domain is greater than the old one,
1312an error is raised.
1313
1314\item[dvar_replace(+DVar, +NewDom)]
1315\index{dvar_replace/2}
1316This predicate is similar to \bipref{dvar_update/2}{../bips/lib/fd/dvar_update-2.html}, but it
1317does not propagate the changes, i.e.\ no waking is done.
1318If the size of the new domain is 1, {\it DVar}
1319is not instantiated, but it is given this singleton domain.
1320This predicate is useful for local consistency checks.
1321
1322\end{description}
1323
1324\section{Extensions}
1325The {\bf fd.pl} library can be used as a basis for further
1326extensions.
1327There are several hooks that make the interfacing easier:
1328\begin{itemize}
1329\item Each time a new domain variable is created, either
1330in the {\bf ::/2} predicate or by giving it a default domain
1331in a rational arithmetic expression, the predicate \bipref{new_domain_var/1}{../bips/lib/fd/new_domain_var-1.html}
1332is called with the variable as argument.
1333Its default definition does nothing. To use it,
1334it is necessary to redefine it, i.e.\ to recompile it
1335in the {\bf fd} module, e.g.\ using \bipref{compile/2}{../bips/kernel/compiler/compile-2.html}
1336or the tool body of \bipref{compile_term/1}{../bips/kernel/compiler/compile_term-1.html}.
1337
1338\item Default domains
1339\index{domain!default}
1340are created in the predicate \bipref{default_domain/1}{../bips/lib/fd/default_domain-1.html}
1341\index{default_domain/1}
1342in the {\bf fd} module, its default definition is
1343
1344\begin{quote}
1345default_domain(Var) :- Var :: -10000000..10000000.
1346\end{quote}
1347
1348It is possible to change default domains by redefining
1349this predicate in the {\bf fd} module.
1350\end{itemize}
1351
1352\section{Example of Defining a New Constraint}
1353We will demonstrate creation of new constraints on the
1354following example.
1355To show that the constraints are not restricted to linear terms,
1356we can take the constraint
1357\begin{quote}
1358$X^2 + Y^2 \leq C.$
1359\end{quote}
1360Assuming that {\it X} and {\it Y} are domain variables, we would
1361like to define such a predicate that will be woken
1362as soon as one or both variables' domains are updated in such a way that would
1363require updating the other variable's domain, i.e.\ updates
1364that would propagate via this constraint.
1365For simplicity we assume that {\it X} and {\it Y} are nonnegative.
1366We will define the predicate {\bf sq(X, Y, C)} which will
1367implement this constraint:
1368
1369\begin{quote}
1370\begin{verbatim}
1371:- use_module(library(fd)).
1372
1373% A*A + B*B <= C
1374sq(A, B, C) :-
1375    dvar_domain(A, DomA),
1376    dvar_domain(B, DomB),
1377    dom_range(DomA, MinA, MaxA),
1378    dom_range(DomB, MinB, MaxB),
1379    MiA2 is MinA*MinA,
1380    MaB2 is MaxB*MaxB,
1381    (MiA2 + MaB2 > C ->
1382        NewMaxB is fix(sqrt(C - MiA2)),
1383        dvar_remove_greater(B, NewMaxB)
1384    ;
1385        NewMaxB = MaxB
1386    ),
1387    MaA2 is MaxA*MaxA,
1388    MiB2 is MinB*MinB,
1389    (MaA2 + MiB2 > C ->
1390        NewMaxA is fix(sqrt(C - MiB2)),
1391        dvar_remove_greater(A, NewMaxA)
1392    ;
1393        NewMaxA = MaxA
1394    ),
1395    (NewMaxA*NewMaxA + NewMaxB*NewMaxB =< C ->
1396        true
1397    ;
1398        suspend(sq(A, B, C), 3, (A, B)->min)
1399    ),
1400    wake.                % Trigger the propagation
1401\end{verbatim}
1402\end{quote}
1403
1404The steps to be executed when this constraint becomes active,
1405i.e.\ when the predicate {\bf sq/3} is called or woken
1406are the following:
1407\begin{enumerate}
1408\item We access the domains of the two variables
1409using the predicate \bipref{dvar_domain/2}{../bips/lib/fd/dvar_domain-2.html} and
1410and obtain their bounds using \bipref{dom_range/3}{../bips/lib/fd/dom_range-3.html}.
1411Note that it may happen that one of the two variables is already instantiated,
1412but these predicates still work as if the variable had a singleton domain.
1413
1414\item We check if the maximum of one or the other variable is still
1415consistent with this constraint, i.e.\ if there is a value
1416in the other variable's domain that satisfies the constraint
1417together with this maximum.
1418
1419\item If the maximum value is no longer consistent, we compute
1420the new maximum of the domain, and then update the domain
1421so that all values greater than this value are removed
1422using the predicate \bipref{dvar_remove_greater/2}{../bips/lib/fd/dvar_remove_greater-2.html}.
1423This predicate also wakes all concerned suspension lists
1424and instantiates the variable if its new domain is a singleton.
1425
1426\item After checking the updates for both variables we test
1427if the constraint is now satisfied for all values
1428in the new domains.
1429If this is not the case, we have to suspend the predicate
1430so that it is woken as soon as the minimum of either domain
1431is changed.
1432This is done using the predicate \bipref{suspend/3}{../bips/kernel/suspensions/suspend-3.html}.
1433
1434\item The last action is to trigger the execution of all goals that 
1435are waiting for
1436the updates we have made.
1437It is necessary to wake these goals {\bf after} inserting
1438the new suspension, otherwise updates made in the
1439woken goals would not be propagated back to this constraint.
1440\end{enumerate}
1441
1442Here is what we get:
1443\begin{quote}
1444\begin{verbatim}
1445[eclipse 20]: [X,Y]::1..10, sq(X, Y, 50).
1446
1447X = X{[1..7]}
1448Y = Y{[1..7]}
1449
1450Delayed goals:
1451	sq(X{[1..7]}, Y{[1..7]}, 50)
1452yes.
1453[eclipse 21]: [X,Y]::1..10, sq(X, Y, 50), X #> 5.
1454
1455Y = Y{[1..3]}
1456X = X{[6, 7]}
1457
1458Delayed goals:
1459	sq(X{[6, 7]}, Y{[1..3]}, 50)
1460yes.
1461[eclipse 22]: [X,Y]::1..10, sq(X, Y, 50), X #> 5, Y #> 1.
1462
1463X = 6
1464Y = Y{[2, 3]}
1465yes.
1466[eclipse 23]: [X,Y]::1..10, sq(X, Y, 50), X #> 5, Y #> 2.
1467
1468X = 6
1469Y = 3
1470yes.
1471\end{verbatim}
1472\end{quote}
1473
1474\section{Program Examples}
1475In this section we present some FD programs that show various
1476aspects of the library usage.
1477
1478\subsection{Constraining Variable Pairs}
1479The finite domain library gives the user the possibility
1480to impose constraints on the value of a variable.
1481How, in general, is it possible to impose constraints on two
1482or more variables?
1483For example, let us assume that we have a set of colours and we
1484want to define that some colours fit with each other and others do not.
1485This should work in such a way as to propagate possible changes
1486in the domains as soon as this becomes possible.
1487
1488
1489Let us assume we have a symmetric relation that defines which
1490colours fit with each other:
1491\begin{quote}
1492\begin{verbatim}
1493% The basic relation
1494fit(yellow, blue).
1495fit(yellow, red).
1496fit(blue, yellow).
1497fit(red, yellow).
1498fit(green, orange).
1499fit(orange, green).
1500\end{verbatim}
1501\end{quote}
1502
1503The predicate {\bf nice_pair(X, Y)} is a constraint and any change of
1504the possible values of X or Y is propagated
1505to the other variable.
1506There are many ways in which this pairing can be defined in \eclipse.
1507They are different solutions with different properties, but
1508they yield the same results.
1509
1510\subsubsection{User-Defined Constraints}
1511We use more or less directly the low-level primitives to handle
1512finite domain variables.
1513We collect all consistent values for the two variables, remove
1514all other values from their domains and then suspend
1515the predicate until one of its arguments is updated:
1516\begin{quote}
1517\begin{verbatim}
1518nice_pair(A, B) :-
1519        % get the domains of both variables
1520    dvar_domain(A, DA),         
1521    dvar_domain(B, DB),         
1522        % make a list of respective matching colours
1523    setof(Y, X^(dom_member(X, DA), fit(X, Y)), BL),
1524    setof(X, Y^(dom_member(Y, DB), fit(X, Y)), AL),
1525        % convert the lists to domains
1526    sorted_list_to_dom(AL, DA1),
1527    sorted_list_to_dom(BL, DB1),
1528        % intersect the lists with the original domains
1529    dom_intersection(DA, DA1, DA_New, _),
1530    dom_intersection(DB, DB1, DB_New, _),
1531        % and impose the result on the variables
1532    dvar_update(A, DA_New),
1533    dvar_update(B, DB_New),
1534        % unless one variable is already instantiated, suspend
1535        % and wake as soon as any element of the domain is removed
1536    (var(A), var(B) ->
1537        suspend(nice_pair(A, B), 2, [A,B]->any)
1538    ;
1539        true
1540    ).
1541
1542% Declare the domains
1543colour(A) :-
1544    findall(X, fit(X, _), L),
1545    A :: L.
1546\end{verbatim}
1547\end{quote}
1548
1549After defining the domains, we can state the constraints:
1550\begin{quote}
1551\begin{verbatim}
1552[eclipse 5]: colour([A,B,C]), nice_pair(A, B), nice_pair(B, C), A #\= green.
1553
1554B = B{[blue, green, red, yellow]}
1555C = C{[blue, orange, red, yellow]}
1556A = A{[blue, orange, red, yellow]}
1557 
1558Delayed goals:
1559  nice_pair(A{[blue, orange, red, yellow]}, B{[blue, green, red, yellow]})
1560  nice_pair(B{[blue, green, red, yellow]}, C{[blue, orange, red, yellow]})
1561\end{verbatim}
1562\end{quote}
1563
1564This way of defining new constraints is often the most efficient
1565one, but usually also the most tedious one.
1566
1567
1568\subsubsection{Using the {\it element} Constraint}
1569In this case we use the available primitive in the fd library. Whenever
1570it is necessary to associate a fd variable with some other fd variable,
1571the \bipref{element/3}{../bips/lib/fd/element-3.html} constraint is a likely candidate. Sometimes it is
1572rather awkward to use, because additional variables must be used,
1573but it gives enough power:
1574
1575\begin{quote}
1576\begin{verbatim}
1577nice_pair(A, B) :-
1578    element(I, [yellow, yellow, blue, red, green, orange], A),
1579    element(I, [blue, red, yellow, yellow, orange, green], B).
1580\end{verbatim}
1581\end{quote}
1582
1583We define a new variable {\bf I} which is a sort of index into the
1584clauses of the fit predicate. The first colour list contains
1585colours in the first argument of fit/2 and the second list
1586contains colours from the second argument. The propagation is similar
1587to that of the previous one.
1588
1589When \bipref{element/3}{../bips/lib/fd/element-3.html} can be used, it is usually faster
1590than the previous approach, because \bipref{element/3}{../bips/lib/fd/element-3.html} is partly
1591implemented in C.
1592
1593\subsubsection{Using Evaluation Constraints}
1594We can also encode directly the relations between elements
1595in the domains of the two variables:
1596
1597\begin{quote}
1598\begin{verbatim}
1599nice_pair(A, B) :-
1600    np(A, B),
1601    np(B, A).
1602
1603np(A, B) :-
1604    [A,B] :: [yellow, blue, red, orange, green],
1605    A #= yellow #=> B :: [blue, red],
1606    A #= blue #=> B #= yellow,
1607    A #= red #=> B #= yellow,
1608    A #= green #=> B #= orange,
1609    A #= orange #=> B #= green.
1610\end{verbatim}
1611\end{quote}
1612
1613This method is quite simple and does not need any special analysis;
1614on the other hand it potentially creates a huge number of
1615auxiliary constraints and variables.
1616
1617
1618\subsubsection{Using Generalised Propagation}
1619Propia is the first candidate to convert an existing relation into
1620a constraint. One can simply use {\bf infers most} to achieve the propagation:
1621
1622\begin{quote}
1623\begin{verbatim}
1624nice_pair(A, B) :-
1625    fit(A, B) infers most.
1626\end{verbatim}
1627\end{quote}
1628
1629Using Propia is usually very easy and the programs are short
1630and readable, so that this style of constraints writing
1631is quite useful e.g.\ for teaching.
1632It is not as efficient as with user-defined constraints, but
1633if the amount of propagation is more important that the efficiency
1634of the constraint itself, it can yield good results, too.
1635
1636\subsubsection{Using Constraint Handling Rules}
1637The {\tt domain} solver in {\sf CHR} can be used directly with the
1638\bipref{element/3}{../bips/lib/fd/element-3.html} constraint as well, however it is also possible
1639to define directly domains consisting of pairs:
1640\begin{quote}
1641\begin{verbatim}
1642:- lib(chr).
1643:- chr(lib(domain)).
1644
1645nice_pair(A, B) :-
1646    setof(X-Y, fit(X, Y), L),
1647    A-B :: L.
1648
1649\end{verbatim}
1650\end{quote}
1651
1652The pairs are then constrained accordingly:
1653\begin{quote}
1654\begin{verbatim}
1655[eclipse 2]: nice_pair(A, B), nice_pair(B, C), A ne orange.
1656
1657B = B
1658C = C
1659A = A
1660
1661Constraints:
1662(9) A_g1484 - B_g1516 :: [blue - yellow, green - orange, red - yellow,
1663yellow - blue, yellow - red]
1664(10) A_g1484 :: [blue, green, red, yellow]
1665(12) B_g1516 - C_g3730 :: [blue - yellow, orange - green, red - yellow,
1666yellow - blue, yellow - red]
1667(13) B_g1516 :: [blue, orange, red, yellow]
1668(14) C_g3730 :: [blue, green, red, yellow]
1669\end{verbatim}
1670\end{quote}
1671
1672
1673\subsection{Puzzles}
1674Various kinds of puzzles can be easily solved using finite domains.
1675We show here the classical Lewis Carrol's puzzle with five houses and a zebra:
1676\begin{quote}
1677\begin{verbatim}
1678Five men with different nationalities live in the first five houses
1679of a street.  They practise five distinct professions, and each of
1680them has a favourite animal and a favourite drink, all of them
1681different.  The five houses are painted in different colours.
1682
1683The Englishman lives in a red house.
1684The Spaniard owns a dog.
1685The Japanese is a painter.
1686The Italian drinks tea.
1687The Norwegian lives in the first house on the left.
1688The owner of the green house drinks coffee.
1689The green house is on the right of the white one.
1690The sculptor breeds snails.
1691The diplomat lives in the yellow house.
1692Milk is drunk in the middle house.
1693The Norwegian's house is next to the blue one.
1694The violinist drinks fruit juice.
1695The fox is in a house next to that of the doctor.
1696The horse is in a house next to that of the diplomat.
1697
1698Who owns a Zebra, and who drinks water?
1699\end{verbatim}
1700\end{quote}
1701
1702One may be tempted to define five variables Nationality,
1703Profession, Colour, etc. with atomic domains to represent
1704the problem.
1705Then, however, it is quite difficult to express equalities
1706over these different domains.
1707A much simpler solution is to define 5x5 integer variables for each
1708mentioned item, to number the houses from one to five
1709and to represent the fact that e.g.\ Italian drinks tea
1710by equating Italian = Tea.
1711The value of both variables represents then the number of their house.
1712In this way, no special constraints are needed and
1713the problem is very easily described:
1714\begin{quote}
1715\begin{verbatim}
1716:- lib(fd).
1717
1718zebra([zebra(Zebra), water(Water)]) :-
1719    Sol = [Nat, Color, Profession, Pet, Drink],
1720    Nat = [English, Spaniard, Japanese, Italian, Norwegian],
1721    Color = [Red, Green, White, Yellow, Blue],
1722    Profession = [Painter, Sculptor, Diplomat, Violinist, Doctor],
1723    Pet = [Dog, Snails, Fox, Horse, Zebra],
1724    Drink = [Tea, Coffee, Milk, Juice, Water],
1725
1726    % we specify the domains and the fact
1727    % that the values are exclusive
1728    Nat :: 1..5,
1729    Color :: 1..5,
1730    Profession :: 1..5,
1731    Pet :: 1..5,
1732    Drink :: 1..5,
1733    alldifferent(Nat),
1734    alldifferent(Color),
1735    alldifferent(Profession),
1736    alldifferent(Pet),
1737    alldifferent(Drink),
1738
1739    % and here follow the actual constraints
1740    English = Red,
1741    Spaniard = Dog,
1742    Japanese = Painter,
1743    Italian = Tea,
1744    Norwegian = 1,
1745    Green = Coffee,
1746    Green #= White + 1,
1747    Sculptor = Snails,
1748    Diplomat = Yellow,
1749    Milk = 3,
1750    Dist1 #= Norwegian - Blue, Dist1 :: [-1, 1],
1751    Violinist = Juice,
1752    Dist2 #= Fox - Doctor, Dist2 :: [-1, 1],
1753    Dist3 #= Horse - Diplomat, Dist3 :: [-1, 1],
1754
1755    flatten(Sol, List),
1756    labeling(List).
1757\end{verbatim}
1758\end{quote}
1759
1760\subsection{Bin Packing}
1761In this type of problems the goal is to pack a certain amount of
1762different things into the minimal number of bins under specific constraints.
1763Let us solve an example given by Andre Vellino in the Usenet
1764group comp.lang.prolog, June 93:
1765\begin{itemize}
1766\item There are 5 types of components:
1767
1768        glass, plastic, steel, wood, copper
1769
1770\item There are three types of bins:
1771
1772        red, blue, green
1773
1774\item        whose capacity constraints are:
1775
1776\begin{itemize}
1777\item        red   has capacity 3
1778\item        blue  has capacity 1
1779\item green has capacity 4
1780\end{itemize}
1781
1782\item containment constraints are:
1783\begin{itemize}
1784\item        red   can contain glass, wood, copper
1785\item        blue  can contain glass, steel, copper
1786\item   green can contain plastic, wood, copper
1787\end{itemize}
1788
1789\item and requirement constraints are (for all bin types):
1790
1791        wood requires plastic
1792
1793\item Certain component types cannot coexist:
1794
1795\begin{itemize}
1796\item glass  exclusive copper
1797\item        copper exclusive plastic
1798\end{itemize}
1799
1800\item and certain bin types have capacity constraint for certain
1801components
1802
1803\begin{itemize}
1804\item red   contains at most 1 of wood
1805\item green contains at most 2 of wood
1806\end{itemize}
1807
1808\item Given an initial supply of:
18091 of glass,
18102 of plastic,
18111 of steel,
18123 of wood,
18132 of copper,
1814what is the minimum total number of bins required to
1815contain the components?
1816\end{itemize}
1817
1818To solve this problem, it is not enough to state constraints on some
1819variables and to start a labeling procedure on them.
1820The variables are namely not known, because we don't know how many
1821bins we should take.
1822One possibility would be to take a large enough number of bins
1823and to try to find a minimum number.
1824However, usually it is better to generate constraints
1825for an increasing fixed number of bins until a solution is found.
1826
1827The predicate {\bf solve/1} returns the solution for this
1828particular problem, {\bf solve_bin/2} is the general predicate
1829that takes an amount of components packed into a {\bf cont/5}
1830structure and it returns the solution.
1831\begin{quote}
1832\begin{verbatim}
1833solve(Bins) :-
1834    solve_bin(cont(1, 2, 1, 3, 2), Bins).
1835\end{verbatim}
1836\end{quote}
1837
1838{\bf solve_bin/2} computes the sum of all components which is necessary
1839as a limit value for various domains, calls {\bf bins/4} to
1840generate a list {\bf Bins} with an increasing number of elements
1841and finally it labels all variables in the list:
1842\begin{quote}
1843\begin{verbatim}
1844solve_bin(Demand, Bins) :-
1845    Demand = cont(G, P, S, W, C),
1846    Sum is G + P + S + W + C,
1847    bins(Demand, Sum, [Sum, Sum, Sum, Sum, Sum, Sum], Bins),
1848    label(Bins).
1849\end{verbatim}
1850\end{quote}
1851
1852The predicate to generate a list of bins with appropriate
1853constraints works as follows:
1854first it tries to match the amount of remaining components with zero
1855and the list with nil.
1856If this fails, a new bin represented by a list
1857\begin{quote}
1858${\bf [Colour, Glass, Plastic, Steel, Wood, Copper]}$
1859\end{quote}
1860is added to the bin list,
1861appropriate constraints are imposed on all the new bin's
1862variables,
1863its contents is subtracted from the remaining number of components,
1864and the predicate calls itself recursively:
1865
1866\begin{quote}
1867\begin{verbatim}
1868bins(cont(0, 0, 0, 0, 0), 0, _, []).
1869bins(cont(G0, P0, S0, W0, C0), Sum0, LastBin, [Bin|Bins]) :-
1870    Bin = [_Col, G, P, S, W, C],
1871    bin(Bin, Sum),
1872    G2 #= G0 - G,
1873    P2 #= P0 - P,
1874    S2 #= S0 - S,
1875    W2 #= W0 - W,
1876    C2 #= C0 - C,
1877    Sum2 #= Sum0 - Sum,
1878    ordering(Bin, LastBin),
1879    bins(cont(G2, P2, S2, W2, C2), Sum2, Bin, Bins).
1880\end{verbatim}
1881\end{quote}
1882The {\bf ordering/2} constraints are strictly necessary because
1883this problem has a huge number of symmetric solutions.
1884
1885The constraints imposed on a single bin correspond exactly to the
1886problem statement:
1887\begin{quote}
1888\begin{verbatim}
1889bin([Col, G, P, S, W, C], Sum) :-
1890    Col :: [red, blue, green],
1891    [Capacity, G, P, S, W, C] :: 0..4,
1892    G + P + S + W + C #= Sum,
1893    Sum #> 0,               % no empty bins
1894    Sum #<= Capacity,
1895    capacity(Col, Capacity),
1896    contents(Col, G, P, S, W, C),
1897    requires(W, P),
1898    exclusive(G, C),
1899    exclusive(C, P),
1900    at_most(1, red, Col, W),
1901    at_most(2, green, Col, W).
1902\end{verbatim}
1903\end{quote}
1904
1905We will code all of the special constraints with the
1906maximum amount of propagation to show how this can be
1907achieved.
1908In most programs, however, it is not necessary to
1909propagate all values everywhere which simplifies the
1910code quite considerably.
1911Often it is also possible to use some of the built-in symbolic
1912constraints of \eclipse, e.g.\ \bipref{element/3}{../bips/lib/fd/element-3.html} or \bipref{atmost/3}{../bips/lib/fd/atmost-3.html}.
1913
1914\subsubsection{Capacity Constraints}
1915{\bf capacity(Color, Capacity)} should instantiate the capacity
1916if the colour is known, and reduce the colour values
1917if the capacity is known to be greater than
1918some values.
1919If we use evaluation constraints, we can code the constraint directly,
1920using equivalences:
1921\begin{quote}
1922\begin{verbatim}
1923capacity(Color, Capacity) :-
1924    Color #= blue #<=> Capacity #= 1,
1925    Color #= green #<=> Capacity #= 4,
1926    Color #= red #<=> Capacity #= 3.
1927\end{verbatim}
1928\end{quote}
1929
1930A more efficient code would take into account the ordering on the
1931capacities.
1932Concretely, if the capacity is greater than 1, the colour cannot
1933be blue and if it is greater than 3, it must be green:
1934
1935\begin{quote}
1936\begin{verbatim}
1937capacity(Color, Capacity) :-
1938    var(Color),
1939    !,
1940    dvar_domain(Capacity, DC),
1941    dom_range(DC, MinC, _),
1942    (MinC > 1 ->
1943        Color #\= blue,
1944        (MinC > 3 ->
1945            Color = green
1946        ;
1947            suspend(capacity(Color, Capacity), 3, (Color, Capacity)->inst)
1948        )
1949    ;
1950        suspend(capacity(Color, Capacity), 3, [Color->inst, Capacity->min])
1951    ).
1952capacity(blue, 1).
1953capacity(green, 4).
1954capacity(red, 3).
1955\end{verbatim}
1956\end{quote}
1957Note that when suspended, the predicate waits for colour instantiation
1958or for minimum of the capacity to be updated (except that 3 is one less
1959than the maximum capacity and thus waiting for its instantiation
1960is equivalent).
1961
1962\subsubsection{Containment Constraints}
1963The containment constraints are stated as logical expressions
1964and this is also the easiest way to medel them.
1965The important point to remember is that a condition like
1966{\it red can contain glass, wood, copper}
1967actually means
1968{\it red cannot contain plastic or steel}
1969which can be written as
1970
1971\begin{quote}
1972\begin{verbatim}
1973contents(Col, G, P, S, W, _) :-
1974    Col #= red #=> P #= 0 #/\ S #= 0,
1975    Col #= blue #=> P #= 0 #/\ W #= 0,
1976    Col #= green #=> G #= 0 #/\ S #= 0.
1977\end{verbatim}
1978\end{quote}
1979
1980If we want to model the containment with low-level domain predicates,
1981it is easier to state them in the equivalent conjugate form:
1982\begin{itemize}
1983\item glass can be contained in red or blue
1984\item plastic can be contained in green
1985\item steel can be contained in blue
1986\item wood can be contained in red, green
1987\item copper can be contained in red, blue, green
1988\end{itemize}
1989
1990or in a further equivalent form that uses at most one bin colour:
1991\begin{itemize}
1992\item glass can not be contained in green
1993\item plastic can be contained in green
1994\item steel can be contained in blue
1995\item wood can not be contained in blue
1996\item copper can be contained in anything
1997\end{itemize}
1998
1999\begin{quote}
2000\begin{verbatim}
2001contents(Col, G, P, S, W, _) :-
2002    not_contained_in(Col, G, green),
2003    contained_in(Col, P, green),
2004    contained_in(Col, S, blue),
2005    not_contained_in(Col, W, blue).
2006\end{verbatim}
2007\end{quote}
2008
2009{\bf contained_in(Color, Component, In)} states that
2010if Color is different from In, there can be no such component
2011in it, i.e.\ Component is zero:
2012\begin{quote}
2013\begin{verbatim}
2014contained_in(Col, Comp, In) :-
2015    nonvar(Col),
2016    !,
2017    (Col \== In ->
2018        Comp = 0
2019    ;
2020        true
2021    ).
2022contained_in(Col, Comp, In) :-
2023    dvar_domain(Comp, DM),
2024    dom_range(DM, MinD, _),
2025    (MinD > 0 ->
2026        Col = In
2027    ;
2028        suspend(contained_in(Col, Comp, In), 2, [Comp->min, Col->inst])
2029    ).
2030\end{verbatim}
2031\end{quote}
2032
2033{\bf not_contained_in(Color, Component, In)} states that if the bin is of the given
2034colour, the component cannot be contained in it:
2035\begin{quote}
2036\begin{verbatim}
2037not_contained_in(Col, Comp, In) :-
2038    nonvar(Col),
2039    !,
2040    (Col == In ->
2041        Comp = 0
2042    ;
2043        true
2044    ).
2045not_contained_in(Col, Comp, In) :-
2046    dvar_domain(Comp, DM),
2047    dom_range(DM, MinD, _),
2048    (MinD > 0 ->
2049        Col #\= In
2050    ;
2051        suspend(not_contained_in(Col, Comp, In), 2, [Comp->min, Col->any])
2052    ).
2053\end{verbatim}
2054\end{quote}
2055
2056As you can see again, modeling with the low-level domain predicates
2057might give a faster and more precise programs,
2058but it is much more difficult than using constraint
2059expressions and evaluation constraints.
2060A good approach is thus to start with constraint expressions
2061and only if they are not efficient enough, to (stepwise) recode
2062some or all constraints with the low-level predicates.
2063
2064\subsubsection{Requirement Constraints}
2065The constraint `A requires B' is written as
2066
2067\begin{quote}
2068\begin{verbatim}
2069requires(A, B) :-
2070    A #> 0 #=> B #> 0.
2071\end{verbatim}
2072\end{quote}
2073
2074With low-level predicates,
2075the constraint `A requires B' is woken as soon as some
2076A is present or B is known:
2077\begin{quote}
2078\begin{verbatim}
2079requires(A, B) :-
2080    nonvar(B),
2081    !,
2082    ( B = 0 ->
2083        A = 0
2084    ;
2085        true
2086    ).
2087requires(A, B) :-
2088    dvar_domain(A, DA),
2089    dom_range(DA, MinA, _),
2090    ( MinA > 0 ->
2091        B #> 0
2092    ;
2093        suspend(requires(A, B), 2, [A->min, B->inst])
2094    ).
2095\end{verbatim}
2096\end{quote}
2097
2098\subsubsection{Exclusive Constraints}
2099The exclusive constraint can be written as
2100\begin{quote}
2101\begin{verbatim}
2102exclusive(A, B) :-
2103    A #> 0 #=> B #= 0,
2104    B #> 0 #=> A #= 0.
2105\end{verbatim}
2106\end{quote}
2107however a simple form with one disjunction is enough:
2108\begin{quote}
2109\begin{verbatim}
2110exclusive(A, B) :-
2111    A #= 0 #\/ B #= 0.
2112\end{verbatim}
2113\end{quote}
2114
2115With low-level domain predicates,
2116the exclusive constraint defines a suspension which is woken
2117as soon as one of the two components is present:
2118\begin{quote}
2119\begin{verbatim}
2120exclusive(A, B) :-
2121    dvar_domain(A, DA),
2122    dom_range(DA, MinA, MaxA),
2123    ( MinA > 0 ->
2124        B = 0
2125    ; MaxA = 0 ->
2126        % A == 0
2127        true
2128    ;
2129        dvar_domain(B, DB),
2130        dom_range(DB, MinB, MaxB),
2131        ( MinB > 0 ->
2132            A = 0
2133        ; MaxB = 0 ->
2134            % B == 0
2135            true
2136        ;
2137            suspend(exclusive(A, B), 3, (A,B)->min)
2138        )
2139    ).
2140\end{verbatim}
2141\end{quote}
2142
2143\subsubsection{Atmost Constraints}
2144{\bf at_most(N, In, Colour, Components)} states that if Colour
2145is equal to In, then there can be at most N Components
2146and vice versa, if there are more than N Components, the colour
2147cannot be In.
2148With constraint expressions, this can be simply coded as
2149\begin{quote}
2150\begin{verbatim}
2151at_most(N, In, Col, Comp) :-
2152    Col #= In #=> Comp #<= N.
2153\end{verbatim}
2154\end{quote}
2155
2156A low-level solution looks as follows:
2157\begin{quote}
2158\begin{verbatim}
2159at_most(N, In, Col, Comp) :-
2160    nonvar(Col),
2161    !,
2162    (In = Col ->
2163        Comp #<= N
2164    ;
2165        true
2166    ).
2167at_most(N, In, Col, Comp) :-
2168    dvar_domain(Comp, DM),
2169    dom_range(DM, MinM, _),
2170    (MinM > N ->
2171        Col #\= In
2172    ;
2173        suspend(at_most(N, In, Col, Comp), 2, [In->inst, Comp->min])
2174    ).
2175\end{verbatim}
2176\end{quote}
2177
2178\subsubsection{Ordering Constraints}
2179To filter out symmetric solutions we can e.g.\ impose a lexicographic
2180ordering on the bins in the list, i.e.\ the second bin must be
2181lexicographically greater or equal than the first one etc.
2182As long as the corresponding most significant
2183variables in two consecutive bins
2184are not instantiated, we cannot constrain the following ones
2185and thus we suspend the ordering on the {\bf inst} lists:
2186
2187\begin{quote}
2188\begin{verbatim}
2189ordering([], []).
2190ordering([Val1|Bin1], [Val2|Bin2]) :-
2191    Val1 #<= Val2,
2192    (integer(Val1) ->
2193        (integer(Val2) ->
2194            (Val1 = Val2 ->
2195                ordering(Bin1, Bin2)
2196            ;
2197                true
2198            )
2199        ;
2200            suspend(ordering([Val1|Bin1], [Val2|Bin2]), 2, Val2->inst)
2201        )
2202    ;
2203        suspend(ordering([Val1|Bin1], [Val2|Bin2]), 2, Val1->inst)
2204    ).
2205\end{verbatim}
2206\end{quote}
2207
2208There is a problem with the representation of the colour:
2209If the colour is represented by an atom, we cannot apply
2210the {\bf \#\verb+<=+/2} predicate on it.
2211To keep the ordering predicate simple and still have a symbolic
2212representation of the colour in the program, we can define
2213input macros that transform the colour atoms into integers:
2214
2215\begin{quote}
2216\begin{verbatim}
2217:- define_macro(no_macro_expansion(blue)/0, tr_col/2, []).
2218:- define_macro(no_macro_expansion(green)/0, tr_col/2, []).
2219:- define_macro(no_macro_expansion(red)/0, tr_col/2, []).
2220
2221tr_col(no_macro_expansion(red), 1).
2222tr_col(no_macro_expansion(green), 2).
2223tr_col(no_macro_expansion(blue), 3).
2224\end{verbatim}
2225\end{quote}
2226
2227\subsubsection{Labeling}
2228A straightforward labeling would be to flatten the list with
2229the bins and use e.g.\ \bipref{deleteff/3}{../bips/lib/fd/deleteff-3.html} to label a variable out of it.
2230However, for this example not all variables have the same
2231importance --- the colour variables propagate much more data
2232when instantiated.
2233Therefore, we first filter out the colours and label
2234them before all the component variables:
2235\begin{quote}
2236\begin{verbatim}
2237label(Bins) :-
2238    colours(Bins, Colors, Things),
2239    flatten(Things, List),
2240    labeleff(Colors),
2241    labeleff(List).
2242
2243colours([], [], []).
2244colours([[Col|Rest]|Bins], [Col|Cols], [Rest|Things]) :-
2245    colours(Bins, Cols, Things).
2246
2247labeleff([]).
2248labeleff(L) :-
2249    deleteff(V, L, Rest),
2250    indomain(V),
2251    labeleff(Rest).
2252\end{verbatim}
2253\end{quote}
2254
2255Note also that we need a special version of {\bf flatten/3}
2256that works with nonground lists.
2257
2258\section{Current Known Restrictions and Bugs}
2259
2260\begin{enumerate}
2261
2262\item The default domain for integer finite domain variables
2263is -10000000..10000000.
2264Larger domains must be stated explicitly using the ::/2 predicate,
2265however neither bound can be outside the standard integer
2266range for the machine (usually 32 bits).
2267
2268\item Linear integer terms are processed using machine integers
2269and thus if the maximum or minimum value of a linear term
2270overflows this range (usually 32 bits), incorrect results
2271are reported.
2272This may occur if large coefficients are used, if domains are
2273too large or a combination of the two.
2274
2275\end{enumerate}
2276
2277
2278
2279\index{library!fd.pl|)}
2280