Module Documentation¶
This page contains documentation to everything symfit
has to offer.
Fit¶

class
symfit.core.fit.
Fit
(model, *ordered_data, objective=None, minimizer=None, constraints=None, absolute_sigma=None, **named_data)[source]¶ Bases:
symfit.core.fit.HasCovarianceMatrix
Your one stop fitting solution! Based on the nature of the input, this object will attempt to select the right fitting type for your problem.
If you need very specific control over how the problem is solved, you can pass it the minimizer or objective function you would like to use.
Example usage:
a, b = parameters('a, b') x, y = variables('x, y') model = {y: a * x + b} # Fit will use its default settings fit = Fit(model, x=xdata, y=ydata) fit_result = fit.execute() # Use NelderMead instead fit = Fit(model, x=xdata, y=ydata, minimizer=NelderMead) fit_result = fit.execute() # Use NelderMead to get close, and BFGS to polish it off fit = Fit(model, x=xdata, y=ydata, minimizer=[NelderMead, BFGS]) fit_result = fit.execute(minimizer_kwargs=[dict(xatol=0.1), {}])

__init__
(model, *ordered_data, objective=None, minimizer=None, constraints=None, absolute_sigma=None, **named_data)[source]¶ Parameters:  model – (dict of) sympy expression(s) or
Model
object.  constraints – iterable of
Relation
objects to be used as constraints.  absolute_sigma (bool) – 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.
 objective – Have Fit use your specified objective. Can be one of the predefined symfit objectives or any callable which accepts fit parameters and returns a scalar.
 minimizer – Have Fit use your specified
symfit.core.minimizers.BaseMinimizer
. Can be aSequence
ofsymfit.core.minimizers.BaseMinimizer
.  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.
 model – (dict of) sympy expression(s) or


class
symfit.core.fit.
HasCovarianceMatrix
(model, *ordered_data, absolute_sigma=None, **named_data)[source]¶ Bases:
symfit.core.fit.TakesData
Mixin class for calculating the covariance matrix for any model that has a welldefined Jacobian \(J\). The covariance is then approximated as \(J^T W J\), where W contains the weights of each data point.
Supports vector valued models, but is unable to estimate covariances for those, just variances. Therefore, take the result with a grain of salt for vector models.

class
symfit.core.fit.
TakesData
(model, *ordered_data, absolute_sigma=None, **named_data)[source]¶ Bases:
object
An base class for everything that takes data. 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)[source]¶ Parameters:  model – (dict of) sympy expression or
Model
object.  absolute_sigma (bool) – 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.
 model – (dict of) sympy expression or

data_shapes
¶ Returns the shape of the data. In most cases this will be the same for all variables of the same type, if not this raises an Exception.
Ignores variables which are set to None by design so we know that those None variables can be assumed to have the same shape as the other in calculations where this is needed, such as the covariance matrix.
Returns: Tuple of all independent var shapes, dependent var shapes.

dependent_data
¶ Readonly Property
Returns: Data belonging to each dependent variable as a dict with variable names as key, data as value. Return type: collections.OrderedDict

independent_data
¶ Readonly Property
Returns: Data belonging to each independent variable as a dict with variable names as key, data as value. Return type: collections.OrderedDict

initial_guesses
¶ Returns: Initial guesses for every parameter.

sigma_data
¶ Readonly Property
Returns: Data belonging to each sigma variable as a dict with variable names as key, data as value. Return type: collections.OrderedDict

Models¶

class
symfit.core.models.
BaseCallableModel
(model)[source]¶ Bases:
symfit.core.models.BaseModel
Baseclass for callable models. A callable model is expected to have implemented a __call__ method which evaluates the model.

__call__
(*args, **kwargs)[source]¶ 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.


class
symfit.core.models.
BaseGradientModel
(model)[source]¶ Bases:
symfit.core.models.BaseCallableModel
Baseclass for models which have a gradient. Such models are expected to implement an eval_jacobian function.
Any subclass of this baseclass which does not implement its own eval_jacobian will inherit a finite difference gradient.

finite_difference
(*args, dx=1e08, **kwargs)[source]¶ Calculates a numerical approximation of the Jacobian of the model using the sixth order central finite difference method. Accepts a dx keyword to tune the relative stepsize used. Makes 6*n_params calls to the model.
Returns: A numerical approximation of the Jacobian of the model as a list with length n_components containing numpy arrays of shape (n_params, n_datapoints)


class
symfit.core.models.
BaseModel
(model)[source]¶ Bases:
collections.abc.Mapping
ABC for
Model
’s. Makes sure models are iterable. Models can be initiated from Mappings or Iterables of Expressions, or from an expression directly. Expressions are not enforced for ducktyping purposes.
__eq__
(other)[source]¶ Model
’s are considered equal when they have the same dependent variables, and the same expressions for those dependent variables. The same is defined here as passing sympy == for the vars themselves, and as expr1  expr2 == 0 for the expressions. For more info check the sympy docs.Parameters: other – Instance of Model
.Returns: bool

__getitem__
(var)[source]¶ Returns the expression belonging to a given dependent variable.
Parameters: var ( Variable
) – Instance ofVariable
Returns: The expression belonging to var

__init__
(model)[source]¶ Initiate a Model from a dict:
a = Model({y: x**2})
Preferred way of initiating
Model
, since now you know what the dependent variable is called.Parameters: model – dict of Expr
, where dependent variables are the keys.

__neg__
()[source]¶ Returns: new model with opposite sign. Does not change the model inplace, but returns a new copy.

classmethod
as_constraint
(constraint, model, constraint_type=None, **init_kwargs)[source]¶ Initiate a Model which should serve as a constraint. Such a constraintmodel should be initiated with knowledge of another
BaseModel
, from which it will take its parameters:model = Model({y: a * x + b}) constraint = Model.as_constraint(Eq(a, 1), model)
constraint.params
will be[a, b]
instead of[a]
.Parameters:  constraint – An
Expr
, a mapping or iterable ofExpr
, or aRelational
.  model – An instance of (a subclass of)
BaseModel
.  constraint_type – When
constraint
is not aRelational
, aRelational
has to be provided explicitly.  kwargs – Any additional keyword arguments which will be passed on to the init method.
 constraint – An

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

connectivity_mapping
¶ Returns: This property returns a mapping of the interdepencies between variables. This is essentially the dict representation of a connectivity graph, because working with this dict results in cleaner code. Treats variables and parameters on the same footing.

free_params
¶ Returns: ordered list of the subset of variable params

function_dict
¶ Equivalent to
self.model_dict
, but with all variables replaced by functions if applicable. Sorted by the evaluation order according toself.ordered_symbols
, not alphabetical likeself.model_dict
!

ordered_symbols
¶ Returns: list of all symbols in this model, topologically sorted so they can be evaluated in the correct order. Within each group of equal priority symbols, we sort by the order of the derivative.
Returns: bool, indicating if parameters are shared between the vector components of this model.

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

vars_as_functions
¶ Returns: Turn the keys of this model into Function
objects. This is done recursively so the chain rule can be applied correctly. This is done on the basis of connectivity_mapping.Example: for
{y: a * x, z: y**2 + a}
this returns{y: y(x, a), z: z(y(x, a), a)}
.

classmethod
with_dependencies
(model_expr, dependency_model, **init_kwargs)[source]¶ Initiate a model whose components depend on another model. For example:
>>> x, y, z = variables('x, y, z') >>> dependency_model = Model({y: x**2}) >>> model_dict = {z: y**2} >>> model = Model.with_dependencies(model_dict, dependency_model) >>> print(model) [y(x; ) = x**2, z(y; ) = y**2]
Parameters:  model_expr – The
Expr
or mapping/iterable ofExpr
to be turned into a model.  dependency_model – An instance of (a subclass of)
BaseModel
, which contains components on which the argumentmodel_expr
depends.  init_kwargs – Any kwargs to be passed on to the standard init method of this class.
Returns: A standalone
BaseModel
subclass. model_expr – The


class
symfit.core.models.
BaseNumericalModel
(model, independent_vars=None, params=None, *, connectivity_mapping=None, **kwargs)[source]¶ Bases:
symfit.core.models.BaseModel
ABC for Numerical Models. These are models whose components are generic python callables.

__eq__
(other)[source]¶ Model
’s are considered equal when they have the same dependent variables, and the same expressions for those dependent variables. The same is defined here as passing sympy == for the vars themselves, and as expr1  expr2 == 0 for the expressions. For more info check the sympy docs.Parameters: other – Instance of Model
.Returns: bool

__init__
(model, independent_vars=None, params=None, *, connectivity_mapping=None, **kwargs)[source]¶ Parameters:  model – dict of
callable
, where dependent variables are the keys. If instead of a dict a (sequence of)callable
is provided, it will be turned into a dict automatically.  independent_vars – The independent variables of the model.
(Deprecated, use
connectivity_mapping
instead.)  params – The parameters of the model.
(Deprecated, use
connectivity_mapping
instead.)  connectivity_mapping – Mapping indicating the dependencies of
every variable in the model. For example, a model_dict
{y: lambda x, a, b: a * x + b}
needs a connectivity_mapping{y: {x, a, b}}
. (Note that the values of this dict have to be sets.) This only has to be provided for the nonsymbolic components. The part corresponding to the symbolic components of the model is inferred automatically.
 model – dict of

__neg__
()[source]¶ Returns: new model with opposite sign. Does not change the model inplace, but returns a new copy.
BaseNumericalModel’s cannot infer if parameters are shared.


class
symfit.core.models.
CallableModel
(model)[source]¶ Bases:
symfit.core.models.BaseCallableModel
Defines a callable model. 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.

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

class
symfit.core.models.
CallableNumericalModel
(model, independent_vars=None, params=None, *, connectivity_mapping=None, **kwargs)[source]¶ Bases:
symfit.core.models.BaseCallableModel
,symfit.core.models.BaseNumericalModel
Callable model, whose components are callables provided by the user. This allows the user to provide the components directly.
Example:
x, y = variables('x, y') a, b = parameters('a, b') numerical_model = CallableNumericalModel( {y: lambda x, a, b: a * x + b}, connectivity_mapping={y: {x, a, b}} )
This is identical in functionality to the more traditional:
x, y = variables('x, y') a, b = parameters('a, b') model = CallableModel({y: a * x + b})
but allows powerusers a lot more freedom while still interacting seamlessly with the
symfit
API.When mixing symbolical and nonsymbolical components, the
connectivity_mapping
only has to be provided for the nonsymbolical components, the rest are inferred automatically:x, y, z = variables('x, y, z') a, b = parameters('a, b') model_dict = {z: lambda y, a, b: a * y + b, y: x ** a} mixed_model = CallableNumericalModel( model_dict, connectivity_mapping={z: {y, a, b}} )

class
symfit.core.models.
GradientModel
(*args, **kwargs)[source]¶ Bases:
symfit.core.models.CallableModel
,symfit.core.models.BaseGradientModel
Analytical model which has an analytically computed Jacobian.

__init__
(*args, **kwargs)[source]¶ Initiate a Model from a dict:
a = Model({y: x**2})
Preferred way of initiating
Model
, since now you know what the dependent variable is called.Parameters: model – dict of Expr
, where dependent variables are the keys.

jacobian
¶ Returns: Jacobian 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. The return shape is a list over the models components, filled with tha symbolical jacobian for that component, as a list.


class
symfit.core.models.
HessianModel
(*args, **kwargs)[source]¶ Bases:
symfit.core.models.GradientModel
Analytical model which has an analytically computed Hessian.

__init__
(*args, **kwargs)[source]¶ Initiate a Model from a dict:
a = Model({y: x**2})
Preferred way of initiating
Model
, since now you know what the dependent variable is called.Parameters: model – dict of Expr
, where dependent variables are the keys.

hessian
¶ Returns: Hessian filled with the symbolic expressions for all the second order partial derivatives. Partial derivatives are taken with respect to the Parameter’s, not the independent Variable’s.


class
symfit.core.models.
Model
(*args, **kwargs)[source]¶ Bases:
symfit.core.models.HessianModel
Model represents a symbolic function and all it’s derived properties such as sum of squares, jacobian etc. Models should be initiated from a dict:
a = Model({y: x**2})
Models are callable. The usual rules apply to the ordering of the arguments:
 first independent variables, then parameters.
 within each of these groups they are ordered alphabetically.
The output of a call to a model is a special kind of namedtuple:
>>> a(x=3) Ans(y=9)
When turning this into a dict, however, the dict keys will be Variable objects, not strings:
>>> a(x=3)._asdict() OrderedDict(((y, 9),))
Models are also iterable, behaving as their internal model_dict. For example,
a[y]
returnsx**2
,len(a) == 1
,y in a == True
, etc.

