Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
121 commits
Select commit Hold shift + click to select a range
cdd7d52
Work on multistart implement 4/23 morning
sscini Apr 23, 2025
eca0ba8
Finished first draft of pseudocode for multistart
sscini Apr 23, 2025
2160aec
Fixed logical errors in pseudocode
sscini Apr 23, 2025
266beea
Started implementing review comments 4/30
sscini Apr 30, 2025
b877ada
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Apr 30, 2025
9f1ffe5
Work on edits, 5/1/25
sscini May 1, 2025
43f1ab3
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini May 1, 2025
ea067c8
Made edits, still debugging
sscini May 2, 2025
3b839ef
Addressed some comments in code. Still working through example to debug
sscini May 14, 2025
3a7aa1d
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini May 14, 2025
c688f2d
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini May 21, 2025
50c36bc
Got dataframe formatted, still working on executing Q_opt
sscini May 21, 2025
8e5f078
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Jun 2, 2025
f4c7018
Working code, adding features 6/2/25
sscini Jun 2, 2025
4444e6d
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Jun 3, 2025
e788000
Added questions for next round of reviews
sscini Jun 3, 2025
4429caf
Merge branch 'multistart-in-parmest' of https://github.com/sscini/pyo…
sscini Jun 3, 2025
f071718
Removed diagnostic tables to simplify output
sscini Jun 3, 2025
9b1545d
Work from Wednesday of Sprint week
sscini Jun 4, 2025
80079cb
Create Simple_Multimodal_Multistart.ipynb
sscini Jun 4, 2025
1695519
New features Thursday morning
sscini Jun 5, 2025
0634014
First successful running multistart feature, before Alex recommended …
sscini Jun 5, 2025
a959346
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Jun 5, 2025
04a9096
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Jun 23, 2025
06e0a72
Ran black, removed temp example
sscini Jun 24, 2025
6b3ee40
Added utility to update model using suffix values
sscini Jun 27, 2025
5cadfac
Work on Friday 6/27 applying PR comments
sscini Jun 27, 2025
922fd57
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Jun 30, 2025
1be2d9e
Addressed some reviewer comments and ran black.
sscini Jun 30, 2025
56800f5
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Jul 1, 2025
05381c5
Updated argument for theta_est_multistart
sscini Jul 6, 2025
5b4f9c1
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Jul 7, 2025
07ae1e8
Addressed majority of review comments. State before 7/8 dev meeting
sscini Jul 8, 2025
33d838f
Fixing conflict
sscini Jul 8, 2025
65a9cff
Merge branch 'main' into multistart-in-parmest
sscini Jul 15, 2025
90093df
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Jul 17, 2025
e7b2df1
Added in TODO items based on Dan morning meeting
sscini Jul 17, 2025
c55143d
Added in files from main now, removed example
sscini Feb 19, 2026
8f3a902
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Feb 19, 2026
3c87d7a
Added old files in temporarily for reference
sscini Feb 19, 2026
4e09d33
Ran black
sscini Feb 19, 2026
4f94329
Merge branch 'Q_opt-redesign' into multistart-in-parmest
sscini Feb 19, 2026
12d0af1
Made quick working example, and small modification for multistart
sscini Feb 19, 2026
0a1167d
Merge branch 'main' into multistart-in-parmest
sscini Feb 24, 2026
9ccfba4
Added theta generation and old multistart over
sscini Mar 3, 2026
78f65f3
Updated multistart example and code
sscini Mar 3, 2026
43a67ab
Added bounds to models, ran black
sscini Mar 3, 2026
2b41ba5
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Mar 6, 2026
2e5ac42
Merge branch 'Q_opt-redesign' into multistart-in-parmest
sscini Mar 6, 2026
813a981
Adjusted implementation, added new tests in separate file
sscini Mar 6, 2026
96a4792
Initial implementation
sscini Mar 6, 2026
44a0b83
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Mar 6, 2026
8b9db82
Merge branch 'Pyomo:main' into profile-likelihood
sscini Mar 6, 2026
f9c8e3a
Fixed issue with repeat thetas, ran black
sscini Mar 9, 2026
d6cfe37
Merge branch 'multistart-in-parmest' into profile-likelihood
sscini Mar 9, 2026
a025512
Applied changes based on changes to multistart
sscini Mar 9, 2026
6444c54
Merge branch 'Pyomo:main' into profile-likelihood
sscini Mar 17, 2026
12a3c1b
Merge branch 'main' into multistart-in-parmest
sscini Mar 24, 2026
07c42e7
Merge branch 'main' into profile-likelihood
sscini Mar 24, 2026
664d687
Merge branch 'Q_opt-redesign' into multistart-in-parmest
sscini Mar 27, 2026
ea876b1
Merge branch 'multistart-in-parmest' into profile-likelihood
sscini Mar 27, 2026
5530e9d
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Apr 7, 2026
3f2a971
Merge branch 'Pyomo:main' into profile-likelihood
sscini Apr 7, 2026
ee17469
Added features for ACC workshop
sscini May 5, 2026
aa30f0c
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini May 14, 2026
6975a27
Merge branch 'Pyomo:main' into profile-likelihood
sscini May 14, 2026
1a1a7c0
Merge branch 'Q_opt-redesign' into multistart-in-parmest
sscini May 14, 2026
b4518fc
Merge branch 'main' into multistart-in-parmest
sscini May 15, 2026
800143f
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini May 21, 2026
edf6883
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Jun 2, 2026
a17ef9d
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Aug 23, 2026
b0f4b00
Dusting off cob-webs, fixing issues with changes from _Q_opt merging …
sscini Aug 23, 2026
566570e
Removed mock tests, moved all testing over to main test file
sscini Aug 23, 2026
192ba38
Cleaned up commented out code and comments
sscini Aug 23, 2026
a8967c8
Merge branch 'multistart-in-parmest' into profile-likelihood
sscini Aug 23, 2026
32fa236
Merge branch 'main' into multistart-in-parmest
stephenscini Sep 1, 2026
b95148e
Merge branch 'Pyomo:main' into profile-likelihood
sscini Sep 17, 2026
4589624
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Sep 17, 2026
c82ec00
Merge branch 'multistart-in-parmest' into profile-likelihood
sscini Sep 17, 2026
a1f885b
Found missing components from merge that caused test failures
sscini Sep 25, 2026
4f48ebb
All tests passing for profile
sscini Sep 25, 2026
119ff08
Moved tests into main file
sscini Sep 25, 2026
303205a
Remove unused seed argument from profile likelihood
sscini Sep 25, 2026
51ca54a
Fixed unused arguments and corresponding tests.
sscini Sep 29, 2026
d2f1e69
Change yhat to y_hat to avoid typo issue
sscini Sep 29, 2026
b2acde2
Merge branch 'multistart-in-parmest' into profile-likelihood
sscini Sep 29, 2026
6bfb2a7
Address comments, remove parallel implement
sscini Oct 8, 2026
b9c9bee
Remove scenarios.csv
sscini Oct 8, 2026
b28d6d6
Added more helper functions, simplified doc strings and comments, adj…
sscini Oct 16, 2026
c26127e
Rename extra results_df to multistart_result
sscini Oct 16, 2026
c8ac339
Simplify structure to remove duplicate checks and make more readable.…
sscini Oct 16, 2026
439d5b0
Manually checked code readability and expanded hard to read portions
sscini Oct 16, 2026
98cd331
Checked for consistency in naming conventions
sscini Oct 16, 2026
a256021
Fold tests into existing classes, other than strictly unique for mult…
sscini Oct 16, 2026
c00f358
Check coverage and address, add function to documentation
sscini Oct 16, 2026
5b8af9b
Merge branch 'main' into multistart-in-parmest
sscini Oct 16, 2026
f76cb9d
Merge branch 'Pyomo:main' into profile-likelihood
sscini Oct 16, 2026
51ad170
Merge branch 'multistart-in-parmest' into profile-likelihood
sscini Oct 16, 2026
8dc226d
Checked readability, removed duplicate items or checks
sscini Oct 16, 2026
8afb8be
Add warning and rebase option if better optimum found
sscini Oct 16, 2026
110f02e
Restructure and simplify results storage, propagate.
sscini Oct 16, 2026
5fc31a5
Remove success row, adjust test and examples
sscini Oct 16, 2026
2241da6
Remove solver argument, redundant
sscini Oct 16, 2026
26db59b
Add new function names to docs
sscini Oct 16, 2026
d868637
Plot fixes and readability improvements
sscini Oct 16, 2026
f2e9d28
Merge branch 'main' into multistart-in-parmest
mrmundt Oct 16, 2026
4863ee5
Merge branch 'main' into profile-likelihood
sscini Oct 19, 2026
9ba26f1
Merge branch 'main' into multistart-in-parmest
blnicho Nov 2, 2026
927aea0
Merge remote-tracking branch 'upstream/main' into multistart-in-parmest
sscini Nov 6, 2026
6fa03c2
parmest: initialize model states at each multistart start
sscini Nov 6, 2026
aa913e3
Merge branch 'multistart-in-parmest' into profile-likelihood
sscini Nov 6, 2026
7ec5980
parmest: initialize states at each profile likelihood grid value
sscini Nov 6, 2026
7403f08
Merge branch 'Pyomo:main' into multistart-in-parmest
sscini Nov 17, 2026
1bf6328
Addressed Shuvo comments
sscini Nov 17, 2026
f310f65
Merge branch 'main' into multistart-in-parmest
sscini Nov 17, 2026
21164ec
Delete scenarios.csv
sscini Nov 17, 2026
30489d5
Update test_parmest.py
sscini Nov 18, 2026
52a5eb6
Add small section to documentation
sscini Nov 19, 2026
7fad71b
Merge remote-tracking branch 'origin/multistart-in-parmest' into prof…
sscini Nov 19, 2026
cd88987
Make small naming changes consistent with multistart.
sscini Nov 19, 2026
71c9d9b
Merge branch 'Pyomo:main' into profile-likelihood
sscini Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/OnlineDocs/explanation/analysis/parmest/driver.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
50 changes: 44 additions & 6 deletions doc/OnlineDocs/explanation/analysis/parmest/estimability.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
-------------------
Expand Down Expand Up @@ -39,17 +39,55 @@ 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.
Consistent convergence to a unique solution across initializations suggests that the parameters are structurally
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.
``results`` is a Pandas DataFrame with one row per start: the starting and converged (``converged_<name>``)
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.
7 changes: 7 additions & 0 deletions doc/OnlineDocs/explanation/analysis/parmest/graphics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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()
10 changes: 7 additions & 3 deletions pyomo/contrib/parmest/examples/reactor_design/reactor_design.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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()
Original file line number Diff line number Diff line change
@@ -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()
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
85 changes: 85 additions & 0 deletions pyomo/contrib/parmest/graphics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading