### Load and Run Example Script Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst This snippet loads and executes an example script from the 'examples' folder. The ':hide-output:' directive prevents the output from being displayed directly. ```python ../examples/doc_model_gaussian.py ``` -------------------------------- ### Load Model Example Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Shows how to load a previously saved model. This is useful for resuming analysis or using a model in a different session. Ensure the 'dill' package is installed if the model was saved using it. ```python from lmfit import load_model # Load the model saved previously loaded_model = load_model('my_model.save') ``` -------------------------------- ### Load and plot data for SplineModel example Source: https://github.com/lmfit/lmfit-py/blob/master/doc/builtin_models.rst Loads data from a file and plots it, serving as the initial visualization for the SplineModel example. ```python import numpy as np import matplotlib.pyplot as plt from lmfit.models import SplineModel, GaussianModel data = np.loadtxt('test_splinepeak.dat') x = data[:, 0] y = data[:, 1] plt.plot(x, y, label='data') plt.legend() plt.show() ``` -------------------------------- ### Create example problem for confidence interval calculation Source: https://github.com/lmfit/lmfit-py/blob/master/doc/confidence.rst Sets up a simple model with parameters and data for demonstrating confidence interval calculations. Requires numpy and lmfit. ```python import numpy as np import lmfit x = np.linspace(0.3, 10, 100) np.random.seed(0) y = 1/(0.1*x) + 2 + 0.1*np.random.randn(x.size) pars = lmfit.Parameters() pars.add_many(('a', 0.1), ('b', 1)) def residual(p): return 1/(p['a']*x) + p['b'] - y ``` -------------------------------- ### Install lmfit with pip Source: https://github.com/lmfit/lmfit-py/blob/master/doc/installation.rst The recommended way to install lmfit for general use. This command automatically installs all required dependencies. ```bash pip install lmfit ``` -------------------------------- ### Install lmfit development version Source: https://github.com/lmfit/lmfit-py/blob/master/doc/installation.rst Steps to clone the lmfit repository and install the latest development version, including build dependencies and all optional packages. ```bash git clone https://github.com/lmfit/lmfit-py.git ``` ```bash pip install --upgrade build pip setuptools wheel ``` ```bash python -m build ``` ```bash pip install " .[all]" ``` -------------------------------- ### Install lmfit with conda Source: https://github.com/lmfit/lmfit-py/blob/master/doc/installation.rst Alternative installation method for users of Anaconda Python, using the conda-forge channel. ```bash conda install -c conda-forge lmfit ``` -------------------------------- ### Save Model Example Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Demonstrates how to save a fitted model using the save_model function. Ensure the model is saved with sufficient information for later reloading. ```python from lmfit import save_model # Assuming 'model' is a fitted ModelResult object save_model(model, 'my_model.save') ``` -------------------------------- ### Utilize Built-in Models for Ready-to-Use Lineshapes Source: https://context7.com/lmfit/lmfit-py/llms.txt LMfit provides over 20 pre-built model classes in `lmfit.models`, offering automatic parameter discovery and `guess()` methods for initial parameter estimation. Examples include Gaussian, Voigt, Polynomial, and Step models, with options for custom knot positions in SplineModel. ```python import numpy as np from lmfit.models import ( GaussianModel, LorentzianModel, VoigtModel, PseudoVoigtModel, LinearModel, QuadraticModel, PolynomialModel, ConstantModel, ExponentialModel, PowerLawModel, StepModel, RectangleModel, SineModel, GaussianModel, Gaussian2dModel, SplitLorentzianModel, MoffatModel, Pearson4Model, Pearson7Model, SkewedGaussianModel, SkewedVoigtModel, ExponentialGaussianModel, DoniachModel, ThermalDistributionModel, SplineModel, ) x = np.linspace(-5, 15, 500) y = (80/(np.sqrt(2*np.pi)*1.2)) * np.exp(-(x-5)**2/(2*1.44)) \ + np.random.normal(0, 0.5, x.size) # Gaussian: params amplitude, center, sigma (+ fwhm, height as constraints) gmod = GaussianModel() pars = gmod.guess(y, x=x) # auto-estimate starting values from data result_g = gmod.fit(y, pars, x=x) # Voigt: params amplitude, center, sigma, gamma vmod = VoigtModel() pars_v = vmod.guess(y, x=x) pars_v['gamma'].vary = True # allow gamma to differ from sigma result_v = vmod.fit(y, pars_v, x=x) # Polynomial of degree 3: params c0, c1, c2, c3 poly = PolynomialModel(degree=3) pars_p = poly.guess(y, x=x) # Step function (form = 'linear', 'erf', 'logistic', 'heaviside', 'arctan', 'rectangle') step = StepModel(form='erf') pars_s = step.make_params(amplitude=1, center=5, sigma=1) result_s = step.fit(y, pars_s, x=x) # Spline with custom knot positions from lmfit.models import SplineModel xknots = np.linspace(x.min(), x.max(), 12) spline = SplineModel(xknots=xknots) pars_sp = spline.guess(y, x=x) result_sp = spline.fit(y, pars_sp, x=x) print(result_g.fit_report(correl_mode='table')) ``` -------------------------------- ### Fit Data to GaussianModel Source: https://github.com/lmfit/lmfit-py/blob/master/doc/builtin_models.rst Fit peak data to a Gaussian profile using the built-in GaussianModel. This example shows how to load data, initialize the model, guess parameters, and perform the fit. ```python from numpy import loadtxt from lmfit.models import GaussianModel data = loadtxt('test_peak.dat') x = data[:, 0] y = data[:, 1] mod = GaussianModel() pars = mod.guess(y, x=x) out = mod.fit(y, pars, x=x) print(out.fit_report(min_correl=0.25)) ``` -------------------------------- ### Fit Data to VoigtModel Source: https://github.com/lmfit/lmfit-py/blob/master/doc/builtin_models.rst Fit peak data to a Voigt profile using the VoigtModel. This example shows how to use the VoigtModel and compare its fit statistics to other models. ```python from lmfit.models import VoigtModel mod = VoigtModel() pars = mod.guess(y, x=x) out = mod.fit(y, pars, x=x) print(out.fit_report(min_correl=0.25)) ``` -------------------------------- ### Define Objective Function with Parameters Source: https://github.com/lmfit/lmfit-py/blob/master/doc/parameters.rst This example shows how to define an objective function that accepts a Parameters object and unpacks parameter values using valuesdict(). This approach simplifies accessing parameter values within the function. ```python def fcn2min(params, x, data): """Model a decaying sine wave and subtract data.""" v = params.valuesdict() model = v['amp'] * np.sin(x*v['omega'] + v['shift']) * np.exp(-x*x*v['decay']) return model - data ``` -------------------------------- ### Plot Data for Spline Fit Example Source: https://github.com/lmfit/lmfit-py/blob/master/doc/builtin_models.rst Plot the data points used in the example where the number of spline points is increased to fit the full spectra. ```python plt.plot(x, y, 'o', label='data') ``` -------------------------------- ### Composite Model Example Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Demonstrates the use of a composite model with a custom operator for data fitting. This script utilizes numpy convolution for processing. ```python import numpy as np def convolve_with_kernel(tmp, kernel, npts): out = np.convolve(tmp, kernel, mode='valid') noff = int((len(out) - npts) / 2) return (out[noff:])[:npts] ``` -------------------------------- ### Perform Least-Squares Fit with SciPy Source: https://github.com/lmfit/lmfit-py/blob/master/doc/intro.rst Generates synthetic data with noise and experimental uncertainties, then performs a non-linear least-squares fit using SciPy's leastsq function. This example demonstrates how to set up the data and initial variable guesses for the fitting process. ```python from numpy import linspace, random from scipy.optimize import leastsq # generate synthetic data with noise x = linspace(0, 100) noise = random.normal(size=x.size, scale=0.2) data = 7.5 * sin(x*0.22 + 2.5) * exp(-x*x*0.01) + noise # generate experimental uncertainties uncertainty = abs(0.16 + random.normal(size=x.size, scale=0.05)) variables = [10.0, 0.2, 3.0, 0.007] out = leastsq(residual, variables, args=(x, data, uncertainty)) ``` -------------------------------- ### Implement Piecewise Model with Breakpoint in lmfit Source: https://github.com/lmfit/lmfit-py/blob/master/doc/faq.rst This example demonstrates how to define and use a piecewise function with a breakpoint for fitting data using lmfit. The model function `quad_off` handles different behaviors based on the input `x` relative to the breakpoint `x0`. ```python import numpy as np import lmfit def quad_off(x, x0, a, b, c): model = a + b * x**2 model[np.where(x < x0)] = c return model x0 = 19 b = 0.02 a = 2.0 xdat = np.linspace(0, 100, 101) ydat = a + b * xdat**2 ydat[np.where(xdat < x0)] = a + b * x0**2 ``` -------------------------------- ### Create and Fit Model with Initial Values Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst This demonstrates creating a Model from a function and fitting data to it, providing initial values for parameters directly in the fit method. ```python gmodel = Model(gaussian) result = gmodel.fit(y, params, x=x, amp=5, cen=5, wid=1) ``` -------------------------------- ### Initialize Parameters with Model.make_params (With Attributes) Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Specify initial values along with attributes like bounds (min, max) and variation settings (vary) for parameters using dictionaries. ```python # supply initial values, attributes for bounds, etcetera: pars_bounded = mod.make_params(a=dict(value=3, min=0), b=dict(value=0.5, vary=False)) ``` -------------------------------- ### Load Data and Set Up Model Source: https://github.com/lmfit/lmfit-py/blob/master/examples/discuss_model_eval_uncertainty.ipynb Loads data from a file and defines a composite model consisting of two Gaussian models and one Exponential model. Initializes model parameters. ```python import numpy as np import matplotlib.pyplot as plt from lmfit import models # load and set up fit for the NIST Gauss2 data dat = np.loadtxt('NIST_Gauss2.dat') xg = dat[:, 1] yg = dat[:, 0] nmodel = (models.GaussianModel(prefix='g1_') + models.GaussianModel(prefix='g2_') + models.ExponentialModel(prefix='bkg_')) params = nmodel.make_params(bkg_amplitude=100, bkg_decay=80, g1_amplitude=3000, g1_center=100, g1_sigma=10, g2_amplitude=3000, g2_center=150, g2_sigma=10) ``` -------------------------------- ### Plot data for SplineModel example Source: https://github.com/lmfit/lmfit-py/blob/master/doc/builtin_models.rst A simple plot of the data, used to visually inspect the dataset before model fitting. ```python plt.plot(x, y, label='data') plt.legend() plt.show() ``` -------------------------------- ### Initialize Parameters with Model.make_params (Simple Values) Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst When creating parameters with Model.make_params, you can specify initial values using keyword arguments for parameter names. ```python mod = Model(myfunc) # simply supply initial values pars = mod.make_params(a=3, b=0.5) ``` -------------------------------- ### Define GaussianModel and make initial parameters Source: https://github.com/lmfit/lmfit-py/blob/master/doc/builtin_models.rst Initializes a GaussianModel with a specified prefix and creates default parameters for amplitude, center, and sigma. ```python model = GaussianModel(prefix='peak_') params = model.make_params(amplitude=8, center=16, sigma=1) ``` -------------------------------- ### Initialize Parameters for Fitting Source: https://github.com/lmfit/lmfit-py/blob/master/doc/fitting.rst Initializes a Parameters object for use in fitting, demonstrating how to add parameters with initial values. ```python from lmfit import Parameter, Parameters params = Parameters() params['period'] = Parameter(name='period', value=2, min=1.e-10) ``` -------------------------------- ### Define Custom Convolution Function Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Provides a basic implementation of a convolution function for use with CompositeModel. This example shows how to handle custom binary operations. ```python import numpy as np def convolve(dat, kernel): """simple convolution of two arrays""" npts = min(len(dat), len(kernel)) pad = np.ones(npts) tmp = np.concatenate((pad*dat[0], dat, pad*dat[-1])) ``` -------------------------------- ### Create Derived Parameters with Hints Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Use parameter hints to create new, derived parameters with constraint expressions, such as calculating FWHM from width. ```python mod = Model(gaussian) mod.set_param_hint('wid', min=0) mod.set_param_hint('fwhm', expr='2.3548*wid') params = mod.make_params(amp={'value': 10, 'min':0.1, 'max':2000}, cen=5.5, wid=1.25) params.pretty_print() ``` -------------------------------- ### Generate Data and Perform Initial Fit Source: https://github.com/lmfit/lmfit-py/blob/master/doc/confidence.rst Sets up synthetic data with added imperfections and noise, then fits a model (Gaussian + Linear) to this data. Prints the fit report. ```python # import matplotlib.pyplot as plt import numpy as np from lmfit import conf_interval, conf_interval2d, report_ci from lmfit.lineshapes import gaussian from lmfit.models import GaussianModel, LinearModel sigma_levels = [1, 2, 3] rng = np.random.default_rng(seed=102) ######################### # set up data -- deliberately adding imperfections and # a small amount of non-Gaussian noise npts = 501 x = np.linspace(1, 100, num=npts) noise = rng.normal(scale=0.3, size=npts) + 0.2*rng.f(3, 9, size=npts) y = (gaussian(x, amplitude=83, center=47., sigma=5.) + 0.02*x + 4 + 0.25*np.cos((x-20)/8.0) + noise) mod = GaussianModel() + LinearModel() params = mod.make_params(amplitude=100, center=50, sigma=5, slope=0, intecept=2) out = mod.fit(y, params, x=x) print(out.fit_report()) ######################### # run conf_intervale, print report sigma_levels = [1, 2, 3] ci = conf_interval(out, out, sigmas=sigma_levels) print("## Confidence Report:") report_ci(ci) ``` -------------------------------- ### Create and Fit Composite Model Source: https://github.com/lmfit/lmfit-py/blob/master/doc/builtin_models.rst Combine a peak model with a spline background and fit to data. Set sanity bounds on peak parameters to guide the fit. ```python model = model + bkg params["peak_amplitude"].min = 0 params["peak_center"].min = 10 params["peak_center"].max = 20 out = model.fit(y, params, x=x) print(out.fit_report(min_correl=0.3)) ``` -------------------------------- ### Create Model from Math String with ExpressionModel Source: https://context7.com/lmfit/lmfit-py/llms.txt Shows how to build a model directly from a mathematical expression string using ExpressionModel, which automatically detects parameters. Requires lmfit and numpy. ```python import numpy as np from lmfit.models import ExpressionModel # Parameters detected from expression: amplitude, center, sigma model = ExpressionModel( 'amplitude * exp(-(x - center)**2 / (2 * sigma**2))' ) print(model.param_names) # ['amplitude', 'center', 'sigma'] x = np.linspace(-5, 5, 200) y = 6.0 * np.exp(-(x - 1.2)**2 / (2 * 0.7**2)) + np.random.normal(0, 0.2, x.size) pars = model.make_params(amplitude=5, center=0, sigma=1) result = model.fit(y, pars, x=x) print(result.fit_report()) ``` -------------------------------- ### Fit Data to a Composite Model with Step and Constant Models Source: https://github.com/lmfit/lmfit-py/blob/master/doc/builtin_models.rst Demonstrates fitting data to a composite model formed by combining a StepModel and a ConstantModel. It shows how to create models, set initial parameters, and perform the fit. ```python from lmfit import StepModel, ConstantModel # Assume x and y are defined data arrays # Create models step = StepModel(form='erf') const = ConstantModel() # Create composite model composite_model = step + const # Set initial parameters (example using guess for step, make_params for const) params = composite_model.make_params() step_params = step.guess(y, x=x) params.update(step_params) # Fit the data out = composite_model.fit(y, params, x=x) # Print fit report print(out.fit_report()) ``` -------------------------------- ### Concatenate residuals for fitting multiple datasets Source: https://github.com/lmfit/lmfit-py/blob/master/doc/faq.rst To fit multiple datasets simultaneously, concatenate their individual residuals into a single one-dimensional array. This example shows fitting two lines to two datasets, sharing an 'offset' parameter. ```python import numpy as np def fit_function(params, x=None, dat1=None, dat2=None): model1 = params['offset'] + x * params['slope1'] model2 = params['offset'] + x * params['slope2'] resid1 = dat1 - model1 resid2 = dat2 - model2 return np.concatenate((resid1, resid2)) ``` -------------------------------- ### Parameter and Parameters Source: https://context7.com/lmfit/lmfit-py/llms.txt Demonstrates how to create, manipulate, and serialize Parameter and Parameters objects for defining fitting variables. ```APIDOC ## Parameters and Parameter ### Description `Parameter` is a scalar fitting variable that carries its value, bounds (`min`/`max`), a `vary` flag, an algebraic constraint expression (`expr`), and post-fit statistics (`stderr`, `correl`). `Parameters` is a dict-like container of `Parameter` objects that also evaluates constraint expressions via `asteval`. ### Usage ```python import numpy as np from lmfit import Parameters, Parameter # --- Build a Parameters object manually --- params = Parameters() params.add('amplitude', value=10.0, min=0) # bounded, free params.add('center', value=5.0, vary=False) # fixed params.add('sigma', value=1.0, min=0, max=5) # bounded, free params.add('fwhm', expr='2.3548 * sigma') # constrained expression # Access and modify print(params['amplitude'].value) # 10.0 params['sigma'].set(value=1.5, max=10) params['amplitude'].stderr # None before fitting; float after # Arithmetic on Parameter values works transparently val = params['sigma'] * 2.3548 # float, no .value needed # Add many at once: (name, value, vary, min, max, expr, brute_step) params.add_many( ('p0', 1.0, True, 0, None, None, None), ('p1', 0.5, True, None, 1.0, None, None), ('p2', None, True, None, None, 'p0 + p1', None), ) # Dictionary of current values print(params.valuesdict()) # {'amplitude': 10.0, 'center': 5.0, ...} # Serialize / deserialize json_str = params.dumps() params2 = Parameters().loads(json_str) with open('params.json', 'w') as f: params.dump(f) with open('params.json') as f: params3 = Parameters().load(f) ``` ``` -------------------------------- ### Create Parameters with create_params Source: https://github.com/lmfit/lmfit-py/blob/master/doc/intro.rst Initializes Parameters using keyword arguments for names and values. Requires lmfit version 1.2.0 or later. ```python from lmfit import create_params params = create_params(amp=10, decay=0.007, phase=0.2, frequency=3.0) ``` -------------------------------- ### Defining a Model with a Parameter Prefix Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Illustrates how to apply a prefix to all parameters of a model. This is useful when combining models to avoid name collisions, ensuring parameters are correctly mapped to the underlying function arguments. ```python def myfunc(x, amplitude=1, center=0, sigma=1): # function definition, for now just ``pass`` pass mod = Model(myfunc, prefix='f1_') params = mod.make_params() print('Parameters:') for pname, par in params.items(): print(pname, par) ``` -------------------------------- ### Set Initial Parameter Value for VoigtModel Source: https://github.com/lmfit/lmfit-py/blob/master/doc/builtin_models.rst Set an initial value for the 'gamma' parameter in a VoigtModel and enable it for fitting. This is useful when you have prior knowledge or a good estimate for a parameter. ```python mod = VoigtModel() pars = mod.guess(y, x=x) pars['gamma'].set(value=0.7, vary=True, expr='') ``` -------------------------------- ### Re-fitting with Different Methods Source: https://context7.com/lmfit/lmfit-py/llms.txt Demonstrates how to re-fit a model using a different optimization method or with updated data. This allows for comparison of fitting strategies. ```python # Re-fit with different method or data result2 = result.fit(data=y, method='least_squares') ``` -------------------------------- ### Plot initial and best fit with data Source: https://github.com/lmfit/lmfit-py/blob/master/doc/builtin_models.rst Visualizes the initial fit estimate and the final best fit against the original data. ```python plt.plot(x, y) plt.plot(x, out.init_fit, '--', label='initial fit') plt.plot(x, out.best_fit, '-', label='best fit') plt.legend() plt.show() ``` -------------------------------- ### Print Parameter Hints Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Access and print the parameter hints stored in a model's param_hints attribute to review configured hints. ```python print('Parameter hints:') for pname, par in mod.param_hints.items(): print(pname, par) ``` -------------------------------- ### Model.print_param_hints Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Prints the current parameter hints for the model. See model_param_hints_section for details. ```APIDOC ## Model.print_param_hints ### Description Prints all parameter hints currently set for the model. Refer to the `model_param_hints_section` for more information. ``` -------------------------------- ### Initialize Minimizer with Parameters Source: https://github.com/lmfit/lmfit-py/blob/master/doc/constraints.rst Initialize the Minimizer class with a parameter set that includes custom functions for constraints. ```python from lmfit import Minimizer def userfcn(x, params): pass fitter = Minimizer(userfcn, pars) ``` -------------------------------- ### Combine Models using Binary Operators Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Demonstrates how lmfit automatically constructs CompositeModels when standard binary operators (+, *, etc.) are used between Model objects. This allows for intuitive model building. ```python def fcn1(x, a): pass def fcn2(x, b): pass def fcn3(x, c): pass mod = Model(fcn1) + Model(fcn2) * Model(fcn3) ``` -------------------------------- ### Create Parameters Object with create_params() Source: https://context7.com/lmfit/lmfit-py/llms.txt Use the create_params() function for a more concise way to build a Parameters object from keyword arguments. Values can be plain numbers or dictionaries specifying parameter properties. ```python from lmfit import create_params params = create_params( amp=10.0, # plain float → value only cen={'value': 5.0, 'vary': False}, # fixed wid={'value': 1.0, 'min': 0}, # lower-bounded fwhm={'expr': '2.3548 * wid'}, # constrained bg={'value': 0.1, 'min': 0, 'max': 1.0}, # doubly-bounded ) print(params['fwhm'].value) # 2.3548 ``` -------------------------------- ### Fit data to a Gaussian using scipy.optimize.curve_fit Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Demonstrates the traditional approach to curve fitting using scipy.optimize.curve_fit. This serves as a baseline for comparison with lmfit. ```python from scipy.optimize import curve_fit x = linspace(-10, 10, 101) y = gaussian(x, 2.33, 0.21, 1.51) + random.normal(0, 0.2, x.size) init_vals = [1, 0, 1] # for [amp, cen, wid] best_vals, covar = curve_fit(gaussian, x, y, p0=init_vals) ``` -------------------------------- ### Pretty Print Fit Parameters - Python Source: https://github.com/lmfit/lmfit-py/blob/master/doc/fitting.rst Use this method to display fitted parameter values, bounds, and other attributes in a formatted table. Customization options for output formatting are available. ```python result.params.pretty_print() ``` -------------------------------- ### Fit Data with Multiple Peaks using Prefixes Source: https://github.com/lmfit/lmfit-py/blob/master/doc/builtin_models.rst Illustrates fitting a complex dataset with multiple Gaussian peaks using prefixes to distinguish parameters of similarly named models. This approach is crucial for composite models with overlapping parameter names. ```python from lmfit import Model from lmfit.models import GaussianModel, ExponentialModel # Assume x and y are defined data arrays # Create individual models with prefixes exp_model = ExponentialModel(prefix='exp_') g1 = GaussianModel(prefix='g1_') g2 = GaussianModel(prefix='g2_') # Create composite model composite_model = exp_model + g1 + g2 # Create parameters, setting initial guesses and bounds params = composite_model.make_params() # Example: setting parameters for Gaussian 1 params['g1_amplitude'].set(value=100, min=0) params['g1_center'].set(value=5, min=0) params['g1_sigma'].set(value=1, min=0) # Example: setting parameters for Gaussian 2 params['g2_amplitude'].set(value=80, min=0) params['g2_center'].set(value=7, min=0) params['g2_sigma'].set(value=1.5, min=0) # Example: setting parameters for Exponential params['exp_amplitude'].set(value=-50, min=-100) params['exp_decay'].set(value=0.5, min=0) # Fit the data out = composite_model.fit(y, params, x=x) # Print fit report print(out.fit_report()) ``` -------------------------------- ### Create Parameters with Dictionary Attributes Source: https://github.com/lmfit/lmfit-py/blob/master/doc/intro.rst Initializes Parameters using a dictionary where values can specify initial values, bounds, and variation settings. Requires lmfit version 1.2.0 or later. ```python params = create_params(amp={'value': 10, 'vary': False}, decay={'value': 0.007, 'min': 0}, phase=0.2, frequency={'value': 3.0, 'max':10}) ``` -------------------------------- ### Create and Define Parameters with lmfit Source: https://github.com/lmfit/lmfit-py/blob/master/README.rst Instantiate and populate an lmfit Parameters object. Parameters can be set with initial values, fixed status, bounds, or as expressions of other parameters. ```python import lmfit fit_params = lmfit.Parameters() fit_params['amp'] = lmfit.Parameter(value=1.2) fit_params['cen'] = lmfit.Parameter(value=40.0, vary=False) fit_params['wid'] = lmfit.Parameter(value=4, min=0) fit_params['fwhm'] = lmfit.Parameter(expr='wid*2.355') ``` ```python fit_params = lmfit.create_params(amp=1.2, cen={'value':40, 'vary':False}, wid={'value': 4, 'min':0}, fwhm={'expr': 'wid*2.355'}) ``` -------------------------------- ### Define initial parameter guesses for double exponential decay Source: https://github.com/lmfit/lmfit-py/blob/master/doc/fitting.rst Sets up initial guesses for the parameters of a double exponential decay model. Includes parameters for amplitude, decay time, and an offset. ```python p = lmfit.Parameters() p.add_many(('a1', 4.), ('a2', 4.), ('t1', 3.), ('t2', 3., True)) ``` -------------------------------- ### Print Fit Report and Confidence Intervals with lmfit Source: https://context7.com/lmfit/lmfit-py/llms.txt Demonstrates how to generate full fit reports, correlation tables in RST format, and confidence interval reports using lmfit's reporting functions. Requires lmfit and numpy. ```python import numpy as np from lmfit import create_params, minimize, fit_report, conf_interval from lmfit.printfuncs import report_ci, ci_report x = np.linspace(0, 10, 150) y = 4 * np.exp(-0.3 * x) + np.random.normal(0, 0.1, x.size) def residual(p): return p['amp'] * np.exp(-p['decay'] * x) - y params = create_params(amp=3, decay={'value': 0.2, 'min': 0}) mini = minimize(residual, params) # Full fit report: statistics + parameter values + correlations print(fit_report(mini)) # Correlation table in RST format print(fit_report(mini, correl_mode='table', min_correl=0.05)) # Confidence interval report from lmfit import Minimizer mini2 = Minimizer(residual, params) result = mini2.minimize() ci = conf_interval(mini2, result) print(report_ci(ci)) # tabular sigma-level summary print(ci_report(ci)) # same, as a string ``` -------------------------------- ### Define and Minimize with Parameters Source: https://github.com/lmfit/lmfit-py/blob/master/doc/intro.rst Defines a residual function and initializes Parameters for a fit. Access parameters by name for clarity and separation of concerns. ```python from numpy import exp, sin from lmfit import minimize, Parameters def residual(params, x, data, uncertainty): amp = params['amp'] phaseshift = params['phase'] freq = params['frequency'] decay = params['decay'] model = amp * sin(x*freq + phaseshift) * exp(-x*x*decay) return (data-model) / uncertainty params = Parameters() params.add('amp', value=10) params.add('decay', value=0.007) params.add('phase', value=0.2) params.add('frequency', value=3.0) out = minimize(residual, params, args=(x, data, uncertainty)) ``` -------------------------------- ### Guess initial parameters using limited data ranges Source: https://github.com/lmfit/lmfit-py/blob/master/doc/builtin_models.rst This snippet demonstrates how to use the index_of function to define specific data ranges for guessing initial parameters of different model components. ```python ix1 = index_of(x, 75) ix2 = index_of(x, 135) ix3 = index_of(x, 175) exp_mod.guess(y[:ix1], x=x[:ix1]) gauss1.guess(y[ix1:ix2], x=x[ix1:ix2]) gauss2.guess(y[ix2:ix3], x=x[ix2:ix3]) ``` -------------------------------- ### Generating Fit Reports Source: https://context7.com/lmfit/lmfit-py/llms.txt Generate a detailed fit report as a string, optionally including parameter correlations. Also shows how to obtain a JSON-serializable summary dictionary. ```python # Fit report as string print(result.fit_report(show_correl=True, min_correl=0.05)) # summery dict (JSON-serialisable) summary = result.summary() ``` -------------------------------- ### Inferring Parameters from Function Arguments (decay2) Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Demonstrates how function arguments with numerical default values become Parameters, while those with non-numerical defaults (like False) become independent variables. Parameters are initialized with default values from the function signature. ```python def decay2(t, tau, N=10, check_positive=False): if check_positive: arg = abs(t)/max(1.e-9, abs(tau)) else: arg = t/tau return N*np.exp(arg) mod = Model(decay2) print(f'independent variables: {mod.independent_vars}') params = mod.make_params() print('Parameters:') for pname, par in params.items(): print(pname, par) ``` -------------------------------- ### Perform MCMC Sampling with Emcee Source: https://github.com/lmfit/lmfit-py/blob/master/doc/fitting.rst Performs MCMC sampling using the 'emcee' method to explore the posterior probability distribution of the parameters. 'is_weighted=False' indicates unweighted residuals, enabling automatic estimation of data uncertainty. ```python res = lmfit.minimize(residual, method='emcee', nan_policy='omit', burn=300, steps=1000, thin=20, params=mi.params, is_weighted=False, progress=False) ``` -------------------------------- ### Set Parameter Bounds in Objective Function Source: https://github.com/lmfit/lmfit-py/blob/master/doc/fitting.rst Demonstrates how to enforce parameter bounds directly within the objective function to prevent invalid calculations, such as division by zero. ```python if abs(period) < 1.e-10: period = sign(period)*1.e-10 ``` -------------------------------- ### Initialize Model Parameters During Fit or Eval Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Explicitly supply initial values for model parameters as keyword arguments directly to the eval or fit methods. ```python x = linspace(0, 10, 100) y_eval = mod.eval(x=x, a=7.0, b=-2.0) y_sim = y_eval + random.normal(0, 0.2, x.size) out = mod.fit(y_sim, pars, x=x, a=3.0, b=0.0) ``` -------------------------------- ### Perform Minimization and Report Fit Source: https://github.com/lmfit/lmfit-py/blob/master/doc/fitting.rst Performs a minimization using the Nelder-Mead method and prints a report of the fit parameters with correlations above 0.5. ```python mi = lmfit.minimize(residual, p, method='nelder', nan_policy='omit') lmfit.printfuncs.report_fit(mi.params, min_correl=0.5) ``` -------------------------------- ### Perform Fit and Print Report Source: https://github.com/lmfit/lmfit-py/blob/master/examples/discuss_model_eval_uncertainty.ipynb Fits the defined model to the data using the initialized parameters and prints a detailed fit report, including model statistics and variable correlations. ```python result = nmodel.fit(yg, params, x=xg) print(result.fit_report(min_correl=0.5)) ``` -------------------------------- ### Create Model Parameters Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Use the make_params method to generate Parameters for a Model. Initial values can be assigned directly or after creation. ```python params = gmodel.make_params() ``` ```python params = gmodel.make_params(cen=0.3, amp=3, wid=1.25) ``` -------------------------------- ### Perform Minimization with lmfit Source: https://github.com/lmfit/lmfit-py/blob/master/README.rst Call the lmfit.minimize function with the objective function, initial parameters, and any necessary arguments or keyword arguments. ```python result = lmfit.minimize(myfunc, fit_params, args=(x, data), kws={'someflag':True}, ....) ``` -------------------------------- ### Default Independent Variables and Parameters Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Demonstrates how lmfit.Model identifies independent variables and parameters by default, based on function argument order and default values. ```python import numpy as np from lmfit import Model def decay(t, tau, N): return N*np.exp(-t/tau) decay_model = Model(decay) print(f'independent variables: {decay_model.independent_vars}') params = decay_model.make_params() print('\nParameters:') for pname, par in params.items(): print(pname, par) ``` -------------------------------- ### Inferring Parameters from Function Arguments (voigt) Source: https://github.com/lmfit/lmfit-py/blob/master/doc/model.rst Shows how arguments with default values of None, True, or False are treated as independent variables but can be converted to Parameters. This allows flexibility in defining model behavior. ```python def voigt(x, amplitude=1.0, center=0.0, sigma=1.0, gamma=None): """Return a 1-dimensional Voigt function. ... """ if gamma is None: gamma = sigma z = (x-center + 1j*gamma) / max(tiny, (sigma*s2)) return amplitude*real(wofz(z)) / max(tiny, (sigma*s2pi)) mod = Model(voigt) print(f'independent variables: {mod.independent_vars}') params = mod.make_params(amplitude=10, center=5, sigma=2) # or params2 = mod.make_params(amplitude=10, center=5, sigma=2, gamma=1.5) ```