exception
symfit.core.models.
ModelError
[source]¶ Bases:
Exception
Raised when a problem occurs with a model.

class
symfit.core.models.
ModelOutput
(variables, output)[source]¶ Bases:
tuple
Object to hold the output of a model call. It mimics a
collections.namedtuple()
, but is initiated withVariable
objects instead of strings.Its information can be accessed using indexing or as attributes:
>>> x, y = variables('x, y') >>> a, b = parameters('a, b') >>> model = Model({y: a * x + b}) >>> ans = model(x=2, a=1, b=3) >>> print(ans) ModelOutput(variables=[y], output=[5]) >>> ans[0] 5 >>> ans.y 5

__init__
(variables, output)[source]¶ variables
andoutput
need to be in the same order!Parameters:  variables – The variables corresponding to
output
.  output – The output of a call which should be mapped to
variables
.
 variables – The variables corresponding to


class
symfit.core.models.
ODEModel
(model_dict, initial, *lsoda_args, **lsoda_kwargs)[source]¶ Bases:
symfit.core.models.BaseGradientModel
Model build from a system of ODEs. When the model is called, the ODE is integrated using the LSODA package.

__call__
(*args, **kwargs)[source]¶ 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 – Ordered arguments for the parameters and independent variables
 kwargs – Keyword arguments for the parameters and independent variables
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.

__getitem__
(dependent_var)[source]¶ Gives the function defined for the derivative of
dependent_var
. e.g. \(y' = f(y, t)\), model[y] > f(y, t)Parameters: dependent_var – Returns:

__init__
(model_dict, initial, *lsoda_args, **lsoda_kwargs)[source]¶ Parameters:  model_dict – Dictionary specifying ODEs. e.g. model_dict = {D(y, x): a * x**2}
 initial –
dict
of initial conditions for the ODE. Must be provided! e.g. initial = {y: 1.0, x: 0.0}  lsoda_args – args to pass to the lsoda solver. See scipy’s odeint for more info.
 lsoda_kwargs – kwargs to pass to the lsoda solver.


symfit.core.models.
hessian_from_model
(model)[source]¶ Build a
CallableModel
representing the Hessian ofmodel
.This function make sure the chain rule is correctly applied for interdependent variables.
Parameters: model – Any symbolical modeltype. Returns: CallableModel
representing the Hessian ofmodel
.

symfit.core.models.
jacobian_from_model
(model, as_functions=False)[source]¶  Build a
CallableModel
representing the Jacobian  of
model
.
This function make sure the chain rule is correctly applied for interdependent variables.
Parameters:  model – Any symbolical modeltype.
 as_functions – If True, the result is returned using
sympy.core.function.Function
where needed, e.g.{y(x, a): a * x}
instead of{y: a * x}
.
Returns: CallableModel
representing the Jacobian ofmodel
. Build a
Argument¶

class
symfit.core.argument.
Argument
(name=None, *args, **assumptions)[source]¶ Bases:
sympy.core.symbol.Symbol
Base class for
symfit
symbols. This helps makesymfit
symbols distinguishable fromsympy
symbols.If no name is explicitly provided a name will be generated.
For example:
y = Variable() print(y.name) >> 'x_0' y = Variable('y') print(y.name) >> 'y'

class
symfit.core.argument.
Parameter
(name=None, value=1.0, min=None, max=None, fixed=False, **assumptions)[source]¶ Bases:
symfit.core.argument.Argument
Parameter objects are used to facilitate bounds on function parameters. Important change from symfit>0.4.1: the name needs to be the first keyword, followed by the guess value. If no name is provided, the initial value can be passed as a keyword argument, e.g.: value=0.1. A generic name will then be generated.

__call__
(*values, **named_values)¶ Call an expression to evaluate it at the given point.
Future improvements: I would like if func and signature could be buffered after the first call so they don’t have to be recalculated for every call. However, nothing can be stored on self as sympy uses __slots__ for efficiency. This means there is no instance dict to put stuff in! And I’m pretty sure it’s ill advised to hack into the __slots__ of Expr.
However, for the moment I don’t really notice a performance penalty in running tests.
p.s. In the current setup signature is not even needed since no introspection is possible on the Expr before calling it anyway, which makes calculating the signature absolutely useless. However, I hope that someday some monkey patching expert in shining armour comes by and finds a way to store it in __signature__ upon __init__ of any
symfit
expr such that calling inspect_sig.signature on a symbolic expression will tell you which arguments to provide.Parameters:  self – Any subclass of sympy.Expr
 values – Values for the Parameters and Variables of the Expr.
 named_values – Values for the vars and params by name.
named_values
is allowed to contain too many values, as this sometimes happens when using **fit_result.params on a submodel. The irrelevant params are simply ignored.
Returns: The function evaluated at
values
. The type depends entirely on the input. Typically an array or a float but nothing is enforced.

__eq__
(other)[source]¶ Parameters are considered equal when their name, assumptions, and bounds are considered the same.

__hash__
() → int¶ Return hash(self).

__init__
(name=None, value=1.0, min=None, max=None, fixed=False, **assumptions)[source]¶ Parameters:  name – Name of the Parameter.
 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.  assumptions – assumptions to pass to
sympy
.


class
symfit.core.argument.
Variable
(name=None, *args, **assumptions)[source]¶ Bases:
symfit.core.argument.Argument
Variable type.
Operators¶
Monkey Patching module.
This module makes sympy
Expressions callable, which makes the whole project feel more consistent.

symfit.core.operators.
call
(self, *values, **named_values)[source]¶ Call an expression to evaluate it at the given point.
Future improvements: I would like if func and signature could be buffered after the first call so they don’t have to be recalculated for every call. However, nothing can be stored on self as sympy uses __slots__ for efficiency. This means there is no instance dict to put stuff in! And I’m pretty sure it’s ill advised to hack into the __slots__ of Expr.
However, for the moment I don’t really notice a performance penalty in running tests.
p.s. In the current setup signature is not even needed since no introspection is possible on the Expr before calling it anyway, which makes calculating the signature absolutely useless. However, I hope that someday some monkey patching expert in shining armour comes by and finds a way to store it in __signature__ upon __init__ of any
symfit
expr such that calling inspect_sig.signature on a symbolic expression will tell you which arguments to provide.Parameters:  self – Any subclass of sympy.Expr
 values – Values for the Parameters and Variables of the Expr.
 named_values – Values for the vars and params by name.
named_values
is allowed to contain too many values, as this sometimes happens when using **fit_result.params on a submodel. The irrelevant params are simply ignored.
Returns: The function evaluated at
values
. The type depends entirely on the input. Typically an array or a float but nothing is enforced.
Fit Results¶

class
symfit.core.fit_results.
FitResults
(model, popt, covariance_matrix, minimizer, objective, message, *, constraints=None, **minimizer_output)[source]¶ 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.  parameter values + stdev  R squared (Regression coefficient.) or other fit quality qualifiers.  fitting status message  covariance matrix  objective and minimizer used.
Contains the attribute params, which is an
OrderedDict
containing all the parameter names and their optimized values. Can be ** unpacked when evaluatingModel
’s.
__getattr__
(item)[source]¶ Return the requested item if it can be found in the gof_qualifiers dict.
Parameters: item – Name of Goodness of Fit qualifier. Returns: Goodness of Fit qualifier if present.

__init__
(model, popt, covariance_matrix, minimizer, objective, message, *, constraints=None, **minimizer_output)[source]¶ Parameters:  model –
Model
that was fit to.  popt – best fit parameters, same ordering as in model.params.
 covariance_matrix – covariance matrix.
 minimizer – Minimizer instance used.
 objective – Objective function which was optimized.
 message – Status message returned by the minimizer.
 **minimizer_output – Raw output as given by the minimizer.
 model –

covariance
(param_1, param_2)[source]¶ Return the covariance between param_1 and param_2.
Parameters:  param_1 –
Parameter
Instance.  param_2 –
Parameter
Instance.
Returns: Covariance of the two params.
 param_1 –

stdev
(param)[source]¶ Return the standard deviation in a given parameter as found by the fit.
Parameters: param – Parameter
Instance.Returns: Standard deviation of param
.

Minimizers¶

class
symfit.core.minimizers.
BFGS
(*args, **kwargs)[source]¶ Bases:
symfit.core.minimizers.ScipyGradientMinimize
Wrapper around
scipy.optimize.minimize()
’s BFGS algorithm.

class
symfit.core.minimizers.
BaseMinimizer
(objective, parameters)[source]¶ Bases:
object
ABC for all Minimizers.

__init__
(objective, parameters)[source]¶ Parameters:  objective – Objective function to be used.
 parameters – List of
Parameter
instances

execute
(**options)[source]¶ The execute method should implement the actual minimization procedure, and should return a
FitResults
instance.Parameters: options – options to be used by the minimization procedure. Returns: an instance of FitResults
.


class
symfit.core.minimizers.
BasinHopping
(*args, local_minimizer=<class 'symfit.core.minimizers.BFGS'>, **kwargs)[source]¶ Bases:
symfit.core.minimizers.ScipyMinimize
,symfit.core.minimizers.GlobalMinimizer
Wrapper around
scipy.optimize.basinhopping()
’s basinhopping algorithm.As always, the best way to use this algorithm is through
Fit
, as this will automatically select a local minimizer for you depending on whether you provided bounds, constraints, etc.However, BasinHopping can also be used directly. Example (with jacobian):
import numpy as np from symfit.core.minimizers import BFGS, BasinHopping from symfit import parameters def func2d(x1, x2): f = np.cos(14.5 * x1  0.3) + (x2 + 0.2) * x2 + (x1 + 0.2) * x1 return f def jac2d(x1, x2): df = np.zeros(2) df[0] = 14.5 * np.sin(14.5 * x1  0.3) + 2. * x1 + 0.2 df[1] = 2. * x2 + 0.2 return df x0 = [1.0, 1.0] np.random.seed(555) x1, x2 = parameters('x1, x2', value=x0) fit = BasinHopping(func2d, [x1, x2], local_minimizer=BFGS) minimizer_kwargs = {'jac': fit.list2kwargs(jac2d)} fit_result = fit.execute(niter=200, minimizer_kwargs=minimizer_kwargs)
See
scipy.optimize.basinhopping()
for more options.
__init__
(*args, local_minimizer=<class 'symfit.core.minimizers.BFGS'>, **kwargs)[source]¶ Parameters:  local_minimizer – minimizer to be used for local minimization
steps. Can be any subclass of
symfit.core.minimizers.ScipyMinimize
.  args – positional arguments to be passed on to super.
 kwargs – keyword arguments to be passed on to super.
 local_minimizer – minimizer to be used for local minimization
steps. Can be any subclass of

execute
(**minimize_options)[source]¶ Execute the basinhopping minimization.
Parameters: minimize_options – options to be passed on to scipy.optimize.basinhopping()
.Returns: symfit.core.fit_results.FitResults


class
symfit.core.minimizers.
BoundedMinimizer
(objective, parameters)[source]¶ Bases:
symfit.core.minimizers.BaseMinimizer
ABC for Minimizers that support bounds.

class
symfit.core.minimizers.
COBYLA
(*args, **kwargs)[source]¶ Bases:
symfit.core.minimizers.ScipyConstrainedMinimize
,symfit.core.minimizers.BaseMinimizer
Wrapper around
scipy.optimize.minimize()
’s COBYLA algorithm.
execute
(**minimize_options)[source]¶ Calls the wrapped algorithm.
Parameters:  bounds – The bounds for the parameters. Usually filled by
BoundedMinimizer
.  jacobian – The Jacobian. Usually filled by
ScipyGradientMinimize
.  **minimize_options – Further keywords to pass to
scipy.optimize.minimize()
. Note that your method will usually be filled by a specific subclass.
 bounds – The bounds for the parameters. Usually filled by


class
symfit.core.minimizers.
ChainedMinimizer
(*args, minimizers=None, **kwargs)[source]¶ Bases:
symfit.core.minimizers.BaseMinimizer
A minimizer that consists of multiple other minimizers, each executed in order. This is valuable if you have minimizers that are not good at finding the exact minimum such as
NelderMead
orDifferentialEvolution
.
__init__
(*args, minimizers=None, **kwargs)[source]¶ Parameters:  minimizers – a
Sequence
ofBaseMinimizer
objects, which need to be run in order.  *args – passed to
symfit.core.minimizers.BaseMinimizer.__init__()
.  **kwargs – passed to
symfit.core.minimizers.BaseMinimizer.__init__()
.
 minimizers – a

execute
(**minimizer_kwargs)[source]¶ Execute the chainedminimization. In order to pass options to the seperate minimizers, they can be passed by using the names of the minimizers as keywords. For example:
fit = Fit(self.model, self.xx, self.yy, self.ydata, minimizer=[DifferentialEvolution, BFGS]) fit_result = fit.execute( DifferentialEvolution={'seed': 0, 'tol': 1e4, 'maxiter': 10}, BFGS={'tol': 1e4} )
In case of multiple identical minimizers an index is added to each keyword argument to make them identifiable. For example, if:
minimizer=[BFGS, DifferentialEvolution, BFGS])
then the keyword arguments will be ‘BFGS’, ‘DifferentialEvolution’, and ‘BFGS_2’.
Parameters: minimizer_kwargs – Minimizer options to be passed to the minimzers by name Returns: an instance of FitResults
.


class
symfit.core.minimizers.
ConstrainedMinimizer
(*args, constraints=None, **kwargs)[source]¶ Bases:
symfit.core.minimizers.BaseMinimizer
ABC for Minimizers that support constraints

class
symfit.core.minimizers.
DifferentialEvolution
(*args, **kwargs)[source]¶ Bases:
symfit.core.minimizers.ScipyBoundedMinimizer
,symfit.core.minimizers.GlobalMinimizer
A wrapper around
scipy.optimize.differential_evolution()
.
execute
(*, strategy='rand1bin', popsize=40, mutation=(0.423, 1.053), recombination=0.95, polish=False, init='latinhypercube', **de_options)[source]¶ Calls the wrapped algorithm.
Parameters:  bounds – The bounds for the parameters. Usually filled by
BoundedMinimizer
.  jacobian – The Jacobian. Usually filled by
ScipyGradientMinimize
.  **minimize_options – Further keywords to pass to
scipy.optimize.minimize()
. Note that your method will usually be filled by a specific subclass.
 bounds – The bounds for the parameters. Usually filled by


class
symfit.core.minimizers.
DummyModel
(params)¶ Bases:
tuple

__getnewargs__
()¶ Return self as a plain tuple. Used by copy and pickle.

static
__new__
(_cls, params)¶ Create new instance of DummyModel(params,)

__repr__
()¶ Return a nicely formatted representation string

params
¶ Alias for field number 0


class
symfit.core.minimizers.
GlobalMinimizer
(*args, **kwargs)[source]¶ Bases:
symfit.core.minimizers.BaseMinimizer
A minimizer that looks for a global minimum, instead of a local one.

class
symfit.core.minimizers.
GradientMinimizer
(*args, jacobian=None, **kwargs)[source]¶ Bases:
symfit.core.minimizers.BaseMinimizer
ABC for Minizers that support the use of a jacobian

__init__
(*args, jacobian=None, **kwargs)[source]¶ Parameters:  objective – Objective function to be used.
 parameters – List of
Parameter
instances

resize_jac
(func)[source]¶ Removes values with identical indices to fixed parameters from the output of func. func has to return the jacobian of a scalar function.
Parameters: func – Jacobian function to be wrapped. Is assumed to be the jacobian of a scalar function. Returns: Jacobian corresponding to nonfixed parameters only.


class
symfit.core.minimizers.
HessianMinimizer
(*args, hessian=None, **kwargs)[source]¶ Bases:
symfit.core.minimizers.GradientMinimizer
ABC for Minimizers that support the use of a Hessian.

__init__
(*args, hessian=None, **kwargs)[source]¶ Parameters:  objective – Objective function to be used.
 parameters – List of
Parameter
instances

resize_hess
(func)[source]¶ Removes values with identical indices to fixed parameters from the output of func. func has to return the Hessian of a scalar function.
Parameters: func – Hessian function to be wrapped. Is assumed to be the Hessian of a scalar function. Returns: Hessian corresponding to free parameters only.


class
symfit.core.minimizers.
LBFGSB
(*args, **kwargs)[source]¶ Bases:
symfit.core.minimizers.ScipyGradientMinimize
,symfit.core.minimizers.ScipyBoundedMinimizer
Wrapper around
scipy.optimize.minimize()
’s LBFGSB algorithm.

class
symfit.core.minimizers.
MINPACK
(*args, **kwargs)[source]¶ Bases:
symfit.core.minimizers.ScipyBoundedMinimizer
,symfit.core.minimizers.GradientMinimizer
Wrapper to scipy’s implementation of least_squares, since it is the industry standard.

execute
(jacobian=None, method='trf', **minpack_options)[source]¶ Parameters: **minpack_options – Any named arguments to be passed to scipy.optimize.least_squares()

resize_jac
(func)[source]¶ Removes values with identical indices to fixed parameters from the output of func. func has to return the jacobian of the residuals. This method is different from the one in GradientMinimizer, since least_squares expects the jacobian to return an MxN (M=len(data), N=len(params)) matrix, rather than a vector.
Parameters: func – Jacobian function to be wrapped. Is assumed to be the jacobian of the residuals. Returns: Jacobian corresponding to nonfixed parameters only.


class
symfit.core.minimizers.
NelderMead
(*args, **kwargs)[source]¶ Bases:
symfit.core.minimizers.ScipyMinimize
,symfit.core.minimizers.BaseMinimizer
Wrapper around
scipy.optimize.minimize()
’s NelderMead algorithm.

class
symfit.core.minimizers.
Powell
(*args, **kwargs)[source]¶ Bases:
symfit.core.minimizers.ScipyMinimize
,symfit.core.minimizers.BaseMinimizer
Wrapper around
scipy.optimize.minimize()
’s Powell algorithm.

class
symfit.core.minimizers.
SLSQP
(*args, **kwargs)[source]¶ Bases:
symfit.core.minimizers.ScipyGradientMinimize
,symfit.core.minimizers.ScipyConstrainedMinimize
,symfit.core.minimizers.ScipyBoundedMinimizer
Wrapper around
scipy.optimize.minimize()
’s SLSQP algorithm.

class
symfit.core.minimizers.
ScipyBoundedMinimizer
(*args, **kwargs)[source]¶ Bases:
symfit.core.minimizers.ScipyMinimize
,symfit.core.minimizers.BoundedMinimizer
Base class for
scipy.optimize.minimize()
’s boundedminimizers.
execute
(**minimize_options)[source]¶ Calls the wrapped algorithm.
Parameters:  bounds – The bounds for the parameters. Usually filled by
BoundedMinimizer
.  jacobian – The Jacobian. Usually filled by
ScipyGradientMinimize
.  **minimize_options – Further keywords to pass to
scipy.optimize.minimize()
. Note that your method will usually be filled by a specific subclass.
 bounds – The bounds for the parameters. Usually filled by


