-
Notifications
You must be signed in to change notification settings - Fork 10
/
m-integer.tex.in
executable file
·2771 lines (2402 loc) · 94.1 KB
/
m-integer.tex.in
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% -*- mode: LaTeX; -*-
\chapter{Integer and Boolean variables and constraints}
\label{chap:m:int}
This chapter gives an overview of integer and Boolean variables
and the constraints available for them in Gecode. The chapter
focuses on variables and constraints, a discussion of branching
for integer and Boolean variables can be found in
\autoref{sec:m:branch:int}.
The chapter does not make an attempt to duplicate the reference
documentation (see \gecoderef[group]{TaskModelInt}). It is
concerned with the most important ideas and principles underlying
integer and Boolean variables and constraints. In particular, the
chapter provides entry points into the reference documentation
and points to illustrating examples.
\paragraph{Overview.}
\mbox{}\autoref{sec:m:integer:var} details how integer and Boolean
variables (and variables in general) can be used for modeling.
Variable arrays and argument arrays are discussed in
\autoref{sec:m:integer:proper}. Important aspects of how
constraints are posted in Gecode are explained in
\autoref{sec:m:integer:generic}. These sections belong to the
basic reading material of \autoref{part:m}.
The remaining sections \autoref{sec:m:integer:post} and
\autoref{sec:m:integer:exec} provide an overview of the
constraints that are available for integer and Boolean variables
in Gecode.
\begin{important}
Do not forget to add
\begin{code}
#include <gecode/int.hh>
\end{code}
to your program when you want to use integer or Boolean variables
and constraints.
\end{important}
\begin{convention}
All program fragments and references to classes, namespaces,
and other entities assume that declarations and definitions
from the \?Gecode? namespace are visible: for example, by
adding
\begin{code}
using namespace Gecode;
\end{code}
to your program.
The variable \?home? refers to a space reference (of type
\?Space&?) and defines the home space in which new variables,
propagators, and branchers are posted. Often (as in
\autoref{chap:m:started} and \autoref{chap:m:comfy}) \?home? will
be \?*this?, referring to the current space.
\end{convention}
\section{Integer and Boolean variables}
\label{sec:m:integer:var}
Variables in Gecode are for modeling. They provide operations for
creation, access, and update during cloning. By design, the only
way to modify (constrain) a variable is by post functions for
constraints and branchers.
Integer variables are instances of the class
\gecoderef[class]{IntVar} while Boolean variables are instances
of the class \gecoderef[class]{BoolVar}. Integer variables are
\emph{not} related to Boolean variables. A Boolean variable is
\emph{not} an integer variable with a domain that is included in
$\{0,1\}$. The only way to get an integer variable that is equal
to a Boolean variable is by posting a channeling constraint
between them (see
\autoref{sec:m:integer:channel}).
\tip{Do not use views for modeling}{%
If you --- after some browsing of the reference documentation
--- should come across integer views such as \?IntView?, you
might notice that views have a richer interface than
integer variables. You might feel that this interface looks too
powerful to be ignored. Now, you really should put some trust in
this document: views are \emph{not} for modeling.
The more powerful interface only works within propagators and
branchers, see \autoref{part:p} and \autoref{part:b}. }
\subsection{Creating integer variables}
\label{sec:m:integer:create}
A variable provides a read-only interface to a \emph{variable
implementation} where the same variable implementation can be
referred to by arbitrarily many variables.
New integer variables are created by using a constructor. A new integer variable \?x? is created
by
\begin{code}
IntVar x(home, -4, 20);
\end{code}
This declares a variable \?x? of type \gecoderef[class]{IntVar}
in the space \?home?, creates a new integer \emph{variable
implementation} with domain $\{-4,\ldots,20\}$, and points \?x?
to the newly created integer variable implementation.
The domain of a variable can also be specified by an
integer set \gecoderef[class]{IntSet}, for example by
\begin{code}
IntVar x(home, IntSet(-4, 20));
\end{code}
which creates a new variable with domain $\{-4,\ldots,20\}$. An
attempt to create an integer variable with an empty domain throws
an exception of type \gecoderef[class]{Int::VariableEmptyDomain}.
Integer sets can be initialized by an array of integers, for
example
\begin{code}
int v[] = {1,2,3,4};
IntSet c(v, 4);
\end{code}
initializes \?c? to have the four elements (as defined by the
second argument~\?4? in the constructor call)
$\{\mathtt{1},\mathtt{2},\mathtt{3},\mathtt{4}\}$,
whereas
\begin{code}
int r[][2] = {{1,2},{5,7}};
IntSet d(r, 2);
\end{code}
initializes \?d? to have the elements
$\{\mathtt{1},\mathtt{2},\mathtt{5},\mathtt{6},\mathtt{7}\}$
where \?r? is an array of pairs expressing ranges of values.
The same can be expressed with initializer lists as in
\begin{code}
IntSet c({1,2,3,4});
IntSet d({{1,2},{5,7}});
\end{code}
Please note the difference between \?IntSet({1,3})? and
\?IntSet(1,3)?: the former has the elements
$\{\mathtt{1},\mathtt{3}\}$.
while the latter has the elements $\{\mathtt{1},\mathtt{2},\mathtt{3}\}$.
The default or copy constructor of a variable does not create a
new variable (that is, a new variable implementation). Instead,
the variable does not refer to any variable implementation
(default constructor) or to the same variable implementation
(copy constructor). For example, in
\begin{code}
IntVar x(home, 1, 4);
IntVar y(x);
\end{code}
both \?x? and \?y? refer to the same integer variable
implementation. Using a default constructor and
an assignment operator is equivalent:
\begin{code}
IntVar x(home, 1, 4);
IntVar y;
y=x;
\end{code}
\subsection{Limits for integer values}
\label{sec:m:integer:limits}
The set of values for an integer variable is a subset of the
values of the type \?int?. The set of values is symmetric:
$-\mbox{\?Int::Limits::min?}=\mbox{\?Int::Limits::max?}$ for the
smallest possible integer variable value \?Int::Limits::min? and the
largest possible integer variable value \?Int::Limits::max?. Moreover,
\?Int::Limits::max? is strictly smaller than the largest possible
integer value \?INT_MAX? and \?Int::Limits::min? is strictly
larger than the smallest possible integer value \?INT_MIN?. These
limits are defined in the namespace \gecoderef[namespace]{Int::Limits}.
Any attempt to create a variable with values outside the defined
limits throws an exception of type
\gecoderef[class]{Int::OutOfLimits}. The same holds true for any
attempt to use an integer value outside the defined limits when
posting a constraint or brancher.
\subsection{Variable domains are never empty}
\label{sec:m:integer:empty}
An important invariant in Gecode is that the domain of a variable
is never empty. When a variable domain should become empty during
propagation, the space is failed but the variable's domain is
kept. In fact, this is the very reason why an attempt to create
a variable with an empty domain, for example by
\begin{code}
IntVar x(home, 1, 0);
\end{code}
throws an exception of type
\gecoderef[class]{Int::VariableEmptyDomain}.
\tip{Small variable domains are beautiful}{%
\label{tip:m:integer:beautifuldomains}%
It is not an omission that an integer variable has no
constructor that creates a variable with the largest possible
domain. One could argue that a constructor like that would come
in handy for creating temporary variables. After all, one would
not have to worry about the exact domain!
Sorry, but one has to worry. The apparent omission is
deliberate to make you worry indeed. For many propagators
posted for a constraint a small domain is essential. For
example, when posting a \?linear? constraint (as in
\autoref{sec:m:started:first}), variable domains that are too
large might result in an exception of type
\gecoderef[class]{Int::OutOfLimits} as during propagation
numerical overflow might occur (even if Gecode resorts to a
number type supporting larger numbers than \?int? for
propagating \?linear?). Moreover, the runtime of other
propagators (for example, many domain propagators
such as domain consistent \?distinct?) depend critically on the
size of a domain. Again, Gecode tries to be clever in most of
the cases. But, it is better to make it a habit to think about
initial variable domains carefully (please remember: better
safe than sorry).
For examples where small variable domains matter, see
\autoref{tip:c:golomb:beautifuldomains} and
\autoref{tip:c:warehouses:beautifuldomains}.
}
\subsection{Creating Boolean variables}
The only difference between integer and Boolean variables is that
Boolean variables can only take the values \?0? or \?1?. Any
attempt to create a Boolean variable with values different from
\?0? or \?1? throws an exception of type
\gecoderef[class]{Int::NotZeroOne}.
\begin{convention}
If Boolean variables are not explicitly mentioned in the following, the
same functionality for integer variables is also available for
Boolean variables and has the same behavior.
\end{convention}
\subsection{Variable access functions}
Variables provide member functions for access, such as \?x.min()?
for the minimum value of the current domain for an integer or
Boolean variable \?x?. In particular, the member function
\?x.val()? accesses the integer value of an already assigned
variable (if the variable is not yet assigned, an exception of
type \gecoderef[class]{Int::ValOfUnassignedVar} is thrown). In
addition, variables can be printed by the standard output
operator \?<<?.
%>>
\subsection{Iterating over integer variable domains}
\label{sec:m:int:iter}
The entire domain of an integer variable can be accessed by a
\emph{value iterator} \gecoderef[class]{IntVarValues} or a
\emph{range iterator} \gecoderef[class]{IntVarRanges}. For
example, the loop
\begin{code}
for (IntVarValues i(x); i(); ++i)
std::cout << i.val() << ' ';
\end{code}
%>>
uses the value iterator \?i? to print all values of the domain of
the integer variable \?x?. The call operator \?i()? tests whether
there are more values to iterate for \?i?, the prefix increment
operator \?++i? moves the iterator \?i? to the next value, and
\?i.val()? returns the current value of the iterator \?i?. The
values are iterated in strictly increasing order.
Similarly, the following loop
\begin{code}
for (IntVarRanges i(x); i(); ++i)
std::cout << i.min() << ".." << i.max() << ' ';
\end{code}
%>>
uses the range iterator \?i? to print all \emph{ranges} of the
integer variable \?x?. Given a finite set of integers $d$, the
\emph{range sequence} of $d$ is the shortest (and unique) sequence of ranges
(intervals)
$$
\langle\range{n_0}{m_0}\},\ldots,\range{n_k}{m_k}\}\rangle
$$
such that the sequence is ordered and non-adjacent
($m_i+1<n_{i+1}$ for $0\leq i<k$). A range iterator iterates over
the ranges in the range sequence of a variable's domain. Like a value
iterator, a range iterator implements the call operator \?i()? to test
whether there are more ranges to iterate for \?i? and the prefix
increment operator \?++i? to move \?i? to the next range. As a
range iterator \?i? iterates over ranges, it implements the
member functions \?i.min()? and \?i.max()? for the minimal,
respectively maximal, value of the current range.
Iteration of values and ranges for Boolean variables is not
available (as it is not needed).
\subsection{When to inspect a variable}
\label{sec:m:integer:inspect}
Note that one must not change the domain of a variable (for
example, by posting a constraint on that variable) while an
iterator for that variable is still in use. This is the same as
for most iterators, for example, for iterators in the \CPP{}
Standard Template Library (STL).
Otherwise, a variable can always be inspected: at any place (that
is, not only in member functions of the variable's home) and at
any time (regardless of the status of a space). If the variable's
home is failed, the variable can still be inspected. However, it
might be the case that the variable domain has more values than
expected. For example, after creating a variable \?x? with the
singleton domain $\{0\}$ and posting the constraint that \?x?
must be different from \?0? by (read \autoref{tip:m:started:status}
about \?status()?):
\begin{code}
IntVar x(home, 0, 0);
rel(home, x, IRT_NQ, 0);
(void) home.status();
\end{code}
the space \?home? is failed but the variable \?x? still contains
the value \?0? in its domain.
\subsection{Updating variables}
\label{sec:m:integer:update}
As discussed in \autoref{sec:m:started:first}, a variable must be
updated during cloning in the copy constructor used by a space's
\?copy()? member function. For example, a variable \?x? is updated
by
\begin{code}
x.update(home, y);
\end{code}
where \?y? is the variable from which \?x? is to be
updated. While \?x? belongs to \?home?, \?y? belongs
to the space being cloned.
A space only needs to update the variables that are part of the
solution, so that their values can be accessed after a solution
space has been found. Temporary variables do not need to be
copied.
Assume that we want to constrain the integer
variable \?p? to be the product of \?x?, \?y?, and \?z?. Gecode
only offers multiplication of two variables, hence a temporary
variable \?t? is created (assume also that we know that the
values for \?t? are between \?0? and \?1000?):
\begin{code}
IntVar t(home, 0, 1000);
mult(home, x, y, t);
mult(home, t, z, p);
\end{code}
Here, \?t? does not require updating. The multiplication
propagators created by \?mult? take care of updating the variable
implementation of \?t?.
\section{Variable and argument arrays}
\label{sec:m:integer:proper}
Gecode has very few \emph{proper} data structures. The proper
data structures for integer and Boolean variables are the
variables themselves, integer sets, and arrays of variables.
Proper means that these data structures can be updated and hence
be stored in a space.
Of course, data structures that themselves do not contain proper
data structures can be stored in a space, such as integers,
pointers, and strings.
Gecode supports the programming of new proper data structures,
this is discussed in \autoref{sec:p:memory:shared}.
\subsection{Integer and Boolean variable arrays}
\label{sec:m:integer:intvararray}
Integer variable arrays of type \gecoderef[class]{IntVarArray}
can be used like variables. For example,
\begin{code}
IntVarArray x(home, 4, -10, 10);
\end{code}
creates a new integer variable array with four variables
containing newly created variables with domain
$\{-10,\ldots,10\}$. Boolean variable arrays of type
\gecoderef[class]{BoolVarArray} are analogous.
Creation of a variable array allocates memory from the home
space. The memory is freed when the space is deleted (not
when the destructor of the variable array is called). Variable
arrays can be created without creating new variables by just
passing the size. That is,
\begin{code}
IntVarArray x(home, 4);
for (int i=0; i<4; i++)
x[i] = IntVar(home, -10, 10);
\end{code}
is equivalent to the previous example.
The other operations on variable arrays are as one would expect.
For example, one can check whether all variables are assigned
using the \?assigned()? function. More importantly, variable arrays
like variables have an update
function and variable arrays must be updated during cloning. In
the following, we will refer to the size of a variable array \?x?
by $|\mathtt x|$ (which can be computed by \?x.size()?).
\paragraph{Matrix interface.}
Many models are naturally expressed by using matrices. Gecode
offers support that superimposes a matrix interface for modeling
on an array, see \autoref{sec:m:minimodel:matrix}.
\subsection{Argument arrays}
\label{sec:m:integer:args}
As mentioned above, the memory allocated for a variable array is
freed only when its home space is deleted. That makes variable
arrays \emph{unsuited} for temporary variable arrays, in particular
for arrays that are built dynamically or used as arguments for post
functions.
For this reason, Gecode provides argument arrays: \?IntVarArgs? for
integer variables, \?BoolVarArgs? for Boolean variables,
\?IntArgs? for integers, and \?IntSetArgs? for integer sets (see
\gecoderef[group]{TaskModelIntArgs}). Internally, they allocate
space from the heap\footnote{Actually, if an argument array has
few fields it uses some space that is part of the object
implementing the array rather than allocating memory from the
heap. Hence, small argument arrays reside entirely on the
stack.} and the memory is freed when their destructor is
executed.
Argument arrays can be created empty:
\begin{code}
IntVarArgs x;
\end{code}
with a certain size but without initializing the elements:
\begin{code}
IntVarArgs x(5);
\end{code}
using standard initializer lists (assuming that \?a?, \?b?, \?c?,
and \?d? are integer variables):
\begin{code}
IntVarArgs x({a,b,c,d});
\end{code}
or fully initialized:
\begin{code}
IntVarArgs x(home,5,0,10);
\end{code}
For a typical example, consider \autoref{sec:m:started:first} where
an integer argument array and an integer variable argument array
are used to pass coefficients and variables to the \?linear? post
function.
\paragraph{Dynamic argument arrays.}
In contrast to variable arrays, argument arrays can grow dynamically by adding
elements or whole arrays using \?operator<<?:
\begin{code}
IntVarArgs x;
x << IntVar(home,0,10);
IntVarArgs y;
y << IntVar(home,10,20);
y << x;
linear(home, IntVarArgs()<<x[0]<<x[1], IRT_EQ, 0);
\end{code}
Furthermore, argument arrays can be concatenated using \?operator+?:
\begin{code}
IntVarArgs z = x+y;
\end{code}
\paragraph{Slices.}
It is sometimes necessary to post constraints on a subsequence of
the variables in an array. This is made possible by the
\?slice(start,inc,n)? method of variable and argument arrays. The
\?start? parameter gives the starting index of the subsequence.
The \?inc? optional parameter gives the increment, i.e., how to
get from one element to the next (its default is $1$). The \?n?
parameter gives the maximal length of the resulting array (its
default is $-1$, meaning as long as possible).
The following examples should make this clearer. Assume that the
integer variable argument array \?x? is initialized as
follows:
\begin{code}
IntVarArgs x(home, 10, 0, 10);
\end{code}
Then the following calls of \?slice()? return:
\begin{itemize}
\item \?x.slice(5)? returns an array with elements \?x[5],x[6],...,x[9]?.
\item \?x.slice(5,1,3)? returns \?x[5],x[6],x[7]?.
\item \?x.slice(5,-1)? returns \?x[5],x[4],...,x[0]?.
\item \?x.slice(3,3)? returns \?x[3],x[6],x[9]?.
\item \?x.slice(8,-2)? returns \?x[8],x[6],x[4],x[2],x[0]?.
\item \?x.slice(8,-2,3)? returns \?x[8],x[6],x[4]?.
\end{itemize}
\tip{Reversing argument arrays}{%
The \?slice()? method can be used to compute an array with the
elements of \?x? in reverse order like this:
\begin{code}
x.slice(x.size()-1,-1)
\end{code}
}
\paragraph{Creating integer argument arrays.}
Integer argument arrays support standard initializer lists, for
example
\begin{code}
IntArgs c({0,1,2,3});
\end{code}
creates an array with the four elements \?0?, \?1?, \?2?, and
\?3?.
Integer argument arrays with simple sequences of integers can be
generated using the static method
\?IntArgs::create(n,start,inc)?. The \?n? parameter gives the
length of the generated array. The \?start? parameter is the
starting value, and \?inc? determines the increment from one
value to the next.
Here are a few examples:
\begin{itemize}
\item \?IntArgs::create(5,0)? creates an array with elements
\?0,1,2,3,4?.
\item \?IntArgs::create(5,4,-1)? creates \?4,3,2,1,0?.
\item \?IntArgs::create(3,2,0)? creates \?2,2,2?.
\item \?IntArgs::create(6,2,2)? creates \?2,4,6,8,10,12?.
\end{itemize}
\begin{litcode}[texonly]{dynamic script}
class Script : public Space {
IntVarArray x;
public:
Script(void) {
\begin{litblock}{read data}
IntVarArgs _x;
while (...) {
...
_x << IntVar(*this,...);
}
\end{litblock}
...
\begin{litblock}{initialize variable array}
x = IntVarArray(*this,_x);
\end{litblock}
}
...
}
\end{litcode}
\tip{Dynamically constructing models}{%
Sometimes the number of variables cannot be determined easily,
for example when it depends on data read from a file.
\begin{samepage}
Suppose
the following script with a variable array \?x?:
\insertlitcode{dynamic script}
\end{samepage}
It is easy to use a variable argument array \?_x? for
collecting variables as follows:
\insertlitcode{dynamic script:read data}
and then initialize the variable array \?x?
using the argument array:
\insertlitcode{dynamic script:initialize variable array}
}
In the following we do not distinguish between arrays and
argument arrays unless operations require a certain type of
array. In fact, all post functions for constraints and branchers
only accept variable argument arrays. A variable array is
automatically casted to a variable argument array if needed.
\subsection{STL-style iterators}
\label{sec:m:integer:stl}
All arrays in Gecode (including variable arrays and argument
arrays) also support STL-style (Standard Template Library) iterators. For example, assume
that \?a? is an integer variable argument array. Then
\begin{code}
for (IntVarArgs::iterator i = a.begin(); i != a.end(); ++i) {
...
}
\end{code}
creates an iterator \?i? for the elements of \?a? and iterates
from the first to the last element in~\?a?.
More powerfully, iterators give you the ability to work with STL
algorithms. Suppose that \?f()? is a function that takes an
integer variable by reference such as in
\begin{code}
void f(IntVar& x) { ... }
\end{code}
and \?a? is an integer variable argument array. Then
\begin{code}
#include <algorithm>
std::for_each(a.begin(), a.end(), f);
\end{code}
applies the function \?f()? to each integer variable in \?a?.
\section{Posting constraints}
\label{sec:m:integer:generic}
This section provides information about general principles for
posting constraints over integer and Boolean variables.
\subsection{Post functions are clever}
A constraint post function carefully analyzes its
arguments. Based on this analysis, the constraint post function
chooses the best possible propagator for the constraint.
For
example, when posting a \?distinct? constraint (see
\autoref{sec:m:integer:distinct}) for the variable array \?x? by
\begin{code}
distinct(home, x);
\end{code}
where \?x? has two elements, the much more efficient propagator
for disequality $\mathtt{x}_0 \neq \mathtt{x}_1$ is created.
\subsection{Everything is copied}
When passing arguments to a post function, all data structures
that are needed for creating a propagator (or several
propagators) implementing a constraint are copied. That is, none
of the data structures that are passed as arguments are needed
after a constraint has been posted.
\subsection{Reified constraints}
\label{sec:m:integer:reify}
Many constraints also exist as \emph{reified} variants: the
validity of a constraint is reflected to a Boolean control
variable (reified constraints are also known as
meta-constraints). In addition to full reification also half
reification~\cite{HalfReify} is supported for reified
constraints. Whether a reified version exists for a given
constraint can be found in the reference documentation. If a
reified version does exist, the Boolean control variable (and
possibly information about the reification mode, to be discussed
in \autoref{sec:m:integer:halfreify}) is passed as the last
non-optional argument.
For example, posting
\begin{code}
rel(home, x, IRT_EQ, y, b);
\end{code}
for integer variables \?x? and \?y? and a Boolean control
variable \?b? creates a propagator for the reified constraint
$\reifyeqv{\mathtt{b}}{\mathtt{x}=\mathtt{y}}$ that propagates
according to the following rules:
\begin{itemize}
\item If \?b? is assigned to \?1?, the constraint
$\mathtt{x}=\mathtt{y}$ is propagated.
\item If \?b? is assigned to \?0?, the constraint
$\mathtt{x}\neq\mathtt{y}$ is propagated.
\item If the constraint $\mathtt{x}=\mathtt{y}$ holds, then
$\mathtt{b}=\mathtt{1}$ is propagated.
\item If the constraint $\mathtt{x}\neq\mathtt{y}$ holds, then
$\mathtt{b}=\mathtt{0}$ is propagated.
\end{itemize}
\subsection{Half reification}
\label{sec:m:integer:halfreify}
Reification as discussed in the previous paragraph is also known
as \emph{full} reification as it propagates a full equivalence
between the constraint $c$ and the constraint that a Boolean
control variable is equal to \?1?. \emph{Half reification}
propagates only one direction of the
equivalence~\cite{HalfReify}. Half reification can be used by
passing an object of class \gecoderef[class]{Reify} that combines
a Boolean control variable and a \emph{reification mode} of type
\?ReifyMode? (see \gecoderef[group]{TaskModelInt}).
For example, the half reified constraint
$\reifyimp{\mathtt{b}}{\mathtt{x}=\mathtt{y}}$ for
integer variables \?x? and \?y? and a Boolean control variable
\?b? can be posted by
\begin{code}
Reify r(b, RM_IMP);
rel(home, x, IRT_EQ, y, r);
\end{code}
and is propagated as follows (\?RM_IMP? suggests
\emph{implication} $\Rightarrow$):
\begin{itemize}
\item If \?b? is assigned to \?1?, the constraint
$\mathtt{x}=\mathtt{y}$ is propagated.
\item If the constraint $\mathtt{x}\neq\mathtt{y}$ holds, then
$\mathtt{b}=\mathtt{0}$ is propagated.
\end{itemize}
Likewise, the half reified constraint
$\reifypmi{\mathtt{b}}{\mathtt{x}=\mathtt{y}}$ for
integer variables \?x? and \?y? and a Boolean control variable
\?b? can be posted by
\begin{code}
Reify r(b, RM_PMI);
rel(home, x, IRT_EQ, y, r);
\end{code}
and is propagated as follows (\?RM_PMI? suggests \emph{inverse
implication} $\Leftarrow$):
\begin{itemize}
\item If \?b? is assigned to \?0?, the constraint
$\mathtt{x}\neq\mathtt{y}$ is propagated.
\item If the constraint $\mathtt{x}=\mathtt{y}$ holds, then
$\mathtt{b}=\mathtt{1}$ is propagated.
\end{itemize}
Full reification can be requested by the reification mode
\?RM_EQV? (for equivalence $\Leftrightarrow$) as follows:
\begin{code}
Reify r(b, RM_EQV);
rel(home, x, IRT_EQ, y, r);
\end{code}
As the constructor for \gecoderef[class]{Reify} has \?RM_EQV? as
default value for its second argument, this can be written
shorter as:
\begin{code}
Reify r(b);
rel(home, x, IRT_EQ, y, r);
\end{code}
or even shorter as:
\begin{code}
rel(home, x, IRT_EQ, y, b);
\end{code}
For convenience, three functions \?eqv()?, \?imp()?, and \?pmi()?
exist that take a Boolean variable and return a corresponding
object of class \gecoderef[class]{Reify}. For example, instead of
writing:
\begin{code}
Reify r(b, RM_IMP);
rel(home, x, IRT_EQ, y, r);
\end{code}
one can write more concisely:
\begin{code}
rel(home, x, IRT_EQ, y, imp(b));
\end{code}
\subsection{Selecting the propagation level}
\label{sec:m:integer:ipl}
For many constraints, Gecode provides different propagators with
different levels of propagation. All constraint post functions take an
optional argument of type \?IntPropLevel? (see
\gecoderef[group]{TaskModelInt}) controlling which propagator is
chosen for a particular constraint.
The different simple values for \?IntPropLevel? have the
following meaning:
\begin{itemize}
\item \?IPL_VAL?: perform value propagation. A typical example is
naive \?distinct?: wait until a variable becomes assigned to a
value $n$, then prune $n$ from all other variables.
\item \?IPL_BND?: perform bounds propagation or achieve bounds
consistency. This captures both bounds consistency over the
integers (for example, for \?distinct?, see
\autoref{sec:m:integer:distinct}) or bounds consistency over
the real numbers (for example, for \?linear?, see
\autoref{sec:m:integer:linear}). For more information on bounds
consistency over integers or real numbers,
see~\cite{bounds-consistency}.
Some propagators that are selected might not even achieve
bounds consistency but the idea is that the propagator performs
propagation by reasoning on the bounds of variable domains.
\item \?IPL_DOM?: perform domain propagation or achieve domain
consistency. Most propagators selected by \?IPL_DOM? achieve
domain consistency but some just perform propagation by taking
entire variable domains for propagation into account (for
example, \?circuit?, see \autoref{sec:m:integer:circuit}).
\item \?IPL_DEF?: choose default propagation level for this
constraint.
\end{itemize}
Whether bounds or domain consistency is achieved and the default
propagation level for a constraint are mentioned in the reference
documentation for each post function.
In addition to the basic propagation levels listed above, the
following pre-defined values exist:
\begin{itemize}
\item \?IPL_BASIC?: try to optimize for execution performance at
the expense of performing less propagation.
\item \?IPL_ADVANCED?: try to optimize for more propagation at
the expensive of being less efficient.
\end{itemize}
The propagation levels can be specified as disjunctions, for
example \?IPL_DEF|IPL_BASIC? requests basic default propagation
which is equivalent to \?IPL_BASIC? (the \?IPL_DEF? can always
be omitted). Note that in particular the combination
\?IPL_BASIC|IPL_ADVANCED? is meaningful requesting both basic and
advanced propagation to be performed.
Some scheduling constraints, see
\autoref{sec:m:integer:scheduling}, support basic and advanced
propagation levels.
\tip{Different propagation levels have different costs}{
Note that propagators of different propagation level for the
very same constraint can have vastly different cost. In
general, propagation for \?IPL_VAL? will be cheapest, while
propagation for \?IPL_DOM? will be most expensive.
The reference documentation for a constraint lists whether a
particular propagation level might have prohibitive cost for a
large number of variables or a large number of values in the
variables' domains. For example, for the \?linear? constraint
with $n$ variables and at most $d$ values for each variable,
the complexity to perform bounds propagation (that is,
\?IPL_BND?) is $O(n)$ whereas the complexity for domain
propagation (that is, \?IPL_DOM?) is $O(d^n)$.
}
\subsection{Exceptions}
Many post functions check their arguments for consistency before
attempting to create a propagator. For each post function, the
reference documentation lists which exceptions might be thrown.
\subsection{Unsharing arguments}
Some constraints can only deal with \emph{non-shared} variable
arrays: a variable is not allowed to appear more than once in the
array (more precisely: no unassigned variable implementation
appears more than once in the array). An attempt to post one of these
constraints with shared variable arrays will throw an exception
of type \gecoderef[class]{Int::ArgumentSame}.
To be able to post one of these constraints on shared variable
arrays, Gecode provides a function \?unshare? (see
\gecoderef[group]{TaskModelIntUnshare}) that takes a variable
argument array \?x? as argument as in:
\begin{code}
unshare(home, x);
\end{code}
It replaces each but the first occurrence of a variable $y$ in
\?x? by a new variable $z$, and creates a propagator $y=z$ for
each new variable $z$.
Note that \?unshare? requires a variable argument array and
\emph{not} a variable array. If \?x? is a variable array, the
following
\begin{code}
IntVarArgs y(x);
\end{code}
creates a variable argument array \?y? containing the same
variables as \?x?.
\tip{Unsharing is expensive}{%
It is important to keep in mind that \?unshare? creates new
variables and propagators. This is also the reason why
unsharing is not done implicitly by a post function for a
constraint that does not accept shared variable arrays.
\begin{samepage}
Consider the following example using \?extensional? constraints
for a variable argument array \?x? possibly containing a
variable more than once, where \?a? and \?b? are two different
DFAs (see \autoref{sec:m:integer:extensional} for \?extensional?
constraints). By
\begin{code}
unshare(home, x);
extensional(home, x, a);
extensional(home, x, b);
\end{code}
\end{samepage}
multiple occurrences of the same variable in \?x? are unshared
\emph{once} and the propagators for extensional can work on the
same non-shared array.
If unsharing were implicit, the following
\begin{code}
extensional(home, x, a);
extensional(home, x, b);
\end{code}
would unshare \?x? twice and create many more (useless)
propagators and variables. Rather than implicitly unsharing the
same array over and over again (and hence creating variables and
propagators), unsharing is made explicit and should be done only
once, if possible.
}
\section{Constraint overview}
\label{sec:m:integer:post}
This section provides an overview of the constraints and their
post functions available for integer and Boolean variables.
\subsection{Domain constraints}
\label{sec:m:integer:dom}
\gecoderef[group]{TaskModelIntDomain} constrain integer variables
and variable arrays to values from a given domain. For example,
by
\begin{code}
dom(home, x, 2, 12);
\end{code}
the values of the variable \?x? (or of all variables in a
variable array \?x?) are constrained to be between $2$ and $12$.
Domain constraints also take integers (assigning variables to the
integer value) and integer sets of type
\gecoderef[class]{IntSet}. For example,
\begin{code}
IntArgs a({1,-3,5,-7})
IntSet d(a);
dom(home, x, d);
\end{code}
constrains the variable \?x? (or, the variables in \?x?) to take
values from the set $\{-7,-3,1,5\}$
\GCCAT{\CAT[int]{domain,in,in_interval,in_intervals,in_set}{dom}{TaskModelIntDomain}}.
Note that there are no domain constraints for Boolean variables,
please use relation constraints instead, see
\autoref{sec:m:integer:rel:bool}.
The domain of an integer or Boolean variable \?x? can be
constrained according to the domain of another variable \?d? by
\begin{code}
dom(home, x, d);
\end{code}
Here, \?x? and \?d? can also be arrays of integer or Boolean
variables. Note that this needs to be used carefully, the domain
to which the variable \?x? is constrained depends on the domain
to which \?d? is constrained. Only use this constraint post
function if you are sure that all propagation that could
influence the domain of \?d? has been performed!
Domain constraints for a single variable also support
reification. For examples using domain constraints, see
\gecoderef[example]{knights:KnightsReified} and
\gecoderef[example]{perfect-square}.
\subsection{Membership constraints}
\label{sec:m:integer:member}
\gecoderef[group]{TaskModelIntMember} constrain integer or
Boolean variables to be included in an array of integer or
Boolean variables. That is, for an integer variable array \?x? and an
integer variable \?y?, the constraint
\begin{code}
member(home, x, y);
\end{code}
forces that \?y? is included in \?x?:
$$
\mathtt{y}\in\left\{\mathtt{x}_0,\ldots,\mathtt{x}_{|\mathtt{x}|-1}\right\}
$$
As mentioned, \?x? and \?y? can also be Boolean variables.
Membership constraints also support reification.
% \CAT[int]{-}{member}{TaskModelIntMember}
\subsection{Simple relation constraints over integer variables}
\label{sec:m:integer:rel:int}
\begin{figure}
\begin{center}
\begin{tabular}{l@{\quad}l@{\qquad}l@{\quad}l}
\?IRT_EQ? & equality ($=$) &
\?IRT_NQ? & disequality ($\neq$) \\
\?IRT_LE? & strictly less inequality ($<$) &
\?IRT_LQ? & less or equal inequality ($\leq$) \\
\?IRT_GR? & strictly greater inequality ($>$) &
\?IRT_GQ? & greater or equal inequality ($\geq$)
\end{tabular}
\end{center}
\caption{Integer relation types}
\label{fig:m:integer:irt}
\end{figure}
\gecoderef[group]{TaskModelIntRelInt} enforce relations between
integer variables and between integer variables and integer
values. The relation depends on an integer relation type
\?IntRelType? (see \gecoderef[group]{TaskModelIntRelInt}).
\autoref{fig:m:integer:irt} lists the available integer relation
types and their meaning.
\paragraph{Binary relation constraints.}
Assume that \?x? and \?y? are integer variables. Then
\begin{code}
rel(home, x, IRT_LE, y);