Module Documentation — symfit 0.3.0 documentation

# Module Documentation

This page contains documentation to everything `symfit` has to offer.

## BaseFit

class `symfit.core.fit.` `BaseFit`(model, *ordered_data, absolute_sigma=None, **named_data)

  Bases: `object`

  Abstract Base Class for all fitting objects. Most importantly, it takes care of linking the provided data to variables. The allowed variables are extracted from the model.

  `__init__`(model, *ordered_data, absolute_sigma=None, **named_data)

    Parameters: | model – (dict of) sympy expression or `Model` object. bool (absolute_sigma) – True by default. If the sigma is only used for relative weights in your problem, you could consider setting it to False, but if your sigma are measurement errors, keep it at True. Note that curve_fit has this set to False by default, which is wrong in experimental science. ordered_data – data for dependent, independent and sigma variables. Assigned in the following order: independent vars are assigned first, then dependent vars, then sigma’s in dependent vars. Within each group they are assigned in alphabetical order. named_data – assign dependent, independent and sigma variables data by name.

    Standard deviation can be provided to any variable. They have to be prefixed with sigma_. For example, let x be a Variable. Then sigma_x will give the stdev in x.

  `__weakref__`

    list of weak references to the object (if defined)

  `dependent_data`

    Read-only Property

    Returns: | Data belonging to each dependent variable.
    Return type: | dict with variable names as key, data as value.

  `execute`(*args, **kwargs) → symfit.core.fit.FitResults

    Every fit object has to define an execute method. Any * and ** arguments will be passed to the fitting module that is being wrapped, e.g. leastsq.

    Args kwargs: |
    Returns: | Instance of FitResults

  `independent_data`

    Read-only Property

    Returns: | Data belonging to each independent variable.
    Return type: | dict with variable names as key, data as value.

  `initial_guesses`

    Returns: | Initial guesses for every parameter.

  `sigma_data`

    Read-only Property

    Returns: | Data belonging to each sigma variable.
    Return type: | dict with variable names as key, data as value.

## Fit

class `symfit.core.fit.` `BaseFit`(model, *ordered_data, absolute_sigma=None, **named_data)

  Bases: `object`

  Abstract Base Class for all fitting objects. Most importantly, it takes care of linking the provided data to variables. The allowed variables are extracted from the model.

  `__init__`(model, *ordered_data, absolute_sigma=None, **named_data)

    Parameters: | model – (dict of) sympy expression or `Model` object. bool (absolute_sigma) – True by default. If the sigma is only used for relative weights in your problem, you could consider setting it to False, but if your sigma are measurement errors, keep it at True. Note that curve_fit has this set to False by default, which is wrong in experimental science. ordered_data – data for dependent, independent and sigma variables. Assigned in the following order: independent vars are assigned first, then dependent vars, then sigma’s in dependent vars. Within each group they are assigned in alphabetical order. named_data – assign dependent, independent and sigma variables data by name.

    Standard deviation can be provided to any variable. They have to be prefixed with sigma_. For example, let x be a Variable. Then sigma_x will give the stdev in x.

  `__weakref__`

    list of weak references to the object (if defined)

  `dependent_data`

    Read-only Property

    Returns: | Data belonging to each dependent variable.
    Return type: | dict with variable names as key, data as value.

  `execute`(*args, **kwargs) → symfit.core.fit.FitResults

    Every fit object has to define an execute method. Any * and ** arguments will be passed to the fitting module that is being wrapped, e.g. leastsq.

    Args kwargs: |
    Returns: | Instance of FitResults

  `independent_data`

    Read-only Property

    Returns: | Data belonging to each independent variable.
    Return type: | dict with variable names as key, data as value.

  `initial_guesses`

    Returns: | Initial guesses for every parameter.

  `sigma_data`

    Read-only Property

    Returns: | Data belonging to each sigma variable.
    Return type: | dict with variable names as key, data as value.

class `symfit.core.fit.` `Constraint`(constraint: sympy.core.relational.Relational, model: symfit.core.fit.Model)

  Bases: `symfit.core.fit.Model`

  Constraints are a special type of model in that they have a type: >=, == etc. They are made to have lhs - rhs == 0 of the original expression.

  For example, Eq(y + x, 4) -> Eq(y + x - 4, 0)

  Since a constraint belongs to a certain model, it has to be initiated with knowledge of it’s parent model. This is important because all `numerical_` methods are done w.r.t. the parameters and variables of the parent model, not the constraint! This is because the constraint might not have all the parameter or variables that the model has, but in order to compute for example the Jacobian we still want to derive w.r.t. all the parameters, not just those present in the constraint.

  `__init__`(constraint: sympy.core.relational.Relational, model: symfit.core.fit.Model)

    Parameters: | constraint – constraint that model should be subjected to. model – A constraint is always tied to a model.
    Returns: |

  `constraint_type`

    alias of `Equality`

  `jacobian`

    Returns: | Jacobian ‘Matrix’ filled with the symbolic expressions for all the partial derivatives. Partial derivatives are of the components of the function with respect to the Parameter’s, not the independent Variable’s.

  `numerical_components`

    Returns: | lambda functions of each of the components in model_dict, to be used in numerical calculation.

  `numerical_jacobian`

    Returns: | lambda functions of the jacobian matrix of the function, which can be used in numerical optimization.