class
symfit.core.minimizers.
ScipyConstrainedMinimize
(*args, **kwargs)[source]¶ Bases:
symfit.core.minimizers.ScipyMinimize
,symfit.core.minimizers.ConstrainedMinimizer
Base class for
scipy.optimize.minimize()
’s constrainedminimizers.
__init__
(*args, **kwargs)[source]¶ Parameters:  objective – Objective function to be used.
 parameters – List of
Parameter
instances

execute
(**minimize_options)[source]¶ Calls the wrapped algorithm.
Parameters:  bounds – The bounds for the parameters. Usually filled by
BoundedMinimizer
.  jacobian – The Jacobian. Usually filled by
ScipyGradientMinimize
.  **minimize_options – Further keywords to pass to
scipy.optimize.minimize()
. Note that your method will usually be filled by a specific subclass.
 bounds – The bounds for the parameters. Usually filled by

scipy_constraints
(constraints)[source]¶ Returns all constraints in a scipy compatible format.
Parameters: constraints – List of either MinimizeModel instances (this is what is provided by Fit
),BaseModel
, orsympy.core.relational.Relational
.Returns: dict of scipy compatible statements.


class
symfit.core.minimizers.
ScipyGradientMinimize
(*args, **kwargs)[source]¶ Bases:
symfit.core.minimizers.ScipyMinimize
,symfit.core.minimizers.GradientMinimizer
Base class for
scipy.optimize.minimize()
’s gradientminimizers.
execute
(*, jacobian=None, **minimize_options)[source]¶ Calls the wrapped algorithm.
Parameters:  bounds – The bounds for the parameters. Usually filled by
BoundedMinimizer
.  jacobian – The Jacobian. Usually filled by
ScipyGradientMinimize
.  **minimize_options – Further keywords to pass to
scipy.optimize.minimize()
. Note that your method will usually be filled by a specific subclass.
 bounds – The bounds for the parameters. Usually filled by


class
symfit.core.minimizers.
ScipyHessianMinimize
(*args, **kwargs)[source]¶ Bases:
symfit.core.minimizers.ScipyGradientMinimize
,symfit.core.minimizers.HessianMinimizer
Base class for
scipy.optimize.minimize()
’s hessianminimizers.
execute
(*, hessian=None, **minimize_options)[source]¶ Calls the wrapped algorithm.
Parameters:  bounds – The bounds for the parameters. Usually filled by
BoundedMinimizer
.  jacobian – The Jacobian. Usually filled by
ScipyGradientMinimize
.  **minimize_options – Further keywords to pass to
scipy.optimize.minimize()
. Note that your method will usually be filled by a specific subclass.
 bounds – The bounds for the parameters. Usually filled by


class
symfit.core.minimizers.
ScipyMinimize
(*args, **kwargs)[source]¶ Bases:
object
Mixin class that handles the execute calls to
scipy.optimize.minimize()
.
execute
(bounds=None, jacobian=None, hessian=None, constraints=None, *, tol=1e09, **minimize_options)[source]¶ Calls the wrapped algorithm.
Parameters:  bounds – The bounds for the parameters. Usually filled by
BoundedMinimizer
.  jacobian – The Jacobian. Usually filled by
ScipyGradientMinimize
.  **minimize_options – Further keywords to pass to
scipy.optimize.minimize()
. Note that your method will usually be filled by a specific subclass.
 bounds – The bounds for the parameters. Usually filled by


class
symfit.core.minimizers.
TrustConstr
(*args, **kwargs)[source]¶ Bases:
symfit.core.minimizers.ScipyHessianMinimize
,symfit.core.minimizers.ScipyConstrainedMinimize
,symfit.core.minimizers.ScipyBoundedMinimizer
Wrapper around
scipy.optimize.minimize()
’s TrustConstr algorithm.
execute
(*, jacobian=None, hessian=None, options=None, **minimize_options)[source]¶ Calls the wrapped algorithm.
Parameters:  bounds – The bounds for the parameters. Usually filled by
BoundedMinimizer
.  jacobian – The Jacobian. Usually filled by
ScipyGradientMinimize
.  **minimize_options – Further keywords to pass to
scipy.optimize.minimize()
. Note that your method will usually be filled by a specific subclass.
 bounds – The bounds for the parameters. Usually filled by

classmethod
method_name
()[source]¶ Returns the name of the minimize method this object represents. This is needed because the name of the object is not always exactly what needs to be passed on to scipy as a string. :return:

scipy_constraints
(constraints)[source]¶ Returns all constraints in a scipy compatible format.
Parameters: constraints – List of either MinimizeModel instances (this is what is provided by Fit
),BaseModel
, orsympy.core.relational.Relational
.Returns: dict of scipy compatible statements.

Objectives¶
Objective functions are the functions which are minimized by the
minimizers
.
Famous examples are least squares, loglikelihood, or minimizing the model
itself.
symfit
provides objective functions for those cases by default. Custom
objectives can also be created, for example by inheriting from
BaseObjective
,
GradientObjective
or
HessianObjective
.

class
symfit.core.objectives.
BaseIndependentObjective
(model, data)[source]¶ Bases:
symfit.core.objectives.BaseObjective
Some objective functions dependent only on independent variables, not dependent and sigma variables. In this case, sanity checking is greatly simplified.

dependent_data
¶ Returns: Empty OrderedDict. Return type: collections.OrderedDict

sigma_data
¶ Returns: Empty OrderedDict. Return type: collections.OrderedDict


class
symfit.core.objectives.
BaseObjective
(model, data)[source]¶ Bases:
object
ABC for objective functions. Implements basic data handling.

__call__
(ordered_parameters=[], **parameters)[source]¶ Evaluate the objective function for given parameter values.
Parameters:  ordered_parameters – List of parameter, in alphabetical order. Typically provided by the minimizer.
 parameters – parameters as keyword arguments.
Returns: evaluated model.

__eq__
(other)[source]¶ Objectives are considered equal if they are of the same type, have the same model, and the same data.

__init__
(model, data)[source]¶ Parameters:  model – symfit style model.
 data – data for all the variables of the model.

dependent_data
¶ Readonly Property
Returns: Data belonging to each dependent variable as a dict with variable names as key, data as value. Return type: collections.OrderedDict

independent_data
¶ Readonly Property
Returns: Data belonging to each independent variable as a dict with variable names as key, data as value. Return type: collections.OrderedDict

