diffpy.srfit.fitbase package

The base fitting classes for diffpy.srfit.

This package contains modules and subpackages that are used to define a fit problem in SrFit. Unaltered, these classes will help set up a fit problem that can be optimized within a fitting framework or with a standalone optimizer. They provide the basic framework for defining a forward calculator, and from that defining a fit problem with data, constraints and restraints. The classes involved in this collaboration can be tied to a fitting framework at various levels through inheritance. One can create a fitting problem using the FitContribution, Profile and FitRecipe classes.

Various code and design taken from Paul Kienzle’s PARK package. http://www.reflectometry.org/danse/park.html

class diffpy.srfit.fitbase.Calculator(name)[source]

Bases: Operator, ParameterSet

Base class for calculators.

A Calculator organizes Parameters and has a __call__ method that can calculate a generic signal.

name

A name for this organizer.

meta

A dictionary of metadata needed by the calculator.

_calculators

A managed dictionary of Calculators, indexed by name.

_constraints

A set of constrained Parameters. Constraints can be added using the ‘constrain’ methods.

_parameters

A managed OrderedDict of contained Parameters.

_parsets

A managed dictionary of ParameterSets.

_restraints

A set of Restraints. Restraints can be added using the ‘restrain’ or ‘confine’ methods.

_eqfactory

A diffpy.srfit.equation.builder.EquationFactory instance that is used create Equations from string.

args

List of Literal arguments

nin

Number of inputs (<1 means this is variable)

nout

Number of outputs (1)

operation[source]

Function that performs the operation, self.__call__

symbol

Same as name

_value

The value of the Operator.

value

Property for ‘getValue’.

names

Variable names (read only). See get_names.

values

Variable values (read only). See get_values.

nin = -1
nout = 1
operation(*args)[source]

Calculate and cache the signal produced by this Calculator.

Parameters:

*args – The arguments needed to calculate the signal.

Returns:

The calculated signal.

Return type:

object

property symbol

Symbol representing the operator.

class diffpy.srfit.fitbase.FitContribution(name)[source]

Bases: ParameterSet

Organize an Equation, a Profile, and their supporting objects.

FitContributions organize an Equation that calculates the signal, and a Profile that holds the signal. ProfileGenerators and Calculators can be used as well. Constraints and Restraints can be created as part of a FitContribution.

name

A name for this FitContribution.

profile

A Profile that holds the measured (and calculated) signal.

_calculators

A managed dictionary of Calculators, indexed by name.

_constraints

A set of constrained Parameters. Constraints can be added using the constrain methods.

_generators

A managed dictionary of ProfileGenerators.

_parameters

A managed OrderedDict of parameters.

_restraints

A set of Restraints. Restraints can be added using the restrain method.

_parsets

A managed dictionary of ParameterSets.

_eqfactory

A diffpy.srfit.equation.builder.EquationFactory instance that is used to create constraints and restraints from string

_eq

The FitContribution equation that will be optimized.

_reseq

The residual equation.

_xname

Name of the x-variable

_yname

Name of the y-variable

_dyname

Name of the dy-variable

names

Variable names (read only). See get_names.

values

Variable values (read only). See get_values.

