-
Notifications
You must be signed in to change notification settings - Fork 261
/
Copy pathmodel_diagnostics.py
5006 lines (4097 loc) · 171 KB
/
model_diagnostics.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
# -*- coding: utf-8 -*-
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES).
#
# Copyright (c) 2018-2024 by the software owners: The Regents of the
# University of California, through Lawrence Berkeley National Laboratory,
# National Technology & Engineering Solutions of Sandia, LLC, Carnegie Mellon
# University, West Virginia University Research Corporation, et al.
# All rights reserved. Please see the files COPYRIGHT.md and LICENSE.md
# for full copyright and license information.
#################################################################################
"""
This module contains a collection of tools for diagnosing modeling issues.
"""
__author__ = "Alexander Dowling, Douglas Allan, Andrew Lee, Robby Parker, Ben Knueven"
from operator import itemgetter
import sys
from inspect import signature
from math import log, log10, isclose, inf, isfinite
import json
from typing import List
import logging
from itertools import combinations, chain
import numpy as np
from scipy.linalg import svd
from scipy.sparse.linalg import svds, norm
from scipy.sparse import issparse, find
from pyomo.environ import (
Binary,
Integers,
Block,
check_optimal_termination,
ComponentMap,
ConcreteModel,
Constraint,
Expression,
Objective,
Param,
RangeSet,
Set,
SolverFactory,
value,
Var,
)
from pyomo.core.expr.numeric_expr import (
DivisionExpression,
NPV_DivisionExpression,
PowExpression,
NPV_PowExpression,
UnaryFunctionExpression,
NPV_UnaryFunctionExpression,
NumericExpression,
)
from pyomo.core.base.block import BlockData
from pyomo.core.base.var import VarData
from pyomo.core.base.constraint import ConstraintData
from pyomo.core.base.expression import ExpressionData
from pyomo.repn.standard_repn import ( # pylint: disable=no-name-in-module
generate_standard_repn,
)
from pyomo.common.collections import ComponentSet
from pyomo.common.config import (
ConfigDict,
ConfigValue,
document_kwargs_from_configdict,
PositiveInt,
NonNegativeFloat,
NonNegativeInt,
)
from pyomo.util.check_units import identify_inconsistent_units
from pyomo.contrib.incidence_analysis import IncidenceGraphInterface
from pyomo.core.expr.visitor import identify_variables, StreamBasedExpressionVisitor
from pyomo.contrib.pynumero.interfaces.pyomo_nlp import PyomoNLP
from pyomo.contrib.pynumero.asl import AmplInterface
from pyomo.contrib.fbbt.fbbt import compute_bounds_on_expr
from pyomo.contrib.iis import mis
from pyomo.common.deprecation import deprecation_warning
from pyomo.common.errors import PyomoException
from pyomo.common.tempfiles import TempfileManager
from pyomo.core import expr as EXPR
from pyomo.common.numeric_types import native_types
from pyomo.core.base.units_container import _PyomoUnit
from idaes.core.solvers.get_solver import get_solver
from idaes.core.util.misc import compact_expression_to_string
from idaes.core.util.model_statistics import (
activated_blocks_set,
deactivated_blocks_set,
activated_equalities_set,
deactivated_equalities_set,
activated_inequalities_set,
deactivated_inequalities_set,
activated_objectives_set,
deactivated_objectives_set,
variables_in_activated_constraints_set,
variables_not_in_activated_constraints_set,
variables_with_none_value_in_activated_equalities_set,
number_activated_greybox_equalities,
number_deactivated_greybox_equalities,
activated_greybox_block_set,
deactivated_greybox_block_set,
greybox_block_set,
unfixed_greybox_variables,
greybox_variables,
degrees_of_freedom,
large_residuals_set,
variables_near_bounds_set,
)
from idaes.core.util.scaling import (
get_jacobian,
extreme_jacobian_columns,
extreme_jacobian_rows,
extreme_jacobian_entries,
jacobian_cond,
)
from idaes.core.util.parameter_sweep import (
SequentialSweepRunner,
ParameterSweepBase,
is_psweepspec,
)
from idaes.core.util.linalg import svd_rayleigh_ritz
import idaes.logger as idaeslog
_log = idaeslog.getLogger(__name__)
MAX_STR_LENGTH = 84
TAB = " " * 4
# Constants for Degeneracy Hunter
YTOL = 0.9
MMULT = 0.99
# TODO: Add suggested steps to cautions - how?
def svd_callback_validator(val):
"""Domain validator for SVD callbacks
Args:
val : value to be checked
Returns:
TypeError if val is not a valid callback
"""
if callable(val):
sig = signature(val)
if len(sig.parameters) >= 2:
return val
_log.error(
f"SVD callback {val} must be a callable which takes at least two arguments."
)
raise ValueError(
"SVD callback must be a callable which takes at least two arguments."
)
def svd_dense(jacobian, number_singular_values):
"""
Callback for performing SVD analysis using scipy.linalg.svd
Args:
jacobian: Jacobian to be analysed
number_singular_values: number of singular values to compute
Returns:
u, s and v numpy arrays
"""
u, s, vT = svd(jacobian.todense(), full_matrices=False)
# Reorder singular values and vectors so that the singular
# values are from least to greatest
u = np.flip(u[:, -number_singular_values:], axis=1)
s = np.flip(s[-number_singular_values:], axis=0)
vT = np.flip(vT[-number_singular_values:, :], axis=0)
return u, s, vT.transpose()
def svd_sparse(jacobian, number_singular_values):
"""
Callback for performing SVD analysis using scipy.sparse.linalg.svds
Args:
jacobian: Jacobian to be analysed
number_singular_values: number of singular values to compute
Returns:
u, s and v numpy arrays
"""
u, s, vT = svds(jacobian, k=number_singular_values, which="SM")
return u, s, vT.transpose()
def svd_rayleigh_ritz_callback(jacobian, number_singular_values, **kwargs):
"""
Callback for performing SVD analysis using idaes.core.util.linalg.svd_rayleigh_ritz
Args:
jacobian: Jacobian to be analysed
number_singular_values: number of singular values to compute
**kwargs: Dictionary of keyword arguments to pass to svd_rayleigh_ritz
Returns:
u, s and v numpy arrays
"""
# This method also returns the null space, which is not used by
# the model diagnostics at present
m, n = jacobian.shape
if m != n:
u, s, v, _ = svd_rayleigh_ritz(jacobian, number_singular_values, **kwargs)
else:
u, s, v = svd_rayleigh_ritz(jacobian, number_singular_values, **kwargs)
return u, s, v
CONFIG = ConfigDict()
CONFIG.declare(
"variable_bounds_absolute_tolerance",
ConfigValue(
default=1e-4,
domain=NonNegativeFloat,
description="Absolute tolerance for considering a variable to be close "
"to its bounds.",
),
)
CONFIG.declare(
"variable_bounds_relative_tolerance",
ConfigValue(
default=1e-4,
domain=NonNegativeFloat,
description="Relative tolerance for considering a variable to be close "
"to its bounds.",
),
)
CONFIG.declare(
"variable_bounds_violation_tolerance",
ConfigValue(
default=0,
domain=NonNegativeFloat,
description="Absolute tolerance for considering a variable to violate its bounds.",
doc="Absolute tolerance for considering a variable to violate its bounds. "
"Some solvers relax bounds on variables thus allowing a small violation to be "
"considered acceptable.",
),
)
CONFIG.declare(
"constraint_residual_tolerance",
ConfigValue(
default=1e-5,
domain=NonNegativeFloat,
description="Absolute tolerance to use when checking constraint residuals.",
),
)
CONFIG.declare(
"constraint_term_mismatch_tolerance",
ConfigValue(
default=1e6,
domain=NonNegativeFloat,
description="Magnitude difference to use when checking for mismatched additive terms in constraints.",
),
)
CONFIG.declare(
"constraint_term_cancellation_tolerance",
ConfigValue(
default=1e-4,
domain=NonNegativeFloat,
description="Absolute tolerance to use when checking for canceling additive terms in constraints.",
),
)
CONFIG.declare(
"max_canceling_terms",
ConfigValue(
default=5,
domain=NonNegativeInt,
description="Maximum number of terms to consider when looking for canceling combinations in expressions.",
),
)
CONFIG.declare(
"constraint_term_zero_tolerance",
ConfigValue(
default=1e-10,
domain=NonNegativeFloat,
description="Absolute tolerance to use when determining if a constraint term is equal to zero.",
),
)
CONFIG.declare(
"variable_large_value_tolerance",
ConfigValue(
default=1e4,
domain=NonNegativeFloat,
description="Absolute tolerance for considering a value to be large.",
),
)
CONFIG.declare(
"variable_small_value_tolerance",
ConfigValue(
default=1e-4,
domain=NonNegativeFloat,
description="Absolute tolerance for considering a value to be small.",
),
)
CONFIG.declare(
"variable_zero_value_tolerance",
ConfigValue(
default=1e-8,
domain=NonNegativeFloat,
description="Absolute tolerance for considering a value to be near to zero.",
),
)
CONFIG.declare(
"jacobian_large_value_caution",
ConfigValue(
default=1e4,
domain=NonNegativeFloat,
description="Tolerance for raising a caution for large Jacobian values.",
),
)
CONFIG.declare(
"jacobian_large_value_warning",
ConfigValue(
default=1e8,
domain=NonNegativeFloat,
description="Tolerance for raising a warning for large Jacobian values.",
),
)
CONFIG.declare(
"jacobian_small_value_caution",
ConfigValue(
default=1e-4,
domain=NonNegativeFloat,
description="Tolerance for raising a caution for small Jacobian values.",
),
)
CONFIG.declare(
"jacobian_small_value_warning",
ConfigValue(
default=1e-8,
domain=NonNegativeFloat,
description="Tolerance for raising a warning for small Jacobian values.",
),
)
CONFIG.declare(
"warn_for_evaluation_error_at_bounds",
ConfigValue(
default=True,
domain=bool,
description="If False, warnings will not be generated for things like log(x) with x >= 0",
),
)
CONFIG.declare(
"parallel_component_tolerance",
ConfigValue(
default=1e-8,
domain=NonNegativeFloat,
description="Tolerance for identifying near-parallel Jacobian rows/columns",
),
)
CONFIG.declare(
"absolute_feasibility_tolerance",
ConfigValue(
default=1e-6,
domain=NonNegativeFloat,
description="Feasibility tolerance for identifying infeasible constraints and bounds",
),
)
SVDCONFIG = ConfigDict()
SVDCONFIG.declare(
"number_of_smallest_singular_values",
ConfigValue(
domain=PositiveInt,
description="Number of smallest singular values to compute",
),
)
SVDCONFIG.declare(
"svd_callback",
ConfigValue(
default=svd_rayleigh_ritz_callback,
domain=svd_callback_validator,
description="Callback to SVD method of choice (default = svd_rayleigh_ritz_callback)",
doc="Callback to SVD method of choice (default = svd_rayleigh_ritz_callback). "
"Callbacks should take the Jacobian and number of singular values "
"to compute as options, plus any method specific arguments, and should "
"return the u, s and v matrices as numpy arrays.",
),
)
SVDCONFIG.declare(
"svd_callback_arguments",
ConfigValue(
default=None,
domain=dict,
description="Optional arguments to pass to SVD callback (default = None)",
),
)
SVDCONFIG.declare(
"singular_value_tolerance",
ConfigValue(
default=1e-6,
domain=NonNegativeFloat,
description="Tolerance for defining a small singular value",
),
)
SVDCONFIG.declare(
"size_cutoff_in_singular_vector",
ConfigValue(
default=0.1,
domain=NonNegativeFloat,
description="Size below which to ignore constraints and variables in "
"the singular vector",
),
)
DHCONFIG = ConfigDict()
DHCONFIG.declare(
"solver",
ConfigValue(
default="scip",
domain=str,
description="MILP solver to use for finding irreducible degenerate sets.",
),
)
DHCONFIG.declare(
"solver_options",
ConfigValue(
domain=None,
description="Options to pass to MILP solver.",
),
)
DHCONFIG.declare(
"M", # TODO: Need better name
ConfigValue(
default=1e5,
domain=NonNegativeFloat,
description="Maximum value for nu in MILP models.",
),
)
DHCONFIG.declare(
"m_small", # TODO: Need better name
ConfigValue(
default=1e-5,
domain=NonNegativeFloat,
description="Smallest value for nu to be considered non-zero in MILP models.",
),
)
DHCONFIG.declare(
"trivial_constraint_tolerance",
ConfigValue(
default=1e-6,
domain=NonNegativeFloat,
description="Tolerance for identifying non-zero rows in Jacobian.",
),
)
@document_kwargs_from_configdict(CONFIG)
class DiagnosticsToolbox:
"""
The IDAES Model DiagnosticsToolbox.
To get started:
1. Create an instance of your model (this does not need to be initialized yet).
2. Fix variables until you have 0 degrees of freedom. Many of these tools presume
a square model, and a square model should always be the foundation of any more
advanced model.
3. Create an instance of the DiagnosticsToolbox and provide the model to debug as
the model argument.
4. Call the ``report_structural_issues()`` method.
Model diagnostics is an iterative process and you will likely need to run these
tools multiple times to resolve all issues. After making a change to your model,
you should always start from the beginning again to ensure the change did not
introduce any new issues; i.e., always start from the report_structural_issues()
method.
Note that structural checks do not require the model to be initialized, thus users
should start with these. Numerical checks require at least a partial solution to the
model and should only be run once all structural issues have been resolved.
Report methods will print a summary containing three parts:
1. Warnings - these are critical issues that should be resolved before continuing.
For each warning, a method will be suggested in the Next Steps section to get
additional information.
2. Cautions - these are things that could be correct but could also be the source of
solver issues. Not all cautions need to be addressed, but users should investigate
each one to ensure that the behavior is correct and that they will not be the source
of difficulties later. Methods exist to provide more information on all cautions,
but these will not appear in the Next Steps section.
3. Next Steps - these are recommended methods to call from the DiagnosticsToolbox to
get further information on warnings. If no warnings are found, this will suggest
the next report method to call.
Args:
model: model to be diagnosed. The DiagnosticsToolbox does not support indexed Blocks.
"""
def __init__(self, model: BlockData, **kwargs):
# TODO: In future may want to generalise this to accept indexed blocks
# However, for now some of the tools do not support indexed blocks
if not isinstance(model, BlockData):
raise TypeError(
"model argument must be an instance of a Pyomo BlockData object "
"(either a scalar Block or an element of an indexed Block)."
)
if len(greybox_block_set(model)) != 0:
raise NotImplementedError(
"Model contains Greybox models, which are not supported by Diagnostics toolbox at the moment"
)
self._model = model
self.config = CONFIG(kwargs)
@property
def model(self):
"""
Model currently being diagnosed.
"""
return self._model
def display_external_variables(self, stream=None):
"""
Prints a list of variables that appear within activated Constraints in the
model but are not contained within the model themselves.
Args:
stream: an I/O object to write the list to (default = stdout)
Returns:
None
"""
if stream is None:
stream = sys.stdout
ext_vars = []
for v in variables_in_activated_constraints_set(self._model):
if not _var_in_block(v, self._model):
ext_vars.append(v.name)
_write_report_section(
stream=stream,
lines_list=ext_vars,
title="The following external variable(s) appear in constraints within the model:",
header="=",
footer="=",
)
def display_unused_variables(self, stream=None):
"""
Prints a list of variables that do not appear in any activated Constraints.
Args:
stream: an I/O object to write the list to (default = stdout)
Returns:
None
"""
if stream is None:
stream = sys.stdout
_write_report_section(
stream=stream,
lines_list=variables_not_in_activated_constraints_set(self._model),
title="The following variable(s) do not appear in any activated constraints within the model:",
header="=",
footer="=",
)
def display_variables_fixed_to_zero(self, stream=None):
"""
Prints a list of variables that are fixed to an absolute value of 0.
Args:
stream: an I/O object to write the list to (default = stdout)
Returns:
None
"""
if stream is None:
stream = sys.stdout
_write_report_section(
stream=stream,
lines_list=_vars_fixed_to_zero(self._model),
title="The following variable(s) are fixed to zero:",
header="=",
footer="=",
)
def display_variables_at_or_outside_bounds(self, stream=None):
"""
Prints a list of variables with values that fall at or outside the bounds
on the variable.
Args:
stream: an I/O object to write the list to (default = stdout)
Returns:
None
"""
if stream is None:
stream = sys.stdout
_write_report_section(
stream=stream,
lines_list=[
f"{v.name} ({'fixed' if v.fixed else 'free'}): value={value(v)} bounds={v.bounds}"
for v in _vars_violating_bounds(
self._model,
tolerance=self.config.variable_bounds_violation_tolerance,
)
],
title="The following variable(s) have values at or outside their bounds "
f"(tol={self.config.variable_bounds_violation_tolerance:.1E}):",
header="=",
footer="=",
)
def display_variables_with_none_value(self, stream=None):
"""
Prints a list of variables with a value of None.
Args:
stream: an I/O object to write the list to (default = stdout)
Returns:
None
"""
if stream is None:
stream = sys.stdout
_write_report_section(
stream=stream,
lines_list=_vars_with_none_value(self._model),
title="The following variable(s) have a value of None:",
header="=",
footer="=",
)
def display_variables_with_none_value_in_activated_constraints(self, stream=None):
"""
Prints a list of variables with values of None that are present in the
mathematical program generated to solve the model. This list includes only
variables in active constraints that are reachable through active blocks.
Args:
stream: an I/O object to write the list to (default = stdout)
Returns:
None
"""
if stream is None:
stream = sys.stdout
_write_report_section(
stream=stream,
lines_list=[
f"{v.name}"
for v in variables_with_none_value_in_activated_equalities_set(
self._model
)
],
title="The following variable(s) have a value of None:",
header="=",
footer="=",
)
def _verify_active_variables_initialized(self, stream=None):
"""
Validate that all variables are initialized (i.e., have values set to
something other than None) before doing further numerical analysis.
Stream argument provided for forward compatibility (in case we want
to print a list or something).
"""
n_uninit = len(
variables_with_none_value_in_activated_equalities_set(self._model)
)
if n_uninit > 0:
raise RuntimeError(
f"Found {n_uninit} variables with a value of None in the mathematical "
"program generated by the model. They must be initialized with non-None "
"values before numerical analysis can proceed. Run "
+ self.display_variables_with_none_value_in_activated_constraints.__name__
+ " to display a list of these variables."
)
def display_variables_with_value_near_zero(self, stream=None):
"""
Prints a list of variables with a value close to zero. The tolerance
for determining what is close to zero can be set in the class configuration
options.
Args:
stream: an I/O object to write the list to (default = stdout)
Returns:
None
"""
if stream is None:
stream = sys.stdout
_write_report_section(
stream=stream,
lines_list=[
f"{v.name}: value={value(v)}"
for v in _vars_near_zero(
self._model, self.config.variable_zero_value_tolerance
)
],
title=f"The following variable(s) have a value close to zero "
f"(tol={self.config.variable_zero_value_tolerance:.1E}):",
header="=",
footer="=",
)
def display_variables_with_extreme_values(self, stream=None):
"""
Prints a list of variables with extreme values.
Tolerances can be set in the class configuration options.
Args:
stream: an I/O object to write the list to (default = stdout)
Returns:
None
"""
if stream is None:
stream = sys.stdout
_write_report_section(
stream=stream,
lines_list=[
f"{i.name}: {value(i)}"
for i in _vars_with_extreme_values(
model=self._model,
large=self.config.variable_large_value_tolerance,
small=self.config.variable_small_value_tolerance,
zero=self.config.variable_zero_value_tolerance,
)
],
title=f"The following variable(s) have extreme values "
f"(<{self.config.variable_small_value_tolerance:.1E} or "
f"> {self.config.variable_large_value_tolerance:.1E}):",
header="=",
footer="=",
)
def display_variables_near_bounds(self, stream=None):
"""
Prints a list of variables with values close to their bounds. Tolerance can
be set in the class configuration options.
Args:
stream: an I/O object to write the list to (default = stdout)
Returns:
None
"""
if stream is None:
stream = sys.stdout
_write_report_section(
stream=stream,
lines_list=[
f"{v.name}: value={value(v)} bounds={v.bounds}"
for v in variables_near_bounds_set(
self._model,
abs_tol=self.config.variable_bounds_absolute_tolerance,
rel_tol=self.config.variable_bounds_relative_tolerance,
)
],
title=f"The following variable(s) have values close to their bounds "
f"(abs={self.config.variable_bounds_absolute_tolerance:.1E}, "
f"rel={self.config.variable_bounds_relative_tolerance:.1E}):",
header="=",
footer="=",
)
def display_components_with_inconsistent_units(self, stream=None):
"""
Prints a list of all Constraints, Expressions and Objectives in the
model with inconsistent units of measurement.
Args:
stream: an I/O object to write the list to (default = stdout)
Returns:
None
"""
if stream is None:
stream = sys.stdout
_write_report_section(
stream=stream,
lines_list=identify_inconsistent_units(self._model),
title="The following component(s) have unit consistency issues:",
end_line="For more details on unit inconsistencies, import the "
"assert_units_consistent method\nfrom pyomo.util.check_units",
header="=",
footer="=",
)
def display_constraints_with_large_residuals(self, stream=None):
"""
Prints a list of Constraints with residuals greater than a specified tolerance.
Tolerance can be set in the class configuration options.
Args:
stream: an I/O object to write the list to (default = stdout)
Returns:
None
"""
if stream is None:
stream = sys.stdout
lrdict = large_residuals_set(
self._model,
tol=self.config.constraint_residual_tolerance,
return_residual_values=True,
)
lrs = []
for k, v in lrdict.items():
lrs.append(f"{k.name}: {v:.5E}")
_write_report_section(
stream=stream,
lines_list=lrs,
title=f"The following constraint(s) have large residuals "
f"(>{self.config.constraint_residual_tolerance:.1E}):",
header="=",
footer="=",
)
def compute_infeasibility_explanation(self, stream=None, solver=None, tee=False):
"""
This function attempts to determine why a given model is infeasible. It deploys
two main algorithms:
1. Relaxes the constraints of the problem, and reports to the user
some sets of constraints and variable bounds, which when relaxed, creates a
feasible model.
2. Uses the information collected from (1) to attempt to compute a Minimal
Infeasible System (MIS), which is a set of constraints and variable bounds
which appear to be in conflict with each other. It is minimal in the sense
that removing any single constraint or variable bound would result in a
feasible subsystem.
Args:
stream: I/O object to write report to (default = stdout)
solver: A pyomo solver object or a string for SolverFactory
(default = get_solver())
tee: Display intermediate solves conducted (False)
Returns:
None
"""
if solver is None:
solver = get_solver("ipopt_v2")
if stream is None:
stream = sys.stdout
h = logging.StreamHandler(stream)
h.setLevel(logging.INFO)
l = logging.Logger(name=__name__ + ".compute_infeasibility_explanation")
l.setLevel(logging.INFO)
l.addHandler(h)
mis.compute_infeasibility_explanation(
self._model,
solver,
tee=tee,
tolerance=self.config.absolute_feasibility_tolerance,
logger=l,
)
def get_dulmage_mendelsohn_partition(self):
"""
Performs a Dulmage-Mendelsohn partitioning on the model and returns
the over- and under-constrained sub-problems.
Returns:
list-of-lists variables in each independent block of the under-constrained set
list-of-lists constraints in each independent block of the under-constrained set
list-of-lists variables in each independent block of the over-constrained set
list-of-lists constraints in each independent block of the over-constrained set
"""
igraph = IncidenceGraphInterface(self._model, include_inequality=False)
var_dm_partition, con_dm_partition = igraph.dulmage_mendelsohn()
# Collect under- and over-constrained sub-system
uc_var = var_dm_partition.unmatched + var_dm_partition.underconstrained
uc_con = con_dm_partition.underconstrained
oc_var = var_dm_partition.overconstrained
oc_con = con_dm_partition.overconstrained + con_dm_partition.unmatched
uc_vblocks, uc_cblocks = igraph.get_connected_components(uc_var, uc_con)
oc_vblocks, oc_cblocks = igraph.get_connected_components(oc_var, oc_con)
return uc_vblocks, uc_cblocks, oc_vblocks, oc_cblocks
def display_underconstrained_set(self, stream=None):
"""
Prints the variables and constraints in the under-constrained sub-problem
from a Dulmage-Mendelsohn partitioning.
This can be used to identify the under-defined part of a model and thus
where additional information (fixed variables or constraints) are required.
Args:
stream: an I/O object to write the list to (default = stdout)
Returns:
None
"""
if stream is None:
stream = sys.stdout
uc_vblocks, uc_cblocks, _, _ = self.get_dulmage_mendelsohn_partition()
stream.write("=" * MAX_STR_LENGTH + "\n")
stream.write("Dulmage-Mendelsohn Under-Constrained Set\n\n")
for i, uc_vblock in enumerate(uc_vblocks):
stream.write(f"{TAB}Independent Block {i}:\n\n")
stream.write(f"{2*TAB}Variables:\n\n")
for v in uc_vblock:
stream.write(f"{3*TAB}{v.name}\n")
stream.write(f"\n{2*TAB}Constraints:\n\n")
for c in uc_cblocks[i]:
stream.write(f"{3*TAB}{c.name}\n")
stream.write("\n")
stream.write("=" * MAX_STR_LENGTH + "\n")
def display_overconstrained_set(self, stream=None):
"""
Prints the variables and constraints in the over-constrained sub-problem
from a Dulmage-Mendelsohn partitioning.
This can be used to identify the over-defined part of a model and thus
where constraints must be removed or variables unfixed.
Args:
stream: an I/O object to write the list to (default = stdout)
Returns:
None
"""
if stream is None:
stream = sys.stdout
_, _, oc_vblocks, oc_cblocks = self.get_dulmage_mendelsohn_partition()
stream.write("=" * MAX_STR_LENGTH + "\n")
stream.write("Dulmage-Mendelsohn Over-Constrained Set\n\n")
for i, oc_vblock in enumerate(oc_vblocks):
stream.write(f"{TAB}Independent Block {i}:\n\n")
stream.write(f"{2*TAB}Variables:\n\n")
for v in oc_vblock:
stream.write(f"{3*TAB}{v.name}\n")
stream.write(f"\n{2*TAB}Constraints:\n\n")
for c in oc_cblocks[i]:
stream.write(f"{3*TAB}{c.name}\n")