sas.sascalc.fit package

Submodules

sas.sascalc.fit.AbstractFitEngine module

class sas.sascalc.fit.AbstractFitEngine.FResult(model=None, param_list=None, data=None)

Bases: object

Storing fit result

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.AbstractFitEngine', '__doc__': '\n    Storing fit result\n    ', '__init__': <function FResult.__init__>, 'set_model': <function FResult.set_model>, 'set_fitness': <function FResult.set_fitness>, '__str__': <function FResult.__str__>, 'print_summary': <function FResult.print_summary>, '__dict__': <attribute '__dict__' of 'FResult' objects>, '__weakref__': <attribute '__weakref__' of 'FResult' objects>, '__annotations__': {}})
__doc__ = '\n    Storing fit result\n    '
__init__(model=None, param_list=None, data=None)
__module__ = 'sas.sascalc.fit.AbstractFitEngine'
__str__()
__weakref__

list of weak references to the object

print_summary()
set_fitness(fitness)
set_model(model)
exception sas.sascalc.fit.AbstractFitEngine.FitAbort

Bases: Exception

Exception raise to stop the fit

__doc__ = '\n    Exception raise to stop the fit\n    '
__module__ = 'sas.sascalc.fit.AbstractFitEngine'
__weakref__

list of weak references to the object

class sas.sascalc.fit.AbstractFitEngine.FitArrange

Bases: object

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.AbstractFitEngine', '__init__': <function FitArrange.__init__>, 'set_model': <function FitArrange.set_model>, 'add_data': <function FitArrange.add_data>, 'get_model': <function FitArrange.get_model>, 'get_data': <function FitArrange.get_data>, 'remove_data': <function FitArrange.remove_data>, 'set_to_fit': <function FitArrange.set_to_fit>, 'get_to_fit': <function FitArrange.get_to_fit>, '__dict__': <attribute '__dict__' of 'FitArrange' objects>, '__weakref__': <attribute '__weakref__' of 'FitArrange' objects>, '__doc__': None, '__annotations__': {}})
__doc__ = None
__init__()

Class FitArrange contains a set of data for a given model to perform the Fit.FitArrange must contain exactly one model and at least one data for the fit to be performed.

model: the model selected by the user Ldata: a list of data what the user wants to fit

__module__ = 'sas.sascalc.fit.AbstractFitEngine'
__weakref__

list of weak references to the object

add_data(data)

add_data fill a self.data_list with data to fit

Parameters:

data – Data to add in the list

get_data()
Returns:

list of data data_list

get_model()
Returns:

saved model

get_to_fit()

return self.selected value

remove_data(data)

Remove one element from the list

Parameters:

data – Data to remove from data_list

set_model(model)

set_model save a copy of the model

Parameters:

model – the model being set

set_to_fit(value=0)

set self.selected to 0 or 1 for other values raise an exception

Parameters:

value – integer between 0 or 1

class sas.sascalc.fit.AbstractFitEngine.FitData1D(x, y, dx=None, dy=None, smearer=None, data=None, lam=None, dlam=None)

Bases: Data1D

Wrapper class for SAS data FitData1D inherits from DataLoader.data_info.Data1D. Implements a way to get residuals from data.

__annotations__ = {}
__doc__ = '\n        Wrapper class  for SAS data\n        FitData1D inherits from DataLoader.data_info.Data1D. Implements\n        a way to get residuals from data.\n    '
__init__(x, y, dx=None, dy=None, smearer=None, data=None, lam=None, dlam=None)
Parameters:

smearer – is an object of class QSmearer or SlitSmearer that will smear the theory data (slit smearing or resolution smearing) when set.

The proper way to set the smearing object would be to do the following:

from sas.sascalc.fit.qsmearing import smear_selection
smearer = smear_selection(some_data)
fitdata1d = FitData1D( x= [1,3,..,],
                        y= [3,4,..,8],
                        dx=None,
                        dy=[1,2...], smearer= smearer)
Note:

that some_data _HAS_ to be of class DataLoader.data_info.Data1D Setting it back to None will turn smearing off.

__module__ = 'sas.sascalc.fit.AbstractFitEngine'
get_fit_range()

Return the range of data.x to fit

residuals(fn)

Compute residuals.

If self.smearer has been set, use if to smear the data before computing chi squared.

Parameters:

fn – function that return model value

Returns:

residuals

residuals_deriv(model, pars=[])
Returns:

residuals derivatives .

Note:

in this case just return empty array

set_fit_range(qmin=None, qmax=None)

to set the fit range

size()

Number of measurement points in data set after masking, etc.

class sas.sascalc.fit.AbstractFitEngine.FitData2D(sas_data2d, data=None, err_data=None)

Bases: Data2D

Wrapper class for SAS data

__annotations__ = {}
__doc__ = '\n        Wrapper class  for SAS data\n    '
__init__(sas_data2d, data=None, err_data=None)

Initialization

__module__ = 'sas.sascalc.fit.AbstractFitEngine'
get_fit_range()

return the range of data.x to fit

residuals(fn)

return the residuals

residuals_deriv(model, pars=[])
Returns:

residuals derivatives .

Note:

in this case just return empty array

set_data(sas_data2d, qmin=None, qmax=None)

Determine the correct qx_data and qy_data within range to fit

set_fit_range(qmin=None, qmax=None)

To set the fit range

set_smearer(smearer)

Set smearer

size()

Number of measurement points in data set after masking, etc.