class `symfit.core.fit.` `Fit`(model, *ordered_data, absolute_sigma=None, **named_data)

  Bases: `symfit.core.fit.NumericalLeastSquares`

  Wrapper for NumericalLeastSquares to give it a more appealing name. In the future I hope to make this object more intelligent so it can search out the best fitting object based on certain qualifiers and return that instead.

class `symfit.core.fit.` `FitResults`(params, popt, pcov, infodic, mesg, ier, ydata=None, sigma=None)

  Bases: `object`

  Class to display the results of a fit in a nice and unambiguous way. All things related to the fit are available on this class, e.g. - parameters + stdev - R squared (Regression coefficient.) - fitting status message

  This object is made to behave entirely read-only. This is a bit unnatural to enforce in Python but I feel it is necessary to guarantee the integrity of the results.

  `__init__`(params, popt, pcov, infodic, mesg, ier, ydata=None, sigma=None)

    Excuse the ugly names of most of these variables, they are inherited. Should be changed. from scipy. :param params: list of `Parameter`‘s. :param popt: best fit parameters, same ordering as in params. :param pcov: covariance matrix. :param infodic: dict with fitting info. :param mesg: Status message. :param ier: Number of iterations. :param ydata:

  `__str__`()

    Pretty print the results as a table. :return:

  `__weakref__`

    list of weak references to the object (if defined)

  `infodict`

    Read-only Property.

  `iterations`

    Read-only Property.

  `params`

    Read-only Property.

  `r_squared`

    r_squared Property.

    Returns: | Regression coefficient.

  `status_message`

    Read-only Property.

class `symfit.core.fit.` `Likelihood`(model, *args, constraints=None, **kwargs)

  Bases: `symfit.core.fit.Maximize`

  Fit using a Maximum-Likelihood approach.

  `error_func`(p, data)

    Error function to be maximised(!) in the case of likelihood fitting.

    Parameters: | p – guess params data – xdata
    Returns: | scalar value of log-likelihood

  `eval_jacobian`(p, data)

    Jacobian for likelihood is defined as \(\nabla_{\vec{p}}( \log( L(\vec{p} | \vec{x})))\).

    Parameters: | p – guess params data – data for the variables.
    Returns: | array of length number of `Parameter`‘s in the model, with all partial derivatives evaluated at p, data.

class `symfit.core.fit.` `Maximize`(model, *args, constraints=None, **kwargs)

  Bases: `symfit.core.fit.Minimize`

  Maximize a model subject to constraints. Simply flips the sign on error_func and eval_jacobian in order to maximize.

class `symfit.core.fit.` `Minimize`(model, *args, constraints=None, **kwargs)

  Bases: `symfit.core.fit.BaseFit`

  Minimize a model subject to constraints. A wrapper for `scipy.optimize.minimize`. `Minimize` currently doesn’t work when data is provided to Variables, and doesn’t support vector functions.

  `__init__`(model, *args, constraints=None, **kwargs)

    Because in a lot of use cases for Minimize no data is supplied to variables, all the empty variables are replaced by an empty np array.

    Constraints: | constraints the minimization is subject to.

  `error_func`(p, data)

    The function to be optimized. Scalar valued models are assumed. For Minimize the thing to evaluate is simply self.model(*(list(data) + list(p)))

    Parameters: | p – array of floats for the parameters. data – data to be provided to `Variable`‘s.

  `eval_jacobian`(p, data)

    Takes partial derivatives of model w.r.t. each `Parameter`.

    Parameters: | p – array of floats for the parameters. data – data to be provided to `Variable`‘s.
    Returns: | array of length number of `Parameter`‘s in the model, with all partial derivatives evaluated at p, data.

  `scipy_constraints`

    Read-only Property of all constraints in a scipy compatible format.

    Returns: | dict of scipy compatible statements.

