Non-linear least-squares minimization and curve-fitting with enhanced parameter management and confidence interval estimation
npx @tessl/cli install tessl/pypi-lmfit@1.3.00
# LMFIT
1
2
Non-linear least-squares minimization and curve-fitting library for Python, providing enhanced parameter management with bounds and constraints, flexible optimization algorithms, and improved confidence interval estimation. Built on top of SciPy and NumPy, it enables sophisticated curve fitting with Parameter objects that can be fixed, bounded, or constrained by algebraic expressions.
3
4
## Package Information
5
6
- **Package Name**: lmfit
7
- **Language**: Python
8
- **Installation**: `pip install lmfit`
9
10
## Core Imports
11
12
```python
13
import lmfit
14
```
15
16
Common components:
17
18
```python
19
from lmfit import minimize, Parameters, Parameter, Model
20
from lmfit import fit_report, conf_interval
21
from lmfit import lineshapes, models
22
```
23
24
For direct access to built-in models:
25
26
```python
27
from lmfit.models import GaussianModel, LinearModel, ExponentialModel
28
```
29
30
## Basic Usage
31
32
```python
33
import numpy as np
34
from lmfit import minimize, Parameters, fit_report
35
36
# Define a simple model function
37
def residual(params, x, data):
38
"""Calculate residual of model vs data"""
39
a = params['a']
40
b = params['b']
41
c = params['c']
42
model = a * np.exp(-b * x) + c
43
return model - data
44
45
# Create sample data
46
x = np.linspace(0, 15, 301)
47
data = 5.0 * np.exp(-0.5 * x) + np.random.normal(size=301, scale=0.2) + 2.0
48
49
# Create parameters with initial guesses and constraints
50
params = Parameters()
51
params.add('a', value=10, min=0) # amplitude, must be positive
52
params.add('b', value=1, min=0) # decay rate, must be positive
53
params.add('c', value=2) # offset, unconstrained
54
55
# Perform the fit
56
result = minimize(residual, params, args=(x, data))
57
58
# Display results
59
print(fit_report(result))
60
```
61
62
## Architecture
63
64
LMFIT's architecture centers around enhanced parameter objects and flexible model building:
65
66
- **Parameter Objects**: Replace plain floats with rich objects supporting bounds, constraints, and algebraic expressions
67
- **Parameters Container**: Dictionary-like collection with constraint evaluation using asteval
68
- **Minimizer**: Core optimization engine supporting 15+ algorithms from scipy.optimize plus MCMC
69
- **Model Framework**: High-level interface for curve fitting with automatic parameter guessing
70
- **Built-in Models**: 33 ready-to-use models for common lineshapes and functions
71
72
This design enables complex fitting scenarios while maintaining compatibility with scipy.optimize methods and providing enhanced parameter management for real-world applications.
73
74
## Capabilities
75
76
### Core Parameter Management
77
78
Parameter objects that can be varied, fixed, bounded, or constrained by mathematical expressions, providing the foundation for all fitting operations in LMFIT.
79
80
```python { .api }
81
class Parameter:
82
def __init__(self, name=None, value=None, vary=True, min=-inf, max=inf, expr=None, brute_step=None, user_data=None): ...
83
def set(self, value=None, vary=None, min=None, max=None, expr=None, brute_step=None): ...
84
85
class Parameters(dict):
86
def __init__(self, usersyms=None): ...
87
def add(self, name, value=None, vary=None, min=-inf, max=inf, expr=None, brute_step=None): ...
88
def add_many(self, *parlist): ...
89
def valuesdict(self): ...
90
91
def create_params(**kws): ...
92
```
93
94
[Parameters and Constraints](./parameters.md)
95
96
### Minimization and Optimization
97
98
Comprehensive minimization capabilities with support for 15+ optimization methods, including least-squares, global optimization, and Markov Chain Monte Carlo sampling.
99
100
```python { .api }
101
class Minimizer:
102
def __init__(self, userfcn, params, fcn_args=None, fcn_kws=None, **kws): ...
103
def minimize(self, method='leastsq', params=None, **kws): ...
104
def emcee(self, params=None, steps=1000, nwalkers=100, **kws): ...
105
106
def minimize(fcn, params, method='leastsq', **kws): ...
107
108
class MinimizerResult:
109
# Attributes: success, message, method, nfev, chisqr, redchi, aic, bic
110
# params, var_names, covar, best_values, init_values
111
def show_candidates(self, n_candidates=5): ...
112
```
113
114
[Minimization and Optimization](./minimization.md)
115
116
### High-Level Model Interface
117
118
Model class that transforms user functions into fitting models with automatic parameter creation, guessing capabilities, and comprehensive result analysis.
119
120
```python { .api }
121
class Model:
122
def __init__(self, func, independent_vars=None, param_names=None, **kws): ...
123
def fit(self, data, params=None, weights=None, method='leastsq', **kws): ...
124
def guess(self, data, **kws): ...
125
def make_params(self, **kws): ...
126
def eval(self, params=None, **kws): ...
127
128
class CompositeModel(Model):
129
def __init__(self, left, right, op, **kws): ...
130
131
class ModelResult(MinimizerResult):
132
def eval_components(self, **kws): ...
133
def plot(self, **kws): ...
134
```
135
136
[Model Interface](./models.md)
137
138
### Built-in Models and Lineshapes
139
140
Comprehensive collection of 33 built-in model classes and 73 mathematical lineshape functions for common peak shapes, distributions, and mathematical functions.
141
142
```python { .api }
143
# Example built-in models
144
class GaussianModel(Model): ...
145
class LorentzianModel(Model): ...
146
class VoigtModel(Model): ...
147
class ExponentialModel(Model): ...
148
class LinearModel(Model): ...
149
150
# Example lineshape functions
151
def gaussian(x, amplitude=1.0, center=0.0, sigma=1.0): ...
152
def lorentzian(x, amplitude=1.0, center=0.0, sigma=1.0): ...
153
def voigt(x, amplitude=1.0, center=0.0, sigma=1.0, gamma=None): ...
154
```
155
156
[Built-in Models](./builtin-models.md)
157
158
### Confidence Intervals and Error Analysis
159
160
Statistical analysis tools for parameter confidence intervals, correlation analysis, and uncertainty propagation in fitted parameters.
161
162
```python { .api }
163
def conf_interval(minimizer, result, p_names=None, sigmas=(0.674, 0.95, 0.997), **kws): ...
164
def conf_interval2d(minimizer, result, x_name, y_name, nx=10, ny=10, **kws): ...
165
```
166
167
[Confidence Intervals](./confidence.md)
168
169
### Results Reporting
170
171
Comprehensive reporting functions for fit results, parameter values, uncertainties, correlations, and confidence intervals in both text and HTML formats.
172
173
```python { .api }
174
def fit_report(inpars, modelpars=None, show_correl=True, min_correl=0.1): ...
175
def ci_report(ci, with_offset=True, ndigits=5): ...
176
def report_fit(params, **kws): ... # alias for fit_report
177
def report_ci(ci): ... # alias for ci_report
178
```
179
180
[Results and Reporting](./reporting.md)
181
182
## Exception Classes
183
184
```python { .api }
185
class MinimizerException(Exception):
186
"""General purpose minimizer exception"""
187
def __init__(self, msg): ...
188
189
class AbortFitException(MinimizerException):
190
"""Raised when a fit is aborted by the user"""
191
```