31. Sasview interface¶
sasmodels.sasview_model¶
Sasview model constructor.
Given a module defining an OpenCL kernel such as sasmodels.models.cylinder, create a sasview model class to run that kernel as follows:
from sasmodels.sasview_model import load_custom_model
CylinderModel = load_custom_model('sasmodels/models/cylinder.py')
- sasmodels.sasview_model.MODELS: dict[str, Callable[[int], SasviewModel]] = {}¶
set of defined models (standard and custom)
- sasmodels.sasview_model.MODEL_BY_PATH: dict[str, Callable[[int], SasviewModel]] = {}¶
custom model {path: model} mapping so we can check timestamps
- sasmodels.sasview_model.MultiplicationModel(form_factor: SasviewModel, structure_factor: SasviewModel) SasviewModel¶
Returns a constructed product model from form_factor and structure_factor.
- class sasmodels.sasview_model.MultiplicityInfo(number, control, choices, x_axis_label)¶
Bases:
tuple- __add__(value, /)¶
Return self+value.
- __class__¶
alias of
type
- classmethod __class_getitem__()¶
See PEP 585
- __contains__(key, /)¶
Return key in self.
- __delattr__(name, /)¶
Implement delattr(self, name).
- __dir__()¶
Default dir() implementation.
- __doc__ = 'MultiplicityInfo(number, control, choices, x_axis_label)'¶
- __eq__(value, /)¶
Return self==value.
- __format__(format_spec, /)¶
Default object formatter.
- __ge__(value, /)¶
Return self>=value.
- __getattribute__(name, /)¶
Return getattr(self, name).
- __getitem__(key, /)¶
Return self[key].
- __getnewargs__()¶
Return self as a plain tuple. Used by copy and pickle.
- __getstate__()¶
Helper for pickle.
- __gt__(value, /)¶
Return self>value.
- __hash__()¶
Return hash(self).
- __init__()¶
- classmethod __init_subclass__()¶
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
- __iter__()¶
Implement iter(self).
- __le__(value, /)¶
Return self<=value.
- __len__()¶
Return len(self).
- __lt__(value, /)¶
Return self<value.
- __match_args__ = ('number', 'control', 'choices', 'x_axis_label')¶
- __module__ = 'sasmodels.sasview_model'¶
- __mul__(value, /)¶
Return self*value.
- __ne__(value, /)¶
Return self!=value.
- static __new__(_cls, number, control, choices, x_axis_label)¶
Create new instance of MultiplicityInfo(number, control, choices, x_axis_label)
- __reduce__()¶
Helper for pickle.
- __reduce_ex__(protocol, /)¶
Helper for pickle.
- __repr__()¶
Return a nicely formatted representation string
- __rmul__(value, /)¶
Return value*self.
- __setattr__(name, value, /)¶
Implement setattr(self, name, value).
- __sizeof__()¶
Size of object in memory, in bytes.
- __slots__ = ()¶
- __str__()¶
Return str(self).
- classmethod __subclasshook__()¶
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
- _asdict()¶
Return a new dict which maps field names to their values.
- _field_defaults = {}¶
- _fields = ('number', 'control', 'choices', 'x_axis_label')¶
- classmethod _make(iterable)¶
Make a new MultiplicityInfo object from a sequence or iterable
- _replace(**kwds)¶
Return a new MultiplicityInfo object replacing specified fields with new values
- choices¶
Alias for field number 2
- control¶
Alias for field number 1
- count(value, /)¶
Return number of occurrences of value.
- index(value, start=0, stop=9223372036854775807, /)¶
Return first index of value.
Raises ValueError if the value is not present.
- number¶
Alias for field number 0
- x_axis_label¶
Alias for field number 3
- sasmodels.sasview_model.MultiplicityInfoType¶
alias of
MultiplicityInfo
- sasmodels.sasview_model.SUPPORT_OLD_STYLE_PLUGINS = True¶
True if pre-existing plugins, with the old names and parameters, should continue to be supported.
- class sasmodels.sasview_model.SasviewModel(multiplicity: int | None = None)¶
Bases:
objectSasview wrapper for opencl/ctypes model.
- __class__¶
alias of
type
- __delattr__(name, /)¶
Implement delattr(self, name).
- __dict__ = mappingproxy({'__module__': 'sasmodels.sasview_model', '__doc__': '\n Sasview wrapper for opencl/ctypes model.\n ', '_model': None, '_model_info': None, 'id': None, 'name': None, 'description': None, 'category': None, 'orientation_params': None, 'magnetic_params': None, 'fixed': None, 'input_name': 'Q', 'input_unit': 'A^{-1}', 'output_name': 'Intensity', 'output_unit': 'cm^{-1}', 'cutoff': 1e-05, 'non_fittable': (), 'is_structure_factor': False, 'is_form_factor': False, 'is_multiplicity_model': False, 'multiplicity_info': None, 'params': None, 'dispersion': None, 'details': None, 'multiplicity': None, '_persistency_dict': None, '__init__': <function SasviewModel.__init__>, '__get_state__': <function SasviewModel.__get_state__>, '__set_state__': <function SasviewModel.__set_state__>, '__str__': <function SasviewModel.__str__>, 'is_fittable': <function SasviewModel.is_fittable>, 'getProfile': <function SasviewModel.getProfile>, 'setParam': <function SasviewModel.setParam>, 'getParam': <function SasviewModel.getParam>, 'getParamList': <function SasviewModel.getParamList>, 'getDispParamList': <function SasviewModel.getDispParamList>, 'clone': <function SasviewModel.clone>, 'run': <function SasviewModel.run>, 'runXY': <function SasviewModel.runXY>, 'evalDistribution': <function SasviewModel.evalDistribution>, 'calc_composition_models': <function SasviewModel.calc_composition_models>, 'calculate_Iq': <function SasviewModel.calculate_Iq>, '_calculate_Iq': <function SasviewModel._calculate_Iq>, 'calculate_ER': <function SasviewModel.calculate_ER>, 'calculate_VR': <function SasviewModel.calculate_VR>, 'set_dispersion': <function SasviewModel.set_dispersion>, '_dispersion_mesh': <function SasviewModel._dispersion_mesh>, '_get_weights': <function SasviewModel._get_weights>, 'runTests': <classmethod(<function SasviewModel.runTests>)>, '__dict__': <attribute '__dict__' of 'SasviewModel' objects>, '__weakref__': <attribute '__weakref__' of 'SasviewModel' objects>, '__annotations__': {'_model': 'KernelModel', '_model_info': 'ModelInfo', 'id': 'str', 'name': 'str', 'description': 'str', 'category': 'str', 'orientation_params': 'list[str]', 'magnetic_params': 'list[str]', 'fixed': 'list[str]', 'non_fittable': 'Sequence[str]', 'multiplicity_info': 'MultiplicityInfoType', 'params': 'dict[str, float]', 'dispersion': 'dict[str, Any]', 'details': 'dict[str, Sequence[Any]]', 'multiplicity': 'Optional[int]', '_persistency_dict': 'dict[str, tuple[np.ndarray, np.ndarray]]'}})¶
- __dir__()¶
Default dir() implementation.
- __doc__ = '\n Sasview wrapper for opencl/ctypes model.\n '¶
- __eq__(value, /)¶
Return self==value.
- __format__(format_spec, /)¶
Default object formatter.
- __ge__(value, /)¶
Return self>=value.
- __getattribute__(name, /)¶
Return getattr(self, name).
- __getstate__()¶
Helper for pickle.
- __gt__(value, /)¶
Return self>value.
- __hash__()¶
Return hash(self).
- __init__(multiplicity: int | None = None) None¶
- classmethod __init_subclass__()¶
This method is called when a class is subclassed.
The default implementation does nothing. It may be overridden to extend subclasses.
- __le__(value, /)¶
Return self<=value.
- __lt__(value, /)¶
Return self<value.
- __module__ = 'sasmodels.sasview_model'¶
- __ne__(value, /)¶
Return self!=value.
- classmethod __new__(*args, **kwargs)¶
- __reduce__()¶
Helper for pickle.
- __reduce_ex__(protocol, /)¶
Helper for pickle.
- __repr__()¶
Return repr(self).
- __setattr__(name, value, /)¶
Implement setattr(self, name, value).
- __sizeof__()¶
Size of object in memory, in bytes.
- __str__() str¶
- Returns:
string representation
- classmethod __subclasshook__()¶
Abstract classes can override this to customize issubclass().
This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached).
- __weakref__¶
list of weak references to the object
- _calculate_Iq(qx, qy=None)¶
- _dispersion_mesh() list[tuple[ndarray, ndarray]]¶
Create a mesh grid of dispersion parameters and weights.
Returns [p1,p2,…],w where pj is a vector of values for parameter j and w is a vector containing the products for weights for each parameter set in the vector.
- _model: KernelModel = None¶
- _persistency_dict: dict[str, tuple[ndarray, ndarray]] = None¶
memory for polydispersity array if using ArrayDispersion (used by sasview).
- calc_composition_models(qx)¶
returns parts of the composition model or None if not a composition model.
- calculate_ER(mode: int = 1) float¶
Calculate the effective radius for P(q)*S(q)
mode is the R_eff type, which defaults to 1 to match the ER calculation for sasview models from version 3.x.
- Returns:
the value of the effective radius
- calculate_Iq(qx: Sequence[float], qy: Sequence[float] | None = None) tuple[ndarray, Callable[[], OrderedDict[str, ndarray]]]¶
Calculate Iq for one set of q with the current parameters.
If the model is 1D, use q. If 2D, use qx, qy.
This should NOT be used for fitting since it copies the q vectors to the card for each evaluation.
The returned tuple contains the scattering intensity followed by a callable which returns a dictionary of intermediate data from ProductKernel.
- calculate_VR() float¶
Calculate the volf ratio for P(q)*S(q)
- Returns:
the value of the form:shell volume ratio
- category: str = None¶
default model category
- clone() SasviewModel¶
Return a identical copy of self
- cutoff = 1e-05¶
default cutoff for polydispersity
- description: str = None¶
short model description
- evalDistribution(qdist: ndarray | tuple[ndarray, ndarray] | list[ndarray]) ndarray¶
Evaluate a distribution of q-values.
- Parameters:
qdist – array of q or a list of arrays [qx,qy]
For 1D, a numpy array is expected as input
evalDistribution(q) where *q* is a numpy array.
For 2D, a list of [qx,qy] is expected with 1D arrays as input
qx = [ qx[0], qx[1], qx[2], ....] qy = [ qy[0], qy[1], qy[2], ....]
If the model is 1D only, then
\[q = \sqrt{q_x^2+q_y^2}\]
- fixed: list[str] = None¶
names of the fittable parameters
- getDispParamList() Sequence[str]¶
Return a list of polydispersity parameters for the model
- getParam(name: str) float¶
Set the value of a model parameter
- Parameters:
name – name of the parameter
- getParamList() Sequence[str]¶
Return a list of all available parameters for the model
- getProfile() tuple[ndarray, ndarray]¶
Get SLD profile
- : return: (z, beta) where z is a list of depth of the transition points
beta is a list of the corresponding SLD values
- id: str = None¶
load/save name for the model
- input_name = 'Q'¶
- input_unit = 'A^{-1}'¶
- is_fittable(par_name: str) bool¶
Check if a given parameter is fittable or not
- Parameters:
par_name – the parameter name to check
- is_form_factor = False¶
True if model should appear as a form factor
- is_multiplicity_model = False¶
True if model has multiplicity
- is_structure_factor = False¶
True if model should appear as a structure factor
- magnetic_params: list[str] = None¶
names of the magnetic parameters in the order they appear
- multiplicity: int | None = None¶
multiplicity value, or None if no multiplicity on the model
- multiplicity_info: MultiplicityInfo = None¶
Multiplicity information
- name: str = None¶
display name for the model
- non_fittable: Sequence[str] = ()¶
parameters that are not fitted
- orientation_params: list[str] = None¶
names of the orientation parameters in the order they appear
- output_name = 'Intensity'¶
- output_unit = 'cm^{-1}'¶
- params: dict[str, float] = None¶
parameter {name: value} mapping
- run(x: float | tuple[float, float] | Sequence[float] = 0.0) float¶
Evaluate the model
- Parameters:
x – input q, or [q,phi]
- Returns:
scattering function P(q)
DEPRECATED: use calculate_Iq instead
- classmethod runTests()¶
Run any tests built into the model and captures the test output.
Returns success flag and output
- runXY(x: float | [<class 'float'>, <class 'float'>] | ~collections.abc.Sequence[float] = 0.0) float¶
Evaluate the model in cartesian coordinates
- Parameters:
x – input q, or [qx, qy]
- Returns:
scattering function P(q)
DEPRECATED: use calculate_Iq instead
- setParam(name: str, value: float) None¶
Set the value of a model parameter
- Parameters:
name – name of the parameter
value – value of the parameter
- set_dispersion(parameter: str, dispersion: Dispersion) None¶
Set the dispersion object for a model parameter
- Parameters:
parameter – name of the parameter [string]
dispersion – dispersion object of type Dispersion
- sasmodels.sasview_model._CACHED_MODULE: dict[str, ModuleType] = {}¶
Track modules that we have loaded so we can determine whether the model has changed since we last reloaded.
- sasmodels.sasview_model._generate_model_attributes(model_info: ModelInfo) dict[str, Any]¶
Generate the class attributes for the model.
This should include all the information necessary to query the model details so that you do not need to instantiate a model to query it.
All the attributes should be immutable to avoid accidents.
- sasmodels.sasview_model._make_standard_model(name: str) Callable[[int], SasviewModel]¶
Load the sasview model defined by name.
name can be a standard model name or a path to a custom model.
Returns a class that can be used directly as a sasview model.
- sasmodels.sasview_model._register_old_models() None¶
Place the new models into sasview under the old names.
Monkey patch sas.sascalc.fit as sas.models so that sas.models.pluginmodel is available to the plugin modules.
- sasmodels.sasview_model.find_model(modelname: str) Callable[[int], SasviewModel]¶
Find a model by name. If the model name ends in py, try loading it from custom models, otherwise look for it in the list of builtin models.
- sasmodels.sasview_model.load_custom_model(path: str) Callable[[int], SasviewModel]¶
Load a custom model given the model path.
- sasmodels.sasview_model.load_standard_models() list[Callable[[int], SasviewModel]]¶
Load and return the list of predefined models.
If there is an error loading a model, then a traceback is logged and the model is not returned.
- sasmodels.sasview_model.magnetic_demo()¶
Demostrate call to magnetic model.
- sasmodels.sasview_model.make_model_from_info(model_info: ModelInfo) Callable[[int], SasviewModel]¶
Convert model_info into a SasView model wrapper.
- sasmodels.sasview_model.reset_environment() None¶
Clear the compute engine context so that the GUI can change devices.
This removes all compiled kernels, even those that are active on fit pages, but they will be restored the next time they are needed.
- sasmodels.sasview_model.test_cylinder() float¶
Test that the cylinder model runs, returning the value at [0.1,0.1].
- sasmodels.sasview_model.test_empty_distribution() None¶
Make sure that sasmodels returns NaN when there are no polydispersity points
- sasmodels.sasview_model.test_model_list() None¶
Make sure that all models build as sasview models
- sasmodels.sasview_model.test_old_name() None¶
Load and run cylinder model as sas.models.CylinderModel
- sasmodels.sasview_model.test_product() float¶
Test that 2-D hardsphere model runs and doesn’t produce NaN.
- sasmodels.sasview_model.test_rpa() float¶
Test that the 2-D RPA model runs
- sasmodels.sasview_model.test_structure_factor() float¶
Test that 2-D hardsphere model runs and doesn’t produce NaN.
- sasmodels.sasview_model.test_structure_factor_background() None¶
Check that sasview model and direct model match, with background=0.