Fitting object base class¶
The OneDFit class provides a convenient interface to fitting algorithms.
- class PyAstronomy.funcFit.OneDFit(parList, **kwargs)¶
The base class for fitting objects.
- Parameters
- parListlist of strings
Contains the names of the properties defining the model. By default, variables of the same name are used to represent them.
Notes
The purpose of the class
The purpose of this class is to provide a convenient interface to various fitting algorithms. It provides the functionality, which allows for parameter fitting, but does not implement a particular model. The class can be used to fit any kind of model, which has to be implemented in a class, which inherits from the OneDFit class.
Management of fitting parameters
The fitting parameters are managed by a Params class instance, which provides a wealth of possibilities to influence the behavior of the parameters during the fitting process. This includes deciding whether a particular parameter is supposed to be a free fitting parameter, applying restrictions to limit the valid range for a parameters, or the introduction of functional dependencies among different parameters.
Properties versus variable names
Each model is described by a number of properties, such as, for example, mass and radius. These may be represented by arbitrarily named variables. Normally, it is convenient to name the variables according to the properties they describe, which is the default behavior. However, in some cases, for example if a model consists of two equal subcomponents, such a naming scheme leads to nonunique variable names, which has to be avoided. Now it is necessary to distinguish between the property and the describing variable. This class uses the propMap dictionary, which maps property name to variable name to manage these situations.
Combining fitting objects
Often, it can be convenient to combine a number of simple models to form a new, more complex one. The OneDFit class allows to combine objects using the arithmetic operators +-*/, and the power (**) operator.
Naming scheme for models
For simple models it is convenient to use a one-to-one mapping between property and variable name. It may, however, become necessary to deviate from this scheme, for example, to keep variable names unique. This class supports the following naming scheme: Each model has a “root name”, which is supposed to be a concise string describing the model (for instance, “Gaussian”). The root name is attached to the property name using an underscore. If a complex model consists of more than one component with the same root name, a component counter, enclosed in parenthesis, is attached to the variable name. A variable name could, for example, look like: “mu_Gaussian(1)”.
Methods to be implemented in a model class
A valid model class inheriting this interface class must provide the following methods
__init__() - The constructor.
Defines the set of properties describing the model.
evaluate(x) - An evaluate method.
This method takes a single argument, x, which is an array of points at which the model is to be evaluated. To access the current model parameters, this method should use the set/getitem methods. The return value is an array holding the model evaluated at the points given by x.
- Attributes
- modelarray
Used by the updateModel method to store the evaluated model for current parameter settings. Holds the best-fit model after a call to a fit method.
- penaltyFactorfloat
The penalty factor used to apply penalties for enforcing restrictions (default = 10**20).
Methods
MCMCautoParameters
(ranges[, picky, ...])Convenience function to generate parameters for MCMC fit.
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.
Provides a list of existing parameters.
delRestriction
(parName)Delete restriction
description
([parenthesis])Returns a description of the model based on the names of the individual components.
errorConfInterval
(par[, dstat, statTol, ...])Calculate confidence interval for a parameter.
fit
(x, y[, yerr, X0, minAlgo, mAA, ...])Carries out a fit.
fitEMCEE
([x, y, yerr, nwalker, priors, ...])MCMC sampling using emcee package.
fitMCMC
(x, y, X0, Lims, Steps[, yerr, ...])Carry out MCMC fit/error estimation.
Get the names of the free parameters.
Get names and values of free parameters.
freeze
(specifiers)Consider variables free to float.
Get names and values of frozen parameters.
getRelationsOf
(specifier)Return relations of a variable.
Get all restrictions.
hasVariable
(specifier)Determine whether the variable exists.
Get number of free parameters.
parameterSummary
([toScreen, prefix, sorting])Writes a summary of the parameters in text form.
Obtain parameter names and values.
relate
(dependentVar, independentVars[, func])Define a relation.
removeConditionalRestriction
(*args)Remove an existing conditional constraint.
renameVariable
(oldName, newName)Change name of variable.
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.
setPenaltyFactor
(penalFac)Change the penalty factor.
setRestriction
(restricts)Define restrictions.
setRootName
(root[, rename])Define the root name of the model.
showConditionalRestrictions
(**kwargs)Show conditional restrictions.
steppar
(pars, ranges[, extractFctVal, quiet])Allows to step a parameter through a specified range.
thaw
(specifiers)Consider variables fixed.
untie
(parName[, forceFree])Remove all relations of parameter parName, i.e., the parameter is not dependend on other parameters.
Recalculate the model using current settings.
- MCMCautoParameters(ranges, picky=True, stepsize=0.01, setRestrictionsFromPriors=False)¶
Convenience function to generate parameters for MCMC fit.
This function prepares the X0, Lims, and Steps dictionaries needed to call
fitMCMC()
.For X0, the current parameter values are used. Lims is constructed using the ranges parameter, and Steps is defined on the basis of the stepsize and ranges parameters.
The picky parameter determines how this functions handles behaves if it encounters parameters in the range dictionary, which were either not thawed or have been thawed but have not been specified in ranges. If picky is True (the default), this function throws an error if ranges does not cover all and only the free parameters. If picky is False, the function will automatically thaw all parameters specified through ranges and freeze the rest.
Warning
There is NO guarantee that the sampling parameters (start values, limits for the uniform priors, and initial step sizes for the sampler) are reasonable. You need to check the results.
- Parameters
- rangesdictionary
Holds the fit ranges for the individual parameters. If single values are given, the sampling range (uniform prior) will be arranged symmetrically around the parameter’s current value. It is also possible to specify a range directly using, e.g., “A1”:[0,100].
- stepsizefloat, optional
Defines the step size as a fraction of the fit range given in ranges.
- pickyboolean, optional
If True (default), the list of free parameters has to match exactly the list of parameters specified in ranges. If False, the list of free parameters will be adapted to those given in ranges.
- setRestrictionsFromPriorsboolean, optional
Default: False. If True, parameter restrictions are applied according to the ranges of the uniform priors.
- Returns
- X0dictionary
Maps parameter name to start value.
- limsdictionary
Maps parameter name to [lower, upper] limit.
- stepsdictionary
Maps parameter name to step size.
Examples
from PyAstronomy import funcFit as fuf import numpy as np import matplotlib.pylab as plt x = np.linspace(0,30,1000) gauss = fuf.GaussFit1d() gauss["A"] = 1 gauss["mu"] = 23. gauss["sig"] = 0.5 yerr = np.random.normal(0., 0.05, len(x)) y = gauss.evaluate(x) + yerr # This step is not necessary if <picky>=False in MCMCautoParameters. gauss.thaw(["A","mu","sig"]) X0, lims, steps = gauss.MCMCautoParameters({"A":[0,10],"mu":3, "sig":[0.1,1.0]}) gauss.fitMCMC(x, y, X0, lims, steps, yerr=yerr, iter=1000) plt.plot(x, y, 'k+') plt.plot(x, gauss.evaluate(x), 'r--') plt.show()
- addConditionalRestriction(*args)¶
Define a conditional restriction.
Conditional restrictions can be used to modify the behavior in a more complex manner. For instance, penalties can be added to the objective function depending on the relation of one or more parameters.
The given function is evaluated in each iteration and its return value (a float) is added to the objective function (e.g., chi square).
- Parameters
- parslist of strings
The names of the parameters the given function needs as input.
- funccallable object
This callable object must take the specified parameters (in that exact order) as input. It must return a float, which is added to the value of the objective function.
- Returns
- identifierstring
A unique ID used to refer to the conditional restriction.
- assignValue(specval)¶
Assign new values to variables.
- Parameters
- specvaldictionary
Dictionary mapping variable names (wither given as string or specifier tuple) to value.
- assignValues(specval)¶
Assign new values to variables.
- Parameters
- specvaldictionary
Dictionary mapping variable names (wither given as string or specifier tuple) to value.
- autoFitMCMC(x, y, ranges, picky=True, stepsize=0.001, yerr=None, pymcPars={}, pyy=None, potentials=[], dbfile='mcmcSample.tmp', dbArgs={}, **sampleArgs)¶
Convenience function to using auto-generated sampling parameters in MCMC.
This function is essentially a wrapper around
fitMCMC()
. It allows you to use the start values, step sizes, and limits constructed usingMCMCautoParameters()
. This method takes all parameters but X0, Lims, and Steps, which are expected byfitMCMC()
. Additionally, the following parameters are available.Warning
There is NO guarantee that the sampling parameters (start values, limits for the uniform priors, and initial step sizes for the sampler) are reasonable. You need to check the results.
- Parameters
- rangesdictionary
Holds the fit ranges for the individual parameters. If a single values is given, the fit range will be arranged symmetrically around the parameter’s current value. It is also possible to specify a range directly using, e.g., “A1”:[0,100].
- stepsizefloat, optional
Defines the step size as a fraction of the fit range given in ranges.
- pickyboolean, optional
If True (default), the list of free parameters has to match exactly the list of parameters specified in ranges. If False, the list of free parameters will be adapted to those given in ranges.
Examples
from PyAstronomy import funcFit as fuf import numpy as np import matplotlib.pylab as plt x = np.linspace(0,30,1000) gauss = fuf.GaussFit1d() gauss["A"] = 1 gauss["mu"] = 23. gauss["sig"] = 0.5 yerr = np.random.normal(0., 0.05, len(x)) y = gauss.evaluate(x) + yerr ranges = {"A":[0,5],"mu":10, "sig":[0.1,1.0]} gauss.autoFitMCMC(x, y, ranges, yerr=yerr, iter=1000, picky=False) plt.plot(x, y, 'k+') plt.plot(x, gauss.evaluate(x), 'r--') plt.show()
- availableParameters()¶
Provides a list of existing parameters.
- Returns
- Parameterslist of strings
A list with the names of available parameters.
- delRestriction(parName)¶
Delete restriction
- Parameters
- parNamestring
Name of restricted parameter
- description(parenthesis=False)¶
Returns a description of the model based on the names of the individual components.
- Parameters
- parenthesisboolean, optional
If True, the entire expression/description will be enclosed in parenthesis. The default is False.
- Returns
- Descriptionstring
Description of the model.
- errorConfInterval(par, dstat=2.706, statTol=0.01, hardLimit=None, maxiter=100, scale=None)¶
Calculate confidence interval for a parameter.
This function uses linear extrapolation (similar to Newton’s method) to find the points, where the objective function reaches an offset of dstat from the minimum value.
Note
You need to have carried out a fit before you can use errorConfInterval.
- Parameters
- parstring
The parameter name for which to determine the error.
- dstatfloat, optional
The offset from the minimum to be reached in the objective function’s value. For chi-square, a value of 1.0 corresponds to a one sigma (68%) confidence interval whereas the default of 2.706 refers to a 90% confidence interval.
- statTolfloat, optional
The acceptable (absolute) tolerance in achieving the target value in the objective function. The default is 0.01.
- hardLimitlist of two floats, optional
Hard limits for the confidence interval. You can specify hard limits independently of parameter restrictions defined otherwise. To specify limits, specify a list of two floats defining the lower and upper limit. Use None where no limit is needed: e.g., use hardLimits=[0.0, None].
- maxiterint, optional
The maximum number of acceptable iterations. If exceeded, the calculation of the confidence interval is stopped and None is returned. The default is 100.
- scalefloat, optional
This number should reflect the typical scale or extent of the problem. If nothing is specified, a tenth of the current parameter value is used.
- Returns
- Confidence intervaldictionary
- The dictionary contains the following keys:
- “limits”A list of two floats specifying the lower and upper
limits of the confidence interval.
- “OFVals”A list of two floats containing the values of the
objective function at the lower and upper limit.
“OFMin” : The minimum value of the objective function.
- “parMinVal”The parameter value at the minimum value of the
objective function (best-fit value).
- “iters”The number of iterations needed to reach the result.
Note that the function returns None if the maximum number of iterations is exceeded.
- fit(x, y, yerr=None, X0=None, minAlgo=None, mAA=None, miniFunc=None, printTime=False, *fminPars, **fminArgs)¶
Carries out a fit.
Uses an internal optimizer to find the best-fit parameters. By default, the method uses the scipy.optimize.fmin algorithm (Nelder-Mead Simplex) to find the best-fit parameters. After the fit, the parameter values are set to the best-fit values.
- Parameters
- x,yarrays
Specify the abscissa and ordinate values of the data points.
- yerrarray, optional
Error of data values.
- X0list, optional
The initial guess. If not provided, it will be assumed that the current parameter values already contains the initial guess.
- minAlgocallable or string, optional
The minimization algorithm. If not specified, scipy’s ‘fmin’ implementation will be used. If a callable is given, it must adhere to funcFit’s internal optimizer model (a suitable example is scipy’s fmin_powell). Valid strings are:
‘spfmin’ : scipy.optimize.fmin
‘fufnm’ : funcFit’s implementation of the Nelder-Mead simplex algorithm
‘spfmp’ : scipy.optimize.fmin_powell
- mAAdictionary, optional
Keyword arguments handed to the constructor of minAlgo, i.e., minAlgo Arguments (mAA). Valid keywords depend on the choice of the fit algorithm.
- fminArgsdict
Keywords passed to the minimization method (e.g., xtol or ftol for scipy.optimize.fmin).
- fminPars
Non-keyword arguments passed to the minimization method (e.g., fprime in scipy.optimize.fmin_ncg).
- miniFuncNone, string {“chisqr”, “cash79”}, or function
Function to be minimized. If None or “chisqr” is given, chi-square will be minimized. If “cash79” is given, the Cash statistics (Cash 1979, ApJ 228, 939, Eq. 5) will be minimized. If a function is specified, that, potentially user defined, function will be used to calculated the statistics, which will be minimized.
- printTime: boolean, optional
If True, the number of seconds needed to carry out the fit is printed. Default is False. At any rate, the time in seconds is stored in the “requiredTime” attribute.
- fitEMCEE(x=None, y=None, yerr=None, nwalker=None, priors=None, pots=None, scales=None, sampleArgs=None, dbfile='chain.emcee', ps=None, emcp=None, toMD=True)¶
MCMC sampling using emcee package.
Sample from the posterior probability distribution using the emcee package. By default the likelihood is calculated as -0.5 times the model chi-square value.
The emcee sampler can be accessed via the emceeSampler attribute, which may be used to continue or manipulate sampling.
- Parameters
- nwalkerint, optional
The number of walker to be used. By default, two times the number of free parameters is used.
- scalesdictionary, optional
The scales argument can be used to control the initial distribution of the walkers. By default, all walkers are distributed around the location given by the current state of the object, i.e., the current parameter values. In each direction, the walker are randomly distributed with a Gaussian distribution, whose default standard deviation is one. The scales argument can be used to control the width of Gaussians used to distribute the walkers.
- sampleArgsdictionary, optional
Number controlling the sampling process. Use ‘burn’ (int) to specify the number of burn-in iterations (default is 0). Via ‘iters’ (int) the numbers of iterations after the burn-in can be specified (default 1000). The ‘process’ (int) key can be used to control the number of iterations after which the progress bar is updated (default is iters/100). Note that the ‘progressbar’ package must be installed to get a progress bar. Otherwise more mundane print statements will be used.
- priorsdictionary, optional
For each parameter, a primary can be specified. In particular, a prior is a callable, which is called with two arguments: first, a dictionary mapping the names of the free parameters to their current values, and second, a string specifying the name of the parameter for which the prior is to apply. The return value must be the logarithmic prior probability (natural logarithm). A number of default priors are available in the form of the FuFPrior class. By default, a uniform (improper) prior is used for all parameter, for which no other prior was specified.
- potslist, optional
A list of ‘potentials’. A potential is a function, which is called using a dictionary holding the current value for all parameters and returns the logarithm of the associated probability. Potentials may, e.g., be used to implement certain relations between parameter values not otherwise accounted for.
- dbfilestring, optional
The result of the sampling, i.e., the chain(s), the corresponding values of the posterior, and the names of the free parameters are saved to the specified file (by default ‘chain.emcee’ is used). The traces stored there can be analyzed using the ‘TraceAnalysis’ class. Set this parameter to ‘None’ to avoid saving the results.
- pstuple, optional
A tuple holding the current position and state of the sampler. This tuple is returned by this method. The ps argument can be used to continue sampling from the last state. Note that no burn-in will ne carried out and the other arguments should be given as previously to continue sampling successfully.
- emcpdictionary, optional
Extra arguments handed to EnsembleSampler object.
- toMDboolean, optional
If True (default), the object is set to the lowest-deviance solution after sampling. Otherwise, it remains in a random state.
- fitMCMC(x, y, X0, Lims, Steps, yerr=None, pymcPars=None, pyy=None, potentials=None, dbfile='mcmcSample.tmp', quiet=False, 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, yarray
Array providing the abscissa and ordinate values of the data points. For the MCMC process, it is essential to know the underlying distribution of the data points. fitMCMC assumes Poisson distributed data if 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.
- yerrarray, optional
The error of the data points. If not specified, Poisson distributed data will be assumed.
- pyyPyMC stochastic, optional,
A PyMC variable containing the data. This can be useful if the distribution is neither Poisson nor Gaussian as otherwise assumed by this method.
- X0dict
A dictionary holding {“parName”:value, …} specifying the start values. Note that parameters treated in pymcPars must not be part of this.
- Limsdict,
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.
- Stepsdict
A dictionary providing the step sizes for the MCMC sampler.
- pymcParsdict, optional,
Holds a dictionary of the form {“parName”:PyMC-Variable, …}. pymcPars can be used to specify a nonuniform distribution for a parameter.
- potentialslist of PyMC potentials, optional,
Can be used to provide a list of PyMC potentials, which may be needed to provide priors.
- dbfilestring, optional,
The name of the output file, which is to hold the MCMC chain produced during sampling (default=”mcmcSample.tmp”).
- quietbool, optional,
Set to True in order to suppress the text output.
- sampleArgsdict, 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.
- dbArgsdict, optional,
Keyword arguments specifying the trace database to be used. By default a pickle database named according to the dbfile keyword. You may also use an hdf5 database.
- adaptiveMetropolisbool, optional,
Set to true in order to use the AdaptiveMetropolis step method.
- freeParamNames()¶
Get the names of the free parameters.
- Returns
- Free parameterslist of strings
The names of the free parameters. The order is determined by the paramNum attribute.
- freeParameters()¶
Get names and values of free parameters.
- Returns
- Free parameters: dict
Dictionary containing the names and values of all free parameters ({“parName”:value, …}).
- freeze(specifiers)¶
Consider variables free to float.
- Parameters
- specifierslist of strings or tuples
The names of the variables to be thawed. Either given as string or specifier tuple.
- frozenParameters()¶
Get names and values of frozen parameters.
- Returns
- Frozen parameters: dict
Dictionary containing the names and values of all frozen parameters ({“parName”:value, …}).
- getRelationsOf(specifier)¶
Return relations of a variable.
- Parameters
- specifierstring or tuple
Variable name or specifier tuple.
- Returns
- Relationslist of relations
Those relations in which specifier is the dependent variable, i.e., specifier = f(x,y).
- getRestrictions()¶
Get all restrictions.
- Returns
- Restrictionsdict
Dictionary associating parameter name and restriction (see restrictions attribute).
- hasVariable(specifier)¶
Determine whether the variable exists.
- Parameters
- specifierstring or tuple
Defines the name of the variable to be checked by string or specifier.
- Returns
- Flagboolean
True if the variable exists.
- numberOfFreeParams()¶
Get number of free parameters.
- Returns
- nint
The number of free parameters (determined by isFree).
- parameterSummary(toScreen=True, prefix='', sorting='none')¶
Writes a summary of the parameters in text form.
- Parameters
- toScreenbool, optional, default = True
If True, the output is written to the screen.
- prefixstring, optional, default = “”
A prefix for each line (e.g., ‘#’).
- sortingstring, optional, {‘none’, ‘ps’}
Determines the order in which the parameters are printed out. If ‘none’ is given (default), no particular order is imposed. If ‘ps’, Python’s sorting routine is used to impose an order.
- Returns
- A list of strings containing the text.
- parameters()¶
Obtain parameter names and values.
- Returns
- Name-valuedict
A dictionary with the names and values of all parameters ({“parName”:value, …}).
- relate(dependentVar, independentVars, func=None, **kwargs)¶
Define a relation.
- Parameters
- dependentVarstring or tuple
The dependent variable given by string or specifier tuple.
- independentVarsstring or list of strings
The independent variables. You may also use specifier tuples to address the variables.
- funccallable
The functional form of the relation. Must take the independent variables as arguments and returns the value of the dependent variable. If None is given, equality will be assumed.
- removeConditionalRestriction(*args)¶
Remove an existing conditional constraint.
- Parameters
- idstring
The identifier used to refer to the conditional constraint (returned by addConditionalRestriction).
- renameVariable(oldName, newName)¶
Change name of variable.
- Parameters
- oldNamestring
Current variable name.
- newNamestring
New variable name.
Notes
Variable names and properties are not the same.
- restoreState(resource)¶
Restores parameter values from file or dictionary.
- Parameters
- resourcestring or dictionary
If string, it is interpreted as filename of a pickle file holding the data dictionary. If dictionary, it uses the data saved in it; note that a valid data dictionary is returned by saveState.
- saveState(*args, **kwargs)¶
Save the state of the fitting object.
This method collects the parameter values, the applied restrictions, and the information whether parameters are free or frozen and saves them to the specified file (if given) using pickle. The saved state can be restored using the restoreState method.
Note
Unfortunately, “relations” cannot be saved.
- Parameters
- fnstring, optional
The filename to which the state shall be written. If None, the output will not be written to a file.
- clobberboolean, optional
If True, existing files will be overwritten (default is False).
- Returns
- Saved datadict
The dictionary containing the data saved to the file.
- 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.
- setPenaltyFactor(penalFac)¶
Change the penalty factor.
- Parameters
- penalFacfloat
The penalty factor (default is 1e20).
Notes
May also be done by accessing the penalty property directly.
- setRestriction(restricts)¶
Define restrictions.
- Parameters
- restrictsdictionary
A dictionary associating a variable (given as string or specifier tuple) with a restriction of the form: [lower, upper]. Use “None” where no restrictions shall be applied.
- setRootName(root, rename=False)¶
Define the root name of the model.
- Parameters
- rootstring
A concise description of the model.
- renamebool, optional, default=False
If true, all model variables will be renaming using the root.
- showConditionalRestrictions(**kwargs)¶
Show conditional restrictions.
- Parameters
- toScreenboolean, optional
If True (default), the output is written to stdout.
- Returns
- Outputlist of strings
The output as a list of strings.
- 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.
- thaw(specifiers)¶
Consider variables fixed.
- Parameters
- specifierslist of strings or tuples
The names of the variables to be fixed. Either given as string or specifier tuple.
- untie(parName, forceFree=False)¶
Remove all relations of parameter parName, i.e., the parameter is not dependend on other parameters. The parameter parName is set to “freeze”.
- Parameters
- parNamestring
The name of the dependent variable which should become “unrelated”.
- forceFreeboolean
Set parName to “free” instead of “frozen” if set to True.
- updateModel()¶
Recalculate the model using current settings.
Notes
Updates the model attribute of the class by calling evaluate using the x attribute, which is, e.g., assigned on call to a fit method.
Variable naming¶
- class PyAstronomy.funcFit.ModelNameIdentBase(rootName='')¶
Managing the naming of model components.
This class handles the names of models or model components. Individual names or identifiers are composed of a “root name” and a “component counter”. The root name is supposed to be a concise string summarizing the type of model, while the component counter is used to distinguish between components with the same root name in composed models.
- Parameters
- rootNamestring, optional
A concise name for the model (default=””).
Notes
The term “specifier” is used to indicate either a string containing a variable name or a tuple composed of (property, root name, component counter), which specifies a variable. In some cases, parts of the specifier tuple may be left out.
Methods
composeVariableName
(property[, rootName, ...])Combine property, root name, and counter into a variable name.
convertSpecifier
(specifier)Decompose specifier and compose variable name.
decomposeVariableName
(name)Decomposes variable name into constituents.
getRoot
()Returns the root name.
Return the appropriate identifier.
setRootName
(root)Define the root used to build the identifier.
specifierToName
(input)Convert specifier(s) to variable names.
getComponentCounter
setComponentCounter
- composeVariableName(property, rootName=None, counter=None)¶
Combine property, root name, and counter into a variable name.
- Parameters
- propertystring
The property name.
- rootNamestring, optional,
A root name. If None, the instance’s own root name will be used.
- counterint, optional,
The component counter. If None, the instance’s counter will be used.
- Returns
- Variable namestring
The resulting variable name.
Notes
The standard way used to compose variable names is: “property_rootname(counter)”
- convertSpecifier(specifier)¶
Decompose specifier and compose variable name.
- Parameters
- specifierstring or tuple,
Either a string giving a variable name or a tuple specifying property, root name, and counter (the later two are optional).
- Returns
- Decomposed specifiertuple
A tuple of (variable name, property, root name, component counter).
- decomposeVariableName(name)¶
Decomposes variable name into constituents.
Expects a name of the from “property_root(c)” and returns the individual building blocks of the name, i.e., property, root name, component counter in that order. If one or more of these building blocks is not present, None will be returned instead.
- Parameters
- namestring
The variable name.
- getRoot()¶
Returns the root name.
- identifier()¶
Return the appropriate identifier.
- Returns
- identifierstring
Notes
The “identifier” reads “root-name(c)”, where the later part, “(c)”, will only be present if the componentCounter property is larger than zero; in this case, ‘c’ is that number.
- setRootName(root)¶
Define the root used to build the identifier.
- Parameters
- rootstring
Concise description of the model.
- specifierToName(input)¶
Convert specifier(s) to variable names.
- Returns
- outSame type as input,
Converts all specifiers to variable names. The output is the same type as the input.
Python decorators and MiniFunc¶
In the following, we give a brief introduction to Python decorators and outline the use of the MiniFunc decorator.
- Decorators in Python
Loosely speaking, decorators can be used to add or modify the functionality of a callable object such as a function. This can for example be useful if a whole set of function shares common functionality or if a certain fraction of the required functionality is to be ``hidden’’ from the user, as is the case here.
Applying a decorator, which is in Python marked by the ``@’’ sign, turns one callable object into another one. In our case, it will be necessary to have a decorator with arguments. A minimalistic example may look like this:
class Deco:
def __init__(self, argument):
self.argument = argument
def __call__(self, f):
print "Deco.__call__ is speaking!"
def newFunc(y):
print "First argument was: ", self.argument
print "But now I received: ", y
print "Evaluating function at given point: "
f(y)
return newFunc
def f1(x):
print "x**2 = ", x**2
@Deco(13)
def f2(x):
print "x**2 = ", x**2
print "-------------------------------"
f1(2)
print "-------------------------------"
f2(2)
Execution the above script results in the following output:
Deco.__call__ is speaking!
-------------------------------
x**2 = 4
-------------------------------
First argument was: 13
But now I received: 2
Evaluating function at given point:
x**2 = 4
What happens? At first sight, the functions f1 and f2 look exactly alike, yet the definition of f2 is preceded by the @Deco(13) directive; obviously, a call to f1 provides other output than a call of f2.
Above we defined a class called Deco. Instances of that class are callable objects, as they have a __call__ method. The @Deco(13) directive preceding f2 triggers the following process:
The constructor of Deco is called with a single argument (13),
The __call__ method of Deco is called with a single argument, which is a function pointer pointing at f2.
The __call__ method defines a new function, incorporating the functionality provided by f2, and returns it. This new function can combine the information given to the constructor and the arguments handed to the new function.
The whole process is, thus, replacing one callable object by another, possibly combining and extending the functionality.
- MiniFunc
The MiniFunc decorator can be used to apply user-defined minimization functions. In principle, such a function determines the quantity to be minimized (e.g., Chi square) for a given model and parameter vector. The implementation of the module requires to also carry out some other steps, which is done through the decorator, without making this visible for the user.
An example of a user defined objective function looks like:
gf = GaussFit1d()
@MiniObj(gf)
def mini(odf, P):
return sum(abs((odf.y - odf.model)/odf.yerr))
The first argument of the objective function is the fitting object, and the second is the parameter vector. Properties of the fitting objects such as x, y, or model may be accessed as usual. The return value is the quantity to be minimized.
Note
An example of the application of the decorator is given in the tutorial.
- class PyAstronomy.funcFit.MiniFunc(odf)¶
This decorator can be applied to use self-defined objective functions.
Applied to an objective function, it adds the functionality needed to evaluate the model given a certain parameter vector, so that the user does only have to take care about the quantity to be minimized.
- Parameters
- odffitting object
The fitting object that is supposed to use the self-defined objective function.
Methods
__call__
(f)Parameter:
- Parameter:
odf - An instance of a fitting objects such as for example GaussFit1d.
Methods
__call__
(f)Parameter: