Jupyter-friendly Python frontend for MINUIT2 C++ library for function minimization and error analysis
npx @tessl/cli install tessl/pypi-iminuit@2.31.0A Jupyter-friendly Python frontend for the MINUIT2 C++ library maintained by CERN's ROOT team. Designed for statistical parameter estimation and function minimization, iminuit provides best-fit parameters and error estimates through likelihood profile analysis, with built-in cost functions for statistical fits and comprehensive error analysis capabilities.
pip install iminuitfrom iminuit import Minuit, minimize, describeCost functions (must be imported separately):
from iminuit.cost import LeastSquares, BinnedNLL, UnbinnedNLL, ExtendedBinnedNLL, ExtendedUnbinnedNLL
from iminuit.cost import Template, CostSum, NormalConstraintUtilities (must be imported separately):
from iminuit.util import Matrix, FMin, Paramsfrom iminuit import Minuit
# Define a cost function to minimize
def cost_function(x, y, z):
return (x - 2) ** 2 + (y - 3) ** 2 + (z - 4) ** 2
# Create minimizer with initial parameter values
m = Minuit(cost_function, x=0, y=0, z=0)
# Run minimization algorithm
m.migrad()
# Compute parameter uncertainties
m.hesse()
# Access results
print(f"Parameters: {m.values}") # {'x': 2.0, 'y': 3.0, 'z': 4.0}
print(f"Errors: {m.errors}") # {'x': 1.0, 'y': 1.0, 'z': 1.0}
print(f"Function value: {m.fval}") # ~0.0Advanced fitting with cost functions:
from iminuit import Minuit
from iminuit.cost import LeastSquares
import numpy as np
# Sample data
x = np.linspace(0, 10, 50)
y_true = 2 * x + 1
y_measured = y_true + np.random.normal(0, 0.5, len(x))
y_errors = np.full(len(x), 0.5)
# Define model
def linear_model(x, slope, intercept):
return slope * x + intercept
# Create cost function
cost = LeastSquares(x, y_measured, y_errors, linear_model)
# Minimize
m = Minuit(cost, slope=1, intercept=0)
m.migrad()
m.hesse()
print(f"Best fit: slope={m.values['slope']:.3f}, intercept={m.values['intercept']:.3f}")iminuit provides a Python interface to the MINUIT2 C++ minimization library with the following key components:
The library integrates seamlessly with the scientific Python ecosystem, supporting NumPy arrays, SciPy optimizers, Numba acceleration, and Jupyter notebook visualization.
The primary Minuit class for function minimization, parameter estimation, and uncertainty analysis. Provides access to MINUIT2 algorithms with Python-friendly interface.
class Minuit:
LEAST_SQUARES: float = 1.0
LIKELIHOOD: float = 0.5
def __init__(self, fcn, *args, grad=None, name=None, **kwds): ...
def migrad(self, ncall=None, iterate=5, use_simplex=True): ...
def hesse(self, ncall=None): ...
def minos(self, *parameters, cl=None, ncall=None): ...Statistical cost functions for maximum likelihood and least-squares fitting. Includes support for binned/unbinned data, weighted samples, and template fitting.
class LeastSquares:
def __init__(self, x, y, yerror, model, loss="linear"): ...
class BinnedNLL:
def __init__(self, n, xe, model, use_pdf=True): ...
class UnbinnedNLL:
def __init__(self, data, model, use_pdf=True): ...SciPy-compatible minimization interface for easy integration with existing scipy.optimize workflows.
def minimize(fun, x0, args=(), method="migrad", jac=None, hess=None,
bounds=None, constraints=None, tol=None, options=None):
"""
Interface to MIGRAD using scipy.optimize.minimize API.
Args:
fun: Cost function to minimize
x0: Initial parameter values
method: "migrad" or "simplex"
options: Dictionary with disp, stra, maxfun, eps options
Returns:
OptimizeResult: Result object with x, fun, success attributes
"""Plotting functions for visualizing parameter profiles, confidence contours, and model-data agreement using matplotlib.
def profile(self, vname, size=100, bound=2, grid=None, subtract_min=False): ...
def contour(self, x, y, size=50, bound=2, grid=None, subtract_min=False): ...
def draw_profile(self, vname, band=True, text=True, **kwargs): ...
def draw_contour(self, x, y, **kwargs): ...Utility classes and functions for accessing fit results, parameter information, and performing common operations.
class FMin:
fval: float
edm: float
is_valid: bool
has_accurate_covar: bool
class Matrix:
def __init__(self, data): ...
def correlation(self): ...
def describe(func, annotations=None):
"""Describe function signature and parameter information."""Common test functions for optimization algorithm benchmarking and validation.
def rosenbrock(x, y): ...
def ackley(x, y): ...
def beale(x, y): ...
def sphere_np(x): ...from typing import Protocol, Union, Optional, List, Tuple, Dict, Callable
from numpy.typing import NDArray, ArrayLike
Key = Union[int, str, slice, List[Union[int, str]]]
class UserBound:
min: Optional[float]
max: Optional[float]
# Type annotations for constraints
class Gt:
gt: float
class Lt:
lt: float
class Interval:
min: float
max: float