From d577c83f63e8aec5b90764892816213bb50a6d15 Mon Sep 17 00:00:00 2001 From: Alex Dowling Date: Fri, 25 Sep 2026 09:27:01 -0400 Subject: [PATCH 1/7] Pyomo.DoE bug fixes --- .../explanation/analysis/doe/guide.rst | 24 ++ .../explanation/analysis/doe/objective.rst | 18 +- pyomo/contrib/doe/doe.py | 192 +++++++++---- pyomo/contrib/doe/grey_box_utilities.py | 22 +- pyomo/contrib/doe/tests/test_doe_build.py | 2 +- .../contrib/doe/tests/test_doe_regressions.py | 261 ++++++++++++++++++ pyomo/contrib/doe/tests/test_greybox.py | 85 ++++++ 7 files changed, 545 insertions(+), 59 deletions(-) create mode 100644 pyomo/contrib/doe/tests/test_doe_regressions.py diff --git a/doc/OnlineDocs/explanation/analysis/doe/guide.rst b/doc/OnlineDocs/explanation/analysis/doe/guide.rst index 2e29d09f2a5..953f99a1328 100644 --- a/doc/OnlineDocs/explanation/analysis/doe/guide.rst +++ b/doc/OnlineDocs/explanation/analysis/doe/guide.rst @@ -231,3 +231,27 @@ After applying ``run_doe`` on the ``DesignOfExperiments`` object, the optimal design is an initial concentration of 5.0 mol/L and an initial temperature of 494 K with all other temperatures being 300 K. The corresponding :math:`\log_{10}` determinant of the FIM is 19.32. + +Finite-difference evaluation and results +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``compute_FIM(method="sequential")`` first solves the fixed-design model at +its nominal parameter values. Central differences use this solution as a warm +start; forward and backward differences also use its outputs as the nominal +response in the difference formula. Outputs are evaluated before resetting each +perturbed parameter, including Expression outputs that reference parameters +directly. + +If a relative finite-difference perturbation crosses a declared parameter bound, +Pyomo.DoE widens the bound to include the perturbation and logs a warning for +that parameter. Perturbations are not clipped, so the finite-difference step is +unchanged. Parameters are fixed during these solves. Sequential evaluation +restores the original bounds, including when a solve fails; simultaneous scenario +blocks retain the widened bounds to accommodate their fixed perturbed values. +The experiment model must remain valid at the perturbed parameter values. + +``run_doe(results_file=...)`` accepts a string or a ``pathlib.Path`` and writes +JSON results. The ``"Measurement Error"`` field and +``get_measurement_error_values()`` report the standard deviations stored as +values in the ``measurement_error`` suffix, in suffix order, rather than the +corresponding measured output values. diff --git a/doc/OnlineDocs/explanation/analysis/doe/objective.rst b/doc/OnlineDocs/explanation/analysis/doe/objective.rst index 7a43356c72b..70f59e4d65a 100644 --- a/doc/OnlineDocs/explanation/analysis/doe/objective.rst +++ b/doc/OnlineDocs/explanation/analysis/doe/objective.rst @@ -5,4 +5,20 @@ Objective Options .. note:: - Detailed descriptions and example code for the objective options in Pyomo.DoE will be added in a future update. \ No newline at end of file + Detailed descriptions and example code for the objective options in Pyomo.DoE will be added in a future update. + +Grey-box Hessian interface +-------------------------- + +When using ``use_grey_box_objective=True``, the FIM metric is represented by +``FIMExternalGreyBox``. Its ``evaluate_hessian_outputs()`` method returns the +lower-triangular sparse Hessian multiplied by the output-constraint multiplier, +as required by the ``ExternalGreyBoxModel`` interface. The solver supplies this +multiplier through ``set_output_constraint_multipliers()`` when assembling the +Hessian of the Lagrangian. + +For direct evaluation outside a solver, the multiplier defaults to one, giving +the unweighted metric Hessian. Call ``set_output_constraint_multipliers([1.0])`` +to restore that behavior after a different multiplier has been set. Multipliers +do not change the metric value or its Jacobian; the pseudo-A-optimal metric is +linear in the FIM and has a zero Hessian for every multiplier. diff --git a/pyomo/contrib/doe/doe.py b/pyomo/contrib/doe/doe.py index 8c5f5f86ada..a9cfcd5ccab 100644 --- a/pyomo/contrib/doe/doe.py +++ b/pyomo/contrib/doe/doe.py @@ -279,13 +279,13 @@ def run_doe(self, model=None, results_file=None): Parameters ---------- model: model to run the DoE, default: None (self.model) - results_file: string name of the file path to save the results + results_file: string or pathlib.Path specifying where to save the results to in the form of a .json file default: None --> don't save """ # Check results file name if results_file is not None: - if type(results_file) not in [pathlib.Path, str]: + if not isinstance(results_file, (pathlib.Path, str)): raise ValueError( "``results_file`` must be either a Path object or a string." ) @@ -647,6 +647,83 @@ def compute_FIM(self, model=None, method="sequential"): return self._computed_FIM + def _adjust_bounds_for_fd_perturbation(self, unknown_parameters): + """ + Widen the declared bounds of unknown-parameter Vars when a finite + difference perturbation would fall outside them. + + Pyomo.DoE estimates the sensitivity matrix (and FIM) by perturbing + each unknown parameter to ``nominal * (1 + diff)`` where ``diff`` is + ``+step`` and/or ``-step`` depending on the finite difference formula + (central perturbs both directions, forward only ``+step``, backward + only ``-step``). When a parameter's nominal value sits at or near one + of its declared Var bounds, the perturbed value can fall outside those + bounds. Because the unknown parameters are *fixed* during the finite + difference solves, the declared bounds have no mathematical effect on + the (square) solves -- but ``set_value`` would otherwise emit a + low-level ``W1002`` warning for every offending scenario. + + To replace that warning storm with a single, intentional message, this + method widens the affected bounds just enough to contain every + perturbed value and logs one warning per affected parameter, + identifying the parameter, its original bounds, the perturbation + range, and the adjusted bounds. The computed sensitivities and FIM are + unchanged; only the bound bookkeeping and warning clarity differ. + + Parameters + ---------- + unknown_parameters: mapping (e.g. the ``unknown_parameters`` Suffix) + from each unknown-parameter Var to its nominal value. + + Returns + ------- + list + List of ``(param, lb, ub)`` tuples giving each adjusted Var and its + original bounds, so the caller may restore them after the finite + difference computation if appropriate. + """ + original_bounds = [] + for param, nominal in unknown_parameters.items(): + lb, ub = param.lb, param.ub + # Nothing to violate if the Var is unbounded on both sides + if lb is None and ub is None: + continue + + # Perturbed values this parameter will take across the FD scenarios + if self.fd_formula == FiniteDifferenceStep.central: + perturbed = [nominal * (1 + self.step), nominal * (1 - self.step)] + elif self.fd_formula == FiniteDifferenceStep.forward: + perturbed = [nominal * (1 + self.step)] + elif self.fd_formula == FiniteDifferenceStep.backward: + perturbed = [nominal * (1 - self.step)] + else: + continue + + new_lb, new_ub = lb, ub + if lb is not None and min(perturbed) < lb: + new_lb = min(perturbed) + if ub is not None and max(perturbed) > ub: + new_ub = max(perturbed) + + # No adjustment needed if every perturbation is within bounds + if new_lb == lb and new_ub == ub: + continue + + self.logger.warning( + "Finite difference perturbation of unknown parameter '%s' " + "(perturbed range [%s, %s]) falls outside its declared bounds " + "(%s, %s). Widening the bounds to (%s, %s) for the finite " + "difference computation. The unknown parameters are fixed " + "during these solves, so this does not change the computed " + "sensitivities or FIM." + % (param.name, min(perturbed), max(perturbed), lb, ub, new_lb, new_ub) + ) + original_bounds.append((param, param.lower, param.upper)) + param.setlb(new_lb) + param.setub(new_ub) + + return original_bounds + # Use a sequential method to get the FIM def _sequential_FIM(self, model=None): """ @@ -697,56 +774,62 @@ def _sequential_FIM(self, model=None): for comp in model.experiment_inputs: comp.fix() - measurement_vals = [] - # In a loop..... - # Calculate measurement values for each scenario - for s in model.scenarios: - # Perturbation to be (1 + diff) * param_value - if self.fd_formula == FiniteDifferenceStep.central: - diff = self.step * ( - (-1) ** s - ) # Positive perturbation, even; negative, odd - elif self.fd_formula == FiniteDifferenceStep.backward: - diff = ( - self.step * -1 * (s != 0) - ) # Backward always negative perturbation; 0 at s = 0 - elif self.fd_formula == FiniteDifferenceStep.forward: - diff = self.step * (s != 0) # Forward always positive; 0 at s = 0 - - # If we are doing forward/backward, no change for s=0 - skip_param_update = ( - self.fd_formula - in [FiniteDifferenceStep.forward, FiniteDifferenceStep.backward] - ) and (s == 0) - if not skip_param_update: - param = model.parameter_scenarios[s] - # Update parameter values for the given finite difference scenario - param.set_value(model.unknown_parameters[param] * (1 + diff)) - else: - continue + # Widen any unknown-parameter bounds that the finite difference + # perturbations would violate (see _adjust_bounds_for_fd_perturbation). + # The original bounds are restored after the FD computation below. + original_param_bounds = self._adjust_bounds_for_fd_perturbation( + model.unknown_parameters + ) - # Simulate the model + def solve_and_record(context): try: res = self.solver.solve(model, tee=self.tee) pyo.assert_optimal_termination(res) - except: - # TODO: Make error message more verbose, - # (i.e., add unknown parameter values so the user - # can try to solve the model instance outside of - # the pyomo.DoE framework) + except Exception as err: raise RuntimeError( - "Model from experiment did not solve appropriately." - " Make sure the model is well-posed." - ) + "Model from experiment did not solve appropriately during " + f"{context}. Make sure the model is well-posed." + ) from err + return [pyo.value(output) for output in model.experiment_outputs] - # Reset value of parameter to default value - # before computing finite difference perturbation - param.set_value(model.unknown_parameters[param]) + measurement_vals = [] + try: + # Warm-start perturbations from the solved nominal model. One-sided + # formulas also need the nominal response as their first column. + for param, nominal in model.unknown_parameters.items(): + param.set_value(nominal) + nominal_outputs = solve_and_record("the nominal solve") + if self.fd_formula != FiniteDifferenceStep.central: + measurement_vals.append(nominal_outputs) + + for s in model.scenarios: + if self.fd_formula == FiniteDifferenceStep.central: + diff = self.step * (-1) ** s + elif s == 0: + # The nominal response was already computed above. + continue + elif self.fd_formula == FiniteDifferenceStep.forward: + diff = self.step + else: + diff = -self.step - # Extract the measurement values for the scenario and append - measurement_vals.append( - [pyo.value(k) for k, v in model.experiment_outputs.items()] - ) + param = model.parameter_scenarios[s] + try: + param.set_value(model.unknown_parameters[param] * (1 + diff)) + # Read outputs before resetting the parameter: Expressions + # can depend directly on its perturbed value. + measurement_vals.append( + solve_and_record( + f"finite difference scenario {s} ({param.name})" + ) + ) + finally: + param.set_value(model.unknown_parameters[param]) + finally: + # Restore bounds even when a nominal or perturbed solve fails. + for param, lb, ub in original_param_bounds: + param.setlb(lb) + param.setub(ub) # Use the measurement outputs to make the Q matrix measurement_vals_np = np.array(measurement_vals).T @@ -772,11 +855,11 @@ def _sequential_FIM(self, model=None): col_2 = 2 * i + 1 curr_step *= 2 elif self.fd_formula == FiniteDifferenceStep.forward: - col_1 = i + col_1 = i + 1 col_2 = 0 elif self.fd_formula == FiniteDifferenceStep.backward: col_1 = 0 - col_2 = i + col_2 = i + 1 # If scale_nominal_param_value is active, scale # by nominal parameter value (v) @@ -1293,6 +1376,15 @@ def _generate_scenario_blocks(self, model=None): for comp in model.base_model.experiment_inputs: comp.unfix() + # Widen any unknown-parameter bounds that the finite difference + # perturbations would violate (see _adjust_bounds_for_fd_perturbation). + # This is done on ``base_model`` *before* the scenario blocks are cloned + # from it, so each scenario block inherits the widened bounds and no + # per-scenario W1002 warnings are emitted. The bounds are intentionally + # not restored: each scenario block permanently holds its perturbed + # (fixed) parameter value, which must remain within bounds. + self._adjust_bounds_for_fd_perturbation(model.base_model.unknown_parameters) + # Generate blocks for finite difference scenarios def build_block_scenarios(b, s): # Generate model for the finite difference scenario @@ -2764,7 +2856,7 @@ def get_experiment_output_values(self, model=None): # Gets the measurement error values from an existing model def get_measurement_error_values(self, model=None): """ - Gets the experiment output values (sigma) + Gets the measurement error values (sigma) from the model specified. Parameters @@ -2789,11 +2881,11 @@ def get_measurement_error_values(self, model=None): ) sigma_vals = [ - pyo.value(k) + pyo.value(v) for k, v in model.scenario_blocks[0].measurement_error.items() ] else: - sigma_vals = [pyo.value(k) for k, v in model.measurement_error.items()] + sigma_vals = [pyo.value(v) for k, v in model.measurement_error.items()] return sigma_vals diff --git a/pyomo/contrib/doe/grey_box_utilities.py b/pyomo/contrib/doe/grey_box_utilities.py index 90d20702199..78b3eb59c6a 100644 --- a/pyomo/contrib/doe/grey_box_utilities.py +++ b/pyomo/contrib/doe/grey_box_utilities.py @@ -128,6 +128,11 @@ def __init__(self, doe_object, objective_option="determinant", logger_level=None ) self._n_inputs = len(self._input_values) + # The solver updates this value before requesting the Hessian of the + # Lagrangian. A unit default preserves the unweighted output Hessian + # for direct users of the external model. + self._output_con_mult_values = np.ones(self.n_outputs(), dtype=np.float64) + def _get_FIM(self): # Grabs the current FIM subject # to the input values. @@ -375,11 +380,11 @@ def set_equality_constraint_multipliers(self, eq_con_multiplier_values): ) def set_output_constraint_multipliers(self, output_con_multiplier_values): - # TODO: Do any objectives require constraints? - # Assert length matches - self._output_con_mult_values = np.asarray( + output_con_multiplier_values = np.asarray( output_con_multiplier_values, dtype=np.float64 ) + assert self.n_outputs() == len(output_con_multiplier_values) + self._output_con_mult_values = output_con_multiplier_values def evaluate_hessian_equality_constraints(self): # Returns coo_matrix of the correct shape @@ -844,8 +849,11 @@ def evaluate_hessian_outputs(self): else: ObjectiveLib(self.objective_option) - # Returns coo_matrix of the correct shape - hes = np.asarray(hess_vals) - return scipy.sparse.coo_matrix( - (hes, (hess_rows, hess_cols)), shape=(self._n_inputs, self._n_inputs) + # The ExternalGreyBoxModel contract requires the Hessian of the + # output constraint contribution to the Lagrangian, not the raw + # Hessian of the output itself. + output_hessian = scipy.sparse.coo_matrix( + (np.asarray(hess_vals), (hess_rows, hess_cols)), + shape=(self._n_inputs, self._n_inputs), ) + return self._output_con_mult_values[0] * output_hessian diff --git a/pyomo/contrib/doe/tests/test_doe_build.py b/pyomo/contrib/doe/tests/test_doe_build.py index 333ac1669ef..661811de101 100644 --- a/pyomo/contrib/doe/tests/test_doe_build.py +++ b/pyomo/contrib/doe/tests/test_doe_build.py @@ -462,7 +462,7 @@ def test_get_measurement_error_without_blocks(self): count = 0 for k, v in doe_obj.compute_FIM_model.measurement_error.items(): - self.assertEqual(pyo.value(k), stuff[count]) + self.assertEqual(pyo.value(v), stuff[count]) count += 1 def test_get_unknown_parameters_without_blocks(self): diff --git a/pyomo/contrib/doe/tests/test_doe_regressions.py b/pyomo/contrib/doe/tests/test_doe_regressions.py new file mode 100644 index 00000000000..27a7fb41d12 --- /dev/null +++ b/pyomo/contrib/doe/tests/test_doe_regressions.py @@ -0,0 +1,261 @@ +# ____________________________________________________________________________________ +# +# Pyomo: Python Optimization Modeling Objects +# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC +# Under the terms of Contract DE-NA0003525 with National Technology and Engineering +# Solutions of Sandia, LLC, the U.S. Government retains certain rights in this +# software. This software is distributed under the 3-clause BSD License. +# ____________________________________________________________________________________ + +import json +import logging +from io import StringIO +from pathlib import Path +from tempfile import TemporaryDirectory + +from pyomo.common.dependencies import numpy as np, numpy_available, scipy_available +from pyomo.common.log import LoggingIntercept +import pyomo.common.unittest as unittest +import pyomo.environ as pyo +from pyomo.contrib.doe import DesignOfExperiments +from pyomo.opt import SolverResults, SolverStatus, TerminationCondition + + +class LinearExperiment: + """Two identifiable parameters, including a negative nominal value.""" + + def __init__(self, bounded=False): + self.bounded = bounded + self.model = None + + def get_labeled_model(self): + if self.model is not None: + return self.model + m = pyo.ConcreteModel() + m.design = pyo.Var(initialize=2, bounds=(1, 3)) + m.theta = pyo.Var([0, 1], initialize={0: 3, 1: -4}) + m.theta.fix() + if self.bounded: + m.theta[0].setlb(3) + m.theta[0].setub(6) + m.theta[1].setlb(-8) + m.theta[1].setub(-4) + m.y = pyo.Var(initialize=0) + m.z = pyo.Var(initialize=0) + m.response_y = pyo.Constraint(expr=m.y == m.design * m.theta[0] + m.theta[1]) + m.response_z = pyo.Constraint(expr=m.z == m.theta[0] - 2 * m.theta[1]) + # Must be evaluated before the perturbed parameter is reset. + m.expression_output = pyo.Expression(expr=m.theta[0] + 3 * m.theta[1]) + m.sigma = pyo.Param(initialize=1.5, mutable=True) + m.experiment_inputs = pyo.Suffix(direction=pyo.Suffix.LOCAL) + m.experiment_inputs[m.design] = None + m.unknown_parameters = pyo.Suffix(direction=pyo.Suffix.LOCAL) + m.unknown_parameters.update((v, pyo.value(v)) for v in m.theta.values()) + m.experiment_outputs = pyo.Suffix(direction=pyo.Suffix.LOCAL) + m.measurement_error = pyo.Suffix(direction=pyo.Suffix.LOCAL) + for output, sigma in ((m.y, 0.5), (m.z, 2.0), (m.expression_output, 1.5)): + m.experiment_outputs[output] = None + m.measurement_error[output] = sigma + self.model = m + return m + + +class ExactLinearSolver: + """Record each fixed-design solve and evaluate the linear response exactly.""" + + def __init__(self, fail_on=None, raise_error=False): + self.calls = [] + self.bounds = [] + self.fail_on = fail_on + self.raise_error = raise_error + + def solve(self, model, **kwds): + assert model.design.fixed + assert all(v.fixed for v in model.theta.values()) + theta = [pyo.value(v) for v in model.theta.values()] + self.calls.append(theta) + self.bounds.append([v.bounds for v in model.theta.values()]) + model.y.set_value(pyo.value(model.design) * theta[0] + theta[1]) + model.z.set_value(theta[0] - 2 * theta[1]) + result = SolverResults() + result.solver.status = SolverStatus.ok + result.solver.termination_condition = TerminationCondition.optimal + if len(self.calls) == self.fail_on: + if self.raise_error: + raise ValueError("test solver failure") + result.solver.termination_condition = TerminationCondition.infeasible + return result + + +def make_doe(formula="central", bounded=False, scaled=False, solver=None): + return DesignOfExperiments( + experiment=LinearExperiment(bounded), + solver=solver if solver is not None else ExactLinearSolver(), + fd_formula=formula, + step=0.01, + scale_nominal_param_value=scaled, + objective_option="zero", + ) + + +@unittest.skipIf(not (numpy_available and scipy_available), "Requires numpy and scipy") +class TestDoEFiniteDifferenceAndReporting(unittest.TestCase): + def test_sequential_formulas(self): + expected_calls = { + "central": [[3, -4], [3.03, -4], [2.97, -4], [3, -4.04], [3, -3.96]], + "forward": [[3, -4], [3.03, -4], [3, -4.04]], + "backward": [[3, -4], [2.97, -4], [3, -3.96]], + } + for formula in expected_calls: + for scaled in (False, True): + with self.subTest(formula=formula, scaled=scaled): + doe = make_doe(formula, scaled=scaled) + fim = doe.compute_FIM() + jac = np.array([[2.0, 1.0], [1.0, -2.0], [1.0, 3.0]]) + if scaled: + jac *= [3, -4] + np.testing.assert_allclose( + doe.solver.calls, expected_calls[formula] + ) + np.testing.assert_allclose(doe.seq_jac, jac) + np.testing.assert_allclose( + fim, jac.T @ np.diag([4, 0.25, 1 / 1.5**2]) @ jac + ) + np.testing.assert_allclose( + [pyo.value(v) for v in doe.compute_FIM_model.theta.values()], + [3, -4], + ) + + def test_bounds_sequential_and_simultaneous(self): + for formula in ("central", "forward", "backward"): + for simultaneous in (False, True): + with self.subTest(formula=formula, simultaneous=simultaneous): + doe = make_doe(formula, bounded=True) + output = StringIO() + with LoggingIntercept(output, "pyomo", logging.WARNING): + if simultaneous: + doe.create_doe_model() + else: + fim = doe.compute_FIM() + # Forward perturbations move both signed parameters inward. + warning_count = 0 if formula == "forward" else 2 + self.assertEqual( + output.getvalue().count("Widening the bounds"), warning_count + ) + self.assertNotIn("W1002", output.getvalue()) + for values, bounds in zip(doe.solver.calls, doe.solver.bounds): + for value, (lb, ub) in zip(values, bounds): + self.assertGreaterEqual(value, lb) + self.assertLessEqual(value, ub) + if simultaneous: + for block in doe.model.scenario_blocks.values(): + for param in block.theta.values(): + self.assertGreaterEqual(pyo.value(param), param.lb) + self.assertLessEqual(pyo.value(param), param.ub) + else: + self.assertEqual(doe.compute_FIM_model.theta[0].bounds, (3, 6)) + self.assertEqual( + doe.compute_FIM_model.theta[1].bounds, (-8, -4) + ) + np.testing.assert_allclose(fim, make_doe(formula).compute_FIM()) + # The experiment's source model is not mutated. + source = doe.experiment.get_labeled_model() + self.assertEqual(source.theta[0].bounds, (3, 6)) + + def test_one_sided_and_interior_bounds(self): + bound_cases = ( + ((None, 3), (-4, None)), + ((3, None), (None, -4)), + ((None, None), (None, None)), + ((0, 6), (-8, 0)), + ((3, 3), (-4, -4)), + ) + for formula in ("central", "forward", "backward"): + for bounds in bound_cases: + for simultaneous in (False, True): + with self.subTest( + formula=formula, bounds=bounds, simultaneous=simultaneous + ): + doe = make_doe(formula) + source = doe.experiment.get_labeled_model() + for param, (lb, ub) in zip(source.theta.values(), bounds): + param.setlb(lb) + param.setub(ub) + output = StringIO() + with LoggingIntercept(output, "pyomo", logging.WARNING): + if simultaneous: + doe.create_doe_model() + else: + doe.compute_FIM() + self.assertNotIn("W1002", output.getvalue()) + for values, solve_bounds in zip( + doe.solver.calls, doe.solver.bounds + ): + for value, (lb, ub) in zip(values, solve_bounds): + if lb is not None: + self.assertGreaterEqual(value, lb) + if ub is not None: + self.assertLessEqual(value, ub) + self.assertEqual( + tuple(v.bounds for v in source.theta.values()), bounds + ) + if not simultaneous: + self.assertEqual( + tuple( + v.bounds + for v in doe.compute_FIM_model.theta.values() + ), + bounds, + ) + + def test_sequential_preserves_bound_expressions(self): + doe = make_doe() + model = doe.experiment.get_labeled_model() + model.lower = pyo.Param(initialize=3, mutable=True) + model.theta[0].setlb(model.lower) + doe.compute_FIM(model=model) + self.assertIs(model.theta[0].lower, model.lower) + model.lower.set_value(2) + self.assertEqual(model.theta[0].lb, 2) + + def test_sequential_failure_restores_parameters_and_bounds(self): + for formula in ("central", "forward", "backward"): + for fail_on in (1, 2): + for raise_error in (False, True): + with self.subTest( + formula=formula, fail_on=fail_on, raise_error=raise_error + ): + solver = ExactLinearSolver(fail_on, raise_error) + doe = make_doe(formula, bounded=True, solver=solver) + with self.assertRaisesRegex(RuntimeError, "nominal|scenario"): + doe.compute_FIM() + model = doe.compute_FIM_model + np.testing.assert_allclose( + [pyo.value(v) for v in model.theta.values()], [3, -4] + ) + self.assertEqual(model.theta[0].bounds, (3, 6)) + self.assertEqual(model.theta[1].bounds, (-8, -4)) + self.assertTrue(all(v.fixed for v in model.theta.values())) + + def test_measurement_errors_flat_and_scenario_models(self): + doe = make_doe() + model = doe.experiment.get_labeled_model() + model.measurement_error[model.expression_output] = model.sigma + self.assertEqual(doe.get_measurement_error_values(model), [0.5, 2.0, 1.5]) + doe.model.scenario_blocks = pyo.Block([0]) + doe.model.scenario_blocks[0].transfer_attributes_from(model.clone()) + self.assertEqual(doe.get_measurement_error_values(), [0.5, 2.0, 1.5]) + + @unittest.skipIf(not pyo.SolverFactory("ipopt").available(), "Requires ipopt") + def test_results_file_path_and_string(self): + with TemporaryDirectory() as directory: + for path_type in (Path, str): + with self.subTest(path_type=path_type): + filename = path_type(Path(directory) / "results.json") + doe = make_doe(solver=pyo.SolverFactory("ipopt")) + doe.run_doe(results_file=filename) + with open(filename) as stream: + results = json.load(stream) + self.assertEqual(results["Measurement Error"], [0.5, 2.0, 1.5]) + self.assertEqual(results["FIM"], doe.results["FIM"]) + self.assertEqual(results["Termination Condition"], "optimal") diff --git a/pyomo/contrib/doe/tests/test_greybox.py b/pyomo/contrib/doe/tests/test_greybox.py index f1bcbbe9f64..d051b3e9b5a 100644 --- a/pyomo/contrib/doe/tests/test_greybox.py +++ b/pyomo/contrib/doe/tests/test_greybox.py @@ -9,6 +9,8 @@ import copy import itertools import json +import logging +from types import SimpleNamespace import os.path from pyomo.common.dependencies import ( @@ -430,6 +432,89 @@ def make_greybox_and_doe_objects_rooney_biegler(objective_option): cyipopt_call_working = False +class TestFIMExternalGreyBoxMultipliers(unittest.TestCase): + """Exercise the Hessian interface without an external NLP solver.""" + + def make_greybox(self, objective): + doe = SimpleNamespace( + model=SimpleNamespace(parameter_names=range(4)), + fim_initial=testing_matrix.copy(), + logger=logging.getLogger(__name__), + ) + return FIMExternalGreyBox(doe, objective_option=objective) + + def test_output_hessian_multipliers(self): + for objective in ( + "trace", + "determinant", + "minimum_eigenvalue", + "condition_number", + "pseudo_trace", + ): + with self.subTest(objective=objective): + greybox = self.make_greybox(objective) + default_hessian = greybox.evaluate_hessian_outputs() + outputs = greybox.evaluate_outputs().copy() + jacobian = greybox.evaluate_jacobian_outputs().toarray().copy() + greybox.set_output_constraint_multipliers([1.0]) + unit_hessian = greybox.evaluate_hessian_outputs() + np.testing.assert_allclose( + default_hessian.toarray(), unit_hessian.toarray() + ) + if objective == "pseudo_trace": + np.testing.assert_array_equal(unit_hessian.toarray(), 0) + else: + self.assertGreater(np.linalg.norm(unit_hessian.data), 0) + + # Repeated updates must replace, not accumulate, the multiplier. + for multiplier in (0.0, -2.5, 3.0, 1.0): + with self.subTest(multiplier=multiplier): + greybox.set_output_constraint_multipliers([multiplier]) + hessian = greybox.evaluate_hessian_outputs() + self.assertEqual(hessian.format, "coo") + self.assertEqual(hessian.shape, unit_hessian.shape) + np.testing.assert_array_equal(hessian.row, unit_hessian.row) + np.testing.assert_array_equal(hessian.col, unit_hessian.col) + self.assertTrue(np.all(hessian.row >= hessian.col)) + np.testing.assert_allclose( + hessian.toarray(), multiplier * unit_hessian.toarray() + ) + # Multipliers weight the Hessian contribution only. + np.testing.assert_allclose(greybox.evaluate_outputs(), outputs) + np.testing.assert_allclose( + greybox.evaluate_jacobian_outputs().toarray(), jacobian + ) + + def test_weighted_hessian_matches_finite_difference(self): + for objective in ( + "trace", + "determinant", + "minimum_eigenvalue", + "condition_number", + ): + with self.subTest(objective=objective): + greybox = self.make_greybox(objective) + numerical = get_numerical_second_derivative(greybox) + greybox.set_output_constraint_multipliers([-2.5]) + lower = greybox.evaluate_hessian_outputs().toarray() + symmetric = lower + lower.T - np.diag(np.diag(lower)) + np.testing.assert_allclose( + symmetric, -2.5 * numerical, rtol=1e-4, atol=2.5e-4 + ) + + def test_output_multiplier_length(self): + greybox = self.make_greybox("trace") + greybox.set_output_constraint_multipliers([-2.5]) + expected = greybox.evaluate_hessian_outputs().toarray() + for multipliers in ([], [1.0, 2.0]): + with self.subTest(multipliers=multipliers): + with self.assertRaises(AssertionError): + greybox.set_output_constraint_multipliers(multipliers) + np.testing.assert_allclose( + greybox.evaluate_hessian_outputs().toarray(), expected + ) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' command is not available") @unittest.skipIf(not numpy_available, "Numpy is not available") @unittest.skipIf(not scipy_available, "scipy is not available") From 84bf0aac792ba735d878e14453231dc34c0aad47 Mon Sep 17 00:00:00 2001 From: Alex Dowling Date: Fri, 25 Sep 2026 09:37:40 -0400 Subject: [PATCH 2/7] Document DoE regression helpers and validate finite differences with IPOPT Add rationale for deterministic solve-order and failure-injection tests, expand real-solver coverage across formulas and scaling modes, and document the Hessian interface. Developed with Codex assistance. --- pyomo/contrib/doe/doe.py | 25 ++------ pyomo/contrib/doe/grey_box_utilities.py | 14 +++++ .../contrib/doe/tests/test_doe_regressions.py | 62 ++++++++++++++++++- pyomo/contrib/doe/tests/test_greybox.py | 4 ++ 4 files changed, 85 insertions(+), 20 deletions(-) diff --git a/pyomo/contrib/doe/doe.py b/pyomo/contrib/doe/doe.py index a9cfcd5ccab..6346b98cce5 100644 --- a/pyomo/contrib/doe/doe.py +++ b/pyomo/contrib/doe/doe.py @@ -652,28 +652,14 @@ def _adjust_bounds_for_fd_perturbation(self, unknown_parameters): Widen the declared bounds of unknown-parameter Vars when a finite difference perturbation would fall outside them. - Pyomo.DoE estimates the sensitivity matrix (and FIM) by perturbing - each unknown parameter to ``nominal * (1 + diff)`` where ``diff`` is - ``+step`` and/or ``-step`` depending on the finite difference formula - (central perturbs both directions, forward only ``+step``, backward - only ``-step``). When a parameter's nominal value sits at or near one - of its declared Var bounds, the perturbed value can fall outside those - bounds. Because the unknown parameters are *fixed* during the finite - difference solves, the declared bounds have no mathematical effect on - the (square) solves -- but ``set_value`` would otherwise emit a - low-level ``W1002`` warning for every offending scenario. - - To replace that warning storm with a single, intentional message, this - method widens the affected bounds just enough to contain every - perturbed value and logs one warning per affected parameter, - identifying the parameter, its original bounds, the perturbation - range, and the adjusted bounds. The computed sensitivities and FIM are - unchanged; only the bound bookkeeping and warning clarity differ. + Parameters are fixed during these solves. Widening bounds preserves + the requested perturbation and replaces repeated W1002 messages with + one explanatory warning per parameter. Parameters ---------- - unknown_parameters: mapping (e.g. the ``unknown_parameters`` Suffix) - from each unknown-parameter Var to its nominal value. + unknown_parameters : mapping + Map each unknown-parameter Var to its nominal value. Returns ------- @@ -782,6 +768,7 @@ def _sequential_FIM(self, model=None): ) def solve_and_record(context): + """Solve the current scenario and evaluate outputs before resetting it.""" try: res = self.solver.solve(model, tee=self.tee) pyo.assert_optimal_termination(res) diff --git a/pyomo/contrib/doe/grey_box_utilities.py b/pyomo/contrib/doe/grey_box_utilities.py index 78b3eb59c6a..460db578405 100644 --- a/pyomo/contrib/doe/grey_box_utilities.py +++ b/pyomo/contrib/doe/grey_box_utilities.py @@ -380,6 +380,13 @@ def set_equality_constraint_multipliers(self, eq_con_multiplier_values): ) def set_output_constraint_multipliers(self, output_con_multiplier_values): + """Set the single output-constraint multiplier used in the Hessian. + + Parameters + ---------- + output_con_multiplier_values : array_like + Length-one sequence containing the current output multiplier. + """ output_con_multiplier_values = np.asarray( output_con_multiplier_values, dtype=np.float64 ) @@ -392,6 +399,13 @@ def evaluate_hessian_equality_constraints(self): return None def evaluate_hessian_outputs(self): + """Return the multiplier-weighted Hessian of the FIM metric. + + Returns + ------- + scipy.sparse.coo_matrix + Lower triangle of the output Hessian contribution to the Lagrangian. + """ # Compute the hessian of the objective function with # respect to the fisher information matrix. Then, return # a coo_matrix that aligns with what IPOPT will expect. diff --git a/pyomo/contrib/doe/tests/test_doe_regressions.py b/pyomo/contrib/doe/tests/test_doe_regressions.py index 27a7fb41d12..75a60d54f11 100644 --- a/pyomo/contrib/doe/tests/test_doe_regressions.py +++ b/pyomo/contrib/doe/tests/test_doe_regressions.py @@ -7,6 +7,8 @@ # software. This software is distributed under the 3-clause BSD License. # ____________________________________________________________________________________ +"""Regression tests for finite differences, parameter bounds, and result reporting.""" + import json import logging from io import StringIO @@ -25,10 +27,12 @@ class LinearExperiment: """Two identifiable parameters, including a negative nominal value.""" def __init__(self, bounded=False): + """Optionally place each nominal parameter at a declared bound.""" self.bounded = bounded self.model = None def get_labeled_model(self): + """Return the cached linear model with DoE labels and three outputs.""" if self.model is not None: return self.model m = pyo.ConcreteModel() @@ -61,15 +65,23 @@ def get_labeled_model(self): class ExactLinearSolver: - """Record each fixed-design solve and evaluate the linear response exactly.""" + """Evaluate the linear response and record fixed-design solve inputs. + + This test double makes solve ordering and failure cleanup observable without + relying on solver convergence or external binaries. It does not replace DoE + calculations. Separate IPOPT tests check the same sensitivities and FIM + against their analytical values using the actual model constraints. + """ def __init__(self, fail_on=None, raise_error=False): + """Optionally fail on a one-based solve count, by status or exception.""" self.calls = [] self.bounds = [] self.fail_on = fail_on self.raise_error = raise_error def solve(self, model, **kwds): + """Record parameters and bounds, evaluate responses, and return status.""" assert model.design.fixed assert all(v.fixed for v in model.theta.values()) theta = [pyo.value(v) for v in model.theta.values()] @@ -88,6 +100,7 @@ def solve(self, model, **kwds): def make_doe(formula="central", bounded=False, scaled=False, solver=None): + """Construct a linear DoE using the requested formula, scaling, and solver.""" return DesignOfExperiments( experiment=LinearExperiment(bounded), solver=solver if solver is not None else ExactLinearSolver(), @@ -100,7 +113,10 @@ def make_doe(formula="central", bounded=False, scaled=False, solver=None): @unittest.skipIf(not (numpy_available and scipy_available), "Requires numpy and scipy") class TestDoEFiniteDifferenceAndReporting(unittest.TestCase): + """Check analytical sensitivities, bound cleanup, and serialized results.""" + def test_sequential_formulas(self): + """Check nominal-first solve order and analytical sensitivities for each formula.""" expected_calls = { "central": [[3, -4], [3.03, -4], [2.97, -4], [3, -4.04], [3, -3.96]], "forward": [[3, -4], [3.03, -4], [3, -4.04]], @@ -126,7 +142,46 @@ def test_sequential_formulas(self): [3, -4], ) + @unittest.skipIf(not pyo.SolverFactory("ipopt").available(), "Requires ipopt") + def test_sequential_formulas_with_ipopt(self): + """Validate all formulas against analytical derivatives using real solves.""" + for formula in ("central", "forward", "backward"): + for scaled in (False, True): + for bounded in (False, True): + with self.subTest(formula=formula, scaled=scaled, bounded=bounded): + doe = make_doe( + formula, + bounded=bounded, + scaled=scaled, + solver=pyo.SolverFactory("ipopt"), + ) + fim = doe.compute_FIM() + # Rows differentiate y, z, and the Expression output; + # columns correspond to theta[0] and theta[1]. + expected_jac = np.array([[2.0, 1.0], [1.0, -2.0], [1.0, 3.0]]) + if scaled: + expected_jac *= [3, -4] + expected_fim = ( + expected_jac.T + @ np.diag([4.0, 0.25, 1 / 1.5**2]) + @ expected_jac + ) + np.testing.assert_allclose( + doe.seq_jac, expected_jac, rtol=1e-7, atol=1e-9 + ) + np.testing.assert_allclose( + fim, expected_fim, rtol=1e-7, atol=1e-9 + ) + if bounded: + self.assertEqual( + doe.compute_FIM_model.theta[0].bounds, (3, 6) + ) + self.assertEqual( + doe.compute_FIM_model.theta[1].bounds, (-8, -4) + ) + def test_bounds_sequential_and_simultaneous(self): + """Check bound widening, warnings, and restoration in both DoE paths.""" for formula in ("central", "forward", "backward"): for simultaneous in (False, True): with self.subTest(formula=formula, simultaneous=simultaneous): @@ -163,6 +218,7 @@ def test_bounds_sequential_and_simultaneous(self): self.assertEqual(source.theta[0].bounds, (3, 6)) def test_one_sided_and_interior_bounds(self): + """Keep all solved perturbations inside adjusted bounds without changing the source.""" bound_cases = ( ((None, 3), (-4, None)), ((3, None), (None, -4)), @@ -209,6 +265,7 @@ def test_one_sided_and_interior_bounds(self): ) def test_sequential_preserves_bound_expressions(self): + """Preserve mutable bound expressions when restoring sequential bounds.""" doe = make_doe() model = doe.experiment.get_labeled_model() model.lower = pyo.Param(initialize=3, mutable=True) @@ -219,6 +276,7 @@ def test_sequential_preserves_bound_expressions(self): self.assertEqual(model.theta[0].lb, 2) def test_sequential_failure_restores_parameters_and_bounds(self): + """Restore nominal parameters and bounds after failed or interrupted solves.""" for formula in ("central", "forward", "backward"): for fail_on in (1, 2): for raise_error in (False, True): @@ -238,6 +296,7 @@ def test_sequential_failure_restores_parameters_and_bounds(self): self.assertTrue(all(v.fixed for v in model.theta.values())) def test_measurement_errors_flat_and_scenario_models(self): + """Return suffix values for both supported model structures.""" doe = make_doe() model = doe.experiment.get_labeled_model() model.measurement_error[model.expression_output] = model.sigma @@ -248,6 +307,7 @@ def test_measurement_errors_flat_and_scenario_models(self): @unittest.skipIf(not pyo.SolverFactory("ipopt").available(), "Requires ipopt") def test_results_file_path_and_string(self): + """Write valid JSON with correct measurement errors through Path and string inputs.""" with TemporaryDirectory() as directory: for path_type in (Path, str): with self.subTest(path_type=path_type): diff --git a/pyomo/contrib/doe/tests/test_greybox.py b/pyomo/contrib/doe/tests/test_greybox.py index d051b3e9b5a..76d9e1a0e80 100644 --- a/pyomo/contrib/doe/tests/test_greybox.py +++ b/pyomo/contrib/doe/tests/test_greybox.py @@ -436,6 +436,7 @@ class TestFIMExternalGreyBoxMultipliers(unittest.TestCase): """Exercise the Hessian interface without an external NLP solver.""" def make_greybox(self, objective): + """Construct a metric wrapper around a known positive-definite FIM.""" doe = SimpleNamespace( model=SimpleNamespace(parameter_names=range(4)), fim_initial=testing_matrix.copy(), @@ -444,6 +445,7 @@ def make_greybox(self, objective): return FIMExternalGreyBox(doe, objective_option=objective) def test_output_hessian_multipliers(self): + """Preserve sparse structure while scaling each metric Hessian by its multiplier.""" for objective in ( "trace", "determinant", @@ -486,6 +488,7 @@ def test_output_hessian_multipliers(self): ) def test_weighted_hessian_matches_finite_difference(self): + """Compare weighted Hessians against numerical second derivatives.""" for objective in ( "trace", "determinant", @@ -503,6 +506,7 @@ def test_weighted_hessian_matches_finite_difference(self): ) def test_output_multiplier_length(self): + """Reject invalid multiplier lengths without replacing the last valid value.""" greybox = self.make_greybox("trace") greybox.set_output_constraint_multipliers([-2.5]) expected = greybox.evaluate_hessian_outputs().toarray() From 57348c68990495077c88d4aacd4b882b6e9a7d67 Mon Sep 17 00:00:00 2001 From: Alex Dowling Date: Fri, 25 Sep 2026 10:08:27 -0400 Subject: [PATCH 3/7] Fix DoE Expression sensitivities and initialize FIM from solved scenarios Apply the chain rule to k_aug outputs, reject missing unfixed sensitivities, and retain direct parameter derivatives. Derive default Jacobian/FIM values from solved scenarios while preserving explicit initial arrays and live scenario references. Add analytical, IPOPT, and availability-gated k_aug regressions plus documentation. Developed with Codex assistance. --- .../explanation/analysis/doe/guide.rst | 35 ++++ pyomo/contrib/doe/doe.py | 163 ++++++++++++++--- pyomo/contrib/doe/tests/test_doe_build.py | 32 +++- .../contrib/doe/tests/test_doe_regressions.py | 170 ++++++++++++++++++ pyomo/contrib/doe/tests/test_greybox.py | 2 + pyomo/contrib/doe/tests/test_kaug_outputs.py | 165 +++++++++++++++++ 6 files changed, 534 insertions(+), 33 deletions(-) create mode 100644 pyomo/contrib/doe/tests/test_kaug_outputs.py diff --git a/doc/OnlineDocs/explanation/analysis/doe/guide.rst b/doc/OnlineDocs/explanation/analysis/doe/guide.rst index 953f99a1328..82e1bac1b15 100644 --- a/doc/OnlineDocs/explanation/analysis/doe/guide.rst +++ b/doc/OnlineDocs/explanation/analysis/doe/guide.rst @@ -255,3 +255,38 @@ JSON results. The ``"Measurement Error"`` field and ``get_measurement_error_values()`` report the standard deviations stored as values in the ``measurement_error`` suffix, in suffix order, rather than the corresponding measured output values. + +Expression measurements with k_aug +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``compute_FIM(method="kaug")`` supports measurements labeled with either Vars +or Expressions. Expression sensitivities use the chain rule at the solved +model state, combining output derivatives with the variable sensitivities +returned by k_aug. Direct dependence on unknown parameters is included even +when those parameters are fixed in the experiment model. Ordinary fixed +variables and constant Expressions contribute zero sensitivity. An unfixed +dependency missing from the k_aug sensitivity columns raises an error instead +of silently contributing a zero row. Expressions must support Pyomo's numeric +differentiation. + +The k_aug path requires working ``ipopt``, ``k_aug``, and ``dot_sens`` executables. +The solver-backed Expression regression can be run on an equipped machine with:: + + python -m pytest pyomo/contrib/doe/tests/test_kaug_outputs.py -v + +Starting values from solved scenarios +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +``create_doe_model()`` initializes its default sensitivity matrix from the +already solved finite-difference scenarios. It then initializes the default +FIM using those sensitivities, measurement-error weights, and the prior FIM. +This avoids unnecessary Jacobian/FIM assembly residuals without additional +scenario solves. The fixed-design initialization solve in ``run_doe()`` remains +in place. + +Explicit constructor values for ``jac_initial`` and ``fim_initial`` are +preserved independently. If only ``jac_initial`` is supplied, the default FIM +is computed from that supplied Jacobian; if only ``fim_initial`` is supplied, +the Jacobian is still derived from solved scenarios. Objective auxiliaries use +the resulting FIM and the existing Cholesky regularization policy. Lower-only +FIM storage retains fixed zeros in the unused upper triangle. diff --git a/pyomo/contrib/doe/doe.py b/pyomo/contrib/doe/doe.py index 6346b98cce5..3e8d60e9881 100644 --- a/pyomo/contrib/doe/doe.py +++ b/pyomo/contrib/doe/doe.py @@ -40,6 +40,11 @@ scipy_available, ) +from pyomo.common.collections import ComponentMap +from pyomo.core.expr.calculus.derivatives import differentiate +from pyomo.core.expr.visitor import identify_variables, identify_mutable_parameters +from pyomo.util.calc_var_value import calculate_variable_from_constraint + from pyomo.common.errors import DeveloperError from pyomo.common.timing import TicTocTimer @@ -155,8 +160,11 @@ def __init__( here has been scaled by the parameter values) jac_initial: 2D numpy array as the initial values for the sensitivity matrix. + If None, derive values from the solved finite-difference scenarios. fim_initial: - 2D numpy array as the initial values for the FIM. + 2D numpy array as the initial values for the FIM. If None, compute + values from the initialized sensitivity matrix, measurement errors, + and prior FIM. Explicit constructor initial arrays are preserved. L_diagonal_lower_bound: Lower bound for the values of the lower triangular Cholesky factorization matrix. @@ -216,6 +224,8 @@ def __init__( # Set the initial values for the jacobian, fim, and L matrices self.jac_initial = jac_initial self.fim_initial = fim_initial + self._user_provided_jac_initial = jac_initial is not None + self._user_provided_fim_initial = fim_initial is not None # Set the lower bound on the Cholesky lower triangular matrix self.L_diagonal_lower_bound = L_diagonal_lower_bound @@ -875,6 +885,69 @@ def solve_and_record(context): # Compute and record FIM self.seq_FIM = self.seq_jac.T @ cov_y @ self.seq_jac + self.prior_FIM + def _extract_kaug_output_jacobian(self, model, sensitivities, column_names): + """Apply the chain rule to measurement outputs at the solved model state. + + Parameters + ---------- + model : ConcreteModel + Labeled experiment used to compute the k_aug sensitivities. + sensitivities : ndarray + Variable-by-parameter sensitivities in NL column order. + column_names : list of str + Variable names returned by the sensitivity toolbox. + + Returns + ------- + ndarray + Unscaled output-by-parameter Jacobian in suffix order. + + Raises + ------ + ValueError + If dimensions disagree or an unfixed output dependency has no + k_aug sensitivity. Only fixed non-parameter variables have zero + sensitivities by definition. + """ + n_parameters = len(model.unknown_parameters) + sensitivities = np.asarray(sensitivities) + if sensitivities.shape != (len(column_names), n_parameters): + raise ValueError("k_aug sensitivity dimensions do not match the model.") + + # Resolve external NL names once; use component identity thereafter. + variable_sensitivities = ComponentMap() + for i, name in enumerate(column_names): + component = model.find_component(name) + if component is not None: + variable_sensitivities[component] = sensitivities[i] + parameter_sensitivities = ComponentMap( + (parameter, row) + for parameter, row in zip(model.unknown_parameters, np.eye(n_parameters)) + ) + jacobian = np.zeros((len(model.experiment_outputs), n_parameters)) + for i, output in enumerate(model.experiment_outputs): + dependencies = list(identify_variables(output, include_fixed=True)) + dependencies.extend( + parameter + for parameter in identify_mutable_parameters(output) + if parameter in parameter_sensitivities + ) + partials = differentiate(output, wrt_list=dependencies) + for dependency, partial in zip(dependencies, partials): + if dependency in parameter_sensitivities: + row = parameter_sensitivities[dependency] + elif dependency.fixed: + continue + elif dependency in variable_sensitivities: + row = variable_sensitivities[dependency] + else: + raise ValueError( + f"No k_aug sensitivity for unfixed variable '{dependency.name}' " + f"in experiment output '{output.name}'." + ) + jacobian[i] += partial * row + return jacobian + # Use kaug to get FIM def _kaug_FIM(self, model=None): """ @@ -902,7 +975,8 @@ def _kaug_FIM(self, model=None): for comp in model.experiment_inputs: comp.fix() - self.solver.solve(model, tee=self.tee) + result = self.solver.solve(model, tee=self.tee) + pyo.assert_optimal_termination(result) # Probe the solved model for dsdp results (sensitivities s.t. parameters) params_dict = {k.name: v for k, v in model.unknown_parameters.items()} @@ -913,26 +987,7 @@ def _kaug_FIM(self, model=None): # analyze result dsdp_array = dsdp_re.toarray().T - # store dsdp returned - dsdp_extract = [] - # get right lines from results - measurement_index = [] - - # loop over measurement variables and their time points - for k, v in model.experiment_outputs.items(): - name = k.name - try: - kaug_no = col.index(name) - measurement_index.append(kaug_no) - # get right line of dsdp - dsdp_extract.append(dsdp_array[kaug_no]) - except: - # k_aug does not provide value for fixed variables - self.logger.debug("The variable is fixed: %s", name) - # produce the sensitivity for fixed variables - zero_sens = np.zeros(len(params_names)) - # for fixed variables, the sensitivity are a zero vector - dsdp_extract.append(zero_sens) + dsdp_extract = self._extract_kaug_output_jacobian(model, dsdp_array, col) # Extract and calculate sensitivity if scaled by constants or parameters. jac = [[] for k in params_names] @@ -1170,8 +1225,7 @@ def jacobian_rule(m, n, p): var_lo = cuid.find_component_on(m.scenario_blocks[s2]) param = m.parameter_scenarios[max(s1, s2)] - param_loc = pyo.ComponentUID(param).find_component_on(m.scenario_blocks[0]) - param_val = m.scenario_blocks[0].unknown_parameters[param_loc] + param_val = m.scenario_blocks[0].unknown_parameters[param] param_diff = param_val * fd_step_mult * self.step if self.scale_nominal_param_value: @@ -1257,6 +1311,61 @@ def fim_rule(m, p, q): if self.objective_option == ObjectiveLib.trace: model.fim_inv[p, q].fix(0.0) + self._initialize_fim_assembly_from_scenarios(model) + + def _initialize_fim_assembly_from_scenarios(self, model): + """Seed default assembly values from solved scenarios without solving again. + + Parameters + ---------- + model : ConcreteModel + DoE model with Jacobian and FIM constraints already constructed. + + Notes + ----- + Explicit constructor initial arrays are preserved independently. If only + the Jacobian is supplied, the default FIM is computed from that Jacobian. + Scenario states and variable fixed flags are not changed. + """ + if not self._user_provided_jac_initial: + for index, constraint in model.jacobian_constraint.items(): + calculate_variable_from_constraint( + model.sensitivity_jacobian[index], constraint + ) + self.jac_initial = np.array( + [ + [ + pyo.value(model.sensitivity_jacobian[n, p]) + for p in model.parameter_names + ] + for n in model.output_names + ] + ) + + if not self._user_provided_fim_initial: + # Evaluate information sums before upper-triangle symmetry equations. + names = list(model.parameter_names) + for i, p in enumerate(names): + for q in names[: i + 1]: + calculate_variable_from_constraint( + model.fim[p, q], model.fim_constraint[p, q] + ) + if not self.only_compute_fim_lower: + for i, p in enumerate(names): + for q in names[i + 1 :]: + model.fim[p, q].set_value(pyo.value(model.fim[q, p])) + self.fim_initial = self._get_fim_numpy(model) + + # Keep objective auxiliaries consistent with the resulting FIM. + if hasattr(model, "L"): + self._initialize_cholesky_from_fim(model) + elif hasattr(model, "fim_inv"): + inverse = np.linalg.pinv(self._get_fim_numpy(model)) + for i, p in enumerate(model.parameter_names): + for j, q in enumerate(model.parameter_names): + if not model.fim_inv[p, q].fixed: + model.fim_inv[p, q].set_value(inverse[i, j]) + # Create scenario block structure def _generate_scenario_blocks(self, model=None): """ @@ -1441,6 +1550,12 @@ def global_design_fixing(m, s): con_name, pyo.Constraint(model.scenarios, rule=global_design_fixing) ) + # Keep metadata attached to retained components before deleting the base. + for scenario, parameter in list(model.parameter_scenarios.items()): + model.parameter_scenarios[scenario] = pyo.ComponentUID( + parameter, context=model.base_model + ).find_component_on(model.scenario_blocks[0]) + # Clean up the base model used to generate the scenarios model.del_component(model.base_model) diff --git a/pyomo/contrib/doe/tests/test_doe_build.py b/pyomo/contrib/doe/tests/test_doe_build.py index 661811de101..ba26b4ec7bc 100644 --- a/pyomo/contrib/doe/tests/test_doe_build.py +++ b/pyomo/contrib/doe/tests/test_doe_build.py @@ -166,17 +166,21 @@ def test_rooney_biegler_fd_central_check_fd_eqns(self): diff = (-1) ** s * doe_obj.step param_val = pyo.value( - pyo.ComponentUID(param).find_component_on(model.scenario_blocks[s]) + pyo.ComponentUID( + param, context=model.scenario_blocks[0] + ).find_component_on(model.scenario_blocks[s]) ) param_val_from_step = model.scenario_blocks[0].unknown_parameters[ - pyo.ComponentUID(param).find_component_on(model.scenario_blocks[0]) + pyo.ComponentUID( + param, context=model.scenario_blocks[0] + ).find_component_on(model.scenario_blocks[0]) ] * (1 + diff) for k, v in model.scenario_blocks[s].unknown_parameters.items(): if pyo.ComponentUID( k, context=model.scenario_blocks[s] - ) == pyo.ComponentUID(param): + ) == pyo.ComponentUID(param, context=model.scenario_blocks[0]): continue other_param_val = pyo.value(k) @@ -205,18 +209,22 @@ def test_rooney_biegler_fd_backward_check_fd_eqns(self): param = model.parameter_scenarios[s] param_val = pyo.value( - pyo.ComponentUID(param).find_component_on(model.scenario_blocks[s]) + pyo.ComponentUID( + param, context=model.scenario_blocks[0] + ).find_component_on(model.scenario_blocks[s]) ) param_val_from_step = model.scenario_blocks[0].unknown_parameters[ - pyo.ComponentUID(param).find_component_on(model.scenario_blocks[0]) + pyo.ComponentUID( + param, context=model.scenario_blocks[0] + ).find_component_on(model.scenario_blocks[0]) ] * (1 + diff) self.assertAlmostEqual(param_val, param_val_from_step) for k, v in model.scenario_blocks[s].unknown_parameters.items(): if (s != 0) and pyo.ComponentUID( k, context=model.scenario_blocks[s] - ) == pyo.ComponentUID(param): + ) == pyo.ComponentUID(param, context=model.scenario_blocks[0]): continue other_param_val = pyo.value(k) @@ -243,18 +251,22 @@ def test_rooney_biegler_fd_forward_check_fd_eqns(self): param = model.parameter_scenarios[s] param_val = pyo.value( - pyo.ComponentUID(param).find_component_on(model.scenario_blocks[s]) + pyo.ComponentUID( + param, context=model.scenario_blocks[0] + ).find_component_on(model.scenario_blocks[s]) ) param_val_from_step = model.scenario_blocks[0].unknown_parameters[ - pyo.ComponentUID(param).find_component_on(model.scenario_blocks[0]) + pyo.ComponentUID( + param, context=model.scenario_blocks[0] + ).find_component_on(model.scenario_blocks[0]) ] * (1 + diff) self.assertAlmostEqual(param_val, param_val_from_step) for k, v in model.scenario_blocks[s].unknown_parameters.items(): if (s != 0) and pyo.ComponentUID( k, context=model.scenario_blocks[s] - ) == pyo.ComponentUID(param): + ) == pyo.ComponentUID(param, context=model.scenario_blocks[0]): continue other_param_val = pyo.value(k) @@ -604,6 +616,8 @@ def test_trace_initialization_consistency(self): ] DoE_args = get_standard_args(experiment, fd_method, obj_used) + # This test exercises the explicit identity initial guess. + DoE_args["fim_initial"] = np.eye(2) doe_obj = DesignOfExperiments(**DoE_args) doe_obj.create_doe_model() diff --git a/pyomo/contrib/doe/tests/test_doe_regressions.py b/pyomo/contrib/doe/tests/test_doe_regressions.py index 75a60d54f11..df15c76dd8b 100644 --- a/pyomo/contrib/doe/tests/test_doe_regressions.py +++ b/pyomo/contrib/doe/tests/test_doe_regressions.py @@ -9,6 +9,7 @@ """Regression tests for finite differences, parameter bounds, and result reporting.""" +import gc import json import logging from io import StringIO @@ -319,3 +320,172 @@ def test_results_file_path_and_string(self): self.assertEqual(results["Measurement Error"], [0.5, 2.0, 1.5]) self.assertEqual(results["FIM"], doe.results["FIM"]) self.assertEqual(results["Termination Condition"], "optimal") + + +@unittest.skipIf(not (numpy_available and scipy_available), "Requires numpy and scipy") +class TestDoEAssemblyInitialization(unittest.TestCase): + """Check assembled starting values without an extra initialization solve.""" + + def test_solved_scenario_initialization(self): + """Respect explicit arrays and derive defaults for every FD/storage mode.""" + prior = np.array([[2.0, 0.25], [0.25, 1.0]]) + supplied_jac = np.array([[3.0, 2.0], [2.0, 1.0], [-1.0, 4.0]]) + supplied_fim = np.array([[8.0, 1.0], [1.0, 7.0]]) + for formula in ("central", "forward", "backward"): + for scaled in (False, True): + for lower in (False, True): + for supplied in ("neither", "jac", "fim", "both"): + with self.subTest( + formula=formula, + scaled=scaled, + lower=lower, + supplied=supplied, + ): + solver = ExactLinearSolver() + jac_initial = ( + supplied_jac.copy() + if supplied in ("jac", "both") + else None + ) + fim_initial = ( + supplied_fim.copy() + if supplied in ("fim", "both") + else None + ) + doe = DesignOfExperiments( + experiment=LinearExperiment(), + solver=solver, + objective_option="trace", + fd_formula=formula, + step=0.01, + scale_nominal_param_value=scaled, + scale_constant_value=2.0, + prior_FIM=prior, + jac_initial=jac_initial, + fim_initial=fim_initial, + _only_compute_fim_lower=lower, + ) + doe.create_doe_model() + model = doe.model + expected_jac = ( + np.array([[2.0, 1.0], [1.0, -2.0], [1.0, 3.0]]) * 2.0 + ) + if scaled: + expected_jac *= [3.0, -4.0] + if jac_initial is not None: + expected_jac = supplied_jac + expected_fim = ( + expected_jac.T + @ np.diag([4.0, 0.25, 1 / 1.5**2]) + @ expected_jac + + prior + ) + if fim_initial is not None: + expected_fim = supplied_fim + jac = np.array( + [ + [ + pyo.value(model.sensitivity_jacobian[n, p]) + for p in model.parameter_names + ] + for n in model.output_names + ] + ) + np.testing.assert_allclose(jac, expected_jac) + np.testing.assert_allclose( + doe._get_fim_numpy(model), expected_fim + ) + np.testing.assert_allclose(doe.jac_initial, expected_jac) + np.testing.assert_allclose(doe.fim_initial, expected_fim) + self.assertEqual( + len(solver.calls), 5 if formula == "central" else 3 + ) + for block in model.scenario_blocks.values(): + self.assertAlmostEqual( + pyo.value(block.response_y.body), 0.0 + ) + self.assertAlmostEqual( + pyo.value(block.response_z.body), 0.0 + ) + for p in model.sensitivity_jacobian.values(): + self.assertFalse(p.fixed) + for i, p in enumerate(model.parameter_names): + for j, q in enumerate(model.parameter_names): + self.assertEqual( + model.fim[p, q].fixed, lower and i < j + ) + if lower and i < j: + self.assertEqual( + pyo.value(model.fim[p, q]), 0.0 + ) + if jac_initial is None: + for con in model.jacobian_constraint.values(): + self.assertAlmostEqual( + pyo.value(con.body), 0.0, places=9 + ) + if fim_initial is None: + for con in model.fim_constraint.values(): + self.assertAlmostEqual( + pyo.value(con.body), 0.0, places=9 + ) + L = np.array( + [ + [ + pyo.value(model.L[p, q]) + for q in model.parameter_names + ] + for p in model.parameter_names + ] + ) + np.testing.assert_allclose(L @ L.T, expected_fim) + + @unittest.skipIf(not pyo.SolverFactory("ipopt").available(), "Requires ipopt") + def test_real_solver_assembly_residuals(self): + """Verify default assembly equations directly after real scenario solves.""" + for formula in ("central", "forward", "backward"): + with self.subTest(formula=formula): + doe = make_doe(formula, solver=pyo.SolverFactory("ipopt")) + doe.create_doe_model() + for constraints in ( + doe.model.jacobian_constraint, + doe.model.fim_constraint, + ): + for constraint in constraints.values(): + self.assertAlmostEqual( + pyo.value(constraint.body), 0.0, places=8 + ) + + def test_scenario_metadata_survives_garbage_collection(self): + """Retain parameter identities after the temporary base model is deleted.""" + + class CollectingDoE(DesignOfExperiments): + """Collect temporary models before the assembly constraints are built.""" + + def _generate_scenario_blocks(self, model=None): + """Generate real scenario blocks, then force garbage collection.""" + super()._generate_scenario_blocks(model) + gc.collect() + + doe = CollectingDoE( + experiment=LinearExperiment(), + solver=ExactLinearSolver(), + objective_option="zero", + ) + doe.create_doe_model() + for parameter in doe.model.parameter_scenarios.values(): + self.assertIs(parameter.model(), doe.model) + self.assertIn(parameter, doe.model.scenario_blocks[0].unknown_parameters) + + def test_default_initialization_rebuilds_from_changed_design(self): + """Do not treat automatically derived arrays as explicit user guesses.""" + doe = make_doe() + doe.create_doe_model() + first = doe._get_fim_numpy(doe.model).copy() + doe.experiment.get_labeled_model().design.set_value(3.0) + model = pyo.ConcreteModel() + doe.create_doe_model(model=model) + expected_jac = np.array([[3.0, 1.0], [1.0, -2.0], [1.0, 3.0]]) + np.testing.assert_allclose(doe.jac_initial, expected_jac) + expected_fim = expected_jac.T @ np.diag([4.0, 0.25, 1 / 1.5**2]) @ expected_jac + np.testing.assert_allclose(doe._get_fim_numpy(model), expected_fim) + self.assertFalse(np.allclose(first, expected_fim)) diff --git a/pyomo/contrib/doe/tests/test_greybox.py b/pyomo/contrib/doe/tests/test_greybox.py index 76d9e1a0e80..f589629e597 100644 --- a/pyomo/contrib/doe/tests/test_greybox.py +++ b/pyomo/contrib/doe/tests/test_greybox.py @@ -331,6 +331,8 @@ def make_greybox_and_doe_objects(objective_option): DoE_args = get_standard_args(experiment, fd_method, obj_used) DoE_args["use_grey_box_objective"] = True DoE_args["prior_FIM"] = testing_matrix + # These metric tests intentionally use a prescribed initial FIM. + DoE_args["fim_initial"] = testing_matrix + np.eye(4) doe_obj = DesignOfExperiments(**DoE_args) doe_obj.create_doe_model() diff --git a/pyomo/contrib/doe/tests/test_kaug_outputs.py b/pyomo/contrib/doe/tests/test_kaug_outputs.py new file mode 100644 index 00000000000..ad27ba7a801 --- /dev/null +++ b/pyomo/contrib/doe/tests/test_kaug_outputs.py @@ -0,0 +1,165 @@ +# ____________________________________________________________________________________ +# +# Pyomo: Python Optimization Modeling Objects +# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC +# Under the terms of Contract DE-NA0003525 with National Technology and Engineering +# Solutions of Sandia, LLC, the U.S. Government retains certain rights in this +# software. This software is distributed under the 3-clause BSD License. +# ____________________________________________________________________________________ + +"""Analytical and solver-backed checks for k_aug Expression measurements.""" + +from pyomo.common.dependencies import numpy as np, numpy_available, scipy_available +from pyomo.common.fileutils import Executable +import pyomo.common.unittest as unittest +import pyomo.environ as pyo +from pyomo.contrib.doe import DesignOfExperiments + + +class ExpressionExperiment: + """Two algebraic states with mixed variable and Expression measurements.""" + + def __init__(self, extended=False): + """Optionally include nonlinear, constant, and direct-parameter outputs.""" + self.extended = extended + + def get_labeled_model(self): + """Return a model whose output sensitivities are available analytically.""" + m = pyo.ConcreteModel() + m.u = pyo.Var(initialize=1.5) + m.theta = pyo.Var([0, 1], initialize={0: 2.0, 1: 3.0}) + m.theta.fix() + m.x = pyo.Var([0, 1], initialize={0: 3.0, 1: 6.75}) + m.c1 = pyo.Constraint(expr=m.x[0] == m.theta[0] * m.u) + m.c2 = pyo.Constraint(expr=m.x[1] == m.theta[1] * m.u**2) + m.total = pyo.Expression(expr=m.x[0] + m.x[1]) + m.product = pyo.Expression(expr=m.x[0] * m.x[1]) + m.direct = pyo.Expression(expr=m.theta[0] * m.x[0]) + m.constant = pyo.Expression(expr=7.0) + m.experiment_inputs = pyo.Suffix(direction=pyo.Suffix.LOCAL) + m.experiment_inputs[m.u] = None + m.unknown_parameters = pyo.Suffix(direction=pyo.Suffix.LOCAL) + m.unknown_parameters.update((v, pyo.value(v)) for v in m.theta.values()) + m.experiment_outputs = pyo.Suffix(direction=pyo.Suffix.LOCAL) + m.measurement_error = pyo.Suffix(direction=pyo.Suffix.LOCAL) + outputs = [m.x[0], m.total] + if self.extended: + outputs.extend([m.product, m.direct, m.theta[0], m.u, m.constant]) + for output in outputs: + m.experiment_outputs[output] = None + m.measurement_error[output] = 1.0 + return m + + +def make_doe(extended=False, **kwds): + """Create an unscaled experiment with an explicitly selected IPOPT solver.""" + return DesignOfExperiments( + experiment=ExpressionExperiment(extended), + solver=pyo.SolverFactory("ipopt"), + objective_option="zero", + **kwds, + ) + + +@unittest.skipIf(not (numpy_available and scipy_available), "Requires numpy and scipy") +class TestKaugOutputJacobian(unittest.TestCase): + """Check chain-rule extraction independently of the external executables.""" + + def test_mixed_outputs(self): + """Include direct parameters, fixed variables, and nonlinear Expressions.""" + doe = make_doe(extended=True) + model = doe.experiment.get_labeled_model() + model.u.fix() + # Reversed column order verifies mapping through the supplied NL names. + jac = doe._extract_kaug_output_jacobian( + model, [[0.0, 2.25], [1.5, 0.0]], ["x[1]", "x[0]"] + ) + expected = [ + [1.5, 0.0], + [1.5, 2.25], + [10.125, 6.75], + [6.0, 0.0], + [1.0, 0.0], + [0.0, 0.0], + [0.0, 0.0], + ] + np.testing.assert_allclose(jac, expected) + + def test_missing_unfixed_dependency_raises(self): + """Do not silently zero a sensitivity when an NL column is missing.""" + doe = make_doe() + model = doe.experiment.get_labeled_model() + with self.assertRaisesRegex(ValueError, r"unfixed variable 'x\[1\]'"): + doe._extract_kaug_output_jacobian(model, [[1.5, 0.0]], ["x[0]"]) + + def test_fixed_dependency_has_zero_sensitivity(self): + """An ordinary fixed state can be absent from the sensitivity columns.""" + doe = make_doe() + model = doe.experiment.get_labeled_model() + model.x[1].fix() + jac = doe._extract_kaug_output_jacobian(model, [[1.5, 0.0]], ["x[0]"]) + np.testing.assert_allclose(jac, [[1.5, 0.0], [1.5, 0.0]]) + + def test_mutable_parameter_dependency(self): + """Direct mutable parameter dependence contributes an identity derivative.""" + doe = make_doe() + model = doe.experiment.get_labeled_model() + model.p = pyo.Param(initialize=5.0, mutable=True) + model.unknown_parameters.clear() + model.unknown_parameters[model.p] = 5.0 + model.expression = pyo.Expression(expr=model.p**2) + model.experiment_outputs.clear() + model.experiment_outputs[model.expression] = None + jac = doe._extract_kaug_output_jacobian(model, np.empty((0, 1)), []) + np.testing.assert_allclose(jac, [[10.0]]) + + def test_invalid_sensitivity_dimensions(self): + """Reject a matrix that does not match the NL columns and parameters.""" + doe = make_doe() + with self.assertRaisesRegex(ValueError, "dimensions"): + doe._extract_kaug_output_jacobian( + doe.experiment.get_labeled_model(), np.zeros((1, 1)), ["x[0]"] + ) + + @unittest.skipUnless( + all(Executable(name).available() for name in ("ipopt", "k_aug", "dot_sens")), + "Requires ipopt, k_aug, and dot_sens", + ) + def test_kaug_matches_sequential_and_analytical_fim(self): + """Exercise the real k_aug pipeline with scaling, weighting, and prior.""" + for extended in (False, True): + for scaled in (False, True): + with self.subTest(extended=extended, scaled=scaled): + prior = np.array([[2.0, 0.25], [0.25, 1.0]]) + doe = make_doe( + extended, + scale_nominal_param_value=scaled, + scale_constant_value=2.0, + prior_FIM=prior, + ) + model = doe.experiment.get_labeled_model() + for i, output in enumerate(model.measurement_error): + model.measurement_error[output] = i + 1.0 + seq_fim = doe.compute_FIM(model=model.clone(), method="sequential") + kaug_fim = doe.compute_FIM(model=model.clone(), method="kaug") + jac = np.array( + [ + [1.5, 0.0], + [1.5, 2.25], + [10.125, 6.75], + [6.0, 0.0], + [1.0, 0.0], + [0.0, 0.0], + [0.0, 0.0], + ] + ) + if not extended: + jac = jac[:2] + jac *= 2.0 + if scaled: + jac *= [2.0, 3.0] + sigma = np.arange(1, len(jac) + 1) + expected = (jac / sigma[:, None]).T @ (jac / sigma[:, None]) + prior + np.testing.assert_allclose(doe.kaug_jac, jac, rtol=1e-5, atol=1e-6) + np.testing.assert_allclose(kaug_fim, expected, rtol=1e-5, atol=1e-6) + np.testing.assert_allclose(kaug_fim, seq_fim, rtol=1e-5, atol=1e-6) From 9217c6e5ec7076452bb5ba5b43eddd6e3d01ab46 Mon Sep 17 00:00:00 2001 From: Alex Dowling Date: Fri, 25 Sep 2026 14:23:24 -0400 Subject: [PATCH 4/7] Warn when computing DoE sensitivities with k_aug and inequalities --- .../explanation/analysis/doe/guide.rst | 11 ++++ pyomo/contrib/doe/doe.py | 19 ++++++ pyomo/contrib/doe/tests/test_kaug_outputs.py | 62 +++++++++++++++++++ 3 files changed, 92 insertions(+) diff --git a/doc/OnlineDocs/explanation/analysis/doe/guide.rst b/doc/OnlineDocs/explanation/analysis/doe/guide.rst index 82e1bac1b15..018053f9bda 100644 --- a/doc/OnlineDocs/explanation/analysis/doe/guide.rst +++ b/doc/OnlineDocs/explanation/analysis/doe/guide.rst @@ -269,6 +269,17 @@ dependency missing from the k_aug sensitivity columns raises an error instead of silently contributing a zero row. Expressions must support Pyomo's numeric differentiation. +If the model contains active inequality constraints, Pyomo.DoE logs a warning +before the nominal solve. k_aug may reject such formulations, even if the +inequalities are satisfied at the nominal solution. This includes inequalities +inside active nested blocks; deactivated constraints and variable bounds do not +trigger the warning. Here, "active" refers to Pyomo component activation, not +whether an inequality is binding at the solution. Consider sequential finite +differences or an equivalent formulation with explicit slack variables. The +warning does not alter the model or suppress subsequent solver errors. It uses +the ``pyomo.contrib.doe.doe`` logger at ``logging.WARNING`` level, consistent +with other Pyomo.DoE diagnostics, rather than Python's ``warnings.warn``. + The k_aug path requires working ``ipopt``, ``k_aug``, and ``dot_sens`` executables. The solver-backed Expression regression can be run on an equipped machine with:: diff --git a/pyomo/contrib/doe/doe.py b/pyomo/contrib/doe/doe.py index 3e8d60e9881..d7477efd426 100644 --- a/pyomo/contrib/doe/doe.py +++ b/pyomo/contrib/doe/doe.py @@ -975,6 +975,25 @@ def _kaug_FIM(self, model=None): for comp in model.experiment_inputs: comp.fix() + inequalities = [ + constraint + for constraint in model.component_data_objects( + pyo.Constraint, active=True, descend_into=True + ) + if not constraint.equality + ] + if inequalities: + self.logger.warning( + "Computing the FIM with k_aug on a model containing %s active " + "inequality constraint(s) (first: '%s'). k_aug may reject this " + "formulation, even when the inequalities are satisfied at the " + "nominal solution. Consider method='sequential' or an equivalent " + "formulation with explicit slack variables. The calculation " + "will proceed without modifying the inequalities.", + len(inequalities), + inequalities[0].name, + ) + result = self.solver.solve(model, tee=self.tee) pyo.assert_optimal_termination(result) diff --git a/pyomo/contrib/doe/tests/test_kaug_outputs.py b/pyomo/contrib/doe/tests/test_kaug_outputs.py index ad27ba7a801..a7e1e10eb9c 100644 --- a/pyomo/contrib/doe/tests/test_kaug_outputs.py +++ b/pyomo/contrib/doe/tests/test_kaug_outputs.py @@ -9,6 +9,11 @@ """Analytical and solver-backed checks for k_aug Expression measurements.""" +import io +import logging +from unittest.mock import patch + +from pyomo.common.log import LoggingIntercept from pyomo.common.dependencies import numpy as np, numpy_available, scipy_available from pyomo.common.fileutils import Executable import pyomo.common.unittest as unittest @@ -65,6 +70,63 @@ def make_doe(extended=False, **kwds): class TestKaugOutputJacobian(unittest.TestCase): """Check chain-rule extraction independently of the external executables.""" + def test_active_inequality_warning_before_solve(self): + """Warn for all inequality forms, including constraints in nested blocks.""" + for form in ("lower", "upper", "ranged", "nested"): + with self.subTest(form=form): + doe = make_doe() + model = doe.experiment.get_labeled_model() + if form == "lower": + model.limit = pyo.Constraint(expr=model.x[0] >= 0) + elif form == "upper": + model.limit = pyo.Constraint(expr=model.x[0] <= 10) + elif form == "ranged": + model.limit = pyo.Constraint(expr=(0, model.x[0], 10)) + else: + model.block = pyo.Block() + model.block.limit = pyo.Constraint( + [0, 1], rule=lambda b, i: model.x[i] <= 10 + ) + output = io.StringIO() + # A failing nominal solve must not hide the diagnostic. Stopping + # here makes this a solver-independent test of the public path. + with LoggingIntercept(output, "pyomo", logging.WARNING): + with patch.object( + doe.solver, "solve", side_effect=RuntimeError("nominal failure") + ) as solve: + with self.assertRaisesRegex(RuntimeError, "nominal failure"): + doe.compute_FIM(model=model, method="kaug") + solve.assert_called_once() + warning = output.getvalue() + self.assertIn("active inequality constraint(s)", warning) + self.assertIn("method='sequential'", warning) + self.assertIn("explicit slack variables", warning) + self.assertEqual(warning.count("Computing the FIM with k_aug"), 1) + first = "block.limit[0]" if form == "nested" else "limit" + self.assertIn("first: '%s'" % first, warning) + self.assertTrue(model.find_component(first).active) + + def test_no_warning_for_equalities_bounds_or_inactive_constraints(self): + """Only active inequality rows, not variable bounds, trigger the warning.""" + doe = make_doe() + model = doe.experiment.get_labeled_model() + model.x[0].setlb(0) + model.x[0].setub(10) + model.limit = pyo.Constraint(expr=model.x[0] <= 10) + model.limit.deactivate() + model.block = pyo.Block() + model.block.limit = pyo.Constraint(expr=model.x[1] >= 0) + model.block.deactivate() + output = io.StringIO() + with LoggingIntercept(output, "pyomo", logging.WARNING): + with patch.object( + doe.solver, "solve", side_effect=RuntimeError("nominal failure") + ) as solve: + with self.assertRaisesRegex(RuntimeError, "nominal failure"): + doe.compute_FIM(model=model, method="kaug") + solve.assert_called_once() + self.assertEqual(output.getvalue(), "") + def test_mixed_outputs(self): """Include direct parameters, fixed variables, and nonlinear Expressions.""" doe = make_doe(extended=True) From e56ee769eff525ec9294c0e45bf6475d28bbad70 Mon Sep 17 00:00:00 2001 From: Alex Dowling Date: Fri, 4 Dec 2026 10:26:00 -0500 Subject: [PATCH 5/7] Explain CUID context in DoE build test Co-Authored-By: Claude Sonnet 5.5 --- pyomo/contrib/doe/tests/test_doe_build.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pyomo/contrib/doe/tests/test_doe_build.py b/pyomo/contrib/doe/tests/test_doe_build.py index ba26b4ec7bc..cf11dc0ad7f 100644 --- a/pyomo/contrib/doe/tests/test_doe_build.py +++ b/pyomo/contrib/doe/tests/test_doe_build.py @@ -165,6 +165,9 @@ def test_rooney_biegler_fd_central_check_fd_eqns(self): diff = (-1) ** s * doe_obj.step + # parameter_scenarios now points at scenario_blocks[0] components (the + # base model is deleted), so take the CUID relative to that block to + # find the matching parameter on scenario_blocks[s]. param_val = pyo.value( pyo.ComponentUID( param, context=model.scenario_blocks[0] From 359ab6c7c3ea95c282e972f106df66f69a440f96 Mon Sep 17 00:00:00 2001 From: Alex Dowling Date: Fri, 4 Dec 2026 10:39:02 -0500 Subject: [PATCH 6/7] Test the DoE bounds-widening warning message Co-Authored-By: Claude Sonnet 5.5 --- .../contrib/doe/tests/test_doe_regressions.py | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/pyomo/contrib/doe/tests/test_doe_regressions.py b/pyomo/contrib/doe/tests/test_doe_regressions.py index df15c76dd8b..05855dc16b1 100644 --- a/pyomo/contrib/doe/tests/test_doe_regressions.py +++ b/pyomo/contrib/doe/tests/test_doe_regressions.py @@ -218,6 +218,56 @@ def test_bounds_sequential_and_simultaneous(self): source = doe.experiment.get_labeled_model() self.assertEqual(source.theta[0].bounds, (3, 6)) + def test_bounds_warning_message(self): + """Name each widened parameter with its perturbed range and new bounds.""" + template = ( + "Finite difference perturbation of unknown parameter '{name}' " + "(perturbed range [{lo}, {hi}]) falls outside its declared bounds " + "({lb}, {ub}). Widening the bounds to ({new_lb}, {new_ub}) for the " + "finite difference computation. The unknown parameters are fixed " + "during these solves, so this does not change the computed " + "sensitivities or FIM.\n" + ) + for simultaneous, prefix in ((False, ""), (True, "base_model.")): + with self.subTest(simultaneous=simultaneous): + # A step of 0.25 keeps every perturbed value exactly representable. + doe = DesignOfExperiments( + experiment=LinearExperiment(bounded=True), + solver=ExactLinearSolver(), + fd_formula="central", + step=0.25, + objective_option="zero", + ) + output = StringIO() + with LoggingIntercept(output, "pyomo", logging.WARNING): + if simultaneous: + doe.create_doe_model() + else: + doe.compute_FIM() + # theta[0] = 3 in (3, 6) is perturbed below its lower bound; + # theta[1] = -4 in (-8, -4) is perturbed above its upper bound. + self.assertEqual( + output.getvalue(), + template.format( + name=prefix + "theta[0]", + lo=2.25, + hi=3.75, + lb=3, + ub=6, + new_lb=2.25, + new_ub=6, + ) + + template.format( + name=prefix + "theta[1]", + lo=-5.0, + hi=-3.0, + lb=-8, + ub=-4, + new_lb=-8, + new_ub=-3.0, + ), + ) + def test_one_sided_and_interior_bounds(self): """Keep all solved perturbations inside adjusted bounds without changing the source.""" bound_cases = ( From 99684591aabc99661fc7e84f075d555c03b48dc9 Mon Sep 17 00:00:00 2001 From: Alex Dowling Date: Fri, 4 Dec 2026 10:50:00 -0500 Subject: [PATCH 7/7] Document the finite-difference column layout in _sequential_FIM Co-Authored-By: Claude Sonnet 5.5 --- pyomo/contrib/doe/doe.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pyomo/contrib/doe/doe.py b/pyomo/contrib/doe/doe.py index d7477efd426..fe2d0249da0 100644 --- a/pyomo/contrib/doe/doe.py +++ b/pyomo/contrib/doe/doe.py @@ -847,6 +847,9 @@ def solve_and_record(context): for k, v in model.unknown_parameters.items(): curr_step = v * self.step + # Column layout of measurement_vals_np: central stores a (+, -) pair + # per parameter. Forward and backward store the nominal response in + # column 0, then one perturbed response per parameter (hence i + 1). if self.fd_formula == FiniteDifferenceStep.central: col_1 = 2 * i col_2 = 2 * i + 1