class sas.sascalc.fit.AbstractFitEngine.FitEngine

Bases: object

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.AbstractFitEngine', '__init__': <function FitEngine.__init__>, 'set_model': <function FitEngine.set_model>, 'set_data': <function FitEngine.set_data>, 'get_model': <function FitEngine.get_model>, 'remove_fit_problem': <function FitEngine.remove_fit_problem>, 'select_problem_for_fit': <function FitEngine.select_problem_for_fit>, 'get_problem_to_fit': <function FitEngine.get_problem_to_fit>, 'set_weight_increase': <function FitEngine.set_weight_increase>, 'get_weight_increase': <function FitEngine.get_weight_increase>, '__dict__': <attribute '__dict__' of 'FitEngine' objects>, '__weakref__': <attribute '__weakref__' of 'FitEngine' objects>, '__doc__': None, '__annotations__': {}})
__doc__ = None
__init__()

Base class for the fit engine

__module__ = 'sas.sascalc.fit.AbstractFitEngine'
__weakref__

list of weak references to the object

get_model(id)
Parameters:

id – id is key in the dictionary containing the model to return

Returns:

a model at this id or None if no FitArrange element was created with this id

get_problem_to_fit(id)

return the self.selected value of the fit problem of id

Parameters:

id – the id of the problem

get_weight_increase(fit_id)
remove_fit_problem(id)

remove fitarrange in id

select_problem_for_fit(id, value)

select a couple of model and data at the id position in dictionary and set in self.selected value to value

Parameters:

value – the value to allow fitting. can only have the value one or zero

set_data(data, id, smearer=None, qmin=None, qmax=None)

Receives plottable, creates a list of data to fit,set data in a FitArrange object and adds that object in a dictionary with key id.

Parameters:
  • data – data added

  • id – unique key corresponding to a fitArrange object with data

set_model(model, id, pars=[], constraints=[], data=None)

set a model on a given in the fit engine.

Parameters:
  • model – sas.models type

  • id – is the key of the fitArrange dictionary where model is saved as a value

  • pars – the list of parameters to fit

  • constraints – list of tuple (name of parameter, value of parameters) the value of parameter must be a string to constraint 2 different parameters. Example: we want to fit 2 model M1 and M2 both have parameters A and B. constraints can be constraints = [(M1.A, M2.B+2), (M1.B= M2.A *5),...,]

Note:

pars must contains only name of existing model’s parameters

set_weight_increase(fit_id, weight_increase)
class sas.sascalc.fit.AbstractFitEngine.FitHandler

Bases: object

Abstract interface for fit thread handler.

The methods in this class are called by the optimizer as the fit progresses.

Note that it is up to the optimizer to call the fit handler correctly, reporting all status changes and maintaining the ‘done’ flag.

__annotations__ = {}
__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.AbstractFitEngine', '__doc__': "\n    Abstract interface for fit thread handler.\n\n    The methods in this class are called by the optimizer as the fit\n    progresses.\n\n    Note that it is up to the optimizer to call the fit handler correctly,\n    reporting all status changes and maintaining the 'done' flag.\n    ", 'done': False, 'result': None, 'improvement': <function FitHandler.improvement>, 'error': <function FitHandler.error>, 'progress': <function FitHandler.progress>, 'finalize': <function FitHandler.finalize>, 'abort': <function FitHandler.abort>, 'update_fit': <function FitHandler.update_fit>, 'set_result': <function FitHandler.set_result>, '__dict__': <attribute '__dict__' of 'FitHandler' objects>, '__weakref__': <attribute '__weakref__' of 'FitHandler' objects>, '__annotations__': {}})
__doc__ = "\n    Abstract interface for fit thread handler.\n\n    The methods in this class are called by the optimizer as the fit\n    progresses.\n\n    Note that it is up to the optimizer to call the fit handler correctly,\n    reporting all status changes and maintaining the 'done' flag.\n    "
__module__ = 'sas.sascalc.fit.AbstractFitEngine'
__weakref__

list of weak references to the object

abort()

Fit was aborted.

done = False

True when the fit job is complete

error(msg)

Model had an error; print traceback

finalize()

Fit is complete; best results are reported

improvement()

Called when a result is observed which is better than previous results from the fit.

result is a FitResult object, with parameters, #calls and fitness.

progress(current, expected)

Called each cycle of the fit, reporting the current and the expected amount of work. The meaning of these values is optimizer dependent, but they can be converted into a percent complete using (100*current)//expected.

Progress is updated each iteration of the fit, whatever that means for the particular optimization algorithm. It is called after any calls to improvement for the iteration so that the update handler can control I/O bandwidth by suppressing intermediate improvements until the fit is complete.

result = None

The current best result of the fit

set_result(result=None)
update_fit(last=False)
class sas.sascalc.fit.AbstractFitEngine.Model(sas_model, sas_data=None, **kw)

Bases: object

Fit wrapper for SAS models.

__call__(x)

Call self as a function.

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.AbstractFitEngine', '__doc__': '\n    Fit wrapper for SAS models.\n    ', '__init__': <function Model.__init__>, 'get_params': <function Model.get_params>, 'set_params': <function Model.set_params>, 'set': <function Model.set>, 'eval': <function Model.eval>, 'eval_derivs': <function Model.eval_derivs>, '__call__': <function Model.__call__>, '__dict__': <attribute '__dict__' of 'Model' objects>, '__weakref__': <attribute '__weakref__' of 'Model' objects>, '__annotations__': {}})
__doc__ = '\n    Fit wrapper for SAS models.\n    '
__init__(sas_model, sas_data=None, **kw)
Parameters:

