Parameter and Parameters — Non-Linear Least-Squares Minimization and Curve-Fitting for Python (2024)

This chapter describes the Parameter object, which is a key concept oflmfit.

A Parameter is the quantity to be optimized in all minimizationproblems, replacing the plain floating point number used in theoptimization routines from scipy.optimize. A Parameter hasa value that can either be varied in the fit or held at a fixed value, andcan have lower and/or upper bounds placed on the value. It can even have avalue that is constrained by an algebraic expression of other Parametervalues. Since Parameter objects live outside the coreoptimization routines, they can be used in all optimization routinesfrom scipy.optimize. By using Parameter objects instead ofplain variables, the objective function does not have to be modified toreflect every change of what is varied in the fit, or whether bounds can beapplied. This simplifies the writing of models, allowing general modelsthat describe the phenomenon and gives the user more flexibility in usingand testing variations of that model.

Whereas a Parameter expands on an individual floating pointvariable, the optimization methods actually still need an ordered group offloating point variables. In the scipy.optimize routines this isrequired to be a one-dimensional numpy.ndarray. In lmfit, this one-dimensionalarray is replaced by a Parameters object, which works as anordered dictionary of Parameter objects with a few additionalfeatures and methods. That is, while the concept of a Parameteris central to lmfit, one normally creates and interacts with aParameters instance that contains many Parameter objects.For example, the objective functions you write for lmfit will take aninstance of Parameters as its first argument. A table ofparameter values, bounds, and other attributes can be printed usingParameters.pretty_print().

The Parameter class

class Parameter(name, value=None, vary=True, min=-inf, max=inf, expr=None, brute_step=None, user_data=None)

A Parameter is an object that can be varied in a fit.

It is a central component of lmfit, and all minimization and modelingmethods use Parameter objects.

A Parameter has a name attribute, and a scalar floating pointvalue. It also has a vary attribute that describes whether thevalue should be varied during the minimization. Finite bounds can beplaced on the Parameter’s value by setting its min and/or maxattributes. A Parameter can also have its value determined by amathematical expression of other Parameter values held in the exprattribute. Additional attributes include brute_step used as the stepsize in a brute-force minimization, and user_data reservedexclusively for user’s need.

After a minimization, a Parameter may also gain other attributes,including stderr holding the estimated standard error in theParameter’s value, and correl, a dictionary of correlation valueswith other Parameters used in the minimization.

Parameters:
  • name (str) – Name of the Parameter.

  • value (float, optional) – Numerical Parameter value.

  • vary (bool, optional) – Whether the Parameter is varied during a fit (default is True).

  • min (float, optional) – Lower bound for value (default is -numpy.inf, no lowerbound).

  • max (float, optional) – Upper bound for value (default is numpy.inf, no upperbound).

  • expr (str, optional) – Mathematical expression used to constrain the value during thefit (default is None).

  • brute_step (float, optional) – Step size for grid points in the brute method (default isNone).

  • user_data (optional) – User-definable extra attribute used for a Parameter (defaultis None).

stderr

The estimated standard error for the best-fit value.

Type:

float

correl

A dictionary of the correlation with the other fittedParameters of the form:

{'decay': 0.404, 'phase': -0.020, 'frequency': 0.102}
Type:

dict

See Bounds Implementation for details on the math used to implement thebounds with min and max.

The expr attribute can contain a mathematical expression that willbe used to compute the value for the Parameter at each step in the fit.See Using Mathematical Constraints for more details and examples of thisfeature.

set(value=None, vary=None, min=None, max=None, expr=None, brute_step=None, is_init_value=True)

Set or update Parameter attributes.

Parameters:
  • value (float, optional) – Numerical Parameter value.

  • vary (bool, optional) – Whether the Parameter is varied during a fit.

  • min (float, optional) – Lower bound for value. To remove a lower bound you must use-numpy.inf.

  • max (float, optional) – Upper bound for value. To remove an upper bound you must usenumpy.inf.

  • expr (str, optional) – Mathematical expression used to constrain the value during thefit. To remove a constraint you must supply an empty string.

  • brute_step (float, optional) – Step size for grid points in the brute method. To remove thestep size you must use 0.

  • is_init_value (bool, optional) – Whether to set value as init_value, when setting value.

Notes

Each argument to set() has a default value of None, which willleave the current value for the attribute unchanged. Thus, to lifta lower or upper bound, passing in None will not work. Instead,you must set these to -numpy.inf or numpy.inf, as with:

Similarly, to clear an expression, pass a blank string, (notNone!) as with:

par.set(expr=None) # leaves expression unchangedpar.set(expr='') # removes expression

Explicitly setting a value or setting vary=True will alsoclear the expression.

Finally, to clear the brute_step size, pass 0, not None:

par.set(brute_step=None) # leaves brute_step unchangedpar.set(brute_step=0) # removes brute_step

The Parameters class

