PowerLaw

class Stoner.analysis.fitting.models.generic.PowerLaw(independent_vars=['x'], prefix='', nan_policy='raise', **kwargs)[source]

Bases: PowerLawModel

Power Law Fitting Equation.

Parameters:
  • x (array) – Input data

  • A (float) – Prefactor

  • k (float) – Power

Returns:

Power law.

\(p=Ax^k\)

Example

"""Example of PowerLaw Fit."""
from numpy import linspace
from numpy.random import normal

from Stoner import Data
from Stoner.analysis.fitting.models.generic import PowerLaw, powerLaw

# Make some data
T = linspace(50, 500, 101)
R = powerLaw(T, 1e-2, 0.6666666) * normal(size=len(T), scale=0.1, loc=1.0)
d = Data(T, R, setas="xy", column_headers=["T", "Rate"])

# Curve_fit on its own
d.curve_fit(powerLaw, p0=[1, 0.5], result=True, header="curve_fit")
d.setas = "xyy"
d.plot(fmt=["r.", "b-"])
d.annotate_fit(powerLaw, x=0.5, y=0.25)

# lmfit using lmfit guesses
fit = PowerLaw()
p0 = fit.guess(R, x=T)
d.lmfit(fit, p0=p0, result=True, header="lmfit")
d.setas = "x..y"
d.plot(fmt="g-")
d.annotate_fit(PowerLaw, x=0.5, y=0.05, prefix="PowerLaw")

d.title = "Powerlaw Test Fit"
d.ylabel = "Rate"
d.xlabel = "Temperature (K)"

(png, hires.png, pdf)

../_images/powerlaw-class.png

Attributes Summary

components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

valid_forms

Methods Summary

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

dumps(**kws)

Dump serialization of Model as a JSON string.

eval([params])

Evaluate the model with supplied parameters and keyword arguments.

eval_components([params])

Evaluate the model with the supplied parameters.

fit(data[, params, weights, method, ...])

Fit the model to the data using the supplied Parameters.

guess(data, x, **kwargs)

Guess starting values for the parameters of a model.

load(fp[, funcdefs])

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

loads(s[, funcdefs])

Load Model from a JSON string.

make_funcargs([params, kwargs, strip])

Convert parameter values and keywords to function arguments.

make_params([verbose])

Create a Parameters object for a Model.

post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting 'calculated parameters'

print_param_hints([colwidth])

Print a nicely aligned text-table of parameter hints.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

Attributes Documentation

components

Return components for composite model.

name

Return Model name.

param_names

Return the parameter names of the Model.

prefix

Return Model prefix.

valid_forms = ()

Methods Documentation

copy(**kwargs)

DOES NOT WORK.

dump(fp, **kws)

Dump serialization of Model to a file.

fpfile-like object

An open and .write()-supporting file-like object.

**kwsoptional

Keyword arguments that are passed to json.dumps.

int

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

dumps, load, json.dump

dumps(**kws)

Dump serialization of Model as a JSON string.

**kwsoptional

Keyword arguments that are passed to json.dumps.

str

JSON string representation of Model.

loads, json.dumps

eval(params=None, **kwargs)

Evaluate the model with supplied parameters and keyword arguments.

paramsParameters, optional

Parameters to use in Model.

**kwargsoptional

Additional keyword arguments to pass to model function.

numpy.ndarray, float, int or complex

Value of model given the parameters and other arguments.

1. if params is None, the values for all parameters are expected to be provided as keyword arguments.

2. If params is given, and a keyword argument for a parameter value is also given, the keyword argument will be used in place of the value in the value in params.

3. all non-parameter arguments for the model function, including all the independent variables will need to be passed in using keyword arguments.

4. The return types are generally numpy.ndarray, but may depends on the model function and input independent variables. That is, return values may be Python float, int, or complex values.

eval_components(params=None, **kwargs)

Evaluate the model with the supplied parameters.

paramsParameters, optional

Parameters to use in Model.

**kwargsoptional

Additional keyword arguments to pass to model function.

dict

Keys are prefixes for component model, values are value of each component.

fit(data, params=None, weights=None, method='leastsq', iter_cb=None, scale_covar=True, verbose=False, fit_kws=None, nan_policy=None, calc_covar=True, max_nfev=None, coerce_farray=True, **kwargs)

Fit the model to the data using the supplied Parameters.

dataarray_like

Array of data to be fit.

paramsParameters, optional

Parameters to use in fit (default is None).

weightsarray_like, optional

Weights to use for the calculation of the fit residual [i.e., weights*(data-fit)]. Default is None; must have the same size as data.

methodstr, optional

Name of fitting method to use (default is ‘leastsq’).

iter_cbcallable, optional

Callback function to call at each iteration (default is None).

scale_covarbool, optional

Whether to automatically scale the covariance matrix when calculating uncertainties (default is True).

verbosebool, optional