sas_model – the sas model to wrap for fitting

__module__ = 'sas.sascalc.fit.AbstractFitEngine'
__weakref__

list of weak references to the object

eval(x)

Override eval method of model.

Parameters:

x – the x value used to compute a function

eval_derivs(x, pars=[])

Evaluate the model and derivatives wrt pars at x.

pars is a list of the names of the parameters for which derivatives are desired.

This method needs to be specialized in the model to evaluate the model function. Alternatively, the model can implement is own version of residuals which calculates the residuals directly instead of calling eval.

get_params(fitparams)

return a list of value of parameter to fit

Parameters:

fitparams – list of parameters name to fit

set(**kw)
set_params(paramlist, params)

Set value for parameters to fit

Parameters:

params – list of value for parameters to fit

sas.sascalc.fit.BumpsFitting module

BumpsFitting module runs the bumps optimizer.

class sas.sascalc.fit.BumpsFitting.BumpsFit

Bases: FitEngine

Fit a model using bumps.

__annotations__ = {}
__doc__ = '\n    Fit a model using bumps.\n    '
__init__()

Creates a dictionary (self.fit_arrange_dict={})of FitArrange elements with Uid as keys

__module__ = 'sas.sascalc.fit.BumpsFitting'
fit(msg_q=None, q=None, handler=None, curr_thread=None, ftol=1.49012e-08, reset_flag=False)
class sas.sascalc.fit.BumpsFitting.BumpsMonitor(handler, max_step, pars, dof)

Bases: object

__call__(history)

Call self as a function.

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.BumpsFitting', '__init__': <function BumpsMonitor.__init__>, 'config_history': <function BumpsMonitor.config_history>, '__call__': <function BumpsMonitor.__call__>, '__dict__': <attribute '__dict__' of 'BumpsMonitor' objects>, '__weakref__': <attribute '__weakref__' of 'BumpsMonitor' objects>, '__doc__': None, '__annotations__': {}})
__doc__ = None
__init__(handler, max_step, pars, dof)
__module__ = 'sas.sascalc.fit.BumpsFitting'
__weakref__

list of weak references to the object

config_history(history)
class sas.sascalc.fit.BumpsFitting.ConvergenceMonitor

Bases: object

ConvergenceMonitor contains population summary statistics to show progress of the fit. This is a list [ (best, 0%, 25%, 50%, 75%, 100%) ] or just a list [ (best, ) ] if population size is 1.

__call__(history)

Call self as a function.

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.BumpsFitting', '__doc__': '\n    ConvergenceMonitor contains population summary statistics to show progress\n    of the fit.  This is a list [ (best, 0%, 25%, 50%, 75%, 100%) ] or\n    just a list [ (best, ) ] if population size is 1.\n    ', '__init__': <function ConvergenceMonitor.__init__>, 'config_history': <function ConvergenceMonitor.config_history>, '__call__': <function ConvergenceMonitor.__call__>, '__dict__': <attribute '__dict__' of 'ConvergenceMonitor' objects>, '__weakref__': <attribute '__weakref__' of 'ConvergenceMonitor' objects>, '__annotations__': {}})
__doc__ = '\n    ConvergenceMonitor contains population summary statistics to show progress\n    of the fit.  This is a list [ (best, 0%, 25%, 50%, 75%, 100%) ] or\n    just a list [ (best, ) ] if population size is 1.\n    '
__init__()
__module__ = 'sas.sascalc.fit.BumpsFitting'
__weakref__

list of weak references to the object

config_history(history)
class sas.sascalc.fit.BumpsFitting.ParameterExpressions(models)

Bases: object

__call__()

Call self as a function.

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.BumpsFitting', '__init__': <function ParameterExpressions.__init__>, '_setup': <function ParameterExpressions._setup>, '__call__': <function ParameterExpressions.__call__>, '__getstate__': <function ParameterExpressions.__getstate__>, '__setstate__': <function ParameterExpressions.__setstate__>, '__dict__': <attribute '__dict__' of 'ParameterExpressions' objects>, '__weakref__': <attribute '__weakref__' of 'ParameterExpressions' objects>, '__doc__': None, '__annotations__': {}})
__doc__ = None
__getstate__()

Helper for pickle.

__init__(models)
__module__ = 'sas.sascalc.fit.BumpsFitting'
__setstate__(state)
__weakref__

list of weak references to the object

_setup()
class sas.sascalc.fit.BumpsFitting.Progress(history, max_step, pars, dof)

Bases: object

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.BumpsFitting', '__init__': <function Progress.__init__>, '__str__': <function Progress.__str__>, '__dict__': <attribute '__dict__' of 'Progress' objects>, '__weakref__': <attribute '__weakref__' of 'Progress' objects>, '__doc__': None, '__annotations__': {}})
__doc__ = None
__init__(history, max_step, pars, dof)
__module__ = 'sas.sascalc.fit.BumpsFitting'
__str__()

Return str(self).

__weakref__

list of weak references to the object

class sas.sascalc.fit.BumpsFitting.SasFitness(model, data, fitted=[], constraints={}, initial_values=None, **kw)

Bases: object