class Parameters(usersyms=None)

A dictionary of Parameter objects.

It should contain all Parameter objects that are required to specifya fit model. All minimization and Model fitting routines in lmfit willuse exactly one Parameters object, typically given as the firstargument to the objective function.

All keys of a Parameters() instance must be strings and valid Pythonsymbol names, so that the name must match [a-z_][a-z0-9_]* andcannot be a Python reserved word.

All values of a Parameters() instance must be Parameter objects.

A Parameters(xs) instance includes an asteval Interpreter used forevaluation of constrained Parameters.

Parameters() support copying and pickling, and have methods to convertto and from serializations using json strings.

Parameters:

usersyms (dict, optional) – Dictionary of symbols to add to theasteval.Interpreter (default is None).

add(name, value=None, vary=True, min=-inf, max=inf, expr=None, brute_step=None)

Add a Parameter.

Parameters:
  • name (str or Parameter) – If name refers to a Parameter object it will be added directlyto the Parameters instance, otherwise a new Parameter object with namestring is created before adding it. In both cases, name mustmatch [a-z_][a-z0-9_]* and cannot be a Python reserved word.

  • value (float, optional) – Numerical Parameter value, typically the initial value.

  • vary (bool, optional) – Whether the Parameter is varied during a fit (default is True).

  • min (float, optional) – Lower bound for value (default is -numpy.inf, no lowerbound).

  • max (float, optional) – Upper bound for value (default is numpy.inf, no upperbound).

  • expr (str, optional) – Mathematical expression used to constrain the value during thefit (default is None).

  • brute_step (float, optional) – Step size for grid points in the brute method (default isNone).

Examples

>>> params = Parameters()>>> params.add('xvar', value=0.50, min=0, max=1)>>> params.add('yvar', expr='1.0 - xvar')

which is equivalent to:

>>> params = Parameters()>>> params['xvar'] = Parameter(name='xvar', value=0.50, min=0, max=1)>>> params['yvar'] = Parameter(name='yvar', expr='1.0 - xvar')
add_many(*parlist)

Add many parameters, using a sequence of tuples.

Parameters:

*parlist (sequence of tuple or Parameter) – A sequence of tuples, or a sequence of Parameter instances.If it is a sequence of tuples, then each tuple must contain atleast a name. The order in each tuple must be(name, value, vary, min, max, expr, brute_step).

Examples

>>>  params = Parameters()# add with tuples: (NAME VALUE VARY MIN MAX EXPR BRUTE_STEP)>>> params.add_many(('amp', 10, True, None, None, None, None),...  ('cen', 4, True, 0.0, None, None, None),...  ('wid', 1, False, None, None, None, None),...  ('frac', 0.5))# add a sequence of Parameters>>> f = Parameter('par_f', 100)>>> g = Parameter('par_g', 2.)>>> params.add_many(f, g)
pretty_print(oneline=False, colwidth=8, precision=4, fmt='g', columns=['value', 'min', 'max', 'stderr', 'vary', 'expr', 'brute_step'])

Pretty-print of parameters data.

Parameters:
  • oneline (bool, optional) – If True prints a one-line parameters representation [False]

  • colwidth (int, optional) – Column width for all columns specified in columns [8]

  • precision (int, optional) – Number of digits to be printed after floating point [4]

  • fmt ({'g', 'e', 'f'}, optional) – Single-character numeric formatter. Valid values are: ‘g’floating point and exponential (default), ‘e’ exponential,or ‘f’ floating point.

  • columns (list of str, optional) – List of Parameter attribute names to print (defaultis to show all attributes).

valuesdict()

Return an ordered dictionary of parameter values.

Returns:

A dictionary of name:value pairs for eachParameter.

Return type:

dict

create_uvars(covar=None)

Return a dict of uncertainties ufloats from the current Parametervalues and stderr, and an optionally-supplied covariance matrix.Uncertainties in Parameters with constraint expressions will becalculated, propagating uncertaintes (and including correlations)

Parameters:

covar (optional) – Nvar x Nvar covariance matrix from fit

Return type:

dict with keys of Parameter names and values of uncertainties.ufloats.