sigma_data
¶ Readonly Property
Returns: Data belonging to each sigma variable as a dict with variable names as key, data as value. Return type: collections.OrderedDict


class
symfit.core.objectives.
GradientObjective
(model, data)[source]¶ Bases:
symfit.core.objectives.BaseObjective
ABC for objectives that support gradient methods.

class
symfit.core.objectives.
HessianObjective
(model, data)[source]¶ Bases:
symfit.core.objectives.GradientObjective
ABC for objectives that support hessian methods.

class
symfit.core.objectives.
HessianObjectiveJacApprox
(model, data)[source]¶ Bases:
symfit.core.objectives.HessianObjective
This object should only be used as a Mixin for covariance matrix estimation. Since the covariance matrix for the leastsquares method is proportional to the Hessian of \(S\), this function attempts to return the Hessian upon calculating
eval_hessian
.However, if the model does not have a Hessian defined through
eval_hessian
, we approximate the Hessian as \(J^{T}\cdot J\), where \(J\) is the Jacobian of the model. This approximation is valid when, amongst other things, the residuals are sufficiently small. It can therefore only be used after fitting, not during.An objective which inherits from this object, will return zeros with the shape of the hessian of the model, when
eval_hessian
is called. This code injection will therefore result in the terms proportional to the hessian of the model dropping out, which leaves the famous \(J^{T}\cdot J\) approximation.

class
symfit.core.objectives.
LeastSquares
(model, data)[source]¶ Bases:
symfit.core.objectives.HessianObjective
Objective representing the leastsquares deviation of a model, defined as \(S = \frac{1}{2} \sum_{i} \sum_{x_i} \frac{r_i(x_i, \vec{p})^2}{\sigma_i(x_i)^2}\), where \(i\) ranges over all components of the model, \(r_i(x_i, \vec{p})\) is the residue of the \(i\)th component, \(x_i\) indicates all the data associated with the \(i\)th component, and \(\sigma_i(x_i)\) indicates the associated standard deviations.
The data for each component does not have to be the same, and it does not have to have the same shape. The only thing that matters is that within each component the shapes have to be compatible.

__call__
(ordered_parameters=[], *, flatten_components=True, **parameters)[source]¶ Parameters: Returns: scalar or list of scalars depending on the value of flatten_components.


class
symfit.core.objectives.
LogLikelihood
(model, data)[source]¶ Bases:
symfit.core.objectives.HessianObjective
,symfit.core.objectives.BaseIndependentObjective
Error function to be minimized by a minimizer in order to maximize the loglikelihood.

__call__
(ordered_parameters=[], **parameters)[source]¶ Parameters: parameters – values for the fit parameters. Returns: scalar value of loglikelihood

eval_hessian
(ordered_parameters=[], **parameters)[source]¶ Hessian for loglikelihood is defined as \(\nabla^2_{\vec{p}}( \log( L(\vec{p}  \vec{x})))\).
Parameters: parameters – values for the fit parameters. Returns: array of length number of Parameter
’s in the model, with all partial derivatives evaluated at p, data.

eval_jacobian
(ordered_parameters=[], *, apply_func=<function nansum>, **parameters)[source]¶ Jacobian for loglikelihood is defined as \(\nabla_{\vec{p}}( \log( L(\vec{p}  \vec{x})))\).
Parameters:  parameters – values for the fit parameters.
 apply_func – Function to apply to each component before returning it. The default is to sum away along the datapoint dimension using np.nansum.
Returns: array of length number of
Parameter
’s in the model, with all partial derivatives evaluated at p, data.


class
symfit.core.objectives.
MinimizeModel
(model, *args, **kwargs)[source]¶ Bases:
symfit.core.objectives.HessianObjective
,symfit.core.objectives.BaseIndependentObjective
Objective to use when the model itself is the quantity that should be minimized. This is only supported for scalar models.

__call__
(ordered_parameters=[], **parameters)[source]¶ Evaluate the objective function for given parameter values.
Parameters:  ordered_parameters – List of parameter, in alphabetical order. Typically provided by the minimizer.
 parameters – parameters as keyword arguments.
Returns: evaluated model.

__init__
(model, *args, **kwargs)[source]¶ Parameters:  model – symfit style model.
 data – data for all the variables of the model.


class
symfit.core.objectives.
VectorLeastSquares
(model, data)[source]¶ Bases:
symfit.core.objectives.GradientObjective
Implemented for MINPACK only. Returns the residuals/sigma before squaring and summing, rather then chi2 itself.

__call__
(ordered_parameters=[], *, flatten_components=True, **parameters)[source]¶ Returns the value of the square root of \(\chi^2\), summing over the components.
This function now supports setting variables to None.
Parameters: flatten_components – If True, summing is performed over the data indices (default). Returns: \(\sqrt(\chi^2)\)

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

class
symfit.core.support.
RequiredKeyword
[source]¶ Bases:
object
Flag variable to indicate that this is a required keyword.

exception
symfit.core.support.
RequiredKeywordError
[source]¶ Bases:
Exception
Error raised in case a keywordonly argument is not treated as such.

class
symfit.core.support.
cached_property
(*args, **kwargs)[source]¶ Bases:
property
A property which cashes the output of the first ever call and always returns that value from then on, unless delete is called on the attribute.
This is typically used in converting sympy code into scipy compatible code, which is computationally a very expensive step we would like to perform only once.
Does not allow setting of the attribute.

__delete__
(obj)[source]¶ Calling delete on the attribute will delete the cache. :param obj: parent object.

__get__
(obj, objtype=None)[source]¶ In case of a first call, this will call the decorated function and return it’s output. On every subsequent call, the same output will be returned.
Parameters:  obj – the parent object this property is attached to.
 objtype –
Returns: Output of the first call to the decorated function.


class
symfit.core.support.
deprecated
(replacement=None)[source]¶ Bases:
object
Decorator to raise a DeprecationWarning.

symfit.core.support.
jacobian
(expr, symbols)[source]¶ 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.
key2str
(target)[source]¶ In
symfit
there are many dicts with symbol: value pairs. These can not be used immediately as **kwargs, even though this would make a lot of sense from the context. This function wraps such dict to make them usable as **kwargs immediately.Parameters: target – Mapping to be made save Returns: Mapping of str(symbol): value pairs.