Wrap SAS model as a bumps fitness object

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.BumpsFitting', '__doc__': '\n    Wrap SAS model as a bumps fitness object\n    ', '__init__': <function SasFitness.__init__>, '_reset_pars': <function SasFitness._reset_pars>, '_define_pars': <function SasFitness._define_pars>, '_init_pars': <function SasFitness._init_pars>, 'set_fitted': <function SasFitness.set_fitted>, 'parameters': <function SasFitness.parameters>, 'update': <function SasFitness.update>, '_recalculate': <function SasFitness._recalculate>, 'numpoints': <function SasFitness.numpoints>, 'nllf': <function SasFitness.nllf>, 'theory': <function SasFitness.theory>, 'residuals': <function SasFitness.residuals>, '__dict__': <attribute '__dict__' of 'SasFitness' objects>, '__weakref__': <attribute '__weakref__' of 'SasFitness' objects>, '__annotations__': {}})
__doc__ = '\n    Wrap SAS model as a bumps fitness object\n    '
__init__(model, data, fitted=[], constraints={}, initial_values=None, **kw)
__module__ = 'sas.sascalc.fit.BumpsFitting'
__weakref__

list of weak references to the object

_define_pars()
_init_pars(kw)
_recalculate()
_reset_pars(names, values)
nllf()
numpoints()
parameters()
residuals()
set_fitted(param_list)

Flag a set of parameters as fitted parameters.

theory()
update()
sas.sascalc.fit.BumpsFitting.get_fitter()
sas.sascalc.fit.BumpsFitting.run_bumps(problem, handler, curr_thread)

sas.sascalc.fit.Loader module

class sas.sascalc.fit.Loader.Load(x=None, y=None, dx=None, dy=None)

Bases: object

This class is loading values from given file or value giving by the user

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.Loader', '__doc__': '\n    This class is loading values from given file or value giving by the user\n    ', '__init__': <function Load.__init__>, 'set_filename': <function Load.set_filename>, 'get_filename': <function Load.get_filename>, 'set_values': <function Load.set_values>, 'get_values': <function Load.get_values>, 'load_data': <function Load.load_data>, '__dict__': <attribute '__dict__' of 'Load' objects>, '__weakref__': <attribute '__weakref__' of 'Load' objects>, '__annotations__': {}})
__doc__ = '\n    This class is loading values from given file or value giving by the user\n    '
__init__(x=None, y=None, dx=None, dy=None)
__module__ = 'sas.sascalc.fit.Loader'
__weakref__

list of weak references to the object

get_filename()

return the file’s path

get_values()

Return x, y, dx, dy

load_data(data)

Return plottable

set_filename(path=None)

Store path into a variable.If the user doesn’t give a path as a parameter a pop-up window appears to select the file.

Parameters:

path – the path given by the user

set_values()

Store the values loaded from file in local variables

sas.sascalc.fit.MultiplicationModel module

class sas.sascalc.fit.MultiplicationModel.MultiplicationModel(p_model, s_model)

Bases: BaseComponent

Use for P(Q)*S(Q); function call must be in the order of P(Q) and then S(Q): The model parameters are combined from both models, P(Q) and S(Q), except 1) ‘radius_effective’ of S(Q) which will be calculated from P(Q) via calculate_ER(), and 2) ‘scale’ in P model which is synchronized w/ volfraction in S then P*S is multiplied by a new parameter, ‘scale_factor’. The polydispersion is applicable only to P(Q), not to S(Q).

Note

P(Q) refers to ‘form factor’ model while S(Q) does to ‘structure factor’.

__annotations__ = {}
__doc__ = "\n        Use for P(Q)\\*S(Q); function call must be in the order of P(Q) and then S(Q):\n        The model parameters are combined from both models, P(Q) and S(Q), except 1) 'radius_effective' of S(Q)\n        which will be calculated from P(Q) via calculate_ER(),\n        and 2) 'scale' in P model which is synchronized w/ volfraction in S\n        then P*S is multiplied by a new parameter, 'scale_factor'.\n        The polydispersion is applicable only to P(Q), not to S(Q).\n\n        .. note:: P(Q) refers to 'form factor' model while S(Q) does to 'structure factor'.\n    "
__init__(p_model, s_model)

Initialization

__module__ = 'sas.sascalc.fit.MultiplicationModel'
_clone(obj)

Internal utility function to copy the internal data members to a fresh copy.

_setParamHelper(name, value)

Helper function to setparam

_set_backgrounds()

Set component backgrounds to zero

_set_details()

Concatenate details of the two models to create this model’s details

_set_dispersion()

combine the two models’ dispersions. Polydispersity should not be applied to s_model

_set_fixed_params()

Fill the self.fixed list with the p_model fixed list

_set_params()

Concatenate the parameters of the two models to create these model parameters

_set_radius_effective()

Set effective radius to S(Q) model

_set_scale_factor()

Set scale=volfraction for P model

evalDistribution(x=[])

Evaluate the model in cartesian coordinates

Parameters:

x – input q[], or [qx[], qy[]]

Returns:

scattering function P(q[])

fill_description(p_model, s_model)

Fill the description for P(Q)*S(Q)

getProfile()

Get SLD profile of p_model if exists

Returns:

(r, beta) where r is a list of radius of the transition points beta is a list of the corresponding SLD values

Note

This works only for func_shell num = 2 (exp function).

run(x=0.0)

Evaluate the model

Parameters:

x – input q-value (float or [float, float] as [r, theta])

Returns:

(scattering function value)

runXY(x=0.0)

Evaluate the model

Parameters:

x – input q-value (float or [float, float] as [qx, qy])

Returns:

scattering function value

setParam(name, value)

