Jupyter-friendly Python frontend for MINUIT2 C++ library for function minimization and error analysis
—
matplotlib-based visualization functions for parameter profiles, confidence contours, and model-data agreement. These functions help visualize fit results, parameter uncertainties, and correlations.
1D profiles showing how the cost function varies with individual parameters.
def profile(self, vname, size=100, bound=2, grid=None, subtract_min=False):
"""
Calculate 1D cost function profile over a range.
Args:
vname: Parameter name or index to profile
size: Number of points in profile (int, default: 100)
bound: Range specification (float or UserBound):
- float: symmetric range in units of parameter error
- UserBound: explicit (min, max) range
grid: Custom grid points (array-like, optional)
subtract_min: If True, subtract minimum value from profile
Returns:
Tuple[np.ndarray, np.ndarray]: (parameter_values, cost_values)
"""
def draw_profile(self, vname, band=True, text=True, **kwargs):
"""
Draw 1D cost function profile over a range (requires matplotlib).
Args:
vname: Parameter name or index to profile
band: Whether to show confidence band (bool, default: True)
text: Whether to show parameter information text (bool, default: True)
**kwargs: Additional arguments passed to matplotlib plotting functions
Returns:
Tuple[np.ndarray, np.ndarray]: (parameter_values, cost_values)
"""1D Minos profiles showing asymmetric confidence intervals.
def mnprofile(self, vname, size=30, bound=2, grid=None, subtract_min=False,
ncall=0, iterate=5, use_simplex=True):
"""
Get Minos profile over a specified interval.
Args:
vname: Parameter name or index to profile
size: Number of points in profile (int, default: 30)
bound: Range specification (float or UserBound)
grid: Custom grid points (array-like, optional)
subtract_min: If True, subtract minimum value from profile
ncall: Maximum function calls per point (int, default: 0 = no limit)
iterate: Number of iterations if convergence fails
use_simplex: Whether to use Simplex if MIGRAD fails
Returns:
Tuple[np.ndarray, np.ndarray, np.ndarray]:
(parameter_values, cost_values, valid_points)
"""
def draw_mnprofile(self, vname, band=True, text=True, **kwargs):
"""
Draw Minos profile over a specified interval (requires matplotlib).
Args:
vname: Parameter name or index to profile
band: Whether to show confidence band (bool, default: True)
text: Whether to show parameter information text (bool, default: True)
**kwargs: Additional arguments passed to matplotlib plotting functions
Returns:
Tuple[np.ndarray, np.ndarray]: (parameter_values, cost_values)
"""2D contours showing parameter correlations and confidence regions.
def contour(self, x, y, size=50, bound=2, grid=None, subtract_min=False):
"""
Get a 2D contour of the function around the minimum.
Args:
x: First parameter name or index
y: Second parameter name or index
size: Number of points per dimension (int, default: 50)
bound: Range specification (float or sequence of 2 tuples)
grid: Custom grid (tuple of 2 arrays, optional)
subtract_min: If True, subtract minimum value from contour
Returns:
Tuple[np.ndarray, np.ndarray, np.ndarray]:
(x_values, y_values, cost_values_2d)
"""
def draw_contour(self, x, y, **kwargs):
"""
Draw 2D contour around minimum (requires matplotlib).
Args:
x: First parameter name or index
y: Second parameter name or index
**kwargs: Additional arguments passed to matplotlib contour functions
Returns:
Tuple[np.ndarray, np.ndarray, np.ndarray]:
(x_values, y_values, cost_values_2d)
"""2D Minos confidence regions with proper statistical interpretation.
def mncontour(self, x, y, cl=None, size=100, interpolated=0, experimental=False,
ncall=0, iterate=5, use_simplex=True):
"""
Get 2D Minos confidence region.
Args:
x: First parameter name or index
y: Second parameter name or index
cl: Confidence level (float, optional, uses errordef if None)
size: Number of points on contour (int, default: 100)
interpolated: Interpolation level (int, default: 0)
experimental: Use experimental algorithm (bool, default: False)
ncall: Maximum function calls (int, default: 0 = no limit)
iterate: Number of iterations if convergence fails
use_simplex: Whether to use Simplex if MIGRAD fails
Returns:
np.ndarray: Array of (x, y) points on confidence contour
"""
def draw_mncontour(self, x, y, cl=None, size=100, interpolated=0, experimental=False):
"""
Draw 2D Minos confidence region (requires matplotlib).
Args:
x: First parameter name or index
y: Second parameter name or index
cl: Confidence level(s) (float or array-like, optional)
size: Number of points on contour (int, default: 100)
interpolated: Interpolation level (int, default: 0)
experimental: Use experimental algorithm (bool, default: False)
Returns:
Matplotlib artist objects
"""Visualization of parameter correlation and error matrices.
def draw_mnmatrix(self, cl=None, size=100, experimental=False, figsize=None):
"""
Draw matrix of Minos scans (requires matplotlib).
Args:
cl: Confidence level(s) (float or array-like, optional)
size: Number of points per profile (int, default: 100)
experimental: Use experimental algorithm (bool, default: False)
figsize: Figure size tuple (optional)
Returns:
Matplotlib figure object
"""Visualization of model-data agreement for cost functions that support it.
def visualize(self, plot=None, **kwargs):
"""
Visualize agreement of current model with data (requires matplotlib).
Args:
plot: Custom plotting function (callable, optional)
Signature: plot(x, y, y_model, **kwargs)
**kwargs: Additional arguments passed to plotting functions
Note:
Only works with cost functions that provide visualization support
(LeastSquares, BinnedNLL, etc.)
"""Interactive GUI widgets for parameter adjustment and live fitting.
def interactive(self, plot=None, raise_on_exception=False, **kwargs):
"""
Interactive GUI for fitting (requires ipywidgets in Jupyter).
Args:
plot: Custom plotting function (callable, optional)
raise_on_exception: Whether to raise exceptions or show warnings
**kwargs: Additional arguments passed to plotting functions
Note:
Creates interactive sliders for parameter adjustment with live updates
of fit results and visualizations.
"""from iminuit import Minuit
import matplotlib.pyplot as plt
# After fitting
m.migrad()
m.hesse()
# Draw parameter profile
x, y = m.draw_profile('slope')
plt.show()
# Or get profile data without plotting
x_vals, cost_vals = m.profile('slope', size=200)
plt.plot(x_vals, cost_vals)
plt.xlabel('slope')
plt.ylabel('Cost function')
plt.show()from iminuit.typing import UserBound
# Minos profile over custom range
x, y = m.draw_mnprofile('slope', bound=UserBound(-1, 5))
plt.title('Minos Profile for Slope Parameter')
plt.show()# Draw contour between two parameters
x, y, z = m.draw_contour('slope', 'intercept')
plt.colorbar(label='Cost function')
plt.show()
# Multiple confidence levels
m.draw_mncontour('slope', 'intercept', cl=[0.68, 0.95])
plt.legend(['68% CL', '95% CL'])
plt.show()# Customize plot appearance
m.draw_profile('slope',
band=True, # Show confidence band
text=False, # Hide parameter text
color='red', # Line color
linewidth=2, # Line width
alpha=0.7) # Transparency
plt.title('Custom Profile Plot')
plt.show()from iminuit.cost import LeastSquares
# For cost functions that support visualization
cost = LeastSquares(x_data, y_data, y_errors, model_func)
m = Minuit(cost, param1=1, param2=2)
m.migrad()
# Visualize model vs data
m.visualize()
plt.show()
# Custom visualization function
def my_plot(x, y, y_model):
plt.errorbar(x, y, yerr=y_errors, fmt='o', label='Data')
plt.plot(x, y_model, '-', label='Model')
plt.legend()
m.visualize(plot=my_plot)
plt.show()# Draw matrix showing all parameter profiles
fig = m.draw_mnmatrix(cl=[0.68, 0.95], size=50)
fig.suptitle('Parameter Correlation Matrix')
plt.show()# Interactive parameter adjustment in Jupyter notebook
m.interactive()
# With custom plot function
def custom_plot(x, y, y_model):
plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.errorbar(x, y, yerr=y_errors, fmt='o')
plt.plot(x, y_model, '-')
plt.ylabel('Data')
plt.subplot(2, 1, 2)
plt.plot(x, y - y_model, 'o')
plt.ylabel('Residuals')
plt.xlabel('x')
m.interactive(plot=custom_plot)# Save profile plot
x, y = m.draw_profile('slope')
plt.savefig('parameter_profile.png', dpi=300)
plt.close()
# Save contour plot
m.draw_contour('slope', 'intercept')
plt.savefig('parameter_contour.pdf')
plt.close()fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# Profile for first parameter
plt.sca(axes[0])
m.draw_profile('slope', text=False)
plt.title('Slope Profile')
# Profile for second parameter
plt.sca(axes[1])
m.draw_profile('intercept', text=False)
plt.title('Intercept Profile')
plt.tight_layout()
plt.show()# Custom contour levels and styling
x, y, z = m.contour('slope', 'intercept', size=100)
# Create custom contour plot
plt.figure(figsize=(8, 6))
levels = [0.5, 2.0, 4.5, 8.0] # Custom confidence levels
cs = plt.contour(x, y, z, levels=levels, colors=['blue', 'green', 'orange', 'red'])
plt.clabel(cs, inline=True, fontsize=10)
plt.scatter(m.values['slope'], m.values['intercept'],
marker='*', s=100, color='black', label='Best fit')
plt.xlabel('Slope')
plt.ylabel('Intercept')
plt.legend()
plt.show()All visualization functions require matplotlib to be installed:
pip install matplotlibInteractive fitting additionally requires ipywidgets:
pip install ipywidgetsInstall with Tessl CLI
npx tessl i tessl/pypi-iminuit