class `symfit.core.fit.` `Model`(*ordered_expressions, **named_expressions)

  Bases: `object`

  Model represents a symbolic function and all it’s derived properties such as sum of squares, jacobian etc. Models can be initiated from several objects:

      a = Model.from_dict({y: x**2})
      b = Model(y=x**2)

  Models are callable. The usual rules apply to the ordering of the arguments:

  - first independent variables, then dependent variables, then parameters.
  - within each of these groups they are ordered alphabetically.
  `__call__`(*args, **kwargs)

    Evaluate the model for a certain value of the independent vars and parameters. Signature for this function contains independent vars and parameters, NOT dependent and sigma vars.

    Can be called with both ordered and named parameters. Order is independent vars first, then parameters. Alphabetical order within each group.

    Parameters: | args – kwargs –
    Returns: | A namedtuple of all the dependent vars evaluated at the desired point. Will always return a tuple, even for scalar valued functions. This is done for consistency.

  `__init__`(*ordered_expressions, **named_expressions)

    Initiate a Model from keyword arguments:

        b = Model(y=x**2)

    Parameters: | ordered_expressions – sympy Expr named_expressions – sympy Expr

  `__str__`()

    Pretty print this model.

    Returns: | str

  `__weakref__`

    list of weak references to the object (if defined)

  `bounds`

    Returns: | List of tuples of all bounds on parameters.

  `chi`

    Returns: | Symbolic Square root of \(\chi^2\). Required for MINPACK optimization only. Denoted as \(\sqrt(\chi^2)\)

  `chi_jacobian`

    Return a symbolic jacobian of the \(\sqrt(\chi^2)\) function. Vector of derivatives w.r.t. each parameter. Not a Matrix but a vector! This is because that’s what leastsq needs.

  `chi_squared`

    Returns: | Symbolic \(\chi^2\)

  classmethod `from_dict`(model_dict)

    Initiate a Model from a dict:

        a = Model.from_dict({y: x**2})

    Prefered syntax.

    Parameters: | model_dict – dict of `Expr`, where dependent variables are the keys.

  `jacobian`

    Returns: | Jacobian ‘Matrix’ filled with the symbolic expressions for all the partial derivatives.

    Partial derivatives are of the components of the function with respect to the Parameter’s, not the independent Variable’s.

  `numerical_chi`

    Returns: | lambda function of the `.chi` method, to be used in MINPACK optimisation.

  `numerical_chi_jacobian`

    Returns: | lambda functions of the jacobian of the `.chi` method, which can be used in numerical optimization.

  `numerical_chi_squared`

    Returns: | lambda function of the `.chi_squared` method, to be used in numerical optimisation.

  `numerical_components`

    Returns: | lambda functions of each of the components in model_dict, to be used in numerical calculation.

  `numerical_jacobian`

    Returns: | lambda functions of the jacobian matrix of the function, which can be used in numerical optimization.

  `ss_res`

    Returns: | Residual sum of squares. Similar to chi_squared, but without considering weights.

  `vars`

    Returns: | Returns a list of dependent, independent and sigma variables, in that order.

class `symfit.core.fit.` `NumericalLeastSquares`(model, *ordered_data, absolute_sigma=None, **named_data)

  Bases: `symfit.core.fit.BaseFit`

  Solves least squares numerically using leastsqbounds. Gives results consistent with MINPACK except when borders are provided.

  `execute`(*options, **kwoptions) → symfit.core.fit.FitResults

    Parameters: | options – Any postional arguments to be passed to leastsqbound kwoptions – Any named arguments to be passed to leastsqbound

class `symfit.core.fit.` `ParameterDict`(params, popt, pcov, *args, **kwargs)

  Bases: `object`

  Container for all the parameters and their (co)variances. Behaves mostly like an OrderedDict: can be **-ed, allowing the sexy syntax where a model is called with values for the Variables and **params. However, under iteration it behaves like a list! In other words, it preserves order in the params.

  `__getattr__`(name)

    A user can access the value of a parameter directly through this object.

    Parameters: | name – Name of a `Parameter`. Naming convention: let a = Parameter(). Then: .a gives the value of the parameter. .a_stdev gives the standard deviation.

  `__getitem__`(param_name)

    This method allows this object to be addressed as a dict. This allows for the ** unpacking. Therefore return the value of the best fit parameter, as this is what the user expects.

    Parameters: | param_name – Name of the `Parameter` whose value your interested in.
    Returns: | the value of the best fit parameter with name ‘key’.

  `__iter__`()

    Iteration over the `Parameter` instances. :return: iterator

  `__len__`()

    Length gives the number of `Parameter` instances.

    Returns: | len(self.__params)

  `__weakref__`

    list of weak references to the object (if defined)

  `get_stdev`(param)

    Parameters: | param – `Parameter` instance.
    Returns: | returns the standard deviation of param

  `get_value`(param)

    Parameters: | param – `Parameter` instance.
    Returns: | returns the numerical value of param

  `keys`()

    Returns: | All `Parameter` names.

`symfit.core.fit.` `r_squared`(model: symfit.core.fit.Model, fit_result: symfit.core.fit.FitResults, data: collections.OrderedDict) → float

  Calculates the coefficient of determination, R^2, for the fit.