Set the value of a model parameter

Parameters:
  • name – name of the parameter

  • value – value of the parameter

set_dispersion(parameter, dispersion)

Set the dispersion object for a model parameter

Parameters:

parameter – name of the parameter [string]

Dispersion:

dispersion object of type DispersionModel

sas.sascalc.fit.expression module

Parameter expression evaluator.

For systems in which constraints are expressed as string expressions rather than python code, compile_constraints() can construct an expression evaluator that substitutes the computed values of the expressions into the parameters.

The compiler requires a symbol table, an expression set and a context. The symbol table maps strings containing fully qualified names such as ‘M1.c[3].full_width’ to parameter objects with a ‘value’ property that can be queried and set. The expression set maps symbol names from the symbol table to string expressions. The context provides additional symbols for the expressions in addition to the usual mathematical functions and constants.

The expressions are compiled and interpreted by python, with only minimal effort to make sure that they don’t contain bad code. The resulting constraints function returns 0 so it can be used directly in a fit problem definition.

Extracting the symbol table from the model depends on the structure of the model. If fitness.parameters() is set correctly, then this should simply be a matter of walking the parameter data, remembering the path to each parameter in the symbol table. For compactness, dictionary elements should be referenced by .name rather than [“name”]. Model name can be used as the top level.

Getting the parameter expressions applied correctly is challenging. The following monkey patch works by overriding model_update in FitProblem so that after setp(p) is called and, the constraints expression can be applied before telling the underlying fitness function that the model is out of date:

# Override model update so that parameter constraints are applied
problem._model_update = problem.model_update
def model_update():
    constraints()
    problem._model_update()
problem.model_update = model_update

Ideally, this interface will change

class sas.sascalc.fit.expression._Parameter(value=0)

Bases: object

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.expression', '__init__': <function _Parameter.__init__>, '__dict__': <attribute '__dict__' of '_Parameter' objects>, '__weakref__': <attribute '__weakref__' of '_Parameter' objects>, '__doc__': None, '__annotations__': {}})
__doc__ = None
__init__(value=0)
__module__ = 'sas.sascalc.fit.expression'
__weakref__

list of weak references to the object

sas.sascalc.fit.expression._check(msg, pairs)

Verify that the list n contains the given items, and that the list satisfies the partial ordering given by the pairs in partial order.

sas.sascalc.fit.expression._check_free_variables(target, expr, symbol_table, html=False)
sas.sascalc.fit.expression._check_syntax(target, expr, html=False)
sas.sascalc.fit.expression._compile_constraints(symtab, exprs, context={}, html=False)
sas.sascalc.fit.expression._dependent_symbols(expr, symtab)

Given an expression string and a symbol table, return the set of symbols used in the expression. Symbols are only returned once even if they occur multiple times. The return value is a set with the elements in no particular order. Returns a set containing None if no dependencies (as needed by order_dependencies).

This is the first step in computing a dependency graph.

sas.sascalc.fit.expression._find_dependencies(symtab, exprs)

Returns a list of pair-wise dependencies from the parameter expressions.

symtab gives the {‘parameter’: value} table of available parameters.

exprs gives the {‘parameter’: ‘expr’} table of parameter expressions.

For example, if p3 = p1+p2, then find_dependencies([p1, p2, p3]) will return [(‘p3’, ‘p1’), (‘p3’, ‘p2’)]. For base expressions without dependencies, such as p4 = 2*pi, this should return [(‘p4’, None)].

sas.sascalc.fit.expression._parameter_mapping(pairs)

Find the parameter substitution we need so that expressions can be evaluated without having to traverse a chain of model.layer.parameter.value

sas.sascalc.fit.expression._substitute(expr, mapping)

Replace all occurrences of symbol s with mapping[s] for s in mapping.

sas.sascalc.fit.expression._symbols(expr)
sas.sascalc.fit.expression.check_constraints(symtab, exprs, context={}, html=False)

Returns a list of errors in exprs or the empty list if there are none. If the html flag is set to True, the list elements will have html <b> markups that allow the caller to control rendering:

Unknown symbol: tags unknown symbols in exprs Syntax error: tags the beginning of a syntax error in exprs Cyclic dependency: tags comma separated parameters that have cyclic dependency

All symbols must exist in context or in symtab. The symbols in context should be constants or functions. The symbols in symtab can be constants or parameter objects with a value attribute.

It first runs compile_constraints(), returning a list of errors if any. If there are no errors it runs the compiled constraints function, returning any errors it produces. Any parameters in symtab are copied with a shallow copy so they aren’t overridden when the constraints are run.

sas.sascalc.fit.expression.compile_constraints(symtab, exprs, context={})

Build and return a function to evaluate all parameter expressions in the proper order.

Input:

symtab is the symbol table for the model: { ‘name’: parameter }

exprs is the set of computed symbols: { ‘name’: ‘expression’ }

context is any additional context needed to evaluate the expression

Return:

updater function which sets parameter.value for each expression

Raises:

RunTimeError if any expression contains a syntax error, if any symbol used is not defined, or if there are circular dependencies between symbols. Runtime error argument is a string describing all found errors.

This function is not terribly sophisticated, and it would be easy to trick. However it handles the common cases cleanly and generates reasonable messages for the common errors.

This code has not been fully audited for security. While we have removed the builtins and the ability to import modules, there may be other vectors for users to perform more than simple function evaluations. Unauthenticated users should not be running this code.

Parameter names are assumed to contain only _.a-zA-Z0-9#[]

Both names are provided for inverse functions, e.g., acos and arccos.

Should try running the function to identify syntax errors before running it in a fit.

Use help(fn) to see the code generated for the returned function fn. dis.dis(fn) will show the corresponding python vm instructions.

sas.sascalc.fit.expression.iskeyword()

x.__contains__(y) <==> y in x.

sas.sascalc.fit.expression.no_constraints()

This parameter set has no constraints between the parameters.

sas.sascalc.fit.expression.order_dependencies(pairs)

Order elements from pairs so that b comes before a in the ordered list for all pairs (a, b).

sas.sascalc.fit.expression.standard_symbols(context={})
sas.sascalc.fit.expression.test_deps()
sas.sascalc.fit.expression.test_expr()

sas.sascalc.fit.models module

Utilities to manage models

class sas.sascalc.fit.models.ModelManager

Bases: object

manage the list of available models

__annotations__ = {}
__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.models', '__doc__': '\n    manage the list of available models\n    ', 'base': None, '__init__': <function ModelManager.__init__>, 'cat_model_list': <function ModelManager.cat_model_list>, 'update': <function ModelManager.update>, 'plugins_reset': <function ModelManager.plugins_reset>, 'get_model_list': <function ModelManager.get_model_list>, 'composable_models': <function ModelManager.composable_models>, 'get_model_dictionary': <function ModelManager.get_model_dictionary>, '__dict__': <attribute '__dict__' of 'ModelManager' objects>, '__weakref__': <attribute '__weakref__' of 'ModelManager' objects>, '__annotations__': {'base': 'ModelManagerBase()'}})
__doc__ = '\n    manage the list of available models\n    '
__init__()
__module__ = 'sas.sascalc.fit.models'
__weakref__

list of weak references to the object

base: <sas.sascalc.fit.models.ModelManagerBase object at 0x00000210565A8E10> = None
cat_model_list()
composable_models()
get_model_dictionary()
get_model_list()
plugins_reset()
update()
class sas.sascalc.fit.models.ModelManagerBase

Bases: object

Base class for the model manager

__annotations__ = {}
__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.models', '__doc__': '\n    Base class for the model manager\n    ', 'model_dictionary': None, 'standard_models': None, 'plugin_models': None, 'last_time_dir_modified': 0, '__init__': <function ModelManagerBase.__init__>, '_is_plugin_dir_changed': <function ModelManagerBase._is_plugin_dir_changed>, 'composable_models': <function ModelManagerBase.composable_models>, 'plugins_update': <function ModelManagerBase.plugins_update>, 'plugins_reset': <function ModelManagerBase.plugins_reset>, 'get_model_list': <function ModelManagerBase.get_model_list>, '__dict__': <attribute '__dict__' of 'ModelManagerBase' objects>, '__weakref__': <attribute '__weakref__' of 'ModelManagerBase' objects>, '__annotations__': {'model_dictionary': 'Dict[str, Model]', 'standard_models': 'Dict[str, Model]', 'plugin_models': 'Dict[str, Model]', 'last_time_dir_modified': 'int'}})
__doc__ = '\n    Base class for the model manager\n    '
__init__()
__module__ = 'sas.sascalc.fit.models'
__weakref__

list of weak references to the object

_is_plugin_dir_changed()

check the last time the plugin dir has changed and return true is the directory was modified else return false

composable_models()

return list of standard models that can be used in sum/multiply

get_model_list()

return dictionary of classified models

Structure Factors are the structure factor models Multi-Functions are the multiplicity models Plugin Models are the plugin models

Note that a model can be both a plugin and a structure factor or multiplicity model.

last_time_dir_modified: int = 0

timestamp on the plugin directory at the last plugin update

model_dictionary: Dict[str, Model] = None

mutable dictionary of models, continually updated to reflect the current set of plugins

plugin_models: Dict[str, Model] = None

list of plugin models reset each time the plugin directory is queried

plugins_reset()

return a dictionary of model

plugins_update()

return a dictionary of model if new models were added else return empty dictionary

standard_models: Dict[str, Model] = None

constant list of standard models

class sas.sascalc.fit.models.ReportProblem

Bases: object

Class to check for problems with specific values

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.models', '__doc__': '\n    Class to check for problems with specific values\n    ', '__nonzero__': <function ReportProblem.__nonzero__>, '__dict__': <attribute '__dict__' of 'ReportProblem' objects>, '__weakref__': <attribute '__weakref__' of 'ReportProblem' objects>, '__annotations__': {}})
__doc__ = '\n    Class to check for problems with specific values\n    '
__module__ = 'sas.sascalc.fit.models'
__nonzero__()
__weakref__

list of weak references to the object

sas.sascalc.fit.models._check_plugin(model, name)

Do some checking before model adding plugins in the list

Parameters:
  • model – class model to add into the plugin list

  • name – name of the module plugin

Return model:

model if valid model or None if not valid

sas.sascalc.fit.models.compile_file(dir)

Compile a py file

sas.sascalc.fit.models.find_plugin_models()

Find custom models

sas.sascalc.fit.models.find_plugins_dir()

Find path of the plugins directory. The plugin directory is located in the user’s home directory.

sas.sascalc.fit.models.initialize_plugins_dir(path)
sas.sascalc.fit.models.plugin_log(message)

Log a message in a file located in the user’s home directory

sas.sascalc.fit.pagestate module

Class that holds a fit page state

