diff --git a/doc/OnlineDocs/explanation/analysis/parmest/driver.rst b/doc/OnlineDocs/explanation/analysis/parmest/driver.rst index 3bfab301244..7312b897b6c 100644 --- a/doc/OnlineDocs/explanation/analysis/parmest/driver.rst +++ b/doc/OnlineDocs/explanation/analysis/parmest/driver.rst @@ -128,6 +128,8 @@ the following methods: :nosignatures: ~pyomo.contrib.parmest.parmest.Estimator.theta_est + ~pyomo.contrib.parmest.parmest.Estimator.theta_est_multistart + ~pyomo.contrib.parmest.parmest.Estimator.profile_likelihood ~pyomo.contrib.parmest.parmest.Estimator.cov_est ~pyomo.contrib.parmest.parmest.Estimator.theta_est_bootstrap ~pyomo.contrib.parmest.parmest.Estimator.theta_est_leaveNout @@ -145,6 +147,7 @@ results and fit distributions to theta values. ~pyomo.contrib.parmest.graphics.pairwise_plot ~pyomo.contrib.parmest.graphics.grouped_boxplot ~pyomo.contrib.parmest.graphics.grouped_violinplot + ~pyomo.contrib.parmest.graphics.profile_likelihood_plot ~pyomo.contrib.parmest.graphics.fit_rect_dist ~pyomo.contrib.parmest.graphics.fit_mvn_dist ~pyomo.contrib.parmest.graphics.fit_kde_dist 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/doc/OnlineDocs/explanation/analysis/parmest/graphics.rst b/doc/OnlineDocs/explanation/analysis/parmest/graphics.rst index a0837472bbb..959d76a1c90 100644 --- a/doc/OnlineDocs/explanation/analysis/parmest/graphics.rst +++ b/doc/OnlineDocs/explanation/analysis/parmest/graphics.rst @@ -8,6 +8,7 @@ parmest includes the following functions to help visualize results: * :class:`~pyomo.contrib.parmest.graphics.grouped_boxplot` * :class:`~pyomo.contrib.parmest.graphics.grouped_violinplot` * :class:`~pyomo.contrib.parmest.graphics.pairwise_plot` +* :class:`~pyomo.contrib.parmest.graphics.profile_likelihood_plot` Grouped boxplots and violinplots are used to compare datasets, generally before and after data reconciliation. Pairwise plots are used to @@ -26,6 +27,12 @@ include the following optional information: (i.e. 0.8). For plots with more than 2 parameters, theta* is used to extract a slice of the contour lines for each pairwise plot. +Profile likelihood plots show the likelihood ratio statistic of each +profiled parameter from +:class:`~pyomo.contrib.parmest.parmest.Estimator.profile_likelihood`, with +the chi-square threshold of each confidence level. The confidence interval of +a parameter is where the statistic is below the threshold. + The following examples were generated using the reactor design example. :numref:`fig-boxplot` uses output from data reconciliation, :numref:`fig-pairwise1` uses output from the bootstrap analysis, and 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/profile_likelihood_example.py b/pyomo/contrib/parmest/examples/rooney_biegler/profile_likelihood_example.py new file mode 100644 index 00000000000..e215aa26fb7 --- /dev/null +++ b/pyomo/contrib/parmest/examples/rooney_biegler/profile_likelihood_example.py @@ -0,0 +1,58 @@ +# ____________________________________________________________________________________ +# +# 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"], + ) + + # Build experiment list + exp_list = [RooneyBieglerExperiment(data.loc[i, :]) for i in range(data.shape[0])] + + # Create estimator + pest = parmest.Estimator(exp_list, obj_function="SSE") + + # Compute profile likelihood for both unknown parameters. + # Use a small grid for quick terminal runs. + profiles, intervals, theta_hat, obj_hat = pest.profile_likelihood( + profiled_theta=["asymptote", "rate_constant"], + alphas=[0.9, 0.95], + n_grid=9, + warmstart="neighbor", + # Demonstrate baseline from multistart integration: + use_multistart_for_baseline=True, + baseline_multistart_kwargs={ + "n_starts": 5, + "multistart_sampling_method": "uniform_random", + "seed": 7, + }, + ) + + print("\nBaseline:") + print(theta_hat, obj_hat) + print("\nProfile of asymptote:") + print(profiles.loc["asymptote", ["obj", "lr_stat", 0.95, "success"]]) + print("\nProfile confidence intervals:") + print(intervals) + + # Plot the profiles with the threshold of each alpha + parmest.graphics.profile_likelihood_plot(profiles, intervals) + + +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/graphics.py b/pyomo/contrib/parmest/graphics.py index bed9f9eb824..dc42ac58d08 100644 --- a/pyomo/contrib/parmest/graphics.py +++ b/pyomo/contrib/parmest/graphics.py @@ -488,6 +488,91 @@ def pairwise_plot( plt.close() +def profile_likelihood_plot( + profiles, intervals=None, filename=None, y="lr_stat", ylabel=None, show=True +): + """ + Plot profile likelihood curves from Estimator.profile_likelihood results. + + Parameters + ---------- + profiles: DataFrame + Profiles returned by ``Estimator.profile_likelihood()``, indexed by + ``profiled_theta`` and ``theta_value``. + intervals: DataFrame, optional + Intervals returned by ``Estimator.profile_likelihood()``. If provided + and y is ``lr_stat``, draw the chi-square threshold line of each alpha. + filename: string, optional + Filename used to save the figure. + y: string, optional + Y-axis column to plot. Default is ``lr_stat``. + ylabel: string, optional + Y-axis label. Default is the value of ``y``. + show: bool, optional + If True and filename is not given, show the figure. Default is True. + + Returns + ------- + tuple containing the figure and axes objects + """ + assert isinstance(profiles, pd.DataFrame) + assert isinstance(intervals, (type(None), pd.DataFrame)) + assert isinstance(filename, (type(None), str)) + assert isinstance(y, str) + assert isinstance(ylabel, (type(None), str)) + + if profiles.empty: + raise ValueError("profiles DataFrame is empty.") + if y not in profiles.columns: + raise KeyError(f"profiles DataFrame is missing the '{y}' column.") + + thetas = list(profiles.index.unique(level="profiled_theta")) + + fig, axes = plt.subplots( + nrows=len(thetas), + ncols=1, + figsize=(6.5, max(3.0, 2.8 * len(thetas))), + squeeze=False, + ) + + if ylabel is None: + ylabel = y + + for i, theta in enumerate(thetas): + ax = axes[i, 0] + subset = profiles.loc[theta] + ax.plot(subset.index, subset[y], marker="o", linewidth=1.5) + failed = subset[~subset["success"]] + if len(failed) > 0: + # Failed solves have no y value, so mark them on the x-axis + ax.scatter( + failed.index, + np.zeros(len(failed)), + marker="x", + color="tab:red", + s=24, + label="failed", + transform=ax.get_xaxis_transform(), + clip_on=False, + ) + ax.legend(loc="best", prop={"size": 8}) + # The thresholds are on the lr_stat scale + if intervals is not None and y == "lr_stat": + for threshold in intervals.loc[theta, "threshold"]: + ax.axhline(threshold, color="tab:orange", linestyle="--", linewidth=1.0) + ax.set_xlabel(str(theta)) + ax.set_ylabel(ylabel) + ax.set_title(f"profiled_theta: {theta}") + + if filename is not None: + fig.savefig(filename) + plt.close(fig) + elif show: + plt.show() + + return fig, axes + + def fit_rect_dist(theta_values, alpha): """ Fit an alpha-level rectangular distribution to theta values diff --git a/pyomo/contrib/parmest/parmest.py b/pyomo/contrib/parmest/parmest.py index fc76d21c94e..a74565e1676 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,94 @@ 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``, ``initialization_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["initialization_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): """ @@ -1341,7 +1434,9 @@ def _instance_creation_callback(self, experiment_number=None, cb_data=None): model = self._create_parmest_model(experiment_number) return model - def _create_scenario_blocks(self, bootlist=None, theta_vals=None, fix_theta=False): + def _create_scenario_blocks( + self, bootlist=None, theta_vals=None, fix_theta=False, fixed_theta_values=None + ): """ Create scenario blocks for parameter estimation. @@ -1356,6 +1451,13 @@ def _create_scenario_blocks(self, bootlist=None, theta_vals=None, fix_theta=Fals fix_theta : bool, optional If True, fix the theta values in the model. If False, leave them free. Default is False. + fixed_theta_values : dict, optional + Dictionary of values keyed by theta name for thetas to fix at those + values while the other thetas stay free (used by + profile_likelihood). These values take precedence over theta_vals. + Fixed thetas are not linked to the parent theta variables. + Default is None. + Returns ------- model : ConcreteModel @@ -1376,6 +1478,9 @@ def _create_scenario_blocks(self, bootlist=None, theta_vals=None, fix_theta=Fals # they serve as user-facing labels and result keys. model.parmest_theta = pyo.Var(model._parmest_theta_names) + if fixed_theta_values is None: + fixed_theta_values = {} + # Initialize parent/global theta values from the template model. for name, cuid in zip(expanded_theta_names, expanded_theta_cuids): template_theta_var = cuid.find_component_on(template_model) @@ -1393,7 +1498,9 @@ def _create_scenario_blocks(self, bootlist=None, theta_vals=None, fix_theta=Fals else: parent_theta_var.set_value(pyo.value(template_theta_var)) - if fix_theta: + if name in fixed_theta_values: + parent_theta_var.fix(fixed_theta_values[name]) + elif fix_theta: parent_theta_var.fix() else: parent_theta_var.unfix() @@ -1430,6 +1537,10 @@ def _create_scenario_blocks(self, bootlist=None, theta_vals=None, fix_theta=Fals model.theta_link_constraints = pyo.ConstraintList() + # Theta values each Experiment built its model with (its states are + # consistent with these). Used by _initialize_scenario_states. + model._parmest_experiment_theta = {} + # Link scenario-local theta variables to the parent/global EF theta vars. # CUIDs are used for component lookup. Names are only used to index the # parent EF theta variable. @@ -1446,9 +1557,10 @@ def _create_scenario_blocks(self, bootlist=None, theta_vals=None, fix_theta=Fals f"in scenario block {i}." ) + model._parmest_experiment_theta[i, name] = child_theta_var.value child_theta_var.set_value(theta_value) - if fix_theta: + if fix_theta or name in fixed_theta_values: child_theta_var.fix() else: child_theta_var.unfix() @@ -1474,6 +1586,317 @@ def total_obj(m): self.ef_instance = model return model + # Estimator attributes that each _Q_opt call overwrites with its solution + _ESTIMATION_STATE_ATTRS = ("ef_instance", "estimated_theta", "obj_value") + + def _save_estimation_state(self): + """ + Return the solved model, estimated theta and objective value that are + set, for use with _restore_estimation_state. + """ + state = {} + for attr in self._ESTIMATION_STATE_ATTRS: + if hasattr(self, attr): + state[attr] = getattr(self, attr) + return state + + def _restore_estimation_state(self, state): + """ + Restore the state returned by _save_estimation_state, removing + attributes that were not set when it was saved. + """ + for attr in self._ESTIMATION_STATE_ATTRS: + if attr in state: + setattr(self, attr, state[attr]) + elif hasattr(self, attr): + delattr(self, attr) + + def _copy_scenario_values(self, source, target): + """ + Copy the free variable values of a solved extensive form model into a + new one with the same scenario blocks (used to warm start a profile + grid value from the previous one) + + Fixed variables (data, experiment inputs, fixed thetas) keep the + target's values. The theta values of the source blocks are recorded + as the target's ``_parmest_experiment_theta``, since the copied states + are consistent with them. + + Parameters + ---------- + source : ConcreteModel + Solved extensive form model from _create_scenario_blocks. + target : ConcreteModel + New extensive form model built for the same experiments. + """ + theta_names = list(target._parmest_theta_names) + for name in theta_names: + if not target.parmest_theta[name].fixed: + target.parmest_theta[name].set_value( + pyo.value(source.parmest_theta[name]) + ) + for i in target.scenario_indices: + source_block = source.exp_scenarios[i] + target_block = target.exp_scenarios[i] + for target_var in target_block.component_data_objects( + pyo.Var, descend_into=True + ): + if target_var.fixed: + continue + cuid = ComponentUID(target_var, context=target_block) + source_var = cuid.find_component_on(source_block) + if source_var is not None and source_var.value is not None: + target_var.set_value(source_var.value, skip_validation=True) + for name, cuid in zip(theta_names, target._parmest_theta_cuids): + source_theta = cuid.find_component_on(source_block) + target._parmest_experiment_theta[i, name] = source_theta.value + + def _initialize_scenario_states(self, model): + """ + Initialize the states of each scenario block at its current theta + + Each experiment model is built by its Experiment class, usually with + states that are consistent with the Experiment's own theta values. When + theta is moved to a new point (a multistart start or a profile grid + value), those states no longer match it. Each scenario block is + therefore solved with every theta fixed at its current value (for a + typical model this is a square solve), so that the full estimation + problem starts from states consistent with theta. Theta is then + returned to its previous fixed/free status. + + A direct solve can fail when the new theta is far from the theta the + states were built with (e.g., a stiff ODE trajectory). In that case + theta is moved from the Experiment's values to the new values in + ``continuation_steps`` equal steps, each solve starting from the + previous one, for each number of steps in turn. + + If no attempt terminates optimally, the block's variable values are + restored to what they were before and a warning is logged. + + Parameters + ---------- + model : ConcreteModel + Extensive form model from _create_scenario_blocks. + + Returns + ------- + termination : pyomo.opt.TerminationCondition or str + "optimal" if every block solved optimally, otherwise the + termination condition (or exception message) of the first block + that did not. + """ + sol = SolverFactory('ipopt') + if self.solver_options is not None: + for key in self.solver_options: + sol.options[key] = self.solver_options[key] + + # Number of equal theta steps tried in turn; 1 is a direct solve + continuation_steps = (1, 4, 16) + theta_names = list(model._parmest_theta_names) + experiment_theta = getattr(model, "_parmest_experiment_theta", {}) + + def _solve_block(block): + try: + results = sol.solve(block, tee=self.tee, load_solutions=False) + except Exception as exc: + return False, f"exception: {exc}" + # Load values only after an optimal solve, so a failed solve never + # overwrites the current point + if check_optimal_termination(results): + block.solutions.load_from(results) + return True, results.solver.termination_condition + return False, results.solver.termination_condition + + worst = pyo.TerminationCondition.optimal + for i in model.scenario_indices: + block = model.exp_scenarios[i] + theta_vars = [ + cuid.find_component_on(block) for cuid in model._parmest_theta_cuids + ] + was_fixed = [v.fixed for v in theta_vars] + target = [v.value for v in theta_vars] + origin = [ + experiment_theta.get((i, name), value) + for name, value in zip(theta_names, target) + ] + block_vars = list(block.component_data_objects(pyo.Var, descend_into=True)) + saved_values = [v.value for v in block_vars] + objectives = list(block.component_objects(pyo.Objective)) + + # Reuse the block's own objective so models with extra degrees of + # freedom are initialized at their best fit for this theta + for obj in objectives: + obj.activate() + results_ok = False + termination = None + try: + for n_steps in continuation_steps: + if n_steps > 1 and origin == target: + break + # Each attempt starts from the Experiment's initialization + for v, value in zip(block_vars, saved_values): + v.set_value(value, skip_validation=True) + for step in range(1, n_steps + 1): + frac = step / n_steps + for v, a, b in zip(theta_vars, origin, target): + if a is None or b is None: + v.fix(b) + else: + v.fix(a + frac * (b - a)) + results_ok, termination = _solve_block(block) + if not results_ok: + break + if results_ok: + break + finally: + for obj in objectives: + obj.deactivate() + for v, value, fixed in zip(theta_vars, target, was_fixed): + v.set_value(value) + if not fixed: + v.unfix() + + if not results_ok: + for v, value in zip(block_vars, saved_values): + v.set_value(value, skip_validation=True) + logger.info( + f"State initialization of scenario {i} at the current theta " + f"did not terminate optimally ({termination}); starting " + "from the Experiment's initialization instead." + ) + if worst == pyo.TerminationCondition.optimal: + worst = termination + + return worst + + 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 +1904,10 @@ def _Q_opt( solver="ef_ipopt", theta_vals=None, fix_theta=False, + multistart=False, + fixed_theta_values=None, + initialize_states=False, + warm_start_model=None, ): """ _Q_opt method for parameter estimation using an extensive form @@ -1515,6 +1942,25 @@ 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. + fixed_theta_values : dict, optional + Dictionary keyed by theta name of thetas to fix while the other + thetas are estimated (used by profile_likelihood); see + _create_scenario_blocks. If given, the solve is handled as with + multistart=True. Default is None. + initialize_states : bool, optional + If True, initialize each scenario block's states at theta_vals + (see _initialize_scenario_states) before the estimation solve. The + termination of that step is stored in + ``self._initialization_termination``. Default is False. + warm_start_model : ConcreteModel, optional + Solved extensive form model for the same experiments. Its free + variable values (states and thetas) are copied into the new model + before the initialization and solve (see _copy_scenario_values). + Default is None. + Returns ------- obj_value : float or None @@ -1525,7 +1971,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 or fixed_theta_values is given 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,26 +1982,38 @@ def _Q_opt( If fix_theta is True, this contains the fixed theta values used in the model. + + If multistart is True or fixed_theta_values is given 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, fixed_theta_values is not given, 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, or fixed_theta_values is given. """ # Create extended form model with scenario blocks model = self._create_scenario_blocks( - bootlist=bootlist, theta_vals=theta_vals, fix_theta=fix_theta + bootlist=bootlist, + theta_vals=theta_vals, + fix_theta=fix_theta, + fixed_theta_values=fixed_theta_values, ) expanded_theta_names = list(model._parmest_theta_names) - logger.debug("Parmest _Q_opt model with scenario blocks:") + # Start from a previous solution (e.g., the neighboring profile value) + if warm_start_model is not None: + self._copy_scenario_values(warm_start_model, model) - if logger.isEnabledFor(logging.DEBUG): - model.pprint() + # Make the states consistent with the starting theta + self._initialization_termination = None + if initialize_states: + self._initialization_termination = self._initialize_scenario_states(model) # Check solver and set options if solver == "k_aug": @@ -1585,7 +2046,14 @@ def _Q_opt( obj_value = None return obj_value, theta_estimates, termination_condition - if not fix_theta: + partial_fix_mode = bool(fixed_theta_values) + + # If not fixing theta, a non-optimal solve raises, or in multistart + # and partial-fix (profile likelihood) modes returns only the + # termination condition + if not fix_theta and not check_optimal_termination(solve_result): + if multistart or partial_fix_mode: + return None, None, termination_condition assert_optimal_termination(solve_result) model.solutions.load_from(solve_result) @@ -1600,8 +2068,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, in multistart mode, or fixing some thetas, return + # objective value, theta estimates, and solver status + if fix_theta or multistart or partial_fix_mode: return obj_value, theta_estimates, termination_condition # Extract return values if requested @@ -2260,7 +2729,702 @@ 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, + initialize_states=True, + ): + """ + 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). + + By default, each start first solves every experiment with theta fixed + at the start values, so the model states (e.g., a discretized ODE + trajectory) are consistent with that start. Without this step every + start would begin from the states the Experiment class built for its + own theta values, and only theta would differ between starts. + + 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). + initialize_states: bool, optional + If True, initialize the states of every experiment at each start's + theta values before solving (see above). If an experiment's + initialization does not solve optimally, that start uses the + Experiment's initialization and a warning is logged. Default is + True. + + Returns + ------- + multistart_result: pd.DataFrame + One row per start: starting and converged (``converged_``) + theta values, ``final_objective``, ``solver_termination``, + ``initialization_termination`` (None if initialize_states is + False) and ``solve_time`` (seconds, including initialization). + 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 + prior_state = self._save_estimation_state() + + # 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() + self._initialization_termination = None + try: + obj, theta_hat, termination = self._Q_opt( + theta_vals=theta_vals, + multistart=True, + initialize_states=initialize_states, + ) + 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}" + if self._initialization_termination is not None: + multistart_result.at[i, "initialization_termination"] = str( + self._initialization_termination + ) + 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 initialize_states: + init_status = multistart_result["initialization_termination"] + n_init_failed = int( + ((init_status != "") & (init_status != "optimal")).sum() + ) + if n_init_failed > 0: + logger.warning( + f"State initialization did not terminate optimally for " + f"{n_init_failed} of {len(theta_starts)} starts; those starts " + "began from the Experiment's initialization (see the " + "initialization_termination column)." + ) + + if best_theta is None: + logger.warning( + f"None of the {len(theta_starts)} starts terminated optimally." + ) + self._restore_estimation_state(prior_state) + 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 _build_profile_grid(self, profiled_theta, grid, n_grid, model): + """ + Validate the grid values of one profiled theta, or build n_grid evenly + spaced values between its bounds in model if grid is None. + """ + if grid is not None and not isinstance( + grid, (list, tuple, np.ndarray, pd.Series) + ): + raise TypeError("grid must be a sequence of numeric values or None.") + + if grid is None: + theta_var = model.find_component(profiled_theta) + if theta_var.lb is None or theta_var.ub is None: + raise ValueError( + f"Cannot auto-build grid for '{profiled_theta}' without lower " + f"and upper bounds." + ) + return np.linspace(theta_var.lb, theta_var.ub, n_grid) + + values = np.asarray(grid, dtype=float) + if values.size == 0: + raise ValueError("Provided grid must contain at least one value.") + return values + + def _split_grid_at_center(self, grid_values, center): + """ + Split profile grid values at the value closest to center, for + continuation warm starts. + + Parameters + ---------- + grid_values: list of float + Sorted grid values of the profiled theta. + center: float + Value of the profiled theta at the baseline estimate. + + Returns + ------- + branches: list of list + Values from the closest grid value upward, then (if any) the values + below it in decreasing order, so each branch moves away from center. + """ + # Grid values are rounded, so center may not be in the grid exactly + pivot = min(grid_values, key=lambda v: abs(v - center)) + upper = [v for v in grid_values if v >= pivot] + lower = [v for v in reversed(grid_values) if v < pivot] + if lower: + return [upper, lower] + return [upper] + + def _profile_lr_stat(self, obj, obj_hat): + """ + Likelihood ratio statistic of profile objective values (see + profile_likelihood). Logs a warning and returns NaN where it is not + defined. + """ + obj = np.asarray(obj, dtype=float) + if self.regularization is not None or not isinstance( + self.obj_function, ObjectiveType + ): + logger.warning( + "profile_likelihood: lr_stat is only defined for the 'SSE' and " + "'SSE_weighted' objectives without regularization, so it is " + "set to NaN." + ) + return np.full(obj.shape, np.nan) + + # The objective is half the weighted SSE averaged over the S + # experiments, so 2 * S * obj is the weighted SSE + if self.obj_function == ObjectiveType.SSE_weighted: + return 2.0 * len(self.exp_list) * (obj - obj_hat) + + # SSE: the variance is profiled out, and the likelihood is unbounded + # at a perfect fit + if obj_hat <= 0: + logger.warning( + "profile_likelihood: the baseline objective is zero (a perfect " + "fit), so lr_stat is not defined for the 'SSE' objective and " + "is set to NaN." + ) + return np.full(obj.shape, np.nan) + # One residual per experiment output + n_residuals = 0 + for exp in self.exp_list: + n_residuals += len(_get_labeled_model(exp).experiment_outputs) + return n_residuals * np.log(obj / obj_hat) + + def _profile_intervals(self, profiles, profiled_theta_list, theta_hat, thresholds): + """ + Profile confidence interval of each theta (see profile_likelihood). + + Parameters + ---------- + profiles: pd.DataFrame + Profiles indexed by profiled theta and value, with an lr_stat + column (NaN where the solve failed). + profiled_theta_list: list of str + Names of the profiled thetas. + theta_hat: dict + Baseline theta values keyed by theta name. + thresholds: dict + Chi-square threshold of lr_stat keyed by alpha. + + Returns + ------- + intervals: pd.DataFrame + One row per profiled theta and alpha (see profile_likelihood). + """ + rows = [] + for pname in profiled_theta_list: + prof = profiles.loc[pname] + # Failed solves (and undefined lr_stat) have no value to compare + prof = prof[prof["lr_stat"].notna()] + values = prof.index.to_numpy(dtype=float) + lr = prof["lr_stat"].to_numpy(dtype=float) + for alpha, threshold in thresholds.items(): + bounds = {"lower": np.nan, "upper": np.nan} + if len(values) > 0: + # Walk outward from the grid value closest to theta_hat + # until lr_stat reaches the threshold + center = int(np.argmin(np.abs(values - theta_hat[pname]))) + # If theta_hat is not inside the region, there is no + # interval around it + if lr[center] < threshold: + for side, step in (("lower", -1), ("upper", 1)): + inside = center + while 0 <= inside + step < len(values): + outside = inside + step + if lr[outside] >= threshold: + # Linear interpolation of the crossing + slope = (values[outside] - values[inside]) / ( + lr[outside] - lr[inside] + ) + bounds[side] = ( + values[inside] + + (threshold - lr[inside]) * slope + ) + break + inside = outside + rows.append( + { + "profiled_theta": pname, + "alpha": alpha, + "theta_hat": theta_hat[pname], + "lower": bounds["lower"], + "upper": bounds["upper"], + "threshold": threshold, + "lower_bounded": not np.isnan(bounds["lower"]), + "upper_bounded": not np.isnan(bounds["upper"]), + } + ) + return pd.DataFrame(rows).set_index(["profiled_theta", "alpha"]) + + def _profile_sweep( + self, + profiled_theta_list, + grids, + theta_hat, + warmstart, + max_consecutive_failures, + return_theta_paths, + initialize_states=True, + ): + """ + Solve every grid value of each profiled theta (see profile_likelihood), + with grids keyed by profiled theta name. + + Returns + ------- + rows: list of dict + One row of the profiles DataFrame per grid value solved. + best_obj: float or None + Lowest objective value of the successful solves (None if every + solve failed). + best_theta: dict or None + Estimated value of every theta at best_obj. + """ + rows = [] + best_obj = None + best_theta = None + for pname in profiled_theta_list: + # The theta_hat value is always solved, so each profile includes + # the baseline; np.unique also sorts + grid_values = np.append(grids[pname], theta_hat[pname]) + grid_values = np.unique(np.round(grid_values, decimals=14)).tolist() + + # "neighbor" solves each side outward from theta_hat, so every + # solve starts close to the previous solution + if warmstart == "neighbor": + branches = self._split_grid_at_center( + grid_values, center=theta_hat[pname] + ) + else: + branches = [grid_values] + + # Solution at the first value solved (closest to theta_hat), + # used to start the second side. With "neighbor", the solved model + # is kept too, so the next value starts from its states as well + center_theta = theta_hat + center_model = None + center_value = branches[0][0] + for branch in branches: + previous_theta = center_theta + previous_model = center_model + consecutive_failures = 0 + + for value in branch: + # Start the other thetas from the previous solution, with + # the profiled theta at this grid value + init_theta = dict(previous_theta) + init_theta[pname] = value + + t0 = time.time() + try: + obj_val, theta_conv, term = self._Q_opt( + theta_vals=init_theta, + fixed_theta_values={pname: value}, + initialize_states=initialize_states, + warm_start_model=previous_model, + ) + status = str(term) + except Exception as exc: + theta_conv = None + status = f"exception: {exc}" + + # theta_conv is None unless the solve terminated optimally + success = theta_conv is not None + if success: + consecutive_failures = 0 + if warmstart == "neighbor": + previous_theta = theta_conv + previous_model = self.ef_instance + if value == center_value: + center_theta = theta_conv + center_model = self.ef_instance + # Track the lowest objective to check the baseline + if best_obj is None or obj_val < best_obj: + best_obj = obj_val + best_theta = dict(theta_conv) + else: + obj_val = np.nan + consecutive_failures += 1 + + row = { + "profiled_theta": pname, + "theta_value": value, + "obj": obj_val, + "status": status, + "success": success, + "solve_time": time.time() - t0, + } + if return_theta_paths and success: + for tname, tval in theta_conv.items(): + row[tname] = tval + rows.append(row) + + # Stop this side of the profile (the other side is + # still solved) + if ( + max_consecutive_failures is not None + and consecutive_failures >= max_consecutive_failures + ): + break + return rows, best_obj, best_theta + + def profile_likelihood( + self, + profiled_theta, + alphas=None, + grid=None, + n_grid=21, + theta_hat=None, + obj_hat=None, + use_multistart_for_baseline=False, + baseline_multistart_kwargs=None, + warmstart="neighbor", + max_consecutive_failures=None, + return_theta_paths=True, + max_rebaseline=0, + initialize_states=True, + ): + """ + Profile likelihood for one or more thetas, fixing each profiled theta + at a grid of values and re-estimating the other thetas + + Each grid value is solved as in theta_est. If a solve finds a lower + objective than obj_hat, a warning is logged and that solution becomes + the baseline. The Estimator keeps the estimate it held before the call + (or the baseline estimate, if it is computed here), even if a lower + objective is found. + + Parameters + ---------- + profiled_theta: str or list of str + Name(s) of the theta(s) to profile, as returned by theta_est. Each + theta is profiled separately. + alphas: list of float, optional + Confidence levels (between 0 and 1) of the profile confidence + intervals. Default is None ([0.95]). + grid: list, np.ndarray, pd.Series, dict or None, optional + Values of the profiled theta, or a dict of values keyed by theta + name. If None (or a theta is missing from the dict), n_grid evenly + spaced values between the theta bounds are used. The theta_hat + value is always added. Default is None. + n_grid: int, optional + Number of grid values (at least 2) for a grid built from the theta + bounds. Default is 21. + theta_hat: dict, optional + Estimated theta values keyed by theta name. If theta_hat or obj_hat + is None, both are computed with theta_est (or + theta_est_multistart). Default is None. + obj_hat: float, optional + Objective value at theta_hat. Default is None. + use_multistart_for_baseline: bool, optional + If True, compute theta_hat and obj_hat with theta_est_multistart. + Default is False. + baseline_multistart_kwargs: dict, optional + Keyword arguments for theta_est_multistart. Default is None. + warmstart: str, optional + "neighbor" solves the grid values outward from theta_hat, upward + then downward, each starting from the last successful solution on + that side (its theta values and all its other variable values, + e.g., the states). "none" solves them in increasing order, each + starting from theta_hat and the Experiment's initialization. + Default is "neighbor". + max_consecutive_failures: int, optional + Stop a side of theta_hat ("neighbor") or a theta ("none") after + this many consecutive failed solves. Default is None (no limit). + return_theta_paths: bool, optional + If True, include the estimated value of every theta at each grid + value (one column per theta name). Default is True. + max_rebaseline: int, optional + Maximum number of times the profiles are solved again from a new + baseline, when a lower objective is found. Default is 0 (the + baseline is updated, but the profiles are not solved again). + initialize_states: bool, optional + If True, before each grid value is solved, every experiment is + solved with all thetas fixed at the starting values (the profiled + theta at the grid value), so the states are consistent with them + (see theta_est_multistart). With "neighbor" this starts from the + previous solution, so the step is small. Default is True. + + Returns + ------- + profiles: pd.DataFrame + One row per grid value solved, indexed by ``profiled_theta`` and + ``theta_value``, with columns ``obj`` (NaN if the solve failed), + ``status`` (termination condition or exception message), + ``success``, ``solve_time`` (seconds), ``lr_stat``, one column per + alpha (True if lr_stat is below the threshold) and, if + return_theta_paths is True, one column per theta name. For S + experiments with N residuals, lr_stat is 2 * S * (obj - obj_hat) + for "SSE_weighted" and N * log(obj / obj_hat) for "SSE" (variance + profiled out); it is NaN for other objectives, with + regularization, or for "SSE" when obj_hat is 0. + intervals: pd.DataFrame + Profile confidence interval of each theta, indexed by + ``profiled_theta`` and ``alpha``, with columns ``theta_hat``, + ``lower``, ``upper``, ``threshold`` (chi-square with 1 degree of + freedom), ``lower_bounded`` and ``upper_bounded``. The bounds are + linearly interpolated where lr_stat crosses the threshold on each + side of theta_hat. If it does not cross within the grid, the + bound is NaN and the bounded column is False. + theta_hat: dict + Baseline theta values (updated if a lower objective is found). + obj_hat: float + Objective value at theta_hat. + """ + if self.pest_deprecated is not None: + raise RuntimeError( + "Profile likelihood is not supported in the deprecated parmest interface." + ) + if isinstance(profiled_theta, str): + profiled_theta_list = [profiled_theta] + elif isinstance(profiled_theta, (list, tuple)): + profiled_theta_list = list(profiled_theta) + else: + raise TypeError( + "profiled_theta must be a string or a list/tuple of strings." + ) + if len(profiled_theta_list) == 0: + raise ValueError("At least one profiled theta must be provided.") + if not all(isinstance(p, str) for p in profiled_theta_list): + raise TypeError("Each profiled theta name must be a string.") + if len(profiled_theta_list) != len(set(profiled_theta_list)): + raise ValueError( + f"Duplicate profiled theta names are not allowed: " + f"{profiled_theta_list}" + ) + if not isinstance(n_grid, int): + raise TypeError("n_grid must be an integer.") + if n_grid < 2: + raise ValueError("n_grid must be at least 2.") + if warmstart not in ("neighbor", "none"): + raise ValueError("warmstart must be either 'neighbor' or 'none'.") + if max_consecutive_failures is not None: + if not isinstance(max_consecutive_failures, int): + raise TypeError("max_consecutive_failures must be an integer or None.") + if max_consecutive_failures <= 0: + raise ValueError("max_consecutive_failures must be greater than zero.") + if not isinstance(return_theta_paths, bool): + raise TypeError("return_theta_paths must be a bool.") + if not isinstance(initialize_states, bool): + raise TypeError("initialize_states must be a bool.") + if alphas is None: + alphas = [0.95] + if not isinstance(alphas, (list, tuple)) or len(alphas) == 0: + raise TypeError("alphas must be a non-empty list of floats.") + for a in alphas: + if not isinstance(a, (int, float)) or not 0 < a < 1: + raise ValueError("Each alpha must be between 0 and 1.") + if len(alphas) != len(set(alphas)): + raise ValueError(f"Duplicate alphas are not allowed: {list(alphas)}") + if not isinstance(max_rebaseline, int): + raise TypeError("max_rebaseline must be an integer.") + if max_rebaseline < 0: + raise ValueError("max_rebaseline must be non-negative.") + + # Check the names against the model, before any solve + parmest_model = self._create_parmest_model(0) + theta_names, _ = self._expanded_theta_info(parmest_model) + unknown_requested = set(profiled_theta_list).difference(theta_names) + if unknown_requested: + raise ValueError( + f"Unknown profile theta name(s): {sorted(unknown_requested)}. " + f"Known names: {theta_names}." + ) + if isinstance(grid, dict): + unknown_grid = set(grid).difference(profiled_theta_list) + if unknown_grid: + raise ValueError( + f"grid key(s) {sorted(unknown_grid)} are not profiled " + f"thetas: {profiled_theta_list}." + ) + # Theta columns of profiles would overwrite these + reserved = { + "profiled_theta", + "theta_value", + "obj", + "status", + "success", + "solve_time", + "lr_stat", + } + if return_theta_paths and reserved.intersection(theta_names): + raise ValueError( + f"Theta name(s) {sorted(reserved.intersection(theta_names))} " + f"match profiles column names; use return_theta_paths=False." + ) + + # Check the grids before the baseline, so bad input fails before any + # solve + grids = {} + for pname in profiled_theta_list: + if isinstance(grid, dict): + grid_spec = grid.get(pname) + else: + grid_spec = grid + grids[pname] = self._build_profile_grid( + profiled_theta=pname, grid=grid_spec, n_grid=n_grid, model=parmest_model + ) + + # lr_stat and the warm starts are measured from the baseline + if theta_hat is None or obj_hat is None: + if use_multistart_for_baseline: + if baseline_multistart_kwargs is None: + baseline_multistart_kwargs = {} + _, theta_hat, obj_hat = self.theta_est_multistart( + **baseline_multistart_kwargs + ) + if theta_hat is None: + raise RuntimeError( + "Failed to compute baseline from multistart: no feasible solution found." + ) + else: + obj_hat, theta_hat = self.theta_est() + + # Every theta needs a baseline value to start the profile solves + theta_hat_df = self._normalize_theta_dataframe( + pd.DataFrame([theta_hat]), model=parmest_model + ) + theta_hat = {k: float(v) for k, v in theta_hat_df.iloc[0].items()} + obj_hat = float(obj_hat) + + n_rebaseline = 0 + + # Profile solves overwrite the estimate; restore it afterwards (e.g., + # for cov_est) + prior_state = self._save_estimation_state() + try: + # Solve the profiles; a lower objective becomes the baseline, and + # the profiles are solved again up to max_rebaseline times + while True: + rows, best_obj, best_theta = self._profile_sweep( + profiled_theta_list=profiled_theta_list, + grids=grids, + theta_hat=theta_hat, + warmstart=warmstart, + max_consecutive_failures=max_consecutive_failures, + return_theta_paths=return_theta_paths, + initialize_states=initialize_states, + ) + # Relative tolerance, so solver noise does not count as a + # lower objective + if best_obj is None or best_obj >= obj_hat - 1e-8 * max( + 1.0, abs(obj_hat) + ): + break + + solve_again = n_rebaseline < max_rebaseline + if solve_again: + action = "the profiles are solved again from it" + else: + action = "lr_stat is computed from it" + logger.warning( + f"profile_likelihood: a profile solve found a lower " + f"objective ({best_obj}) than the baseline ({obj_hat}) at " + f"theta = {best_theta}, so it becomes the baseline and " + f"{action}. The Estimator estimate is not updated; re-run " + f"theta_est from this theta to update it." + ) + theta_hat = best_theta + obj_hat = best_obj + if not solve_again: + break + n_rebaseline += 1 + finally: + self._restore_estimation_state(prior_state) + + # Every grid has at least the theta_hat value, so rows is not empty + profiles = pd.DataFrame(rows) + profiles = profiles.set_index(["profiled_theta", "theta_value"]) + profiles = profiles.sort_index(kind="stable") + # lr_stat uses the final baseline; it and the alpha columns go after + # solve_time, before the theta columns + position = profiles.columns.get_loc("solve_time") + 1 + lr_stat = self._profile_lr_stat(profiles["obj"], obj_hat) + profiles.insert(position, "lr_stat", lr_stat) + thresholds = {a: scipy.stats.chi2.ppf(a, df=1) for a in alphas} + for a in alphas: + position += 1 + profiles.insert(position, a, profiles["lr_stat"] < thresholds[a]) + + intervals = self._profile_intervals( + profiles, profiled_theta_list, theta_hat, thresholds + ) + + return profiles, intervals, theta_hat, obj_hat + + def _normalize_theta_dataframe(self, theta_values, model=None): """ Validate and normalize user-provided theta_values columns. @@ -2268,11 +3432,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..f201b42024c 100644 --- a/pyomo/contrib/parmest/tests/test_examples.py +++ b/pyomo/contrib/parmest/tests/test_examples.py @@ -54,6 +54,19 @@ 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() + + @unittest.skipUnless(matplotlib_available, "test requires matplotlib") + def test_profile_likelihood_example(self): + from pyomo.contrib.parmest.examples.rooney_biegler import ( + profile_likelihood_example, + ) + + profile_likelihood_example.main() + def test_regularization_example(self): from pyomo.contrib.parmest.examples.rooney_biegler import regularization_example @@ -154,6 +167,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_graphics.py b/pyomo/contrib/parmest/tests/test_graphics.py index 42c0b2a9f1f..ca7c435236e 100644 --- a/pyomo/contrib/parmest/tests/test_graphics.py +++ b/pyomo/contrib/parmest/tests/test_graphics.py @@ -61,6 +61,42 @@ def test_grouped_boxplot(self): def test_grouped_violinplot(self): graphics.grouped_violinplot(self.A, self.B) + def test_profile_plot_smoke_single_parameter(self): + prof = pd.DataFrame( + { + "profiled_theta": ["theta"] * 3, + "theta_value": [0.8, 1.0, 1.2], + "obj": [2.5, 1.0, float("nan")], + "lr_stat": [3.0, 0.0, float("nan")], + "success": [True, True, False], + } + ).set_index(["profiled_theta", "theta_value"]) + intervals = pd.DataFrame( + {"profiled_theta": ["theta"], "alpha": [0.95], "threshold": [3.84]} + ).set_index(["profiled_theta", "alpha"]) + _, axes = graphics.profile_likelihood_plot(prof, intervals) + ax = axes[0, 0] + # The failed solve is marked on the x-axis + self.assertEqual(ax.collections[0].get_offsets()[:, 0].tolist(), [1.2]) + # Profile line and threshold line + self.assertEqual(len(ax.lines), 2) + self.assertEqual(ax.lines[1].get_ydata()[0], 3.84) + + # The lr_stat threshold is not drawn on the objective axis + _, axes = graphics.profile_likelihood_plot(prof, intervals, y="obj") + self.assertEqual(len(axes[0, 0].lines), 1) + + def test_profile_plot_smoke_multi_parameter(self): + prof = pd.DataFrame( + { + "profiled_theta": ["theta_a", "theta_a", "theta_b", "theta_b"], + "theta_value": [1.0, 2.0, -1.0, 0.0], + "lr_stat": [2.0, 0.0, 1.0, 0.0], + "success": [True, True, True, True], + } + ).set_index(["profiled_theta", "theta_value"]) + graphics.profile_likelihood_plot(prof) + if __name__ == '__main__': unittest.main() diff --git a/pyomo/contrib/parmest/tests/test_parmest.py b/pyomo/contrib/parmest/tests/test_parmest.py index 68fd5860c45..48eb1468e75 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,1156 @@ 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, + ) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_initialize_states_at_start_theta(self): + # Each Experiment builds y at its own theta (y = y_data); after the + # initialization y must be consistent with the start theta instead + pest = _build_estimator(_LINEAR_DATA) + model = pest._create_scenario_blocks(theta_vals={"theta": 5.0}) + for i, (x, y) in enumerate(_LINEAR_DATA): + self.assertAlmostEqual(pyo.value(model.exp_scenarios[i].y), y) + + termination = pest._initialize_scenario_states(model) + + self.assertEqual(termination, pyo.TerminationCondition.optimal) + for i, (x, y) in enumerate(_LINEAR_DATA): + block = model.exp_scenarios[i] + self.assertAlmostEqual(pyo.value(block.y), 5.0 + x, places=6) + # theta keeps its value and is free again for the estimation + self.assertAlmostEqual(pyo.value(block.theta), 5.0) + self.assertFalse(block.theta.fixed) + self.assertFalse(block.Total_Cost_Objective.active) + self.assertTrue(model.Obj.active) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_initialize_states_failure_restores_values(self): + class BoundedOutputExperiment(LinearThetaExperiment): + def create_model(self): + super().create_model() + # y = theta + x cannot exceed 4, so theta = 9 is infeasible + self.model.y.setub(4.0) + + pest = parmest.Estimator( + [BoundedOutputExperiment(x, y) for x, y in _LINEAR_DATA], obj_function="SSE" + ) + model = pest._create_scenario_blocks(theta_vals={"theta": 9.0}) + + termination = pest._initialize_scenario_states(model) + + self.assertNotEqual(termination, pyo.TerminationCondition.optimal) + for i, (x, y) in enumerate(_LINEAR_DATA): + block = model.exp_scenarios[i] + self.assertAlmostEqual(pyo.value(block.y), y) + self.assertAlmostEqual(pyo.value(block.theta), 9.0) + self.assertFalse(block.theta.fixed) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_multistart_records_initialization(self): + pest = _build_estimator(_LINEAR_DATA) + starts = pd.DataFrame({"theta": [-9.0, 9.0]}) + + result, _, _ = pest.theta_est_multistart(user_supplied_vals=starts) + self.assertEqual(list(result["initialization_termination"]), ["optimal"] * 2) + + result_off, _, _ = pest.theta_est_multistart( + user_supplied_vals=starts, initialize_states=False + ) + self.assertEqual(list(result_off["initialization_termination"]), [None] * 2) + # Both settings reach the same optimum on this convex problem + self.assertAlmostEqual( + result.loc[0, "converged_theta"], + result_off.loc[0, "converged_theta"], + places=6, + ) + + 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", + "initialization_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) + + +class AffineTwoThetaExperiment(Experiment): + def __init__(self, x, y): + self.x_data = x + self.y_data = y + self.model = None + + def create_model(self): + m = pyo.ConcreteModel() + m.theta_a = pyo.Var(initialize=1.0, bounds=(0.0, 4.0)) + m.theta_b = pyo.Var(initialize=0.0, bounds=(-3.0, 3.0)) + m.x = pyo.Param(initialize=float(self.x_data), mutable=False) + m.y = pyo.Var(initialize=float(self.y_data)) + m.eq = pyo.Constraint(expr=m.y == m.theta_a * m.x + m.theta_b) + self.model = m + + def label_model(self): + m = self.model + m.experiment_outputs = pyo.Suffix(direction=pyo.Suffix.LOCAL) + m.experiment_outputs.update([(m.y, float(self.y_data))]) + m.unknown_parameters = pyo.Suffix(direction=pyo.Suffix.LOCAL) + m.unknown_parameters.update( + [ + (m.theta_a, pyo.ComponentUID(m.theta_a)), + (m.theta_b, pyo.ComponentUID(m.theta_b)), + ] + ) + m.measurement_error = pyo.Suffix(direction=pyo.Suffix.LOCAL) + m.measurement_error.update([(m.y, None)]) + + def get_labeled_model(self): + self.create_model() + self.label_model() + return self.model + + +class _InitRecordingEstimator(parmest.Estimator): + """ + Estimator that records the initial theta values of each profile solve and + the number of theta_est_multistart calls. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.profile_theta_inits = [] + self.n_multistart_calls = 0 + + def theta_est_multistart(self, *args, **kwargs): + self.n_multistart_calls += 1 + return super().theta_est_multistart(*args, **kwargs) + + def _Q_opt(self, *args, **kwargs): + if kwargs.get("fixed_theta_values"): + self.profile_theta_inits.append(dict(kwargs["theta_vals"])) + return super()._Q_opt(*args, **kwargs) + + +def _build_two_theta_estimator( + estimator_class=parmest.Estimator, obj_function="SSE", **kwargs +): + # Data lie exactly on y = 2x + 1, so theta_hat = (2, 1) and, with + # theta_a fixed at a, the profiled optimum is theta_b = 5 - 2a. + exp_list = [ + AffineTwoThetaExperiment(1.0, 3.0), + AffineTwoThetaExperiment(2.0, 5.0), + AffineTwoThetaExperiment(3.0, 7.0), + ] + return estimator_class(exp_list, obj_function=obj_function, **kwargs) + + +def _build_rooney_biegler_estimator(estimator_class=parmest.Estimator): + from pyomo.contrib.parmest.examples.rooney_biegler.rooney_biegler import ( + RooneyBieglerExperiment, + ) + + 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"], + ) + return estimator_class( + [RooneyBieglerExperiment(data.loc[i, :]) for i in range(data.shape[0])], + obj_function="SSE", + ) + + +@unittest.skipIf( + not parmest.parmest_available, + "Cannot test parmest: required dependencies are missing", +) +class TestParmestProfileLikelihood(unittest.TestCase): + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_likelihood_results(self): + pest = _build_two_theta_estimator() + prof, intervals, _, obj_hat = pest.profile_likelihood( + "theta_a", + alphas=[0.9, 0.95], + grid=[1.2, 2.4, 2.0], + theta_hat={"theta_a": 2.0, "theta_b": 1.0}, + obj_hat=0.0, + ) + self.assertEqual(prof.index.names, ["profiled_theta", "theta_value"]) + self.assertEqual( + list(prof.columns), + [ + "obj", + "status", + "success", + "solve_time", + "lr_stat", + 0.9, + 0.95, + "theta_a", + "theta_b", + ], + ) + self.assertEqual(intervals.index.names, ["profiled_theta", "alpha"]) + self.assertEqual( + list(intervals.columns), + [ + "theta_hat", + "lower", + "upper", + "threshold", + "lower_bounded", + "upper_bounded", + ], + ) + self.assertEqual(list(intervals.index), [("theta_a", 0.9), ("theta_a", 0.95)]) + # The user grid is sorted + prof = prof.loc["theta_a"] + self.assertEqual(prof.index.tolist(), [1.2, 2.0, 2.4]) + self.assertTrue(prof["success"].all()) + # theta_a is fixed at each grid value, and theta_b is re-estimated + np.testing.assert_allclose(prof["theta_a"], prof.index) + np.testing.assert_allclose(prof["theta_b"], 5.0 - 2.0 * prof.index, atol=1e-6) + # The baseline is the profile minimum + self.assertAlmostEqual(prof["obj"].min(), obj_hat, places=8) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_warmstart_neighbor_values_used(self): + # theta_hat["theta_b"] is deliberately off (0.0 instead of 1.0) so that + # warm-started initial values are distinguishable from theta_hat. + theta_hat = {"theta_a": 2.0, "theta_b": 0.0} + grid = [2.0, 2.1, 2.2] + + pest = _build_two_theta_estimator(_InitRecordingEstimator) + pest.profile_likelihood( + "theta_a", grid=grid, theta_hat=theta_hat, obj_hat=0.0, warmstart="neighbor" + ) + inits = pest.profile_theta_inits + self.assertEqual([init["theta_a"] for init in inits], grid) + # First solve starts from theta_hat; each later solve starts from the + # previous converged point (theta_b = 5 - 2 * theta_a). + self.assertEqual(inits[0]["theta_b"], 0.0) + self.assertAlmostEqual(inits[1]["theta_b"], 1.0, places=6) + self.assertAlmostEqual(inits[2]["theta_b"], 0.8, places=6) + + pest = _build_two_theta_estimator(_InitRecordingEstimator) + pest.profile_likelihood( + "theta_a", grid=grid, theta_hat=theta_hat, obj_hat=0.0, warmstart="none" + ) + self.assertEqual( + [init["theta_b"] for init in pest.profile_theta_inits], [0.0, 0.0, 0.0] + ) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_copy_scenario_values_warm_starts_states(self): + pest = _build_two_theta_estimator() + # Solved model with theta_a fixed at 2.4 (theta_b = 5 - 2 * 2.4 = 0.2) + pest._Q_opt( + theta_vals={"theta_a": 2.4, "theta_b": 0.0}, + fixed_theta_values={"theta_a": 2.4}, + ) + source = pest.ef_instance + # New model for the next grid value; its states are the Experiment's + target = pest._create_scenario_blocks( + theta_vals={"theta_a": 2.6, "theta_b": 0.2}, + fixed_theta_values={"theta_a": 2.6}, + ) + + pest._copy_scenario_values(source, target) + + for i, x in enumerate([1.0, 2.0, 3.0]): + block = target.exp_scenarios[i] + # free states and thetas come from the previous solution + self.assertAlmostEqual(pyo.value(block.y), 2.4 * x + 0.2, places=6) + self.assertAlmostEqual(pyo.value(block.theta_b), 0.2, places=6) + # the fixed (profiled) theta keeps the new grid value + self.assertEqual(pyo.value(block.theta_a), 2.6) + self.assertTrue(block.theta_a.fixed) + self.assertAlmostEqual(target._parmest_experiment_theta[i, "theta_a"], 2.4) + + # The initialization then makes the states consistent with 2.6 + pest._initialize_scenario_states(target) + for i, x in enumerate([1.0, 2.0, 3.0]): + block = target.exp_scenarios[i] + self.assertAlmostEqual(pyo.value(block.y), 2.6 * x + 0.2, places=6) + self.assertFalse(block.theta_b.fixed) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_initialize_states_same_profile(self): + kwargs = dict( + grid=[1.6, 2.0, 2.4], + theta_hat={"theta_a": 2.0, "theta_b": 1.0}, + obj_hat=0.0, + ) + for warmstart in ("neighbor", "none"): + prof_on, _, _, _ = _build_two_theta_estimator().profile_likelihood( + "theta_a", warmstart=warmstart, **kwargs + ) + prof_off, _, _, _ = _build_two_theta_estimator().profile_likelihood( + "theta_a", warmstart=warmstart, initialize_states=False, **kwargs + ) + np.testing.assert_allclose( + prof_on["obj"].to_numpy(), prof_off["obj"].to_numpy(), atol=1e-8 + ) + np.testing.assert_allclose( + prof_on["theta_b"].to_numpy(), prof_off["theta_b"].to_numpy(), atol=1e-6 + ) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_failure_recorded_continue(self): + pest = _build_two_theta_estimator() + # theta_a = 5.0 is outside the model bounds (0, 4), so that solve + # fails while the neighboring grid points still succeed. + with LoggingIntercept(level=logging.WARNING) as LOG: + prof, _, _, _ = pest.profile_likelihood( + "theta_a", + grid=[1.9, 5.0, 2.1], + theta_hat={"theta_a": 2.0, "theta_b": 1.0}, + obj_hat=0.0, + ) + self.assertIn("outside the bounds", LOG.getvalue()) + + prof = prof.loc["theta_a"] + self.assertEqual(len(prof), 4) + self.assertIn("exception", str(prof.loc[5.0, "status"])) + self.assertFalse(bool(prof.loc[5.0, "success"])) + self.assertTrue(np.isnan(prof.loc[5.0, "obj"])) + self.assertTrue(prof.drop(index=5.0)["success"].all()) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_nonoptimal_point_records_termination(self): + pest = _build_two_theta_estimator(solver_options={"max_iter": 1}) + # Solves that stop at the iteration limit are recorded with their + # termination condition, not as exceptions. + prof, intervals, _, _ = pest.profile_likelihood( + "theta_a", + grid=[1.9, 2.1], + theta_hat={"theta_a": 2.0, "theta_b": 1.0}, + obj_hat=0.0, + ) + self.assertEqual(len(prof), 3) + self.assertTrue( + (prof["status"] == str(pyo.TerminationCondition.maxIterations)).all() + ) + self.assertFalse(prof["success"].any()) + self.assertTrue(prof["obj"].isna().all()) + # With every solve failed, no point is in the region and no interval + # is bounded + self.assertFalse(prof[0.95].any()) + self.assertTrue(intervals[["lower", "upper"]].isna().all().all()) + self.assertFalse(intervals["lower_bounded"].any()) + self.assertFalse(intervals["upper_bounded"].any()) + + def test_profile_auto_grid_from_bounds(self): + pest = _build_two_theta_estimator() + # theta_a bounds are (0, 4) + grid = pest._build_profile_grid( + profiled_theta="theta_a", + grid=None, + n_grid=5, + model=pest._create_parmest_model(0), + ) + self.assertEqual(grid.tolist(), [0.0, 1.0, 2.0, 3.0, 4.0]) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_baseline_from_multistart(self): + pest = _build_two_theta_estimator(_InitRecordingEstimator) + prof, _, _, obj_hat = pest.profile_likelihood( + profiled_theta="theta_a", + n_grid=5, + use_multistart_for_baseline=True, + baseline_multistart_kwargs={ + "n_starts": 3, + "multistart_sampling_method": "uniform_random", + "seed": 7, + }, + ) + self.assertEqual(pest.n_multistart_calls, 1) + self.assertTrue(np.isfinite(obj_hat)) + self.assertGreaterEqual(prof.shape[0], 1) + + @parameterized.expand([("SSE", None), ("SSE_weighted", 0.5)]) + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_lr_stat_is_likelihood_ratio(self, obj_function, sigma): + from pyomo.contrib.parmest.examples.rooney_biegler.rooney_biegler import ( + RooneyBieglerExperiment, + ) + + 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"], + ) + pest = parmest.Estimator( + [ + RooneyBieglerExperiment(data.loc[i, :], measure_error=sigma) + for i in range(data.shape[0]) + ], + obj_function=obj_function, + ) + prof, _, theta_hat, _ = pest.profile_likelihood( + "asymptote", grid=[16.0, 18.0, 22.0] + ) + self.assertTrue(prof["success"].all()) + + # Independent calculation from the model y = a * (1 - exp(-b * t)) + t, y = data["hour"].to_numpy(float), data["y"].to_numpy(float) + + def ssr(a, b): + return np.sum((y - a * (1 - np.exp(-b * t))) ** 2) + + ssr_hat = ssr(theta_hat["asymptote"], theta_hat["rate_constant"]) + ssr_prof = np.array( + [ssr(a, b) for a, b in zip(prof["asymptote"], prof["rate_constant"])] + ) + if obj_function == "SSE": + # unknown variance profiled out: N * log(SSR / SSR_hat) + expected = len(y) * np.log(ssr_prof / ssr_hat) + else: + # known variance: (SSR - SSR_hat) / sigma^2 + expected = (ssr_prof - ssr_hat) / sigma**2 + np.testing.assert_allclose(prof["lr_stat"], expected, rtol=1e-6, atol=1e-8) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_lr_stat_undefined_for_custom_objective(self): + pest = _build_two_theta_estimator(obj_function=parmest.SSE) + with LoggingIntercept(level=logging.WARNING) as LOG: + prof, _, _, _ = pest.profile_likelihood( + "theta_a", + grid=[1.9, 2.1], + theta_hat={"theta_a": 2.0, "theta_b": 1.0}, + obj_hat=0.0, + ) + self.assertIn( + "profile_likelihood: lr_stat is only defined for the 'SSE' and " + "'SSE_weighted' objectives without regularization, so it is set to " + "NaN.", + LOG.getvalue(), + ) + self.assertTrue(prof["success"].all()) + self.assertTrue(prof["lr_stat"].isna().all()) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_lr_stat_perfect_fit(self): + # The data lie exactly on the model, so SSE_hat = 0 and the likelihood + # ratio is not defined for the SSE objective. + pest = _build_two_theta_estimator() + with LoggingIntercept(level=logging.WARNING) as LOG: + prof, _, _, _ = pest.profile_likelihood( + "theta_a", + grid=[1.9, 2.1], + theta_hat={"theta_a": 2.0, "theta_b": 1.0}, + obj_hat=0.0, + ) + self.assertIn( + "profile_likelihood: the baseline objective is zero (a perfect " + "fit), so lr_stat is not defined for the 'SSE' objective and is " + "set to NaN.", + LOG.getvalue(), + ) + self.assertTrue(prof["success"].all()) + self.assertTrue(prof["lr_stat"].isna().all()) + + def test_split_grid_at_center(self): + pest = _build_two_theta_estimator() + branches = pest._split_grid_at_center([1.0, 1.5, 2.0, 2.5, 3.0], center=2.0) + self.assertEqual(branches, [[2.0, 2.5, 3.0], [1.5, 1.0]]) + # Grid values are rounded, so center may differ slightly from the grid + # value; the closest grid value still starts the upper side. + branches = pest._split_grid_at_center([1.0, 2.0, 3.0], center=2.0 + 1e-15) + self.assertEqual(branches, [[2.0, 3.0], [1.0]]) + # A side with no values is left out. + branches = pest._split_grid_at_center([2.0, 2.5], center=2.0) + self.assertEqual(branches, [[2.0, 2.5]]) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_failures_stop_only_one_side(self): + pest = _build_two_theta_estimator() + # theta_hat is near the upper bound of theta_a (4.0): the solve at + # 4.2 fails, which stops the upper side, while every value below + # theta_hat is still solved. + with LoggingIntercept(level=logging.WARNING): + prof, _, _, _ = pest.profile_likelihood( + "theta_a", + grid=[3.0, 3.4, 3.8, 4.2, 4.4], + theta_hat={"theta_a": 3.9, "theta_b": 5.0 - 2.0 * 3.9}, + obj_hat=0.0, + max_consecutive_failures=1, + ) + prof = prof.loc["theta_a"] + self.assertEqual(sorted(prof.index), [3.0, 3.4, 3.8, 3.9, 4.2]) + self.assertFalse(bool(prof.loc[4.2, "success"])) + self.assertTrue(prof.loc[[3.0, 3.4, 3.8, 3.9], "success"].all()) + for a in (3.0, 3.4, 3.8): + self.assertAlmostEqual(prof.loc[a, "theta_b"], 5.0 - 2.0 * a, 6) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_given_baseline_does_not_use_multistart(self): + pest = _build_two_theta_estimator(_InitRecordingEstimator) + pest.profile_likelihood( + "theta_a", + grid=[1.9, 2.1], + theta_hat={"theta_a": 2.0, "theta_b": 1.0}, + obj_hat=0.0, + use_multistart_for_baseline=True, + ) + self.assertEqual(pest.n_multistart_calls, 0) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_restores_estimator_state(self): + pest = _build_two_theta_estimator() + obj_hat, theta_hat = pest.theta_est() + state = (pest.ef_instance, dict(pest.estimated_theta), pest.obj_value) + # The last grid value solved (theta_a = 3.5) is far from theta_hat. + pest.profile_likelihood( + "theta_a", grid=[1.0, 3.5], theta_hat=dict(theta_hat), obj_hat=obj_hat + ) + self.assertIs(pest.ef_instance, state[0]) + self.assertEqual(pest.estimated_theta, state[1]) + # cov_est reads only these, so it is unchanged by profiling. + self.assertEqual(pest.obj_value, state[2]) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_lower_objective_updates_baseline(self): + pest = _build_rooney_biegler_estimator() + obj_hat, theta_hat = pest.theta_est() + theta_hat = dict(theta_hat) + # The given obj_hat is too high, so the solve at theta_hat finds a + # lower objective. + with LoggingIntercept(level=logging.WARNING) as LOG: + prof, _, new_theta_hat, new_obj_hat = pest.profile_likelihood( + "asymptote", + grid=[16.0, 22.0], + theta_hat=theta_hat, + obj_hat=obj_hat + 1.0, + ) + self.assertIn( + f"profile_likelihood: a profile solve found a lower objective " + f"({new_obj_hat}) than the baseline ({obj_hat + 1.0}) " + f"at theta = {new_theta_hat}, so it becomes the " + f"baseline and lr_stat is computed from it. The Estimator estimate " + f"is not updated; re-run theta_est from this theta to update it.", + LOG.getvalue(), + ) + + self.assertAlmostEqual(new_obj_hat, obj_hat, places=6) + for name, val in theta_hat.items(): + self.assertAlmostEqual(new_theta_hat[name], val, places=4) + # lr_stat is measured from the lowest objective, so it is not negative + self.assertAlmostEqual(prof["lr_stat"].min(), 0.0, places=8) + # The Estimator keeps its estimate + self.assertEqual(pest.obj_value, obj_hat) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_max_rebaseline_solves_again(self): + pest = _build_rooney_biegler_estimator(_InitRecordingEstimator) + obj_hat, theta_hat = pest.theta_est() + # theta_hat["rate_constant"] is off, so the first side starts away + # from the baseline solution, and obj_hat is too high. + bad_theta_hat = dict(theta_hat) + bad_theta_hat["rate_constant"] = 1.0 + with LoggingIntercept(level=logging.WARNING) as LOG: + prof, _, _, new_obj_hat = pest.profile_likelihood( + "asymptote", + grid=[16.0, 22.0], + theta_hat=bad_theta_hat, + obj_hat=obj_hat + 1.0, + max_rebaseline=1, + ) + self.assertIn( + "so it becomes the baseline and the profiles are solved " "again from it.", + LOG.getvalue(), + ) + self.assertNotIn("lr_stat is computed from it", LOG.getvalue()) + self.assertAlmostEqual(new_obj_hat, obj_hat, places=6) + + # Each of the 2 sweeps solves the 3 grid values; the second starts + # from the new baseline. + inits = pest.profile_theta_inits + self.assertEqual(len(inits), 6) + self.assertEqual(inits[0]["rate_constant"], 1.0) + self.assertAlmostEqual( + inits[3]["rate_constant"], theta_hat["rate_constant"], places=4 + ) + # Only the rows of the second sweep are returned + self.assertEqual(len(prof), 3) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_profile_no_lower_objective_keeps_baseline(self): + pest = _build_rooney_biegler_estimator() + obj_hat, theta_hat = pest.theta_est() + with LoggingIntercept(level=logging.WARNING) as LOG: + _, _, new_theta_hat, new_obj_hat = pest.profile_likelihood( + "asymptote", + grid=[16.0, 22.0], + theta_hat=dict(theta_hat), + obj_hat=obj_hat, + max_rebaseline=1, + ) + self.assertNotIn("found a lower objective", LOG.getvalue()) + self.assertEqual(new_obj_hat, obj_hat) + self.assertEqual(new_theta_hat, dict(theta_hat)) + + def test_profile_intervals_interpolated(self): + pest = _build_two_theta_estimator() + profiles = pd.DataFrame( + { + "profiled_theta": ["theta_a"] * 6, + "theta_value": [0.0, 0.5, 1.0, 2.0, 3.0, 4.0], + "lr_stat": [5.0, np.nan, 2.0, 0.0, 1.0, 2.0], + "success": [True, False, True, True, True, True], + } + ).set_index(["profiled_theta", "theta_value"]) + intervals = pest._profile_intervals( + profiles, ["theta_a"], {"theta_a": 2.0, "theta_b": 1.0}, {0.9: 3.0} + ) + row = intervals.loc[("theta_a", 0.9)] + self.assertEqual(row["theta_hat"], 2.0) + self.assertEqual(row["threshold"], 3.0) + # The failed solve at 0.5 is skipped: lr_stat crosses 3.0 between 0.0 + # (5.0) and 1.0 (2.0) + self.assertAlmostEqual(row["lower"], 1.0 - 1.0 / 3.0) + self.assertTrue(row["lower_bounded"]) + # lr_stat stays below 3.0 above theta_hat + self.assertTrue(np.isnan(row["upper"])) + self.assertFalse(row["upper_bounded"]) + + def test_profile_theta_name_matches_column_raises(self): + class ObjThetaEstimator(parmest.Estimator): + def _expanded_theta_info(self, model): + return ["theta_a", "obj"], None + + pest = _build_two_theta_estimator(ObjThetaEstimator) + with self.assertRaisesRegex( + ValueError, + r"Theta name\(s\) \['obj'\] match profiles column names; use " + r"return_theta_paths=False\.", + ): + pest.profile_likelihood("theta_a") + + def test_profile_invalid_arguments_raises(self): + pest = _build_two_theta_estimator() + with self.assertRaisesRegex( + TypeError, r"profiled_theta must be a string or a list/tuple of strings\." + ): + pest.profile_likelihood(1) + with self.assertRaisesRegex( + ValueError, r"At least one profiled theta must be provided\." + ): + pest.profile_likelihood([]) + with self.assertRaisesRegex( + TypeError, r"Each profiled theta name must be a string\." + ): + pest.profile_likelihood(["theta_a", 1]) + with self.assertRaisesRegex( + ValueError, + r"Duplicate profiled theta names are not allowed: " + r"\['theta_a', 'theta_a'\]", + ): + pest.profile_likelihood(["theta_a", "theta_a"]) + with self.assertRaisesRegex(TypeError, r"n_grid must be an integer\."): + pest.profile_likelihood("theta_a", n_grid=2.0) + with self.assertRaisesRegex(ValueError, r"n_grid must be at least 2\."): + pest.profile_likelihood("theta_a", n_grid=1) + with self.assertRaisesRegex( + ValueError, r"warmstart must be either 'neighbor' or 'none'\." + ): + pest.profile_likelihood("theta_a", warmstart="previous") + with self.assertRaisesRegex( + TypeError, r"max_consecutive_failures must be an integer or None\." + ): + pest.profile_likelihood("theta_a", max_consecutive_failures=1.0) + with self.assertRaisesRegex( + ValueError, r"max_consecutive_failures must be greater than zero\." + ): + pest.profile_likelihood("theta_a", max_consecutive_failures=0) + with self.assertRaisesRegex(TypeError, r"return_theta_paths must be a bool\."): + pest.profile_likelihood("theta_a", return_theta_paths="yes") + with self.assertRaisesRegex( + TypeError, r"alphas must be a non-empty list of floats\." + ): + pest.profile_likelihood("theta_a", alphas=0.95) + with self.assertRaisesRegex( + ValueError, r"Each alpha must be between 0 and 1\." + ): + pest.profile_likelihood("theta_a", alphas=[95]) + with self.assertRaisesRegex( + ValueError, r"Duplicate alphas are not allowed: \[0\.95, 0\.95\]" + ): + pest.profile_likelihood("theta_a", alphas=[0.95, 0.95]) + with self.assertRaisesRegex(TypeError, r"max_rebaseline must be an integer\."): + pest.profile_likelihood("theta_a", max_rebaseline=1.0) + with self.assertRaisesRegex( + ValueError, r"max_rebaseline must be non-negative\." + ): + pest.profile_likelihood("theta_a", max_rebaseline=-1) + with self.assertRaisesRegex( + ValueError, + r"Unknown profile theta name\(s\): \['theta_c'\]\. Known names: " + r"\('theta_a', 'theta_b'\)\.", + ): + pest.profile_likelihood("theta_c") + + with self.assertRaisesRegex( + ValueError, + r"grid key\(s\) \['theta_c'\] are not profiled thetas: " r"\['theta_a'\]\.", + ): + pest.profile_likelihood("theta_a", grid={"theta_c": [1.0]}) + + # theta_est fails with one iteration, so the grid checks run before + # the baseline is computed + pest = _build_two_theta_estimator(solver_options={"max_iter": 1}) + with self.assertRaisesRegex( + TypeError, r"grid must be a sequence of numeric values or None\." + ): + pest.profile_likelihood("theta_a", grid="2.0") + with self.assertRaisesRegex( + ValueError, r"Provided grid must contain at least one value\." + ): + pest.profile_likelihood("theta_a", grid=[]) + with self.assertRaisesRegex( + ValueError, + r"Provided theta values \['theta_b'\] do not match expected theta " + r"names \['theta_a', 'theta_b'\]\.", + ): + pest.profile_likelihood( + "theta_a", grid=[1.9], theta_hat={"theta_b": 1.0}, obj_hat=0.0 + ) + + @unittest.skipIf(not ipopt_available, "The 'ipopt' solver is not available") + def test_fixed_theta_values_fix_at_given_values(self): + pest = _build_two_theta_estimator() + # No theta_vals: theta_a must be fixed at 3.0 from fixed_theta_values, + # and the profiled optimum is theta_b = 5 - 2 * 3.0 = -1. + obj, theta, term = pest._Q_opt(fixed_theta_values={"theta_a": 3.0}) + self.assertEqual(str(term), str(pyo.TerminationCondition.optimal)) + self.assertEqual(theta["theta_a"], 3.0) + self.assertAlmostEqual(theta["theta_b"], -1.0, places=6) + # fixed_theta_values takes precedence over theta_vals. + model = pest._create_scenario_blocks( + theta_vals={"theta_a": 1.5, "theta_b": 0.0}, + fixed_theta_values={"theta_a": 3.0}, + ) + self.assertTrue(model.parmest_theta["theta_a"].fixed) + self.assertEqual(pyo.value(model.parmest_theta["theta_a"]), 3.0) + self.assertFalse(model.parmest_theta["theta_b"].fixed) + for block in model.exp_scenarios.values(): + self.assertEqual(pyo.value(block.theta_a), 3.0) + self.assertTrue(block.theta_a.fixed) + + ########################### # tests for deprecated UI # ###########################