-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
cp_model.py
3787 lines (3170 loc) · 135 KB
/
cp_model.py
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-2024 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
constraints 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.
"""
import collections
import itertools
import threading
import time
from typing import (
Any,
Callable,
Dict,
Iterable,
List,
NoReturn,
Optional,
Sequence,
Tuple,
Union,
cast,
overload,
)
import warnings
import numpy as np
import pandas as pd
from ortools.sat import cp_model_pb2
from ortools.sat import sat_parameters_pb2
from ortools.sat.python import cp_model_helper as cmh
from ortools.sat.python import swig_helper
from ortools.util.python import sorted_interval_list
Domain = sorted_interval_list.Domain
# 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 = -(2**63) # hardcoded to be platform independent.
INT_MAX = 2**63 - 1
INT32_MIN = -(2**31)
INT32_MAX = 2**31 - 1
# 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
PSEUDO_COST_SEARCH = sat_parameters_pb2.SatParameters.PSEUDO_COST_SEARCH
PORTFOLIO_WITH_QUICK_RESTART_SEARCH = (
sat_parameters_pb2.SatParameters.PORTFOLIO_WITH_QUICK_RESTART_SEARCH
)
HINT_SEARCH = sat_parameters_pb2.SatParameters.HINT_SEARCH
PARTIAL_FIXED_SEARCH = sat_parameters_pb2.SatParameters.PARTIAL_FIXED_SEARCH
RANDOMIZED_SEARCH = sat_parameters_pb2.SatParameters.RANDOMIZED_SEARCH
# Type aliases
IntegralT = Union[int, np.int8, np.uint8, np.int32, np.uint32, np.int64, np.uint64]
IntegralTypes = (
int,
np.int8,
np.uint8,
np.int32,
np.uint32,
np.int64,
np.uint64,
)
NumberT = Union[
int,
float,
np.int8,
np.uint8,
np.int32,
np.uint32,
np.int64,
np.uint64,
np.double,
]
NumberTypes = (
int,
float,
np.int8,
np.uint8,
np.int32,
np.uint32,
np.int64,
np.uint64,
np.double,
)
LiteralT = Union["IntVar", "_NotBooleanVariable", IntegralT, bool]
BoolVarT = Union["IntVar", "_NotBooleanVariable"]
VariableT = Union["IntVar", IntegralT]
# We need to add 'IntVar' for pytype.
LinearExprT = Union["LinearExpr", "IntVar", IntegralT]
ObjLinearExprT = Union["LinearExpr", NumberT]
BoundedLinearExprT = Union["BoundedLinearExpression", bool]
ArcT = Tuple[IntegralT, IntegralT, LiteralT]
_IndexOrSeries = Union[pd.Index, pd.Series]
def display_bounds(bounds: Sequence[int]) -> str:
"""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 short_name(model: cp_model_pb2.CpModelProto, i: int) -> str:
"""Returns a short name of an integer variable, or its negation."""
if i < 0:
return "not(%s)" % short_name(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]" % display_bounds(v.domain)
def short_expr_name(
model: cp_model_pb2.CpModelProto, e: cp_model_pb2.LinearExpressionProto
) -> str:
"""Pretty-print LinearExpressionProto instances."""
if not e.vars:
return str(e.offset)
if len(e.vars) == 1:
var_name = short_name(model, e.vars[0])
coeff = e.coeffs[0]
result = ""
if coeff == 1:
result = var_name
elif coeff == -1:
result = f"-{var_name}"
elif coeff != 0:
result = f"{coeff} * {var_name}"
if e.offset > 0:
result = f"{result} + {e.offset}"
elif e.offset < 0:
result = f"{result} - {-e.offset}"
return result
# TODO(user): Support more than affine expressions.
return str(e)
class LinearExpr:
"""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 constraints and in the
objective:
* You can define linear constraints as in:
```
model.add(x + 2 * y <= 5)
model.add(sum(array_of_vars) == 5)
```
* In CP-SAT, the objective is a linear expression:
```
model.minimize(x + 2 * y + z)
```
* For large arrays, using the LinearExpr class is faster that using the python
`sum()` function. 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.weighted_sum(expressions, coefficients) >= 0)
```
"""
@classmethod
def sum(cls, expressions: Sequence[LinearExprT]) -> LinearExprT:
"""Creates the expression sum(expressions)."""
if len(expressions) == 1:
return expressions[0]
return _SumArray(expressions)
@overload
@classmethod
def weighted_sum(
cls,
expressions: Sequence[LinearExprT],
coefficients: Sequence[IntegralT],
) -> LinearExprT: ...
@overload
@classmethod
def weighted_sum(
cls,
expressions: Sequence[ObjLinearExprT],
coefficients: Sequence[NumberT],
) -> ObjLinearExprT: ...
@classmethod
def weighted_sum(cls, expressions, coefficients):
"""Creates the expression sum(expressions[i] * coefficients[i])."""
if LinearExpr.is_empty_or_all_null(coefficients):
return 0
elif len(expressions) == 1:
return expressions[0] * coefficients[0]
else:
return _WeightedSum(expressions, coefficients)
@overload
@classmethod
def term(
cls,
expressions: LinearExprT,
coefficients: IntegralT,
) -> LinearExprT: ...
@overload
@classmethod
def term(
cls,
expressions: ObjLinearExprT,
coefficients: NumberT,
) -> ObjLinearExprT: ...
@classmethod
def term(cls, expression, coefficient):
"""Creates `expression * coefficient`."""
if cmh.is_zero(coefficient):
return 0
else:
return expression * coefficient
@classmethod
def is_empty_or_all_null(cls, coefficients: Sequence[NumberT]) -> bool:
for c in coefficients:
if not cmh.is_zero(c):
return False
return True
@classmethod
def rebuild_from_linear_expression_proto(
cls,
model: cp_model_pb2.CpModelProto,
proto: cp_model_pb2.LinearExpressionProto,
) -> LinearExprT:
"""Recreate a LinearExpr from a LinearExpressionProto."""
offset = proto.offset
num_elements = len(proto.vars)
if num_elements == 0:
return offset
elif num_elements == 1:
return (
IntVar(model, proto.vars[0], None) * proto.coeffs[0] + offset
) # pytype: disable=bad-return-type
else:
variables = []
coeffs = []
all_ones = True
for index, coeff in zip(proto.vars, proto.coeffs):
variables.append(IntVar(model, index, None))
coeffs.append(coeff)
if not cmh.is_one(coeff):
all_ones = False
if all_ones:
return _SumArray(variables, offset)
else:
return _WeightedSum(variables, coeffs, offset)
def get_integer_var_value_map(self) -> Tuple[Dict["IntVar", int], int]:
"""Scans the expression, and returns (var_coef_map, constant)."""
coeffs: Dict["IntVar", int] = collections.defaultdict(int)
constant = 0
to_process: List[Tuple[LinearExprT, int]] = [(self, 1)]
while to_process: # Flatten to avoid recursion.
expr: LinearExprT
coeff: int
expr, coeff = to_process.pop()
if isinstance(expr, IntegralTypes):
constant += coeff * int(expr)
elif isinstance(expr, _ProductCst):
to_process.append((expr.expression(), coeff * expr.coefficient()))
elif isinstance(expr, _Sum):
to_process.append((expr.left(), coeff))
to_process.append((expr.right(), coeff))
elif isinstance(expr, _SumArray):
for e in expr.expressions():
to_process.append((e, coeff))
constant += expr.constant() * coeff
elif isinstance(expr, _WeightedSum):
for e, c in zip(expr.expressions(), expr.coefficients()):
to_process.append((e, coeff * c))
constant += expr.constant() * coeff
elif isinstance(expr, IntVar):
coeffs[expr] += coeff
elif isinstance(expr, _NotBooleanVariable):
constant += coeff
coeffs[expr.negated()] -= coeff
elif isinstance(expr, NumberTypes):
raise TypeError(
f"Floating point constants are not supported in constraints: {expr}"
)
else:
raise TypeError("Unrecognized linear expression: " + str(expr))
return coeffs, constant
def get_float_var_value_map(
self,
) -> Tuple[Dict["IntVar", float], float, bool]:
"""Scans the expression. Returns (var_coef_map, constant, is_integer)."""
coeffs: Dict["IntVar", Union[int, float]] = {}
constant: Union[int, float] = 0
to_process: List[Tuple[LinearExprT, Union[int, float]]] = [(self, 1)]
while to_process: # Flatten to avoid recursion.
expr, coeff = to_process.pop()
if isinstance(expr, IntegralTypes): # Keep integrality.
constant += coeff * int(expr)
elif isinstance(expr, NumberTypes):
constant += coeff * float(expr)
elif isinstance(expr, _ProductCst):
to_process.append((expr.expression(), coeff * expr.coefficient()))
elif isinstance(expr, _Sum):
to_process.append((expr.left(), coeff))
to_process.append((expr.right(), coeff))
elif isinstance(expr, _SumArray):
for e in expr.expressions():
to_process.append((e, coeff))
constant += expr.constant() * coeff
elif isinstance(expr, _WeightedSum):
for e, c in zip(expr.expressions(), expr.coefficients()):
to_process.append((e, coeff * c))
constant += expr.constant() * coeff
elif isinstance(expr, IntVar):
if expr in coeffs:
coeffs[expr] += coeff
else:
coeffs[expr] = coeff
elif isinstance(expr, _NotBooleanVariable):
constant += coeff
if expr.negated() in coeffs:
coeffs[expr.negated()] -= coeff
else:
coeffs[expr.negated()] = -coeff
else:
raise TypeError("Unrecognized linear expression: " + str(expr))
is_integer = isinstance(constant, IntegralTypes)
if is_integer:
for coeff in coeffs.values():
if not isinstance(coeff, IntegralTypes):
is_integer = False
break
return coeffs, constant, is_integer
def __hash__(self) -> int:
return object.__hash__(self)
def __abs__(self) -> NoReturn:
raise NotImplementedError(
"calling abs() on a linear expression is not supported, "
"please use CpModel.add_abs_equality"
)
@overload
def __add__(self, arg: "LinearExpr") -> "LinearExpr": ...
@overload
def __add__(self, arg: NumberT) -> "LinearExpr": ...
def __add__(self, arg):
if cmh.is_zero(arg):
return self
return _Sum(self, arg)
@overload
def __radd__(self, arg: "LinearExpr") -> "LinearExpr": ...
@overload
def __radd__(self, arg: NumberT) -> "LinearExpr": ...
def __radd__(self, arg):
return self.__add__(arg)
@overload
def __sub__(self, arg: "LinearExpr") -> "LinearExpr": ...
@overload
def __sub__(self, arg: NumberT) -> "LinearExpr": ...
def __sub__(self, arg):
if cmh.is_zero(arg):
return self
if isinstance(arg, NumberTypes):
arg = cmh.assert_is_a_number(arg)
return _Sum(self, -arg)
else:
return _Sum(self, -arg)
@overload
def __rsub__(self, arg: "LinearExpr") -> "LinearExpr": ...
@overload
def __rsub__(self, arg: NumberT) -> "LinearExpr": ...
def __rsub__(self, arg):
return _Sum(-self, arg)
@overload
def __mul__(self, arg: IntegralT) -> Union["LinearExpr", IntegralT]: ...
@overload
def __mul__(self, arg: NumberT) -> Union["LinearExpr", NumberT]: ...
def __mul__(self, arg):
arg = cmh.assert_is_a_number(arg)
if cmh.is_one(arg):
return self
elif cmh.is_zero(arg):
return 0
return _ProductCst(self, arg)
@overload
def __rmul__(self, arg: IntegralT) -> Union["LinearExpr", IntegralT]: ...
@overload
def __rmul__(self, arg: NumberT) -> Union["LinearExpr", NumberT]: ...
def __rmul__(self, arg):
return self.__mul__(arg)
def __div__(self, _) -> NoReturn:
raise NotImplementedError(
"calling / on a linear expression is not supported, "
"please use CpModel.add_division_equality"
)
def __truediv__(self, _) -> NoReturn:
raise NotImplementedError(
"calling // on a linear expression is not supported, "
"please use CpModel.add_division_equality"
)
def __mod__(self, _) -> NoReturn:
raise NotImplementedError(
"calling %% on a linear expression is not supported, "
"please use CpModel.add_modulo_equality"
)
def __pow__(self, _) -> NoReturn:
raise NotImplementedError(
"calling ** on a linear expression is not supported, "
"please use CpModel.add_multiplication_equality"
)
def __lshift__(self, _) -> NoReturn:
raise NotImplementedError(
"calling left shift on a linear expression is not supported"
)
def __rshift__(self, _) -> NoReturn:
raise NotImplementedError(
"calling right shift on a linear expression is not supported"
)
def __and__(self, _) -> NoReturn:
raise NotImplementedError(
"calling and on a linear expression is not supported, "
"please use CpModel.add_bool_and"
)
def __or__(self, _) -> NoReturn:
raise NotImplementedError(
"calling or on a linear expression is not supported, "
"please use CpModel.add_bool_or"
)
def __xor__(self, _) -> NoReturn:
raise NotImplementedError(
"calling xor on a linear expression is not supported, "
"please use CpModel.add_bool_xor"
)
def __neg__(self) -> "LinearExpr":
return _ProductCst(self, -1)
def __bool__(self) -> NoReturn:
raise NotImplementedError(
"Evaluating a LinearExpr instance as a Boolean is not implemented."
)
def __eq__(self, arg: LinearExprT) -> BoundedLinearExprT: # type: ignore[override]
if arg is None:
return False
if isinstance(arg, IntegralTypes):
arg = cmh.assert_is_int64(arg)
return BoundedLinearExpression(self, [arg, arg])
elif isinstance(arg, LinearExpr):
return BoundedLinearExpression(self - arg, [0, 0])
else:
return False
def __ge__(self, arg: LinearExprT) -> "BoundedLinearExpression":
if isinstance(arg, IntegralTypes):
arg = cmh.assert_is_int64(arg)
return BoundedLinearExpression(self, [arg, INT_MAX])
else:
return BoundedLinearExpression(self - arg, [0, INT_MAX])
def __le__(self, arg: LinearExprT) -> "BoundedLinearExpression":
if isinstance(arg, IntegralTypes):
arg = cmh.assert_is_int64(arg)
return BoundedLinearExpression(self, [INT_MIN, arg])
else:
return BoundedLinearExpression(self - arg, [INT_MIN, 0])
def __lt__(self, arg: LinearExprT) -> "BoundedLinearExpression":
if isinstance(arg, IntegralTypes):
arg = cmh.assert_is_int64(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: LinearExprT) -> "BoundedLinearExpression":
if isinstance(arg, IntegralTypes):
arg = cmh.assert_is_int64(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: LinearExprT) -> BoundedLinearExprT: # type: ignore[override]
if arg is None:
return True
if isinstance(arg, IntegralTypes):
arg = cmh.assert_is_int64(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]
)
elif isinstance(arg, LinearExpr):
return BoundedLinearExpression(self - arg, [INT_MIN, -1, 1, INT_MAX])
else:
return True
# Compatibility with pre PEP8
# pylint: disable=invalid-name
@classmethod
def Sum(cls, expressions: Sequence[LinearExprT]) -> LinearExprT:
"""Creates the expression sum(expressions)."""
return cls.sum(expressions)
@overload
@classmethod
def WeightedSum(
cls,
expressions: Sequence[LinearExprT],
coefficients: Sequence[IntegralT],
) -> LinearExprT: ...
@overload
@classmethod
def WeightedSum(
cls,
expressions: Sequence[ObjLinearExprT],
coefficients: Sequence[NumberT],
) -> ObjLinearExprT: ...
@classmethod
def WeightedSum(cls, expressions, coefficients):
"""Creates the expression sum(expressions[i] * coefficients[i])."""
return cls.weighted_sum(expressions, coefficients)
@overload
@classmethod
def Term(
cls,
expressions: LinearExprT,
coefficients: IntegralT,
) -> LinearExprT: ...
@overload
@classmethod
def Term(
cls,
expressions: ObjLinearExprT,
coefficients: NumberT,
) -> ObjLinearExprT: ...
@classmethod
def Term(cls, expression, coefficient):
"""Creates `expression * coefficient`."""
return cls.term(expression, coefficient)
# pylint: enable=invalid-name
class _Sum(LinearExpr):
"""Represents the sum of two LinearExprs."""
def __init__(self, left, right) -> None:
for x in [left, right]:
if not isinstance(x, (NumberTypes, LinearExpr)):
raise TypeError("not an linear expression: " + str(x))
self.__left = left
self.__right = right
def left(self):
return self.__left
def right(self):
return self.__right
def __str__(self):
return f"({self.__left} + {self.__right})"
def __repr__(self):
return f"sum({self.__left!r}, {self.__right!r})"
class _ProductCst(LinearExpr):
"""Represents the product of a LinearExpr by a constant."""
def __init__(self, expr, coeff) -> None:
coeff = cmh.assert_is_a_number(coeff)
if isinstance(expr, _ProductCst):
self.__expr = expr.expression()
self.__coef = expr.coefficient() * coeff
else:
self.__expr = expr
self.__coef = coeff
def __str__(self):
if self.__coef == -1:
return "-" + str(self.__expr)
else:
return "(" + str(self.__coef) + " * " + str(self.__expr) + ")"
def __repr__(self):
return f"ProductCst({self.__expr!r}, {self.__coef!r})"
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, constant=0) -> None:
self.__expressions = []
self.__constant = constant
for x in expressions:
if isinstance(x, NumberTypes):
if cmh.is_zero(x):
continue
x = cmh.assert_is_a_number(x)
self.__constant += x
elif isinstance(x, LinearExpr):
self.__expressions.append(x)
else:
raise TypeError("not an linear expression: " + str(x))
def __str__(self):
constant_terms = (self.__constant,) if self.__constant != 0 else ()
exprs_str = " + ".join(
map(repr, itertools.chain(self.__expressions, constant_terms))
)
if not exprs_str:
return "0"
return f"({exprs_str})"
def __repr__(self):
exprs_str = ", ".join(map(repr, self.__expressions))
return f"SumArray({exprs_str}, {self.__constant})"
def expressions(self):
return self.__expressions
def constant(self):
return self.__constant
class _WeightedSum(LinearExpr):
"""Represents sum(ai * xi) + b."""
def __init__(self, expressions, coefficients, constant=0) -> None:
self.__expressions = []
self.__coefficients = []
self.__constant = constant
if len(expressions) != len(coefficients):
raise TypeError(
"In the LinearExpr.weighted_sum method, the expression array and the "
" coefficient array must have the same length."
)
for e, c in zip(expressions, coefficients):
c = cmh.assert_is_a_number(c)
if cmh.is_zero(c):
continue
if isinstance(e, NumberTypes):
e = cmh.assert_is_a_number(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 cmh.is_one(coeff):
output = str(expr)
elif not output and cmh.is_minus_one(coeff):
output = "-" + str(expr)
elif not output:
output = f"{coeff} * {expr}"
elif cmh.is_one(coeff):
output += f" + {expr}"
elif cmh.is_minus_one(coeff):
output += f" - {expr}"
elif coeff > 1:
output += f" + {coeff} * {expr}"
elif coeff < -1:
output += f" - {-coeff} * {expr}"
if output is None:
output = str(self.__constant)
elif self.__constant > 0:
output += f" + {self.__constant}"
elif self.__constant < 0:
output += f" - {-self.__constant}"
return output
def __repr__(self):
return (
f"weighted_sum({self.__expressions!r}, {self.__coefficients!r},"
f" {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: cp_model_pb2.CpModelProto,
domain: Union[int, sorted_interval_list.Domain],
name: Optional[str],
) -> None:
"""See CpModel.new_int_var below."""
self.__index: int
self.__var: cp_model_pb2.IntegerVariableProto
self.__negation: Optional[_NotBooleanVariable] = None
# Python do not support multiple __init__ methods.
# This method is only called from the CpModel class.
# We hack the parameter to support the two cases:
# case 1:
# model is a CpModelProto, domain is a Domain, and name is a string.
# case 2:
# model is a CpModelProto, domain is an index (int), and name is None.
if isinstance(domain, IntegralTypes) and name is None:
self.__index = int(domain)
self.__var = model.variables[domain]
else:
self.__index = len(model.variables)
self.__var = model.variables.add()
self.__var.domain.extend(
cast(sorted_interval_list.Domain, domain).flattened_intervals()
)
if name is not None:
self.__var.name = name
@property
def index(self) -> int:
"""Returns the index of the variable in the model."""
return self.__index
@property
def proto(self) -> cp_model_pb2.IntegerVariableProto:
"""Returns the variable protobuf."""
return self.__var
def is_equal_to(self, other: Any) -> bool:
"""Returns true if self == other in the python sense."""
if not isinstance(other, IntVar):
return False
return self.index == other.index
def __str__(self) -> str:
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) -> str:
return "%s(%s)" % (self.__var.name, display_bounds(self.__var.domain))
@property
def name(self) -> str:
if not self.__var or not self.__var.name:
return ""
return self.__var.name
def negated(self) -> "_NotBooleanVariable":
"""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.negated().negated() == x`.
"""
for bound in self.__var.domain:
if bound < 0 or bound > 1:
raise TypeError(
f"cannot call negated on a non boolean variable: {self}"
)
if self.__negation is None:
self.__negation = _NotBooleanVariable(self)
return self.__negation
def __invert__(self) -> "_NotBooleanVariable":
"""Returns the logical negation of a Boolean variable."""
return self.negated()
# Pre PEP8 compatibility.
# pylint: disable=invalid-name
Not = negated
def Name(self) -> str:
return self.name
def Proto(self) -> cp_model_pb2.IntegerVariableProto:
return self.proto
def Index(self) -> int:
return self.index
# pylint: enable=invalid-name
class _NotBooleanVariable(LinearExpr):
"""Negation of a boolean variable."""
def __init__(self, boolvar: IntVar) -> None:
self.__boolvar: IntVar = boolvar
@property
def index(self) -> int:
return -self.__boolvar.index - 1
def negated(self) -> IntVar:
return self.__boolvar
def __invert__(self) -> IntVar:
"""Returns the logical negation of a Boolean literal."""
return self.negated()
def __str__(self) -> str:
return self.name
@property
def name(self) -> str:
return "not(%s)" % str(self.__boolvar)
def __bool__(self) -> NoReturn:
raise NotImplementedError(
"Evaluating a literal as a Boolean value is not implemented."
)
# Pre PEP8 compatibility.
# pylint: disable=invalid-name
def Not(self) -> "IntVar":
return self.negated()
def Index(self) -> int:
return self.index
# pylint: enable=invalid-name
class BoundedLinearExpression:
"""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: LinearExprT, bounds: Sequence[int]) -> None:
self.__expr: LinearExprT = expr