addProfileGenerator(gen, name=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitContribution.add_profile_generator instead.

add_profile_generator(gen, name=None)[source]

Add a ProfileGenerator to be used by this FitContribution.

The ProfileGenerator is given a name so that it can be used as part of the profile equation (see set_equation). This can be different from the name of the ProfileGenerator used for attribute access. FitContributions should not share ProfileGenerator instances. Different ProfileGenerators can share Parameters and ParameterSets, however.

Calling add_profile_generator sets the profile equation to call the calculator if there is not a profile equation already.

Parameters:
  • gen (ProfileGenerator) – The ProfileGenerator instance to add.

  • name (str, optional) – A name for the calculator. If name is None (default), then the ProfileGenerator’s name attribute will be used.

Raises:

ValueError – If the ProfileGenerator has no name, or if the ProfileGenerator has the same name as some other managed object.

evaluate()[source]

Evaluate the contribution equation and update profile.ycalc.

Returns:

The calculated signal.

Return type:

numpy.ndarray

getEquation()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitContribution.get_equation instead.

getResidualEquation()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitContribution.get_residual_equation instead.

get_equation()[source]

Get the math expression string for the active profile equation.

Returns:

The normalized math expression, or an empty string if the profile equation has not been set yet.

Return type:

str

get_residual_equation()[source]

Get the math expression string for the active residual equation.

Returns:

The normalized math formula, or an empty string if the residual equation has not been configured yet.

Return type:

str

residual()[source]

Calculate the residual for this FitContribution.

When this method is called, it is assumed that all parameters have been assigned their most current values by the FitRecipe. This will be the case when being called as part of a FitRecipe refinement.

The residual is by default an array chiv: chiv = (eq() - self.profile.y) / self.profile.dy. The value that is optimized is dot(chiv, chiv).

The residual equation can be changed with the set_residual_equation method.

Returns:

The array of residual values.

Return type:

numpy.ndarray

setEquation(eqstr, ns={})[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitContribution.set_equation instead.

setProfile(profile, xname=None, yname=None, dyname=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitContribution.set_profile instead.

setResidualEquation(eqstr)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitContribution.set_residual_equation instead.

set_equation(eqstr, ns={})[source]

Set the profile equation for the FitContribution.

This sets the equation that will be used when generating the residual for this FitContribution. The equation will be usable within set_residual_equation as "eq", and it takes no arguments.

Parameters:
  • eqstr (str) – A string representation of the equation. Any Parameter registered by addParameter or set_profile, or function registered by register_calculator, register_function or register_string_function can be used in the equation by name. Other names will be turned into Parameters of this FitContribution.

  • ns (dict, optional) – A dictionary of Parameters, indexed by name, that are used in the eqstr, but not registered (default {}).

Raises:

ValueError – If ns uses a name that is already used for a variable.

set_profile(profile, xname=None, yname=None, dyname=None)[source]

Assign the Profile for this FitContribution.

Parameters:
  • profile (Profile) – The Profile that specifies the calculation points and that will store the calculated signal.

  • xname (str, optional) – The name of the independent variable from the Profile. If this is None (default), then the name specified by the Profile for this parameter will be used. This variable is usable within string equations with the specified name.

  • yname (str, optional) – The name of the observed Profile. If this is None (default), then the name specified by the Profile for this parameter will be used. This variable is usable within string equations with the specified name.

  • dyname (str, optional) – The name of the uncertainty in the observed Profile. If this is None (default), then the name specified by the Profile for this parameter will be used. This variable is usable within string equations with the specified name.

set_residual_equation(eqstr)[source]

Set the residual equation for the FitContribution.

Two residuals are preset for convenience, "chiv" and "resv". chiv is defined such that dot(chiv, chiv) = chi^2. resv is defined such that dot(resv, resv) = Rw^2. You can call on these in your residual equation. Note that the quantity that will be optimized is the summed square of the residual equation. Keep that in mind when defining a new residual or using the built-in ones.

Parameters:

eqstr (str) – A string representation of the residual. If eqstr is None (default), then the previous residual equation will be used, or the chi2 residual will be used if that does not exist.

Raises:
  • SrFitError – If the Profile is not yet defined.

  • ValueError – If eqstr depends on a Parameter that is not part of the FitContribution.

class diffpy.srfit.fitbase.FitHook[source]

Bases: object

Base class for inspecting the progress of a FitRecipe refinement.

Can serve as a fithook for the FitRecipe class (see FitRecipe.push_fit_hook method.) The methods in this class are called during the preparation of the FitRecipe for refinement, and during the residual call. See the class methods for a description of their purpose.

postcall(recipe, chiv)[source]

This is called within FitRecipe.residual, after the calculation.

Parameters:
  • recipe (FitRecipe) – The FitRecipe instance.

  • chiv (ndarray) – The residual vector.

precall(recipe)[source]

This is called within FitRecipe.residual, before the calculation.

Parameters:

recipe (FitRecipe) – The FitRecipe instance.

reset(recipe)[source]

Reset the hook data.

This is called whenever FitRecipe._prepare is called, which is whenever a configurational change to the fit hierarchy takes place, such as adding a new ParameterSet, constraint or restraint.

class diffpy.srfit.fitbase.FitRecipe(name='fit')[source]

Bases: FitRecipeInterface, RecipeOrganizer

Organize FitContributions, variables, restraints, and constraints into a refinable recipe.

name

A name for this FitRecipe.

Type:

str

fithooks

The list of FitHook instances that can pass information out of the system during a refinement. By default, this is populated by a PrintFitHook instance.

Type:

list

_constraints

The dictionary of Constraints, indexed by the constrained Parameter. Constraints can be added using the add_constraint method.

Type:

dict

_oconstraints

The ordered list of the constraints from this and all sub-components.

Type:

list

_calculators

The managed dictionary of Calculators.

Type:

dict

_contributions

The managed OrderedDict of FitContributions.

Type:

OrderedDict

_parameters

The managed OrderedDict of parameters (in this case the parameters are varied).

Type:

OrderedDict

_parsets

The managed dictionary of ParameterSets.

Type:

dict

_eqfactory

The diffpy.srfit.equation.builder.EquationFactory instance that is used to create constraints and restraints from strings.

Type:

diffpy.srfit.equation.builder.EquationFactory

_restraintlist

The list of restraints from this and all sub-components.

Type:

list

_restraints

The set of Restraints. Restraints can be added using the ‘restrain’ or ‘confine’ methods.

Type:

set

_ready

The flag indicating if all attributes are ready for the calculation.

Type:

bool

_tagmanager

The TagManager instance for managing tags on Parameters.

Type:

TagManager

_weights

The list of weighing factors for each FitContribution. The weights are multiplied by the residual of the FitContribution when determining the overall residual.

Type:

list

_fixedtag

__fixed, used for tagging variables as fixed. Don’t use this tag unless you want issues.

Type:

str

names

The variable names (read only). See get_names.

Type:

list

values

The variable values (read only). See get_values.

Type:

numpy.ndarray

fixednames

The names of the fixed refinable variables (read only).

Type:

list

fixedvalues

The values of the fixed refinable variables (read only).

Type:

numpy.ndarray

bounds

The bounds on parameters (read only). See get_bounds_pairs.

Type:

list of tuple

bounds2

The bounds on parameters (read only). See get_bounds_array.

Type:

tuple of numpy.ndarray

addContribution(con, weight=1.0)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.add_contribution instead.

addParameterSet(parset)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.add_parameter_set instead.

addVar(par, value=None, name=None, fixed=False, tag=None, tags=[])[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.add_variable instead.

add_constraint(par, con, ns={})[source]

Constrain a parameter to an equation.

Note that only one constraint can exist on a Parameter at a time.

This is overloaded to set the value of con if it represents a variable and its current value is None. A constrained variable will be set as fixed.

Parameters:
  • par (Parameter) – The Parameter to constrain.

  • con (str or Parameter) – The string representation of the constraint equation or a Parameter to constrain to. A constraint equation must consist of numpy operators and “known” Parameters. Parameters are known if they are in the ns argument, or if they are managed by this object.

  • ns (dict, optional) – The dictionary of Parameters, indexed by name, that are used in the eqstr, but not part of this object (default {}).

Raises:
  • ValueError – If ns uses a name that is already used for a variable.

  • ValueError – If eqstr depends on a Parameter that is not part of the FitRecipe and that is not defined in ns.

  • ValueError – If par is marked as constant.

add_contribution(con, weight=1.0)[source]

Add a FitContribution to the FitRecipe.

Parameters:
  • con (FitContribution) – The FitContribution to be stored.

  • weight (float, optional) – The weight of the FitContribution. Default is 1.0.

Raises:

ValueError – If the FitContribution has no name or if the FitContribution has the same name as some other managed object.

add_parameter_set(parset)[source]

Add a ParameterSet to the hierarchy.

Parameters:

parset (ParameterSet) – The ParameterSet to be stored.

Raises:

ValueError – If the ParameterSet has no name or if the ParameterSet has the same name as some other managed object.

add_variable(par, value=None, name=None, fixed=False, tag=None, tags=[])[source]

Add a variable to be refined.

Parameters:
  • par (diffpy.srfit.fitbase.Parameter) – The Parameter that will be varied during a fit.

  • value (float or None, optional) – The initial value for the variable. If this is None (default), then the current value of par will be used.

  • name (str or None, optional) – The name for this variable. If name is None (default), then the name of the parameter will be used.

  • fixed (bool, optional) – Fix the variable so that it does not vary (default False).

  • tag (str or None, optional) – The tag for the variable. This can be used to retrieve, fix or free variables by tag (default None). Note that a variable is automatically tagged with its name and “all”.

  • tags (list of str, optional) – The list of tags (default []). Both tag and tags can be applied.

Returns:

The ParameterProxy (variable) for the passed Parameter.

Return type:

ParameterProxy

Raises:
  • ValueError – If the name of the variable is already taken by another managed object.

  • ValueError – If par is constant.

  • ValueError – If par is constrained.

property bounds
property bounds2
boundsToRestraints(sig=1, scaled=False)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.convert_bounds_to_restraints instead.

clearFitHooks()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.clear_fit_hooks instead.

clear_fit_hooks()[source]

Clear the FitHook sequence.

constrain(par, con, ns={})[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.add_constraint instead.

convert_bounds_to_restraints(sig=1, scaled=False)[source]

Turn all bounded parameters into restraints.

The bounds become limits on the restraint.

Parameters:
  • sig (float or iterable of float, optional) – The number of standard deviations associated with each bound. Smaller values produce stronger restraints. If a scalar is given, the same value is applied to all parameters. If an iterable is provided, it must match the number of parameters. Default is 1.

  • scaled (bool, optional) – If True, scale each restraint by the magnitude of the corresponding parameter, consistent with the behavior of restrain(). Default is False.

create_new_variable(name, value=None, fixed=False, tag=None, tags=[])[source]

Create a new variable of the fit.

This method lets new variables be created that are not tied to a Parameter. Orphan variables may cause a fit to fail, depending on the optimization routine, and therefore should only be created to be used in constraint or restraint equations.

Parameters:
  • name (str) – The name of the variable. The variable will be able to be used by this name in restraint and constraint equations.

  • value (float or None, optional) – The initial value for the variable. If this is None (default), then the variable will be given the value of the first non-None-valued Parameter constrained to it. If this fails, an error will be thrown when ‘residual’ is called.

  • fixed (bool, optional) – Fix the variable so that it does not vary (default False). The variable will still be managed by the FitRecipe.

  • tag (str or None, optional) – The tag for the variable. This can be used to fix and free variables by tag (default None). Note that a variable is automatically tagged with its name and “all”.

  • tags (list of str, optional) – The list of tags (default []). Both tag and tags can be applied.

Returns:

The new variable (Parameter instance).

Return type:

Parameter

delVar(var)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.delete_variable instead.

delete_variable(var)[source]

Remove a variable.

Note that constraints and restraints involving the variable are not modified.

Parameters:

var (ParameterProxy) – A variable of the FitRecipe.

Raises:

ValueError – If var is not part of the FitRecipe.

fix(*args, **kw)[source]

Fix one or more parameters by reference, name, or tag.

This method marks specified parameters as fixed, meaning they will not be refined during the fitting process. By default, all parameters are free (not fixed). Parameters can be specified using their references, names, or tags. Additionally, keyword arguments can be used to assign specific values to the fixed parameters.

Parameters:
  • *args (str or Parameter) – The positional arguments specifying the parameters to fix. These can be parameter objects, their names as strings, or tags. The special string “all” can be used to select all parameters.

  • **kw (dict) – The keyword arguments where the keys are parameter names and the values are the values to assign to the corresponding fixed parameters.

Raises:

ValueError – If an unknown parameter, name, or tag is passed, or if a tag is passed as a keyword argument.

Examples

# Fix a parameter by reference
recipe.fix(param1)

# Fix a parameter by name
recipe.fix("param2")

# Fix all parameters
recipe.fix("all")

# Fix parameters by tag
recipe.fix(tag="group1")

# Fix a parameter and assign it a value
recipe.fix(param3=10.0)
property fixednames

names of the fixed refinable variables

property fixedvalues

values of the fixed refinable variables

free(*args, **kw)[source]

Free one or more parameters by reference, name, or tag.

This method marks specified parameters as free, allowing them to be refined during the fitting process. By default, variables are free unless they are constrained. Constrained variables cannot be freed.

Parameters:
  • *args (str or Parameter) – The positional arguments specifying the parameters to free. These can be: - Parameter objects - Names of parameters (as strings) - Tags associated with parameters (as strings) - The string “all” to select all parameters.

  • **kw (dict) – The keyword arguments specifying parameter names as keys and their values to assign after freeing. This is useful for setting the value of a parameter while marking it as free.

Return type:

None

Raises:

ValueError – If an unknown parameter, name, or tag is passed, or if a tag is passed as a keyword argument.

Notes

  • Parameters that are already free will remain free.

  • Tags associated with fixed parameters will be removed when they are freed.

  • If keyword arguments are provided, the corresponding parameter values will be updated after freeing.

getBounds()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.get_bounds_pairs instead.

getBounds2()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.get_bounds_array instead.

getFitHooks()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.get_fit_hooks instead.

getNames()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.get_names instead.

getValues()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.get_values instead.

get_bounds_array()[source]

Get the bounds on variables in two numpy arrays.

Returns:

  • lower_bounds (numpy.ndarray) – The numpy array of lower bounds on the variables, in the same order as get_names and get_values.

  • upper_bounds (numpy.ndarray) – The numpy array of upper bounds on the variables, in the same order as get_names and get_values.

get_bounds_pairs()[source]

Get the bounds on variables in a list.

Returns:

bounds_pair_list – The list of (lower, upper) bounds on the variables, in the same order as get_names and get_values.

Return type:

list of tuple of float

get_fit_hooks()[source]

Get the sequence of FitHook instances.

Returns:

The list of FitHook instances registered with this FitRecipe.

Return type:

list

get_names()[source]

Retrieve the names of all free variables in the fit recipe.

This method iterates through the parameters in the fit recipe and returns a list of names for those variables that are marked as free.

Returns:

parameter_names – The list containing the names of free variables.

Return type:

list of str

get_values()[source]

Retrieve the current values of all free variables in the fit recipe.

This method collects the values of all parameters that are marked as free (i.e., adjustable during the fitting process) and returns them as a NumPy array.

Returns:

values_array – The array containing the current values of all free variables in the fit recipe.

Return type:

numpy.ndarray

initialize_recipe_with_recipe(recipe_object)[source]

Initialize a FitRecipe with another FitRecipe.

This is used to initialize a FitRecipe with the contribution(s), parameters, constraints and restraints of another FitRecipe. If a duplicate contribution, parameter, constraint, or restraint is added to the FitRecipe you are initializing, the value from the added object will be used.

Parameters:

recipe_object (FitRecipe) – The FitRecipe to initialize with.

Raises:

ValueError – If the object passed is not a FitRecipe.

initialize_recipe_with_results(results, verbose=True)[source]

Initialize a FitRecipe with a FitResults object or a results file.

Note that at least one FitContribution must already exist in the FitRecipe.

Parameters:
  • results (FitResults, pathlib.Path, or str) – The FitResults object or path to results file to initialize with.

  • verbose (bool, optional) – If True, print warnings for any parameters in the results that are not in the FitRecipe. Default is True.

Raises:

ValueError – If the input results is not a FitResults object or a path to a results file.

isFree(var)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.is_free instead.

is_free(var)[source]

Determine if a variable is free (not fixed) in the fit recipe.

This method checks whether the specified variable does not have the fixed tag associated with it, indicating that it is free to vary during the fitting process.

Parameters:

var (object) – The variable to check. This is typically an instance of a parameter or variable object used in the fit recipe.

Returns:

True if the variable is free (not fixed), False otherwise.

Return type:

bool

newVar(name, value=None, fixed=False, tag=None, tags=[])[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.create_new_variable instead.

plot_recipe(ax=None, return_fig=False, **kwargs)[source]

Plot the observed, fit, and difference curves for each contribution of the fit recipe.

If the recipe has multiple contributions, a separate plot is created for each contribution.

Parameters:
  • ax (matplotlib.axes.Axes or None, optional) – The axes object to plot on. If None, creates a new figure. Default is None.

  • return_fig (bool, optional) – The figure and axes objects are returned if True. Default is False.

  • **kwargs (dict) – Any plotting option can be passed to override the defaults in FitRecipe().plot_options. See the FitRecipe().set_plot_defaults() method for available keyword arguments.

Returns:

fig, axes – The figure and axes objects, returned only if return_fig=True. If the recipe has a single contribution, a single mpl.figure.Figure and mpl.axes.Axes are returned. If it has multiple contributions, a list of figures and a list of axes (one per contribution) are returned instead.

Return type:

tuple

Examples

Plot with default settings:

>>> recipe.plot_recipe()

Override defaults for one plot:

>>> recipe.plot_recipe(show_diff=False, title='My Custom Title')

Set defaults once, use everywhere:

>>> recipe.set_plot_defaults(xlabel='r (Å)', ylabel='G(r)')
>>> recipe.plot_recipe()  # Uses xlabel and ylabel
>>> recipe.plot_recipe()  # Still uses them

Override a default for one plot:

>>> recipe.set_plot_defaults(figsize=(10, 7))
>>> recipe.plot_recipe()  # Uses (10, 7)
>>> recipe.plot_recipe(figsize=(12, 8))  # Temporarily uses (12, 8)
>>> recipe.plot_recipe()  # Back to (10, 7)

Notes

The default values are taken from recipe.plot_options. You can modify these defaults in three ways:

1. Using set_plot_defaults(): recipe.set_plot_defaults(xlabel=’r (Å)’)

2. Direct attribute access: recipe.plot_options[‘xlabel’] = ‘r (Å)’

3. Using update(): recipe.plot_options.update({‘xlabel’: ‘r (Å)’, ‘ylabel’: ‘G(r)’})

popFitHook(fithook=None, index=-1)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.pop_fit_hook instead.

pop_fit_hook(fithook=None, index=-1)[source]

Remove a FitHook by index or reference.

Parameters:
  • fithook (diffpy.srfit.fitbase.fithook.FitHook or None, optional) – The FitHook instance to remove from the sequence. If this is None (default), default to index.

  • index (int, optional) – The index of FitHook instance to remove (default -1).

Raises:
  • ValueError – If fithook is not None, but is not present in the sequence.

  • IndexError – If the sequence is empty or index is out of range.

pushFitHook(fithook, index=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.push_fit_hook instead.

push_fit_hook(fithook, index=None)[source]

Add a FitHook to be called within the residual method.

The hook is an object for reporting updates, or more fundamentally, passing information out of the system during a refinement. See the diffpy.srfit.fitbase.fithook.FitHook class for the required interface. Added FitHooks will be called sequentially during refinement.

Parameters:
  • fithook (diffpy.srfit.fitbase.fithook.FitHook) – The FitHook instance to add to the sequence.

  • index (int or None, optional) – The index for inserting fithook into the list of fit hooks. If this is None (default), the fithook is added to the end.

removeParameterSet(parset)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.remove_parameter_set instead.

remove_constraint(*pars)[source]

Unconstrain a Parameter.

This removes any constraints on a Parameter. If the Parameter is also a variable of the recipe, it will be freed as well.

Parameters:

*pars (str or Parameter) – The names of Parameters or Parameter objects to unconstrain.

Raises:

ValueError – If the Parameter is not constrained.

remove_parameter_set(parset)[source]

Remove a ParameterSet from the hierarchy.

This method removes the specified ParameterSet object from the internal hierarchy of managed ParameterSets. If the provided ParameterSet is not currently managed by this object, a ValueError will be raised.

Parameters:

parset (ParameterSet) – The ParameterSet instance to be removed from the hierarchy.

Raises:

ValueError – If the provided ParameterSet is not managed by this object.

residual(p=[])[source]

Calculate the vector residual to be optimized.

The residual is by default the weighted concatenation of each FitContribution’s residual, plus the value of each restraint. The array returned, denoted chiv, is such that dot(chiv, chiv) = chi^2 + restraints.

Parameters:

p (list or numpy.ndarray) – The list of current variable values, provided in the same order as the _parameters list. If p is an empty iterable (default), then it is assumed that the parameters have already been updated in some other way, and the explicit update within this function is skipped.

Returns:

chiv – The array of residuals to be optimized. The array is such that dot(chiv, chiv) = chi^2 + restraints.

Return type:

numpy.ndarray

scalarResidual(p=[])[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.scalar_residual instead.

scalar_residual(p=[])[source]

Calculate the scalar residual to be optimized.

Parameters:

p (list or numpy.ndarray) – The list of current variable values, provided in the same order as the _parameters list. If p is an empty iterable (default), then it is assumed that the parameters have already been updated in some other way, and the explicit update within this function is skipped.

Returns:

The scalar residual, dot(chiv, chiv), where chiv is the vector residual returned by residual.

Return type:

float

Notes

The residual is by default the weighted concatenation of each FitContribution residual, plus the value of each restraint. The returned array, denoted chiv, is such that dot(chiv, chiv) = chi^2 + restraints.

setWeight(con, weight)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.set_weight instead.

set_plot_defaults(**kwargs)[source]

Set default plotting options for all future plots.

Any keyword argument accepted by plot_recipe() can be set here.

Parameters:
  • show_observed (bool, optional) – The observed data is plotted if True. Default is True.

  • show_fit (bool, optional) – The fit to the data is plotted if True. Default is True.

  • show_diff (bool, optional) – The difference curve (observed - calculated) is plotted if True. Default is True.

  • offset_scale (float, optional) – The scaling factor for the difference curve offset. The difference curve is offset below the data by (min_y - 0.1*range) * offset_scale. Default is 1.0.

  • xmin (float or None, optional) – The minimum x value to plot. If None, uses the minimum x value of the data. Default is None.

  • xmax (float or None, optional) – The maximum x value to plot. If None, uses the maximum x value of the data. Default is None.

  • figsize (tuple, optional) – The figure size as (width, height). Default is (8, 6).

  • data_style (str, optional) – The matplotlib line/marker style for data points. Default is “o”.

  • fit_style (str, optional) – The matplotlib line/marker style for the calculated fit. Default is “-“.

  • diff_style (str, optional) – The matplotlib line/marker style for the difference curve. Default is “-“.

  • data_color (str or None, optional) – The color for data plot. If None, uses default matplotlib colors.

  • fit_color (str or None, optional) – The color for the fit plot. If None, uses default matplotlib colors.

  • diff_color (str or None, optional) – The color for the difference plot. If None, uses default matplotlib colors.

  • data_label (str, optional) – The legend label for observed data. Default is “Observed”.

  • fit_label (str, optional) – The legend label for the calculated fit. Default is “Calculated”.

  • diff_label (str, optional) – The legend label for the difference curve. Default is “Difference”.

  • xlabel (str, optional) – The label for the x-axis.

  • ylabel (str, optional) – The label for the y-axis.

  • title (str or None, optional) – The plot title. If None (default), each figure created by plot_recipe is titled with the name of the contribution it shows. A title is not added to a user-supplied axes.

  • legend (bool, optional) – The legend is shown if True. Default is True.

  • legend_loc (str, optional) – The legend location. Default is “best”.

  • grid (bool, optional) – The grid is shown if True. Default is False.

  • markersize (float, optional) – The size of data point markers.

  • linewidth (float, optional) – The width of fit and difference lines.

  • alpha (float, optional) – The transparency of all plot elements (0=transparent, 1=opaque). Default is 1.0.

  • show (bool, optional) – The plot is displayed using plt.show() if True. Default is True.

Notes

The data_label, fit_label, diff_label and title options accept a {contribution} placeholder that is replaced by the name of the FitContribution being plotted, e.g. fit_label="{contribution} calculated". When several contributions are drawn on a shared axes, labels without the placeholder are prefixed with the contribution name so the legend entries stay distinguishable.

Examples

>>> recipe.set_plot_defaults(
        xlabel='r (Å)',
        ylabel='G(r) (Å⁻²)',
        data_color='black',
        fit_color='red'
    )
set_weight(con, weight)[source]

Set the weight of a FitContribution.

Parameters:
  • con (FitContribution) – The FitContribution object whose weight is to be set.

  • weight (float) – The weight value to assign to the specified FitContribution.

Return type:

None

unconstrain(*pars)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.remove_constraint instead.

class diffpy.srfit.fitbase.FitResults(recipe, update=True, showfixed=True, showcon=False)[source]

Bases: object

Class for processing, presenting and storing results of a fit.

recipe

The recipe from which the results were generated.

Type:

FitRecipe

cov

The covariance matrix of the refined variables. None if unavailable.

Type:

numpy.ndarray or None

conresults

The ordered mapping of FitContribution name → ContributionResults.

Type:

collections.OrderedDict[str, ContributionResults]

derivstep

The fractional step size used for numerical derivatives (default 1e-8).

Type:

float

varnames

The names of refined variables in the recipe.

Type:

list[str]

varvals

The optimized values of the refined variables.

Type:

numpy.ndarray

varunc

The estimated standard uncertainties of the variables. None if invalid.

Type:

numpy.ndarray or None

showfixed

The flag indicating whether to show the fixed variables in the formatted output (default True).

Type:

bool

fixednames

The names of variables held fixed during refinement.

Type:

list[str]

fixedvals

The values of the fixed variables.

Type:

numpy.ndarray

showcon

The flag indicating whether to show the constrained parameters in the formatted output (default False).

Type:

bool

connames

The names of constrained parameters.

Type:

list[str]

convals

The values of constrained parameters.

Type:

numpy.ndarray

conunc

The uncertainties of constrained parameters. None if unavailable.

Type:

numpy.ndarray or None

residual

The scalar residual value of the recipe.

Type:

float

penalty

The penalty contribution to the residual from restraints.

Type:

float

chi2

The chi-squared value of the fit.

Type:

float

cumchi2

The cumulative chi-squared as a function of data index.

Type:

numpy.ndarray

rchi2

The reduced chi-squared of the fit.

Type:

float

rw

The weighted R-factor of the fit.

Type:

float

cumrw

The cumulative weighted R-factor as a function of data index.

Type:

numpy.ndarray

messages

The informational or warning messages associated with the results.

Type:

list[str]

precision

The number of digits used when formatting numeric output (default 8).

Type:

int

_dcon

The jacobian of constraint equations with respect to variables. Used internally for uncertainty propagation.

Type:

numpy.ndarray

Each of these attributes, except the recipe, are created or updated when
the update method is called.
formatResults(header='', footer='', update=False)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitResults.get_results_string instead.

get_results_dictionary()[source]

Get a dictionary of results, with variable names and values, and overall metrics.

Returns:

results_dict – The dictionary containing the variable names and values, and overall metrics, from the FitResults.

Return type:

dict

get_results_string(header='', footer='', update=False)[source]

Format the results and return them in a string.

This function is called by print_results and save_results. Overloading the formatting here will change all three functions.

Parameters:
  • header (str) – The header to add to the output (default “”)

  • footer (str) – The footer to add to the output (default “”)

  • update (bool) – The flag indicating whether to call update() (default False).

Returns:

The string containing the formatted results.

Return type:

str

printResults(header='', footer='', update=False)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitResults.print_results instead.

print_results(header='', footer='', update=False)[source]

Format and print the results.

Parameters:
  • header (str) – The header to add to the output (default “”)

  • footer (str) – The footer to add to the output (default “”)

  • update (bool) – The flag indicating whether to call update() (default False).

saveResults(filename, header='', footer='', update=False)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitResults.save_results instead.

save_results(filename, header='', footer='', update=False)[source]

Format and save the results.

Parameters:
  • filename (str) – The name of the save file.

  • header (str) – The header to add to the output (default “”)

  • footer (str) – The footer to add to the output (default “”)

  • update (bool) – The flag indicating whether to call update() (default False).

update()[source]

Update the results according to the current state of the recipe.

class diffpy.srfit.fitbase.PlotFitHook[source]

Bases: FitHook

Live-plot the progress of a FitRecipe refinement.

postcall(recipe, chiv)[source]

This is called within FitRecipe.residual, after the calculation.

Find data and plot it.

Parameters:
  • recipe (FitRecipe) – The FitRecipe instance.

  • chiv (ndarray) – The residual vector.

reset(recipe)[source]

Set up the plot.

class diffpy.srfit.fitbase.Profile[source]

Bases: Observable, Validatable

Observed and calculated profile container.

Profile is an Observable. The xpar, ypar and dypar attributes are observed by the Profile, which can in turn be observed by some other object.

_xobs

A numpy array of the observed independent variable (default None)

xobs

Read-only property of _xobs.

_yobs

A numpy array of the observed signal (default None)

yobs

Read-only property of _yobs.

_dyobs

A numpy array of the uncertainty of the observed signal (default None, optional).

dyobs

Read-only property of _dyobs.

x

A numpy array of the calculated independent variable (default None, property for xpar accessors).

y

The profile over the calculation range (default None, property for ypar accessors).

dy

The uncertainty in the profile over the calculation range (default None, property for dypar accessors).

ycalc

A numpy array of the calculated signal (default None).

xpar

A Parameter that stores x (named “x”).

ypar

A Parameter that stores y (named “y”).

dypar

A Parameter that stores dy (named “dy”).

ycpar

A Parameter that stores ycalc (named “ycalc”). This is not observed by the profile, but it is present so it can be constrained to.

meta

A dictionary of metadata. This is only set if provided by a parser.

property dy
property dyobs
loadParsedData(parser)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.profile.Profile.load_parsed_data instead.

load_parsed_data(parser)[source]

Load parsed data from a ProfileParser.

This sets the xobs, yobs, dyobs arrays as well as the metadata.

Parameters:

parser (ProfileParser) – The parser holding the observed profile data and metadata.

loadtxt(*args, **kw)[source]

Load data using numpy.loadtxt.

Arguments are passed to numpy.loadtxt. unpack=True is enforced. The first two arrays returned by numpy.loadtxt are assumed to be x and y. If there is a third array, it is assumed to be dy. Any other arrays are ignored. The loaded arrays are passed to set_observed_profile.

Parameters:
  • *args – The positional arguments passed to numpy.loadtxt.

  • **kw – The keyword arguments passed to numpy.loadtxt.

Returns:

  • x (numpy.ndarray) – The array of the independent variable loaded from the file.

  • y (numpy.ndarray) – The array of the observed signal loaded from the file.

  • dy (numpy.ndarray or None) – The array of the uncertainty loaded from the file, or None if no third column is present.

Raises:

ValueError – If the call to numpy.loadtxt returns fewer than 2 arrays.

savetxt(fname, **kwargs)[source]

Call numpy.savetxt with x, ycalc, y, dy.

Parameters:
  • fname (filename or file handle) – The filename or file handle passed to numpy.savetxt.

  • **kwargs – The keyword arguments that are passed to numpy.savetxt. We preset file header “x ycalc y dy”. Use header='' to save data without any header.

Raises:

SrFitError – When self.ycalc has not been set.

See also

numpy.savetxt

setCalculationPoints(x)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.profile.Profile.set_calculation_points instead.

setCalculationRange(xmin=None, xmax=None, dx=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.profile.Profile.set_calculation_range instead.

setObservedProfile(xobs, yobs, dyobs=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.profile.Profile.set_observed_profile instead.

set_calculation_points(x)[source]

Set the calculation points.

This creates y and dy on the specified grid if xobs, yobs and dyobs exist.

Parameters:

x (numpy.ndarray) – The non-empty array of calculation points. If xobs exists, the bounds of x will be limited to its bounds.

set_calculation_range(xmin=None, xmax=None, dx=None)[source]

Set epsilon-inclusive calculation range.

Adhere to the observed xobs points when dx is the same as in the data. xmin and xmax are clipped at the bounds of the observed data.

Parameters:
  • xmin (float or "obs", optional) – The minimum value of the independent variable. Keep the current minimum when not specified. If specified as “obs” reset to the minimum observed value.

  • xmax (float or "obs", optional) – The maximum value of the independent variable. Keep the current maximum when not specified. If specified as “obs” reset to the maximum observed value.

  • dx (float or "obs", optional) – The sample spacing in the independent variable. When different from the data, resample the x as anchored at xmin.

  • clipped). (Note that xmin is always inclusive (unless)

  • data. (xmax is inclusive if it is within the bounds of the observed)

Raises:
  • AttributeError – If there is no observed data.

  • ValueError – When xmin > xmax or if dx <= 0. Also if dx > xmax - xmin.

set_observed_profile(xobs, yobs, dyobs=None)[source]

Set the observed profile.

Parameters:
  • xobs (numpy.ndarray) – The array of the independent variable.

  • yobs (numpy.ndarray) – The array of the observed signal.

  • dyobs (numpy.ndarray, optional) – The array of the uncertainty in the observed signal. If dyobs is None (default), dyobs stays None to indicate no uncertainty was observed, and the calculated dy will be set to 1 at each calculation point instead.

Raises:
  • ValueError – If len(yobs) != len(xobs).

  • ValueError – If dyobs is not None and len(dyobs) != len(xobs).

property x
property xobs
property y
property ycalc
property yobs
class diffpy.srfit.fitbase.ProfileGenerator(name)[source]

Bases: Operator, ParameterSet

Base class for profile generators.

A ProfileGenerator organizes Parameters and has a __call__ method that can generate a profile. ProfileGenerator is also an Operator (diffpy.srfit.equation.literals.operators), so it can be used directly in an evaluation network.

name

A name for this organizer.

profile

A Profile instance that contains the calculation range and will contain the generated profile.

meta

A dictionary of metadata needed by the generator.

eq

The Equation object used to wrap this ProfileGenerator. This is set when the ProfileGenerator is added to a FitContribution.

_calculators

A managed dictionary of Calculators, indexed by name.

_constraints

A set of constrained Parameters. Constraints can be added using the ‘constrain’ methods.

_parameters

A managed OrderedDict of contained Parameters.

_parsets

A managed dictionary of ParameterSets.

_restraints

A set of Restraints. Restraints can be added using the ‘restrain’ or ‘confine’ methods.

_eqfactory

A diffpy.srfit.equation.builder.EquationFactory instance that is used create Equations from string.

args

List of Literal arguments, set with ‘addLiteral’

name

A name for this operator. e.g. “add” or “sin”

nin

Number of inputs (<1 means this is variable)

nout

Number of outputs

operation[source]

Function that performs the operation. e.g. numpy.add. In this case, operation is an instance method.

symbol

The symbolic representation. e.g. “+” or “sin”

_value

The value of the Operator.

value

Property for ‘getValue’.

names

Variable names (read only). See get_names.

values

Variable values (read only). See get_values.

nin = 0
nout = 1
operation()[source]

Evaluate the profile.

Returns:

The result of __call__(profile.x).

Return type:

ndarray

set_profile(profile)[source]

Assign the profile.

Parameters:

profile (Profile) – The Profile that specifies the calculation points and which will store the calculated signal.

property symbol

Symbol representing the operator.

class diffpy.srfit.fitbase.ProfileParser[source]

Bases: object

Base class for parsing profile data from a file.

_format

The name of the data format that this parses (string, default ""). The format string is a unique identifier for the data format handled by the parser.

Type:

str, optional

_banks

The data from each bank. Each bank contains a (x, y, dx, dy) tuple: x : np.ndarray

The independent variable read from the file.

ynp.ndarray

The dependent variable (profile) read from the file.

dxnp.ndarray

The uncertainties associated with x read from the file. This is None if the uncertainty cannot be read.

dynp.ndarray

The uncertainties associated with y read from the file. This is None if the uncertainty cannot be read.

Type:

list of tuples

_x

Independent variable from the chosen bank

Type:

np.ndarray

_y

Profile from the chosen bank

Type:

np.ndarray

_dx

Uncertainty in independent variable from the chosen bank

Type:

np.ndarray

_dy

Uncertainty in profile from the chosen bank

Type:

np.ndarray

_meta

A dictionary containing metadata read from the file.

Type:

dict

General Metadata:
  • filename (str or Path) – The name of the file from which data was parsed. This key will not exist if data was not read from file.

  • nbanks (int) – The number of banks parsed.

  • bank (int) – The chosen bank number.

getData(index=None)[source]

This function is deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.ProfileParser.get_data instead.

getFormat()[source]

This function is deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.ProfileParser.get_format instead.

getMetaData()[source]

This function is deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.ProfileParser.get_metadata instead.

getNumBanks()[source]

This function is deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.ProfileParser.get_num_banks instead.

get_data(index=None)[source]

Get the data.

This method should only be called after the data has been parsed. The chosen bank number is not persistent, and so must be re-selected if the parser is used to parse more data. This uses python list notation, so index -n returns the nth bank from the end.

Parameters:

index (int, optional) – The index of the bank (integer, starting at 0, default None). If index is None then the currently selected bank is used.

Returns:

The (x, y, dx, dy) tuple for the bank. dx and dy are None if they cannot be determined from the data format.

Return type:

tuple

get_format()[source]

Get the format string.

Returns:

The unique identifier for the data format handled by this parser.

Return type:

str

get_metadata()[source]

Get the parsed metadata.

Returns:

A dictionary containing metadata read from the file.

Return type:

dict

get_num_banks()[source]

Get the number of banks read by the parser.

Returns:

The number of banks read by the parser.

Return type:

int

parseFile(filename)[source]

This function is deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.ProfileParser.parse_file instead.

parse_file(filename, column_format=None, metadata=None, **kwargs)[source]

Parse a data file to extract data and metadata, with automatic handling of uncertainties.

This is a template method. Subclasses customize a format by overriding the _parse_metadata and _parse_data hooks rather than this method.

The default _parse_data reads a single bank:

  • For files with 2 columns: assumes (x, y) and sets dx, dy to None.

  • For files with 3 columns: assumes (x, y, dy) and sets dx to None.

  • For files with 4 columns: assumes (x, y, dx, dy).

  • For other cases: column_format must be explicitly specified.

Uncertainty columns (dx, dy) are only considered valid if all values are positive and not NaN/Inf. Otherwise they are set to None.

This wipes out the currently loaded data and selected bank number.

Parameters:
  • filename (str or Path) – The name of the file to parse.

  • column_format (tuple of str, optional) –

    The order in which columns appear in the file. If None, the format is auto-detected based on the number of columns.

    Valid labels: "x", "y", "dx", "dy"

    Examples:

    • ("x", "y")

    • ("x", "y", "dy")

    • ("x", "y", "dx", "dy")

    • ("x", "dx", "y", "dy")

  • metadata (dict, optional) – Additional metadata to merge into the metadata parsed from the file. Keys must be strings. A key that collides with one already present in the parsed metadata overrides the parsed value. A key that collides with "filename", "bank", or "nbanks", which parse_file sets itself, also overrides the automatically set value, but raises a UserWarning since it may affect other code that relies on the automatically set value.

  • kwargs – The keyword arguments passed on to diffpy.utils.parsers.load_data, such as usecols, delimiter, comments and minrows. Use usecols to select four columns out of a wider file, then label them with column_format.

Raises:

ParseError – If parsing fails or ambiguity detected.

selectBank(index)[source]

This function is deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.ProfileParser.select_bank instead.

select_bank(index)[source]

Select which bank to use.

This method should only be called after the data has been parsed. The chosen bank number is not persistent, and so must be re-selected if the parser is used to parse more data. This uses python list notation, so index -n returns the nth bank from the end.

Parameters:

index (int) – The index of the bank (integer, starting at 0).

Raises:

IndexError – If requesting a bank that does not exist.

class diffpy.srfit.fitbase.SimpleRecipe(name='fit', conclass=<class 'diffpy.srfit.fitbase.fitcontribution.FitContribution'>)[source]

Bases: FitRecipe

FitRecipe with a built-in Profile and FitContribution.

This is a FitRecipe with a built-in Profile (the ‘profile’ attribute) and FitContribution (the ‘contribution’ attribute). Unique methods from each of these are exposed through this class to facilitate the creation of a simple fit recipe.

profile

The built-in Profile object.

contribution

The built-in FitContribution object.

results

The built-in FitResults object.

name

A name for this FitRecipe.

fithooks

The list of FitHook instances that can pass information out of the system during a refinement. By default, this is populated by a PrintFitHook instance.

Type:

list

_constraints

A dictionary of Constraints, indexed by the constrained Parameter. Constraints can be added using the ‘constrain’ method.

_oconstraints

An ordered list of the constraints from this and all sub-components.

_calculators

A managed dictionary of Calculators.

_contributions

A managed OrderedDict of FitContributions.

_parameters

A managed OrderedDict of parameters (in this case the parameters are varied).

_parsets

A managed dictionary of ParameterSets.

_eqfactory

A diffpy.srfit.equation.builder.EquationFactory instance that is used to create constraints and restraints from string equations.

_fixed

A set of parameters that are not actually varied.

_restraintlist

A list of restraints from this and all sub-components.

_restraints

A set of Restraints. Restraints can be added using the ‘restrain’ or ‘confine’ methods.

_ready

A flag indicating if all attributes are ready for the calculation.

_tagdict

A dictionary of tags to variables.

_weights

List of weighing factors for each FitContribution. The weights are multiplied by the residual of the FitContribution when determining the overall residual.

names

Variable names (read only). See get_names.

values

Variable values (read only). See get_values.

loadParsedData(parser)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.SimpleRecipe.load_parsed_data instead.

load_parsed_data(parser)[source]

Load parsed data from a ProfileParser.

This sets the xobs, yobs, dyobs arrays as well as the metadata.

Parameters:

parser (ProfileParser) – The ProfileParser to load data from.

loadtxt(*args, **kw)[source]

Use numpy.loadtxt to load data.

Arguments are passed to numpy.loadtxt. unpack = True is enforced. The first two arrays returned by numpy.loadtxt are assumed to be x and y. If there is a third array, it is assumed to by dy. Any other arrays are ignored. These are passed to set_observed_profile.

Raises:

ValueError – If the call to numpy.loadtxt returns fewer than 2 arrays.

Returns:

The x, y and dy arrays loaded from the file.

Return type:

tuple

printResults(header='', footer='')[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.SimpleRecipe.print_results instead.

print_results(header='', footer='')[source]

Format and print the results.

Parameters:
  • header (str, optional) – The header to add to the output (default “”).

  • footer (str, optional) – The footer to add to the output (default “”).

saveResults(filename, header='', footer='')[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.SimpleRecipe.save_results instead.

save_results(filename, header='', footer='')[source]

Format and save the results.

Parameters:
  • filename (str) – The name of the save file.

  • header (str, optional) – The header to add to the output (default “”).

  • footer (str, optional) – The footer to add to the output (default “”).

setCalculationPoints(x)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.SimpleRecipe.set_calculation_points instead.

setCalculationRange(xmin=None, xmax=None, dx=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.SimpleRecipe.set_calculation_range instead.

setEquation(eqstr, ns={})[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.SimpleRecipe.set_equation instead.

setObservedProfile(xobs, yobs, dyobs=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.SimpleRecipe.set_observed_profile instead.

set_calculation_points(x)[source]

Set the calculation points.

This will create y and dy on the specified grid if xobs, yobs and dyobs exist.

Parameters:

x (ndarray) – The non-empty array of calculation points. If xobs exists, the bounds of x will be limited to its bounds.

set_calculation_range(xmin=None, xmax=None, dx=None)[source]

Set epsilon-inclusive calculation range.

Adhere to the observed xobs points when dx is the same as in the data. xmin and xmax are clipped at the bounds of the observed data.

Parameters:
  • xmin (float or obs, optional) – The minimum value of the independent variable. Keep the current minimum when not specified. If specified as “obs” reset to the minimum observed value.

  • xmax (float or obs, optional) – The maximum value of the independent variable. Keep the current maximum when not specified. If specified as “obs” reset to the maximum observed value.

  • dx (float or obs, optional) – The sample spacing in the independent variable. When different from the data, resample the x as anchored at xmin.

  • clipped). (Note that xmin is always inclusive (unless)

  • data. (xmax is inclusive if it is within the bounds of the observed)

Raises:
  • AttributeError – If there is no observed data.

  • ValueError – When xmin > xmax or if dx <= 0. Also if dx > xmax - xmin.

set_equation(eqstr, ns={})[source]

Set the profile equation for the FitContribution.

This sets the equation that will be used when generating the residual. The equation will be usable within set_residual_equation as “eq”, and it takes no arguments.

Parameters:
  • eqstr (str) – The string representation of the equation. Variables will be extracted from this equation and be given an initial value of 0.

  • ns (dict, optional) – The dictionary of Parameters, indexed by name, that are used in the eqstr, but not registered (default {}).

Raises:

ValueError – If ns uses a name that is already used for a variable.

set_observed_profile(xobs, yobs, dyobs=None)[source]

Set the observed profile.

Parameters:
  • xobs (ndarray) – The independent variable.

  • yobs (ndarray) – The observed signal.

  • dyobs (ndarray, optional) – The uncertainty in the observed signal. If dyobs is None (default), it will be set to 1 at each observed xobs.

Raises:

ValueError – If len(yobs) != len(xobs), or if dyobs is not None and len(dyobs) != len(xobs).

diffpy.srfit.fitbase.initializeRecipe(recipe, results)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.initialize_recipe_with_results instead.

Initialize the variables of a recipe from a results file.

This reads the results from file and initializes any variables (fixed or free) in the recipe to the results values. Note that the recipe has to be configured, with variables. This does not reconstruct a FitRecipe.

Parameters:
  • recipe (FitRecipe) – The configured recipe with variables.

  • results (str or file-like) – The open file-like object, name of a file that contains results from FitResults, or a string containing fit results.

Raises:

AttributeError – If no results can be found in results.

Submodules

diffpy.srfit.fitbase.simplerecipe module

Simple FitRecipe class that includes a FitContribution and Profile.

class diffpy.srfit.fitbase.simplerecipe.SimpleRecipe(name='fit', conclass=<class 'diffpy.srfit.fitbase.fitcontribution.FitContribution'>)[source]

Bases: FitRecipe

FitRecipe with a built-in Profile and FitContribution.

This is a FitRecipe with a built-in Profile (the ‘profile’ attribute) and FitContribution (the ‘contribution’ attribute). Unique methods from each of these are exposed through this class to facilitate the creation of a simple fit recipe.

profile

The built-in Profile object.

contribution

The built-in FitContribution object.

results

The built-in FitResults object.

name

A name for this FitRecipe.

fithooks

The list of FitHook instances that can pass information out of the system during a refinement. By default, this is populated by a PrintFitHook instance.

Type:

list

_constraints

A dictionary of Constraints, indexed by the constrained Parameter. Constraints can be added using the ‘constrain’ method.

_oconstraints

An ordered list of the constraints from this and all sub-components.

_calculators

A managed dictionary of Calculators.

_contributions

A managed OrderedDict of FitContributions.

_parameters

A managed OrderedDict of parameters (in this case the parameters are varied).

_parsets

A managed dictionary of ParameterSets.

_eqfactory

A diffpy.srfit.equation.builder.EquationFactory instance that is used to create constraints and restraints from string equations.

_fixed

A set of parameters that are not actually varied.

_restraintlist

A list of restraints from this and all sub-components.

_restraints

A set of Restraints. Restraints can be added using the ‘restrain’ or ‘confine’ methods.

_ready

A flag indicating if all attributes are ready for the calculation.

_tagdict

A dictionary of tags to variables.

_weights

List of weighing factors for each FitContribution. The weights are multiplied by the residual of the FitContribution when determining the overall residual.

names

Variable names (read only). See get_names.

values

Variable values (read only). See get_values.

loadParsedData(parser)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.SimpleRecipe.load_parsed_data instead.

load_parsed_data(parser)[source]

Load parsed data from a ProfileParser.

This sets the xobs, yobs, dyobs arrays as well as the metadata.

Parameters:

parser (ProfileParser) – The ProfileParser to load data from.

loadtxt(*args, **kw)[source]

Use numpy.loadtxt to load data.

Arguments are passed to numpy.loadtxt. unpack = True is enforced. The first two arrays returned by numpy.loadtxt are assumed to be x and y. If there is a third array, it is assumed to by dy. Any other arrays are ignored. These are passed to set_observed_profile.

Raises:

ValueError – If the call to numpy.loadtxt returns fewer than 2 arrays.

Returns:

The x, y and dy arrays loaded from the file.

Return type:

tuple

printResults(header='', footer='')[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.SimpleRecipe.print_results instead.

print_results(header='', footer='')[source]

Format and print the results.

Parameters:
  • header (str, optional) – The header to add to the output (default “”).

  • footer (str, optional) – The footer to add to the output (default “”).

saveResults(filename, header='', footer='')[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.SimpleRecipe.save_results instead.

save_results(filename, header='', footer='')[source]

Format and save the results.

Parameters:
  • filename (str) – The name of the save file.

  • header (str, optional) – The header to add to the output (default “”).

  • footer (str, optional) – The footer to add to the output (default “”).

setCalculationPoints(x)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.SimpleRecipe.set_calculation_points instead.

setCalculationRange(xmin=None, xmax=None, dx=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.SimpleRecipe.set_calculation_range instead.

setEquation(eqstr, ns={})[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.SimpleRecipe.set_equation instead.

setObservedProfile(xobs, yobs, dyobs=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.SimpleRecipe.set_observed_profile instead.

set_calculation_points(x)[source]

Set the calculation points.

This will create y and dy on the specified grid if xobs, yobs and dyobs exist.

Parameters:

x (ndarray) – The non-empty array of calculation points. If xobs exists, the bounds of x will be limited to its bounds.

set_calculation_range(xmin=None, xmax=None, dx=None)[source]

Set epsilon-inclusive calculation range.

Adhere to the observed xobs points when dx is the same as in the data. xmin and xmax are clipped at the bounds of the observed data.

Parameters:
  • xmin (float or obs, optional) – The minimum value of the independent variable. Keep the current minimum when not specified. If specified as “obs” reset to the minimum observed value.

  • xmax (float or obs, optional) – The maximum value of the independent variable. Keep the current maximum when not specified. If specified as “obs” reset to the maximum observed value.

  • dx (float or obs, optional) – The sample spacing in the independent variable. When different from the data, resample the x as anchored at xmin.

  • clipped). (Note that xmin is always inclusive (unless)

  • data. (xmax is inclusive if it is within the bounds of the observed)

Raises:
  • AttributeError – If there is no observed data.

  • ValueError – When xmin > xmax or if dx <= 0. Also if dx > xmax - xmin.

set_equation(eqstr, ns={})[source]

Set the profile equation for the FitContribution.

This sets the equation that will be used when generating the residual. The equation will be usable within set_residual_equation as “eq”, and it takes no arguments.

Parameters:
  • eqstr (str) – The string representation of the equation. Variables will be extracted from this equation and be given an initial value of 0.

  • ns (dict, optional) – The dictionary of Parameters, indexed by name, that are used in the eqstr, but not registered (default {}).

Raises:

ValueError – If ns uses a name that is already used for a variable.

set_observed_profile(xobs, yobs, dyobs=None)[source]

Set the observed profile.

Parameters:
  • xobs (ndarray) – The independent variable.

  • yobs (ndarray) – The observed signal.

  • dyobs (ndarray, optional) – The uncertainty in the observed signal. If dyobs is None (default), it will be set to 1 at each observed xobs.

Raises:

ValueError – If len(yobs) != len(xobs), or if dyobs is not None and len(dyobs) != len(xobs).

diffpy.srfit.fitbase.constraint module

Constraint class.

Constraints are used by a FitRecipe (and other RecipeOrganizers) to organize constraint equations. They store a Parameter object and an Equation object that is used to compute its value. The Constraint.constrain method is used to create this association.

class diffpy.srfit.fitbase.constraint.Constraint[source]

Bases: Validatable

Associate a Parameter with an equation that determines its value.

Constraints are designed to be stored in only one place. (The holder of the constraint owns it).

par

The Parameter that is the subject of the constraint.

eq

The equation whose evaluation is used to set the value of the constraint.

add_constraint(par, eq)[source]

Constrain a Parameter according to an Equation.

The parameter will be set constant once it is constrained. This will keep it from being constrained multiple times.

Parameters:
  • par (Parameter) – The Parameter to constrain.

  • eq (Equation) – The Equation to use to constrain the Parameter.

Raises:

ValueError – If par is constant or already constrained.

constrain(par, eq)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.constraint.Constraint.add_constraint instead.

remove_constraint()[source]

Clear the constraint from a Parameter.

unconstrain()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.constraint.Constraint.remove_constraint instead.

update()[source]

Update the parameter according to the equation.

diffpy.srfit.fitbase.fithook module

The FitHook class for inspecting the progress of a FitRecipe refinement.

FitHooks are called by a FitRecipe during various times of the residual is evaluation. The default FitHook simply counts the number of times the residual is called, and reports that number every time the residual is calculated. Depending on the verbosity, it will also report the residual and the current variable values.

Custom FitHooks can be added to a FitRecipe with the FitRecipe.push_fit_hook method.

class diffpy.srfit.fitbase.fithook.FitHook[source]

Bases: object

Base class for inspecting the progress of a FitRecipe refinement.

Can serve as a fithook for the FitRecipe class (see FitRecipe.push_fit_hook method.) The methods in this class are called during the preparation of the FitRecipe for refinement, and during the residual call. See the class methods for a description of their purpose.

postcall(recipe, chiv)[source]

This is called within FitRecipe.residual, after the calculation.

Parameters:
  • recipe (FitRecipe) – The FitRecipe instance.

  • chiv (ndarray) – The residual vector.

precall(recipe)[source]

This is called within FitRecipe.residual, before the calculation.

Parameters:

recipe (FitRecipe) – The FitRecipe instance.

reset(recipe)[source]

Reset the hook data.

This is called whenever FitRecipe._prepare is called, which is whenever a configurational change to the fit hierarchy takes place, such as adding a new ParameterSet, constraint or restraint.

diffpy.srfit.fitbase.fitresults module

The FitResults and ContributionResults classes for storing results of a fit.

The FitResults class is used to display the current state of a FitRecipe. It stores the state, and uses it to calculate useful statistics, which can be displayed on screen or saved to file.

class diffpy.srfit.fitbase.fitresults.ContributionResults(con, weight, fitres)[source]

Bases: object

Class for processing, storing FitContribution results.

This does not store the FitContribution.

y

The FitContribution’s profile over the calculation range (default None).

Type:

numpy.ndarray or None

dy

The uncertainty in the FitContribution’s profile over the calculation range (default None).

Type:

numpy.ndarray or None

x

The numpy array of the calculated independent variable for the FitContribution (default None).

Type:

numpy.ndarray or None

ycalc

The numpy array of the calculated signal for the FitContribution (default None).

Type:

numpy.ndarray or None

residual

The scalar residual of the FitContribution.

Type:

float

chi2

The chi2 of the FitContribution.

Type:

float

cumchi2

The cumulative chi2 of the FitContribution.

Type:

numpy.ndarray

rw

The Rw of the FitContribution.

Type:

float

cumrw

The cumulative Rw of the FitContribution.

Type:

numpy.ndarray

weight

The weight of the FitContribution in the recipe.

Type:

float

conlocs

The location of the constrained parameters in the FitContribution (see the RecipeContainer._locate_managed_object method).

Type:

list

convals

The values of the constrained parameters.

Type:

list

conunc

The uncertainties in the constraint values.

Type:

list

class diffpy.srfit.fitbase.fitresults.FitResults(recipe, update=True, showfixed=True, showcon=False)[source]

Bases: object

Class for processing, presenting and storing results of a fit.

recipe

The recipe from which the results were generated.

Type:

FitRecipe

cov

The covariance matrix of the refined variables. None if unavailable.

Type:

numpy.ndarray or None

conresults

The ordered mapping of FitContribution name → ContributionResults.

Type:

collections.OrderedDict[str, ContributionResults]

derivstep

The fractional step size used for numerical derivatives (default 1e-8).

Type:

float

varnames

The names of refined variables in the recipe.

Type:

list[str]

varvals

The optimized values of the refined variables.

Type:

numpy.ndarray

varunc

The estimated standard uncertainties of the variables. None if invalid.

Type:

numpy.ndarray or None

showfixed

The flag indicating whether to show the fixed variables in the formatted output (default True).

Type:

bool

fixednames

The names of variables held fixed during refinement.

Type:

list[str]

fixedvals

The values of the fixed variables.

Type:

numpy.ndarray

showcon

The flag indicating whether to show the constrained parameters in the formatted output (default False).

Type:

bool

connames

The names of constrained parameters.

Type:

list[str]

convals

The values of constrained parameters.

Type:

numpy.ndarray

conunc

The uncertainties of constrained parameters. None if unavailable.

Type:

numpy.ndarray or None

residual

The scalar residual value of the recipe.

Type:

float

penalty

The penalty contribution to the residual from restraints.

Type:

float

chi2

The chi-squared value of the fit.

Type:

float

cumchi2

The cumulative chi-squared as a function of data index.

Type:

numpy.ndarray

rchi2

The reduced chi-squared of the fit.

Type:

float

rw

The weighted R-factor of the fit.

Type:

float

cumrw

The cumulative weighted R-factor as a function of data index.

Type:

numpy.ndarray

messages

The informational or warning messages associated with the results.

Type:

list[str]

precision

The number of digits used when formatting numeric output (default 8).

Type:

int

_dcon

The jacobian of constraint equations with respect to variables. Used internally for uncertainty propagation.

Type:

numpy.ndarray

Each of these attributes, except the recipe, are created or updated when
the update method is called.
formatResults(header='', footer='', update=False)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitResults.get_results_string instead.

get_results_dictionary()[source]

Get a dictionary of results, with variable names and values, and overall metrics.

Returns:

results_dict – The dictionary containing the variable names and values, and overall metrics, from the FitResults.

Return type:

dict

get_results_string(header='', footer='', update=False)[source]

Format the results and return them in a string.

This function is called by print_results and save_results. Overloading the formatting here will change all three functions.

Parameters:
  • header (str) – The header to add to the output (default “”)

  • footer (str) – The footer to add to the output (default “”)

  • update (bool) – The flag indicating whether to call update() (default False).

Returns:

The string containing the formatted results.

Return type:

str

printResults(header='', footer='', update=False)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitResults.print_results instead.

print_results(header='', footer='', update=False)[source]

Format and print the results.

Parameters:
  • header (str) – The header to add to the output (default “”)

  • footer (str) – The footer to add to the output (default “”)

  • update (bool) – The flag indicating whether to call update() (default False).

saveResults(filename, header='', footer='', update=False)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitResults.save_results instead.

save_results(filename, header='', footer='', update=False)[source]

Format and save the results.

Parameters:
  • filename (str) – The name of the save file.

  • header (str) – The header to add to the output (default “”)

  • footer (str) – The footer to add to the output (default “”)

  • update (bool) – The flag indicating whether to call update() (default False).

update()[source]

Update the results according to the current state of the recipe.

diffpy.srfit.fitbase.fitresults.initializeRecipe(recipe, results)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.initialize_recipe_with_results instead.

Initialize the variables of a recipe from a results file.

This reads the results from file and initializes any variables (fixed or free) in the recipe to the results values. Note that the recipe has to be configured, with variables. This does not reconstruct a FitRecipe.

Parameters:
  • recipe (FitRecipe) – The configured recipe with variables.

  • results (str or file-like) – The open file-like object, name of a file that contains results from FitResults, or a string containing fit results.

Raises:

AttributeError – If no results can be found in results.

diffpy.srfit.fitbase.profilegenerator module

The ProfileGenerator class for generating a profile.

ProfileGenerators encapsulate the evaluation and required Parameters and ParameterSets of a profile calculator. The ProfileGenerator class can be associated with a FitContribution to help calculate a profile.

To define a ProfileGenerator, one must implement the required Parameters and ParameterSets as well as overload the __call__ method with the calculation. A very simple example is

class Gaussian(ProfileGenerator):
    def __init__(self):
        # Initialize and give this a name
        ProfileGenerator.__init__(self, "g")
        # Add amplitude, center and width parameters
        self.newParameter("amp", 0)
        self.newParameter("center", 0)
        self.newParameter("width", 0)
    def __call__(self, x):
        a = self.amp.getValue()
        x0 = self.center.getValue()
        w = self.width.getValue()
        return a * exp(-0.5*((x-x0)/w)**2)

More examples can be found in the example directory of the documentation.

class diffpy.srfit.fitbase.profilegenerator.ProfileGenerator(name)[source]

Bases: Operator, ParameterSet

Base class for profile generators.

A ProfileGenerator organizes Parameters and has a __call__ method that can generate a profile. ProfileGenerator is also an Operator (diffpy.srfit.equation.literals.operators), so it can be used directly in an evaluation network.

name

A name for this organizer.

profile

A Profile instance that contains the calculation range and will contain the generated profile.

meta

A dictionary of metadata needed by the generator.

eq

The Equation object used to wrap this ProfileGenerator. This is set when the ProfileGenerator is added to a FitContribution.

_calculators

A managed dictionary of Calculators, indexed by name.

_constraints

A set of constrained Parameters. Constraints can be added using the ‘constrain’ methods.

_parameters

A managed OrderedDict of contained Parameters.

_parsets

A managed dictionary of ParameterSets.

_restraints

A set of Restraints. Restraints can be added using the ‘restrain’ or ‘confine’ methods.

_eqfactory

A diffpy.srfit.equation.builder.EquationFactory instance that is used create Equations from string.

args

List of Literal arguments, set with ‘addLiteral’

name

A name for this operator. e.g. “add” or “sin”

nin

Number of inputs (<1 means this is variable)

nout

Number of outputs

operation[source]

Function that performs the operation. e.g. numpy.add. In this case, operation is an instance method.

symbol

The symbolic representation. e.g. “+” or “sin”

_value

The value of the Operator.

value

Property for ‘getValue’.

names

Variable names (read only). See get_names.

values

Variable values (read only). See get_values.

nin = 0
nout = 1
operation()[source]

Evaluate the profile.

Returns:

The result of __call__(profile.x).

Return type:

ndarray

set_profile(profile)[source]

Assign the profile.

Parameters:

profile (Profile) – The Profile that specifies the calculation points and which will store the calculated signal.

property symbol

Symbol representing the operator.

diffpy.srfit.fitbase.validatable module

Validatable class.

A Validatable has state that must be validated before a FitRecipe can first calculate the residual.

class diffpy.srfit.fitbase.validatable.Validatable[source]

Bases: object

Base class for objects with state that must be validated.

A Validatable has state that must be validated by a FitRecipe.

diffpy.srfit.fitbase.configurable module

Configurable class.

A Configurable has state of which a FitRecipe must be aware.

class diffpy.srfit.fitbase.configurable.Configurable[source]

Bases: object

Base class for objects with state a FitRecipe must be aware of.

_configobjs

The set of Configurables in a hierarchy of instances. Messages get passed up the hierarchy to a FitRecipe via these objects.

diffpy.srfit.fitbase.profile module

The Profile class containing the physical and calculated data.

Profile holds the arrays representing an observed profile, a selected subset of the observed profile and a calculated profile. Profiles are used by Calculators to store a calculated signal, and by FitContributions to help calculate a residual equation.

class diffpy.srfit.fitbase.profile.Parameter(name, value=None, const=False)[source]

Bases: ParameterInterface, Argument, Validatable

Encapsulate an adjustable parameter within SrFit.

name

A name for this Parameter.

const

A flag indicating whether this is considered a constant.

_value

The value of the Parameter. Modified with set_value.

value

Property for getValue and set_value.

constrained

A flag indicating if the Parameter is constrained (default False).

bounds

A 2-list defining the bounds on the Parameter. This can be used by some optimizers when the Parameter is varied. See FitRecipe.get_bounds_pairs and FitRecipe.convert_bounds_to_restraints.

boundRange(lb=None, ub=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.Parameter.bound_range instead.

boundWindow(lr=0, ur=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.Parameter.bound_window instead.

bound_range(lower_bound=None, upper_bound=None)[source]

Set lower and upper bound of the Parameter.

Parameters:
  • lower_bound (float) – The lower bound for the bounds list.

  • upper_bound (float) – The upper bound for the bounds list.

Returns:

Return self so that mutators can be chained.

Return type:

Parameter

bound_window(lower_radius=0, upper_radius=None)[source]

Create bounds centered on the current value of the Parameter.

Parameters:
  • lower_radius (float, optional) – The radius of the lower bound (default 0). The lower bound is computed as value - lower_radius.

  • upper_radius (float, optional) – The radius of the upper bound. The upper bound is computed as value + upper_radius. If this is None (default), then the value of the lower radius is used.

Returns:

Return self so that mutators can be chained.

Return type:

Parameter

setConst(const=True, value=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.Parameter.set_constant instead.

setValue(val)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.Parameter.set_value instead.

set_constant(is_constant=True, value=None)[source]

Toggle the Parameter as constant.

Parameters:
  • is_constant (bool, optional) – The flag indicating if the parameter is constant (default True).

  • value (float, optional) – The value to set the parameter to (default None). If this is not None, then the parameter will get a new value, constant or otherwise.

Returns:

Return self so that mutators can be chained.

Return type:

Parameter

set_value(val)[source]

Set the value of the Parameter.

Parameters:

val (float) – The value to assign.

Returns:

Return self so that mutators can be chained.

Return type:

Parameter

class diffpy.srfit.fitbase.profile.Profile[source]

Bases: Observable, Validatable

Observed and calculated profile container.

Profile is an Observable. The xpar, ypar and dypar attributes are observed by the Profile, which can in turn be observed by some other object.

_xobs

A numpy array of the observed independent variable (default None)

xobs

Read-only property of _xobs.

_yobs

A numpy array of the observed signal (default None)

yobs

Read-only property of _yobs.

_dyobs

A numpy array of the uncertainty of the observed signal (default None, optional).

dyobs

Read-only property of _dyobs.

x

A numpy array of the calculated independent variable (default None, property for xpar accessors).

y

The profile over the calculation range (default None, property for ypar accessors).

dy

The uncertainty in the profile over the calculation range (default None, property for dypar accessors).

ycalc

A numpy array of the calculated signal (default None).

xpar

A Parameter that stores x (named “x”).

ypar

A Parameter that stores y (named “y”).

dypar

A Parameter that stores dy (named “dy”).

ycpar

A Parameter that stores ycalc (named “ycalc”). This is not observed by the profile, but it is present so it can be constrained to.

meta

A dictionary of metadata. This is only set if provided by a parser.

property dy
property dyobs
loadParsedData(parser)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.profile.Profile.load_parsed_data instead.

load_parsed_data(parser)[source]

Load parsed data from a ProfileParser.

This sets the xobs, yobs, dyobs arrays as well as the metadata.

Parameters:

parser (ProfileParser) – The parser holding the observed profile data and metadata.

loadtxt(*args, **kw)[source]

Load data using numpy.loadtxt.

Arguments are passed to numpy.loadtxt. unpack=True is enforced. The first two arrays returned by numpy.loadtxt are assumed to be x and y. If there is a third array, it is assumed to be dy. Any other arrays are ignored. The loaded arrays are passed to set_observed_profile.

Parameters:
  • *args – The positional arguments passed to numpy.loadtxt.

  • **kw – The keyword arguments passed to numpy.loadtxt.

Returns:

  • x (numpy.ndarray) – The array of the independent variable loaded from the file.

  • y (numpy.ndarray) – The array of the observed signal loaded from the file.

  • dy (numpy.ndarray or None) – The array of the uncertainty loaded from the file, or None if no third column is present.

Raises:

ValueError – If the call to numpy.loadtxt returns fewer than 2 arrays.

savetxt(fname, **kwargs)[source]

Call numpy.savetxt with x, ycalc, y, dy.

Parameters:
  • fname (filename or file handle) – The filename or file handle passed to numpy.savetxt.

  • **kwargs – The keyword arguments that are passed to numpy.savetxt. We preset file header “x ycalc y dy”. Use header='' to save data without any header.

Raises:

SrFitError – When self.ycalc has not been set.

See also

numpy.savetxt

setCalculationPoints(x)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.profile.Profile.set_calculation_points instead.

setCalculationRange(xmin=None, xmax=None, dx=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.profile.Profile.set_calculation_range instead.

setObservedProfile(xobs, yobs, dyobs=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.profile.Profile.set_observed_profile instead.

set_calculation_points(x)[source]

Set the calculation points.

This creates y and dy on the specified grid if xobs, yobs and dyobs exist.

Parameters:

x (numpy.ndarray) – The non-empty array of calculation points. If xobs exists, the bounds of x will be limited to its bounds.

set_calculation_range(xmin=None, xmax=None, dx=None)[source]

Set epsilon-inclusive calculation range.

Adhere to the observed xobs points when dx is the same as in the data. xmin and xmax are clipped at the bounds of the observed data.

Parameters:
  • xmin (float or "obs", optional) – The minimum value of the independent variable. Keep the current minimum when not specified. If specified as “obs” reset to the minimum observed value.

  • xmax (float or "obs", optional) – The maximum value of the independent variable. Keep the current maximum when not specified. If specified as “obs” reset to the maximum observed value.

  • dx (float or "obs", optional) – The sample spacing in the independent variable. When different from the data, resample the x as anchored at xmin.

  • clipped). (Note that xmin is always inclusive (unless)

  • data. (xmax is inclusive if it is within the bounds of the observed)

Raises:
  • AttributeError – If there is no observed data.

  • ValueError – When xmin > xmax or if dx <= 0. Also if dx > xmax - xmin.

set_observed_profile(xobs, yobs, dyobs=None)[source]

Set the observed profile.

Parameters:
  • xobs (numpy.ndarray) – The array of the independent variable.

  • yobs (numpy.ndarray) – The array of the observed signal.

  • dyobs (numpy.ndarray, optional) – The array of the uncertainty in the observed signal. If dyobs is None (default), dyobs stays None to indicate no uncertainty was observed, and the calculated dy will be set to 1 at each calculation point instead.

Raises:
  • ValueError – If len(yobs) != len(xobs).

  • ValueError – If dyobs is not None and len(dyobs) != len(xobs).

property x
property xobs
property y
property ycalc
property yobs

diffpy.srfit.fitbase.restraint module

Restraints class.

Restraints are used by RecipeOrganizers to organize restraint equations. Restraints store an Equation, bounds on its value, and the form of the penalty function for breaking a restraint. This penalty is added to the residual equation calculated by a FitRecipe.

class diffpy.srfit.fitbase.restraint.Restraint(eq, lower_bound=-inf, upper_bound=inf, sig=1, scaled=False)[source]

Bases: Validatable

Restrain an equation to specified bounds.

The penalty for breaking the restraint is calculated as (max(0, lower_bound - val, val - upper_bound) / sig) ** 2, where val is the value of the calculated equation. This is multiplied by the average chi^2 if scaled is True.

eq

The equation whose evaluation is compared against the restraint bounds.

Type:

Equation

lower_bound

The lower bound on the restraint evaluation (default -inf).

Type:

float

upper_bound

The upper bound on the restraint evaluation (default inf).

Type:

float

sig

The uncertainty on the bounds (default 1).

Type:

float

scaled

A flag indicating if the restraint is scaled (multiplied) by the unrestrained point-average chi^2 (chi^2/numpoints) (default False).

Type:

bool

penalty(w=1.0)[source]

Calculate the penalty of the restraint.

Parameters:

w (float, optional) – The point-average chi^2 which is optionally used to scale the penalty (default 1.0).

Returns:

The penalty for breaking the restraint.

Return type:

float

diffpy.srfit.fitbase.fitcontribution module

FitContribution class.

FitContributions generate a residual function for a FitRecipe. A FitContribution associates an Equation for generating a signal, optionally one or more ProfileGenerators or Calculators that help in this, and a Profile that holds the observed and calculated signals.

See the examples in the documentation for how to use a FitContribution.

class diffpy.srfit.fitbase.fitcontribution.FitContribution(name)[source]

Bases: ParameterSet

Organize an Equation, a Profile, and their supporting objects.

FitContributions organize an Equation that calculates the signal, and a Profile that holds the signal. ProfileGenerators and Calculators can be used as well. Constraints and Restraints can be created as part of a FitContribution.

name

A name for this FitContribution.

profile

A Profile that holds the measured (and calculated) signal.

_calculators

A managed dictionary of Calculators, indexed by name.

_constraints

A set of constrained Parameters. Constraints can be added using the constrain methods.

_generators

A managed dictionary of ProfileGenerators.

_parameters

A managed OrderedDict of parameters.

_restraints

A set of Restraints. Restraints can be added using the restrain method.

_parsets

A managed dictionary of ParameterSets.

_eqfactory

A diffpy.srfit.equation.builder.EquationFactory instance that is used to create constraints and restraints from string

_eq

The FitContribution equation that will be optimized.

_reseq

The residual equation.

_xname

Name of the x-variable

_yname

Name of the y-variable

_dyname

Name of the dy-variable

names

Variable names (read only). See get_names.

values

Variable values (read only). See get_values.

addProfileGenerator(gen, name=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitContribution.add_profile_generator instead.

add_profile_generator(gen, name=None)[source]

Add a ProfileGenerator to be used by this FitContribution.

The ProfileGenerator is given a name so that it can be used as part of the profile equation (see set_equation). This can be different from the name of the ProfileGenerator used for attribute access. FitContributions should not share ProfileGenerator instances. Different ProfileGenerators can share Parameters and ParameterSets, however.

Calling add_profile_generator sets the profile equation to call the calculator if there is not a profile equation already.

Parameters:
  • gen (ProfileGenerator) – The ProfileGenerator instance to add.

  • name (str, optional) – A name for the calculator. If name is None (default), then the ProfileGenerator’s name attribute will be used.

Raises:

ValueError – If the ProfileGenerator has no name, or if the ProfileGenerator has the same name as some other managed object.

evaluate()[source]

Evaluate the contribution equation and update profile.ycalc.

Returns:

The calculated signal.

Return type:

numpy.ndarray

getEquation()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitContribution.get_equation instead.

getResidualEquation()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitContribution.get_residual_equation instead.

get_equation()[source]

Get the math expression string for the active profile equation.

Returns:

The normalized math expression, or an empty string if the profile equation has not been set yet.

Return type:

str

get_residual_equation()[source]

Get the math expression string for the active residual equation.

Returns:

The normalized math formula, or an empty string if the residual equation has not been configured yet.

Return type:

str

residual()[source]

Calculate the residual for this FitContribution.

When this method is called, it is assumed that all parameters have been assigned their most current values by the FitRecipe. This will be the case when being called as part of a FitRecipe refinement.

The residual is by default an array chiv: chiv = (eq() - self.profile.y) / self.profile.dy. The value that is optimized is dot(chiv, chiv).

The residual equation can be changed with the set_residual_equation method.

Returns:

The array of residual values.

Return type:

numpy.ndarray

setEquation(eqstr, ns={})[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitContribution.set_equation instead.

setProfile(profile, xname=None, yname=None, dyname=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitContribution.set_profile instead.

setResidualEquation(eqstr)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitContribution.set_residual_equation instead.

set_equation(eqstr, ns={})[source]

Set the profile equation for the FitContribution.

This sets the equation that will be used when generating the residual for this FitContribution. The equation will be usable within set_residual_equation as "eq", and it takes no arguments.

Parameters:
  • eqstr (str) – A string representation of the equation. Any Parameter registered by addParameter or set_profile, or function registered by register_calculator, register_function or register_string_function can be used in the equation by name. Other names will be turned into Parameters of this FitContribution.

  • ns (dict, optional) – A dictionary of Parameters, indexed by name, that are used in the eqstr, but not registered (default {}).

Raises:

ValueError – If ns uses a name that is already used for a variable.

set_profile(profile, xname=None, yname=None, dyname=None)[source]

Assign the Profile for this FitContribution.

Parameters:
  • profile (Profile) – The Profile that specifies the calculation points and that will store the calculated signal.

  • xname (str, optional) – The name of the independent variable from the Profile. If this is None (default), then the name specified by the Profile for this parameter will be used. This variable is usable within string equations with the specified name.

  • yname (str, optional) – The name of the observed Profile. If this is None (default), then the name specified by the Profile for this parameter will be used. This variable is usable within string equations with the specified name.

  • dyname (str, optional) – The name of the uncertainty in the observed Profile. If this is None (default), then the name specified by the Profile for this parameter will be used. This variable is usable within string equations with the specified name.

set_residual_equation(eqstr)[source]

Set the residual equation for the FitContribution.

Two residuals are preset for convenience, "chiv" and "resv". chiv is defined such that dot(chiv, chiv) = chi^2. resv is defined such that dot(resv, resv) = Rw^2. You can call on these in your residual equation. Note that the quantity that will be optimized is the summed square of the residual equation. Keep that in mind when defining a new residual or using the built-in ones.

Parameters:

eqstr (str) – A string representation of the residual. If eqstr is None (default), then the previous residual equation will be used, or the chi2 residual will be used if that does not exist.

Raises:
  • SrFitError – If the Profile is not yet defined.

  • ValueError – If eqstr depends on a Parameter that is not part of the FitContribution.

diffpy.srfit.fitbase.recipeorganizer module

Base classes and tools for constructing a FitRecipe.

RecipeContainer is the base class for organizing Parameters, and other RecipeContainers. RecipeOrganizer is an extended RecipeContainer that incorporates equation building, constraints and Restraints. get_equation_from_string creates an Equation instance from a string.

class diffpy.srfit.fitbase.recipeorganizer.RecipeContainer(name)[source]

Bases: Observable, Configurable, Validatable

Base class for organizing pieces of a FitRecipe.

RecipeContainers are hierarchical organizations of Parameters and other RecipeContainers. This class provides attribute-access to these contained objects. Parameters and other RecipeContainers can be found within the hierarchy with the _locate_managed_object method.

A RecipeContainer can manage dictionaries for that store various objects. These dictionaries can be added to the RecipeContainer using the _manage method. RecipeContainer methods that add, remove or retrieve objects will work with any managed dictionary. This makes it easy to add new types of objects to be contained by a RecipeContainer. By default, the RecipeContainer is configured to manage an OrderedDict of Parameter objects.

RecipeContainer is an Observable, and observes its managed objects and Parameters. This allows hierarchical calculation elements, such as ProfileGenerator, to detect changes in Parameters and Restraints on which it may depend.

name

A name for this RecipeContainer. Names should be unique within a RecipeContainer and should be valid attribute names.

_parameters

A managed OrderedDict of contained Parameters.

__managed

A list of managed dictionaries. This is used for attribute access, addition and removal.

_configobjs

A set of configurable objects that must know of configuration changes within this object.

names

Variable names (read only). See get_names.

values

Variable values (read only). See get_values.

get(name, default=None)[source]

Get a managed object.

Parameters:
  • name (str) – The name of the managed object to retrieve.

  • default (optional) – The value to return if no managed object is found under name (default None).

Returns:

The managed object registered under name, or default if no such object exists.

Return type:

object

getNames()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeContainer.get_names instead.

getValues()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeContainer.get_values instead.

get_names()[source]

Get the names of managed parameters.

Returns:

The names of the managed Parameters.

Return type:

list of str

get_values()[source]

Get the values of managed parameters.

Returns:

The values of the managed Parameters.

Return type:

list

iterPars(pattern='', recurse=True)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeContainer.iterate_over_parameters instead.

iterate_over_parameters(pattern='', recurse=True, fullnames=False)[source]

Iterate over the Parameters contained in this object.

Parameters:
  • pattern (str, optional) – The regular expression pattern to match parameter names against. Only parameters with names matching this pattern will be returned. Default is an empty string, which matches all parameter names.

  • recurse (bool, optional) – The flag indicating whether to recurse into managed objects when iterating over parameters. If True (default), the method will also iterate over parameters in managed sub-objects. If False, only top-level parameters will be iterated over.

  • fullnames (bool, optional) – The flag indicating whether to match against hierarchical dotted names relative to this object. If False (default), match only leaf parameter names.

Yields:

Parameter – The next Parameter whose name matches pattern.

Examples

property names
property values
class diffpy.srfit.fitbase.recipeorganizer.RecipeOrganizer(name)[source]

Bases: RecipeOrganizerInterface, RecipeContainer

Extended base class for organizing pieces of a FitRecipe.

This class extends RecipeContainer by organizing constraints and Restraints, as well as Equations that can be used in Constraint and Restraint equations. These constraints and Restraints can be placed at any level and a flattened list of them can be retrieved with the _get_constraints and _get_restraints methods.

name

A name for this organizer. Names should be unique within a RecipeOrganizer and should be valid attribute names.

_calculators

A managed dictionary of Calculators, indexed by name.

_parameters

A managed OrderedDict of contained Parameters.

_constraints

A dictionary of Constraints, indexed by the constrained Parameter. Constraints can be added using the ‘constrain’ method.

_restraints

A set of Restraints. Restraints can be added using the ‘restrain’ method.

_eqfactory

A diffpy.srfit.equation.builder.EquationFactory instance that is used create Equations from string.

names

Variable names (read only). See get_names.

values

Variable values (read only). See get_values.

Raises:

ValueError – If the name is not a valid attribute identifier.

addRestraint(res)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeOrganizer.register_soft_bounds instead.

add_constraint(parameter, constraint_eq, params={})[source]

Constrain a parameter to an equation.

Note that only one constraint can exist on a Parameter at a time.

Parameters:
  • parameter (str or Parameter) – The name of a Parameter or a Parameter to constrain.

  • constraint_eq (str or Equation) – A string representation of the constraint equation or a Parameter to constrain to. A constraint equation must consist of numpy operators and “known” Parameters. Parameters are known if they are in the params argument, or if they are managed by this object.

  • params (dict, optional) – A dictionary of Parameters, indexed by name, that are used in parameter, but not part of this object (default {}).

Raises:
  • ValueError – If params uses a name that is already used for a variable.

  • ValueError – If parameter is a string but not part of this object or in params.

  • ValueError – If parameter is marked as constant.

add_soft_bounds(param_or_eq, lower_bound=-inf, upper_bound=inf, sig=1, scaled=False, params={})[source]

Restrain an expression to specified bounds.

See Notes for how the penalty is calculated.

Parameters:
  • param_or_eq (str) – The equation or parameter to restrain.

  • lower_bound (float, optional) – The lower bound for the restraint evaluation (default is -inf).

  • upper_bound (float, optional) – The upper bound for the restraint evaluation (default is inf).

  • sig (float, optional) – The uncertainty associated with the bounds (default is 1). Please see Notes for how this is used in the penalty calculation.

  • scaled (bool, optional) – If True, the restraint penalty is scaled by the unrestrained point-average chi^2 (chi^2/numpoints) (default is False).

  • params (dict, optional) – The dictionary of Parameters, indexed by name, that are used in param_or_eq (if an equation string is used) but are not part of the RecipeOrganizer (default is {}).

Returns:

The created Restraint object, which can be used with the ‘unrestrain’ method.

Return type:

Restraint

Notes

The penalty is calculated as:

where val is the value of the evaluated param_or_eq. If scaled is True, this penalty is multiplied by the average chi^2.

Examples

Restraining the lattice parameters of an Ni lattice to be approximately 7.4Å (2x the original lattice param) can be done with the following code: ..

recipe.add_soft_bounds(

“a_ni + b_ni”, lower_bound=7.0, upper_bound=7.5, sig=0.1, scaled=True, params={“b_ni”: Parameter(“b_ni”, 3.473)}

)

Raises:
  • ValueError – If params contains a name that is already used for a Parameter.

  • ValueError – If param_or_eq depends on a Parameter that is not part of the RecipeOrganizer and is not defined in params.

clearConstraints(recurse=False)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeOrganizer.clear_all_constraints instead.

clearRestraints(recurse=False)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeOrganizer.clear_all_soft_bounds instead.

clear_all_constraints(recurse=False)[source]

Clear all constraints managed by this organizer.

This removes constraints that are held in this organizer, no matter where the constrained parameters are from.

Parameters:

recurse (bool, optional) – If False (default), only constraints in this object are cleared. If True, constraints in managed sub-objects are also cleared.

clear_all_soft_bounds(recurse=False)[source]

Clear all restraints.

Parameters:

recurse (bool, optional) – If False (default), only restraints in this object are cleared. If True, restraints in managed sub-objects are also cleared.

constrain(par, con, ns={})[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeOrganizer.add_constraint instead.

evaluateEquation(eqstr, ns={})[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeOrganizer.evaluate_equation instead.

evaluate_equation(equation_str, func_params={})[source]

Evaluate a string equation.

This method takes a string representation of a mathematical equation and evaluates it using the current values of the registered Parameters in the FitRecipe. Additional parameters not part of the FitRecipe can also be provided via the func_params dictionary.

Parameters:
  • equation_str – The string equation to evaluate. The equation is evaluated at the current value of the registered Parameters.

  • func_params (dict, optional) – The dictionary of Parameters, indexed by name, that are used in equation_str, but not part of the FitRecipe (default {}).

Returns:

returned_value – The value of the evaluated equation.

Return type:

float

Raises:

ValueError – If func_params uses a name that is already used for a variable.

getConstrainedPars(recurse=False)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeOrganizer.get_constrained_parmeters instead.

get_constrained_parmeters(recurse=False)[source]

Get a list of constrained managed Parameters in this object.

Parameters:

recurse (bool, optional) – If False (default), only constrained Parameters in this object are returned. If True, constrained Parameters in managed sub-objects are also included.

Returns:

constrained_params – The list of constrained managed Parameters in this object.

Return type:

list of Parameter

isConstrained(par)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeOrganizer.is_constrained instead.

is_constrained(parameter)[source]

Determine if a Parameter is constrained in this object.

Parameters:

parameter (str or Parameter) – The name of a Parameter or a Parameter to check.

Returns:

True if the Parameter is constrained in this object, False otherwise.

Return type:

bool

registerCalculator(f, argnames=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeOrganizer.register_calculator instead.

registerFunction(f, name=None, argnames=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeOrganizer.register_function instead.

registerStringFunction(fstr, name, ns={})[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeOrganizer.register_string_function instead.

register_calculator(calculator, argnames=None)[source]

Register a Calculator so it can be used within equation strings.

A Calculator is an elaborate function that can organize Parameters. This creates a function with this class that can be used within string equations. The resulting equation can be used in a string with arguments like a function or without, in which case the values of the Parameters created from argnames will be be used to compute the value.

Parameters:
  • calculator (Calculator object) – The Calculator to register.

  • argnames (list or None, optional) – The names of the arguments to calculator (list or None). If this is None, then the argument names will be extracted from the function.

Returns:

The callable Equation object wrapping calculator.

Return type:

Equation

register_function(function, name=None, argnames=None)[source]

Register a function so it can be used within equation strings.

This creates a function with this class that can be used within string equations. The resulting equation does not require the arguments to be passed in the equation string, as this will be handled automatically.

Parameters:
  • function (callable) – The callable to register. If this is an Equation instance, then all that needs to be provided is a name.

  • name (str or None, optional) – The name of the function to be used in equations. If this is None (default), the method will try to determine the name of the function automatically.

  • argnames (list or None, optional) – The names of the arguments to function (list or None). If this is None (default), then the argument names will be extracted from the function.

Returns:

equation_object – The callable Equation object.

Return type:

Equation

Raises:
  • TypeError – If name or argnames cannot be automatically extracted.

  • TypeError – If an automatically extracted name is ‘<lambda>’.

  • ValueError – If function is an Equation object and name is None.

Notes

The name and argnames args can be extracted from regular Python functions (of type <function>), bound class methods, and callable classes.

register_soft_bounds(res)[source]

Add a Restraint instance to the RecipeOrganizer.

Parameters:

res (Restraint) – A Restraint instance.

register_string_function(function_str, name, func_params={})[source]

Register a string function.

This creates a function with this class that can be used within string equations. The resulting equation does not require the arguments to be passed in the function string, as this will be handled automatically.

Parameters:
  • function_str (str) – A string equation to register.

  • name (str) – The name of the function to be used in equations.

  • func_params (dict, optional) – A dictionary of Parameters, indexed by name, that are used in function_str, but not part of the FitRecipe (default {}).

Returns:

equation_object – The callable Equation object.

Return type:

Equation

Raises:
  • ValueError – If func_params uses a name that is already used for another managed object.

  • ValueError – If the function name is the name of another managed object.

remove_constraint(*pars)[source]

Unconstrain a Parameter.

This removes any constraints on a Parameter.

Parameters:

*pars (str or Parameter) – The names of Parameters or Parameters to unconstrain.

Raises:

ValueError – If the Parameter is not constrained.

remove_soft_bounds(*ress)[source]

Remove a Restraint from the RecipeOrganizer.

Parameters:

*ress (Restraint) – The Restraints returned from the ‘add_soft_bounds’ method or added with the ‘register_soft_bounds’ method.

restrain(res, lb=-inf, ub=inf, sig=1, scaled=False, ns={})[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeOrganizer.add_soft_bounds instead.

show(pattern='', textwidth=78)[source]

Show the configuration hierarchy on the screen.

This will print out a summary of all contained objects.

Parameters:
  • pattern (str, optional) – Limit output to only those parameters that match this regular expression (match all by default).

  • textwidth (int, optional) – Trim formatted lines at this text width to avoid folding at the screen width. Do not trim when negative or 0.

unconstrain(*pars)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeOrganizer.remove_constraint instead.

unrestrain(*ress)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.recipeorganizer.RecipeOrganizer.remove_soft_bounds instead.

diffpy.srfit.fitbase.recipeorganizer.get_equation_from_string(eqstr, factory, ns={}, buildargs=False, argclass=<class 'diffpy.srfit.fitbase.parameter.Parameter'>, argkw={})[source]

Make an Equation object from a string.

Parameters:
  • eqstr (str) – A string representation of the equation. The equation must consist of numpy operators and “known” Parameters. Parameters are known if they are in ns, or already defined in the factory.

  • factory (EquationFactory) – An EquationFactory instance.

  • ns (dict, optional) – The dictionary of Parameters indexed by name that are used in the eqstr but not already defined in the factory (default {}).

  • buildargs (bool, optional) – A flag indicating whether missing Parameters can be created by the Factory (default False). If False, then the a ValueError will be raised if there are undefined arguments in the eqstr.

  • argclass (Parameter class, optional) – Class to use when creating new Arguments (default Parameter). The class constructor must accept the ‘name’ key word.

  • argkw (dict, optional) – Key word dictionary to pass to the argclass constructor (default {}).

Returns:

eq – An Equation instance representing the equation in eqstr.

Return type:

Equation

Raises:

ValueError – If buildargs is False and there are undefined parameters in eqstr or if ns uses a name that is already defined in the factory.

diffpy.srfit.fitbase.fitrecipe module

FitRecipe class.

FitRecipes organize FitContributions, variables, Restraints and Constraints to create a recipe of the system you wish to optimize. From the client’s perspective, the FitRecipe is a residual calculator. The residual method does the work of updating variable values, which get propagated to the Parameters of the underlying FitContributions via the variables and Constraints. This class needs no special knowledge of the type of FitContribution or data being used. Thus, it is suitable for combining residual equations from various types of refinements into a single residual.

Variables added to a FitRecipe can be tagged with string identifiers. Variables can be later retrieved or manipulated by tag. The tag name __fixed is reserved.

See the examples in the documentation for how to create an optimization problem using FitRecipe.

class diffpy.srfit.fitbase.fitrecipe.FitRecipe(name='fit')[source]

Bases: FitRecipeInterface, RecipeOrganizer

Organize FitContributions, variables, restraints, and constraints into a refinable recipe.

name

A name for this FitRecipe.

Type:

str

fithooks

The list of FitHook instances that can pass information out of the system during a refinement. By default, this is populated by a PrintFitHook instance.

Type:

list

_constraints

The dictionary of Constraints, indexed by the constrained Parameter. Constraints can be added using the add_constraint method.

Type:

dict

_oconstraints

The ordered list of the constraints from this and all sub-components.

Type:

list

_calculators

The managed dictionary of Calculators.

Type:

dict

_contributions

The managed OrderedDict of FitContributions.

Type:

OrderedDict

_parameters

The managed OrderedDict of parameters (in this case the parameters are varied).

Type:

OrderedDict

_parsets

The managed dictionary of ParameterSets.

Type:

dict

_eqfactory

The diffpy.srfit.equation.builder.EquationFactory instance that is used to create constraints and restraints from strings.

Type:

diffpy.srfit.equation.builder.EquationFactory

_restraintlist

The list of restraints from this and all sub-components.

Type:

list

_restraints

The set of Restraints. Restraints can be added using the ‘restrain’ or ‘confine’ methods.

Type:

set

_ready

The flag indicating if all attributes are ready for the calculation.

Type:

bool

_tagmanager

The TagManager instance for managing tags on Parameters.

Type:

TagManager

_weights

The list of weighing factors for each FitContribution. The weights are multiplied by the residual of the FitContribution when determining the overall residual.

Type:

list

_fixedtag

__fixed, used for tagging variables as fixed. Don’t use this tag unless you want issues.

Type:

str

names

The variable names (read only). See get_names.

Type:

list

values

The variable values (read only). See get_values.

Type:

numpy.ndarray

fixednames

The names of the fixed refinable variables (read only).

Type:

list

fixedvalues

The values of the fixed refinable variables (read only).

Type:

numpy.ndarray

bounds

The bounds on parameters (read only). See get_bounds_pairs.

Type:

list of tuple

bounds2

The bounds on parameters (read only). See get_bounds_array.

Type:

tuple of numpy.ndarray

addContribution(con, weight=1.0)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.add_contribution instead.

addParameterSet(parset)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.add_parameter_set instead.

addVar(par, value=None, name=None, fixed=False, tag=None, tags=[])[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.add_variable instead.

add_constraint(par, con, ns={})[source]

Constrain a parameter to an equation.

Note that only one constraint can exist on a Parameter at a time.

This is overloaded to set the value of con if it represents a variable and its current value is None. A constrained variable will be set as fixed.

Parameters:
  • par (Parameter) – The Parameter to constrain.

  • con (str or Parameter) – The string representation of the constraint equation or a Parameter to constrain to. A constraint equation must consist of numpy operators and “known” Parameters. Parameters are known if they are in the ns argument, or if they are managed by this object.

  • ns (dict, optional) – The dictionary of Parameters, indexed by name, that are used in the eqstr, but not part of this object (default {}).

Raises:
  • ValueError – If ns uses a name that is already used for a variable.

  • ValueError – If eqstr depends on a Parameter that is not part of the FitRecipe and that is not defined in ns.

  • ValueError – If par is marked as constant.

add_contribution(con, weight=1.0)[source]

Add a FitContribution to the FitRecipe.

Parameters:
  • con (FitContribution) – The FitContribution to be stored.

  • weight (float, optional) – The weight of the FitContribution. Default is 1.0.

Raises:

ValueError – If the FitContribution has no name or if the FitContribution has the same name as some other managed object.

add_parameter_set(parset)[source]

Add a ParameterSet to the hierarchy.

Parameters:

parset (ParameterSet) – The ParameterSet to be stored.

Raises:

ValueError – If the ParameterSet has no name or if the ParameterSet has the same name as some other managed object.

add_variable(par, value=None, name=None, fixed=False, tag=None, tags=[])[source]

Add a variable to be refined.

Parameters:
  • par (diffpy.srfit.fitbase.Parameter) – The Parameter that will be varied during a fit.

  • value (float or None, optional) – The initial value for the variable. If this is None (default), then the current value of par will be used.

  • name (str or None, optional) – The name for this variable. If name is None (default), then the name of the parameter will be used.

  • fixed (bool, optional) – Fix the variable so that it does not vary (default False).

  • tag (str or None, optional) – The tag for the variable. This can be used to retrieve, fix or free variables by tag (default None). Note that a variable is automatically tagged with its name and “all”.

  • tags (list of str, optional) – The list of tags (default []). Both tag and tags can be applied.

Returns:

The ParameterProxy (variable) for the passed Parameter.

Return type:

ParameterProxy

Raises:
  • ValueError – If the name of the variable is already taken by another managed object.

  • ValueError – If par is constant.

  • ValueError – If par is constrained.

property bounds
property bounds2
boundsToRestraints(sig=1, scaled=False)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.convert_bounds_to_restraints instead.

clearFitHooks()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.clear_fit_hooks instead.

clear_fit_hooks()[source]

Clear the FitHook sequence.

constrain(par, con, ns={})[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.add_constraint instead.

convert_bounds_to_restraints(sig=1, scaled=False)[source]

Turn all bounded parameters into restraints.

The bounds become limits on the restraint.

Parameters:
  • sig (float or iterable of float, optional) – The number of standard deviations associated with each bound. Smaller values produce stronger restraints. If a scalar is given, the same value is applied to all parameters. If an iterable is provided, it must match the number of parameters. Default is 1.

  • scaled (bool, optional) – If True, scale each restraint by the magnitude of the corresponding parameter, consistent with the behavior of restrain(). Default is False.

create_new_variable(name, value=None, fixed=False, tag=None, tags=[])[source]

Create a new variable of the fit.

This method lets new variables be created that are not tied to a Parameter. Orphan variables may cause a fit to fail, depending on the optimization routine, and therefore should only be created to be used in constraint or restraint equations.

Parameters:
  • name (str) – The name of the variable. The variable will be able to be used by this name in restraint and constraint equations.

  • value (float or None, optional) – The initial value for the variable. If this is None (default), then the variable will be given the value of the first non-None-valued Parameter constrained to it. If this fails, an error will be thrown when ‘residual’ is called.

  • fixed (bool, optional) – Fix the variable so that it does not vary (default False). The variable will still be managed by the FitRecipe.

  • tag (str or None, optional) – The tag for the variable. This can be used to fix and free variables by tag (default None). Note that a variable is automatically tagged with its name and “all”.

  • tags (list of str, optional) – The list of tags (default []). Both tag and tags can be applied.

Returns:

The new variable (Parameter instance).

Return type:

Parameter

delVar(var)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.delete_variable instead.

delete_variable(var)[source]

Remove a variable.

Note that constraints and restraints involving the variable are not modified.

Parameters:

var (ParameterProxy) – A variable of the FitRecipe.

Raises:

ValueError – If var is not part of the FitRecipe.

fix(*args, **kw)[source]

Fix one or more parameters by reference, name, or tag.

This method marks specified parameters as fixed, meaning they will not be refined during the fitting process. By default, all parameters are free (not fixed). Parameters can be specified using their references, names, or tags. Additionally, keyword arguments can be used to assign specific values to the fixed parameters.

Parameters:
  • *args (str or Parameter) – The positional arguments specifying the parameters to fix. These can be parameter objects, their names as strings, or tags. The special string “all” can be used to select all parameters.

  • **kw (dict) – The keyword arguments where the keys are parameter names and the values are the values to assign to the corresponding fixed parameters.

Raises:

ValueError – If an unknown parameter, name, or tag is passed, or if a tag is passed as a keyword argument.

Examples

# Fix a parameter by reference
recipe.fix(param1)

# Fix a parameter by name
recipe.fix("param2")

# Fix all parameters
recipe.fix("all")

# Fix parameters by tag
recipe.fix(tag="group1")

# Fix a parameter and assign it a value
recipe.fix(param3=10.0)
property fixednames

names of the fixed refinable variables

property fixedvalues

values of the fixed refinable variables

free(*args, **kw)[source]

Free one or more parameters by reference, name, or tag.

This method marks specified parameters as free, allowing them to be refined during the fitting process. By default, variables are free unless they are constrained. Constrained variables cannot be freed.

Parameters:
  • *args (str or Parameter) – The positional arguments specifying the parameters to free. These can be: - Parameter objects - Names of parameters (as strings) - Tags associated with parameters (as strings) - The string “all” to select all parameters.

  • **kw (dict) – The keyword arguments specifying parameter names as keys and their values to assign after freeing. This is useful for setting the value of a parameter while marking it as free.

Return type:

None

Raises:

ValueError – If an unknown parameter, name, or tag is passed, or if a tag is passed as a keyword argument.

Notes

  • Parameters that are already free will remain free.

  • Tags associated with fixed parameters will be removed when they are freed.

  • If keyword arguments are provided, the corresponding parameter values will be updated after freeing.

getBounds()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.get_bounds_pairs instead.

getBounds2()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.get_bounds_array instead.

getFitHooks()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.get_fit_hooks instead.

getNames()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.get_names instead.

getValues()[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.get_values instead.

get_bounds_array()[source]

Get the bounds on variables in two numpy arrays.

Returns:

  • lower_bounds (numpy.ndarray) – The numpy array of lower bounds on the variables, in the same order as get_names and get_values.

  • upper_bounds (numpy.ndarray) – The numpy array of upper bounds on the variables, in the same order as get_names and get_values.

get_bounds_pairs()[source]

Get the bounds on variables in a list.

Returns:

bounds_pair_list – The list of (lower, upper) bounds on the variables, in the same order as get_names and get_values.

Return type:

list of tuple of float

get_fit_hooks()[source]

Get the sequence of FitHook instances.

Returns:

The list of FitHook instances registered with this FitRecipe.

Return type:

list

get_names()[source]

Retrieve the names of all free variables in the fit recipe.

This method iterates through the parameters in the fit recipe and returns a list of names for those variables that are marked as free.

Returns:

parameter_names – The list containing the names of free variables.

Return type:

list of str

get_values()[source]

Retrieve the current values of all free variables in the fit recipe.

This method collects the values of all parameters that are marked as free (i.e., adjustable during the fitting process) and returns them as a NumPy array.

Returns:

values_array – The array containing the current values of all free variables in the fit recipe.

Return type:

numpy.ndarray

initialize_recipe_with_recipe(recipe_object)[source]

Initialize a FitRecipe with another FitRecipe.

This is used to initialize a FitRecipe with the contribution(s), parameters, constraints and restraints of another FitRecipe. If a duplicate contribution, parameter, constraint, or restraint is added to the FitRecipe you are initializing, the value from the added object will be used.

Parameters:

recipe_object (FitRecipe) – The FitRecipe to initialize with.

Raises:

ValueError – If the object passed is not a FitRecipe.

initialize_recipe_with_results(results, verbose=True)[source]

Initialize a FitRecipe with a FitResults object or a results file.

Note that at least one FitContribution must already exist in the FitRecipe.

Parameters:
  • results (FitResults, pathlib.Path, or str) – The FitResults object or path to results file to initialize with.

  • verbose (bool, optional) – If True, print warnings for any parameters in the results that are not in the FitRecipe. Default is True.

Raises:

ValueError – If the input results is not a FitResults object or a path to a results file.

isFree(var)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.is_free instead.

is_free(var)[source]

Determine if a variable is free (not fixed) in the fit recipe.

This method checks whether the specified variable does not have the fixed tag associated with it, indicating that it is free to vary during the fitting process.

Parameters:

var (object) – The variable to check. This is typically an instance of a parameter or variable object used in the fit recipe.

Returns:

True if the variable is free (not fixed), False otherwise.

Return type:

bool

newVar(name, value=None, fixed=False, tag=None, tags=[])[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.create_new_variable instead.

plot_recipe(ax=None, return_fig=False, **kwargs)[source]

Plot the observed, fit, and difference curves for each contribution of the fit recipe.

If the recipe has multiple contributions, a separate plot is created for each contribution.

Parameters:
  • ax (matplotlib.axes.Axes or None, optional) – The axes object to plot on. If None, creates a new figure. Default is None.

  • return_fig (bool, optional) – The figure and axes objects are returned if True. Default is False.

  • **kwargs (dict) – Any plotting option can be passed to override the defaults in FitRecipe().plot_options. See the FitRecipe().set_plot_defaults() method for available keyword arguments.

Returns:

fig, axes – The figure and axes objects, returned only if return_fig=True. If the recipe has a single contribution, a single mpl.figure.Figure and mpl.axes.Axes are returned. If it has multiple contributions, a list of figures and a list of axes (one per contribution) are returned instead.

Return type:

tuple

Examples

Plot with default settings:

>>> recipe.plot_recipe()

Override defaults for one plot:

>>> recipe.plot_recipe(show_diff=False, title='My Custom Title')

Set defaults once, use everywhere:

>>> recipe.set_plot_defaults(xlabel='r (Å)', ylabel='G(r)')
>>> recipe.plot_recipe()  # Uses xlabel and ylabel
>>> recipe.plot_recipe()  # Still uses them

Override a default for one plot:

>>> recipe.set_plot_defaults(figsize=(10, 7))
>>> recipe.plot_recipe()  # Uses (10, 7)
>>> recipe.plot_recipe(figsize=(12, 8))  # Temporarily uses (12, 8)
>>> recipe.plot_recipe()  # Back to (10, 7)

Notes

The default values are taken from recipe.plot_options. You can modify these defaults in three ways:

1. Using set_plot_defaults(): recipe.set_plot_defaults(xlabel=’r (Å)’)

2. Direct attribute access: recipe.plot_options[‘xlabel’] = ‘r (Å)’

3. Using update(): recipe.plot_options.update({‘xlabel’: ‘r (Å)’, ‘ylabel’: ‘G(r)’})

popFitHook(fithook=None, index=-1)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.pop_fit_hook instead.

pop_fit_hook(fithook=None, index=-1)[source]

Remove a FitHook by index or reference.

Parameters:
  • fithook (diffpy.srfit.fitbase.fithook.FitHook or None, optional) – The FitHook instance to remove from the sequence. If this is None (default), default to index.

  • index (int, optional) – The index of FitHook instance to remove (default -1).

Raises:
  • ValueError – If fithook is not None, but is not present in the sequence.

  • IndexError – If the sequence is empty or index is out of range.

pushFitHook(fithook, index=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.push_fit_hook instead.

push_fit_hook(fithook, index=None)[source]

Add a FitHook to be called within the residual method.

The hook is an object for reporting updates, or more fundamentally, passing information out of the system during a refinement. See the diffpy.srfit.fitbase.fithook.FitHook class for the required interface. Added FitHooks will be called sequentially during refinement.

Parameters:
  • fithook (diffpy.srfit.fitbase.fithook.FitHook) – The FitHook instance to add to the sequence.

  • index (int or None, optional) – The index for inserting fithook into the list of fit hooks. If this is None (default), the fithook is added to the end.

removeParameterSet(parset)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.remove_parameter_set instead.

remove_constraint(*pars)[source]

Unconstrain a Parameter.

This removes any constraints on a Parameter. If the Parameter is also a variable of the recipe, it will be freed as well.

Parameters:

*pars (str or Parameter) – The names of Parameters or Parameter objects to unconstrain.

Raises:

ValueError – If the Parameter is not constrained.

remove_parameter_set(parset)[source]

Remove a ParameterSet from the hierarchy.

This method removes the specified ParameterSet object from the internal hierarchy of managed ParameterSets. If the provided ParameterSet is not currently managed by this object, a ValueError will be raised.

Parameters:

parset (ParameterSet) – The ParameterSet instance to be removed from the hierarchy.

Raises:

ValueError – If the provided ParameterSet is not managed by this object.

residual(p=[])[source]

Calculate the vector residual to be optimized.

The residual is by default the weighted concatenation of each FitContribution’s residual, plus the value of each restraint. The array returned, denoted chiv, is such that dot(chiv, chiv) = chi^2 + restraints.

Parameters:

p (list or numpy.ndarray) – The list of current variable values, provided in the same order as the _parameters list. If p is an empty iterable (default), then it is assumed that the parameters have already been updated in some other way, and the explicit update within this function is skipped.

Returns:

chiv – The array of residuals to be optimized. The array is such that dot(chiv, chiv) = chi^2 + restraints.

Return type:

numpy.ndarray

scalarResidual(p=[])[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.scalar_residual instead.

scalar_residual(p=[])[source]

Calculate the scalar residual to be optimized.

Parameters:

p (list or numpy.ndarray) – The list of current variable values, provided in the same order as the _parameters list. If p is an empty iterable (default), then it is assumed that the parameters have already been updated in some other way, and the explicit update within this function is skipped.

Returns:

The scalar residual, dot(chiv, chiv), where chiv is the vector residual returned by residual.

Return type:

float

Notes

The residual is by default the weighted concatenation of each FitContribution residual, plus the value of each restraint. The returned array, denoted chiv, is such that dot(chiv, chiv) = chi^2 + restraints.

setWeight(con, weight)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.set_weight instead.

set_plot_defaults(**kwargs)[source]

Set default plotting options for all future plots.

Any keyword argument accepted by plot_recipe() can be set here.

Parameters:
  • show_observed (bool, optional) – The observed data is plotted if True. Default is True.

  • show_fit (bool, optional) – The fit to the data is plotted if True. Default is True.

  • show_diff (bool, optional) – The difference curve (observed - calculated) is plotted if True. Default is True.

  • offset_scale (float, optional) – The scaling factor for the difference curve offset. The difference curve is offset below the data by (min_y - 0.1*range) * offset_scale. Default is 1.0.

  • xmin (float or None, optional) – The minimum x value to plot. If None, uses the minimum x value of the data. Default is None.

  • xmax (float or None, optional) – The maximum x value to plot. If None, uses the maximum x value of the data. Default is None.

  • figsize (tuple, optional) – The figure size as (width, height). Default is (8, 6).

  • data_style (str, optional) – The matplotlib line/marker style for data points. Default is “o”.

  • fit_style (str, optional) – The matplotlib line/marker style for the calculated fit. Default is “-“.

  • diff_style (str, optional) – The matplotlib line/marker style for the difference curve. Default is “-“.

  • data_color (str or None, optional) – The color for data plot. If None, uses default matplotlib colors.

  • fit_color (str or None, optional) – The color for the fit plot. If None, uses default matplotlib colors.

  • diff_color (str or None, optional) – The color for the difference plot. If None, uses default matplotlib colors.

  • data_label (str, optional) – The legend label for observed data. Default is “Observed”.

  • fit_label (str, optional) – The legend label for the calculated fit. Default is “Calculated”.

  • diff_label (str, optional) – The legend label for the difference curve. Default is “Difference”.

  • xlabel (str, optional) – The label for the x-axis.

  • ylabel (str, optional) – The label for the y-axis.

  • title (str or None, optional) – The plot title. If None (default), each figure created by plot_recipe is titled with the name of the contribution it shows. A title is not added to a user-supplied axes.

  • legend (bool, optional) – The legend is shown if True. Default is True.

  • legend_loc (str, optional) – The legend location. Default is “best”.

  • grid (bool, optional) – The grid is shown if True. Default is False.

  • markersize (float, optional) – The size of data point markers.

  • linewidth (float, optional) – The width of fit and difference lines.

  • alpha (float, optional) – The transparency of all plot elements (0=transparent, 1=opaque). Default is 1.0.

  • show (bool, optional) – The plot is displayed using plt.show() if True. Default is True.

Notes

The data_label, fit_label, diff_label and title options accept a {contribution} placeholder that is replaced by the name of the FitContribution being plotted, e.g. fit_label="{contribution} calculated". When several contributions are drawn on a shared axes, labels without the placeholder are prefixed with the contribution name so the legend entries stay distinguishable.

Examples

>>> recipe.set_plot_defaults(
        xlabel='r (Å)',
        ylabel='G(r) (Å⁻²)',
        data_color='black',
        fit_color='red'
    )
set_weight(con, weight)[source]

Set the weight of a FitContribution.

Parameters:
  • con (FitContribution) – The FitContribution object whose weight is to be set.

  • weight (float) – The weight value to assign to the specified FitContribution.

Return type:

None

unconstrain(*pars)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.FitRecipe.remove_constraint instead.

diffpy.srfit.fitbase.parameterset module

ParameterSet class.

ParameterSets organize Parameters, Constraints, Restraints and other ParameterSets. They provide attribute-access of other ParameterSets and embedded Parameters.

class diffpy.srfit.fitbase.parameterset.ParameterSet(name)[source]

Bases: RecipeOrganizer

Organize Parameters and other ParameterSets in a hierarchy.

ParameterSets are hierarchical organizations of Parameters, Constraints, Restraints and other ParameterSets.

Contained Parameters and other ParameterSets can be accessed by name as attributes in order to facilitate multi-level constraints and restraints. These constraints and restraints can be placed at any level and a flattened list of them can be retrieved with the ‘_get_constraints’ and ‘_get_restraints’ methods.

name

A name for this organizer.

_calculators

A managed dictionary of Calculators, indexed by name.

_constraints

A set of constrained Parameters. Constraints can be added using the ‘constrain’ methods.

_parameters

A managed OrderedDict of parameters.

_restraints

A set of Restraints. Restraints can be added using the ‘restrain’ methods.

_parsets

A managed dictionary of ParameterSets.

_eqfactory

A diffpy.srfit.equation.builder.EquationFactory instance that is used to create constraints and restraints from string equations.

names

Variable names (read only). See get_names.

values

Variable values (read only). See get_values.

addParameter(parameter, check=True)

Store a Parameter.

Parameters added in this way are registered with the _eqfactory.

Parameters:
  • parameter – The Parameter to be stored.

  • check – If True (default), a ValueError is raised if a Parameter of the specified name has already been inserted.

Raises:
  • ValueError – If the Parameter has no name.

  • ValueError – If the Parameter has the same name as a contained RecipeContainer.

addParameterSet(parset)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.parameterset.ParameterSet.add_parameter_set instead.

add_parameter_set(parset)[source]

Add a ParameterSet to the hierarchy.

Parameters:

parset (ParameterSet) – The ParameterSet to be stored.

Raises:

ValueError – If the ParameterSet has no name, or if it has the same name as some other managed object.

newParameter(name, value, check=True)

Add a new Parameter to the container.

This creates a new Parameter and adds it to the container using the _add_parameter method.

Returns:

The newly created Parameter.

Return type:

Parameter

removeParameter(parameter)

Remove a parameter.

This de-registers the Parameter with the _eqfactory. The Parameter will remain part of built equations.

Note that constraints and restraints involving the Parameter are not modified.

Raises:

ValueError – If parameter is not part of the RecipeOrganizer.

removeParameterSet(parset)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.parameterset.ParameterSet.remove_parameter_set instead.

remove_parameter_set(parset)[source]

Remove a ParameterSet from the hierarchy.

Parameters:

parset (ParameterSet) – The ParameterSet to remove.

Raises:

ValueError – If parset is not managed by this object.

setConst(const=True)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.parameterset.ParameterSet.set_constant instead.

set_constant(is_constant=True)[source]

Set every parameter within the set to a constant.

Parameters:

is_constant (bool, optional) – The flag indicating if the parameter is constant (default True).

diffpy.srfit.fitbase.calculator module

The Calculator for Parameter-aware functions.

Calculator is a functor class for producing a signal from embedded Parameters. Calculators can store Parameters and ParameterSets, Constraints and Restraints. Also, the __call__ function can be overloaded to accept external arguments. Calculators are used to wrap registered functions so that the function’s Parameters are contained in an object specific to the function. A custom Calculator can be added to another RecipeOrganizer with the ‘register_calculator’ method.

class diffpy.srfit.fitbase.calculator.Calculator(name)[source]

Bases: Operator, ParameterSet

Base class for calculators.

A Calculator organizes Parameters and has a __call__ method that can calculate a generic signal.

name

A name for this organizer.

meta

A dictionary of metadata needed by the calculator.

_calculators

A managed dictionary of Calculators, indexed by name.

_constraints

A set of constrained Parameters. Constraints can be added using the ‘constrain’ methods.

_parameters

A managed OrderedDict of contained Parameters.

_parsets

A managed dictionary of ParameterSets.

_restraints

A set of Restraints. Restraints can be added using the ‘restrain’ or ‘confine’ methods.

_eqfactory

A diffpy.srfit.equation.builder.EquationFactory instance that is used create Equations from string.

args

List of Literal arguments

nin

Number of inputs (<1 means this is variable)

nout

Number of outputs (1)

operation[source]

Function that performs the operation, self.__call__

symbol

Same as name

_value

The value of the Operator.

value

Property for ‘getValue’.

names

Variable names (read only). See get_names.

values

Variable values (read only). See get_values.

nin = -1
nout = 1
operation(*args)[source]

Calculate and cache the signal produced by this Calculator.

Parameters:

*args – The arguments needed to calculate the signal.

Returns:

The calculated signal.

Return type:

object

property symbol

Symbol representing the operator.

diffpy.srfit.fitbase.parameter module

Parameter classes.

Parameters encapsulate an adjustable parameter within SrFit.

class diffpy.srfit.fitbase.parameter.Parameter(name, value=None, const=False)[source]

Bases: ParameterInterface, Argument, Validatable

Encapsulate an adjustable parameter within SrFit.

name

A name for this Parameter.

const

A flag indicating whether this is considered a constant.

_value

The value of the Parameter. Modified with set_value.

value

Property for getValue and set_value.

constrained

A flag indicating if the Parameter is constrained (default False).

bounds

A 2-list defining the bounds on the Parameter. This can be used by some optimizers when the Parameter is varied. See FitRecipe.get_bounds_pairs and FitRecipe.convert_bounds_to_restraints.

boundRange(lb=None, ub=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.Parameter.bound_range instead.

boundWindow(lr=0, ur=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.Parameter.bound_window instead.

bound_range(lower_bound=None, upper_bound=None)[source]

Set lower and upper bound of the Parameter.

Parameters:
  • lower_bound (float) – The lower bound for the bounds list.

  • upper_bound (float) – The upper bound for the bounds list.

Returns:

Return self so that mutators can be chained.

Return type:

Parameter

bound_window(lower_radius=0, upper_radius=None)[source]

Create bounds centered on the current value of the Parameter.

Parameters:
  • lower_radius (float, optional) – The radius of the lower bound (default 0). The lower bound is computed as value - lower_radius.

  • upper_radius (float, optional) – The radius of the upper bound. The upper bound is computed as value + upper_radius. If this is None (default), then the value of the lower radius is used.

Returns:

Return self so that mutators can be chained.

Return type:

Parameter

setConst(const=True, value=None)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.Parameter.set_constant instead.

setValue(val)[source]

This function has been deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.Parameter.set_value instead.

set_constant(is_constant=True, value=None)[source]

Toggle the Parameter as constant.

Parameters:
  • is_constant (bool, optional) – The flag indicating if the parameter is constant (default True).

  • value (float, optional) – The value to set the parameter to (default None). If this is not None, then the parameter will get a new value, constant or otherwise.

Returns:

Return self so that mutators can be chained.

Return type:

Parameter

set_value(val)[source]

Set the value of the Parameter.

Parameters:

val (float) – The value to assign.

Returns:

Return self so that mutators can be chained.

Return type:

Parameter

class diffpy.srfit.fitbase.parameter.ParameterAdapter(name, obj, getter=None, setter=None, attr=None)[source]

Bases: Parameter

An adapter for parameter-like objects.

This class wraps an object as a Parameter. The getValue and set_value methods defer to the data of the wrapped object.

getValue()[source]

Get the value of the Parameter.

Returns:

The current value of the wrapped attribute.

Return type:

object

set_value(value)[source]

Set the value of the Parameter.

Parameters:

value (object) – The value to assign.

Returns:

Return self so that mutators can be chained.

Return type:

ParameterAdapter

class diffpy.srfit.fitbase.parameter.ParameterProxy(name, par)[source]

Bases: Parameter

A Parameter proxy for another parameter.

This allows for the same parameter to have multiple names.

name

A name for this ParameterProxy. Names should be unique within a RecipeOrganizer and should be valid attribute names.

par

The Parameter this is a proxy for.

bound_range(lower_bound=None, upper_bound=None)[source]

Set lower and upper bound of the Parameter.

Parameters:
  • lower_bound (float) – The lower bound for the bounds list.

  • upper_bound (float) – The upper bound for the bounds list.

Returns:

Return self so that mutators can be chained.

Return type:

Parameter

bound_window(lower_radius=0, upper_radius=None)[source]

Create bounds centered on the current value of the Parameter.

Parameters:
  • lower_radius (float, optional) – The radius of the lower bound (default 0). The lower bound is computed as value - lower_radius.

  • upper_radius (float, optional) – The radius of the upper bound. The upper bound is computed as value + upper_radius. If this is None (default), then the value of the lower radius is used.

Returns:

Return self so that mutators can be chained.

Return type:

Parameter

property bounds

List of lower and upper bounds of the proxied Parameter.

This can be used by some optimizers when the Parameter is varied. See FitRecipe.get_bounds_pairs and FitRecipe.convert_bounds_to_restraints.

property constrained

A flag indicating if the proxied Parameter is constrained.

getValue()

Get the value of this Literal.

set_constant(is_constant=True, value=None)[source]

Toggle the Parameter as constant.

Parameters:
  • is_constant (bool, optional) – The flag indicating if the parameter is constant (default True).

  • value (float, optional) – The value to set the parameter to (default None). If this is not None, then the parameter will get a new value, constant or otherwise.

Returns:

Return self so that mutators can be chained.

Return type:

Parameter

set_value(val)[source]

Set the value of the Parameter.

Parameters:

val (float) – The value to assign.

Returns:

Return self so that mutators can be chained.

Return type:

Parameter

diffpy.srfit.fitbase.profileparser module

This module contains classes for parsing profiles from files.

ProfileParser is a base class for parsing data. It can interact with a Profile object to automatically set the Profile’s data and metadata. Each specific file format must be encapsulated in a ProfileParser subclass.

See the class documentation for more information.

class diffpy.srfit.fitbase.profileparser.ProfileParser[source]

Bases: object

Base class for parsing profile data from a file.

_format

The name of the data format that this parses (string, default ""). The format string is a unique identifier for the data format handled by the parser.

Type:

str, optional

_banks

The data from each bank. Each bank contains a (x, y, dx, dy) tuple: x : np.ndarray

The independent variable read from the file.

ynp.ndarray

The dependent variable (profile) read from the file.

dxnp.ndarray

The uncertainties associated with x read from the file. This is None if the uncertainty cannot be read.

dynp.ndarray

The uncertainties associated with y read from the file. This is None if the uncertainty cannot be read.

Type:

list of tuples

_x

Independent variable from the chosen bank

Type:

np.ndarray

_y

Profile from the chosen bank

Type:

np.ndarray

_dx

Uncertainty in independent variable from the chosen bank

Type:

np.ndarray

_dy

Uncertainty in profile from the chosen bank

Type:

np.ndarray

_meta

A dictionary containing metadata read from the file.

Type:

dict

General Metadata:
  • filename (str or Path) – The name of the file from which data was parsed. This key will not exist if data was not read from file.

  • nbanks (int) – The number of banks parsed.

  • bank (int) – The chosen bank number.

getData(index=None)[source]

This function is deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.ProfileParser.get_data instead.

getFormat()[source]

This function is deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.ProfileParser.get_format instead.

getMetaData()[source]

This function is deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.ProfileParser.get_metadata instead.

getNumBanks()[source]

This function is deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.ProfileParser.get_num_banks instead.

get_data(index=None)[source]

Get the data.

This method should only be called after the data has been parsed. The chosen bank number is not persistent, and so must be re-selected if the parser is used to parse more data. This uses python list notation, so index -n returns the nth bank from the end.

Parameters:

index (int, optional) – The index of the bank (integer, starting at 0, default None). If index is None then the currently selected bank is used.

Returns:

The (x, y, dx, dy) tuple for the bank. dx and dy are None if they cannot be determined from the data format.

Return type:

tuple

get_format()[source]

Get the format string.

Returns:

The unique identifier for the data format handled by this parser.

Return type:

str

get_metadata()[source]

Get the parsed metadata.

Returns:

A dictionary containing metadata read from the file.

Return type:

dict

get_num_banks()[source]

Get the number of banks read by the parser.

Returns:

The number of banks read by the parser.

Return type:

int

parseFile(filename)[source]

This function is deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.ProfileParser.parse_file instead.

parse_file(filename, column_format=None, metadata=None, **kwargs)[source]

Parse a data file to extract data and metadata, with automatic handling of uncertainties.

This is a template method. Subclasses customize a format by overriding the _parse_metadata and _parse_data hooks rather than this method.

The default _parse_data reads a single bank:

  • For files with 2 columns: assumes (x, y) and sets dx, dy to None.

  • For files with 3 columns: assumes (x, y, dy) and sets dx to None.

  • For files with 4 columns: assumes (x, y, dx, dy).

  • For other cases: column_format must be explicitly specified.

Uncertainty columns (dx, dy) are only considered valid if all values are positive and not NaN/Inf. Otherwise they are set to None.

This wipes out the currently loaded data and selected bank number.

Parameters:
  • filename (str or Path) – The name of the file to parse.

  • column_format (tuple of str, optional) –

    The order in which columns appear in the file. If None, the format is auto-detected based on the number of columns.

    Valid labels: "x", "y", "dx", "dy"

    Examples:

    • ("x", "y")

    • ("x", "y", "dy")

    • ("x", "y", "dx", "dy")

    • ("x", "dx", "y", "dy")

  • metadata (dict, optional) – Additional metadata to merge into the metadata parsed from the file. Keys must be strings. A key that collides with one already present in the parsed metadata overrides the parsed value. A key that collides with "filename", "bank", or "nbanks", which parse_file sets itself, also overrides the automatically set value, but raises a UserWarning since it may affect other code that relies on the automatically set value.

  • kwargs – The keyword arguments passed on to diffpy.utils.parsers.load_data, such as usecols, delimiter, comments and minrows. Use usecols to select four columns out of a wider file, then label them with column_format.

Raises:

ParseError – If parsing fails or ambiguity detected.

selectBank(index)[source]

This function is deprecated and will be removed in version 4.0.0.

Please use diffpy.srfit.fitbase.ProfileParser.select_bank instead.

select_bank(index)[source]

Select which bank to use.

This method should only be called after the data has been parsed. The chosen bank number is not persistent, and so must be re-selected if the parser is used to parse more data. This uses python list notation, so index -n returns the nth bank from the end.

Parameters:

index (int) – The index of the bank (integer, starting at 0).

Raises:

IndexError – If requesting a bank that does not exist.