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.0Non-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.
pip install lmfitimport lmfitCommon components:
from lmfit import minimize, Parameters, Parameter, Model
from lmfit import fit_report, conf_interval
from lmfit import lineshapes, modelsFor direct access to built-in models:
from lmfit.models import GaussianModel, LinearModel, ExponentialModelimport numpy as np
from lmfit import minimize, Parameters, fit_report
# Define a simple model function
def residual(params, x, data):
"""Calculate residual of model vs data"""
a = params['a']
b = params['b']
c = params['c']
model = a * np.exp(-b * x) + c
return model - data
# Create sample data
x = np.linspace(0, 15, 301)
data = 5.0 * np.exp(-0.5 * x) + np.random.normal(size=301, scale=0.2) + 2.0
# Create parameters with initial guesses and constraints
params = Parameters()
params.add('a', value=10, min=0) # amplitude, must be positive
params.add('b', value=1, min=0) # decay rate, must be positive
params.add('c', value=2) # offset, unconstrained
# Perform the fit
result = minimize(residual, params, args=(x, data))
# Display results
print(fit_report(result))LMFIT's architecture centers around enhanced parameter objects and flexible model building:
This design enables complex fitting scenarios while maintaining compatibility with scipy.optimize methods and providing enhanced parameter management for real-world applications.
Parameter objects that can be varied, fixed, bounded, or constrained by mathematical expressions, providing the foundation for all fitting operations in LMFIT.
class Parameter:
def __init__(self, name=None, value=None, vary=True, min=-inf, max=inf, expr=None, brute_step=None, user_data=None): ...
def set(self, value=None, vary=None, min=None, max=None, expr=None, brute_step=None): ...
class Parameters(dict):
def __init__(self, usersyms=None): ...
def add(self, name, value=None, vary=None, min=-inf, max=inf, expr=None, brute_step=None): ...
def add_many(self, *parlist): ...
def valuesdict(self): ...
def create_params(**kws): ...Comprehensive minimization capabilities with support for 15+ optimization methods, including least-squares, global optimization, and Markov Chain Monte Carlo sampling.
class Minimizer:
def __init__(self, userfcn, params, fcn_args=None, fcn_kws=None, **kws): ...
def minimize(self, method='leastsq', params=None, **kws): ...
def emcee(self, params=None, steps=1000, nwalkers=100, **kws): ...
def minimize(fcn, params, method='leastsq', **kws): ...
class MinimizerResult:
# Attributes: success, message, method, nfev, chisqr, redchi, aic, bic
# params, var_names, covar, best_values, init_values
def show_candidates(self, n_candidates=5): ...Model class that transforms user functions into fitting models with automatic parameter creation, guessing capabilities, and comprehensive result analysis.
class Model:
def __init__(self, func, independent_vars=None, param_names=None, **kws): ...
def fit(self, data, params=None, weights=None, method='leastsq', **kws): ...
def guess(self, data, **kws): ...
def make_params(self, **kws): ...
def eval(self, params=None, **kws): ...
class CompositeModel(Model):
def __init__(self, left, right, op, **kws): ...
class ModelResult(MinimizerResult):
def eval_components(self, **kws): ...
def plot(self, **kws): ...Comprehensive collection of 33 built-in model classes and 73 mathematical lineshape functions for common peak shapes, distributions, and mathematical functions.
# Example built-in models
class GaussianModel(Model): ...
class LorentzianModel(Model): ...
class VoigtModel(Model): ...
class ExponentialModel(Model): ...
class LinearModel(Model): ...
# Example lineshape functions
def gaussian(x, amplitude=1.0, center=0.0, sigma=1.0): ...
def lorentzian(x, amplitude=1.0, center=0.0, sigma=1.0): ...
def voigt(x, amplitude=1.0, center=0.0, sigma=1.0, gamma=None): ...Statistical analysis tools for parameter confidence intervals, correlation analysis, and uncertainty propagation in fitted parameters.
def conf_interval(minimizer, result, p_names=None, sigmas=(0.674, 0.95, 0.997), **kws): ...
def conf_interval2d(minimizer, result, x_name, y_name, nx=10, ny=10, **kws): ...Comprehensive reporting functions for fit results, parameter values, uncertainties, correlations, and confidence intervals in both text and HTML formats.
def fit_report(inpars, modelpars=None, show_correl=True, min_correl=0.1): ...
def ci_report(ci, with_offset=True, ndigits=5): ...
def report_fit(params, **kws): ... # alias for fit_report
def report_ci(ci): ... # alias for ci_reportclass MinimizerException(Exception):
"""General purpose minimizer exception"""
def __init__(self, msg): ...
class AbortFitException(MinimizerException):
"""Raised when a fit is aborted by the user"""