class sas.sascalc.fit.pagestate.PageState(model=None, data=None)

Bases: object

Contains information to reconstruct a page of the fitpanel.

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.pagestate', '__doc__': '\n    Contains information to reconstruct a page of the fitpanel.\n    ', '__init__': <function PageState.__init__>, 'clone': <function PageState.clone>, '_old_first_model': <function PageState._old_first_model>, 'param_remap_to_sasmodels_convert': <staticmethod(<function PageState.param_remap_to_sasmodels_convert>)>, 'param_remap_from_sasmodels_convert': <staticmethod(<function PageState.param_remap_from_sasmodels_convert>)>, '_convert_to_sasmodels': <function PageState._convert_to_sasmodels>, '_repr_helper': <function PageState._repr_helper>, '__repr__': <function PageState.__repr__>, '_get_report_string': <function PageState._get_report_string>, '_check_html_format': <function PageState._check_html_format>, 'report': <function PageState.report>, '_to_xml_helper': <function PageState._to_xml_helper>, 'to_xml': <function PageState.to_xml>, '_from_xml_helper': <function PageState._from_xml_helper>, 'from_xml': <function PageState.from_xml>, '__dict__': <attribute '__dict__' of 'PageState' objects>, '__weakref__': <attribute '__weakref__' of 'PageState' objects>, '__annotations__': {}})
__doc__ = '\n    Contains information to reconstruct a page of the fitpanel.\n    '
__init__(model=None, data=None)

Initialize the current state

Parameters:
  • model – a selected model within a page

  • data

__module__ = 'sas.sascalc.fit.pagestate'
__repr__()

output string for printing

__weakref__

list of weak references to the object

_check_html_format(name)

Check string ‘%’ for html format

_convert_to_sasmodels()

Convert parameters to a form usable by sasmodels converter

Returns:

None

_from_xml_helper(node, list)

Helper function to write state to xml

_get_report_string()

Get the values (strings) from __str__ for report

_old_first_model()

Handle save states from 4.0.1 and before where the first item in the selection boxes of category, formfactor and structurefactor were not saved. :return: None

_repr_helper(list, rep)

Helper method to print a state

_to_xml_helper(thelist, element, newdoc)

Helper method to create xml file for saving state

clone()

Create a new copy of the current object

from_xml(file=None, node=None)

Load fitting state from a file

Parameters:
  • file – .fitv file

  • node – node of a XML document to read from

static param_remap_from_sasmodels_convert(params)

Converts {name : value} map back to [] param list :param params: parameter map returned from sasmodels :return: None

static param_remap_to_sasmodels_convert(params, is_string=False)

Remaps the parameters for sasmodels conversion

Parameters:

params – list of parameters (likely self.parameters)

Returns:

remapped dictionary of parameters

report(fig_urls)

Invoke report dialog panel

: param figs: list of pylab figures [list]

to_xml(file='fitting_state.fitv', doc=None, entry_node=None, batch_fit_state=None)

Writes the state of the fit panel to file, as XML.

Compatible with standalone writing, or appending to an already existing XML document. In that case, the XML document is required. An optional entry node in the XML document may also be given.

Parameters:
  • file – file to write to

  • doc – XML document object [optional]

  • entry_node – XML node within the XML document at which we will append the data [optional]

  • batch_fit_state – simultaneous fit state

class sas.sascalc.fit.pagestate.Reader(call_back=None, cansas=True)

Bases: Reader

Class to load a .fitv fitting file

__annotations__ = {}
__doc__ = '\n    Class to load a .fitv fitting file\n    '
__init__(call_back=None, cansas=True)
__module__ = 'sas.sascalc.fit.pagestate'
_parse_save_state_entry(dom)

Parse a SASentry

Parameters:

node – SASentry node

Returns:

Data1D/Data2D object

_parse_simfit_state(entry)

Parses the saved data for a simultaneous fit :param entry: XML object to read from :return: XML object for a simultaneous fit or None

_parse_state(entry)

Read a fit result from an XML node

Parameters:

entry – XML node to read from

Returns:

PageState object

_read_cansas(path)

Load data and fitting information from a CanSAS XML file.

Parameters:

path – file path

Returns:

Data1D object if a single SASentry was found, or a list of Data1D objects if multiple entries were found, or None of nothing was found

Raises:
  • RuntimeError – when the file can’t be opened

  • ValueError – when the length of the data vectors are inconsistent

ext = ['.fitv', '.FITV', '.svs', 'SVS']
get_state()
read(path)

Load a new P(r) inversion state from file

Parameters:

path – file path

type = ['Fitting files (*.fitv)|*.fitvSASView file (*.svs)|*.svs']
type_name = 'Fitting'
write(filename, datainfo=None, fitstate=None)

Write the content of a Data1D as a CanSAS XML file only for standalone

Parameters:
  • filename – name of the file to write

  • datainfo – Data1D object

  • fitstate – PageState object

write_toXML(datainfo=None, state=None, batchfit=None)

Write toXML, a helper for write(), could be used by guimanager._on_save()

: return: xml doc

class sas.sascalc.fit.pagestate.SimFitPageState

Bases: object

State of the simultaneous fit page for saving purposes

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.pagestate', '__doc__': '\n    State of the simultaneous fit page for saving purposes\n    ', '__init__': <function SimFitPageState.__init__>, '__repr__': <function SimFitPageState.__repr__>, '__dict__': <attribute '__dict__' of 'SimFitPageState' objects>, '__weakref__': <attribute '__weakref__' of 'SimFitPageState' objects>, '__annotations__': {}})
__doc__ = '\n    State of the simultaneous fit page for saving purposes\n    '
__init__()
__module__ = 'sas.sascalc.fit.pagestate'
__repr__()

