-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathmodel_builder.py
More file actions
1442 lines (1199 loc) · 53.4 KB
/
Copy pathmodel_builder.py
File metadata and controls
1442 lines (1199 loc) · 53.4 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
#!/usr/bin/env python3
# Copyright 2010-2025 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 model_builder models.
The following two sections describe the main
methods for building and solving those models.
* [`Model`](#model_builder.Model): Methods for creating
models, including variables and constraints.
* [`Solver`](#model_builder.Solver): Methods for solving
a model and evaluating solutions.
Additional methods for solving Model models:
* [`Constraint`](#model_builder.Constraint): A few utility methods for modifying
constraints created by `Model`.
* [`LinearExpr`](#model_builder.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 collections.abc import Callable
import math
import numbers
import typing
from typing import Optional, Union
import numpy as np
import pandas as pd
from ortools.linear_solver import linear_solver_pb2
from ortools.linear_solver.python import model_builder_helper as mbh
from ortools.linear_solver.python import model_builder_numbers as mbn
# Custom types.
NumberT = Union[int, float, numbers.Real, np.number]
IntegerT = Union[int, numbers.Integral, np.integer]
LinearExprT = Union[mbh.LinearExpr, NumberT]
ConstraintT = Union[mbh.BoundedLinearExpression, bool]
_IndexOrSeries = Union[pd.Index, pd.Series]
_VariableOrConstraint = Union["LinearConstraint", mbh.Variable]
# Forward solve statuses.
AffineExpr = mbh.AffineExpr
BoundedLinearExpression = mbh.BoundedLinearExpression
FlatExpr = mbh.FlatExpr
LinearExpr = mbh.LinearExpr
SolveStatus = mbh.SolveStatus
Variable = mbh.Variable
def _add_linear_constraint_to_helper(
bounded_expr: Union[bool, mbh.BoundedLinearExpression],
helper: mbh.ModelBuilderHelper,
name: Optional[str],
):
"""Creates a new linear constraint in the helper.
It handles boolean values (which might arise in the construction of
BoundedLinearExpressions).
If bounded_expr is a Boolean value, the created constraint is different.
In that case, the constraint will be immutable and marked as under-specified.
It will be always feasible or infeasible whether the value is True or False.
Args:
bounded_expr: The bounded expression used to create the constraint.
helper: The helper to create the constraint.
name: The name of the constraint to be created.
Returns:
LinearConstraint: a constraint in the helper corresponding to the input.
Raises:
TypeError: If constraint is an invalid type.
"""
if isinstance(bounded_expr, bool):
c = LinearConstraint(helper, is_under_specified=True)
if name is not None:
helper.set_constraint_name(c.index, name)
if bounded_expr:
# constraint that is always feasible: 0.0 <= nothing <= 0.0
helper.set_constraint_lower_bound(c.index, 0.0)
helper.set_constraint_upper_bound(c.index, 0.0)
else:
# constraint that is always infeasible: +oo <= nothing <= -oo
helper.set_constraint_lower_bound(c.index, 1)
helper.set_constraint_upper_bound(c.index, -1)
return c
if isinstance(bounded_expr, mbh.BoundedLinearExpression):
c = LinearConstraint(helper)
# pylint: disable=protected-access
helper.add_terms_to_constraint(c.index, bounded_expr.vars, bounded_expr.coeffs)
helper.set_constraint_lower_bound(c.index, bounded_expr.lower_bound)
helper.set_constraint_upper_bound(c.index, bounded_expr.upper_bound)
# pylint: enable=protected-access
if name is not None:
helper.set_constraint_name(c.index, name)
return c
raise TypeError(f"invalid type={type(bounded_expr).__name__!r}")
def _add_enforced_linear_constraint_to_helper(
bounded_expr: Union[bool, mbh.BoundedLinearExpression],
helper: mbh.ModelBuilderHelper,
var: Variable,
value: bool,
name: Optional[str],
):
"""Creates a new enforced linear constraint in the helper.
It handles boolean values (which might arise in the construction of
BoundedLinearExpressions).
If bounded_expr is a Boolean value, the linear part of the constraint is
different.
In that case, the constraint will be immutable and marked as under-specified.
Its linear part will be always feasible or infeasible whether the value is
True or False.
Args:
bounded_expr: The bounded expression used to create the constraint.
helper: The helper to create the constraint.
var: the variable used in the indicator
value: the value used in the indicator
name: The name of the constraint to be created.
Returns:
EnforcedLinearConstraint: a constraint in the helper corresponding to the
input.
Raises:
TypeError: If constraint is an invalid type.
"""
if isinstance(bounded_expr, bool):
# TODO(user): create indicator variable assignment instead ?
c = EnforcedLinearConstraint(helper, is_under_specified=True)
c.indicator_variable = var
c.indicator_value = value
if name is not None:
helper.set_enforced_constraint_name(c.index, name)
if bounded_expr:
# constraint that is always feasible: 0.0 <= nothing <= 0.0
helper.set_enforced_constraint_lower_bound(c.index, 0.0)
helper.set_enforced_constraint_upper_bound(c.index, 0.0)
else:
# constraint that is always infeasible: +oo <= nothing <= -oo
helper.set_enforced_constraint_lower_bound(c.index, 1)
helper.set_enforced_constraint_upper_bound(c.index, -1)
return c
if isinstance(bounded_expr, mbh.BoundedLinearExpression):
c = EnforcedLinearConstraint(helper)
c.indicator_variable = var
c.indicator_value = value
helper.add_terms_to_enforced_constraint(
c.index, bounded_expr.vars, bounded_expr.coeffs
)
helper.set_enforced_constraint_lower_bound(c.index, bounded_expr.lower_bound)
helper.set_enforced_constraint_upper_bound(c.index, bounded_expr.upper_bound)
if name is not None:
helper.set_constraint_name(c.index, name)
return c
raise TypeError(f"invalid type={type(bounded_expr).__name__!r}")
class LinearConstraint:
"""Stores a linear equation.
Example:
x = model.new_num_var(0, 10, 'x')
y = model.new_num_var(0, 10, 'y')
linear_constraint = model.add(x + 2 * y == 5)
"""
def __init__(
self,
helper: mbh.ModelBuilderHelper,
*,
index: Optional[IntegerT] = None,
is_under_specified: bool = False,
) -> None:
"""LinearConstraint constructor.
Args:
helper: The pybind11 ModelBuilderHelper.
index: If specified, recreates a wrapper to an existing linear constraint.
is_under_specified: indicates if the constraint was created by
model.add(bool).
"""
if index is None:
self.__index = helper.add_linear_constraint()
else:
self.__index = index
self.__helper: mbh.ModelBuilderHelper = helper
self.__is_under_specified = is_under_specified
def __hash__(self):
return hash((self.__helper, self.__index))
@property
def index(self) -> IntegerT:
"""Returns the index of the constraint in the helper."""
return self.__index
@property
def helper(self) -> mbh.ModelBuilderHelper:
"""Returns the ModelBuilderHelper instance."""
return self.__helper
@property
def lower_bound(self) -> np.double:
return self.__helper.constraint_lower_bound(self.__index)
@lower_bound.setter
def lower_bound(self, bound: NumberT) -> None:
self.assert_constraint_is_well_defined()
self.__helper.set_constraint_lower_bound(self.__index, bound)
@property
def upper_bound(self) -> np.double:
return self.__helper.constraint_upper_bound(self.__index)
@upper_bound.setter
def upper_bound(self, bound: NumberT) -> None:
self.assert_constraint_is_well_defined()
self.__helper.set_constraint_upper_bound(self.__index, bound)
@property
def name(self) -> str:
constraint_name = self.__helper.constraint_name(self.__index)
if constraint_name:
return constraint_name
return f"linear_constraint#{self.__index}"
@name.setter
def name(self, name: str) -> None:
return self.__helper.set_constraint_name(self.__index, name)
@property
def is_under_specified(self) -> bool:
"""Returns True if the constraint is under specified.
Usually, it means that it was created by model.add(False) or model.add(True)
The effect is that modifying the constraint will raise an exception.
"""
return self.__is_under_specified
def assert_constraint_is_well_defined(self) -> None:
"""Raises an exception if the constraint is under specified."""
if self.__is_under_specified:
raise ValueError(
f"Constraint {self.index} is under specified and cannot be modified"
)
def __str__(self):
return self.name
def __repr__(self):
return (
f"LinearConstraint({self.name}, lb={self.lower_bound},"
f" ub={self.upper_bound},"
f" var_indices={self.helper.constraint_var_indices(self.index)},"
f" coefficients={self.helper.constraint_coefficients(self.index)})"
)
def set_coefficient(self, var: Variable, coeff: NumberT) -> None:
"""Sets the coefficient of the variable in the constraint."""
self.assert_constraint_is_well_defined()
self.__helper.set_constraint_coefficient(self.__index, var.index, coeff)
def add_term(self, var: Variable, coeff: NumberT) -> None:
"""Adds var * coeff to the constraint."""
self.assert_constraint_is_well_defined()
self.__helper.safe_add_term_to_constraint(self.__index, var.index, coeff)
def clear_terms(self) -> None:
"""Clear all terms of the constraint."""
self.assert_constraint_is_well_defined()
self.__helper.clear_constraint_terms(self.__index)
class EnforcedLinearConstraint:
"""Stores an enforced linear equation, also name indicator constraint.
Example:
x = model.new_num_var(0, 10, 'x')
y = model.new_num_var(0, 10, 'y')
z = model.new_bool_var('z')
enforced_linear_constraint = model.add_enforced(x + 2 * y == 5, z, False)
"""
def __init__(
self,
helper: mbh.ModelBuilderHelper,
*,
index: Optional[IntegerT] = None,
is_under_specified: bool = False,
) -> None:
"""EnforcedLinearConstraint constructor.
Args:
helper: The pybind11 ModelBuilderHelper.
index: If specified, recreates a wrapper to an existing linear constraint.
is_under_specified: indicates if the constraint was created by
model.add(bool).
"""
if index is None:
self.__index = helper.add_enforced_linear_constraint()
else:
if not helper.is_enforced_linear_constraint(index):
raise ValueError(
f"the given index {index} does not refer to an enforced linear"
" constraint"
)
self.__index = index
self.__helper: mbh.ModelBuilderHelper = helper
self.__is_under_specified = is_under_specified
@property
def index(self) -> IntegerT:
"""Returns the index of the constraint in the helper."""
return self.__index
@property
def helper(self) -> mbh.ModelBuilderHelper:
"""Returns the ModelBuilderHelper instance."""
return self.__helper
@property
def lower_bound(self) -> np.double:
return self.__helper.enforced_constraint_lower_bound(self.__index)
@lower_bound.setter
def lower_bound(self, bound: NumberT) -> None:
self.assert_constraint_is_well_defined()
self.__helper.set_enforced_constraint_lower_bound(self.__index, bound)
@property
def upper_bound(self) -> np.double:
return self.__helper.enforced_constraint_upper_bound(self.__index)
@upper_bound.setter
def upper_bound(self, bound: NumberT) -> None:
self.assert_constraint_is_well_defined()
self.__helper.set_enforced_constraint_upper_bound(self.__index, bound)
@property
def indicator_variable(self) -> "Variable":
enforcement_var_index = (
self.__helper.enforced_constraint_indicator_variable_index(self.__index)
)
return Variable(self.__helper, enforcement_var_index)
@indicator_variable.setter
def indicator_variable(self, var: "Variable") -> None:
self.__helper.set_enforced_constraint_indicator_variable_index(
self.__index, var.index
)
@property
def indicator_value(self) -> bool:
return self.__helper.enforced_constraint_indicator_value(self.__index)
@indicator_value.setter
def indicator_value(self, value: bool) -> None:
self.__helper.set_enforced_constraint_indicator_value(self.__index, value)
@property
def name(self) -> str:
constraint_name = self.__helper.enforced_constraint_name(self.__index)
if constraint_name:
return constraint_name
return f"enforced_linear_constraint#{self.__index}"
@name.setter
def name(self, name: str) -> None:
return self.__helper.set_enforced_constraint_name(self.__index, name)
@property
def is_under_specified(self) -> bool:
"""Returns True if the constraint is under specified.
Usually, it means that it was created by model.add(False) or model.add(True)
The effect is that modifying the constraint will raise an exception.
"""
return self.__is_under_specified
def assert_constraint_is_well_defined(self) -> None:
"""Raises an exception if the constraint is under specified."""
if self.__is_under_specified:
raise ValueError(
f"Constraint {self.index} is under specified and cannot be modified"
)
def __str__(self):
return self.name
def __repr__(self):
return (
f"EnforcedLinearConstraint({self.name}, lb={self.lower_bound},"
f" ub={self.upper_bound},"
f" var_indices={self.helper.enforced_constraint_var_indices(self.index)},"
f" coefficients={self.helper.enforced_constraint_coefficients(self.index)},"
f" indicator_variable={self.indicator_variable}"
f" indicator_value={self.indicator_value})"
)
def set_coefficient(self, var: Variable, coeff: NumberT) -> None:
"""Sets the coefficient of the variable in the constraint."""
self.assert_constraint_is_well_defined()
self.__helper.set_enforced_constraint_coefficient(
self.__index, var.index, coeff
)
def add_term(self, var: Variable, coeff: NumberT) -> None:
"""Adds var * coeff to the constraint."""
self.assert_constraint_is_well_defined()
self.__helper.safe_add_term_to_enforced_constraint(
self.__index, var.index, coeff
)
def clear_terms(self) -> None:
"""Clear all terms of the constraint."""
self.assert_constraint_is_well_defined()
self.__helper.clear_enforced_constraint_terms(self.__index)
class Model:
"""Methods for building a linear 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.__helper: mbh.ModelBuilderHelper = mbh.ModelBuilderHelper()
def clone(self) -> "Model":
"""Returns a clone of the current model."""
clone = Model()
clone.helper.overwrite_model(self.helper)
return clone
@typing.overload
def _get_linear_constraints(self, constraints: Optional[pd.Index]) -> pd.Index: ...
@typing.overload
def _get_linear_constraints(self, constraints: pd.Series) -> pd.Series: ...
def _get_linear_constraints(
self, constraints: Optional[_IndexOrSeries] = None
) -> _IndexOrSeries:
if constraints is None:
return self.get_linear_constraints()
return constraints
@typing.overload
def _get_variables(self, variables: Optional[pd.Index]) -> pd.Index: ...
@typing.overload
def _get_variables(self, variables: pd.Series) -> pd.Series: ...
def _get_variables(
self, variables: Optional[_IndexOrSeries] = None
) -> _IndexOrSeries:
if variables is None:
return self.get_variables()
return variables
def get_linear_constraints(self) -> pd.Index:
"""Gets all linear constraints in the model."""
return pd.Index(
[self.linear_constraint_from_index(i) for i in range(self.num_constraints)],
name="linear_constraint",
)
def get_linear_constraint_expressions(
self, constraints: Optional[_IndexOrSeries] = None
) -> pd.Series:
"""Gets the expressions of all linear constraints in the set.
If `constraints` is a `pd.Index`, then the output will be indexed by the
constraints. If `constraints` is a `pd.Series` indexed by the underlying
dimensions, then the output will be indexed by the same underlying
dimensions.
Args:
constraints (Union[pd.Index, pd.Series]): Optional. The set of linear
constraints from which to get the expressions. If unspecified, all
linear constraints will be in scope.
Returns:
pd.Series: The expressions of all linear constraints in the set.
"""
return _attribute_series(
# pylint: disable=g-long-lambda
func=lambda c: mbh.FlatExpr(
# pylint: disable=g-complex-comprehension
[
Variable(self.__helper, var_id)
for var_id in c.helper.constraint_var_indices(c.index)
],
c.helper.constraint_coefficients(c.index),
0.0,
),
values=self._get_linear_constraints(constraints),
)
def get_linear_constraint_lower_bounds(
self, constraints: Optional[_IndexOrSeries] = None
) -> pd.Series:
"""Gets the lower bounds of all linear constraints in the set.
If `constraints` is a `pd.Index`, then the output will be indexed by the
constraints. If `constraints` is a `pd.Series` indexed by the underlying
dimensions, then the output will be indexed by the same underlying
dimensions.
Args:
constraints (Union[pd.Index, pd.Series]): Optional. The set of linear
constraints from which to get the lower bounds. If unspecified, all
linear constraints will be in scope.
Returns:
pd.Series: The lower bounds of all linear constraints in the set.
"""
return _attribute_series(
func=lambda c: c.lower_bound, # pylint: disable=protected-access
values=self._get_linear_constraints(constraints),
)
def get_linear_constraint_upper_bounds(
self, constraints: Optional[_IndexOrSeries] = None
) -> pd.Series:
"""Gets the upper bounds of all linear constraints in the set.
If `constraints` is a `pd.Index`, then the output will be indexed by the
constraints. If `constraints` is a `pd.Series` indexed by the underlying
dimensions, then the output will be indexed by the same underlying
dimensions.
Args:
constraints (Union[pd.Index, pd.Series]): Optional. The set of linear
constraints. If unspecified, all linear constraints will be in scope.
Returns:
pd.Series: The upper bounds of all linear constraints in the set.
"""
return _attribute_series(
func=lambda c: c.upper_bound, # pylint: disable=protected-access
values=self._get_linear_constraints(constraints),
)
def get_variables(self) -> pd.Index:
"""Gets all variables in the model."""
return pd.Index(
[self.var_from_index(i) for i in range(self.num_variables)],
name="variable",
)
def get_variable_lower_bounds(
self, variables: Optional[_IndexOrSeries] = None
) -> pd.Series:
"""Gets the lower bounds of all variables in the set.
If `variables` is a `pd.Index`, then the output will be indexed by the
variables. If `variables` is a `pd.Series` indexed by the underlying
dimensions, then the output will be indexed by the same underlying
dimensions.
Args:
variables (Union[pd.Index, pd.Series]): Optional. The set of variables
from which to get the lower bounds. If unspecified, all variables will
be in scope.
Returns:
pd.Series: The lower bounds of all variables in the set.
"""
return _attribute_series(
func=lambda v: v.lower_bound, # pylint: disable=protected-access
values=self._get_variables(variables),
)
def get_variable_upper_bounds(
self, variables: Optional[_IndexOrSeries] = None
) -> pd.Series:
"""Gets the upper bounds of all variables in the set.
Args:
variables (Union[pd.Index, pd.Series]): Optional. The set of variables
from which to get the upper bounds. If unspecified, all variables will
be in scope.
Returns:
pd.Series: The upper bounds of all variables in the set.
"""
return _attribute_series(
func=lambda v: v.upper_bound, # pylint: disable=protected-access
values=self._get_variables(variables),
)
# Integer variable.
def new_var(
self, lb: NumberT, ub: NumberT, is_integer: bool, name: Optional[str]
) -> Variable:
"""Create an integer variable with domain [lb, ub].
Args:
lb: Lower bound of the variable.
ub: Upper bound of the variable.
is_integer: Indicates if the variable must take integral values.
name: The name of the variable.
Returns:
a variable whose domain is [lb, ub].
"""
if name:
return Variable(self.__helper, lb, ub, is_integer, name)
else:
return Variable(self.__helper, lb, ub, is_integer)
def new_int_var(
self, lb: NumberT, ub: NumberT, name: Optional[str] = None
) -> Variable:
"""Create an integer variable with domain [lb, ub].
Args:
lb: Lower bound of the variable.
ub: Upper bound of the variable.
name: The name of the variable.
Returns:
a variable whose domain is [lb, ub].
"""
return self.new_var(lb, ub, True, name)
def new_num_var(
self, lb: NumberT, ub: NumberT, name: Optional[str] = None
) -> Variable:
"""Create an integer variable with domain [lb, ub].
Args:
lb: Lower bound of the variable.
ub: Upper bound of the variable.
name: The name of the variable.
Returns:
a variable whose domain is [lb, ub].
"""
return self.new_var(lb, ub, False, name)
def new_bool_var(self, name: Optional[str] = None) -> Variable:
"""Creates a 0-1 variable with the given name."""
return self.new_var(0, 1, True, name) # numpy-scalars
def new_constant(self, value: NumberT) -> Variable:
"""Declares a constant variable."""
return self.new_var(value, value, False, None)
def new_var_series(
self,
name: str,
index: pd.Index,
lower_bounds: Union[NumberT, pd.Series] = -math.inf,
upper_bounds: Union[NumberT, pd.Series] = math.inf,
is_integral: Union[bool, pd.Series] = False,
) -> pd.Series:
"""Creates a series of (scalar-valued) variables with the given name.
Args:
name (str): Required. The name of the variable set.
index (pd.Index): Required. The index to use for the variable set.
lower_bounds (Union[int, float, pd.Series]): Optional. A lower bound for
variables in the set. If a `pd.Series` is passed in, it will be based on
the corresponding values of the pd.Series. Defaults to -inf.
upper_bounds (Union[int, float, pd.Series]): Optional. An upper bound for
variables in the set. If a `pd.Series` is passed in, it will be based on
the corresponding values of the pd.Series. Defaults to +inf.
is_integral (bool, pd.Series): Optional. Indicates if the variable can
only take integer values. If a `pd.Series` is passed in, it will be
based on the corresponding values of the pd.Series. Defaults to False.
Returns:
pd.Series: The variable set indexed by its corresponding dimensions.
Raises:
TypeError: if the `index` is invalid (e.g. a `DataFrame`).
ValueError: if the `name` is not a valid identifier or already exists.
ValueError: if the `lowerbound` is greater than the `upperbound`.
ValueError: if the index of `lower_bound`, `upper_bound`, or `is_integer`
does not match the input index.
"""
if not isinstance(index, pd.Index):
raise TypeError("Non-index object is used as index")
if not name.isidentifier():
raise ValueError(f"name={name!r} is not a valid identifier")
if (
mbn.is_a_number(lower_bounds)
and mbn.is_a_number(upper_bounds)
and lower_bounds > upper_bounds
):
raise ValueError(
f"lower_bound={lower_bounds} is greater than"
f" upper_bound={upper_bounds} for variable set={name!r}"
)
if (
isinstance(is_integral, bool)
and is_integral
and mbn.is_a_number(lower_bounds)
and mbn.is_a_number(upper_bounds)
and math.isfinite(lower_bounds)
and math.isfinite(upper_bounds)
and math.ceil(lower_bounds) > math.floor(upper_bounds)
):
raise ValueError(
f"ceil(lower_bound={lower_bounds})={math.ceil(lower_bounds)}"
f" is greater than floor({upper_bounds}) = {math.floor(upper_bounds)}"
f" for variable set={name!r}"
)
lower_bounds = _convert_to_series_and_validate_index(lower_bounds, index)
upper_bounds = _convert_to_series_and_validate_index(upper_bounds, index)
is_integrals = _convert_to_series_and_validate_index(is_integral, index)
return pd.Series(
index=index,
data=[
# pylint: disable=g-complex-comprehension
Variable(
self.__helper,
lower_bounds[i],
upper_bounds[i],
is_integrals[i],
f"{name}[{i}]",
)
for i in index
],
)
def new_num_var_series(
self,
name: str,
index: pd.Index,
lower_bounds: Union[NumberT, pd.Series] = -math.inf,
upper_bounds: Union[NumberT, pd.Series] = math.inf,
) -> pd.Series:
"""Creates a series of continuous variables with the given name.
Args:
name (str): Required. The name of the variable set.
index (pd.Index): Required. The index to use for the variable set.
lower_bounds (Union[int, float, pd.Series]): Optional. A lower bound for
variables in the set. If a `pd.Series` is passed in, it will be based on
the corresponding values of the pd.Series. Defaults to -inf.
upper_bounds (Union[int, float, pd.Series]): Optional. An upper bound for
variables in the set. If a `pd.Series` is passed in, it will be based on
the corresponding values of the pd.Series. Defaults to +inf.
Returns:
pd.Series: The variable set indexed by its corresponding dimensions.
Raises:
TypeError: if the `index` is invalid (e.g. a `DataFrame`).
ValueError: if the `name` is not a valid identifier or already exists.
ValueError: if the `lowerbound` is greater than the `upperbound`.
ValueError: if the index of `lower_bound`, `upper_bound`, or `is_integer`
does not match the input index.
"""
return self.new_var_series(name, index, lower_bounds, upper_bounds, False)
def new_int_var_series(
self,
name: str,
index: pd.Index,
lower_bounds: Union[NumberT, pd.Series] = -math.inf,
upper_bounds: Union[NumberT, pd.Series] = math.inf,
) -> pd.Series:
"""Creates a series of integer variables with the given name.
Args:
name (str): Required. The name of the variable set.
index (pd.Index): Required. The index to use for the variable set.
lower_bounds (Union[int, float, pd.Series]): Optional. A lower bound for
variables in the set. If a `pd.Series` is passed in, it will be based on
the corresponding values of the pd.Series. Defaults to -inf.
upper_bounds (Union[int, float, pd.Series]): Optional. An upper bound for
variables in the set. If a `pd.Series` is passed in, it will be based on
the corresponding values of the pd.Series. Defaults to +inf.
Returns:
pd.Series: The variable set indexed by its corresponding dimensions.
Raises:
TypeError: if the `index` is invalid (e.g. a `DataFrame`).
ValueError: if the `name` is not a valid identifier or already exists.
ValueError: if the `lowerbound` is greater than the `upperbound`.
ValueError: if the index of `lower_bound`, `upper_bound`, or `is_integer`
does not match the input index.
"""
return self.new_var_series(name, index, lower_bounds, upper_bounds, True)
def new_bool_var_series(
self,
name: str,
index: pd.Index,
) -> pd.Series:
"""Creates a series of Boolean variables with the given name.
Args:
name (str): Required. The name of the variable set.
index (pd.Index): Required. The index to use for the variable set.
Returns:
pd.Series: The variable set indexed by its corresponding dimensions.
Raises:
TypeError: if the `index` is invalid (e.g. a `DataFrame`).
ValueError: if the `name` is not a valid identifier or already exists.
ValueError: if the `lowerbound` is greater than the `upperbound`.
ValueError: if the index of `lower_bound`, `upper_bound`, or `is_integer`
does not match the input index.
"""
return self.new_var_series(name, index, 0, 1, True)
def var_from_index(self, index: IntegerT) -> Variable:
"""Rebuilds a variable object from the model and its index."""
return Variable(self.__helper, index)
# Linear constraints.
def add_linear_constraint( # pytype: disable=annotation-type-mismatch # numpy-scalars
self,
linear_expr: LinearExprT,
lb: NumberT = -math.inf,
ub: NumberT = math.inf,
name: Optional[str] = None,
) -> LinearConstraint:
"""Adds the constraint: `lb <= linear_expr <= ub` with the given name."""
ct = LinearConstraint(self.__helper)
if name:
self.__helper.set_constraint_name(ct.index, name)
if mbn.is_a_number(linear_expr):
self.__helper.set_constraint_lower_bound(ct.index, lb - linear_expr)
self.__helper.set_constraint_upper_bound(ct.index, ub - linear_expr)
elif isinstance(linear_expr, LinearExpr):
flat_expr = mbh.FlatExpr(linear_expr)
# pylint: disable=protected-access
self.__helper.set_constraint_lower_bound(ct.index, lb - flat_expr.offset)
self.__helper.set_constraint_upper_bound(ct.index, ub - flat_expr.offset)
self.__helper.add_terms_to_constraint(
ct.index, flat_expr.vars, flat_expr.coeffs
)
else:
raise TypeError(
"Not supported:"
f" Model.add_linear_constraint({type(linear_expr).__name__!r})"
)
return ct
def add(
self, ct: Union[ConstraintT, pd.Series], name: Optional[str] = None
) -> Union[LinearConstraint, pd.Series]:
"""Adds a `BoundedLinearExpression` to the model.
Args:
ct: A [`BoundedLinearExpression`](#boundedlinearexpression).
name: An optional name.
Returns:
An instance of the `Constraint` class.
Note that a special treatment is done when the argument does not contain any
variable, and thus evaluates to True or False.
`model.add(True)` will create a constraint 0 <= empty sum <= 0.
The constraint will be marked as under specified, and cannot be modified
thereafter.
`model.add(False)` will create a constraint inf <= empty sum <= -inf. The
constraint will be marked as under specified, and cannot be modified
thereafter.
you can check the if a constraint is under specified by reading the
`LinearConstraint.is_under_specified` property.
"""
if isinstance(ct, mbh.BoundedLinearExpression):
return _add_linear_constraint_to_helper(ct, self.__helper, name)
elif isinstance(ct, bool):
return _add_linear_constraint_to_helper(ct, self.__helper, name)
elif isinstance(ct, pd.Series):
return pd.Series(
index=ct.index,
data=[
_add_linear_constraint_to_helper(
expr, self.__helper, f"{name}[{i}]"
)
for (i, expr) in zip(ct.index, ct)
],
)
else:
raise TypeError(f"Not supported: Model.add({type(ct).__name__!r})")
def linear_constraint_from_index(self, index: IntegerT) -> LinearConstraint:
"""Rebuilds a linear constraint object from the model and its index."""
return LinearConstraint(self.__helper, index=index)
# Enforced Linear constraints.
def add_enforced_linear_constraint( # pytype: disable=annotation-type-mismatch # numpy-scalars
self,
linear_expr: LinearExprT,
ivar: "Variable",
ivalue: bool,
lb: NumberT = -math.inf,
ub: NumberT = math.inf,
name: Optional[str] = None,
) -> EnforcedLinearConstraint:
"""Adds the constraint: `ivar == ivalue => lb <= linear_expr <= ub` with the given name."""
ct = EnforcedLinearConstraint(self.__helper)
ct.indicator_variable = ivar
ct.indicator_value = ivalue
if name:
self.__helper.set_constraint_name(ct.index, name)
if mbn.is_a_number(linear_expr):
self.__helper.set_constraint_lower_bound(ct.index, lb - linear_expr)
self.__helper.set_constraint_upper_bound(ct.index, ub - linear_expr)
elif isinstance(linear_expr, LinearExpr):
flat_expr = mbh.FlatExpr(linear_expr)
# pylint: disable=protected-access
self.__helper.set_constraint_lower_bound(ct.index, lb - flat_expr.offset)
self.__helper.set_constraint_upper_bound(ct.index, ub - flat_expr.offset)
self.__helper.add_terms_to_constraint(
ct.index, flat_expr.vars, flat_expr.coeffs
)
else:
raise TypeError(
"Not supported:"
f" Model.add_enforced_linear_constraint({type(linear_expr).__name__!r})"
)
return ct
def add_enforced(
self,
ct: Union[ConstraintT, pd.Series],
var: Union[Variable, pd.Series],
value: Union[bool, pd.Series],
name: Optional[str] = None,
) -> Union[EnforcedLinearConstraint, pd.Series]:
"""Adds a `ivar == ivalue => BoundedLinearExpression` to the model.
Args:
ct: A [`BoundedLinearExpression`](#boundedlinearexpression).
var: The indicator variable
value: the indicator value
name: An optional name.
Returns:
An instance of the `Constraint` class.
Note that a special treatment is done when the argument does not contain any
variable, and thus evaluates to True or False.
model.add_enforced(True, ivar, ivalue) will create a constraint 0 <= empty
sum <= 0
model.add_enforced(False, var, value) will create a constraint inf <=
empty sum <= -inf
you can check the if a constraint is always false (lb=inf, ub=-inf) by
calling EnforcedLinearConstraint.is_always_false()
"""
if isinstance(ct, mbh.BoundedLinearExpression):
return _add_enforced_linear_constraint_to_helper(
ct, self.__helper, var, value, name
)
elif (
isinstance(ct, bool)
and isinstance(var, Variable)
and isinstance(value, bool)