0
# iminuit
1
2
A 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.
3
4
## Package Information
5
6
- **Package Name**: iminuit
7
- **Language**: Python
8
- **Installation**: `pip install iminuit`
9
- **Documentation**: https://scikit-hep.org/iminuit
10
- **Dependencies**: numpy (required), matplotlib, ipywidgets, scipy, numba (optional)
11
12
## Core Imports
13
14
```python
15
from iminuit import Minuit, minimize, describe
16
```
17
18
Cost functions (must be imported separately):
19
20
```python
21
from iminuit.cost import LeastSquares, BinnedNLL, UnbinnedNLL, ExtendedBinnedNLL, ExtendedUnbinnedNLL
22
from iminuit.cost import Template, CostSum, NormalConstraint
23
```
24
25
Utilities (must be imported separately):
26
27
```python
28
from iminuit.util import Matrix, FMin, Params
29
```
30
31
## Basic Usage
32
33
```python
34
from iminuit import Minuit
35
36
# Define a cost function to minimize
37
def cost_function(x, y, z):
38
return (x - 2) ** 2 + (y - 3) ** 2 + (z - 4) ** 2
39
40
# Create minimizer with initial parameter values
41
m = Minuit(cost_function, x=0, y=0, z=0)
42
43
# Run minimization algorithm
44
m.migrad()
45
46
# Compute parameter uncertainties
47
m.hesse()
48
49
# Access results
50
print(f"Parameters: {m.values}") # {'x': 2.0, 'y': 3.0, 'z': 4.0}
51
print(f"Errors: {m.errors}") # {'x': 1.0, 'y': 1.0, 'z': 1.0}
52
print(f"Function value: {m.fval}") # ~0.0
53
```
54
55
Advanced fitting with cost functions:
56
57
```python
58
from iminuit import Minuit
59
from iminuit.cost import LeastSquares
60
import numpy as np
61
62
# Sample data
63
x = np.linspace(0, 10, 50)
64
y_true = 2 * x + 1
65
y_measured = y_true + np.random.normal(0, 0.5, len(x))
66
y_errors = np.full(len(x), 0.5)
67
68
# Define model
69
def linear_model(x, slope, intercept):
70
return slope * x + intercept
71
72
# Create cost function
73
cost = LeastSquares(x, y_measured, y_errors, linear_model)
74
75
# Minimize
76
m = Minuit(cost, slope=1, intercept=0)
77
m.migrad()
78
m.hesse()
79
80
print(f"Best fit: slope={m.values['slope']:.3f}, intercept={m.values['intercept']:.3f}")
81
```
82
83
## Architecture
84
85
iminuit provides a Python interface to the MINUIT2 C++ minimization library with the following key components:
86
87
- **Minuit Class**: Primary interface for function minimization with 50+ methods and properties
88
- **Cost Functions**: Built-in statistical models (LeastSquares, BinnedNLL, UnbinnedNLL, etc.)
89
- **Algorithms**: MIGRAD (primary), Simplex, SCAN, and SciPy integration
90
- **Error Analysis**: Asymptotic (HESSE) and profile-based (MINOS) uncertainty estimation
91
- **Visualization**: Matplotlib integration for plotting profiles, contours, and fit results
92
93
The library integrates seamlessly with the scientific Python ecosystem, supporting NumPy arrays, SciPy optimizers, Numba acceleration, and Jupyter notebook visualization.
94
95
## Capabilities
96
97
### Core Minimization
98
99
The primary Minuit class for function minimization, parameter estimation, and uncertainty analysis. Provides access to MINUIT2 algorithms with Python-friendly interface.
100
101
```python { .api }
102
class Minuit:
103
LEAST_SQUARES: float = 1.0
104
LIKELIHOOD: float = 0.5
105
106
def __init__(self, fcn, *args, grad=None, name=None, **kwds): ...
107
def migrad(self, ncall=None, iterate=5, use_simplex=True): ...
108
def hesse(self, ncall=None): ...
109
def minos(self, *parameters, cl=None, ncall=None): ...
110
```
111
112
[Core Minimization](./core-minimization.md)
113
114
### Cost Functions
115
116
Statistical cost functions for maximum likelihood and least-squares fitting. Includes support for binned/unbinned data, weighted samples, and template fitting.
117
118
```python { .api }
119
class LeastSquares:
120
def __init__(self, x, y, yerror, model, loss="linear"): ...
121
122
class BinnedNLL:
123
def __init__(self, n, xe, model, use_pdf=True): ...
124
125
class UnbinnedNLL:
126
def __init__(self, data, model, use_pdf=True): ...
127
```
128
129
[Cost Functions](./cost-functions.md)
130
131
### SciPy Interface
132
133
SciPy-compatible minimization interface for easy integration with existing scipy.optimize workflows.
134
135
```python { .api }
136
def minimize(fun, x0, args=(), method="migrad", jac=None, hess=None,
137
bounds=None, constraints=None, tol=None, options=None):
138
"""
139
Interface to MIGRAD using scipy.optimize.minimize API.
140
141
Args:
142
fun: Cost function to minimize
143
x0: Initial parameter values
144
method: "migrad" or "simplex"
145
options: Dictionary with disp, stra, maxfun, eps options
146
147
Returns:
148
OptimizeResult: Result object with x, fun, success attributes
149
"""
150
```
151
152
[SciPy Interface](./scipy-interface.md)
153
154
### Visualization and Profiles
155
156
Plotting functions for visualizing parameter profiles, confidence contours, and model-data agreement using matplotlib.
157
158
```python { .api }
159
def profile(self, vname, size=100, bound=2, grid=None, subtract_min=False): ...
160
def contour(self, x, y, size=50, bound=2, grid=None, subtract_min=False): ...
161
def draw_profile(self, vname, band=True, text=True, **kwargs): ...
162
def draw_contour(self, x, y, **kwargs): ...
163
```
164
165
[Visualization](./visualization.md)
166
167
### Utilities and Data Access
168
169
Utility classes and functions for accessing fit results, parameter information, and performing common operations.
170
171
```python { .api }
172
class FMin:
173
fval: float
174
edm: float
175
is_valid: bool
176
has_accurate_covar: bool
177
178
class Matrix:
179
def __init__(self, data): ...
180
def correlation(self): ...
181
182
def describe(func, annotations=None):
183
"""Describe function signature and parameter information."""
184
```
185
186
[Utilities](./utilities.md)
187
188
### Testing and Benchmarks
189
190
Common test functions for optimization algorithm benchmarking and validation.
191
192
```python { .api }
193
def rosenbrock(x, y): ...
194
def ackley(x, y): ...
195
def beale(x, y): ...
196
def sphere_np(x): ...
197
```
198
199
[Testing Functions](./testing.md)
200
201
## Types
202
203
```python { .api }
204
from typing import Protocol, Union, Optional, List, Tuple, Dict, Callable
205
from numpy.typing import NDArray, ArrayLike
206
207
Key = Union[int, str, slice, List[Union[int, str]]]
208
209
class UserBound:
210
min: Optional[float]
211
max: Optional[float]
212
213
# Type annotations for constraints
214
class Gt:
215
gt: float
216
217
class Lt:
218
lt: float
219
220
class Interval:
221
min: float
222
max: float
223
```