Whether to print a message when a new parameter is added because of a hint (default is True).

fit_kwsdict, optional

Options to pass to the minimizer being used.

nan_policy{‘raise’, ‘propagate’, ‘omit’}, optional

What to do when encountering NaNs when fitting Model.

calc_covarbool, optional

Whether to calculate the covariance matrix (default is True) for solvers other than ‘leastsq’ and ‘least_squares’. Requires the numdifftools package to be installed.

max_nfevint or None, optional

Maximum number of function evaluations (default is None). The default value depends on the fitting method.

coerce_farraybool, optional

Whether to coerce data and independent data to be ndarrays with dtype of float64 (or complex128). If set to False, data and independent data are not coerced at all, but the output of the model function will be. (default is True)

**kwargsoptional

Arguments to pass to the model function, possibly overriding parameters.

ModelResult

1. if params is None, the values for all parameters are expected to be provided as keyword arguments. Mixing params and keyword arguments is deprecated (see Model.eval).

2. all non-parameter arguments for the model function, including all the independent variables will need to be passed in using keyword arguments.

3. Parameters are copied on input, so that the original Parameter objects are unchanged, and the updated values are in the returned ModelResult.

Take t to be the independent variable and data to be the curve we will fit. Use keyword arguments to set initial guesses:

>>> result = my_model.fit(data, tau=5, N=3, t=t)

Or, for more control, pass a Parameters object.

>>> result = my_model.fit(data, params, t=t)
guess(data, x, **kwargs)

Guess starting values for the parameters of a model.

dataarray_like

Array of data (i.e., y-values) to use to guess parameter values.

xarray_like

Array of values for the independent variable (i.e., x-values).

**kwsoptional

Additional keyword arguments, passed to model function.

paramsParameters

Initial, guessed values for the parameters of a Model.

Changed in version 1.0.3: Argument x is now explicitly required to estimate starting values.

load(fp, funcdefs=None, **kws)

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

fpfile-like object

An open and .read()-supporting file-like object.

funcdefsdict, optional

Dictionary of function definitions to use to construct Model.

**kwsoptional

Keyword arguments that are passed to loads.

Model

Model created from fp.

dump, loads, json.load

loads(s, funcdefs=None, **kws)

Load Model from a JSON string.

sstr

Input JSON string containing serialized Model.

funcdefsdict, optional

Dictionary of function definitions to use to construct Model.

**kwsoptional

Keyword arguments that are passed to json.loads.

Model

Model created from JSON string.

dump, dumps, load, json.loads

make_funcargs(params=None, kwargs=None, strip=True)

Convert parameter values and keywords to function arguments.

make_params(verbose=False, **kwargs)

Create a Parameters object for a Model.

verbosebool, optional

Whether to print out messages (default is False).

**kwargsoptional
Parameter names and initial values or dictionaries of

values and attributes.

paramsParameters

Parameters object for the Model.

  1. Parameter values can be numbers (floats or ints) to set the parameter value, or dictionaries with any of the following keywords: value, vary, min, max, expr, brute_step, is_init_value to set those parameter attributes.

  2. This method will also apply any default values or parameter hints that may have been defined for the model.

>>> gmodel = GaussianModel(prefix='peak_') + LinearModel(prefix='bkg_')
>>> gmodel.make_params(peak_center=3200, bkg_offset=0, bkg_slope=0,
...                    peak_amplitdue=dict(value=100, min=2),
...                    peak_sigma=dict(value=25, min=0, max=1000))
post_fit(fitresult)

function that is called just after fit, can be overloaded by subclasses to add non-fitting ‘calculated parameters’

print_param_hints(colwidth=8)

Print a nicely aligned text-table of parameter hints.

colwidthint, optional

Width of each column, except for first and last columns.

set_param_hint(name, **kwargs)

Set hints to use when creating parameters with make_params().

The given hint can include optional bounds and constraints (value, vary, min, max, expr), which will be used by Model.make_params() when building default parameters.

While this can be used to set initial values, Model.make_params or the function create_params should be preferred for creating parameters with initial values.

The intended use here is to control how a Model should create parameters, such as setting bounds that are required by the mathematics of the model (for example, that a peak width cannot be negative), or to define common constrained parameters.

namestr

Parameter name, can include the models prefix or not.

**kwargsoptional

Arbitrary keyword arguments, needs to be a Parameter attribute. Can be any of the following:

  • valuefloat, optional

    Numerical Parameter value.

  • varybool, optional

    Whether the Parameter is varied during a fit (default is True).

  • minfloat, optional

    Lower bound for value (default is -numpy.inf, no lower bound).

  • maxfloat, optional

    Upper bound for value (default is numpy.inf, no upper bound).

  • exprstr, optional

    Mathematical expression used to constrain the value during the fit.

>>> model = GaussianModel()
>>> model.set_param_hint('sigma', min=0)