Simultaneous model fitting¶
The class SyncFitContainer is designed to provide a simple interface for fitting different models defined on different axes simultaneously. It is designed to mimic the behavior of the OneDFit class, but is not itself an object derived from OneDFit. An example of usage is given in the tutorial.
- class PyAstronomy.funcFit.SyncFitContainer¶
Simultaneous model fitting.
As an example, take a simultaneous measurement of a photometric planetary transit and the Rossiter-McLaughlin effect. Surely, both should be described by a subset of common parameters like the size of the planet and the large semi-major axis, but the models/measurements refer to quite different regimes: brightness and radial-velocity shift. This class can be used to carry out a fit of both simultaneously.
- Attributes
- parsInstance of Params
Manages the model parameters.
- modelsdictionary
A dictionary of the form component-number model; saves the evaluated models.
- penaltyFactorfloat
Factor used to scale the penalty imposed if parameter restrictions are violated.
- _composdictionary
A dictionary of the form component-number model-component. The component number uniquely identifies every model component.
Methods
MCMCautoParameters
(ranges[, picky, ...])Convenience function to generate parameters for MCMC fit.
addComponent
(newCompo)Add a new component to the container.
addConditionalRestriction
(*args)Define a conditional restriction.
assignValue
(specval)Assign new values to variables.
assignValues
(specval)Assign new values to variables.
autoFitMCMC
(x, y, ranges[, picky, stepsize, ...])Convenience function to using auto-generated sampling parameters in MCMC.
availableParameters
()Provides a list of existing parameters.
Returns:
delRestriction
(parName)Delete restriction
evaluate
(axes[, component])Parameters:
fit
(data[, yerr, X0, minAlgo, miniFunc])Carries out the fit.
fitMCMC
(data, X0, Lims, Steps[, yerr, ...])Carry out MCMC fit/error estimation.
freeParamNames
()Get the names of the free parameters.
freeParameters
()Get names and values of free parameters.
freeze
(specifiers)Consider variables free to float.
frozenParameters
()Get names and values of frozen parameters.
getRelationsOf
(specifier)Return relations of a variable.
getRestrictions
()Get all restrictions.
hasVariable
(specifier)Determine whether the variable exists.
numberOfFreeParams
()Get number of free parameters.
parameters
()Obtain parameter names and values.
relate
(dependentVar, independentVars[, func])Define a relation.
removeConditionalRestriction
(*args)Remove an existing conditional constraint.
restoreState
(resource)Restores parameter values from file or dictionary.
saveState
(*args, **kwargs)Save the state of the fitting object.
setObjectiveFunction
([miniFunc])Define the objective function.
setRestriction
(restricts)Define restrictions.
showConditionalRestrictions
(**kwargs)Show conditional restrictions.
steppar
(pars, ranges[, extractFctVal, quiet])Allows to step a parameter through a specified range.
thaw
(specifiers)Consider variables fixed.
treatAsEqual
(parameter)Treat parameters as equal.
untie
(parName[, forceFree])Remove all relations of parameter parName, i.e., the parameter is not dependend on other parameters.
Evaluate all components.
parameterSummary
- addComponent(newCompo)¶
Add a new component to the container.
- Parameters:
newCompo - A funcFit model.
- Returns:
The component identifier.
- components()¶
- Returns:
A list holding the component names.
- evaluate(axes, component=None)¶
- Parameters:
axes - If component is not given, a dictionary holding the x-axis for each component name. Otherwise, the x-axis for the specified component.
component - string, optional, The name of the component to be evaluated.
The evaluated model(s) is saved in the models dictionary.
- fit(data, yerr=None, X0=None, minAlgo=None, miniFunc=None, *fminPars, **fminArgs)¶
Carries out the fit.
In principle, any fit algorithm can be used. If none is specified, the default is scipy.optimize.fmin (Nelder-Mead Simplex). Another choice could for instance be scipy.optimize.fmin_powell. After the fit, the return value of the fitting method is stored in the class property fitResult and the model property is set to the best fit.
- Parameters:
- data - Dictionary of the form: {c:[x, y], …}. Here c is the component number (starts
with one, and x, y are the x-axis and associated values.
- yerr - array, optional: Error of data values. A dictionary of the from: {c:yerr}, where
c is the component and yerr the array of error bars.
X0 - list, optional: The initial guess. If not provided, it will be assumed that self.pars already contains the initial guess.
minAlgo - callable, The minimization algorithm. Default is scipy.optimize.fmin; other algorithms from scipy may be chosen. Alternatively, any callable object taking the function to minimize as the first, the vector of starting values as the second, and a full_output flag as arguments can be used.
fminArgs - Keywords which are passed to the minimization method (default is of scipy.optimize.fmin) (e.g., xtol or ftol).
fminPars - Non-keyword arguments passed to the minimization method (e.g., fprime in scipy.optimize.fmin_ncg).
- fitMCMC(data, X0, Lims, Steps, yerr=None, pymcPars=None, pyy=None, potentials=None, dbfile='mcmcSample.tmp', dbArgs=None, adaptiveMetropolis=False, **sampleArgs)¶
Carry out MCMC fit/error estimation.
This member is designed to provide a flexible but easy to use interface to the capabilities of pymc. In the simplest case, it assumes a Poisson or Gaussian distribution of data points and uses continuous, uniform variables (all free fitting variables) with starting values defined by X0, Limits given by Lims, and step sizes given by Steps to sample from the posterior.
Note
The result (the Marchov-Chain/PyMC MCMC-object) will be contained in the self.MCMC property; the output dictionary of MCMC.stats() (Mean, HPD interval etc.) is saved to self.basicStats.
- Parameters:
x - An array providing the x-values of the data points.
y - An array providing the y-values of the data points. Note that for the MCMC process, it is essential to know the underlying distribution of the data points. fitMCMC assumes Poisson distributed data of yerr is not specified and Gaussian data if it is specified. If other distributions shall be used, the pyy parameter must contain a pymc random variable specifying it.
- yerr - array, optional,
Error of data values. A dictionary of the from: {c:yerr}, where c is the component and yerr the array of error bars. If specified a Gaussian distribution will be assumed for the data points, otherwise a Poisson distribution is assumed.
- pyy - optional,
Can be used to handle a PyMC variable containing the data. This can be useful if the distribution is neither Poisson nor Gaussian as otherwise assumed by this function.
X0 - A dictionary holding {“parName”:value, …} specifying the start values. Note that parameters treated in pymcPars must not be part of this.
Lims - A dictionary of type {“ParName:[min,max], …} specifying the lower and upper limit of a variable. Note that parameters treated in pymcPars must not be part of this.
Steps - A dictionary providing the step sizes for the MCMC sampler.
- pymcPars - optional,
This variable is supposed to hold a dictionary of the form {“parName”:PyMC-Variable, …}. pymcPars can be used to specify a nonuniform distribution for a parameter.
- potentials - optional,
Can be used to provide a list of PyMC potentials, which may be needed to provide priors.
dbfile - The name of the output file, which is to hold the MCMC chain produced during sampling.
- **sampleArgs - optional,
Here additional keywords can be specified, which will be handed to the isample member of PyMC. Most notably it is useful to specify iter, burn, and thin. For other possibilities see PyMC documentation.
- setObjectiveFunction(miniFunc='chisqr')¶
Define the objective function.
This function sets the miniFunc attribute, which is used to calculate the quantity to be minimized.
- Parameters
- miniFuncstr {chisqr, cash79, sqrdiff} or callable
The objective function. If “chisqr”, chi-square will be minimzed. If “cash 79”, the Cash statistics (Cash 1979, ApJ 228, 939, Eq. 5) will be used. If “sqrdiff” is specified, Otherwise, a user-defined function is assumed.
- steppar(pars, ranges, extractFctVal=None, quiet=False)¶
Allows to step a parameter through a specified range.
This function steps the specified parameters through the given ranges. During each steps, all free parameters, except for those which are stepped, are fitted. The resulting contours allow to estimate confidence intervals.
This command uses the fitting parameters specified on a call to the fit method. In particular, the same values for x, y, yerr, minAlgo, miniFunc, fminPars, and fminArgs are used.
Note
You need to have carried out a fit before you can use steppar.
- Parameters
- parsstring or list of strings
The parameter(s) which are to be stepped.
- rangesdictionary
A dictionary mapping parameter name to range specifier. The latter is a list containing [lower limit, upper limit, no. of steps, ‘lin’/’log’]. The fourth entry, which is optional, is a string specifying whether a constant linear step size (‘lin’) or a constant logarithmic step size (‘log’) shall be used.
- quietboolean, optional
If True, output will be suppressed.
- extractFctValcallable, optional
A function specifying how the function value is extracted from the fit result. If standard settings are used, the default of None is adequate.
- Returns
- Parameter stepslist
The return value is a list of lists. Each individual list contains the values of the stepped parameters as the first entries (same order as the input pars list), the following entry is the value of the objective function (e.g., chi square), and the last entry is a tuple containing the indices of the steps of the parameter values. This last entry can be useful to convert the result into an arrow to plot, e.g., contours.
- treatAsEqual(parameter)¶
Treat parameters as equal.
- parameter - string or list of string,
If a string is given, all parameters with this “base name” (i.e., neglecting everything after an underscore) will be treated as equal. Otherwise the specified parameters will be treated as equal.
This method uses the relations known from OneDFit to treat parameters as equal. Dependent variables are thawed before the relation is applied, if they are not already free.
- updateModel()¶
Evaluate all components. Updates the values in the models dictionary.