forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcp_model.py
More file actions
1849 lines (1507 loc) · 67.3 KB
/
cp_model.py
File metadata and controls
1849 lines (1507 loc) · 67.3 KB
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
# Copyright 2010-2018 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Methods for building and solving CP-SAT models.
The following two sections describe the main
methods for building and solving CP-SAT models.
* [`CpModel`](#cp_model.CpModel): Methods for creating
models, including variables and constraints.
* [`CPSolver`](#cp_model.CpSolver): Methods for solving
a model and evaluating solutions.
The following methods implement callbacks that the
solver calls each time it finds a new solution.
* [`CpSolverSolutionCallback`](#cp_model.CpSolverSolutionCallback):
A general method for implementing callbacks.
* [`ObjectiveSolutionPrinter`](#cp_model.ObjectiveSolutionPrinter):
Print objective values and elapsed time for intermediate solutions.
* [`VarArraySolutionPrinter`](#cp_model.VarArraySolutionPrinter):
Print intermediate solutions (variable values, time).
* [`VarArrayAndObjectiveSolutionPrinter`]
(#cp_model.VarArrayAndObjectiveSolutionPrinter):
Print both intermediate solutions and objective values.
Additional methods for solving CP-SAT models:
* [`Constraint`](#cp_model.Constraint): A few utility methods for modifying
contraints created by `CpModel`.
* [`LinearExpr`](#lineacp_model.LinearExpr): Methods for creating constraints
and the objective from large arrays of coefficients.
Other methods and functions listed are primarily used for developing OR-Tools,
rather than for solving specific optimization problems.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import numbers
import time
from six import iteritems
from ortools.sat import cp_model_pb2
from ortools.sat import sat_parameters_pb2
from ortools.sat.python import cp_model_helper
from ortools.sat import pywrapsat
from ortools.util import sorted_interval_list
Domain = sorted_interval_list.Domain
# Documentation cleaning.
# Remove the documentation of some functions.
# See https://pdoc3.github.io/pdoc/doc/pdoc/#overriding-docstrings-with-
__pdoc__ = {}
__pdoc__['DisplayBounds'] = False
__pdoc__['EvaluateLinearExpr'] = False
__pdoc__['EvaluateBooleanExpression'] = False
__pdoc__['ShortName'] = False
# The classes below allow linear expressions to be expressed naturally with the
# usual arithmetic operators +-*/ and with constant numbers, which makes the
# python API very intuitive. See ../samples/*.py for examples.
INT_MIN = -9223372036854775808 # hardcoded to be platform independent.
INT_MAX = 9223372036854775807
INT32_MAX = 2147483647
INT32_MIN = -2147483648
# CpSolver status (exported to avoid importing cp_model_cp2).
UNKNOWN = cp_model_pb2.UNKNOWN
MODEL_INVALID = cp_model_pb2.MODEL_INVALID
FEASIBLE = cp_model_pb2.FEASIBLE
INFEASIBLE = cp_model_pb2.INFEASIBLE
OPTIMAL = cp_model_pb2.OPTIMAL
# Variable selection strategy
CHOOSE_FIRST = cp_model_pb2.DecisionStrategyProto.CHOOSE_FIRST
CHOOSE_LOWEST_MIN = cp_model_pb2.DecisionStrategyProto.CHOOSE_LOWEST_MIN
CHOOSE_HIGHEST_MAX = cp_model_pb2.DecisionStrategyProto.CHOOSE_HIGHEST_MAX
CHOOSE_MIN_DOMAIN_SIZE = (
cp_model_pb2.DecisionStrategyProto.CHOOSE_MIN_DOMAIN_SIZE)
CHOOSE_MAX_DOMAIN_SIZE = (
cp_model_pb2.DecisionStrategyProto.CHOOSE_MAX_DOMAIN_SIZE)
# Domain reduction strategy
SELECT_MIN_VALUE = cp_model_pb2.DecisionStrategyProto.SELECT_MIN_VALUE
SELECT_MAX_VALUE = cp_model_pb2.DecisionStrategyProto.SELECT_MAX_VALUE
SELECT_LOWER_HALF = cp_model_pb2.DecisionStrategyProto.SELECT_LOWER_HALF
SELECT_UPPER_HALF = cp_model_pb2.DecisionStrategyProto.SELECT_UPPER_HALF
# Search branching
AUTOMATIC_SEARCH = sat_parameters_pb2.SatParameters.AUTOMATIC_SEARCH
FIXED_SEARCH = sat_parameters_pb2.SatParameters.FIXED_SEARCH
PORTFOLIO_SEARCH = sat_parameters_pb2.SatParameters.PORTFOLIO_SEARCH
LP_SEARCH = sat_parameters_pb2.SatParameters.LP_SEARCH
def DisplayBounds(bounds):
"""Displays a flattened list of intervals."""
out = ''
for i in range(0, len(bounds), 2):
if i != 0:
out += ', '
if bounds[i] == bounds[i + 1]:
out += str(bounds[i])
else:
out += str(bounds[i]) + '..' + str(bounds[i + 1])
return out
def ShortName(model, i):
"""Returns a short name of an integer variable, or its negation."""
if i < 0:
return 'Not(%s)' % ShortName(model, -i - 1)
v = model.variables[i]
if v.name:
return v.name
elif len(v.domain) == 2 and v.domain[0] == v.domain[1]:
return str(v.domain[0])
else:
return '[%s]' % DisplayBounds(v.domain)
class LinearExpr(object):
"""Holds an integer linear expression.
A linear expression is built from integer constants and variables.
For example, x + 2 * (y - z + 1).
Linear expressions are used in CP-SAT models in two ways:
* To define constraints. For example
model.Add(x + 2 * y <= 5)
model.Add(sum(array_of_vars) == 5)
* To define the objective function. For example
model.Minimize(x + 2 * y + z)
For large arrays, you can create constraints and the objective
from lists of linear expressions or coefficients as follows:
model.Minimize(cp_model.LinearExpr.Sum(expressions))
model.Add(cp_model.LinearExpr.ScalProd(expressions, coefficients) >= 0)
"""
@classmethod
def Sum(cls, expressions):
"""Creates the expression sum(expressions)."""
return _SumArray(expressions)
@classmethod
def ScalProd(cls, expressions, coefficients):
"""Creates the expression sum(expressions[i] * coefficients[i])."""
return _ScalProd(expressions, coefficients)
@classmethod
def Term(cls, expression, coefficient):
"""Creates `expression * coefficient`."""
return expression * coefficient
def GetVarValueMap(self):
"""Scans the expression, and return a list of (var_coef_map, constant)."""
coeffs = collections.defaultdict(int)
constant = 0
to_process = [(self, 1)]
while to_process: # Flatten to avoid recursion.
expr, coef = to_process.pop()
if isinstance(expr, _ProductCst):
to_process.append(
(expr.Expression(), coef * expr.Coefficient()))
elif isinstance(expr, _SumArray):
for e in expr.Expressions():
to_process.append((e, coef))
constant += expr.Constant() * coef
elif isinstance(expr, _ScalProd):
for e, c in zip(expr.Expressions(), expr.Coefficients()):
to_process.append((e, coef * c))
constant += expr.Constant() * coef
elif isinstance(expr, IntVar):
coeffs[expr] += coef
elif isinstance(expr, _NotBooleanVariable):
constant += coef
coeffs[expr.Not()] -= coef
else:
raise TypeError('Unrecognized linear expression: ' + str(expr))
return coeffs, constant
def __hash__(self):
return object.__hash__(self)
def __abs__(self):
raise NotImplementedError(
'calling abs() on a linear expression is not supported, '
'please use CpModel.AddAbsEquality')
def __add__(self, expr):
return _SumArray([self, expr])
def __radd__(self, arg):
return _SumArray([self, arg])
def __sub__(self, expr):
return _SumArray([self, -expr])
def __rsub__(self, arg):
return _SumArray([-self, arg])
def __mul__(self, arg):
if isinstance(arg, numbers.Integral):
if arg == 1:
return self
elif arg == 0:
return 0
cp_model_helper.AssertIsInt64(arg)
return _ProductCst(self, arg)
else:
raise TypeError('Not an integer linear expression: ' + str(arg))
def __rmul__(self, arg):
cp_model_helper.AssertIsInt64(arg)
if arg == 1:
return self
return _ProductCst(self, arg)
def __div__(self, _):
raise NotImplementedError(
'calling / on a linear expression is not supported, '
'please use CpModel.AddDivisionEquality')
def __truediv__(self, _):
raise NotImplementedError(
'calling // on a linear expression is not supported, '
'please use CpModel.AddDivisionEquality')
def __mod__(self, _):
raise NotImplementedError(
'calling %% on a linear expression is not supported, '
'please use CpModel.AddModuloEquality')
def __neg__(self):
return _ProductCst(self, -1)
def __eq__(self, arg):
if arg is None:
return False
if isinstance(arg, numbers.Integral):
cp_model_helper.AssertIsInt64(arg)
return BoundedLinearExpression(self, [arg, arg])
else:
return BoundedLinearExpression(self - arg, [0, 0])
def __ge__(self, arg):
if isinstance(arg, numbers.Integral):
cp_model_helper.AssertIsInt64(arg)
return BoundedLinearExpression(self, [arg, INT_MAX])
else:
return BoundedLinearExpression(self - arg, [0, INT_MAX])
def __le__(self, arg):
if isinstance(arg, numbers.Integral):
cp_model_helper.AssertIsInt64(arg)
return BoundedLinearExpression(self, [INT_MIN, arg])
else:
return BoundedLinearExpression(self - arg, [INT_MIN, 0])
def __lt__(self, arg):
if isinstance(arg, numbers.Integral):
cp_model_helper.AssertIsInt64(arg)
if arg == INT_MIN:
raise ArithmeticError('< INT_MIN is not supported')
return BoundedLinearExpression(self, [INT_MIN, arg - 1])
else:
return BoundedLinearExpression(self - arg, [INT_MIN, -1])
def __gt__(self, arg):
if isinstance(arg, numbers.Integral):
cp_model_helper.AssertIsInt64(arg)
if arg == INT_MAX:
raise ArithmeticError('> INT_MAX is not supported')
return BoundedLinearExpression(self, [arg + 1, INT_MAX])
else:
return BoundedLinearExpression(self - arg, [1, INT_MAX])
def __ne__(self, arg):
if arg is None:
return True
if isinstance(arg, numbers.Integral):
cp_model_helper.AssertIsInt64(arg)
if arg == INT_MAX:
return BoundedLinearExpression(self, [INT_MIN, INT_MAX - 1])
elif arg == INT_MIN:
return BoundedLinearExpression(self, [INT_MIN + 1, INT_MAX])
else:
return BoundedLinearExpression(
self, [INT_MIN, arg - 1, arg + 1, INT_MAX])
else:
return BoundedLinearExpression(self - arg,
[INT_MIN, -1, 1, INT_MAX])
class _ProductCst(LinearExpr):
"""Represents the product of a LinearExpr by a constant."""
def __init__(self, expr, coef):
cp_model_helper.AssertIsInt64(coef)
if isinstance(expr, _ProductCst):
self.__expr = expr.Expression()
self.__coef = expr.Coefficient() * coef
else:
self.__expr = expr
self.__coef = coef
def __str__(self):
if self.__coef == -1:
return '-' + str(self.__expr)
else:
return '(' + str(self.__coef) + ' * ' + str(self.__expr) + ')'
def __repr__(self):
return 'ProductCst(' + repr(self.__expr) + ', ' + repr(
self.__coef) + ')'
def Coefficient(self):
return self.__coef
def Expression(self):
return self.__expr
class _SumArray(LinearExpr):
"""Represents the sum of a list of LinearExpr and a constant."""
def __init__(self, expressions):
self.__expressions = []
self.__constant = 0
for x in expressions:
if isinstance(x, numbers.Integral):
cp_model_helper.AssertIsInt64(x)
self.__constant += x
elif isinstance(x, LinearExpr):
self.__expressions.append(x)
else:
raise TypeError('Not an linear expression: ' + str(x))
def __str__(self):
if self.__constant == 0:
return '({})'.format(' + '.join(map(str, self.__expressions)))
else:
return '({} + {})'.format(' + '.join(map(str, self.__expressions)),
self.__constant)
def __repr__(self):
return 'SumArray({}, {})'.format(
', '.join(map(repr, self.__expressions)), self.__constant)
def Expressions(self):
return self.__expressions
def Constant(self):
return self.__constant
class _ScalProd(LinearExpr):
"""Represents the scalar product of expressions with constants and a constant."""
def __init__(self, expressions, coefficients):
self.__expressions = []
self.__coefficients = []
self.__constant = 0
if len(expressions) != len(coefficients):
raise TypeError(
'In the LinearExpr.ScalProd method, the expression array and the '
' coefficient array must have the same length.')
for e, c in zip(expressions, coefficients):
cp_model_helper.AssertIsInt64(c)
if c == 0:
continue
if isinstance(e, numbers.Integral):
cp_model_helper.AssertIsInt64(e)
self.__constant += e * c
elif isinstance(e, LinearExpr):
self.__expressions.append(e)
self.__coefficients.append(c)
else:
raise TypeError('Not an linear expression: ' + str(e))
def __str__(self):
output = None
for expr, coeff in zip(self.__expressions, self.__coefficients):
if not output and coeff == 1:
output = str(expr)
elif not output and coeff == -1:
output = '-' + str(expr)
elif not output:
output = '{} * {}'.format(coeff, str(expr))
elif coeff == 1:
output += ' + {}'.format(str(expr))
elif coeff == -1:
output += ' - {}'.format(str(expr))
elif coeff > 1:
output += ' + {} * {}'.format(coeff, str(expr))
elif coeff < -1:
output += ' - {} * {}'.format(-coeff, str(expr))
if self.__constant > 0:
output += ' + {}'.format(self.__constant)
elif self.__constant < 0:
output += ' - {}'.format(-self.__constant)
return output
def __repr__(self):
return 'ScalProd([{}], [{}], {})'.format(
', '.join(map(repr, self.__expressions)),
', '.join(map(repr, self.__coefficients)), self.__constant)
def Expressions(self):
return self.__expressions
def Coefficients(self):
return self.__coefficients
def Constant(self):
return self.__constant
class IntVar(LinearExpr):
"""An integer variable.
An IntVar is an object that can take on any integer value within defined
ranges. Variables appear in constraint like:
x + y >= 5
AllDifferent([x, y, z])
Solving a model is equivalent to finding, for each variable, a single value
from the set of initial values (called the initial domain), such that the
model is feasible, or optimal if you provided an objective function.
"""
def __init__(self, model, domain, name):
"""See CpModel.NewIntVar below."""
self.__model = model
self.__index = len(model.variables)
self.__var = model.variables.add()
self.__var.domain.extend(domain.FlattenedIntervals())
self.__var.name = name
self.__negation = None
def Index(self):
"""Returns the index of the variable in the model."""
return self.__index
def Proto(self):
"""Returns the variable protobuf."""
return self.__var
def __str__(self):
if not self.__var.name:
if len(self.__var.domain
) == 2 and self.__var.domain[0] == self.__var.domain[1]:
# Special case for constants.
return str(self.__var.domain[0])
else:
return 'unnamed_var_%i' % self.__index
return self.__var.name
def __repr__(self):
return '%s(%s)' % (self.__var.name, DisplayBounds(self.__var.domain))
def Name(self):
return self.__var.name
def Not(self):
"""Returns the negation of a Boolean variable.
This method implements the logical negation of a Boolean variable.
It is only valid if the variable has a Boolean domain (0 or 1).
Note that this method is nilpotent: `x.Not().Not() == x`.
"""
for bound in self.__var.domain:
if bound < 0 or bound > 1:
raise TypeError(
'Cannot call Not on a non boolean variable: %s' % self)
if not self.__negation:
self.__negation = _NotBooleanVariable(self)
return self.__negation
class _NotBooleanVariable(LinearExpr):
"""Negation of a boolean variable."""
def __init__(self, boolvar):
self.__boolvar = boolvar
def Index(self):
return -self.__boolvar.Index() - 1
def Not(self):
return self.__boolvar
def __str__(self):
return 'not(%s)' % str(self.__boolvar)
class BoundedLinearExpression(object):
"""Represents a linear constraint: `lb <= linear expression <= ub`.
The only use of this class is to be added to the CpModel through
`CpModel.Add(expression)`, as in:
model.Add(x + 2 * y -1 >= z)
"""
def __init__(self, expr, bounds):
self.__expr = expr
self.__bounds = bounds
def __str__(self):
if len(self.__bounds) == 2:
lb = self.__bounds[0]
ub = self.__bounds[1]
if lb > INT_MIN and ub < INT_MAX:
if lb == ub:
return str(self.__expr) + ' == ' + str(lb)
else:
return str(lb) + ' <= ' + str(
self.__expr) + ' <= ' + str(ub)
elif lb > INT_MIN:
return str(self.__expr) + ' >= ' + str(lb)
elif ub < INT_MAX:
return str(self.__expr) + ' <= ' + str(ub)
else:
return 'True (unbounded expr ' + str(self.__expr) + ')'
else:
return str(self.__expr) + ' in [' + DisplayBounds(
self.__bounds) + ']'
def Expression(self):
return self.__expr
def Bounds(self):
return self.__bounds
class Constraint(object):
"""Base class for constraints.
Constraints are built by the CpModel through the Add<XXX> methods.
Once created by the CpModel class, they are automatically added to the model.
The purpose of this class is to allow specification of enforcement literals
for this constraint.
b = model.BoolVar('b')
x = model.IntVar(0, 10, 'x')
y = model.IntVar(0, 10, 'y')
model.Add(x + 2 * y == 5).OnlyEnforceIf(b.Not())
"""
def __init__(self, constraints):
self.__index = len(constraints)
self.__constraint = constraints.add()
def OnlyEnforceIf(self, boolvar):
"""Adds an enforcement literal to the constraint.
This method adds one or more literals (that is, a boolean variable or its
negation) as enforcement literals. The conjunction of all these literals
determines whether the constraint is active or not. It acts as an
implication, so if the conjunction is true, it implies that the constraint
must be enforced. If it is false, then the constraint is ignored.
BoolOr, BoolAnd, and linear constraints all support enforcement literals.
Args:
boolvar: A boolean literal or a list of boolean literals.
Returns:
self.
"""
if isinstance(boolvar, numbers.Integral) and boolvar == 1:
# Always true. Do nothing.
pass
elif isinstance(boolvar, list):
for b in boolvar:
if isinstance(b, numbers.Integral) and b == 1:
pass
else:
self.__constraint.enforcement_literal.append(b.Index())
else:
self.__constraint.enforcement_literal.append(boolvar.Index())
return self
def Index(self):
"""Returns the index of the constraint in the model."""
return self.__index
def Proto(self):
"""Returns the constraint protobuf."""
return self.__constraint
class IntervalVar(object):
"""Represents an Interval variable.
An interval variable is both a constraint and a variable. It is defined by
three integer variables: start, size, and end.
It is a constraint because, internally, it enforces that start + size == end.
It is also a variable as it can appear in specific scheduling constraints:
NoOverlap, NoOverlap2D, Cumulative.
Optionally, an enforcement literal can be added to this constraint, in which
case these scheduling constraints will ignore interval variables with
enforcement literals assigned to false. Conversely, these constraints will
also set these enforcement literals to false if they cannot fit these
intervals into the schedule.
"""
def __init__(self, model, start_index, size_index, end_index,
is_present_index, name):
self.__model = model
self.__index = len(model.constraints)
self.__ct = self.__model.constraints.add()
self.__ct.interval.start = start_index
self.__ct.interval.size = size_index
self.__ct.interval.end = end_index
if is_present_index is not None:
self.__ct.enforcement_literal.append(is_present_index)
if name:
self.__ct.name = name
def Index(self):
"""Returns the index of the interval constraint in the model."""
return self.__index
def Proto(self):
"""Returns the interval protobuf."""
return self.__ct.interval
def __str__(self):
return self.__ct.name
def __repr__(self):
interval = self.__ct.interval
if self.__ct.enforcement_literal:
return '%s(start = %s, size = %s, end = %s, is_present = %s)' % (
self.__ct.name, ShortName(self.__model, interval.start),
ShortName(self.__model,
interval.size), ShortName(self.__model, interval.end),
ShortName(self.__model, self.__ct.enforcement_literal[0]))
else:
return '%s(start = %s, size = %s, end = %s)' % (
self.__ct.name, ShortName(self.__model, interval.start),
ShortName(self.__model,
interval.size), ShortName(self.__model, interval.end))
def Name(self):
return self.__ct.name
class CpModel(object):
"""Methods for building a CP model.
Methods beginning with:
* ```New``` create integer, boolean, or interval variables.
* ```Add``` create new constraints and add them to the model.
"""
def __init__(self):
self.__model = cp_model_pb2.CpModelProto()
self.__constant_map = {}
self.__optional_constant_map = {}
# Integer variable.
def NewIntVar(self, lb, ub, name):
"""Create an integer variable with domain [lb, ub].
The CP-SAT solver is limited to integer variables. If you have fractional
values, scale them up so that they become integers; if you have strings,
encode them as integers.
Args:
lb: Lower bound for the variable.
ub: Upper bound for the variable.
name: The name of the variable.
Returns:
a variable whose domain is [lb, ub].
"""
return IntVar(self.__model, Domain(lb, ub), name)
def NewIntVarFromDomain(self, domain, name):
"""Create an integer variable from a domain.
A domain is a set of integers specified by a collection of intervals.
For example, `model.NewIntVarFromDomain(cp_model.
Domain.FromIntervals([[1, 2], [4, 6]]), 'x')`
Args:
domain: An instance of the Domain class.
name: The name of the variable.
Returns:
a variable whose domain is the given domain.
"""
return IntVar(self.__model, domain, name)
def NewBoolVar(self, name):
"""Creates a 0-1 variable with the given name."""
return IntVar(self.__model, Domain(0, 1), name)
def NewConstant(self, value):
"""Declares a constant integer."""
return IntVar(self.__model, Domain(value, value), '')
# Linear constraints.
def AddLinearConstraint(self, linear_expr, lb, ub):
"""Adds the constraint: `lb <= linear_expr <= ub`."""
return self.AddLinearExpressionInDomain(linear_expr, Domain(lb, ub))
def AddLinearExpressionInDomain(self, linear_expr, domain):
"""Adds the constraint: `linear_expr` in `domain`."""
if isinstance(linear_expr, LinearExpr):
ct = Constraint(self.__model.constraints)
model_ct = self.__model.constraints[ct.Index()]
coeffs_map, constant = linear_expr.GetVarValueMap()
for t in iteritems(coeffs_map):
if not isinstance(t[0], IntVar):
raise TypeError('Wrong argument' + str(t))
cp_model_helper.AssertIsInt64(t[1])
model_ct.linear.vars.append(t[0].Index())
model_ct.linear.coeffs.append(t[1])
model_ct.linear.domain.extend([
cp_model_helper.CapSub(x, constant)
for x in domain.FlattenedIntervals()
])
return ct
elif isinstance(linear_expr, numbers.Integral):
if not domain.Contains(linear_expr):
return self.AddBoolOr([]) # Evaluate to false.
# Nothing to do otherwise.
else:
raise TypeError(
'Not supported: CpModel.AddLinearExpressionInDomain(' +
str(linear_expr) + ' ' + str(domain) + ')')
def Add(self, ct):
"""Adds a `BoundedLinearExpression` to the model.
Args:
ct: A [`BoundedLinearExpression`](#boundedlinearexpression).
Returns:
An instance of the `Constraint` class.
"""
if isinstance(ct, BoundedLinearExpression):
return self.AddLinearExpressionInDomain(
ct.Expression(), Domain.FromFlatIntervals(ct.Bounds()))
elif ct and isinstance(ct, bool):
return self.AddBoolOr([True])
elif not ct and isinstance(ct, bool):
return self.AddBoolOr([]) # Evaluate to false.
else:
raise TypeError('Not supported: CpModel.Add(' + str(ct) + ')')
# General Integer Constraints.
def AddAllDifferent(self, variables):
"""Adds AllDifferent(variables).
This constraint forces all variables to have different values.
Args:
variables: a list of integer variables.
Returns:
An instance of the `Constraint` class.
"""
ct = Constraint(self.__model.constraints)
model_ct = self.__model.constraints[ct.Index()]
model_ct.all_diff.vars.extend(
[self.GetOrMakeIndex(x) for x in variables])
return ct
def AddElement(self, index, variables, target):
"""Adds the element constraint: `variables[index] == target`."""
if not variables:
raise ValueError('AddElement expects a non-empty variables array')
if isinstance(index, numbers.Integral):
return self.Add(list(variables)[index] == target)
ct = Constraint(self.__model.constraints)
model_ct = self.__model.constraints[ct.Index()]
model_ct.element.index = self.GetOrMakeIndex(index)
model_ct.element.vars.extend(
[self.GetOrMakeIndex(x) for x in variables])
model_ct.element.target = self.GetOrMakeIndex(target)
return ct
def AddCircuit(self, arcs):
"""Adds Circuit(arcs).
Adds a circuit constraint from a sparse list of arcs that encode the graph.
A circuit is a unique Hamiltonian path in a subgraph of the total
graph. In case a node 'i' is not in the path, then there must be a
loop arc 'i -> i' associated with a true literal. Otherwise
this constraint will fail.
Args:
arcs: a list of arcs. An arc is a tuple (source_node, destination_node,
literal). The arc is selected in the circuit if the literal is true.
Both source_node and destination_node must be integers between 0 and the
number of nodes - 1.
Returns:
An instance of the `Constraint` class.
Raises:
ValueError: If the list of arcs is empty.
"""
if not arcs:
raise ValueError('AddCircuit expects a non-empty array of arcs')
ct = Constraint(self.__model.constraints)
model_ct = self.__model.constraints[ct.Index()]
for arc in arcs:
cp_model_helper.AssertIsInt32(arc[0])
cp_model_helper.AssertIsInt32(arc[1])
lit = self.GetOrMakeBooleanIndex(arc[2])
model_ct.circuit.tails.append(arc[0])
model_ct.circuit.heads.append(arc[1])
model_ct.circuit.literals.append(lit)
return ct
def AddAllowedAssignments(self, variables, tuples_list):
"""Adds AllowedAssignments(variables, tuples_list).
An AllowedAssignments constraint is a constraint on an array of variables,
which requires that when all variables are assigned values, the resulting
array equals one of the tuples in `tuple_list`.
Args:
variables: A list of variables.
tuples_list: A list of admissible tuples. Each tuple must have the same
length as the variables, and the ith value of a tuple corresponds to the
ith variable.
Returns:
An instance of the `Constraint` class.
Raises:
TypeError: If a tuple does not have the same size as the list of
variables.
ValueError: If the array of variables is empty.
"""
if not variables:
raise ValueError(
'AddAllowedAssignments expects a non-empty variables '
'array')
ct = Constraint(self.__model.constraints)
model_ct = self.__model.constraints[ct.Index()]
model_ct.table.vars.extend([self.GetOrMakeIndex(x) for x in variables])
arity = len(variables)
for t in tuples_list:
if len(t) != arity:
raise TypeError('Tuple ' + str(t) + ' has the wrong arity')
for v in t:
cp_model_helper.AssertIsInt64(v)
model_ct.table.values.extend(t)
return ct
def AddForbiddenAssignments(self, variables, tuples_list):
"""Adds AddForbiddenAssignments(variables, [tuples_list]).
A ForbiddenAssignments constraint is a constraint on an array of variables
where the list of impossible combinations is provided in the tuples list.
Args:
variables: A list of variables.
tuples_list: A list of forbidden tuples. Each tuple must have the same
length as the variables, and the *i*th value of a tuple corresponds to
the *i*th variable.
Returns:
An instance of the `Constraint` class.
Raises:
TypeError: If a tuple does not have the same size as the list of
variables.
ValueError: If the array of variables is empty.
"""
if not variables:
raise ValueError(
'AddForbiddenAssignments expects a non-empty variables '
'array')
index = len(self.__model.constraints)
ct = self.AddAllowedAssignments(variables, tuples_list)
self.__model.constraints[index].table.negated = True
return ct
def AddAutomaton(self, transition_variables, starting_state, final_states,
transition_triples):
"""Adds an automaton constraint.
An automaton constraint takes a list of variables (of size *n*), an initial
state, a set of final states, and a set of transitions. A transition is a
triplet (*tail*, *transition*, *head*), where *tail* and *head* are states,
and *transition* is the label of an arc from *head* to *tail*,
corresponding to the value of one variable in the list of variables.
This automaton will be unrolled into a flow with *n* + 1 phases. Each phase
contains the possible states of the automaton. The first state contains the
initial state. The last phase contains the final states.
Between two consecutive phases *i* and *i* + 1, the automaton creates a set
of arcs. For each transition (*tail*, *transition*, *head*), it will add
an arc from the state *tail* of phase *i* and the state *head* of phase
*i* + 1. This arc is labeled by the value *transition* of the variables
`variables[i]`. That is, this arc can only be selected if `variables[i]`
is assigned the value *transition*.
A feasible solution of this constraint is an assignment of variables such
that, starting from the initial state in phase 0, there is a path labeled by
the values of the variables that ends in one of the final states in the
final phase.
Args:
transition_variables: A non-empty list of variables whose values
correspond to the labels of the arcs traversed by the automaton.
starting_state: The initial state of the automaton.
final_states: A non-empty list of admissible final states.
transition_triples: A list of transitions for the automaton, in the
following format (current_state, variable_value, next_state).
Returns:
An instance of the `Constraint` class.
Raises:
ValueError: if `transition_variables`, `final_states`, or
`transition_triples` are empty.
"""
if not transition_variables:
raise ValueError(
'AddAutomaton expects a non-empty transition_variables '
'array')
if not final_states:
raise ValueError('AddAutomaton expects some final states')
if not transition_triples:
raise ValueError('AddAutomaton expects some transtion triples')
ct = Constraint(self.__model.constraints)
model_ct = self.__model.constraints[ct.Index()]
model_ct.automaton.vars.extend(
[self.GetOrMakeIndex(x) for x in transition_variables])
cp_model_helper.AssertIsInt64(starting_state)
model_ct.automaton.starting_state = starting_state
for v in final_states:
cp_model_helper.AssertIsInt64(v)
model_ct.automaton.final_states.append(v)
for t in transition_triples:
if len(t) != 3:
raise TypeError('Tuple ' + str(t) +
' has the wrong arity (!= 3)')
cp_model_helper.AssertIsInt64(t[0])
cp_model_helper.AssertIsInt64(t[1])
cp_model_helper.AssertIsInt64(t[2])
model_ct.automaton.transition_tail.append(t[0])
model_ct.automaton.transition_label.append(t[1])