forked from Pyomo/pyomo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_gdpopt.py
More file actions
1827 lines (1664 loc) · 73 KB
/
Copy pathtest_gdpopt.py
File metadata and controls
1827 lines (1664 loc) · 73 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
# ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 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 GDPopt solver plugin."""
from contextlib import redirect_stdout
from io import StringIO
import logging
from math import fabs
from os.path import join, normpath
import pyomo.common.unittest as unittest
from pyomo.common.log import LoggingIntercept
from pyomo.common.collections import Bunch
from pyomo.common.config import ConfigDict, ConfigValue
from pyomo.common.fileutils import import_file, PYOMO_ROOT_DIR
from pyomo.contrib.gdpopt.create_oa_subproblems import (
add_util_block,
add_disjunct_list,
add_constraints_by_disjunct,
add_global_constraint_list,
)
import pyomo.contrib.gdpopt.tests.common_tests as ct
from pyomo.contrib.gdpopt.util import is_feasible, time_code
from pyomo.contrib.mcpp.pyomo_mcpp import mcpp_available
from pyomo.contrib.gdpopt.solve_discrete_problem import (
solve_MILP_discrete_problem,
distinguish_mip_infeasible_or_unbounded,
)
from pyomo.environ import (
Block,
ConcreteModel,
Constraint,
Integers,
LogicalConstraint,
maximize,
minimize,
Objective,
RangeSet,
TransformationFactory,
SolverFactory,
sqrt,
value,
Var,
)
from pyomo.gdp import Disjunct, Disjunction
from pyomo.gdp.tests import models
from pyomo.opt import TerminationCondition
exdir = normpath(join(PYOMO_ROOT_DIR, 'examples', 'gdp'))
mip_solver = 'glpk'
nlp_solver = 'ipopt'
global_nlp_solver = 'baron'
global_nlp_solver_args = dict()
minlp_solver = 'baron'
LOA_solvers = (mip_solver, nlp_solver)
GLOA_solvers = (mip_solver, global_nlp_solver, minlp_solver)
LOA_solvers_available = all(SolverFactory(s).available() for s in LOA_solvers)
GLOA_solvers_available = all(SolverFactory(s).available() for s in GLOA_solvers)
license_available = (
SolverFactory(global_nlp_solver).license_is_valid()
if GLOA_solvers_available
else False
)
gurobi_available = (
SolverFactory('gurobi').available(exception_flag=False)
and SolverFactory('gurobi').license_is_valid()
)
class TestGDPoptUnit(unittest.TestCase):
"""Real unit tests for GDPopt"""
@unittest.skipUnless(
SolverFactory(mip_solver).available(), "MIP solver not available"
)
def test_solve_discrete_problem_unbounded(self):
m = ConcreteModel()
m.GDPopt_utils = Block()
m.x = Var(bounds=(-1, 10))
m.y = Var(bounds=(2, 3))
m.z = Var()
# Include a disjunction so that we don't default to just a MIP solver
m.d = Disjunction(expr=[[m.x + m.y >= 5], [m.x - m.y <= 3]])
m.o = Objective(expr=m.z)
m.GDPopt_utils.variable_list = [m.x, m.y, m.z]
m.GDPopt_utils.disjunct_list = [m.d._autodisjuncts[0], m.d._autodisjuncts[1]]
TransformationFactory('gdp.bigm').apply_to(m)
output = StringIO()
with LoggingIntercept(output, 'pyomo.contrib.gdpopt', logging.WARNING):
solver = SolverFactory('gdpopt.loa')
dummy = Block()
dummy.timing = Bunch()
with time_code(dummy.timing, 'main', is_main_timer=True):
tc = solve_MILP_discrete_problem(
m.GDPopt_utils, dummy, solver.CONFIG(dict(mip_solver=mip_solver))
)
self.assertIn(
"Discrete problem was unbounded. Re-solving with "
"arbitrary bound values",
output.getvalue().strip(),
)
self.assertIs(tc, TerminationCondition.unbounded)
@unittest.skipUnless(
SolverFactory(mip_solver).available(), "MIP solver not available"
)
def test_solve_lp(self):
m = ConcreteModel()
m.x = Var(bounds=(-5, 5))
m.c = Constraint(expr=m.x >= 1)
m.o = Objective(expr=m.x)
output = StringIO()
with LoggingIntercept(output, 'pyomo.contrib.gdpopt', logging.INFO):
results = SolverFactory('gdpopt.loa').solve(m, mip_solver=mip_solver)
self.assertIn(
"Your model is an LP (linear program).", output.getvalue().strip()
)
self.assertAlmostEqual(value(m.o.expr), 1)
self.assertEqual(results.problem.number_of_binary_variables, 0)
self.assertEqual(results.problem.number_of_integer_variables, 0)
self.assertEqual(results.problem.number_of_disjunctions, 0)
self.assertAlmostEqual(results.problem.lower_bound, 1)
self.assertAlmostEqual(results.problem.upper_bound, 1)
@unittest.skipUnless(gurobi_available, 'Gurobi not available')
def test_solve_nlp(self):
m = ConcreteModel()
m.x = Var(bounds=(-5, 5))
m.c = Constraint(expr=m.x >= 1)
m.o = Objective(expr=m.x**2)
output = StringIO()
with LoggingIntercept(output, 'pyomo.contrib.gdpopt', logging.INFO):
results = SolverFactory('gdpopt.loa').solve(m, nlp_solver='gurobi')
self.assertIn(
"Your model is an NLP (nonlinear program).", output.getvalue().strip()
)
self.assertAlmostEqual(value(m.o.expr), 1)
self.assertEqual(results.problem.number_of_binary_variables, 0)
self.assertEqual(results.problem.number_of_integer_variables, 0)
self.assertEqual(results.problem.number_of_disjunctions, 0)
self.assertAlmostEqual(results.problem.lower_bound, 1)
self.assertAlmostEqual(results.problem.upper_bound, 1)
@unittest.skipUnless(
SolverFactory(mip_solver).available(), "MIP solver not available"
)
def test_solve_constant_obj(self):
m = ConcreteModel()
m.x = Var(bounds=(-5, 5))
m.c = Constraint(expr=m.x >= 1)
m.o = Objective(expr=1)
output = StringIO()
with LoggingIntercept(output, 'pyomo.contrib.gdpopt', logging.INFO):
SolverFactory('gdpopt.loa').solve(m, mip_solver=mip_solver)
self.assertIn(
"Your model is an LP (linear program).", output.getvalue().strip()
)
self.assertAlmostEqual(value(m.o.expr), 1)
@unittest.skipUnless(
SolverFactory(nlp_solver).available(), 'NLP solver not available'
)
def test_no_objective(self):
m = ConcreteModel()
m.x = Var(bounds=(-5, 5))
m.c = Constraint(expr=m.x**2 >= 1)
output = StringIO()
with LoggingIntercept(output, 'pyomo.contrib.gdpopt', logging.WARNING):
SolverFactory('gdpopt.loa').solve(m, nlp_solver=nlp_solver)
self.assertIn(
"Model has no active objectives. Adding dummy objective.",
output.getvalue().strip(),
)
# check that the dummy objective is removed after the solve (else
# repeated solves result in the error about multiple active objectives
# on the model)
self.assertIsNone(m.component("dummy_obj"))
def test_multiple_objectives(self):
m = ConcreteModel()
m.x = Var()
m.o = Objective(expr=m.x)
m.o2 = Objective(expr=m.x + 1)
with self.assertRaisesRegex(ValueError, "Model has multiple active objectives"):
SolverFactory('gdpopt.loa').solve(m)
def test_is_feasible_function(self):
m = ConcreteModel()
m.x = Var(bounds=(0, 3), initialize=2)
m.c = Constraint(expr=m.x == 2)
GDP_LOA_Solver = SolverFactory('gdpopt.loa')
self.assertTrue(is_feasible(m, GDP_LOA_Solver.CONFIG()))
m.c2 = Constraint(expr=m.x <= 1)
self.assertFalse(is_feasible(m, GDP_LOA_Solver.CONFIG()))
m = ConcreteModel()
m.x = Var(bounds=(0, 3), initialize=2)
m.c = Constraint(expr=m.x >= 5)
self.assertFalse(is_feasible(m, GDP_LOA_Solver.CONFIG()))
m = ConcreteModel()
m.x = Var(bounds=(3, 3), initialize=2)
self.assertFalse(is_feasible(m, GDP_LOA_Solver.CONFIG()))
m = ConcreteModel()
m.x = Var(bounds=(0, 1), initialize=2)
self.assertFalse(is_feasible(m, GDP_LOA_Solver.CONFIG()))
m = ConcreteModel()
m.x = Var(bounds=(0, 1), initialize=2)
m.d = Disjunct()
with self.assertRaisesRegex(NotImplementedError, "Found active disjunct"):
is_feasible(m, GDP_LOA_Solver.CONFIG())
@unittest.skipUnless(gurobi_available, 'Gurobi not available')
def test_infeasible_or_unbounded_mip_termination(self):
m = ConcreteModel()
m.x = Var()
m.c1 = Constraint(expr=m.x >= 2)
m.c2 = Constraint(expr=m.x <= 1.9)
m.obj = Objective(expr=m.x)
results = SolverFactory('gurobi').solve(m)
# Gurobi shrugs:
self.assertEqual(
results.solver.termination_condition,
TerminationCondition.infeasibleOrUnbounded,
)
# just pretend on the config block--we only need these two:
config = ConfigDict()
config.declare('mip_solver', ConfigValue('gurobi'))
config.declare('mip_solver_args', ConfigValue({}))
# We tell Gurobi to figure it out
results, termination_condition = distinguish_mip_infeasible_or_unbounded(
m, config
)
# It's infeasible:
self.assertEqual(termination_condition, TerminationCondition.infeasible)
self.assertEqual(
results.solver.termination_condition, TerminationCondition.infeasible
)
def get_GDP_on_block(self):
m = ConcreteModel()
m.x = Var(bounds=(-5, 5))
m.y = Var(bounds=(-2, 6))
m.b = Block()
m.b.disjunction = Disjunction(
expr=[
[m.x + m.y <= 1, m.y >= 0.5],
[m.x == 2, m.y == 4],
[m.x**2 - m.y <= 3],
]
)
m.disjunction = Disjunction(
expr=[
[m.x - m.y <= -2, m.y >= -1],
[m.x == 0, m.y >= 0],
[m.y**2 + m.x <= 3],
]
)
return m
def test_gloa_cut_generation_ignores_deactivated_constraints(self):
m = self.get_GDP_on_block()
m.b.disjunction.disjuncts[0].indicator_var.fix(True)
m.b.disjunction.disjuncts[1].indicator_var.fix(False)
m.b.disjunction.disjuncts[2].indicator_var.fix(False)
m.b.deactivate()
m.disjunction.disjuncts[0].indicator_var.fix(False)
m.disjunction.disjuncts[1].indicator_var.fix(True)
m.disjunction.disjuncts[2].indicator_var.fix(False)
# set up the util block
add_util_block(m)
util_block = m._gdpopt_cuts
add_disjunct_list(util_block)
add_constraints_by_disjunct(util_block)
add_global_constraint_list(util_block)
TransformationFactory('gdp.bigm').apply_to(m)
config = ConfigDict()
config.declare('integer_tolerance', ConfigValue(1e-6))
gloa = SolverFactory('gdpopt.gloa')
constraints = list(
gloa._get_active_untransformed_constraints(util_block, config)
)
self.assertEqual(len(constraints), 2)
c1 = constraints[0]
c2 = constraints[1]
self.assertIs(c1.body, m.x)
self.assertEqual(c1.lower, 0)
self.assertEqual(c1.upper, 0)
self.assertIs(c2.body, m.y)
self.assertEqual(c2.lower, 0)
self.assertIsNone(c2.upper)
def test_complain_when_no_algorithm_specified(self):
m = self.get_GDP_on_block()
with self.assertRaisesRegex(
ValueError,
"No algorithm was specified to the solve method. "
"Please specify an algorithm or use an "
"algorithm-specific solver.",
):
SolverFactory('gdpopt').solve(m)
def test_loa_augmented_penalty_objective_preserves_objective_sense(self):
for sense in (minimize, maximize):
m = ConcreteModel()
m.GDPopt_utils = Block()
m.x = Var(bounds=(0, 1))
m.obj = Objective(expr=m.x, sense=sense)
solver = SolverFactory('gdpopt.loa')
original_obj = solver._setup_augmented_penalty_objective(m.GDPopt_utils)
self.assertIs(original_obj, m.obj)
self.assertFalse(m.obj.active)
self.assertEqual(m.GDPopt_utils.oa_obj.sense, sense)
@unittest.skipUnless(
SolverFactory(mip_solver).available(), "MIP solver not available"
)
def test_LOA_maximize_matches_minimize_negated_objective(self):
def build_model(maximize_objective):
m = ConcreteModel()
m.x = Var(bounds=(0, 10))
m.disjunction = Disjunction(expr=[[m.x == 1], [m.x == 9]])
if maximize_objective:
m.obj = Objective(expr=m.x, sense=maximize)
else:
m.obj = Objective(expr=-m.x)
return m
for maximize_objective in (False, True):
m = build_model(maximize_objective)
results = SolverFactory('gdpopt.loa').solve(
m,
mip_solver=mip_solver,
nlp_solver=nlp_solver,
init_algorithm='no_init',
)
self.assertEqual(
results.solver.termination_condition, TerminationCondition.optimal
)
self.assertAlmostEqual(value(m.x), 9)
@unittest.skipIf(
not LOA_solvers_available,
"Required subsolvers %s are not available" % (LOA_solvers,),
)
def test_solve_block(self):
m = ConcreteModel()
m.b = Block()
m.b.x = Var(bounds=(-5, 5))
m.b.y = Var(bounds=(-2, 6))
m.b.disjunction = Disjunction(
expr=[
[m.b.x + m.b.y <= 1, m.b.y >= 0.5],
[m.b.x == 2, m.b.y == 4],
[m.b.x**2 - m.b.y <= 3],
]
)
m.disjunction = Disjunction(
expr=[
[m.b.x - m.b.y <= -2, m.b.y >= -1],
[m.b.x == 0, m.b.y >= 0],
[m.b.y**2 + m.b.x <= 3],
]
)
m.b.obj = Objective(expr=m.b.x)
SolverFactory('gdpopt.ric').solve(
m.b, mip_solver=mip_solver, nlp_solver=nlp_solver
)
# There are multiple optimal solutions, so just leave it at this:
self.assertAlmostEqual(value(m.b.x), -5)
# We didn't declare any Block on m--it's still just b.
self.assertEqual(len(m.component_map(Block)), 1)
@unittest.skipIf(
not LOA_solvers_available,
"Required subsolvers %s are not available" % (LOA_solvers,),
)
class TestGDPopt(unittest.TestCase):
"""Tests for the GDPopt solver plugin."""
def test_infeasible_GDP(self):
"""Test for infeasible GDP."""
m = models.make_infeasible_gdp_model()
output = StringIO()
with LoggingIntercept(output, 'pyomo.contrib.gdpopt', logging.WARNING):
results = SolverFactory('gdpopt.loa').solve(
m, mip_solver=mip_solver, nlp_solver=nlp_solver
)
self.assertIn(
"Set covering problem is infeasible.", output.getvalue().strip()
)
self.assertEqual(
results.solver.termination_condition, TerminationCondition.infeasible
)
self.assertIsNone(m.x.value)
self.assertIsNone(m.d.disjuncts[0].indicator_var.value)
self.assertIsNone(m.d.disjuncts[1].indicator_var.value)
# Test maximization problem infeasibility also
m.o.sense = maximize
output = StringIO()
with LoggingIntercept(output, 'pyomo.contrib.gdpopt', logging.INFO):
results = SolverFactory('gdpopt').solve(
m,
mip_solver=mip_solver,
nlp_solver=nlp_solver,
init_algorithm='no_init',
algorithm='LOA',
)
self.assertIn(
"GDPopt exiting--problem is infeasible.", output.getvalue().strip()
)
self.assertEqual(
results.solver.termination_condition, TerminationCondition.infeasible
)
self.assertIsNotNone(results.solver.user_time)
self.assertIsNone(m.x.value)
self.assertIsNone(m.d.disjuncts[0].indicator_var.value)
self.assertIsNone(m.d.disjuncts[1].indicator_var.value)
def test_infeasible_gdp_max_binary(self):
"""Test that max binary initialization catches infeasible GDP too"""
m = models.make_infeasible_gdp_model()
output = StringIO()
with LoggingIntercept(output, 'pyomo.contrib.gdpopt', logging.DEBUG):
results = SolverFactory('gdpopt.loa').solve(
m,
mip_solver=mip_solver,
nlp_solver=nlp_solver,
init_algorithm='max_binary',
)
self.assertIn(
"MILP relaxation for initialization was infeasible. "
"Problem is infeasible.",
output.getvalue().strip(),
)
self.assertEqual(
results.solver.termination_condition, TerminationCondition.infeasible
)
def test_unbounded_gdp_minimization(self):
m = ConcreteModel()
m.GDPopt_utils = Block()
m.x = Var(bounds=(-1, 10))
m.y = Var(bounds=(2, 3))
m.z = Var()
m.d = Disjunction(expr=[[m.x + m.y >= 5], [m.x - m.y <= 3]])
m.o = Objective(expr=m.z)
m.GDPopt_utils.variable_list = [m.x, m.y, m.z]
m.GDPopt_utils.disjunct_list = [m.d._autodisjuncts[0], m.d._autodisjuncts[1]]
results = SolverFactory('gdpopt.loa').solve(
m, mip_solver=mip_solver, nlp_solver=nlp_solver
)
self.assertEqual(
results.solver.termination_condition, TerminationCondition.unbounded
)
def test_unbounded_gdp_maximization(self):
m = ConcreteModel()
m.GDPopt_utils = Block()
m.x = Var(bounds=(-1, 10))
m.y = Var(bounds=(2, 3))
m.z = Var()
m.d = Disjunction(expr=[[m.x + m.y <= 5], [m.x - m.y >= 3]])
m.o = Objective(expr=m.z, sense=maximize)
m.GDPopt_utils.variable_list = [m.x, m.y, m.z]
m.GDPopt_utils.disjunct_list = [m.d._autodisjuncts[0], m.d._autodisjuncts[1]]
results = SolverFactory('gdpopt.loa').solve(
m, mip_solver=mip_solver, nlp_solver=nlp_solver
)
self.assertEqual(
results.solver.termination_condition, TerminationCondition.unbounded
)
# [ESJ 5/16/22]: Using Gurobi for this test because glpk seems to get angry
# on Windows when the MIP is arbitrarily bounded with the large bounds. And
# I think I blame glpk...
@unittest.skipUnless(gurobi_available, "Gurobi solver not available")
def test_GDP_nonlinear_objective(self):
m = ConcreteModel()
m.x = Var(bounds=(-1, 10))
m.y = Var(bounds=(2, 3))
m.d = Disjunction(expr=[[m.x + m.y >= 5], [m.x - m.y <= 3]])
m.o = Objective(expr=m.x**2)
SolverFactory('gdpopt.loa').solve(m, mip_solver='gurobi', nlp_solver=nlp_solver)
self.assertAlmostEqual(value(m.o), 0)
m = ConcreteModel()
m.x = Var(bounds=(-1, 10))
m.y = Var(bounds=(2, 3))
m.d = Disjunction(expr=[[m.x + m.y >= 5], [m.x - m.y <= 3]])
m.o = Objective(expr=-m.x**2, sense=maximize)
print("second")
SolverFactory('gdpopt.loa').solve(m, mip_solver='gurobi', nlp_solver=nlp_solver)
self.assertAlmostEqual(value(m.o), 0)
def test_nested_disjunctions_set_covering(self):
# This test triggers the InfeasibleConstraintException in
# deactivate_trivial_constraints in one of the subproblem solves during
# initialization. This makes sure we get the correct answer anyway, as
# there is a feasible solution.
m = models.makeNestedNonlinearModel()
SolverFactory('gdpopt.loa').solve(
m,
mip_solver=mip_solver,
nlp_solver=nlp_solver,
init_algorithm='set_covering',
)
self.assertAlmostEqual(value(m.x), sqrt(2) / 2)
self.assertAlmostEqual(value(m.y), sqrt(2) / 2)
self.assertTrue(value(m.disj.disjuncts[1].indicator_var))
self.assertFalse(value(m.disj.disjuncts[0].indicator_var))
self.assertTrue(value(m.d1.indicator_var))
self.assertFalse(value(m.d2.indicator_var))
def test_equality_propagation_infeasibility_in_subproblems(self):
m = ConcreteModel()
m.x = Var(bounds=(-10, 10))
m.y = Var(bounds=(-10, 10))
m.disj = Disjunction(
expr=[[m.x == m.y, m.y == 2], [m.y == 8], [m.x + m.y >= 4, m.y == m.x + 1]]
)
m.cons = Constraint(expr=m.x == 3)
m.obj = Objective(expr=m.x + m.y)
SolverFactory('gdpopt').solve(
m,
mip_solver=mip_solver,
nlp_solver=nlp_solver,
init_algorithm='set_covering',
algorithm='RIC',
)
self.assertAlmostEqual(value(m.x), 3)
self.assertAlmostEqual(value(m.y), 4)
self.assertFalse(value(m.disj.disjuncts[0].indicator_var))
self.assertFalse(value(m.disj.disjuncts[1].indicator_var))
self.assertTrue(value(m.disj.disjuncts[2].indicator_var))
def test_bound_infeasibility_in_subproblems(self):
m = ConcreteModel()
m.x = Var(bounds=(2, 4))
m.y = Var(bounds=(5, 10))
m.disj = Disjunction(expr=[[m.x == m.y, m.x + m.y >= 8], [m.x == 4]])
m.obj = Objective(expr=m.x + m.y)
SolverFactory('gdpopt.ric').solve(
m,
mip_solver=mip_solver,
nlp_solver=nlp_solver,
init_algorithm='set_covering',
tee=True,
)
self.assertAlmostEqual(value(m.x), 4)
self.assertAlmostEqual(value(m.y), 5)
self.assertFalse(value(m.disj.disjuncts[0].indicator_var))
self.assertTrue(value(m.disj.disjuncts[1].indicator_var))
def test_subproblem_preprocessing_encounters_trivial_constraints(self):
m = ConcreteModel()
m.x = Var(bounds=(0, 10))
m.z = Var(bounds=(-10, 10))
m.disjunction = Disjunction(expr=[[m.x == 0, m.z >= 4], [m.x + m.z <= 0]])
m.cons = Constraint(expr=m.x * m.z <= 0)
m.obj = Objective(expr=-m.z)
m.disjunction.disjuncts[0].indicator_var.fix(True)
m.disjunction.disjuncts[1].indicator_var.fix(False)
SolverFactory('gdpopt.ric').solve(
m,
mip_solver=mip_solver,
nlp_solver=nlp_solver,
init_algorithm='fix_disjuncts',
)
# The real test is that this doesn't throw an error when we preprocess
# to solve the first subproblem (in the initialization). The nonlinear
# constraint becomes trivial, which we need to make sure is handled
# correctly.
self.assertEqual(value(m.x), 0)
self.assertEqual(value(m.z), 10)
self.assertTrue(value(m.disjunction.disjuncts[0].indicator_var))
self.assertFalse(value(m.disjunction.disjuncts[1].indicator_var))
def make_convex_circle_and_circle_slice_disjunction(self):
m = ConcreteModel()
# x will only appear in nonlinear expressions
m.x = Var(bounds=(-10, 18))
m.y = Var(bounds=(0, 7))
m.obj = Objective(expr=m.x**2 + m.y)
m.disjunction = Disjunction(
expr=[
[m.x**2 + m.y**2 <= 3, m.y >= 1],
(m.x - 3) ** 2 + (m.y - 2) ** 2 <= 1,
]
)
return m
def test_some_vars_only_in_subproblem(self):
# Even variables that only appear in nonlinear constraints will be
# introduced to the discrete problem via the cuts, so we check that
# that works out.
m = self.make_convex_circle_and_circle_slice_disjunction()
results = SolverFactory('gdpopt.loa').solve(
m, mip_solver=mip_solver, nlp_solver=nlp_solver
)
self.assertEqual(
results.solver.termination_condition, TerminationCondition.optimal
)
self.assertAlmostEqual(results.problem.upper_bound, 1)
self.assertAlmostEqual(value(m.x), 0)
self.assertAlmostEqual(value(m.y), 1)
def test_fixed_vars_honored(self):
# Make sure that the algorithm doesn't stomp on user-fixed variables
m = self.make_convex_circle_and_circle_slice_disjunction()
# first, force ourselves into the suboptimal disjunct
m.disjunction.disjuncts[0].indicator_var.fix(False)
SolverFactory('gdpopt.loa').solve(
m, mip_solver=mip_solver, nlp_solver=nlp_solver
)
self.assertTrue(value(m.disjunction.disjuncts[1].indicator_var))
self.assertFalse(value(m.disjunction.disjuncts[0].indicator_var))
self.assertTrue(m.disjunction.disjuncts[0].indicator_var.fixed)
self.assertAlmostEqual(value(m.x), 2.029, places=3)
self.assertAlmostEqual(value(m.y), 1.761, places=3)
self.assertAlmostEqual(value(m.obj), 5.878, places=3)
# Now, do it by fixing a continuous variable
m.disjunction.disjuncts[0].indicator_var.fixed = False
m.x.fix(3)
SolverFactory('gdpopt.loa').solve(
m, mip_solver=mip_solver, nlp_solver=nlp_solver
)
self.assertTrue(value(m.disjunction.disjuncts[1].indicator_var))
self.assertFalse(value(m.disjunction.disjuncts[0].indicator_var))
self.assertEqual(value(m.x), 3)
self.assertTrue(m.x.fixed)
self.assertAlmostEqual(value(m.y), 1)
self.assertAlmostEqual(value(m.obj), 10)
def test_ignore_set_for_oa_cuts(self):
m = self.make_convex_circle_and_circle_slice_disjunction()
m.disjunction.disjuncts[1].GDPopt_ignore_OA = [
m.disjunction.disjuncts[1].constraint[1]
]
output = StringIO()
with LoggingIntercept(output, 'pyomo.contrib.gdpopt', logging.DEBUG):
SolverFactory('gdpopt.loa').solve(
m, mip_solver=mip_solver, nlp_solver=nlp_solver
)
self.assertIn(
'OA cut addition for '
'disjunction_disjuncts[1].constraint[1] skipped '
'because it is in the ignore set.',
output.getvalue().strip(),
)
# and the solution is optimal
self.assertAlmostEqual(value(m.x), 0)
self.assertAlmostEqual(value(m.y), 1)
def test_reverse_numeric_differentiation_in_LOA(self):
# Having more than 1000 variables in the same constraint expression will
# trigger reverse numeric differentiation. We make sure that works with
# a disjunction between a pair of hyperspheres in 1300-dimensional
# space.
m = ConcreteModel()
m.s = RangeSet(1300)
m.x = Var(m.s, bounds=(-10, 10))
m.d1 = Disjunct()
m.d1.hypersphere = Constraint(expr=sum(m.x[i] ** 2 for i in m.s) <= 1)
m.d2 = Disjunct()
m.d2.translated_hyper_sphere = Constraint(
expr=sum((m.x[i] - i) ** 2 for i in m.s) <= 1
)
m.disjunction = Disjunction(expr=[m.d1, m.d2])
# we'll go in the sphere centered at (0,0,...,0)
m.obj = Objective(expr=sum(m.x[i] for i in m.s))
results = SolverFactory('gdpopt.loa').solve(
m, mip_solver=mip_solver, nlp_solver=nlp_solver
)
self.assertEqual(
results.solver.termination_condition, TerminationCondition.optimal
)
self.assertTrue(value(m.d1.indicator_var))
self.assertFalse(value(m.d2.indicator_var))
x_val = -sqrt(1300) / 1300
for x in m.x.values():
self.assertAlmostEqual(value(x), x_val)
self.assertAlmostEqual(results.problem.upper_bound, 1300 * x_val, places=6)
def test_logical_constraints_on_disjuncts(self):
m = models.makeLogicalConstraintsOnDisjuncts()
SolverFactory('gdpopt.loa').solve(
m, mip_solver=mip_solver, nlp_solver=nlp_solver
)
self.assertAlmostEqual(value(m.x), 8)
def test_logical_constraints_on_disjuncts_nonlinear_convex(self):
m = models.makeLogicalConstraintsOnDisjuncts_NonlinearConvex()
results = SolverFactory('gdpopt.loa').solve(
m, mip_solver=mip_solver, nlp_solver=nlp_solver
)
self.assertEqual(
results.solver.termination_condition, TerminationCondition.optimal
)
self.assertAlmostEqual(value(m.x), 4)
def test_nested_disjunctions_no_init(self):
m = models.makeNestedNonlinearModel()
SolverFactory('gdpopt.loa').solve(
m, mip_solver=mip_solver, nlp_solver=nlp_solver, init_algorithm='no_init'
)
self.assertAlmostEqual(value(m.x), sqrt(2) / 2)
self.assertAlmostEqual(value(m.y), sqrt(2) / 2)
def test_nested_disjunctions_max_binary(self):
m = models.makeNestedNonlinearModel()
SolverFactory('gdpopt.loa').solve(
m, mip_solver=mip_solver, nlp_solver=nlp_solver, init_algorithm='max_binary'
)
self.assertAlmostEqual(value(m.x), sqrt(2) / 2)
self.assertAlmostEqual(value(m.y), sqrt(2) / 2)
def test_boolean_vars_on_disjuncts(self):
m = models.makeBooleanVarsOnDisjuncts()
SolverFactory('gdpopt.loa').solve(
m, mip_solver=mip_solver, nlp_solver=nlp_solver
)
self.assertAlmostEqual(value(m.x), 8)
def test_LOA_8PP_default_init(self):
"""Test logic-based outer approximation with 8PP."""
exfile = import_file(join(exdir, 'eight_process', 'eight_proc_model.py'))
eight_process = exfile.build_eight_process_flowsheet()
results = SolverFactory('gdpopt.loa').solve(
eight_process, mip_solver=mip_solver, nlp_solver=nlp_solver
)
ct.check_8PP_solution(self, eight_process, results)
def test_iteration_limit(self):
exfile = import_file(join(exdir, 'eight_process', 'eight_proc_model.py'))
eight_process = exfile.build_eight_process_flowsheet()
output = StringIO()
with LoggingIntercept(output, 'pyomo.contrib.gdpopt', logging.INFO):
results = SolverFactory('gdpopt.loa').solve(
eight_process, mip_solver=mip_solver, nlp_solver=nlp_solver, iterlim=2
)
self.assertIn(
"GDPopt unable to converge bounds within iteration "
"limit of 2 iterations.",
output.getvalue().strip(),
)
self.assertEqual(
results.solver.termination_condition, TerminationCondition.maxIterations
)
def test_time_limit(self):
exfile = import_file(join(exdir, 'eight_process', 'eight_proc_model.py'))
eight_process = exfile.build_eight_process_flowsheet()
output = StringIO()
with LoggingIntercept(output, 'pyomo.contrib.gdpopt', logging.INFO):
results = SolverFactory('gdpopt.loa').solve(
eight_process,
mip_solver=mip_solver,
nlp_solver=nlp_solver,
time_limit=1,
)
self.assertIn(
"GDPopt exiting--Did not converge bounds before "
"time limit of 1 seconds.",
output.getvalue().strip(),
)
self.assertEqual(
results.solver.termination_condition, TerminationCondition.maxTimeLimit
)
@unittest.skipUnless(
license_available, "No BARON license--8PP logical problem exceeds demo size"
)
def test_LOA_8PP_logical_default_init(self):
"""Test logic-based outer approximation with 8PP."""
exfile = import_file(join(exdir, 'eight_process', 'eight_proc_logical.py'))
eight_process = exfile.build_eight_process_flowsheet()
results = SolverFactory('gdpopt.loa').solve(
eight_process, mip_solver=mip_solver, nlp_solver=nlp_solver, tee=False
)
ct.check_8PP_logical_solution(self, eight_process, results)
@unittest.skipUnless(
SolverFactory('gams').available(exception_flag=False),
'GAMS solver not available',
)
def test_LOA_8PP_gams_solver(self):
# Make sure that the duals are still correct
exfile = import_file(join(exdir, 'eight_process', 'eight_proc_model.py'))
eight_process = exfile.build_eight_process_flowsheet()
results = SolverFactory('gdpopt.loa').solve(
eight_process,
mip_solver=mip_solver,
nlp_solver='gams',
max_slack=0,
tee=False,
)
ct.check_8PP_solution(self, eight_process, results)
def test_LOA_8PP_force_NLP(self):
exfile = import_file(join(exdir, 'eight_process', 'eight_proc_model.py'))
eight_process = exfile.build_eight_process_flowsheet()
results = SolverFactory('gdpopt.loa').solve(
eight_process,
mip_solver=mip_solver,
nlp_solver=nlp_solver,
force_subproblem_nlp=True,
tee=False,
)
ct.check_8PP_solution(self, eight_process, results)
def test_LOA_strip_pack_default_init(self):
"""Test logic-based outer approximation with strip packing."""
exfile = import_file(join(exdir, 'strip_packing', 'strip_packing_concrete.py'))
strip_pack = exfile.build_rect_strip_packing_model()
SolverFactory('gdpopt.loa').solve(
strip_pack, mip_solver=mip_solver, nlp_solver=nlp_solver
)
self.assertTrue(fabs(value(strip_pack.total_length.expr) - 11) <= 1e-2)
def test_LOA_strip_pack_logical_constraints(self):
"""Test logic-based outer approximation with variation of strip
packing with some logical constraints."""
exfile = import_file(join(exdir, 'strip_packing', 'strip_packing_concrete.py'))
strip_pack = exfile.build_rect_strip_packing_model()
# add logical constraints
strip_pack.Rec3AboveOrBelowRec1 = LogicalConstraint(
expr=strip_pack.no_overlap[1, 3]
.disjuncts[2]
.indicator_var.lor(strip_pack.no_overlap[1, 3].disjuncts[3].indicator_var)
)
strip_pack.Rec3RightOrLeftOfRec2 = LogicalConstraint(
expr=strip_pack.no_overlap[2, 3]
.disjuncts[0]
.indicator_var.lor(strip_pack.no_overlap[2, 3].disjuncts[1].indicator_var)
)
SolverFactory('gdpopt.loa').solve(
strip_pack,
mip_solver=mip_solver,
nlp_solver=nlp_solver,
subproblem_presolve=False,
) # skip preprocessing for linear problem
# and so that we test everything is still
# fine
self.assertTrue(fabs(value(strip_pack.total_length.expr) - 13) <= 1e-2)
@unittest.pytest.mark.expensive
def test_LOA_constrained_layout_default_init(self):
"""Test LOA with constrained layout."""
exfile = import_file(join(exdir, 'constrained_layout', 'cons_layout_model.py'))
cons_layout = exfile.build_constrained_layout_model()
SolverFactory('gdpopt.loa').solve(
cons_layout,
mip_solver=mip_solver,
nlp_solver=nlp_solver,
iterlim=120,
max_slack=5, # problem is convex, so can decrease slack
)
objective_value = value(cons_layout.min_dist_cost.expr)
self.assertTrue(
fabs(objective_value - 41573) <= 200,
"Objective value of %s instead of 41573" % objective_value,
)
def test_LOA_8PP_maxBinary(self):
"""Test logic-based OA with max_binary initialization."""
exfile = import_file(join(exdir, 'eight_process', 'eight_proc_model.py'))
eight_process = exfile.build_eight_process_flowsheet()
results = SolverFactory('gdpopt.loa').solve(
eight_process,
init_algorithm='max_binary',
mip_solver=mip_solver,
nlp_solver=nlp_solver,
)
ct.check_8PP_solution(self, eight_process, results)
@unittest.skipUnless(
license_available, "No BARON license--8PP logical problem exceeds demo size"
)
def test_LOA_8PP_logical_maxBinary(self):
"""Test logic-based OA with max_binary initialization."""
exfile = import_file(join(exdir, 'eight_process', 'eight_proc_logical.py'))
eight_process = exfile.build_eight_process_flowsheet()
results = SolverFactory('gdpopt.loa').solve(
eight_process,
init_algorithm='max_binary',
mip_solver=mip_solver,
nlp_solver=nlp_solver,
)
ct.check_8PP_logical_solution(self, eight_process, results)
def test_LOA_strip_pack_maxBinary(self):
"""Test LOA with strip packing using max_binary initialization."""
exfile = import_file(join(exdir, 'strip_packing', 'strip_packing_concrete.py'))
strip_pack = exfile.build_rect_strip_packing_model()
SolverFactory('gdpopt.loa').solve(
strip_pack,
init_algorithm='max_binary',
mip_solver=mip_solver,
nlp_solver=nlp_solver,
)
self.assertTrue(fabs(value(strip_pack.total_length.expr) - 11) <= 1e-2)
def test_LOA_strip_pack_maxBinary_logical_constraints(self):
"""Test LOA with strip packing using max_binary initialization and
logical constraints."""
exfile = import_file(join(exdir, 'strip_packing', 'strip_packing_concrete.py'))
strip_pack = exfile.build_rect_strip_packing_model()
# add logical constraints
strip_pack.Rec3AboveOrBelowRec1 = LogicalConstraint(
expr=strip_pack.no_overlap[1, 3]
.disjuncts[2]
.indicator_var.lor(strip_pack.no_overlap[1, 3].disjuncts[3].indicator_var)
)
strip_pack.Rec3RightOrLeftOfRec2 = LogicalConstraint(
expr=strip_pack.no_overlap[2, 3]
.disjuncts[0]
.indicator_var.lor(strip_pack.no_overlap[2, 3].disjuncts[1].indicator_var)
)
SolverFactory('gdpopt.loa').solve(
strip_pack,
init_algorithm='max_binary',
mip_solver=mip_solver,
nlp_solver=nlp_solver,
)
self.assertTrue(fabs(value(strip_pack.total_length.expr) - 13) <= 1e-2)
def test_LOA_8PP_fixed_disjuncts(self):
"""Test LOA with 8PP using fixed disjuncts initialization."""
exfile = import_file(join(exdir, 'eight_process', 'eight_proc_model.py'))
eight_process = exfile.build_eight_process_flowsheet()
initialize = [
# Use units 1, 4, 7, 8
eight_process.use_unit_1or2.disjuncts[0],
eight_process.use_unit_3ornot.disjuncts[1],
eight_process.use_unit_4or5ornot.disjuncts[0],
eight_process.use_unit_6or7ornot.disjuncts[1],
eight_process.use_unit_8ornot.disjuncts[0],
]
for disj in eight_process.component_data_objects(Disjunct):
if disj in initialize:
disj.binary_indicator_var.set_value(1)
else:
disj.binary_indicator_var.set_value(0)
results = SolverFactory('gdpopt.loa').solve(
eight_process,
init_algorithm='fix_disjuncts',
mip_solver=mip_solver,
nlp_solver=nlp_solver,
)
ct.check_8PP_solution(self, eight_process, results)
def test_LOA_custom_disjuncts_with_silly_components_in_list(self):
exfile = import_file(join(exdir, 'eight_process', 'eight_proc_model.py'))
eight_process = exfile.build_eight_process_flowsheet()
eight_process.goofy = Disjunct()
eight_process.goofy.deactivate()
initialize = [
# Use units 1, 4, 7, 8