Notes

  1. if covar is provide, it must correspond to the existing variableParameters. If covar is given, the returned uncertainties ufloatswill take the correlations into account when combining values.

  2. See the uncertainties package documentation(https://pythonhosted.org/uncertainties) for more details.

dumps(**kws)

Represent Parameters as a JSON string.

Parameters:

**kws (optional) – Keyword arguments that are passed to json.dumps.

Returns:

JSON string representation of Parameters.

Return type:

str

See also

dump, loads, load, json.dumps

dump(fp, **kws)

Write JSON representation of Parameters to a file-like object.

Parameters:
  • fp (file-like object) – An open and .write()-supporting file-like object.

  • **kws (optional) – Keyword arguments that are passed to dumps.

Returns:

Return value from fp.write(): the number of characterswritten.

Return type:

int

See also

dumps, load, json.dump

eval(expr)

Evaluate a statement using the asteval Interpreter.

Parameters:

expr (str) – An expression containing parameter names and other symbolsrecognizable by the asteval Interpreter.

Returns:

The result of evaluating the expression.

Return type:

float

loads(s, **kws)

Load Parameters from a JSON string.

Parameters:

**kws (optional) – Keyword arguments that are passed to json.loads.

Returns:

Updated Parameters from the JSON string.

Return type:

Parameters

Notes

Current Parameters will be cleared before loading the data fromthe JSON string.

See also

dump, dumps, load, json.loads

load(fp, **kws)

Load JSON representation of Parameters from a file-like object.

Parameters:
  • fp (file-like object) – An open and .read()-supporting file-like object.

  • **kws (optional) – Keyword arguments that are passed to loads.

Returns:

Updated Parameters loaded from fp.

Return type:

Parameters

See also

dump, loads, json.load

Warning

Saving Parameters with user-added functions to the _astevalinterpreter using :meth::dump and dumps() may not be easilyrecovered with the load() and loads(). SeeSaving and Loading Models for further discussion.

The create_params() function

New in version 1.2.0.

The create_params() function is probably the easiest method for makingParameters objects, as it allows defining Parameter names by keywordwith values either being the numerical initial value for the Parameter or beinga dictionary with keyword/value pairs for value as well as other Parameterattribute such as min, max, expr, and so forth.

create_params(**kws)

Create lmfit.Parameters instance and set initial values and attributes.

Parameters:

**kws – keywords are parameter names, value are dictionaries of Parametervalues and attributes.

Return type:

Parameters instance

Notes

  1. keyword arguments will be used to create parameter names.

  2. values can either be numbers (floats or integers) to set the parametervalue, or can be dictionaries with any of the following keywords:value, vary, min, max, expr, brute_step, oris_init_value to set those parameter attributes.

  3. for each parameter, is_init_value controls whether to setinit_value when setting value, and defaults to True.

Examples

>>> params = create_params(amplitude=2, center=200, sigma={'value': 3, 'min':0}, fwhm={'expr': '2.0*sigma'})

Simple Example

A basic example making use of Parameters and theminimize() function (discussed in the next chapter)might look like this:

# <examples/doc_parameters_basic.py>import numpy as npfrom lmfit import Minimizer, Parameters, create_params, report_fit# create data to be fittedx = np.linspace(0, 15, 301)np.random.seed(2021)data = (5.0 * np.sin(2.0*x - 0.1) * np.exp(-x*x*0.025) + np.random.normal(size=x.size, scale=0.2))# define objective function: returns the array to be minimizeddef fcn2min(params, x, data): """Model a decaying sine wave and subtract data.""" amp = params['amp'] shift = params['shift'] omega = params['omega'] decay = params['decay'] model = amp * np.sin(x*omega + shift) * np.exp(-x*x*decay) return model - data# create a set of Parametersparams = Parameters()params.add('amp', value=10, min=0)params.add('decay', value=0.1)params.add('shift', value=0.0, min=-np.pi/2., max=np.pi/2.)params.add('omega', value=3.0)# ... or useparams = create_params(amp=dict(value=10, min=0), decay=0.1, omega=3, shift=dict(value=0, min=-np.pi/2, max=np.pi/2))# do fit, here with the default leastsq algorithmminner = Minimizer(fcn2min, params, fcn_args=(x, data))result = minner.minimize()# calculate final resultfinal = data + result.residual# write error reportreport_fit(result)# try to plot resultstry: import matplotlib.pyplot as plt plt.plot(x, data, '+') plt.plot(x, final) plt.show()except ImportError: pass# <end of examples/doc_parameters_basic.py>

Here, the objective function explicitly unpacks each Parameter value. Thiscan be simplified using the Parameters valuesdict() method,which would make the objective function fcn2min above look like:

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

The results are identical, and the difference is a stylistic choice.

© Copyright 2024, Matthew Newville, Till Stensitzki, Renee Otten, and others. Created using Sphinx 7.2.6.

Parameter and Parameters — Non-Linear Least-Squares Minimization and Curve-Fitting for Python (2024)

References

Top Articles
Latest Posts
Article information

Author: Mr. See Jast

Last Updated:

Views: 5579

Rating: 4.4 / 5 (55 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Mr. See Jast

Birthday: 1999-07-30

Address: 8409 Megan Mountain, New Mathew, MT 44997-8193

Phone: +5023589614038

Job: Chief Executive

Hobby: Leather crafting, Flag Football, Candle making, Flying, Poi, Gunsmithing, Swimming

Introduction: My name is Mr. See Jast, I am a open, jolly, gorgeous, courageous, inexpensive, friendly, homely person who loves writing and wants to share my knowledge and understanding with you.