\n",
"**Inline Exercise:**\n",
"Import the DiagnosticsToolbox in the cell below.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"from idaes.core.util import DiagnosticsToolbox"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To get some information on where to start, try using the Python ``help()`` function to see the documentation for the ``DiagnosticsToolbox``.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Call `help(DiagnosticsToolbox)` to see some more information on the toolbox and some instructions on how to get started.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on class DiagnosticsToolbox in module idaes.core.util.model_diagnostics:\n",
"\n",
"class DiagnosticsToolbox(builtins.object)\n",
" | DiagnosticsToolbox(model: pyomo.core.base.block._BlockData, **kwargs)\n",
" | \n",
" | The IDAES Model DiagnosticsToolbox.\n",
" | \n",
" | To get started:\n",
" | \n",
" | 1. Create an instance of your model (this does not need to be initialized yet).\n",
" | 2. Fix variables until you have 0 degrees of freedom. Many of these tools presume\n",
" | a square model, and a square model should always be the foundation of any more\n",
" | advanced model.\n",
" | 3. Create an instance of the DiagnosticsToolbox and provide the model to debug as\n",
" | the model argument.\n",
" | 4. Call the ``report_structural_issues()`` method.\n",
" | \n",
" | Model diagnostics is an iterative process and you will likely need to run these\n",
" | tools multiple times to resolve all issues. After making a change to your model,\n",
" | you should always start from the beginning again to ensure the change did not\n",
" | introduce any new issues; i.e., always start from the report_structural_issues()\n",
" | method.\n",
" | \n",
" | Note that structural checks do not require the model to be initialized, thus users\n",
" | should start with these. Numerical checks require at least a partial solution to the\n",
" | model and should only be run once all structural issues have been resolved.\n",
" | \n",
" | Report methods will print a summary containing three parts:\n",
" | \n",
" | 1. Warnings - these are critical issues that should be resolved before continuing.\n",
" | For each warning, a method will be suggested in the Next Steps section to get\n",
" | additional information.\n",
" | 2. Cautions - these are things that could be correct but could also be the source of\n",
" | solver issues. Not all cautions need to be addressed, but users should investigate\n",
" | each one to ensure that the behavior is correct and that they will not be the source\n",
" | of difficulties later. Methods exist to provide more information on all cautions,\n",
" | but these will not appear in the Next Steps section.\n",
" | 3. Next Steps - these are recommended methods to call from the DiagnosticsToolbox to\n",
" | get further information on warnings. If no warnings are found, this will suggest\n",
" | the next report method to call.\n",
" | \n",
" | Args:\n",
" | \n",
" | model: model to be diagnosed. The DiagnosticsToolbox does not support indexed Blocks.\n",
" | \n",
" | Keyword Arguments\n",
" | -----------------\n",
" | variable_bounds_absolute_tolerance: float, default=0.0001\n",
" | Absolute tolerance for considering a variable to be close to its\n",
" | bounds.\n",
" | \n",
" | variable_bounds_relative_tolerance: float, default=0.0001\n",
" | Relative tolerance for considering a variable to be close to its\n",
" | bounds.\n",
" | \n",
" | variable_bounds_violation_tolerance: float, default=0\n",
" | Absolute tolerance for considering a variable to violate its bounds.\n",
" | Some solvers relax bounds on variables thus allowing a small violation\n",
" | to be considered acceptable.\n",
" | \n",
" | constraint_residual_tolerance: float, default=1e-05\n",
" | Absolute tolerance to use when checking constraint residuals.\n",
" | \n",
" | variable_large_value_tolerance: float, default=10000.0\n",
" | Absolute tolerance for considering a value to be large.\n",
" | \n",
" | variable_small_value_tolerance: float, default=0.0001\n",
" | Absolute tolerance for considering a value to be small.\n",
" | \n",
" | variable_zero_value_tolerance: float, default=1e-08\n",
" | Absolute tolerance for considering a value to be near to zero.\n",
" | \n",
" | jacobian_large_value_caution: float, default=10000.0\n",
" | Tolerance for raising a caution for large Jacobian values.\n",
" | \n",
" | jacobian_large_value_warning: float, default=100000000.0\n",
" | Tolerance for raising a warning for large Jacobian values.\n",
" | \n",
" | jacobian_small_value_caution: float, default=0.0001\n",
" | Tolerance for raising a caution for small Jacobian values.\n",
" | \n",
" | jacobian_small_value_warning: float, default=1e-08\n",
" | Tolerance for raising a warning for small Jacobian values.\n",
" | \n",
" | warn_for_evaluation_error_at_bounds: bool, default=True\n",
" | If False, warnings will not be generated for things like log(x) with x\n",
" | >= 0\n",
" | \n",
" | Methods defined here:\n",
" | \n",
" | __init__(self, model: pyomo.core.base.block._BlockData, **kwargs)\n",
" | Initialize self. See help(type(self)) for accurate signature.\n",
" | \n",
" | assert_no_numerical_warnings(self)\n",
" | Checks for numerical warnings in the model and raises an AssertionError\n",
" | if any are found.\n",
" | \n",
" | Raises:\n",
" | AssertionError if any warnings are identified by numerical analysis.\n",
" | \n",
" | assert_no_structural_warnings(self)\n",
" | Checks for structural warnings in the model and raises an AssertionError\n",
" | if any are found.\n",
" | \n",
" | Raises:\n",
" | AssertionError if any warnings are identified by structural analysis.\n",
" | \n",
" | display_components_with_inconsistent_units(self, stream=None)\n",
" | Prints a list of all Constraints, Expressions and Objectives in the\n",
" | model with inconsistent units of measurement.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the list to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_constraints_with_extreme_jacobians(self, stream=None)\n",
" | Prints the constraints associated with rows in the Jacobian with extreme\n",
" | L2 norms. This often indicates poorly scaled constraints.\n",
" | \n",
" | Tolerances can be set via the DiagnosticsToolbox config.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the output to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_constraints_with_large_residuals(self, stream=None)\n",
" | Prints a list of Constraints with residuals greater than a specified tolerance.\n",
" | Tolerance can be set in the class configuration options.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the list to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_external_variables(self, stream=None)\n",
" | Prints a list of variables that appear within activated Constraints in the\n",
" | model but are not contained within the model themselves.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the list to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_extreme_jacobian_entries(self, stream=None)\n",
" | Prints variables and constraints associated with entries in the Jacobian with extreme\n",
" | values. This can be indicative of poor scaling, especially for isolated terms (e.g.\n",
" | variables which appear only in one term of a single constraint).\n",
" | \n",
" | Tolerances can be set via the DiagnosticsToolbox config.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the output to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_overconstrained_set(self, stream=None)\n",
" | Prints the variables and constraints in the over-constrained sub-problem\n",
" | from a Dulmage-Mendelsohn partitioning.\n",
" | \n",
" | This can be used to identify the over-defined part of a model and thus\n",
" | where constraints must be removed or variables unfixed.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the list to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_potential_evaluation_errors(self, stream=None)\n",
" | Prints constraints that may be prone to evaluation errors\n",
" | (e.g., log of a negative number) based on variable bounds.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the output to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_underconstrained_set(self, stream=None)\n",
" | Prints the variables and constraints in the under-constrained sub-problem\n",
" | from a Dulmage-Mendelsohn partitioning.\n",
" | \n",
" | This can be used to identify the under-defined part of a model and thus\n",
" | where additional information (fixed variables or constraints) are required.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the list to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_unused_variables(self, stream=None)\n",
" | Prints a list of variables that do not appear in any activated Constraints.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the list to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_variables_at_or_outside_bounds(self, stream=None)\n",
" | Prints a list of variables with values that fall at or outside the bounds\n",
" | on the variable.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the list to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_variables_fixed_to_zero(self, stream=None)\n",
" | Prints a list of variables that are fixed to an absolute value of 0.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the list to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_variables_near_bounds(self, stream=None)\n",
" | Prints a list of variables with values close to their bounds. Tolerance can\n",
" | be set in the class configuration options.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the list to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_variables_with_extreme_jacobians(self, stream=None)\n",
" | Prints the variables associated with columns in the Jacobian with extreme\n",
" | L2 norms. This often indicates poorly scaled variables.\n",
" | \n",
" | Tolerances can be set via the DiagnosticsToolbox config.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the output to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_variables_with_extreme_values(self, stream=None)\n",
" | Prints a list of variables with extreme values.\n",
" | \n",
" | Tolerances can be set in the class configuration options.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the list to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_variables_with_none_value(self, stream=None)\n",
" | Prints a list of variables with a value of None.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the list to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | display_variables_with_value_near_zero(self, stream=None)\n",
" | Prints a list of variables with a value close to zero. The tolerance\n",
" | for determining what is close to zero can be set in the class configuration\n",
" | options.\n",
" | \n",
" | Args:\n",
" | stream: an I/O object to write the list to (default = stdout)\n",
" | \n",
" | Returns:\n",
" | None\n",
" | \n",
" | get_dulmage_mendelsohn_partition(self)\n",
" | Performs a Dulmage-Mendelsohn partitioning on the model and returns\n",
" | the over- and under-constrained sub-problems.\n",
" | \n",
" | Returns:\n",
" | list-of-lists variables in each independent block of the under-constrained set\n",
" | list-of-lists constraints in each independent block of the under-constrained set\n",
" | list-of-lists variables in each independent block of the over-constrained set\n",
" | list-of-lists constraints in each independent block of the over-constrained set\n",
" | \n",
" | prepare_degeneracy_hunter(self, **kwargs)\n",
" | Create an instance of the DegeneracyHunter and store as self.degeneracy_hunter.\n",
" | \n",
" | After creating an instance of the toolbox, call\n",
" | report_irreducible_degenerate_sets.\n",
" | \n",
" | Returns:\n",
" | \n",
" | Instance of DegeneracyHunter\n",
" | \n",
" | Keyword Arguments\n",
" | -----------------\n",
" | solver: str, default='scip'\n",
" | MILP solver to use for finding irreducible degenerate sets.\n",
" | \n",
" | solver_options: optional\n",
" | Options to pass to MILP solver.\n",
" | \n",
" | M: float, default=100000.0\n",
" | Maximum value for nu in MILP models.\n",
" | \n",
" | m_small: float, default=1e-05\n",
" | Smallest value for nu to be considered non-zero in MILP models.\n",
" | \n",
" | trivial_constraint_tolerance: float, default=1e-06\n",
" | Tolerance for identifying non-zero rows in Jacobian.\n",
" | \n",
" | prepare_svd_toolbox(self, **kwargs)\n",
" | Create an instance of the SVDToolbox and store as self.svd_toolbox.\n",
" | \n",
" | After creating an instance of the toolbox, call\n",
" | display_underdetermined_variables_and_constraints().\n",
" | \n",
" | Returns:\n",
" | \n",
" | Instance of SVDToolbox\n",
" | \n",
" | Keyword Arguments\n",
" | -----------------\n",
" | number_of_smallest_singular_values: PositiveInt, optional\n",
" | Number of smallest singular values to compute\n",
" | \n",
" | svd_callback: svd_callback_validator, default=\n",
"**Inline Exercise:**\n",
"Create an instance of the DiagnosticsToolbox: dt = DiagnosticsToolbox(m)\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [],
"source": [
"dt = DiagnosticsToolbox(m)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Finally, the instructions tell us to run the ``report_structural_issues()`` method. Structural issues represent issues that exist solely in the form of the model equations and thus do not depend on the current value of any of the variables. This is useful as it means we can check for these before we even call a solver, which can be critical as sometimes these issues will cause a solver to fail without providing a useful solution.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Call dt.report_structural_issues() in the cell below.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"====================================================================================\n",
"Model Statistics\n",
"\n",
" Activated Blocks: 1 (Deactivated: 0)\n",
" Free Variables in Activated Constraints: 4 (External: 0)\n",
" Free Variables with only lower bounds: 0\n",
" Free Variables with only upper bounds: 0\n",
" Free Variables with upper and lower bounds: 2\n",
" Fixed Variables in Activated Constraints: 3 (External: 0)\n",
" Activated Equality Constraints: 4 (Deactivated: 0)\n",
" Activated Inequality Constraints: 0 (Deactivated: 0)\n",
" Activated Objectives: 0 (Deactivated: 0)\n",
"\n",
"------------------------------------------------------------------------------------\n",
"2 WARNINGS\n",
"\n",
" WARNING: 1 Component with inconsistent units\n",
" WARNING: Structural singularity found\n",
" Under-Constrained Set: 3 variables, 2 constraints\n",
" Over-Constrained Set: 1 variables, 2 constraints\n",
"\n",
"------------------------------------------------------------------------------------\n",
"2 Cautions\n",
"\n",
" Caution: 1 variable fixed to 0\n",
" Caution: 1 unused variable (0 fixed)\n",
"\n",
"------------------------------------------------------------------------------------\n",
"Suggested next steps:\n",
"\n",
" display_components_with_inconsistent_units()\n",
" display_underconstrained_set()\n",
" display_overconstrained_set()\n",
"\n",
"====================================================================================\n"
]
}
],
"source": [
"dt.report_structural_issues()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Looking at the output from the ``report_structural_issues()`` method, we can see that it provides a fairly short summary containing 4 sections.\n",
"\n",
"1. The first section is a summary of the size of the model, indicating things like the number of variables and constraints. The size of the model is often important for judging how difficult it will be to solve, and this information can also be useful for comparison to what is being sent to the solver. Most solvers will report the size of the model in their output logs, and if there is a difference between what is reported here and by the solver, then you should probably look into what is happening. This section also notes some things such as if you have any deactivated Blocks, Constraints or Objectives, or if you have variables which appear in the constraints that are not part of the model; these are not necessarily wrong but it is easy to have accidentally deactivated something you did not intend to so you should always check to see that these are expected.\n",
"\n",
"2. The second section provides a summary of any critical structural issues that were found - in this case we can see that there are 2 warnings we are going to need to look into. Warnings represent issues that need to be addressed before moving on as these will likely cause the solver to fail or give an incorrect answer.\n",
"\n",
"3. The third section lists a summary of any cautions that are found. Cautions represent issues that may or may not be problematic; in many cases these might be expected behaviors or borderline issues. However, these could also represent conceptual issues that should be addressed, so users should take the time to investigate these and determine if they need to be fixed or not.\n",
"\n",
"4. Finally, there is a section that suggests the next steps to take to help guide you through the model diagnosis process. If any warnings were identified, this section will list methods that can help you get more information on each specific problem, and if no warnings are found then it will guide you onto the next step in the model diagnosis workflow.\n",
"\n",
"**Note:** there are methods available to help investigate cautions as well, but these will not show up in the next steps in order to avoid cluttering the output. You can get more information on the available methods for investigating cautions via the documentation or ``help()`` function.\n",
"\n",
"In our current model, we have 2 critical issues (warnings) that we need to look into and resolve. The order in which we resolve these will generally not matter, but be aware that these can often be interrelated - fixing one warning might resolve other warnings as well (or create new ones), and sometimes you will need to look at multiple issues together to find the overall root cause.\n",
"\n",
"To start with, let us look at the unit consistency issue. From the \"Next Steps\" section above, the toolbox is suggesting we run the ``display_components_with_inconsistent_units()`` method for more information.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Call the `display_components_with_inconsistent_units()` method from the DiagnosticsToolbox to see more information on which constraint is causing the unit consistency issues.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"scrolled": false,
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"====================================================================================\n",
"The following component(s) have unit consistency issues:\n",
"\n",
" c1\n",
"\n",
"For more details on unit inconsistencies, import the assert_units_consistent method\n",
"from pyomo.util.check_units\n",
"====================================================================================\n"
]
}
],
"source": [
"dt.display_components_with_inconsistent_units()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This tells us that the issue lies in constraint ``c1``. If we go back and look at this constraint, we can see that it says ``v1 + v2 == 10``. ``v1`` and ``v2`` both have units of ``m`` which is consistent, but the constant in the expression (right hand side) is unitless. Thus, we need to correct this so that the right hand side has units for the constraint to be consistent.\n",
"\n",
"The cell below shows how to delete a constraint and replace it with a new one with the correct units.\n",
"\n",
"\n",
"**Warning:**\n",
"Deleting components can cause unexpected issues if something else in a model is using that component (e.g., deleting a variable which is used in a constraint). You should always be careful when deleting Pyomo components and make sure you only delete components that are not used elsewhere.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"# Delete the incorrect Constraint\n",
"m.del_component(m.c1)\n",
"\n",
"# Re-create the Constraint with the correct units\n",
"m.c1 = pyo.Constraint(expr=m.v1 + m.v2 == 10 * pyo.units.m)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"**Warning:**\n",
"Fixing issues in models is often an iterative process requiring trial and error. You might also have some results from a model before running the diagnostics tools and the changes you make during debugging may make it difficult to replicate those results afterwards.\n",
" \n",
"It is strongly recommended that you keep a record of the changes you make at each step and why, along with a Git hash (or similar version control marker) corresponding to these changes. This will allow you see what changes and why, and give you a way to go back to previous iterations if the current approach does not work out. The IDAES documentation contains recommendations on how to keep and maintain a modeling logbook.\n",
"

\n",
"\n",
"Now, re-run the ``report_structural_issues()`` method and see if this change has fixed the unit consistency issue.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Call dt.report_structural_issues() in the cell below.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"scrolled": true,
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"====================================================================================\n",
"Model Statistics\n",
"\n",
" Activated Blocks: 1 (Deactivated: 0)\n",
" Free Variables in Activated Constraints: 4 (External: 0)\n",
" Free Variables with only lower bounds: 0\n",
" Free Variables with only upper bounds: 0\n",
" Free Variables with upper and lower bounds: 2\n",
" Fixed Variables in Activated Constraints: 3 (External: 0)\n",
" Activated Equality Constraints: 4 (Deactivated: 0)\n",
" Activated Inequality Constraints: 0 (Deactivated: 0)\n",
" Activated Objectives: 0 (Deactivated: 0)\n",
"\n",
"------------------------------------------------------------------------------------\n",
"1 WARNINGS\n",
"\n",
" WARNING: Structural singularity found\n",
" Under-Constrained Set: 3 variables, 2 constraints\n",
" Over-Constrained Set: 1 variables, 2 constraints\n",
"\n",
"------------------------------------------------------------------------------------\n",
"2 Cautions\n",
"\n",
" Caution: 1 variable fixed to 0\n",
" Caution: 1 unused variable (0 fixed)\n",
"\n",
"------------------------------------------------------------------------------------\n",
"Suggested next steps:\n",
"\n",
" display_underconstrained_set()\n",
" display_overconstrained_set()\n",
"\n",
"====================================================================================\n"
]
}
],
"source": [
"dt.report_structural_issues()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The unit consistency issue has been resolved by the changes above, so now we need to look at the structural singularity. A structural singularity occurs when one sub-part of the model is over-constrained (negative degrees of freedom), which generally means another part is under-constrained (positive degrees of freedom, assuming that there are 0 degrees of freedom overall).\n",
"\n",
"The toolbox is suggesting we use the ``display_overconstrained_set()`` and ``display_underconstrained_set()`` methods to get more information on the singularity; for now, let us start with the over-constrained set.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Call dt.display_overconstrained_set() in the cell below.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"====================================================================================\n",
"Dulmage-Mendelsohn Over-Constrained Set\n",
"\n",
" Independent Block 0:\n",
"\n",
" Variables:\n",
"\n",
" v3\n",
"\n",
" Constraints:\n",
"\n",
" c2\n",
" c3\n",
"\n",
"====================================================================================\n"
]
}
],
"source": [
"dt.display_overconstrained_set()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"From the output above, the toolbox is telling us that we have two constraints (``c2`` and ``c3``) which only contain a single unfixed variable (``v3``); thus in this part of the model we have -1 degree of freedom and the model is not well defined (structurally singular). If we go back and look at these constraints, we can see the that the constraints are:\n",
"\n",
"``c2: v3 == v4 + v5``\n",
"\n",
"``c3: 2*v3 == 3*v4 + 4*v5 + v6``\n",
"\n",
"We can see that in addition to ``v3`` these constraints actually contain 3 other variables (``v4``, ``v5`` and ``v6``), however these are all variables we fixed to get our initial zero degrees of freedom. It looks like we have either accidentally fixed one too many variables or written one too many constraints.\n",
"\n",
"For this example, let us assume that ``v4`` was not supposed to be fixed and unfix it.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Resolve the structural singularity and then call dt.report_structural_issues() in the cell below.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"scrolled": true,
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"====================================================================================\n",
"Model Statistics\n",
"\n",
" Activated Blocks: 1 (Deactivated: 0)\n",
" Free Variables in Activated Constraints: 5 (External: 0)\n",
" Free Variables with only lower bounds: 0\n",
" Free Variables with only upper bounds: 0\n",
" Free Variables with upper and lower bounds: 2\n",
" Fixed Variables in Activated Constraints: 2 (External: 0)\n",
" Activated Equality Constraints: 4 (Deactivated: 0)\n",
" Activated Inequality Constraints: 0 (Deactivated: 0)\n",
" Activated Objectives: 0 (Deactivated: 0)\n",
"\n",
"------------------------------------------------------------------------------------\n",
"2 WARNINGS\n",
"\n",
" WARNING: 1 Degree of Freedom\n",
" WARNING: Structural singularity found\n",
" Under-Constrained Set: 3 variables, 2 constraints\n",
" Over-Constrained Set: 0 variables, 0 constraints\n",
"\n",
"------------------------------------------------------------------------------------\n",
"2 Cautions\n",
"\n",
" Caution: 1 variable fixed to 0\n",
" Caution: 1 unused variable (0 fixed)\n",
"\n",
"------------------------------------------------------------------------------------\n",
"Suggested next steps:\n",
"\n",
" display_underconstrained_set()\n",
"\n",
"====================================================================================\n"
]
}
],
"source": [
"m.v4.unfix()\n",
"\n",
"dt.report_structural_issues()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can see that the over-constrained set is now empty (0 variables and 0 constraints) but the under-constrained set still has 3 variables and only 2 constraints. We can also see that there is a new warning about having 1 degree of freedom in the model, however this should not be surprising as we have just unfixed ``v4`` to resolve the over-constrained set so we have added a degree of freedom to the model.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Display the under-constrained set in the cell below.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"====================================================================================\n",
"Dulmage-Mendelsohn Under-Constrained Set\n",
"\n",
" Independent Block 0:\n",
"\n",
" Variables:\n",
"\n",
" v2\n",
" v1\n",
" v7\n",
"\n",
" Constraints:\n",
"\n",
" c1\n",
" c4\n",
"\n",
"====================================================================================\n"
]
}
],
"source": [
"dt.display_underconstrained_set()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Looking at the output from the ``display_underconstrained_set()`` method, we can see that we have two constraints, ``c1`` and ``c4``, which contain three unfixed variables, ``v1``, ``v2`` and ``v7``. Thus, we have one degree of freedom that needs to be addressed. To fix this, we could either fix one of the variables shown or add an additional equality constraint to the model.\n",
"\n",
"For this example let's fix ``v2`` to a value of 5 and then re-run the ``report_structural_issues()`` method.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Fix v2 to a value of 5 and then re-run dt.report_structural_issues.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"scrolled": true,
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"====================================================================================\n",
"Model Statistics\n",
"\n",
" Activated Blocks: 1 (Deactivated: 0)\n",
" Free Variables in Activated Constraints: 4 (External: 0)\n",
" Free Variables with only lower bounds: 0\n",
" Free Variables with only upper bounds: 0\n",
" Free Variables with upper and lower bounds: 2\n",
" Fixed Variables in Activated Constraints: 3 (External: 0)\n",
" Activated Equality Constraints: 4 (Deactivated: 0)\n",
" Activated Inequality Constraints: 0 (Deactivated: 0)\n",
" Activated Objectives: 0 (Deactivated: 0)\n",
"\n",
"------------------------------------------------------------------------------------\n",
"0 WARNINGS\n",
"\n",
" No warnings found!\n",
"\n",
"------------------------------------------------------------------------------------\n",
"2 Cautions\n",
"\n",
" Caution: 1 variable fixed to 0\n",
" Caution: 1 unused variable (0 fixed)\n",
"\n",
"------------------------------------------------------------------------------------\n",
"Suggested next steps:\n",
"\n",
" Try to initialize/solve your model and then call report_numerical_issues()\n",
"\n",
"====================================================================================\n"
]
}
],
"source": [
"m.v2.fix(5)\n",
"\n",
"dt.report_structural_issues()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The toolbox is now telling us that no warnings were found, so we have resolved all the structural issues (for now at least). The toolbox is telling us that there are also 2 non-critical issues (cautions) that we should look at; one about an unused variable and one about a variable fixed to zero. If you wish, you can look into identifying and fixing these yourself, however for this example we will move on to the next step (remember that the toolbox has methods to display more details for each of these which you can find in the documentation or from the ``help()`` function).\n",
"\n",
"For the Next Steps section, the toolbox is recommending we try to solve our model and then check for numerical issues.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Use the Pyomo SolverFactory to create an instance of IPOPT and then try to solve the model. Make sure to set \"tee=True\" as this is going to fail (and it is always good practice to review the solver logs).\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Ipopt 3.13.2: \n",
"\n",
"******************************************************************************\n",
"This program contains Ipopt, a library for large-scale nonlinear optimization.\n",
" Ipopt is released as open source code under the Eclipse Public License (EPL).\n",
" For more information visit http://projects.coin-or.org/Ipopt\n",
"\n",
"This version of Ipopt was compiled from source code available at\n",
" https://github.com/IDAES/Ipopt as part of the Institute for the Design of\n",
" Advanced Energy Systems Process Systems Engineering Framework (IDAES PSE\n",
" Framework) Copyright (c) 2018-2019. See https://github.com/IDAES/idaes-pse.\n",
"\n",
"This version of Ipopt was compiled using HSL, a collection of Fortran codes\n",
" for large-scale scientific computation. All technical papers, sales and\n",
" publicity material resulting from use of the HSL codes within IPOPT must\n",
" contain the following acknowledgement:\n",
" HSL, a collection of Fortran codes for large-scale scientific\n",
" computation. See http://www.hsl.rl.ac.uk.\n",
"******************************************************************************\n",
"\n",
"This is Ipopt version 3.13.2, running with linear solver ma27.\n",
"\n",
"Number of nonzeros in equality constraint Jacobian...: 7\n",
"Number of nonzeros in inequality constraint Jacobian.: 0\n",
"Number of nonzeros in Lagrangian Hessian.............: 0\n",
"\n",
"Total number of variables............................: 4\n",
" variables with only lower bounds: 0\n",
" variables with lower and upper bounds: 2\n",
" variables with only upper bounds: 0\n",
"Total number of equality constraints.................: 4\n",
"Total number of inequality constraints...............: 0\n",
" inequality constraints with only lower bounds: 0\n",
" inequality constraints with lower and upper bounds: 0\n",
" inequality constraints with only upper bounds: 0\n",
"\n",
"iter objective inf_pr inf_du lg(mu) ||d|| lg(rg) alpha_du alpha_pr ls\n",
" 0 0.0000000e+00 1.40e+01 0.00e+00 -1.0 0.00e+00 - 0.00e+00 0.00e+00 0\n",
" 1 0.0000000e+00 1.39e+01 1.50e+02 -1.0 6.00e+00 - 7.16e-01 4.93e-03h 1\n",
" 2 0.0000000e+00 1.39e+01 3.03e+06 -1.0 5.97e+00 - 1.00e+00 4.95e-05h 1\n",
" 3r 0.0000000e+00 1.39e+01 1.00e+03 1.1 0.00e+00 - 0.00e+00 2.47e-07R 2\n",
" 4r 0.0000000e+00 4.19e+00 9.42e+02 1.1 3.50e+03 - 4.02e-01 3.37e-03f 1\n",
" 5r 0.0000000e+00 2.12e+00 8.72e+02 1.1 5.89e+01 - 4.35e-01 7.06e-02f 1\n",
" 6r 0.0000000e+00 6.74e-01 6.06e+02 1.1 5.29e+00 - 9.93e-03 3.98e-01f 1\n",
" 7r 0.0000000e+00 6.80e-01 3.14e+02 0.4 2.05e-01 - 1.00e+00 1.03e-01f 1\n",
" 8r 0.0000000e+00 6.69e-01 2.78e-05 0.4 2.58e-02 - 1.00e+00 1.00e+00f 1\n",
" 9r 0.0000000e+00 6.67e-01 7.56e+00 -1.7 8.13e-03 - 9.93e-01 9.96e-01f 1\n",
"iter objective inf_pr inf_du lg(mu) ||d|| lg(rg) alpha_du alpha_pr ls\n",
" 10r 0.0000000e+00 6.67e-01 2.23e-07 -1.7 4.13e-05 - 1.00e+00 1.00e+00f 1\n",
" 11r 0.0000000e+00 6.67e-01 6.73e-01 -3.7 6.61e-05 - 1.00e+00 1.00e+00f 1\n",
" 12r 0.0000000e+00 6.67e-01 1.91e-09 -3.7 1.48e-09 - 1.00e+00 1.00e+00h 1\n",
" 13r 0.0000000e+00 6.67e-01 2.69e+00 -8.4 5.74e-07 - 1.00e+00 9.26e-01f 1\n",
" 14r 0.0000000e+00 6.67e-01 7.65e+01 -8.4 4.23e-08 - 8.68e-01 1.00e+00f 1\n",
"\n",
"Number of Iterations....: 14\n",
"\n",
" (scaled) (unscaled)\n",
"Objective...............: 0.0000000000000000e+00 0.0000000000000000e+00\n",
"Dual infeasibility......: 3.2644919411246030e-04 3.2644919411246030e-04\n",
"Constraint violation....: 6.6666666333656233e-01 6.6666666333656233e-01\n",
"Complementarity.........: 4.6615546565561981e-09 4.6615546565561981e-09\n",
"Overall NLP error.......: 6.6666666333656233e-01 6.6666666333656233e-01\n",
"\n",
"\n",
"Number of objective function evaluations = 18\n",
"Number of objective gradient evaluations = 5\n",
"Number of equality constraint evaluations = 18\n",
"Number of inequality constraint evaluations = 0\n",
"Number of equality constraint Jacobian evaluations = 17\n",
"Number of inequality constraint Jacobian evaluations = 0\n",
"Number of Lagrangian Hessian evaluations = 15\n",
"Total CPU secs in IPOPT (w/o function evaluations) = 0.003\n",
"Total CPU secs in NLP function evaluations = 0.000\n",
"\n",
"EXIT: Converged to a point of local infeasibility. Problem may be infeasible.\n",
"WARNING: Loading a SolverResults object with a warning status into\n",
"model.name=\"unknown\";\n",
" - termination condition: infeasible\n",
" - message from solver: Ipopt 3.13.2\\x3a Converged to a locally infeasible\n",
" point. Problem may be infeasible.\n"
]
},
{
"data": {
"text/plain": [
"{'Problem': [{'Lower bound': -inf, 'Upper bound': inf, 'Number of objectives': 1, 'Number of constraints': 4, 'Number of variables': 4, 'Sense': 'unknown'}], 'Solver': [{'Status': 'warning', 'Message': 'Ipopt 3.13.2\\\\x3a Converged to a locally infeasible point. Problem may be infeasible.', 'Termination condition': 'infeasible', 'Id': 200, 'Error rc': 0, 'Time': 0.007064104080200195}], 'Solution': [OrderedDict([('number of solutions', 0), ('number of solutions displayed', 0)])]}"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"solver = pyo.SolverFactory(\"ipopt\")\n",
"solver.solve(m, tee=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As hinted at above, IPOPT has returned a warning that the problem may be infeasible. Before moving on however, it is always good practice to look over the solver outputs and see what it is telling you.\n",
"\n",
"\n",
"**Warning:**\n",
"A lot of useful information is contained in the solver logs which is extremely useful when diagnosing modeling issues. Each solver has its own way of reporting output and its own specific behavior, so you will need to learn to interpret the output of each solver you use. The IDAES Documentation contains some guidance on interpreting output logs for a few common solvers.\n",
"

\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Call the report_numerical_issues method in the cell below.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"====================================================================================\n",
"Model Statistics\n",
"\n",
" Jacobian Condition Number: 1.700E+01\n",
"\n",
"------------------------------------------------------------------------------------\n",
"2 WARNINGS\n",
"\n",
" WARNING: 1 Constraint with large residuals (>1.0E-05)\n",
" WARNING: 1 Variable at or outside bounds (tol=0.0E+00)\n",
"\n",
"------------------------------------------------------------------------------------\n",
"5 Cautions\n",
"\n",
" Caution: 2 Variables with value close to their bounds (abs=1.0E-04, rel=1.0E-04)\n",
" Caution: 2 Variables with value close to zero (tol=1.0E-08)\n",
" Caution: 1 Variable with extreme value (<1.0E-04 or >1.0E+04)\n",
" Caution: 1 Variable with None value\n",
" Caution: 1 extreme Jacobian Entry (<1.0E-04 or >1.0E+04)\n",
"\n",
"------------------------------------------------------------------------------------\n",
"Suggested next steps:\n",
"\n",
" display_constraints_with_large_residuals()\n",
" display_variables_at_or_outside_bounds()\n",
"\n",
"====================================================================================\n"
]
}
],
"source": [
"dt.report_numerical_issues()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The ``report_numerical_issues()`` provides a summary similar to that which we saw for the structural issues. Firstly, it reports to us the Jacobian condition number for our problem which can give us an idea of how well-scaled the problem is, followed by a list of warnings, cautions and suggested next steps.\n",
"\n",
"Unsurprisingly, we are seeing a warning about a constraint with a large residual which we would expect when a solver reports a potentially infeasible problem. We are also seeing a warning about a variable with bound violations which might be contributing to the potential infeasibility.\n",
"\n",
"For the next steps, the toolbox is suggesting some new methods to get more information on these issues; let us start by looking at the constraints with large residuals.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Display the constraint with a large residual in the cell below.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"====================================================================================\n",
"The following constraint(s) have large residuals (>1.0E-05):\n",
"\n",
" c2: 6.66667E-01\n",
"\n",
"====================================================================================\n"
]
}
],
"source": [
"dt.display_constraints_with_large_residuals()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The toolbox is telling us that the constraint which failed to converge is ``c2``, however this is generally only part of the story. Solvers work by trying to minimize the infeasibility in the model (residual of the constraints), which generally means they push any infeasibility onto the least sensitive constraint in the problem. Thus, the constraint which shows the infeasibility is often not the root cause of the problem, but only the symptom of the underlying issue.\n",
"\n",
"If we look back at the constraints, we can see that the same variables also appear in ``c3`` and that some of these have bounds, all of which could be contributing to the infeasibility. In this case the solver tried to minimize the residual in all the constraints and ended up pushing all the issues off onto ``c2``.\n",
"\n",
"\n",
"**Warning:**\n",
"When dealing with solver issues such as this, you should always remember that the obvious symptoms are often just the tip of the iceberg and that the real issue generally lies somewhere else; the challenge is tracing the symptoms back to their ultimate source.\n",
"

\n",
"\n",
"Next, let us take a look at the variables at or outside their bounds as well. When a solver reports an potentially infeasible solution, the most common cause is unexpected bounds violations so you should always check these first.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Display the variables with bounds violations.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"====================================================================================\n",
"The following variable(s) have values at or outside their bounds (tol=0.0E+00):\n",
"\n",
" v3 (free): value=0.0 bounds=(0, 5)\n",
"\n",
"====================================================================================\n"
]
}
],
"source": [
"dt.display_variables_at_or_outside_bounds()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The toolbox is telling us that ``v3`` is the variable with a potential issue. It is also showing us the current value and bounds for ``v3`` as well as if it is a fixed or free variable, which will be useful for diagnosing the issues.\n",
"\n",
"We can see that ``v3`` is a free variable with bounds between 0 and 5 and a current value of 0. As ``v3`` is a free variable, this suggests that the solver has pushed the value to the bound where it cannot go any further, and this might be part of the cause of our infeasibility.\n",
"\n",
"\n",
"**Warning:**\n",
"When dealing with bounds violations you should always start by understanding why the bounds exist and what they mean - in many cases a bound indicates the range over which the model can be trusted and that going beyond this may result in unexpected behavior due to extrapolation.\n",
" \n",
"Never arbitrarily change a bound just because it is causing your model to be infeasible without understanding the consequences of this decision. Often, a bound violation is an indication that you need to re-think some of the constraints in your model to find alternatives which are valid in the actual range of values you are trying to solve for.\n",
"

\n",
"\n",
"For this example, let us assume that we made a mistake with the bounds on ``v3`` and set the lower bound to be -5.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Update the bounds on v3 in the cell below.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [],
"source": [
"m.v3.setlb(-5)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that we have fixed the bounds issues, we should check whether our model is now feasible. However, before we continue we should recognize that we have just made a structural change to the model. If we were not careful, this could have introduced new structural issues to the model, so we should start from the beginning just to be sure.\n",
"\n",
"\n",
"**Warning:**\n",
"In general, you should always start from the beginning of the model diagnosis workflow after you make any change to the model. Remember to also record these changes in your log book in case something unexpected happens so that you can revert any changes that cause problems.\n",
"

\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Check to see if there are any new structural issues in the cell below.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"scrolled": true,
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"====================================================================================\n",
"Model Statistics\n",
"\n",
" Activated Blocks: 1 (Deactivated: 0)\n",
" Free Variables in Activated Constraints: 4 (External: 0)\n",
" Free Variables with only lower bounds: 0\n",
" Free Variables with only upper bounds: 0\n",
" Free Variables with upper and lower bounds: 2\n",
" Fixed Variables in Activated Constraints: 3 (External: 0)\n",
" Activated Equality Constraints: 4 (Deactivated: 0)\n",
" Activated Inequality Constraints: 0 (Deactivated: 0)\n",
" Activated Objectives: 0 (Deactivated: 0)\n",
"\n",
"------------------------------------------------------------------------------------\n",
"0 WARNINGS\n",
"\n",
" No warnings found!\n",
"\n",
"------------------------------------------------------------------------------------\n",
"2 Cautions\n",
"\n",
" Caution: 1 variable fixed to 0\n",
" Caution: 1 unused variable (0 fixed)\n",
"\n",
"------------------------------------------------------------------------------------\n",
"Suggested next steps:\n",
"\n",
" Try to initialize/solve your model and then call report_numerical_issues()\n",
"\n",
"====================================================================================\n"
]
}
],
"source": [
"dt.report_structural_issues()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Our change has not introduced any new structural issues, so we can move on and try to solve the model again.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Re-solve the model in the cell below.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Ipopt 3.13.2: \n",
"\n",
"******************************************************************************\n",
"This program contains Ipopt, a library for large-scale nonlinear optimization.\n",
" Ipopt is released as open source code under the Eclipse Public License (EPL).\n",
" For more information visit http://projects.coin-or.org/Ipopt\n",
"\n",
"This version of Ipopt was compiled from source code available at\n",
" https://github.com/IDAES/Ipopt as part of the Institute for the Design of\n",
" Advanced Energy Systems Process Systems Engineering Framework (IDAES PSE\n",
" Framework) Copyright (c) 2018-2019. See https://github.com/IDAES/idaes-pse.\n",
"\n",
"This version of Ipopt was compiled using HSL, a collection of Fortran codes\n",
" for large-scale scientific computation. All technical papers, sales and\n",
" publicity material resulting from use of the HSL codes within IPOPT must\n",
" contain the following acknowledgement:\n",
" HSL, a collection of Fortran codes for large-scale scientific\n",
" computation. See http://www.hsl.rl.ac.uk.\n",
"******************************************************************************\n",
"\n",
"This is Ipopt version 3.13.2, running with linear solver ma27.\n",
"\n",
"Number of nonzeros in equality constraint Jacobian...: 7\n",
"Number of nonzeros in inequality constraint Jacobian.: 0\n",
"Number of nonzeros in Lagrangian Hessian.............: 0\n",
"\n",
"Total number of variables............................: 4\n",
" variables with only lower bounds: 0\n",
" variables with lower and upper bounds: 2\n",
" variables with only upper bounds: 0\n",
"Total number of equality constraints.................: 4\n",
"Total number of inequality constraints...............: 0\n",
" inequality constraints with only lower bounds: 0\n",
" inequality constraints with lower and upper bounds: 0\n",
" inequality constraints with only upper bounds: 0\n",
"\n",
"iter objective inf_pr inf_du lg(mu) ||d|| lg(rg) alpha_du alpha_pr ls\n",
" 0 0.0000000e+00 6.67e-01 0.00e+00 -1.0 0.00e+00 - 0.00e+00 0.00e+00 0\n",
" 1 0.0000000e+00 6.66e-03 2.97e+00 -1.0 2.00e+00 - 7.17e-01 9.90e-01h 1\n",
" 2 0.0000000e+00 6.27e-05 9.38e+00 -1.0 2.00e-02 - 1.00e+00 9.91e-01h 1\n",
" 3 0.0000000e+00 8.88e-16 1.13e-12 -1.0 1.88e-04 - 1.00e+00 1.00e+00h 1\n",
"\n",
"Number of Iterations....: 3\n",
"\n",
" (scaled) (unscaled)\n",
"Objective...............: 0.0000000000000000e+00 0.0000000000000000e+00\n",
"Dual infeasibility......: 0.0000000000000000e+00 0.0000000000000000e+00\n",
"Constraint violation....: 8.8817841970012523e-16 8.8817841970012523e-16\n",
"Complementarity.........: 0.0000000000000000e+00 0.0000000000000000e+00\n",
"Overall NLP error.......: 8.8817841970012523e-16 8.8817841970012523e-16\n",
"\n",
"\n",
"Number of objective function evaluations = 4\n",
"Number of objective gradient evaluations = 4\n",
"Number of equality constraint evaluations = 4\n",
"Number of inequality constraint evaluations = 0\n",
"Number of equality constraint Jacobian evaluations = 4\n",
"Number of inequality constraint Jacobian evaluations = 0\n",
"Number of Lagrangian Hessian evaluations = 3\n",
"Total CPU secs in IPOPT (w/o function evaluations) = 0.001\n",
"Total CPU secs in NLP function evaluations = 0.000\n",
"\n",
"EXIT: Optimal Solution Found.\n"
]
},
{
"data": {
"text/plain": [
"{'Problem': [{'Lower bound': -inf, 'Upper bound': inf, 'Number of objectives': 1, 'Number of constraints': 4, 'Number of variables': 4, 'Sense': 'unknown'}], 'Solver': [{'Status': 'ok', 'Message': 'Ipopt 3.13.2\\\\x3a Optimal Solution Found', 'Termination condition': 'optimal', 'Id': 0, 'Error rc': 0, 'Time': 0.02317023277282715}], 'Solution': [OrderedDict([('number of solutions', 0), ('number of solutions displayed', 0)])]}"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"solver.solve(m, tee=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"IPOPT should have returned optimal solution now, so it looks like those bounds were what was causing the model to be infeasible. At this point, the model is now solving (for the current values at least), so you might think that the model is now ready for optimization.\n",
"\n",
"However, if we look at the solver logs we can see that it took around 3 iterations for IPOPT to solve our model (depending on minor variations in computer architecture). For a model this simple, we would generally expect it to solve in only 1 iteration so there is still some room for improvement.\n",
"\n",
"\n",
"**Warning:**\n",
"You should keep in mind that just because you get an optimal solution does not mean that your model is robust and free of issues.\n",
" \n",
"You should always take the time to look over the solver logs to look for signs of trouble, even if you get an optimal solution. While you might get an optimal solution for the current state, there may be advance warning signs of issues that will cause problems later when you try to solve the model at a different state.\n",
"

\n",
"\n",
"Let us run the ``report_numerical_issues`` method again to see if there are any other problems we need to address.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Check for additional numerical issues in the cell below.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"====================================================================================\n",
"Model Statistics\n",
"\n",
" Jacobian Condition Number: 1.700E+01\n",
"\n",
"------------------------------------------------------------------------------------\n",
"0 WARNINGS\n",
"\n",
" No warnings found!\n",
"\n",
"------------------------------------------------------------------------------------\n",
"5 Cautions\n",
"\n",
" Caution: 1 Variable with value close to their bounds (abs=1.0E-04, rel=1.0E-04)\n",
" Caution: 1 Variable with value close to zero (tol=1.0E-08)\n",
" Caution: 1 Variable with extreme value (<1.0E-04 or >1.0E+04)\n",
" Caution: 1 Variable with None value\n",
" Caution: 1 extreme Jacobian Entry (<1.0E-04 or >1.0E+04)\n",
"\n",
"------------------------------------------------------------------------------------\n",
"Suggested next steps:\n",
"\n",
" If you still have issues converging your model consider:\n",
" prepare_svd_toolbox()\n",
" prepare_degeneracy_hunter()\n",
"\n",
"====================================================================================\n"
]
}
],
"source": [
"dt.report_numerical_issues()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The toolbox is not reporting any warnings which is good, however there are still 5 numerical cautions that it has identified which might be contributing to the larger than expected number of iterations. As mentioned earlier, the toolbox does not suggest methods for investigating these, but there are methods available. For example, we can look at the variable with an extreme value using the `display_variables_with_extreme_values()` method.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Check for additional information about variables with extreme values.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"====================================================================================\n",
"The following variable(s) have extreme values (<1.0E-04 or > 1.0E+04):\n",
"\n",
" v7: 4.9999999999999945e-08\n",
"\n",
"====================================================================================\n"
]
}
],
"source": [
"dt.display_variables_with_extreme_values()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can see that ``v7`` is potentially causing problems due to having a very small value (on the order of magnitude of the solver tolerance). This can be especially problematic for interior point solvers like IPOPT if there is a lower bound of 0 (which there is in this case). IPOPT tries to avoid bounds and thus perturbs solutions away from these if it gets too close, which can cause convergence to be slow (or fail) if the solution lies close to the bound.\n",
"\n",
"We can address this by scaling the variable so that the value of the scaled variable is large enough that the solution is not close to the lower bound. Additionally, we should look at any constraint that ``v7`` appears in (in this case ``c4``) and ensure that those constraints are well scaled as well (so that a residual of 1e-6 is reasonable for the terms involved).\n",
"\n",
"For this case, we can set a scaling factor of 1e8 for both ``v7`` and ``c4`` as shown below. Note that we also need to apply Pyomo's scaling transformation to create a new scaled model to work with."
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [],
"source": [
"m.scaling_factor = pyo.Suffix(direction=pyo.Suffix.EXPORT)\n",
"\n",
"m.scaling_factor[m.v7] = 1e8\n",
"m.scaling_factor[m.c4] = 1e8\n",
"\n",
"scaling = pyo.TransformationFactory(\"core.scale_model\")\n",
"scaled_model = scaling.create_using(m, rename=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now that we have a scaled model, we can try to solve it and hopefully see better convergence than the unscaled model.\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Solve the scaled model and check to see how many iterations are required.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Ipopt 3.13.2: \n",
"\n",
"******************************************************************************\n",
"This program contains Ipopt, a library for large-scale nonlinear optimization.\n",
" Ipopt is released as open source code under the Eclipse Public License (EPL).\n",
" For more information visit http://projects.coin-or.org/Ipopt\n",
"\n",
"This version of Ipopt was compiled from source code available at\n",
" https://github.com/IDAES/Ipopt as part of the Institute for the Design of\n",
" Advanced Energy Systems Process Systems Engineering Framework (IDAES PSE\n",
" Framework) Copyright (c) 2018-2019. See https://github.com/IDAES/idaes-pse.\n",
"\n",
"This version of Ipopt was compiled using HSL, a collection of Fortran codes\n",
" for large-scale scientific computation. All technical papers, sales and\n",
" publicity material resulting from use of the HSL codes within IPOPT must\n",
" contain the following acknowledgement:\n",
" HSL, a collection of Fortran codes for large-scale scientific\n",
" computation. See http://www.hsl.rl.ac.uk.\n",
"******************************************************************************\n",
"\n",
"This is Ipopt version 3.13.2, running with linear solver ma27.\n",
"\n",
"Number of nonzeros in equality constraint Jacobian...: 7\n",
"Number of nonzeros in inequality constraint Jacobian.: 0\n",
"Number of nonzeros in Lagrangian Hessian.............: 0\n",
"\n",
"Total number of variables............................: 4\n",
" variables with only lower bounds: 0\n",
" variables with lower and upper bounds: 2\n",
" variables with only upper bounds: 0\n",
"Total number of equality constraints.................: 4\n",
"Total number of inequality constraints...............: 0\n",
" inequality constraints with only lower bounds: 0\n",
" inequality constraints with lower and upper bounds: 0\n",
" inequality constraints with only upper bounds: 0\n",
"\n",
"iter objective inf_pr inf_du lg(mu) ||d|| lg(rg) alpha_du alpha_pr ls\n",
" 0 0.0000000e+00 5.33e-15 0.00e+00 -1.0 0.00e+00 - 0.00e+00 0.00e+00 0\n",
"\n",
"Number of Iterations....: 0\n",
"\n",
" (scaled) (unscaled)\n",
"Objective...............: 0.0000000000000000e+00 0.0000000000000000e+00\n",
"Dual infeasibility......: 0.0000000000000000e+00 0.0000000000000000e+00\n",
"Constraint violation....: 5.3290705182007514e-15 5.3290705182007514e-15\n",
"Complementarity.........: 0.0000000000000000e+00 0.0000000000000000e+00\n",
"Overall NLP error.......: 5.3290705182007514e-15 5.3290705182007514e-15\n",
"\n",
"\n",
"Number of objective function evaluations = 1\n",
"Number of objective gradient evaluations = 1\n",
"Number of equality constraint evaluations = 1\n",
"Number of inequality constraint evaluations = 0\n",
"Number of equality constraint Jacobian evaluations = 1\n",
"Number of inequality constraint Jacobian evaluations = 0\n",
"Number of Lagrangian Hessian evaluations = 0\n",
"Total CPU secs in IPOPT (w/o function evaluations) = 0.000\n",
"Total CPU secs in NLP function evaluations = 0.000\n",
"\n",
"EXIT: Optimal Solution Found.\n",
"\b\b\b\b\b\b\b\b\b\b\b\b\b\b"
]
},
{
"data": {
"text/plain": [
"{'Problem': [{'Lower bound': -inf, 'Upper bound': inf, 'Number of objectives': 1, 'Number of constraints': 4, 'Number of variables': 4, 'Sense': 'unknown'}], 'Solver': [{'Status': 'ok', 'Message': 'Ipopt 3.13.2\\\\x3a Optimal Solution Found', 'Termination condition': 'optimal', 'Id': 0, 'Error rc': 0, 'Time': 0.0058002471923828125}], 'Solution': [OrderedDict([('number of solutions', 0), ('number of solutions displayed', 0)])]}"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"solver.solve(scaled_model, tee=True)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As we can see, the scaled model solved in 0 iterations (indicating that it already had the right solution). However, had we done this to the unscaled model we would have found it required 2-3 iterations again due to IPOPT perturbing the initial (correct) solution away from the bounds.\n",
"\n",
"\n",
"**Warning:**\n",
"Normally in these cases we would need to map the solution from the scaled model back to the unscaled model so we can view the results. In this case, we are not actually interested in the solution so we move on with the model diagnosis.\n",
"

\n",
"\n",
"Now that we have fixed the scaling issues, we can go back to the ``DiagnosticsToolbox`` and see if we still have any warnings. Note however that we need to look at the scaled model now rather than the original model, so we need to create a new instance of the ``DiagnosticsToolbox`` with the scaled model as the ``model`` argument.\n",
"\n",
"\n",
"\n",
"**Inline Exercise:**\n",
"Create a new instance of the DiagnosticsToolbox and check the scaled model for issues.\n",
"

"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {
"tags": [
"solution"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"====================================================================================\n",
"Model Statistics\n",
"\n",
" Jacobian Condition Number: 1.800E+01\n",
"\n",
"------------------------------------------------------------------------------------\n",
"0 WARNINGS\n",
"\n",
" No warnings found!\n",
"\n",
"------------------------------------------------------------------------------------\n",
"3 Cautions\n",
"\n",
" Caution: 1 Variable with value close to their bounds (abs=1.0E-04, rel=1.0E-04)\n",
" Caution: 1 Variable with value close to zero (tol=1.0E-08)\n",
" Caution: 1 Variable with None value\n",
"\n",
"------------------------------------------------------------------------------------\n",
"Suggested next steps:\n",
"\n",
" If you still have issues converging your model consider:\n",
" prepare_svd_toolbox()\n",
" prepare_degeneracy_hunter()\n",
"\n",
"====================================================================================\n"
]
}
],
"source": [
"dt_scaled = DiagnosticsToolbox(scaled_model)\n",
"dt_scaled.report_numerical_issues()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We can see that applying scaling addressed two of the cautions we had before (the variable with an extreme value and an associated large value in the model Jacobian). Whilst we were able to solve the unscaled model in this case, this is in part because it was a simple linear model. In more complex, non-linear models, scaling becomes much more important and often depends strongly on the current state of the model. That is, you can often find cases where the unscaled (or poorly scaled) model solves for a limited range of conditions but fails to solve if you move too far away for the current state. Whilst you might be able to solve the model at the current state, you should always check the solver logs and numerical cautions for advanced warning signs of scaling issues that might manifest later when you try to solve the model for a different state (e.g., during optimization).\n",
"\n",
"\n",
"**Warning:**\n",
"By their nature, numerical issues depend on the current values of the variables in the model, and thus may remain hidden until someone tries to solve the model close to where the issue exists. For this reason, the full model diagnostics workflow contains steps to run the numerical checks across a wide range of variable values to try to ensure that no issues remain hidden. This is beyond the scope of this tutorial however.\n",
"

\n",
"\n",
"At this point, we have addressed all the issues that were preventing us from solving the demonstration model and so reached the end of this tutorial. For cases where we are still having trouble solving the model, we can see that the toolbox is suggesting additional methods for further debugging and these advanced features will be the focus of separate tutorials."
]
}
],
"metadata": {
"celltoolbar": "Tags",
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.5"
}
},
"nbformat": 4,
"nbformat_minor": 3
}