class
symfit.core.support.
keywordonly
(**kwonly_arguments)[source]¶ Bases:
object
Decorator class which wraps a python 2 function into one with keywordonly arguments.
Example:
@keywordonly(floor=True) def f(x, **kwargs): floor = kwargs.pop('floor') return np.floor(x**2) if floor else x**2
This decorator is not much more than:
floor = kwargs.pop('floor') if 'floor' in kwargs else True
However, I prefer it’s usage because:
 it’s clear from reading the function declaration there is an option to provide this argument. The information on possible keywords is where you’d expect it to be.
 you’re guaranteed that the pop works.
 It is fully inspect compatible such that sphynx is able to index these properly as keyword only arguments just like it would for native py3 keyword only arguments.
Please note that this decorator needs a ** argument on the wrapped function in order to work.

symfit.core.support.
name
(self)[source]¶ Save name which can be used for alphabetic sorting and can be turned into a kwarg.

symfit.core.support.
parameters
(names, **kwargs)[source]¶ Convenience function for the creation of multiple parameters. For more control, consider using
symbols(names, cls=Parameter, **kwargs)
directly.The Parameter attributes value, min, max and fixed can also be provided directly. If given as a single value, the same value will be set for all Parameter’s. When a sequence, it must be of the same length as the number of parameters created.
 Example::
 x1, x2 = parameters(‘x1, x2’, value=[2.0, 1.3], min=0.0)
Parameters:  names – string of parameter names. Example: a, b = parameters(‘a, b’)
 kwargs – kwargs to be passed onto
sympy.core.symbol.symbols()
. value, min and max will be handled separately if they are sequences.
Returns: iterable of
symfit.core.argument.Parameter
objects

symfit.core.support.
seperate_symbols
(func)[source]¶ 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, args)[source]¶ 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
 args – variables and parameters in this model
Returns: lambda function to be used for numerical evaluation of the model.

symfit.core.support.
sympy_to_scipy
(func, vars, params)[source]¶ Convert a symbolic expression to one scipy digs. Not used by
symfit
any more.Parameters:  func – sympy expression
 vars – variables
 params – parameters
Returns: Scipystyle function to be used for numerical evaluation of the model.

symfit.core.support.
variables
(names, **kwargs)[source]¶ Convenience function for the creation of multiple variables. For more control, consider using
symbols(names, cls=Variable, **kwargs)
directly.Parameters:  names – string of variable names. Example: x, y = variables(‘x, y’)
 kwargs – kwargs to be passed onto
sympy.core.symbol.symbols()
Returns: iterable of
symfit.core.argument.Variable
objects
Printing¶
symfit
occasionally updates the printing of sympy
objects, such that they
print into their numpy
/scipy
equivalent. This is done because sometimes
such printing has not been implemented in sympy
yet, or because we want
slightly different behavior from the standard one.
Users using both symfit
and sympy
should be aware of this.
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.
BivariateGaussian
(x, y, mu_x, mu_y, sig_x, sig_y, rho)[source]¶ 
Parameters:  x –
symfit.core.argument.Variable
 y –
symfit.core.argument.Variable
 mu_x –
symfit.core.argument.Parameter
for the mean of x  mu_y –
symfit.core.argument.Parameter
for the mean of y  sig_x –
symfit.core.argument.Parameter
for the standard deviation of x  sig_y –
symfit.core.argument.Parameter
for the standard deviation of y  rho –
symfit.core.argument.Parameter
for the correlation between x and y.
Returns: sympy expression for a Bivariate Gaussian pdf.
 x –
Contrib¶
Contrib modules are modules and extensions to symfit provided by other people. This usually means the code is of slightly less quality, and may not survive future versions.

class
symfit.contrib.interactive_guess.interactive_guess.
InteractiveGuess
(*args, n_points=50, log_contour=True, percentile=(5, 95), **kwargs)[source]¶ Bases:
symfit.core.fit.TakesData
A class that provides an graphical, interactive way of guessing initial fitting parameters.

__init__
(*args, n_points=50, log_contour=True, percentile=(5, 95), **kwargs)[source]¶ Create a matplotlib window with sliders for all parameters in this model, so that you may graphically guess initial fitting parameters. n_points is the number of points drawn for the plot. Data points are plotted as a blue contour plot, the proposed model as a red line. The errorbars on the proposed model represent the percentile of data within the thresholds.
Slider extremes are taken from the parameters where possible. If these are not provided, the minimum is 0; and the maximum is value*2. If no initial value is provided, it defaults to 1.
This will modify the values of the parameters present in model.
Parameters:  n_points (int) – The number of points used for drawing the fitted function. Defaults to 50.
 log_contour (bool) – Whether to plot the contour plot of the log of the density, rather than the density itself. If True, any density less than 1e7 will be considered 0. Defaults to True.
 percentile (list) – Controls the errorbars on the proposed model, such that the lower errorbar will cover percentile[0]% of the data, and the upper will cover percentile[1]%. Defaults to [5, 95], with corresponds to a 90% percentile. Should be a list of 2 numbers.


class
symfit.contrib.interactive_guess.interactive_guess.
InteractiveGuess2D
(*args, **kwargs)[source]¶ Bases:
symfit.contrib.interactive_guess.interactive_guess.InteractiveGuess

__init__
(*args, **kwargs)[source]¶ Create a matplotlib window with sliders for all parameters in this model, so that you may graphically guess initial fitting parameters. n_points is the number of points drawn for the plot. Data points are plotted as a blue contour plot, the proposed model as a red line. The errorbars on the proposed model represent the percentile of data within the thresholds.
Slider extremes are taken from the parameters where possible. If these are not provided, the minimum is 0; and the maximum is value*2. If no initial value is provided, it defaults to 1.
This will modify the values of the parameters present in model.
Parameters:  n_points (int) – The number of points used for drawing the fitted function. Defaults to 50.
 log_contour (bool) – Whether to plot the contour plot of the log of the density, rather than the density itself. If True, any density less than 1e7 will be considered 0. Defaults to True.
 percentile (list) – Controls the errorbars on the proposed model, such that the lower errorbar will cover percentile[0]% of the data, and the upper will cover percentile[1]%. Defaults to [5, 95], with corresponds to a 90% percentile. Should be a list of 2 numbers.


class
symfit.contrib.interactive_guess.interactive_guess.
Strategy2D
(interactive_guess)[source]¶ Bases:
object
A strategy that describes how to plot a model that depends on a single independent variable, and how to update that plot.

class
symfit.contrib.interactive_guess.interactive_guess.
StrategynD
(interactive_guess)[source]¶ Bases:
object
A strategy that describes how to plot a model that depends on a multiple independent variables, and how to update that plot.