## Argument

class `symfit.core.argument.` `Argument`(name=None, *sympy_args, **sympy_kwargs)

  Bases: `sympy.core.symbol.Symbol`

  Base class for `symfit` symbols. This helps make `symfit` symbols distinguishable from `sympy` symbols.

  The `Argument` class also makes DRY possible in defining `Argument`‘s: it uses `inspect` to read the lhs of the assignment and uses that as the name for the `Argument` is none is explicitly set.

  For example:

      x = Variable()
      print(x.name)
      >> 'x'

  `__weakref__`

    list of weak references to the object (if defined)

class `symfit.core.argument.` `Parameter`(value=1.0, min=None, max=None, fixed=False, name=None, *sympy_args, **sympy_kwargs)

  Bases: `symfit.core.argument.Argument`

  Parameter objects are used to facilitate bounds on function parameters.

  `__call__`(**values)

    Parameters: | self – Any subclass of sympy.Expr values – Values for the Parameters and Variables of the Expr.
    Returns: | The function evaluated at `values`. Depending on the Expr and `values`, this could be a single number or an array.

  `__init__`(value=1.0, min=None, max=None, fixed=False, name=None, *sympy_args, **sympy_kwargs)

    Parameters: | value – Initial guess value. min – Lower bound on the parameter value. max – Upper bound on the parameter value. fixed (bool) – Fix the parameter to `value` during fitting. name – Name of the Parameter. sympy_args – Args to pass to `sympy`. sympy_kwargs – Kwargs to pass to `sympy`.

class `symfit.core.argument.` `Variable`(name=None, *sympy_args, **sympy_kwargs)

  Bases: `symfit.core.argument.Argument`

  Variable type.

## Operators

This module makes sympy Epressions callable, which makes the whole project feel more consistent.

`symfit.core.operators.` `call`(self, **values)

  Parameters: | self – Any subclass of sympy.Expr values – Values for the Parameters and Variables of the Expr.
  Returns: | The function evaluated at `values`. Depending on the Expr and `values`, this could be a single number or an array.

## Support

This module contains support functions and convenience methods used throughout symfit. Some are used predominantly internally, others are designed for users.

`symfit.core.support.` `cache`(func)

  Decorator function that gets a method as its input and either buffers the input, or returns the buffered output. Used in conjunction with properties to take away the standard buffering logic.

  Parameters: | func –
  Returns: |

`symfit.core.support.` `jacobian`(expr, symbols)

  Derive a symbolic expr w.r.t. each symbol in symbols. This returns a symbolic jacobian vector.

  Parameters: | expr – A sympy Expr. symbols – The symbols w.r.t. which to derive.

`symfit.core.support.` `parameters`(names)

  Convenience function for the creation of multiple parameters.

  Parameters: | names – string of parameter names. Should be comma seperated. Example: a, b = parameters(‘a, b’)

`symfit.core.support.` `seperate_symbols`(func)

  Seperate the symbols in symbolic function func. Return them in alphabetical order.

  Parameters: | func – scipy symbolic function.
  Returns: | (vars, params), a tuple of all variables and parameters, each sorted in alphabetical order.
  Raises TypeError:
  | only symfit Variable and Parameter are allowed, not sympy Symbols.

`symfit.core.support.` `sympy_to_py`(func, vars, params)

  Turn a symbolic expression into a Python lambda function, which has the names of the variables and parameters as it’s argument names.

  Parameters: | func – sympy expression vars – variables in this model params – parameters in this model
  Returns: | lambda function to be used for numerical evaluation of the model. Ordering of the arguments will be vars first, then params.

`symfit.core.support.` `sympy_to_scipy`(func, vars, params)

  Convert a symbolic expression to one scipy digs. Not used by `symfit` any more.

  Parameters: | func – sympy expression vars – variables params – parameters
  Returns: | Scipy-style function to be used for numerical evaluation of the model.

`symfit.core.support.` `variables`(names)

  Convenience function for the creation of multiple variables.

  Parameters: | names – string of variable names. Should be comma seperated. Example: x, y = variables(‘x, y’)

## Distributions

Some common distributions are defined in this module. That way, users can easily build more complicated expressions without making them look hard.

I have deliberately chosen to start these function with a capital, e.g. Gaussian instead of gaussian, because this makes the resulting expressions more readable.

`symfit.distributions.` `Exp`(x, l)

  Exponential Distribution pdf. :param x: free variable. :param l: rate parameter. :return: sympy.Expr for an Exponential Distribution pdf.

`symfit.distributions.` `Gaussian`(x, mu, sig)

  Gaussian pdf. :param x: free variable. :param mu: mean of the distribution. :param sig: standard deviation of the distribution. :return: sympy.Expr for a Gaussian pdf.