diff --git a/doc/OnlineDocs/explanation/analysis/parmest/driver.rst b/doc/OnlineDocs/explanation/analysis/parmest/driver.rst index 3bfab301244..28fab84524c 100644 --- a/doc/OnlineDocs/explanation/analysis/parmest/driver.rst +++ b/doc/OnlineDocs/explanation/analysis/parmest/driver.rst @@ -128,6 +128,7 @@ the following methods: :nosignatures: ~pyomo.contrib.parmest.parmest.Estimator.theta_est + ~pyomo.contrib.parmest.parmest.Estimator.theta_est_multistart ~pyomo.contrib.parmest.parmest.Estimator.cov_est ~pyomo.contrib.parmest.parmest.Estimator.theta_est_bootstrap ~pyomo.contrib.parmest.parmest.Estimator.theta_est_leaveNout diff --git a/doc/OnlineDocs/explanation/analysis/parmest/estimability.rst b/doc/OnlineDocs/explanation/analysis/parmest/estimability.rst index 4710990e9e0..e5b4a4b748c 100644 --- a/doc/OnlineDocs/explanation/analysis/parmest/estimability.rst +++ b/doc/OnlineDocs/explanation/analysis/parmest/estimability.rst @@ -9,7 +9,7 @@ parameters that cannot be reliably estimated from the available data due to limi model structure. If such parameters exist, the model may need to be reformulated, replaced with an alternative structure, or augmented with additional prior information. In parmest, estimability analysis can be performed using eigen-decomposition of the parameter covariance matrix, profile likelihood methods, or -multi-start initialization routines. +multistart optimization. Eigen-decomposition ------------------- @@ -39,10 +39,10 @@ determined by the model formulation, particularly in nonlinear systems. Detailed descriptions and example code for this method will be added in a future update. -Multi-start Initialization --------------------------- +Multistart Optimization +----------------------- -Multi-start initialization assesses parameter estimability by exploring a range of initial guesses. Because +Multistart optimization assesses parameter estimability by exploring a range of initial guesses. Because parameter estimation problems are often nonlinear and may exhibit multiple local minima, different initializations can lead to different parameter estimates. By solving the estimation problem from multiple starting points, one can evaluate the robustness of the solution and identify potential issues related to non-convexity or non-identifiability. @@ -50,6 +50,44 @@ Consistent convergence to a unique solution across initializations suggests that identifiable within the model formulation, whereas sensitivity to initialization indicates potential estimability issues. -.. note:: +In parmest, multistart optimization is performed with +:class:`~pyomo.contrib.parmest.parmest.Estimator.theta_est_multistart`, which solves the parameter estimation +problem from several starting values and returns the best start that terminates optimally. The starting values are +sampled between the parameter bounds, so every fitted parameter must have finite lower and upper bounds. The +``multistart_sampling_method`` argument selects ``"uniform_random"`` (the default), ``"latin_hypercube"``, or +``"sobol_sampling"`` (which works best when ``n_starts`` is a power of 2), and ``seed`` makes the starting values +reproducible. Starting values can also be given directly with ``user_supplied_vals``. Using the data and +:class:`~pyomo.contrib.parmest.experiment.Experiment` class from the :ref:`driversection` Section: + +.. testsetup:: * + :skipif: not __import__('pyomo.contrib.parmest.parmest').contrib.parmest.parmest.parmest_available + + # Data + import pandas as pd + data = pd.DataFrame( + data=[[1, 8.3], [2, 10.3], [3, 19.0], + [4, 16.0], [5, 15.6], [7, 19.8]], + columns=['hour', 'y'], + ) + + # Create the Experiment class + from pyomo.contrib.parmest.examples.rooney_biegler.rooney_biegler import RooneyBieglerExperiment + + exp_list = [] + for i in range(data.shape[0]): + exp_list.append(RooneyBieglerExperiment(data.loc[i, :])) + +.. doctest:: + :skipif: not __import__('pyomo.contrib.parmest.parmest').contrib.parmest.parmest.parmest_available + + >>> import pyomo.contrib.parmest.parmest as parmest + >>> pest = parmest.Estimator(exp_list, obj_function="SSE") + >>> results, best_theta, best_obj = pest.theta_est_multistart( + ... n_starts=8, multistart_sampling_method="latin_hypercube", seed=42 + ... ) - Detailed descriptions and example code for this method will be added in a future update. \ No newline at end of file +``results`` is a Pandas DataFrame with one row per start: the starting and converged (``converged_``) +parameter values, the objective value, the solver termination condition, and the solve time. Comparing the +converged values and objectives of the optimal starts shows whether the estimate depends on the initialization. +The solution of the best start is kept in the :class:`~pyomo.contrib.parmest.parmest.Estimator` object, so +methods such as :class:`~pyomo.contrib.parmest.parmest.Estimator.cov_est` can be called afterwards. diff --git a/pyomo/contrib/parmest/examples/reactor_design/multistart_example.py b/pyomo/contrib/parmest/examples/reactor_design/multistart_example.py new file mode 100644 index 00000000000..d5490bc452a --- /dev/null +++ b/pyomo/contrib/parmest/examples/reactor_design/multistart_example.py @@ -0,0 +1,52 @@ +# ____________________________________________________________________________________ +# +# 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. +# ____________________________________________________________________________________ + +from pyomo.common.dependencies import pandas as pd +from os.path import join, abspath, dirname +import pyomo.contrib.parmest.parmest as parmest +from pyomo.contrib.parmest.examples.reactor_design.reactor_design import ( + ReactorDesignExperiment, +) + + +def main(): + + # Read in data + file_dirname = dirname(abspath(str(__file__))) + file_name = abspath(join(file_dirname, "reactor_data.csv")) + data = pd.read_csv(file_name) + + # Create an experiment list + exp_list = [ReactorDesignExperiment(data, i) for i in range(data.shape[0])] + + # Ipopt options + solver_options = {"max_iter": 1000, "tol": 1e-6} + + pest = parmest.Estimator( + exp_list, obj_function="SSE", solver_options=solver_options + ) + + # Single-start estimation + obj, theta = pest.theta_est() + print("Single-start objective:", obj) + print("Single-start theta:\n", theta) + + # Multistart estimation + multistart_result, best_theta, best_obj = pest.theta_est_multistart( + n_starts=10, multistart_sampling_method="uniform_random", seed=42 + ) + + print("\nMultistart best objective:", best_obj) + print("Multistart best theta:", best_theta) + print("\nAll multistart results:") + print(multistart_result) + + +if __name__ == "__main__": + main() diff --git a/pyomo/contrib/parmest/examples/reactor_design/reactor_design.py b/pyomo/contrib/parmest/examples/reactor_design/reactor_design.py index 6172096e1ad..6a065d20a63 100644 --- a/pyomo/contrib/parmest/examples/reactor_design/reactor_design.py +++ b/pyomo/contrib/parmest/examples/reactor_design/reactor_design.py @@ -23,10 +23,14 @@ def reactor_design_model(): model = pyo.ConcreteModel() # Rate constants, make unknown parameters variables - model.k1 = pyo.Var(initialize=5.0 / 6.0, within=pyo.PositiveReals) # min^-1 - model.k2 = pyo.Var(initialize=5.0 / 3.0, within=pyo.PositiveReals) # min^-1 + model.k1 = pyo.Var( + initialize=5.0 / 6.0, within=pyo.PositiveReals, bounds=(0.1, 10.0) + ) # min^-1 + model.k2 = pyo.Var( + initialize=5.0 / 3.0, within=pyo.PositiveReals, bounds=(0.1, 10.0) + ) # min^-1 model.k3 = pyo.Var( - initialize=1.0 / 6000.0, within=pyo.PositiveReals + initialize=1.0 / 6000.0, within=pyo.PositiveReals, bounds=(1e-5, 1e-3) ) # m^3/(gmol min) # Inlet concentration of A, gmol/m^3 diff --git a/pyomo/contrib/parmest/examples/rooney_biegler/multistart_example.py b/pyomo/contrib/parmest/examples/rooney_biegler/multistart_example.py new file mode 100644 index 00000000000..5e1dea26398 --- /dev/null +++ b/pyomo/contrib/parmest/examples/rooney_biegler/multistart_example.py @@ -0,0 +1,54 @@ +# ____________________________________________________________________________________ +# +# 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. +# ____________________________________________________________________________________ + +from pyomo.common.dependencies import pandas as pd +import pyomo.contrib.parmest.parmest as parmest +from pyomo.contrib.parmest.examples.rooney_biegler.rooney_biegler import ( + RooneyBieglerExperiment, +) + + +def main(): + + # Data + data = pd.DataFrame( + data=[[1, 8.3], [2, 10.3], [3, 19.0], [4, 16.0], [5, 15.6], [7, 19.8]], + columns=['hour', 'y'], + ) + + # Create an experiment list + exp_list = [] + for i in range(data.shape[0]): + exp_list.append(RooneyBieglerExperiment(data.loc[i, :])) + + # Ipopt options + solver_options = {"max_iter": 1000, "tol": 1e-6} + + pest = parmest.Estimator( + exp_list, obj_function="SSE", solver_options=solver_options + ) + + # Single-start estimation + obj, theta = pest.theta_est() + print("Single-start objective:", obj) + print("Single-start theta:\n", theta) + + # Multistart estimation + multistart_result, best_theta, best_obj = pest.theta_est_multistart( + n_starts=10, multistart_sampling_method="uniform_random", seed=42 + ) + + print("\nMultistart best objective:", best_obj) + print("Multistart best theta:", best_theta) + print("\nAll multistart results:") + print(multistart_result) + + +if __name__ == "__main__": + main() diff --git a/pyomo/contrib/parmest/examples/rooney_biegler/rooney_biegler.py b/pyomo/contrib/parmest/examples/rooney_biegler/rooney_biegler.py index bdb494bca03..4ed4e8fc947 100644 --- a/pyomo/contrib/parmest/examples/rooney_biegler/rooney_biegler.py +++ b/pyomo/contrib/parmest/examples/rooney_biegler/rooney_biegler.py @@ -43,8 +43,8 @@ def rooney_biegler_model(data, theta=None): if theta is None: theta = {'asymptote': 15, 'rate_constant': 0.5} - model.asymptote = pyo.Var(initialize=theta['asymptote']) - model.rate_constant = pyo.Var(initialize=theta['rate_constant']) + model.asymptote = pyo.Var(initialize=theta['asymptote'], bounds=(0.1, 100)) + model.rate_constant = pyo.Var(initialize=theta['rate_constant'], bounds=(0, 10)) # Fix the unknown parameters model.asymptote.fix() diff --git a/pyomo/contrib/parmest/parmest.py b/pyomo/contrib/parmest/parmest.py index fc76d21c94e..76f8e2fa576 100644 --- a/pyomo/contrib/parmest/parmest.py +++ b/pyomo/contrib/parmest/parmest.py @@ -40,8 +40,10 @@ import re import importlib as im import logging +import time import types import json +import numbers from collections.abc import Callable from itertools import combinations from functools import singledispatchmethod @@ -61,7 +63,10 @@ from pyomo.opt import SolverFactory from pyomo.environ import Block, ComponentUID -from pyomo.opt.results.solver import assert_optimal_termination +from pyomo.opt.results.solver import ( + assert_optimal_termination, + check_optimal_termination, +) from pyomo.common.flags import NOTSET from pyomo.contrib.sensitivity_toolbox.sens import get_dsdp @@ -540,6 +545,93 @@ class RegularizationType(Enum): L2 = "L2" +class MultistartSamplingMethod(Enum): + uniform_random = "uniform_random" + latin_hypercube = "latin_hypercube" + sobol_sampling = "sobol_sampling" + + +def _sample_initial_theta( + multistart_sampling_method, n_starts, lower_bounds, upper_bounds, seed=None +): + """ + Sample starting theta values within the theta bounds. + + Parameters + ---------- + multistart_sampling_method : str or MultistartSamplingMethod + Sampling method. + n_starts : int + Number of starts. + lower_bounds, upper_bounds : np.ndarray + Theta bounds. + seed : int, optional + Random seed. Default is None. + + Returns + ------- + np.ndarray + Starting values, shape (n_starts, number of thetas). + """ + try: + multistart_sampling_method = MultistartSamplingMethod( + multistart_sampling_method + ) + except ValueError: + raise ValueError( + f"Invalid multistart_sampling_method: " + f"'{multistart_sampling_method}'. Choose from: " + f"{[e.value for e in MultistartSamplingMethod]}." + ) + # numbers.Integral also accepts numpy integers; bool is not a count + if not isinstance(n_starts, numbers.Integral) or isinstance(n_starts, bool): + raise TypeError("n_starts must be an integer.") + if n_starts <= 0: + raise ValueError("n_starts must be greater than zero.") + + # Each method gives samples in [0, 1], shape (n_starts, n_theta) + n_theta = len(lower_bounds) + if multistart_sampling_method == MultistartSamplingMethod.uniform_random: + # Local RNG, so the global random state is unchanged + rng = np.random.default_rng(seed) + samples = rng.random((n_starts, n_theta)) + elif multistart_sampling_method == MultistartSamplingMethod.latin_hypercube: + sampler = scipy.stats.qmc.LatinHypercube(d=n_theta, seed=seed) + samples = sampler.random(n=n_starts) + else: + # Scrambled, so the first point is not the origin + sampler = scipy.stats.qmc.Sobol(d=n_theta, scramble=True, seed=seed) + samples = sampler.random(n=n_starts) + + # Scale the samples to the theta bounds + return lower_bounds + (upper_bounds - lower_bounds) * samples + + +def _build_multistart_table(theta_starts): + """ + Add the result columns filled in by theta_est_multistart. + + Parameters + ---------- + theta_starts : pd.DataFrame + Starting values, one row per start and one column per theta. + + Returns + ------- + pd.DataFrame + Starting values plus ``converged_``, ``final_objective``, + ``solver_termination`` and ``solve_time`` columns, all missing + (NaN or None) until filled. + """ + multistart_result = theta_starts.copy() + for name in theta_starts.columns: + multistart_result[f"converged_{name}"] = np.nan + multistart_result["final_objective"] = np.nan + multistart_result["solver_termination"] = None + multistart_result["solve_time"] = np.nan + return multistart_result + + # Compute the Jacobian matrix of measured variables with respect to the parameters def _compute_jacobian(experiment, theta_vals, step, solver, tee, solver_options): """ @@ -1474,6 +1566,134 @@ def total_obj(m): self.ef_instance = model return model + def _generate_initial_theta( + self, + seed=None, + n_starts=None, + multistart_sampling_method=None, + user_supplied_vals=None, + ): + """ + Create the table of starting theta values for theta_est_multistart. + + Theta names and bounds come from the first experiment. Every theta + needs finite bounds, and all starting values must be within them. + + Parameters + ---------- + seed : int, optional + Random seed for sampling. Default is None. + n_starts : int, optional + Number of starts to sample. Not used with user_supplied_vals. + Default is None. + multistart_sampling_method : str or MultistartSamplingMethod, optional + See theta_est_multistart. Default is None (uniform_random). + user_supplied_vals : dict or pd.DataFrame, optional + See theta_est_multistart. Default is None. + + Returns + ------- + pd.DataFrame + Starting values, one row per start and one column per theta (in + model order). + """ + parmest_model = self._create_parmest_model(0) + + # Same theta names as _Q_opt uses + theta_names = list(self._expanded_theta_info(parmest_model)[0]) + # E.g., an indexed theta and one of its elements both labeled + if len(theta_names) != len(set(theta_names)): + raise ValueError(f"Duplicate theta names are not allowed: {theta_names}") + lower_bounds = [] + upper_bounds = [] + for name in theta_names: + theta_var = parmest_model.find_component(name) + lower_bounds.append(theta_var.lb) + upper_bounds.append(theta_var.ub) + # Missing bounds (None) become NaN + lower_bounds = np.array(lower_bounds, dtype=float) + upper_bounds = np.array(upper_bounds, dtype=float) + + if np.any(np.isnan(lower_bounds)) or np.any(np.isnan(upper_bounds)): + raise ValueError( + "The lower and upper bounds for the theta values must be defined." + ) + if np.any(lower_bounds > upper_bounds): + raise ValueError( + "Each lower bound must be less than or equal to the corresponding " + "upper bound." + ) + equal_bounds = [ + name + for name, lb, ub in zip(theta_names, lower_bounds, upper_bounds) + if lb == ub + ] + if equal_bounds: + logger.warning( + f"Theta {equal_bounds} has equal lower and upper bounds. Fix it " + "instead of estimating it, or widen its bounds." + ) + + if user_supplied_vals is not None: + if multistart_sampling_method is not None: + logger.warning( + "multistart_sampling_method is ignored when " + "user_supplied_vals is given." + ) + if isinstance(user_supplied_vals, dict): + # Check the names before converting or counting the values + self._normalize_theta_dataframe( + pd.DataFrame(columns=list(user_supplied_vals)), model=parmest_model + ) + # A single value per theta is one start + starts = {} + for name, vals in user_supplied_vals.items(): + starts[name] = np.atleast_1d(vals) + start_counts = {len(vals) for vals in starts.values()} + if len(start_counts) > 1: + raise ValueError( + "Each theta in user_supplied_vals must have the same " + "number of starting values." + ) + user_supplied_vals = pd.DataFrame(starts) + if not isinstance(user_supplied_vals, pd.DataFrame): + raise TypeError( + "user_supplied_vals must be a dict or a pandas DataFrame." + ) + # Match to the model theta names and order + theta_starts = self._normalize_theta_dataframe( + user_supplied_vals, model=parmest_model + ) + # Results are filled by row position, so drop the user's index + theta_starts = theta_starts.reset_index(drop=True) + if len(theta_starts) == 0: + raise ValueError( + "user_supplied_vals must contain at least one starting value." + ) + # NaN fails both comparisons, so it is also rejected + theta_arr = theta_starts.to_numpy(dtype=float) + above_lower = theta_arr >= lower_bounds + below_upper = theta_arr <= upper_bounds + if not (above_lower & below_upper).all(): + raise ValueError( + "user_supplied_vals must be finite and within the theta bounds." + ) + else: + if multistart_sampling_method is None: + multistart_sampling_method = MultistartSamplingMethod.uniform_random + theta_starts = pd.DataFrame( + _sample_initial_theta( + multistart_sampling_method, + n_starts, + lower_bounds, + upper_bounds, + seed=seed, + ), + columns=theta_names, + ) + + return theta_starts + def _Q_opt( self, return_values=None, @@ -1481,6 +1701,7 @@ def _Q_opt( solver="ef_ipopt", theta_vals=None, fix_theta=False, + multistart=False, ): """ _Q_opt method for parameter estimation using an extensive form @@ -1515,6 +1736,10 @@ def _Q_opt( fix_theta : bool, optional If True, fix the theta values in the model. If False, leave them free. Default is False. + multistart : bool, optional + If True, return the termination condition, and return None values + instead of raising if the solve is not optimal. Default is False. + Returns ------- obj_value : float or None @@ -1525,7 +1750,10 @@ def _Q_opt( If fix_theta is True, this is the objective value at the fixed theta values. If the fixed-theta problem does not return a solution, obj_value is None. - theta_estimates : dict + + If multistart is True and the solve is not optimal, obj_value is + None. + theta_estimates : dict or None Dictionary of theta values keyed by theta name. If fix_theta is False, this contains the estimated parameter values @@ -1533,14 +1761,18 @@ def _Q_opt( If fix_theta is True, this contains the fixed theta values used in the model. + + If multistart is True and the solve is not optimal, + theta_estimates is None. var_values : pd.DataFrame, optional DataFrame of variable values for the variables specified in - return_values. Only returned when fix_theta is False and - return_values is not None and contains at least one valid variable - name. The DataFrame has one row per scenario block and columns - corresponding to the variable names in return_values. + return_values. Only returned when fix_theta and multistart are + False and return_values is not None and contains at least one valid + variable name. The DataFrame has one row per scenario block and + columns corresponding to the variable names in return_values. termination_condition : pyomo.opt.TerminationCondition, optional - Solver termination condition. Only returned when fix_theta is True. + Solver termination condition. Only returned when fix_theta or + multistart is True. """ # Create extended form model with scenario blocks @@ -1549,11 +1781,6 @@ def _Q_opt( ) expanded_theta_names = list(model._parmest_theta_names) - logger.debug("Parmest _Q_opt model with scenario blocks:") - - if logger.isEnabledFor(logging.DEBUG): - model.pprint() - # Check solver and set options if solver == "k_aug": raise RuntimeError("k_aug no longer supported.") @@ -1585,7 +1812,11 @@ def _Q_opt( obj_value = None return obj_value, theta_estimates, termination_condition - if not fix_theta: + # If not fixing theta, a non-optimal solve raises, or in multistart + # mode returns only the termination condition + if not fix_theta and not check_optimal_termination(solve_result): + if multistart: + return None, None, termination_condition assert_optimal_termination(solve_result) model.solutions.load_from(solve_result) @@ -1600,8 +1831,9 @@ def _Q_opt( self.obj_value = obj_value self.estimated_theta = theta_estimates - # If fixing theta, return objective value, theta estimates, and solver status - if fix_theta: + # If fixing theta or multistart, return objective value, theta + # estimates, and solver status + if fix_theta or multistart: return obj_value, theta_estimates, termination_condition # Extract return values if requested @@ -2260,7 +2492,127 @@ def leaveNout_bootstrap_test( return results - def _normalize_theta_dataframe(self, theta_values): + def theta_est_multistart( + self, + n_starts=20, + multistart_sampling_method=None, + user_supplied_vals=None, + seed=None, + file_name=None, + ): + """ + Parameter estimation using all scenarios in the data, from multiple + starting values of theta + + Each start is solved as in theta_est. Every theta needs finite bounds. + The best start is the optimal start with the smallest objective; its + solution is kept on the Estimator (e.g., for cov_est). + + Parameters + ---------- + n_starts: int, optional + Number of starts to sample. Not used with user_supplied_vals. + Default is 20. + multistart_sampling_method: str or MultistartSamplingMethod, optional + "uniform_random", "latin_hypercube" or "sobol_sampling". Ignored, + with a warning, if user_supplied_vals is given. Default is None + (uniform_random). + user_supplied_vals: dict or pd.DataFrame, optional + Starting values keyed by theta name, e.g., + ``{"asymptote": [10, 20], "rate_constant": [0.1, 0.5]}``. + Default is None. + seed: int, optional + Random seed for sampling. Default is None. + file_name: str, optional + If given, write multistart_result to this CSV file. Default is + None (not written). + + Returns + ------- + multistart_result: pd.DataFrame + One row per start: starting and converged (``converged_``) + theta values, ``final_objective``, ``solver_termination`` and + ``solve_time`` (seconds). + best_theta: dict or None + Theta values of the best start. None if no start is optimal. + best_obj: float + Objective of the best start. NaN if no start is optimal. + """ + if self.pest_deprecated is not None: + raise RuntimeError( + "Multistart is not supported in the deprecated parmest interface." + ) + + theta_starts = self._generate_initial_theta( + seed=seed, + n_starts=n_starts, + multistart_sampling_method=multistart_sampling_method, + user_supplied_vals=user_supplied_vals, + ) + theta_names = list(theta_starts.columns) + multistart_result = _build_multistart_table(theta_starts) + + # _Q_opt overwrites these; restore them if no start is optimal + state_attrs = ("ef_instance", "estimated_theta", "obj_value") + prior_state = {} + for attr in state_attrs: + if hasattr(self, attr): + prior_state[attr] = getattr(self, attr) + + # Best optimal start so far. Non-optimal objectives (e.g., at + # infeasible points) are not comparable, so only optimal starts count. + best_obj = np.nan + best_theta = None + best_model = None + for i in range(len(theta_starts)): + theta_vals = {} + for name in theta_names: + theta_vals[name] = float(theta_starts.at[i, name]) + t0 = time.time() + try: + obj, theta_hat, termination = self._Q_opt( + theta_vals=theta_vals, multistart=True + ) + multistart_result.at[i, "solver_termination"] = str(termination) + except Exception as exc: + logger.warning(f"Start {i} raised an exception: {exc}") + theta_hat = None + multistart_result.at[i, "solver_termination"] = f"exception: {exc}" + multistart_result.at[i, "solve_time"] = time.time() - t0 + + # theta_hat is None unless the solve terminated optimally: + # _Q_opt(multistart=True) applies check_optimal_termination, the + # check assert_optimal_termination makes in theta_est + if theta_hat is not None: + multistart_result.at[i, "final_objective"] = obj + for name in theta_names: + multistart_result.at[i, f"converged_{name}"] = theta_hat[name] + if best_theta is None or obj < best_obj: + best_obj = obj + best_theta = theta_hat + best_model = self.ef_instance + + if best_theta is None: + logger.warning( + f"None of the {len(theta_starts)} starts terminated optimally." + ) + for attr in state_attrs: + if attr in prior_state: + setattr(self, attr, prior_state[attr]) + elif hasattr(self, attr): + delattr(self, attr) + else: + # Keep the best start's solution (e.g., for cov_est) + self.ef_instance = best_model + self.estimated_theta = best_theta + self.obj_value = best_obj + + if file_name is not None: + multistart_result.to_csv(file_name, index=False) + + return multistart_result, best_theta, best_obj + + def _normalize_theta_dataframe(self, theta_values, model=None): """ Validate and normalize user-provided theta_values columns. @@ -2268,11 +2620,15 @@ def _normalize_theta_dataframe(self, theta_values): the model. This allows quote-insensitive matching while preserving canonical model - names internally. + names internally. Theta names come from model if given, otherwise from + the first experiment. """ assert isinstance(theta_values, pd.DataFrame) - template_model = self._create_parmest_model(0) + if model is not None: + template_model = model + else: + template_model = self._create_parmest_model(0) expected_theta_names, _ = self._expanded_theta_info(template_model) expected_theta_names = list(expected_theta_names) diff --git a/pyomo/contrib/parmest/tests/test_examples.py b/pyomo/contrib/parmest/tests/test_examples.py index b10d894a085..95b9e2c9594 100644 --- a/pyomo/contrib/parmest/tests/test_examples.py +++ b/pyomo/contrib/parmest/tests/test_examples.py @@ -54,6 +54,11 @@ def test_likelihood_ratio_example(self): likelihood_ratio_example.main() + def test_multistart_example(self): + from pyomo.contrib.parmest.examples.rooney_biegler import multistart_example + + multistart_example.main() + def test_regularization_example(self): from pyomo.contrib.parmest.examples.rooney_biegler import regularization_example @@ -154,6 +159,11 @@ def test_parameter_estimation_example(self): parameter_estimation_example.main() + def test_multistart_example(self): + from pyomo.contrib.parmest.examples.reactor_design import multistart_example + + multistart_example.main() + @unittest.skipUnless(seaborn_available, "test requires seaborn") def test_bootstrap_example(self): from pyomo.contrib.parmest.examples.reactor_design import bootstrap_example diff --git a/pyomo/contrib/parmest/tests/test_parmest.py b/pyomo/contrib/parmest/tests/test_parmest.py index 68fd5860c45..4f2048a5da7 100644 --- a/pyomo/contrib/parmest/tests/test_parmest.py +++ b/pyomo/contrib/parmest/tests/test_parmest.py @@ -19,9 +19,13 @@ import pyomo.contrib.parmest as parmestbase import pyomo.environ as pyo import pyomo.dae as dae +import io +import logging from pyomo.common.dependencies import numpy as np, pandas as pd, scipy, matplotlib from pyomo.common.fileutils import this_file_dir +from pyomo.common.log import LoggingIntercept +from pyomo.common.tempfiles import TempfileManager from pyomo.contrib.parmest.experiment import Experiment from pyomo.contrib.pynumero.asl import AmplInterface @@ -748,8 +752,9 @@ def label_model(self): def rooney_biegler_vars(data): model = pyo.ConcreteModel() - model.asymptote = pyo.Var(initialize=15) - model.rate_constant = pyo.Var(initialize=0.5) + # Bounds, as in the rooney_biegler example, are needed for multistart + model.asymptote = pyo.Var(initialize=15, bounds=(0.1, 100)) + model.rate_constant = pyo.Var(initialize=0.5, bounds=(0, 10)) model.asymptote.fixed = True # parmest will unfix theta variables model.rate_constant.fixed = True @@ -801,7 +806,9 @@ def rooney_biegler_indexed_vars(data): model.var_names = pyo.Set(initialize=["asymptote", "rate_constant"]) model.theta = pyo.Var( - model.var_names, initialize={"asymptote": 15, "rate_constant": 0.5} + model.var_names, + initialize={"asymptote": 15, "rate_constant": 0.5}, + bounds={"asymptote": (0.1, 100), "rate_constant": (0, 10)}, ) model.theta["asymptote"].fixed = ( True # parmest will unfix theta variables, even when they are indexed @@ -975,6 +982,59 @@ def test_parmest_basics_with_square_problem_solve(self): # SSE includes a 1/2: half of 16.531953 self.assertAlmostEqual(obj_at_theta["obj"][0], 8.2659765, places=2) + def test_theta_est_multistart(self): + for model_type, parmest_input in self.input.items(): + pest = parmest.Estimator( + parmest_input["exp_list"], obj_function=self.objective_function + ) + + # Params have no bounds, which multistart needs + if model_type.startswith("param"): + with self.assertRaisesRegex( + ValueError, + r"The lower and upper bounds for the theta values must be " + r"defined\.", + ): + pest.theta_est_multistart(n_starts=2, seed=0) + continue + + # Starts keyed by this variant's theta names (plain, quoted or + # unquoted indices), or by theta_vals for the indexed variant + theta_names = parmest_input["theta_names"] + if len(theta_names) == 2: + starts = {theta_names[0]: [20.0, 10.0], theta_names[1]: [1.0, 0.2]} + else: + starts = parmest_input["theta_vals"] + + multistart_result, best_theta, best_obj = pest.theta_est_multistart( + user_supplied_vals=starts + ) + objval, thetavals = pest.theta_est() + + # Results use the same theta names as theta_est + self.assertEqual(list(best_theta), list(thetavals)) + self.assertAlmostEqual(best_obj, objval, places=6) + for name in thetavals: + self.assertAlmostEqual(best_theta[name], thetavals[name], places=4) + + def test_multistart_starts_initialize_ef_model(self): + pest = parmest.Estimator( + self.input["vars_index"]["exp_list"], obj_function=self.objective_function + ) + # Quoted names, in a different order from the model + starts = {"theta['rate_constant']": 0.4, "theta['asymptote']": 21.0} + theta_starts = pest._generate_initial_theta(user_supplied_vals=starts) + self.assertEqual( + list(theta_starts.columns), ["theta[asymptote]", "theta[rate_constant]"] + ) + + # theta_est_multistart passes each row as theta_vals + model = pest._create_scenario_blocks(theta_vals=theta_starts.loc[0].to_dict()) + self.assertEqual(pyo.value(model.parmest_theta["theta[asymptote]"]), 21.0) + child = model.exp_scenarios[0] + self.assertEqual(pyo.value(child.theta["asymptote"]), 21.0) + self.assertEqual(pyo.value(child.theta["rate_constant"]), 0.4) + @unittest.skipUnless(pynumero_ASL_available, 'pynumero_ASL is not available') def test_parmest_basics_with_square_problem_solve_no_theta_vals(self): @@ -2459,6 +2519,432 @@ def test_count_total_experiments_rejects_time_not_in_first_index(self): parmest._count_total_experiments(exp_list) +class SineExperiment(Experiment): + """ + One point of y = sin(k x); the SSE has several local minima in k. + """ + + def __init__(self, x, y): + self.x = x + self.y = y + + def get_labeled_model(self): + m = pyo.ConcreteModel() + m.k = pyo.Var(initialize=1.0, bounds=(0.1, 10.0)) + m.k.fix() + m.y_hat = pyo.Var(initialize=0.0) + m.y_hat_link = pyo.Constraint(expr=m.y_hat == pyo.sin(m.k * self.x)) + m.experiment_outputs = pyo.Suffix(direction=pyo.Suffix.LOCAL) + m.experiment_outputs.update([(m.y_hat, self.y)]) + m.unknown_parameters = pyo.Suffix(direction=pyo.Suffix.LOCAL) + m.unknown_parameters.update([(m.k, pyo.ComponentUID(m.k))]) + m.measurement_error = pyo.Suffix(direction=pyo.Suffix.LOCAL) + m.measurement_error.update([(m.y_hat, None)]) + return m + + +def _build_sine_estimator(solver_options=None, noise=0.0): + # Data from k = 2. A start at k = 6 converges to a worse local minimum + # near k = 6.2. Noise gives a nonzero covariance at the best start. + xs = np.linspace(0.2, 3.0, 8) + ys = np.sin(2.0 * xs) + noise * np.random.default_rng(0).standard_normal(8) + exp_list = [SineExperiment(x, float(y)) for x, y in zip(xs, ys)] + return parmest.Estimator( + exp_list, obj_function="SSE", solver_options=solver_options + ) + + +_LINEAR_DATA = [(1.0, 2.0), (2.0, 3.0)] + + +class _FailingStartsEstimator(parmest.Estimator): + """ + Estimator whose solve fails for chosen starts: a non-optimal termination + for starts in nonoptimal_starts and an exception for starts in + exception_starts (keyed by the "theta" start value). + """ + + nonoptimal_starts = () + exception_starts = () + + def _Q_opt(self, theta_vals=None, **kwargs): + if theta_vals["theta"] in self.nonoptimal_starts: + return None, None, pyo.TerminationCondition.maxIterations + if theta_vals["theta"] in self.exception_starts: + raise RuntimeError("solver failed") + return super()._Q_opt(theta_vals=theta_vals, **kwargs) + + +@unittest.skipIf( + not parmest.parmest_available, + "Cannot test parmest: required dependencies are missing", +) +class TestParmestMultistart(unittest.TestCase): + def test_sampling_changes_with_different_seed(self): + pest = _build_estimator(_LINEAR_DATA) + theta_starts_1 = pest._generate_initial_theta(seed=4, n_starts=5) + theta_starts_2 = pest._generate_initial_theta(seed=5, n_starts=5) + self.assertFalse(theta_starts_1.equals(theta_starts_2)) + + def test_invalid_bounds_raises(self): + class InvalidBoundsExperiment(LinearThetaExperiment): + def create_model(self): + super().create_model() + self.model.theta.setlb(2.0) + self.model.theta.setub(1.0) + + pest = parmest.Estimator( + [InvalidBoundsExperiment(1.0, 2.0)], obj_function="SSE" + ) + with self.assertRaisesRegex( + ValueError, + r"Each lower bound must be less than or equal to the corresponding " + r"upper bound\.", + ): + pest._generate_initial_theta(seed=1, n_starts=2) + + def test_duplicate_model_theta_names_raises(self): + class DuplicateThetaExperiment(IndexedThetaExperiment): + def label_model(self): + super().label_model() + # Label one element again, alongside its indexed parent + m = self.model + m.unknown_parameters[m.theta["a"]] = pyo.ComponentUID(m.theta["a"]) + + pest = parmest.Estimator( + [DuplicateThetaExperiment(1.0, 2.0)], obj_function="SSE" + ) + with self.assertRaisesRegex( + ValueError, + r"Duplicate theta names are not allowed: " + r"\['theta\[a\]', 'theta\[b\]', 'theta\[a\]'\]", + ): + pest._generate_initial_theta(seed=1, n_starts=2) + + def test_user_supplied_names_mismatch_raises(self): + pest = _build_estimator(_LINEAR_DATA) + starts = pd.DataFrame([[1.0, 2.0]], columns=["theta", "extra"]) + with self.assertRaisesRegex( + ValueError, + r"Provided theta values \['theta', 'extra'\] do not match " + r"expected theta names \['theta'\]\.", + ): + pest.theta_est_multistart(user_supplied_vals=starts) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_state_isolation_between_starts(self): + pest = _build_estimator(_LINEAR_DATA) + starts = pd.DataFrame({"theta": [-9.0, 9.0]}) + multistart_result, _, _ = pest.theta_est_multistart(user_supplied_vals=starts) + # Initial starts should remain exactly as supplied. + self.assertAlmostEqual(multistart_result.loc[0, "theta"], -9.0, places=12) + self.assertAlmostEqual(multistart_result.loc[1, "theta"], 9.0, places=12) + # Both starts reach the same optimum (no state leaks between starts) + self.assertAlmostEqual( + multistart_result.loc[0, "converged_theta"], + multistart_result.loc[1, "converged_theta"], + places=8, + ) + + def test_indexed_unknown_parameters_supported_in_sampling(self): + pest = _build_indexed_theta_estimator(_LINEAR_DATA) + theta_starts = pest._generate_initial_theta(seed=10, n_starts=3) + self.assertEqual(list(theta_starts.columns), ["theta[a]", "theta[b]"]) + + def test_user_supplied_duplicate_names_raises(self): + pest = _build_indexed_theta_estimator(_LINEAR_DATA) + starts = pd.DataFrame([[0.3, 4.2]], columns=["theta[a]", "theta[a]"]) + with self.assertRaisesRegex( + ValueError, + r"Duplicate theta names are not allowed: " + r"\['theta\[a\]', 'theta\[a\]'\]", + ): + pest._generate_initial_theta(user_supplied_vals=starts) + + def test_user_supplied_dict_matches_dataframe(self): + pest = _build_indexed_theta_estimator(_LINEAR_DATA) + from_dict = pest._generate_initial_theta( + user_supplied_vals={"theta[b]": [0.3, 0.4], "theta[a]": [4.2, 4.1]} + ) + from_df = pest._generate_initial_theta( + user_supplied_vals=pd.DataFrame( + {"theta[a]": [4.2, 4.1], "theta[b]": [0.3, 0.4]} + ) + ) + pd.testing.assert_frame_equal(from_dict, from_df) + + def test_user_supplied_dict_of_scalars_is_one_start(self): + pest = _build_indexed_theta_estimator(_LINEAR_DATA) + theta_starts = pest._generate_initial_theta( + user_supplied_vals={"theta[a]": 4.2, "theta[b]": 0.3} + ) + self.assertEqual(len(theta_starts), 1) + self.assertEqual(theta_starts.loc[0, "theta[a]"], 4.2) + self.assertEqual(theta_starts.loc[0, "theta[b]"], 0.3) + + def test_user_supplied_dict_unequal_lengths_raises(self): + pest = _build_indexed_theta_estimator(_LINEAR_DATA) + with self.assertRaisesRegex( + ValueError, + r"Each theta in user_supplied_vals must have the same number of " + r"starting values\.", + ): + pest._generate_initial_theta( + user_supplied_vals={"theta[a]": [4.2, 4.1], "theta[b]": [0.3]} + ) + + def test_user_supplied_dict_names_checked_before_lengths(self): + pest = _build_indexed_theta_estimator(_LINEAR_DATA) + with self.assertRaisesRegex(ValueError, r"do not match expected theta names"): + pest._generate_initial_theta( + user_supplied_vals={"theta[a]": [4.2, 4.1], "theta[c]": [0.3]} + ) + + def test_user_supplied_invalid_type_raises(self): + pest = _build_estimator(_LINEAR_DATA) + with self.assertRaisesRegex( + TypeError, r"user_supplied_vals must be a dict or a pandas DataFrame\." + ): + pest._generate_initial_theta(user_supplied_vals=[[1.0], [2.0]]) + + def test_user_supplied_outside_bounds_raises(self): + pest = _build_estimator(_LINEAR_DATA) + for vals in ([11.0], [np.nan], [np.inf]): + with self.assertRaisesRegex( + ValueError, + r"user_supplied_vals must be finite and within the theta bounds\.", + ): + pest._generate_initial_theta(user_supplied_vals={"theta": vals}) + + def test_user_supplied_dataframe_index_is_reset(self): + # Results are filled by row position, so the user's index is dropped + pest = _build_estimator(_LINEAR_DATA) + starts = pd.DataFrame({"theta": [-9.0, 9.0]}, index=["first", "second"]) + theta_starts = pest._generate_initial_theta(user_supplied_vals=starts) + self.assertEqual(list(theta_starts.index), [0, 1]) + self.assertEqual(theta_starts["theta"].tolist(), [-9.0, 9.0]) + + def test_sample_initial_theta_without_estimator(self): + lower_bound = np.array([0.0, -1.0]) + upper_bound = np.array([1.0, 1.0]) + for method in parmest.MultistartSamplingMethod: + samples = parmest._sample_initial_theta( + method, 8, lower_bound, upper_bound, seed=0 + ) + self.assertEqual(samples.shape, (8, 2)) + self.assertTrue((samples >= lower_bound).all()) + self.assertTrue((samples <= upper_bound).all()) + + def test_sampling_is_deterministic_for_enum_or_string(self): + # Same seed, so an Enum and its string value give the same starts + pest = _build_estimator(_LINEAR_DATA) + for method in parmest.MultistartSamplingMethod: + from_enum = pest._generate_initial_theta( + seed=3, n_starts=4, multistart_sampling_method=method + ) + from_str = pest._generate_initial_theta( + seed=3, n_starts=4, multistart_sampling_method=method.value + ) + pd.testing.assert_frame_equal(from_enum, from_str) + + def test_default_sampling_method_is_uniform_random(self): + pest = _build_estimator(_LINEAR_DATA) + from_default = pest._generate_initial_theta(seed=3, n_starts=4) + from_uniform = pest._generate_initial_theta( + seed=3, n_starts=4, multistart_sampling_method="uniform_random" + ) + pd.testing.assert_frame_equal(from_default, from_uniform) + + def test_n_starts_not_integer_raises(self): + pest = _build_estimator(_LINEAR_DATA) + with self.assertRaisesRegex(TypeError, r"n_starts must be an integer\."): + pest._generate_initial_theta(seed=1, n_starts=2.0) + + def test_n_starts_numpy_integer_and_bool(self): + pest = _build_estimator(_LINEAR_DATA) + theta_starts = pest._generate_initial_theta(seed=1, n_starts=np.int64(3)) + self.assertEqual(len(theta_starts), 3) + with self.assertRaisesRegex(TypeError, r"n_starts must be an integer\."): + pest._generate_initial_theta(seed=1, n_starts=True) + + def test_multistart_table_placeholders_are_missing(self): + table = parmest._build_multistart_table(pd.DataFrame({"theta": [1.0, 2.0]})) + result_columns = [ + "converged_theta", + "final_objective", + "solver_termination", + "solve_time", + ] + self.assertEqual(list(table.columns), ["theta"] + result_columns) + self.assertTrue(table[result_columns].isna().all().all()) + + def test_n_starts_not_positive_raises(self): + pest = _build_estimator(_LINEAR_DATA) + with self.assertRaisesRegex( + ValueError, r"n_starts must be greater than zero\." + ): + pest._generate_initial_theta(seed=1, n_starts=0) + + def test_equal_bounds_warns(self): + class EqualBoundsExperiment(LinearThetaExperiment): + def create_model(self): + super().create_model() + self.model.theta.setlb(2.0) + self.model.theta.setub(2.0) + + pest = parmest.Estimator( + [EqualBoundsExperiment(x=x, y=y) for x, y in _LINEAR_DATA], + obj_function="SSE", + ) + with self.assertLogs(parmest.logger.name, level="WARNING") as logs: + theta_starts = pest._generate_initial_theta(seed=1, n_starts=2) + self.assertEqual( + logs.output, + [ + f"WARNING:{parmest.logger.name}:Theta ['theta'] has equal lower and " + "upper bounds. Fix it instead of estimating it, or widen its bounds." + ], + ) + self.assertEqual(theta_starts["theta"].tolist(), [2.0, 2.0]) + + def test_user_supplied_empty_raises(self): + pest = _build_estimator(_LINEAR_DATA) + with self.assertRaisesRegex( + ValueError, r"user_supplied_vals must contain at least one starting value\." + ): + pest._generate_initial_theta(user_supplied_vals={"theta": []}) + + def test_invalid_sampling_method_raises(self): + pest = _build_estimator(_LINEAR_DATA) + with self.assertRaisesRegex( + ValueError, + r"Invalid multistart_sampling_method: 'bad_method'\. Choose from: " + r"\['uniform_random', 'latin_hypercube', 'sobol_sampling'\]\.", + ): + pest._generate_initial_theta( + seed=1, n_starts=2, multistart_sampling_method="bad_method" + ) + + def test_sampling_method_with_user_supplied_vals_warns(self): + pest = _build_estimator(_LINEAR_DATA) + starts = pd.DataFrame({"theta": [-9.0, 9.0]}) + log = io.StringIO() + with LoggingIntercept(log, "pyomo.contrib.parmest", logging.WARNING): + theta_starts = pest._generate_initial_theta( + multistart_sampling_method="latin_hypercube", user_supplied_vals=starts + ) + self.assertIn( + "multistart_sampling_method is ignored when user_supplied_vals " + "is given.", + log.getvalue(), + ) + # The user-supplied starts are used, not sampled ones + self.assertEqual(theta_starts["theta"].tolist(), [-9.0, 9.0]) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_estimator_state_after_multistart_is_best_start(self): + pest = _build_sine_estimator(noise=0.02) + # Best start first, so leftover state from the last solve is detected + starts = pd.DataFrame({"k": [2.3, 6.0]}) + multistart_result, best_theta, best_obj = pest.theta_est_multistart( + user_supplied_vals=starts + ) + self.assertAlmostEqual(multistart_result.loc[1, "converged_k"], 6.18, places=1) + self.assertAlmostEqual(best_theta["k"], 2.0, delta=0.01) + self.assertLess(best_obj, multistart_result.loc[1, "final_objective"]) + # The best start's solution is restored as-is, not solved again. + self.assertEqual(pest.estimated_theta, best_theta) + self.assertEqual(pest.obj_value, best_obj) + self.assertEqual( + pyo.value(pest.ef_instance.parmest_theta["k"]), best_theta["k"] + ) + # cov_est must match a run whose only start is the best one. + # reduced_hessian uses ef_instance; finite_difference uses + # estimated_theta. + ref = _build_sine_estimator(noise=0.02) + ref.theta_est_multistart(user_supplied_vals=pd.DataFrame({"k": [2.3]})) + methods = ["finite_difference"] + if parmest.inverse_reduced_hessian_available: + methods.append("reduced_hessian") + for method in methods: + np.testing.assert_allclose( + pest.cov_est(method=method).to_numpy(), + ref.cov_est(method=method).to_numpy(), + rtol=1e-6, + err_msg=method, + ) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_file_name_writes_results(self): + pest = _build_estimator(_LINEAR_DATA) + with TempfileManager.new_context() as tempfiles: + file_name = os.path.join(tempfiles.mkdtemp(), "multistart.csv") + multistart_result, _, _ = pest.theta_est_multistart( + user_supplied_vals={"theta": [-1.0, 1.0]}, file_name=file_name + ) + saved = pd.read_csv(file_name) + self.assertEqual(list(saved.columns), list(multistart_result.columns)) + np.testing.assert_allclose( + saved["final_objective"], multistart_result["final_objective"] + ) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_some_starts_fail(self): + # Start -9 is not optimal and start 0 raises, so the best start is the + # only optimal one (9), and the failed starts are recorded, not raised + exp_list = [LinearThetaExperiment(x, y) for x, y in _LINEAR_DATA] + pest = _FailingStartsEstimator(exp_list, obj_function="SSE") + pest.nonoptimal_starts = (-9.0,) + pest.exception_starts = (0.0,) + log = io.StringIO() + with LoggingIntercept(log, "pyomo.contrib.parmest", logging.WARNING): + multistart_result, best_theta, best_obj = pest.theta_est_multistart( + user_supplied_vals={"theta": [-9.0, 0.0, 9.0]} + ) + self.assertEqual( + multistart_result["solver_termination"].tolist(), + [ + str(pyo.TerminationCondition.maxIterations), + "exception: solver failed", + str(pyo.TerminationCondition.optimal), + ], + ) + self.assertTrue(multistart_result["final_objective"][:2].isna().all()) + self.assertTrue(multistart_result["converged_theta"][:2].isna().all()) + self.assertIn("Start 1 raised an exception: solver failed", log.getvalue()) + self.assertAlmostEqual(best_theta["theta"], 1.0, places=6) + self.assertAlmostEqual( + best_obj, multistart_result.loc[2, "final_objective"], places=12 + ) + self.assertEqual(pest.estimated_theta, best_theta) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_all_starts_fail_returns_none_and_keeps_state(self): + # best_theta is None only when every start fails + pest = _build_sine_estimator(solver_options={"max_iter": 1}) + # Earlier state is kept when no start converges + pest.estimated_theta = {"k": 1.23} + pest.obj_value = 4.56 + log = io.StringIO() + with LoggingIntercept(log, "pyomo.contrib.parmest", logging.WARNING): + multistart_result, best_theta, best_obj = pest.theta_est_multistart( + n_starts=3, seed=3 + ) + self.assertTrue( + ( + multistart_result["solver_termination"] + == str(pyo.TerminationCondition.maxIterations) + ).all() + ) + self.assertTrue(multistart_result["final_objective"].isna().all()) + self.assertIsNone(best_theta) + self.assertTrue(np.isnan(best_obj)) + self.assertIn("None of the 3 starts terminated optimally.", log.getvalue()) + self.assertEqual(pest.estimated_theta, {"k": 1.23}) + self.assertEqual(pest.obj_value, 4.56) + + ########################### # tests for deprecated UI # ###########################