This module provides wrappers, called Fitters, around some Numpy and Scipy fitting functions. All Fitters can be called as functions. They take an instance of ParametricModel as input and modify parameters attribute. The idea is to make this extensible and allow users to easily add other fitters.
Linear fitting is done using Numpy’s lstsq function. There are currently two non-linear fitters which use leastsq and fmin_slsqp.
The rules for passing input to fitters are:
Fitting a polynomial model to multiple data sets simultaneously:
>>> from astropy.modeling import models, fitting
>>> import numpy as np
>>> p1 = models.Polynomial1D(3)
>>> p1.c0 = 1
>>> p1.c1 = 2
>>> p1.parameters
array([ 1., 2., 0., 0.])
>>> x = np.arange(10)
>>> y = p1(x)
>>> yy = np.array([y, y]).T
>>> p2 = models.Polynomial1D(3, param_dim=2)
>>> pfit = fitting.LinearLSQFitter()
>>> new_model = pfit(p2, x, yy)
>>> print(new_model.param_sets)
[[ 1.00000000e+00 1.00000000e+00]
[ 2.00000000e+00 2.00000000e+00]
[ 3.88335494e-16 3.88335494e-16]
[ -2.997...e-17 -2.997...e-17]]
Fitters support constrained fitting.
All fitters support fixed (frozen) parameters through the fixed argument to models or setting the fixed attribute directly on a parameter.
For linear fitters, freezing a polynomial coefficient means that a polynomial without that term will be fitted to the data. For example, fixing c0 in a polynomial model will fit a polynomial with the zero-th order term missing. However, the fixed value of the coefficient is used when evaluating the model:
>>> x = np.arange(1, 10, .1)
>>> p1 = models.Polynomial1D(2, param_dim=2)
>>> p1.parameters = [1, 1, 2, 2, 3, 3]
>>> p1.param_sets
array([[ 1., 1.],
[ 2., 2.],
[ 3., 3.]])
>>> y = p1(x)
>>> p1.c0.fixed = True
>>> pfit = fitting.LinearLSQFitter()
>>> new_model = pfit(p1, x, y)
>>> new_model.param_sets
array([[ 1., 1. ],
[ 2.38641216, 2.38641216],
[ 2.96827886, 2.96827886]])
A parameter can be tied (linked to another parameter). This can be done in two ways:
>>> def tiedfunc(g1):
... mean = 3 * g1.stddev
... return mean
>>> g1 = models.Gaussian1D(amplitude=10., mean=3, stddev=.5,
... tied={'mean': tiedfunc})
or:
>>> g1 = models.Gaussian1D(amplitude=10., mean=3, stddev=.5)
>>> g1.mean.tied = tiedfunc
>>> gfit = fitting.NonLinearLSQFitter()
Bounded fitting is supported through the bounds arguments to models or by setting min and max attributes on a parameter. Bounds for the NonLinearLSQFitter are always exactly satisfied–if the value of the parameter is outside the fitting interval, it will be reset to the value at the bounds. The SLSQPFitter handles bounds internally.
Different fitters support different types of constraints:
>>> fitting.LinearLSQFitter.supported_constraints
['fixed']
>>> fitting.NonLinearLSQFitter.supported_constraints
['fixed', 'tied', 'bounds']
>>> fitting.SLSQPFitter.supported_constraints
['bounds', 'eqcons', 'ineqcons', 'fixed', 'tied']