-
Notifications
You must be signed in to change notification settings - Fork 529
/
Copy pathtest_preprocessor.py
3011 lines (2677 loc) · 114 KB
/
test_preprocessor.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
# ___________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2025
# National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and
# Engineering Solutions of Sandia, LLC, the U.S. Government retains certain
# rights in this software.
# This software is distributed under the 3-clause BSD License.
# ___________________________________________________________________________
"""
Tests for the PyROS preprocessor.
"""
import logging
import textwrap
import pyomo.common.unittest as unittest
from pyomo.common.collections import Bunch, ComponentSet, ComponentMap
from pyomo.common.dependencies import numpy_available
from pyomo.common.dependencies import scipy as sp, scipy_available
from pyomo.common.dependencies import attempt_import
from pyomo.common.log import LoggingIntercept
from pyomo.core.base import (
Any,
Var,
Constraint,
Expression,
Objective,
ConcreteModel,
Param,
RangeSet,
maximize,
Block,
)
from pyomo.core.base.set_types import NonNegativeReals, NonPositiveReals, Reals
from pyomo.core.expr import (
LinearExpression,
log,
sin,
exp,
RangedExpression,
SumExpression,
)
from pyomo.core.expr.compare import assertExpressionsEqual
from pyomo.contrib.pyros.uncertainty_sets import BoxSet, DiscreteScenarioSet
from pyomo.contrib.pyros.util import (
ModelData,
ObjectiveType,
get_effective_var_partitioning,
get_var_certain_uncertain_bounds,
get_var_bound_pairs,
turn_nonadjustable_var_bounds_to_constraints,
turn_adjustable_var_bounds_to_constraints,
standardize_inequality_constraints,
standardize_equality_constraints,
standardize_active_objective,
declare_objective_expressions,
add_decision_rule_constraints,
add_decision_rule_variables,
reformulate_state_var_independent_eq_cons,
setup_working_model,
VariablePartitioning,
preprocess_model_data,
log_model_statistics,
)
parameterized, param_available = attempt_import('parameterized')
if not (numpy_available and scipy_available and param_available):
raise unittest.SkipTest(
'PyROS preprocessor unit tests require parameterized, numpy, and scipy'
)
parameterized = parameterized.parameterized
logger = logging.getLogger(__name__)
class TestEffectiveVarPartitioning(unittest.TestCase):
"""
Test method(s) for identification of nonadjustable variables
which are not necessarily in the user-provided sequence of
first-stage variables.
"""
def build_simple_test_model_data(self):
"""
Build simple model for effective variable partitioning tests.
"""
m = ConcreteModel()
m.q = Param(mutable=True, initialize=1)
m.q2 = Param(mutable=True, initialize=2)
m.x1 = Var(bounds=(m.q2, m.q2))
m.x2 = Var()
m.z = Var()
m.y = Var(range(1, 5))
m.c0 = Constraint(expr=m.q + m.x1 + m.z == 0)
m.c1 = Constraint(expr=(0, m.x1 - m.z * (m.q2 - 1), 0))
m.c2 = Constraint(expr=m.x1**2 - m.z + m.y[1] == 0)
m.c2_dupl = Constraint(expr=m.x1**2 - m.z + m.y[1] == 0)
m.c3 = Constraint(expr=m.x1**3 + m.y[1] + 2 * m.y[2] == 0)
m.c4 = Constraint(expr=m.x2**2 + m.y[1] + m.y[2] + m.y[3] + m.y[4] == 0)
m.c5 = Constraint(expr=m.x2 + 2 * m.y[2] + m.y[3] + 2 * m.y[4] == 0)
model_data = Bunch()
model_data.config = Bunch()
model_data.working_model = ConcreteModel()
model_data.working_model.user_model = mdl = m.clone()
model_data.working_model.uncertain_params = [mdl.q, mdl.q2]
model_data.working_model.effective_uncertain_params = [mdl.q]
user_var_partitioning = model_data.working_model.user_var_partitioning = Bunch()
user_var_partitioning.first_stage_variables = [mdl.x1, mdl.x2]
user_var_partitioning.second_stage_variables = [mdl.z]
user_var_partitioning.state_variables = list(mdl.y.values())
return model_data
def test_effective_partitioning_system(self):
"""
Test effective partitioning on an example system of
constraints.
"""
model_data = self.build_simple_test_model_data()
m = model_data.working_model.user_model
config = model_data.config
config.decision_rule_order = 0
config.progress_logger = logger
expected_partitioning = {
"first_stage_variables": [m.x1, m.x2, m.z, m.y[1], m.y[2]],
"second_stage_variables": [],
"state_variables": [m.y[3], m.y[4]],
}
for dr_order in [0, 1, 2]:
config.decision_rule_order = dr_order
actual_partitioning = get_effective_var_partitioning(model_data=model_data)
for vartype, expected_vars in expected_partitioning.items():
actual_vars = getattr(actual_partitioning, vartype)
self.assertEqual(
ComponentSet(expected_vars),
ComponentSet(actual_vars),
msg=(
f"Effective {vartype!r} are not as expected "
f"for decision rule order {config.decision_rule_order}. "
"\n"
f"Expected: {[var.name for var in expected_vars]}"
"\n"
f"Actual: {[var.name for var in actual_vars]}"
),
)
# linear coefficient below tolerance;
# that should prevent pretriangularization
m.c2.set_value(m.x1**2 + m.z + 1e-10 * m.y[1] == 0)
m.c2_dupl.set_value(m.x1**2 + m.z + 1e-10 * m.y[1] == 0)
expected_partitioning = {
"first_stage_variables": [m.x1, m.x2, m.z],
"second_stage_variables": [],
"state_variables": list(m.y.values()),
}
for dr_order in [0, 1, 2]:
config.decision_rule_order = dr_order
actual_partitioning = get_effective_var_partitioning(model_data)
for vartype, expected_vars in expected_partitioning.items():
actual_vars = getattr(actual_partitioning, vartype)
self.assertEqual(
ComponentSet(expected_vars),
ComponentSet(actual_vars),
msg=(
f"Effective {vartype!r} are not as expected "
f"for decision rule order {config.decision_rule_order}. "
"\n"
f"Expected: {[var.name for var in expected_vars]}"
"\n"
f"Actual: {[var.name for var in actual_vars]}"
),
)
# put linear coefs above tolerance again:
# original behavior expected
m.c2.set_value(1e-6 * m.y[1] + m.x1**2 + m.z + 1e-10 * m.y[1] == 0)
m.c2_dupl.set_value(1e-6 * m.y[1] + m.x1**2 + m.z + 1e-10 * m.y[1] == 0)
expected_partitioning = {
"first_stage_variables": [m.x1, m.x2, m.z, m.y[1], m.y[2]],
"second_stage_variables": [],
"state_variables": [m.y[3], m.y[4]],
}
for dr_order in [0, 1, 2]:
config.decision_rule_order = dr_order
actual_partitioning = get_effective_var_partitioning(model_data)
for vartype, expected_vars in expected_partitioning.items():
actual_vars = getattr(actual_partitioning, vartype)
self.assertEqual(
ComponentSet(expected_vars),
ComponentSet(actual_vars),
msg=(
f"Effective {vartype!r} are not as expected "
f"for decision rule order {config.decision_rule_order}. "
"\n"
f"Expected: {[var.name for var in expected_vars]}"
"\n"
f"Actual: {[var.name for var in actual_vars]}"
),
)
# introducing this simple nonlinearity prevents
# y[2] from being identified as pretriangular
expected_partitioning = {
"first_stage_variables": [m.x1, m.x2, m.z, m.y[1]],
"second_stage_variables": [],
"state_variables": [m.y[2], m.y[3], m.y[4]],
}
m.c3.set_value(m.x1**3 + m.y[1] + 2 * m.y[1] * m.y[2] == 0)
for dr_order in [0, 1, 2]:
config.decision_rule_order = dr_order
actual_partitioning = get_effective_var_partitioning(model_data)
for vartype, expected_vars in expected_partitioning.items():
actual_vars = getattr(actual_partitioning, vartype)
self.assertEqual(
ComponentSet(expected_vars),
ComponentSet(actual_vars),
msg=(
f"Effective {vartype!r} are not as expected "
f"for decision rule order {config.decision_rule_order}. "
"\n"
f"Expected: {[var.name for var in expected_vars]}"
"\n"
f"Actual: {[var.name for var in actual_vars]}"
),
)
# fixing y[2] should make y[2] nonadjustable regardless
m.y[2].fix(10)
expected_partitioning = {
"first_stage_variables": [m.x1, m.x2, m.z, m.y[1], m.y[2]],
"second_stage_variables": [],
"state_variables": [m.y[3], m.y[4]],
}
for dr_order in [0, 1, 2]:
config.decision_rule_order = dr_order
actual_partitioning = get_effective_var_partitioning(model_data)
for vartype, expected_vars in expected_partitioning.items():
actual_vars = getattr(actual_partitioning, vartype)
self.assertEqual(
ComponentSet(expected_vars),
ComponentSet(actual_vars),
msg=(
f"Effective {vartype!r} are not as expected "
f"for decision rule order {config.decision_rule_order}. "
"\n"
f"Expected: {[var.name for var in expected_vars]}"
"\n"
f"Actual: {[var.name for var in actual_vars]}"
),
)
def test_effective_partitioning_modified_linear_system(self):
"""
Test effective partitioning on modified system of equations.
"""
model_data = self.build_simple_test_model_data()
m = model_data.working_model.user_model
# now the second-stage variable can't be determined uniquely;
# can't pretriangularize this unless z already known to be
# nonadjustable
m.c1.set_value((0, m.x1 + m.z**2, 0))
config = model_data.config
config.decision_rule_order = 0
config.progress_logger = logger
expected_partitioning_static_dr = {
"first_stage_variables": [m.x1, m.x2, m.z, m.y[1], m.y[2]],
"second_stage_variables": [],
"state_variables": [m.y[3], m.y[4]],
}
actual_partitioning_static_dr = get_effective_var_partitioning(model_data)
for vartype, expected_vars in expected_partitioning_static_dr.items():
actual_vars = getattr(actual_partitioning_static_dr, vartype)
self.assertEqual(
ComponentSet(expected_vars),
ComponentSet(actual_vars),
msg=(
f"Effective {vartype!r} are not as expected "
f"for decision rule order {config.decision_rule_order}. "
"\n"
f"Expected: {[var.name for var in expected_vars]}"
"\n"
f"Actual: {[var.name for var in actual_vars]}"
),
)
config.decision_rule_order = 1
expected_partitioning_nonstatic_dr = {
"first_stage_variables": [m.x1, m.x2],
"second_stage_variables": [m.z],
"state_variables": list(m.y.values()),
}
for dr_order in [1, 2]:
actual_partitioning_nonstatic_dr = get_effective_var_partitioning(
model_data
)
for vartype, expected_vars in expected_partitioning_nonstatic_dr.items():
actual_vars = getattr(actual_partitioning_nonstatic_dr, vartype)
self.assertEqual(
ComponentSet(expected_vars),
ComponentSet(actual_vars),
msg=(
f"Effective {vartype!r} are not as expected "
f"for decision rule order {config.decision_rule_order}. "
"\n"
f"Expected: {[var.name for var in expected_vars]}"
"\n"
f"Actual: {[var.name for var in actual_vars]}"
),
)
class TestSetupModelData(unittest.TestCase):
"""
Test method for setting up the working model works as expected.
"""
def build_test_model_data(self):
"""
Build model data object for the preprocessor.
"""
model_data = Bunch()
model_data.config = Bunch()
model_data.original_model = m = ConcreteModel()
# PARAMS: one uncertain, one certain
m.p = Param(initialize=2, mutable=True)
m.q = Param(initialize=4.5, mutable=True)
# first-stage variables
m.x1 = Var(bounds=(0, m.q), initialize=1)
m.x2 = Var(domain=NonNegativeReals, bounds=[m.p, m.p], initialize=m.p)
# second-stage variables
m.z1 = Var(domain=RangeSet(2, 4, 0), bounds=[-m.p, m.q], initialize=2)
m.z2 = Var(bounds=(-2 * m.q**2, None), initialize=1)
m.z3 = Var(bounds=(-m.q, 0), initialize=0)
m.z4 = Var(initialize=5)
m.z5 = Var(domain=NonNegativeReals, bounds=(m.q, m.q))
# state variables
m.y1 = Var(domain=NonNegativeReals, initialize=0)
m.y2 = Var(initialize=10)
# note: y3 out-of-scope, as it will not appear in the active
# Objective and Constraint objects
m.y3 = Var(domain=RangeSet(0, 1, 0), bounds=(0.2, 0.5))
# Var to represent an uncertain Param;
# bounds will be ignored
m.q2var = Var(bounds=(0, None), initialize=3.2)
# fix some variables
m.z4.fix()
m.y2.fix()
# NAMED EXPRESSIONS: mainly to test
# Var -> Param substitution for uncertain params
m.nexpr = Expression(expr=log(m.y2) + m.q2var)
# EQUALITY CONSTRAINTS
m.eq1 = Constraint(expr=m.q * (m.z3 + m.x2) == 0)
m.eq2 = Constraint(expr=m.x1 - m.z1 == 0)
m.eq3 = Constraint(expr=m.x1**2 + m.x2 + m.p * m.z2 == m.p)
m.eq4 = Constraint(expr=m.z3 + m.y1 == m.q)
# INEQUALITY CONSTRAINTS
m.ineq1 = Constraint(expr=(-m.p, m.x1 + m.z1, exp(m.q)))
m.ineq2 = Constraint(expr=(0, m.x1 + m.x2, 10))
m.ineq3 = Constraint(expr=(2 * m.q, 2 * (m.z3 + m.y1), 2 * m.q))
m.ineq4 = Constraint(expr=-m.q <= m.y2**2 + m.nexpr)
# out of scope: deactivated
m.ineq5 = Constraint(expr=m.y3 <= m.q)
m.ineq5.deactivate()
# OBJECTIVE
# contains a rich combination of first-stage and second-stage terms
m.obj = Objective(
expr=(
m.p**2
+ 2 * m.p * m.q
+ log(m.x1)
+ 2 * m.p * m.x1
+ m.q**2 * m.x1
+ m.p**3 * (m.z1 + m.z2 + m.y1)
+ m.z4
+ m.z5
)
)
# inactive objective
m.inactive_obj = Objective(expr=1 + m.q2var + m.x1)
m.inactive_obj.deactivate()
# set up the var partitioning
user_var_partitioning = VariablePartitioning(
first_stage_variables=[m.x1, m.x2],
second_stage_variables=[m.z1, m.z2, m.z3, m.z4, m.z5],
# note: y3 out of scope, so excluded
state_variables=[m.y1, m.y2],
)
return model_data, user_var_partitioning
def test_setup_working_model(self):
"""
Test method for setting up the working model is as expected.
"""
model_data, user_var_partitioning = self.build_test_model_data()
om = model_data.original_model
config = model_data.config
config.uncertain_params = [om.q, om.q2var]
config.progress_logger = logger
config.nominal_uncertain_param_vals = [om.q.value, om.q2var.value]
setup_working_model(model_data, user_var_partitioning)
working_model = model_data.working_model
# active constraints
m = model_data.working_model.user_model
self.assertEqual(
ComponentSet(working_model.original_active_equality_cons),
ComponentSet([m.eq1, m.eq2, m.eq3, m.eq4]),
)
self.assertEqual(
ComponentSet(working_model.original_active_inequality_cons),
ComponentSet([m.ineq1, m.ineq2, m.ineq3, m.ineq4]),
)
# active objective
self.assertTrue(m.obj.active)
self.assertFalse(m.inactive_obj.active)
# user var partitioning
up = working_model.user_var_partitioning
self.assertEqual(
ComponentSet(up.first_stage_variables), ComponentSet([m.x1, m.x2])
)
self.assertEqual(
ComponentSet(up.second_stage_variables),
ComponentSet([m.z1, m.z2, m.z3, m.z4, m.z5]),
)
self.assertEqual(ComponentSet(up.state_variables), ComponentSet([m.y1, m.y2]))
# uncertain params
self.assertEqual(
ComponentSet(working_model.orig_uncertain_params),
ComponentSet([m.q, m.q2var]),
)
self.assertEqual(list(working_model.temp_uncertain_params.index_set()), [1])
temp_uncertain_param = working_model.temp_uncertain_params[1]
self.assertEqual(
ComponentSet(working_model.uncertain_params),
ComponentSet([m.q, temp_uncertain_param]),
)
# ensure original model unchanged
self.assertFalse(
hasattr(om, "util"), msg="Original model still has temporary util block"
)
# constraint partitioning initialization
self.assertFalse(working_model.first_stage.inequality_cons)
self.assertFalse(working_model.first_stage.equality_cons)
self.assertFalse(working_model.second_stage.inequality_cons)
self.assertFalse(working_model.second_stage.equality_cons)
# ensure uncertain Param substitutions carried out properly
ublk = model_data.working_model.user_model
self.assertExpressionsEqual(
ublk.nexpr.expr, log(ublk.y2) + temp_uncertain_param
)
self.assertExpressionsEqual(
ublk.inactive_obj.expr, LinearExpression([1, temp_uncertain_param, m.x1])
)
self.assertExpressionsEqual(ublk.ineq4.expr, -ublk.q <= ublk.y2**2 + ublk.nexpr)
# other component expressions should remain as declared
self.assertExpressionsEqual(ublk.eq1.expr, ublk.q * (ublk.z3 + ublk.x2) == 0)
self.assertExpressionsEqual(ublk.eq2.expr, ublk.x1 - ublk.z1 == 0)
self.assertExpressionsEqual(
ublk.eq3.expr, ublk.x1**2 + ublk.x2 + ublk.p * ublk.z2 == ublk.p
)
self.assertExpressionsEqual(ublk.eq4.expr, ublk.z3 + ublk.y1 == ublk.q)
self.assertExpressionsEqual(
ublk.ineq1.expr,
RangedExpression((-ublk.p, ublk.x1 + ublk.z1, exp(ublk.q)), False),
)
self.assertExpressionsEqual(
ublk.ineq2.expr, RangedExpression((0, ublk.x1 + ublk.x2, 10), False)
)
self.assertExpressionsEqual(
ublk.ineq3.expr,
RangedExpression((2 * ublk.q, 2 * (ublk.z3 + ublk.y1), 2 * ublk.q), False),
)
self.assertExpressionsEqual(ublk.ineq5.expr, ublk.y3 <= ublk.q)
self.assertExpressionsEqual(
ublk.obj.expr,
(
ublk.p**2
+ 2 * ublk.p * ublk.q
+ log(ublk.x1)
+ 2 * ublk.p * ublk.x1
+ ublk.q**2 * ublk.x1
+ ublk.p**3 * (ublk.z1 + ublk.z2 + ublk.y1)
+ ublk.z4
+ ublk.z5
),
)
class TestResolveVarBounds(unittest.TestCase):
"""
Tests for resolution of variable bounds.
"""
def test_resolve_var_bounds(self):
"""
Test resolve variable bounds.
"""
m = ConcreteModel()
m.q1 = Param(initialize=1, mutable=True)
m.q2 = Param(initialize=1, mutable=True)
m.p1 = Param(initialize=5, mutable=True)
m.p2 = Param(initialize=0, mutable=True)
m.z1 = Var(bounds=(0, 1))
m.z2 = Var(bounds=(1, 1))
m.z3 = Var(domain=NonNegativeReals, bounds=(2, 4))
m.z4 = Var(domain=NonNegativeReals, bounds=(m.q1, 0))
m.z5 = Var(domain=RangeSet(2, 4, 0), bounds=(4, 6))
m.z6 = Var(domain=NonNegativeReals, bounds=(m.q1, m.q1))
m.z7 = Var(domain=NonNegativeReals, bounds=(m.q1, 1 * m.q1))
m.z8 = Var(domain=RangeSet(0, 5, 0), bounds=[m.q1, m.q2])
m.z9 = Var(domain=RangeSet(0, 5, 0), bounds=[m.q1, m.p1])
m.z10 = Var(domain=RangeSet(0, 5, 0), bounds=[m.q1, m.p2])
# useful for checking domains later
original_var_domains = ComponentMap(
(
(var, var.domain)
for var in (m.z1, m.z2, m.z3, m.z4, m.z5, m.z6, m.z7, m.z8, m.z9, m.z10)
)
)
expected_bounds = (
(m.z1, (0, None, 1), (None, None, None)),
(m.z2, (None, 1, None), (None, None, None)),
(m.z3, (2, None, 4), (None, None, None)),
(m.z4, (None, 0, None), (m.q1, None, None)),
(m.z5, (None, 4, None), (None, None, None)),
(m.z6, (0, None, None), (None, m.q1, None)),
# the 1 * q expression is simplified to just q
# when variable bounds are specified
(m.z7, (0, None, None), (None, m.q1, None)),
(m.z8, (0, None, 5), (m.q1, None, m.q2)),
(m.z9, (0, None, m.p1), (m.q1, None, None)),
(m.z10, (0, None, m.p2), (m.q1, None, None)),
)
for var, exp_cert_bounds, exp_uncert_bounds in expected_bounds:
actual_cert_bounds, actual_uncert_bounds = get_var_certain_uncertain_bounds(
var, [m.q1, m.q2]
)
for btype, exp_bound in zip(("lower", "eq", "upper"), exp_cert_bounds):
actual_bound = getattr(actual_cert_bounds, btype)
self.assertIs(
exp_bound,
actual_bound,
msg=(
f"Resolved certain {btype} bound for variable "
f"{var.name!r} is not as expected. "
"\n Expected certain bounds: "
f"lower={str(exp_cert_bounds[0])}, "
f"eq={str(exp_cert_bounds[1])}, "
f"upper={str(exp_cert_bounds[2])} "
"\n Actual certain bounds: "
f"lower={str(actual_cert_bounds.lower)}, "
f"eq={str(actual_cert_bounds.eq)}, "
f"upper={str(actual_cert_bounds.upper)} "
),
)
for btype, exp_bound in zip(("lower", "eq", "upper"), exp_uncert_bounds):
actual_bound = getattr(actual_uncert_bounds, btype)
self.assertIs(
exp_bound,
actual_bound,
msg=(
f"Resolved uncertain {btype} bound for variable "
f"{var.name!r} is not as expected. "
"\n Expected uncertain bounds: "
f"lower={str(exp_uncert_bounds[0])}, "
f"eq={str(exp_uncert_bounds[1])}, "
f"upper={str(exp_uncert_bounds[2])} "
"\n Actual uncertain bounds: "
f"lower={str(actual_uncert_bounds.lower)}, "
f"eq={str(actual_uncert_bounds.eq)}, "
f"upper={str(actual_uncert_bounds.upper)} "
),
)
# the bounds resolution method should leave domains unaltered
for var, orig_domain in original_var_domains.items():
self.assertIs(
var.domain,
orig_domain,
msg=(
f"Domain for var {var.name!r} appears to have been changed "
f"from {orig_domain} to {var.domain} "
"by the bounds resolution method "
f"{get_var_certain_uncertain_bounds.__name__!r}."
),
)
class TestTurnVarBoundsToConstraints(unittest.TestCase):
"""
Tests for reformulating variable bounds to explicit
inequality/equality constraints.
"""
def build_simple_test_model_data(self):
"""
Build simple model data object for turning bounds
to constraints.
"""
model_data = Bunch()
model_data.config = Bunch()
model_data.working_model = ConcreteModel()
model_data.working_model.user_model = m = ConcreteModel()
m.q1 = Param(initialize=1, mutable=True)
m.q2 = Param(initialize=1, mutable=True)
m.p1 = Param(initialize=5, mutable=True)
m.p2 = Param(initialize=0, mutable=True)
m.z1 = Var(bounds=(None, None))
m.z2 = Var(bounds=(1, 1))
m.z3 = Var(domain=NonNegativeReals, bounds=(2, m.p1))
m.z4 = Var(domain=NonNegativeReals, bounds=(m.q1, 0))
m.z5 = Var(domain=RangeSet(2, 4, 0), bounds=(4, m.q2))
m.z6 = Var(domain=NonNegativeReals, bounds=(m.q1, m.q1))
m.z7 = Var(domain=NonPositiveReals, bounds=(m.q1, 1 * m.q1))
m.z8 = Var(domain=RangeSet(0, 5, 0), bounds=[m.q1, m.q2])
m.z9 = Var(domain=RangeSet(0, 5, 0), bounds=[m.q1, m.p1])
m.z10 = Var(domain=RangeSet(0, 5, 0), bounds=[m.q1, m.p2])
model_data.working_model.uncertain_params = [m.q1, m.q2, m.p1]
model_data.working_model.effective_uncertain_params = [m.q1, m.q2]
model_data.working_model.second_stage = Block()
model_data.working_model.second_stage.inequality_cons = Constraint(Any)
model_data.working_model.second_stage.equality_cons = Constraint(Any)
model_data.separation_priority_order = dict()
return model_data
def test_turn_nonadjustable_bounds_to_constraints(self):
"""
Test subroutine for reformulating bounds on nonadjustable
variables to constraints.
This subroutine should reformulate only the uncertain
declared bounds for the nonadjustable variables.
All other variable bounds should be left unchanged.
All variable domains should remain unchanged.
"""
model_data = self.build_simple_test_model_data()
working_model = model_data.working_model
m = model_data.working_model.user_model
# mock effective partitioning for testing
ep = model_data.working_model.effective_var_partitioning = Bunch()
ep.first_stage_variables = [m.z1, m.z2, m.z3, m.z4, m.z5, m.z6, m.z7, m.z8]
ep.second_stage_variables = [m.z9]
ep.state_variables = [m.z10]
effective_first_stage_var_set = ComponentSet(ep.first_stage_variables)
original_var_domains_and_bounds = ComponentMap(
(var, (var.domain, get_var_bound_pairs(var)[1]))
for var in model_data.working_model.user_model.component_data_objects(Var)
)
# expected final bounds and bound constraint types
expected_final_nonadj_var_bounds = ComponentMap(
(
(m.z1, (get_var_bound_pairs(m.z1)[1], [])),
(m.z2, (get_var_bound_pairs(m.z2)[1], [])),
(m.z3, (get_var_bound_pairs(m.z3)[1], [])),
(m.z4, ((None, 0), ["lower"])),
(m.z5, ((4, None), ["upper"])),
(m.z6, ((None, None), ["eq"])),
(m.z7, ((None, None), ["eq"])),
(m.z8, ((None, None), ["lower", "upper"])),
)
)
turn_nonadjustable_var_bounds_to_constraints(model_data)
for var, (orig_domain, orig_bounds) in original_var_domains_and_bounds.items():
# all var domains should remain unchanged
self.assertIs(
var.domain,
orig_domain,
msg=(
f"Domain of variable {var.name!r} was changed from "
f"{orig_domain} to {var.domain} by "
f"{turn_nonadjustable_var_bounds_to_constraints.__name__!r}. "
),
)
_, (final_lb, final_ub) = get_var_bound_pairs(var)
if var not in effective_first_stage_var_set:
# these are the adjustable variables.
# bounds should not have been changed
self.assertIs(
orig_bounds[0],
final_lb,
msg=(
f"Lower bound for adjustable variable {var.name!r} appears to "
f"have been changed from {orig_bounds[0]} to {final_lb}."
),
)
self.assertIs(
orig_bounds[1],
final_ub,
msg=(
f"Upper bound for adjustable variable {var.name!r} appears to "
f"have been changed from {orig_bounds[1]} to {final_ub}."
),
)
else:
# these are the nonadjustable variables.
# only the uncertain bounds should have been
# changed, and accompanying constraints added
expected_bounds, con_bound_types = expected_final_nonadj_var_bounds[var]
expected_lb, expected_ub = expected_bounds
self.assertIs(
expected_lb,
final_lb,
msg=(
f"Lower bound for nonadjustable variable {var.name!r} "
f"should be {expected_lb}, but was "
f"found to be {final_lb}."
),
)
self.assertIs(
expected_ub,
final_ub,
msg=(
f"Upper bound for nonadjustable variable {var.name!r} "
f"should be {expected_ub}, but was "
f"found to be {final_ub}."
),
)
second_stage = working_model.second_stage
# verify bound constraint expressions
assertExpressionsEqual(
self,
second_stage.inequality_cons["var_z4_uncertain_lower_bound_con"].expr,
-m.z4 <= -m.q1,
)
assertExpressionsEqual(
self,
second_stage.inequality_cons["var_z5_uncertain_upper_bound_con"].expr,
m.z5 <= m.q2,
)
assertExpressionsEqual(
self,
second_stage.equality_cons["var_z6_uncertain_eq_bound_con"].expr,
m.z6 == m.q1,
)
assertExpressionsEqual(
self,
second_stage.equality_cons["var_z7_uncertain_eq_bound_con"].expr,
m.z7 == m.q1,
)
assertExpressionsEqual(
self,
second_stage.inequality_cons["var_z8_uncertain_lower_bound_con"].expr,
-m.z8 <= -m.q1,
)
assertExpressionsEqual(
self,
second_stage.inequality_cons["var_z8_uncertain_upper_bound_con"].expr,
m.z8 <= m.q2,
)
# check constraint partitioning
self.assertEqual(
len(working_model.second_stage.inequality_cons),
4,
msg="Number of second-stage inequalities not as expected.",
)
self.assertEqual(
len(working_model.second_stage.equality_cons),
2,
msg="Number of second-stage equalities not as expected.",
)
# check separation priorities
for con_name in second_stage.inequality_cons:
self.assertEqual(
model_data.separation_priority_order[con_name],
0,
msg=(
f"Separation priority for entry {con_name!r} of second-stage "
"inequalities not as expected."
),
)
def test_turn_adjustable_bounds_to_constraints(self):
"""
Test subroutine for reformulating domains and bounds
on adjustable variables to constraints.
This subroutine should reformulate the domain and
declared bounds for every adjustable
(i.e. effective second-stage and effective state)
variable.
The domains and bounds for all other variables
should be left unchanged.
"""
model_data = self.build_simple_test_model_data()
m = model_data.working_model.user_model
# simple mock partitioning for the test
ep = model_data.working_model.effective_var_partitioning = Bunch()
ep.first_stage_variables = [m.z9, m.z10]
ep.second_stage_variables = [m.z1, m.z2, m.z3, m.z4, m.z5, m.z6]
ep.state_variables = [m.z7, m.z8]
effective_first_stage_var_set = ComponentSet(ep.first_stage_variables)
original_var_domains_and_bounds = ComponentMap(
(var, (var.domain, get_var_bound_pairs(var)[1]))
for var in model_data.working_model.user_model.component_data_objects(Var)
)
turn_adjustable_var_bounds_to_constraints(model_data)
for var, (orig_domain, orig_bounds) in original_var_domains_and_bounds.items():
_, (final_lb, final_ub) = get_var_bound_pairs(var)
if var not in effective_first_stage_var_set:
# these are the adjustable variables.
# domains should have been removed,
# i.e. changed to reals.
# bounds should also have been removed
self.assertIs(
var.domain,
Reals,
msg=(
f"Domain of adjustable variable {var.name!r} "
"should now be Reals, but was instead found to be "
f"{var.domain}"
),
)
self.assertIsNone(
final_lb,
msg=(
f"Declared lower bound for adjustable variable {var.name!r} "
"should now be None, as all adjustable variable bounds "
"should have been removed, but was instead found to be"
f"{final_lb}."
),
)
self.assertIsNone(
final_ub,
msg=(
f"Declared upper bound for adjustable variable {var.name!r} "
"should now be None, as all adjustable variable bounds "
"should have been removed, but was instead found to be"
f"{final_ub}."
),
)
else:
# these are the nonadjustable variables.
# domains and bounds should be left unchanged
self.assertIs(
var.domain,
orig_domain,
msg=(
f"Domain of adjustable variable {var.name!r} "
"should now be Reals, but was instead found to be "
f"{var.domain}"
),
)
self.assertIs(
orig_bounds[0],
final_lb,
msg=(
f"Lower bound for nonadjustable variable {var.name!r} "
"appears to "
f"have been changed from {orig_bounds[0]} to {final_lb}."
),
)
self.assertIs(
orig_bounds[1],
final_ub,
msg=(
f"Upper bound for nonadjustable variable {var.name!r} "
"appears to "
f"have been changed from {orig_bounds[1]} to {final_ub}."
),
)
second_stage = model_data.working_model.second_stage
self.assertEqual(len(second_stage.inequality_cons), 10)
self.assertEqual(len(second_stage.equality_cons), 5)
# verify bound constraint expressions
assertExpressionsEqual(
self,
second_stage.equality_cons["var_z2_certain_eq_bound_con"].expr,
m.z2 == 1,
)
assertExpressionsEqual(
self,
second_stage.inequality_cons["var_z3_certain_lower_bound_con"].expr,
-m.z3 <= -2,
)
assertExpressionsEqual(
self,
second_stage.inequality_cons["var_z3_certain_upper_bound_con"].expr,
m.z3 <= m.p1,
)
assertExpressionsEqual(
self,
second_stage.equality_cons["var_z4_certain_eq_bound_con"].expr,
m.z4 == 0,
)
assertExpressionsEqual(
self,
second_stage.inequality_cons["var_z4_uncertain_lower_bound_con"].expr,
-m.z4 <= -m.q1,
)
assertExpressionsEqual(
self,
second_stage.equality_cons["var_z5_certain_eq_bound_con"].expr,
m.z5 == 4,
)
assertExpressionsEqual(
self,
second_stage.inequality_cons["var_z5_uncertain_upper_bound_con"].expr,
m.z5 <= m.q2,
)
assertExpressionsEqual(
self,
second_stage.inequality_cons["var_z6_certain_lower_bound_con"].expr,
-m.z6 <= 0,
)
assertExpressionsEqual(
self,
second_stage.equality_cons["var_z6_uncertain_eq_bound_con"].expr,
m.z6 == m.q1,
)
assertExpressionsEqual(
self,
second_stage.inequality_cons["var_z7_certain_upper_bound_con"].expr,
m.z7 <= 0,
)
assertExpressionsEqual(
self,
second_stage.equality_cons["var_z7_uncertain_eq_bound_con"].expr,
m.z7 == m.q1,
)
assertExpressionsEqual(
self,
second_stage.inequality_cons["var_z8_certain_lower_bound_con"].expr,
-m.z8 <= 0,
)
assertExpressionsEqual(
self,
second_stage.inequality_cons["var_z8_certain_upper_bound_con"].expr,
m.z8 <= 5,
)
assertExpressionsEqual(
self,
second_stage.inequality_cons["var_z8_uncertain_lower_bound_con"].expr,