Return repr(self).

__weakref__

list of weak references to the object

sas.sascalc.fit.pagestate.parse_entry_helper(node, item)

Create a numpy list from value extrated from the node

Parameters:
  • node – node from each the value is stored

  • item – list name of three strings.the two first are name of data attribute and the third one is the type of the value of that attribute. type can be string, float, bool, etc.

: return: numpy array

sas.sascalc.fit.pluginmodel module

class sas.sascalc.fit.pluginmodel.Model1DPlugin(name='Plugin Model')

Bases: BaseComponent

__annotations__ = {}
__doc__ = None
__init__(name='Plugin Model')

Initialization

__module__ = 'sas.sascalc.fit.pluginmodel'
function(x)

Function to be implemented by the plug-in writer

is_multiplicity_model = False
run(x=0.0)

Evaluate the model

Parameters:

x – input x, or [x, phi] [radian]

Returns:

function value

runXY(x=0.0)

Evaluate the model

Parameters:

x – input x, or [x, y]

Returns:

function value

set_details()

Set default details

sas.sascalc.fit.qsmearing module

Handle Q smearing

class sas.sascalc.fit.qsmearing.PySmear(resolution, model, offset=None)

Bases: object

Wrapper for pure python sasmodels resolution functions.

__call__(iq_in, first_bin=0, last_bin=None)

Apply the resolution function to the data. Note that this is called with iq_in matching data.x, but with iq_in[first_bin:last_bin] set to theory values for these bins, and the remainder left undefined. The first_bin, last_bin values should be those returned from get_bin_range. The returned value is of the same length as iq_in, with the range first_bin:last_bin set to the resolution smeared values.

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.qsmearing', '__doc__': '\n    Wrapper for pure python sasmodels resolution functions.\n    ', '__init__': <function PySmear.__init__>, 'apply': <function PySmear.apply>, '__call__': <function PySmear.apply>, 'get_bin_range': <function PySmear.get_bin_range>, '__dict__': <attribute '__dict__' of 'PySmear' objects>, '__weakref__': <attribute '__weakref__' of 'PySmear' objects>, '__annotations__': {}})
__doc__ = '\n    Wrapper for pure python sasmodels resolution functions.\n    '
__init__(resolution, model, offset=None)
__module__ = 'sas.sascalc.fit.qsmearing'
__weakref__

list of weak references to the object

apply(iq_in, first_bin=0, last_bin=None)

Apply the resolution function to the data. Note that this is called with iq_in matching data.x, but with iq_in[first_bin:last_bin] set to theory values for these bins, and the remainder left undefined. The first_bin, last_bin values should be those returned from get_bin_range. The returned value is of the same length as iq_in, with the range first_bin:last_bin set to the resolution smeared values.

get_bin_range(q_min=None, q_max=None)

For a given q_min, q_max, find the corresponding indices in the data. Returns first, last. Note that these are indexes into q from the data, not the q_calc needed by the resolution function. Note also that these are the indices, not the range limits. That is, the complete range will be q[first:last+1].

class sas.sascalc.fit.qsmearing.PySmear2D(data=None, model=None)

Bases: object

Q smearing class for SAS 2d pinhole data

__dict__ = mappingproxy({'__module__': 'sas.sascalc.fit.qsmearing', '__doc__': '\n    Q smearing class for SAS 2d pinhole data\n    ', '__init__': <function PySmear2D.__init__>, 'set_accuracy': <function PySmear2D.set_accuracy>, 'set_smearer': <function PySmear2D.set_smearer>, 'set_data': <function PySmear2D.set_data>, 'set_model': <function PySmear2D.set_model>, 'set_index': <function PySmear2D.set_index>, 'get_value': <function PySmear2D.get_value>, '__dict__': <attribute '__dict__' of 'PySmear2D' objects>, '__weakref__': <attribute '__weakref__' of 'PySmear2D' objects>, '__annotations__': {}})
__doc__ = '\n    Q smearing class for SAS 2d pinhole data\n    '
__init__(data=None, model=None)
__module__ = 'sas.sascalc.fit.qsmearing'
__weakref__

list of weak references to the object

get_value()

Over sampling of r_nbins times phi_nbins, calculate Gaussian weights, then find smeared intensity

set_accuracy(accuracy='Low')

Set accuracy.

Parameters:

accuracy – string

set_data(data=None)

Set data.

Parameters:

data – DataLoader.Data_info type

set_index(index=None)

Set index.

Parameters:

index – 1d arrays

set_model(model=None)

Set model.

Parameters:

model – sas.models instance

set_smearer(smearer=True)

Set whether or not smearer will be used

Parameters:

smearer – smear object

sas.sascalc.fit.qsmearing.pinhole_smear(data, model=None)
sas.sascalc.fit.qsmearing.slit_smear(data, model=None)
sas.sascalc.fit.qsmearing.smear_selection(data, model=None)

Creates the right type of smearer according to the data. The canSAS format has a rule that either slit smearing data OR resolution smearing data is available.

For the present purpose, we choose the one that has none-zero data. If both slit and resolution smearing arrays are filled with good data (which should not happen), then we choose the resolution smearing data.

Parameters:
  • data – Data1D object

  • model – sas.model instance

Module contents