[87985ca] | 1 | """ |
---|
| 2 | Sasview model constructor. |
---|
| 3 | |
---|
| 4 | Given a module defining an OpenCL kernel such as sasmodels.models.cylinder, |
---|
| 5 | create a sasview model class to run that kernel as follows:: |
---|
| 6 | |
---|
[92d38285] | 7 | from sasmodels.sasview_model import load_custom_model |
---|
| 8 | CylinderModel = load_custom_model('sasmodels/models/cylinder.py') |
---|
[87985ca] | 9 | """ |
---|
[4d76711] | 10 | from __future__ import print_function |
---|
[87985ca] | 11 | |
---|
[ce27e21] | 12 | import math |
---|
| 13 | from copy import deepcopy |
---|
[2622b3f] | 14 | import collections |
---|
[4d76711] | 15 | import traceback |
---|
| 16 | import logging |
---|
[724257c] | 17 | from os.path import basename, splitext, abspath, getmtime |
---|
[9f8ade1] | 18 | try: |
---|
| 19 | import _thread as thread |
---|
| 20 | except ImportError: |
---|
| 21 | import thread |
---|
[ce27e21] | 22 | |
---|
[7ae2b7f] | 23 | import numpy as np # type: ignore |
---|
[ce27e21] | 24 | |
---|
[aa4946b] | 25 | from . import core |
---|
[4d76711] | 26 | from . import custom |
---|
[a80e64c] | 27 | from . import product |
---|
[72a081d] | 28 | from . import generate |
---|
[fb5914f] | 29 | from . import weights |
---|
[6d6508e] | 30 | from . import modelinfo |
---|
[bde38b5] | 31 | from .details import make_kernel_args, dispersion_mesh |
---|
[ff7119b] | 32 | |
---|
[2d81cfe] | 33 | # pylint: disable=unused-import |
---|
[fa5fd8d] | 34 | try: |
---|
[2d81cfe] | 35 | from typing import (Dict, Mapping, Any, Sequence, Tuple, NamedTuple, |
---|
| 36 | List, Optional, Union, Callable) |
---|
[fa5fd8d] | 37 | from .modelinfo import ModelInfo, Parameter |
---|
| 38 | from .kernel import KernelModel |
---|
| 39 | MultiplicityInfoType = NamedTuple( |
---|
[a9bc435] | 40 | 'MultiplicityInfo', |
---|
[fa5fd8d] | 41 | [("number", int), ("control", str), ("choices", List[str]), |
---|
| 42 | ("x_axis_label", str)]) |
---|
[60f03de] | 43 | SasviewModelType = Callable[[int], "SasviewModel"] |
---|
[fa5fd8d] | 44 | except ImportError: |
---|
| 45 | pass |
---|
[2d81cfe] | 46 | # pylint: enable=unused-import |
---|
[fa5fd8d] | 47 | |
---|
[724257c] | 48 | logger = logging.getLogger(__name__) |
---|
| 49 | |
---|
[a38b065] | 50 | calculation_lock = thread.allocate_lock() |
---|
| 51 | |
---|
[724257c] | 52 | #: True if pre-existing plugins, with the old names and parameters, should |
---|
| 53 | #: continue to be supported. |
---|
[c95dfc63] | 54 | SUPPORT_OLD_STYLE_PLUGINS = True |
---|
| 55 | |
---|
[fa5fd8d] | 56 | # TODO: separate x_axis_label from multiplicity info |
---|
| 57 | MultiplicityInfo = collections.namedtuple( |
---|
| 58 | 'MultiplicityInfo', |
---|
| 59 | ["number", "control", "choices", "x_axis_label"], |
---|
| 60 | ) |
---|
| 61 | |
---|
[724257c] | 62 | #: set of defined models (standard and custom) |
---|
| 63 | MODELS = {} # type: Dict[str, SasviewModelType] |
---|
[839fd68] | 64 | # TODO: remove unused MODEL_BY_PATH cache once sasview no longer references it |
---|
[724257c] | 65 | #: custom model {path: model} mapping so we can check timestamps |
---|
| 66 | MODEL_BY_PATH = {} # type: Dict[str, SasviewModelType] |
---|
[d321747] | 67 | #: Track modules that we have loaded so we can determine whether the model |
---|
| 68 | #: has changed since we last reloaded. |
---|
| 69 | _CACHED_MODULE = {} # type: Dict[str, "module"] |
---|
[724257c] | 70 | |
---|
[92d38285] | 71 | def find_model(modelname): |
---|
[b32dafd] | 72 | # type: (str) -> SasviewModelType |
---|
| 73 | """ |
---|
| 74 | Find a model by name. If the model name ends in py, try loading it from |
---|
| 75 | custom models, otherwise look for it in the list of builtin models. |
---|
| 76 | """ |
---|
[92d38285] | 77 | # TODO: used by sum/product model to load an existing model |
---|
| 78 | # TODO: doesn't handle custom models properly |
---|
| 79 | if modelname.endswith('.py'): |
---|
| 80 | return load_custom_model(modelname) |
---|
| 81 | elif modelname in MODELS: |
---|
| 82 | return MODELS[modelname] |
---|
| 83 | else: |
---|
| 84 | raise ValueError("unknown model %r"%modelname) |
---|
| 85 | |
---|
[56b2687] | 86 | |
---|
[fa5fd8d] | 87 | # TODO: figure out how to say that the return type is a subclass |
---|
[4d76711] | 88 | def load_standard_models(): |
---|
[60f03de] | 89 | # type: () -> List[SasviewModelType] |
---|
[4d76711] | 90 | """ |
---|
| 91 | Load and return the list of predefined models. |
---|
| 92 | |
---|
| 93 | If there is an error loading a model, then a traceback is logged and the |
---|
| 94 | model is not returned. |
---|
| 95 | """ |
---|
| 96 | for name in core.list_models(): |
---|
| 97 | try: |
---|
[92d38285] | 98 | MODELS[name] = _make_standard_model(name) |
---|
[ee8f734] | 99 | except Exception: |
---|
[724257c] | 100 | logger.error(traceback.format_exc()) |
---|
[c95dfc63] | 101 | if SUPPORT_OLD_STYLE_PLUGINS: |
---|
| 102 | _register_old_models() |
---|
| 103 | |
---|
[724257c] | 104 | return list(MODELS.values()) |
---|
[de97440] | 105 | |
---|
[4d76711] | 106 | |
---|
| 107 | def load_custom_model(path): |
---|
[60f03de] | 108 | # type: (str) -> SasviewModelType |
---|
[4d76711] | 109 | """ |
---|
| 110 | Load a custom model given the model path. |
---|
[ff7119b] | 111 | """ |
---|
[724257c] | 112 | #logger.info("Loading model %s", path) |
---|
[d321747] | 113 | |
---|
| 114 | # Load the kernel module. This may already be cached by the loader, so |
---|
| 115 | # only requires checking the timestamps of the dependents. |
---|
[4d76711] | 116 | kernel_module = custom.load_custom_kernel_module(path) |
---|
[d321747] | 117 | |
---|
| 118 | # Check if the module has changed since we last looked. |
---|
| 119 | reloaded = kernel_module != _CACHED_MODULE.get(path, None) |
---|
| 120 | _CACHED_MODULE[path] = kernel_module |
---|
| 121 | |
---|
| 122 | # Turn the module into a model. We need to do this in even if the |
---|
| 123 | # model has already been loaded so that we can determine the model |
---|
| 124 | # name and retrieve it from the MODELS cache. |
---|
| 125 | model = getattr(kernel_module, 'Model', None) |
---|
| 126 | if model is not None: |
---|
[9457498] | 127 | # Old style models do not set the name in the class attributes, so |
---|
| 128 | # set it here; this name will be overridden when the object is created |
---|
| 129 | # with an instance variable that has the same value. |
---|
| 130 | if model.name == "": |
---|
| 131 | model.name = splitext(basename(path))[0] |
---|
[20a70bc] | 132 | if not hasattr(model, 'filename'): |
---|
[724257c] | 133 | model.filename = abspath(kernel_module.__file__).replace('.pyc', '.py') |
---|
[e4bf271] | 134 | if not hasattr(model, 'id'): |
---|
| 135 | model.id = splitext(basename(model.filename))[0] |
---|
[724257c] | 136 | else: |
---|
[56b2687] | 137 | model_info = modelinfo.make_model_info(kernel_module) |
---|
[bcdd6c9] | 138 | model = make_model_from_info(model_info) |
---|
[ed10b57] | 139 | |
---|
[2f2c70c] | 140 | # If a model name already exists and we are loading a different model, |
---|
| 141 | # use the model file name as the model name. |
---|
| 142 | if model.name in MODELS and not model.filename == MODELS[model.name].filename: |
---|
| 143 | _previous_name = model.name |
---|
| 144 | model.name = model.id |
---|
[bf8c271] | 145 | |
---|
[2f2c70c] | 146 | # If the new model name is still in the model list (for instance, |
---|
| 147 | # if we put a cylinder.py in our plug-in directory), then append |
---|
| 148 | # an identifier. |
---|
| 149 | if model.name in MODELS and not model.filename == MODELS[model.name].filename: |
---|
| 150 | model.name = model.id + '_user' |
---|
[724257c] | 151 | logger.info("Model %s already exists: using %s [%s]", |
---|
| 152 | _previous_name, model.name, model.filename) |
---|
[ed10b57] | 153 | |
---|
[d321747] | 154 | # Only update the model if the module has changed |
---|
| 155 | if reloaded or model.name not in MODELS: |
---|
| 156 | MODELS[model.name] = model |
---|
| 157 | |
---|
| 158 | return MODELS[model.name] |
---|
[4d76711] | 159 | |
---|
[87985ca] | 160 | |
---|
[bcdd6c9] | 161 | def make_model_from_info(model_info): |
---|
| 162 | # type: (ModelInfo) -> SasviewModelType |
---|
| 163 | """ |
---|
| 164 | Convert *model_info* into a SasView model wrapper. |
---|
| 165 | """ |
---|
| 166 | def __init__(self, multiplicity=None): |
---|
| 167 | SasviewModel.__init__(self, multiplicity=multiplicity) |
---|
| 168 | attrs = _generate_model_attributes(model_info) |
---|
| 169 | attrs['__init__'] = __init__ |
---|
| 170 | attrs['filename'] = model_info.filename |
---|
| 171 | ConstructedModel = type(model_info.name, (SasviewModel,), attrs) # type: SasviewModelType |
---|
| 172 | return ConstructedModel |
---|
| 173 | |
---|
| 174 | |
---|
[4d76711] | 175 | def _make_standard_model(name): |
---|
[60f03de] | 176 | # type: (str) -> SasviewModelType |
---|
[ff7119b] | 177 | """ |
---|
[4d76711] | 178 | Load the sasview model defined by *name*. |
---|
[72a081d] | 179 | |
---|
[4d76711] | 180 | *name* can be a standard model name or a path to a custom model. |
---|
[87985ca] | 181 | |
---|
[4d76711] | 182 | Returns a class that can be used directly as a sasview model. |
---|
[ff7119b] | 183 | """ |
---|
[4d76711] | 184 | kernel_module = generate.load_kernel_module(name) |
---|
[fa5fd8d] | 185 | model_info = modelinfo.make_model_info(kernel_module) |
---|
[bcdd6c9] | 186 | return make_model_from_info(model_info) |
---|
[72a081d] | 187 | |
---|
| 188 | |
---|
[724257c] | 189 | def _register_old_models(): |
---|
| 190 | # type: () -> None |
---|
| 191 | """ |
---|
| 192 | Place the new models into sasview under the old names. |
---|
| 193 | |
---|
| 194 | Monkey patch sas.sascalc.fit as sas.models so that sas.models.pluginmodel |
---|
| 195 | is available to the plugin modules. |
---|
| 196 | """ |
---|
| 197 | import sys |
---|
| 198 | import sas # needed in order to set sas.models |
---|
| 199 | import sas.sascalc.fit |
---|
| 200 | sys.modules['sas.models'] = sas.sascalc.fit |
---|
| 201 | sas.models = sas.sascalc.fit |
---|
| 202 | import sas.models |
---|
| 203 | from sasmodels.conversion_table import CONVERSION_TABLE |
---|
[e65c3ba] | 204 | |
---|
[724257c] | 205 | for new_name, conversion in CONVERSION_TABLE.get((3, 1, 2), {}).items(): |
---|
| 206 | # CoreShellEllipsoidModel => core_shell_ellipsoid:1 |
---|
| 207 | new_name = new_name.split(':')[0] |
---|
| 208 | old_name = conversion[0] if len(conversion) < 3 else conversion[2] |
---|
| 209 | module_attrs = {old_name: find_model(new_name)} |
---|
| 210 | ConstructedModule = type(old_name, (), module_attrs) |
---|
| 211 | old_path = 'sas.models.' + old_name |
---|
| 212 | setattr(sas.models, old_path, ConstructedModule) |
---|
| 213 | sys.modules[old_path] = ConstructedModule |
---|
| 214 | |
---|
| 215 | |
---|
[a80e64c] | 216 | def MultiplicationModel(form_factor, structure_factor): |
---|
| 217 | # type: ("SasviewModel", "SasviewModel") -> "SasviewModel" |
---|
[e65c3ba] | 218 | """ |
---|
| 219 | Returns a constructed product model from form_factor and structure_factor. |
---|
| 220 | """ |
---|
[a80e64c] | 221 | model_info = product.make_product_info(form_factor._model_info, |
---|
| 222 | structure_factor._model_info) |
---|
[bcdd6c9] | 223 | ConstructedModel = make_model_from_info(model_info) |
---|
[a06af5d] | 224 | return ConstructedModel(form_factor.multiplicity) |
---|
[a80e64c] | 225 | |
---|
[ce27e21] | 226 | |
---|
[fa5fd8d] | 227 | def _generate_model_attributes(model_info): |
---|
| 228 | # type: (ModelInfo) -> Dict[str, Any] |
---|
| 229 | """ |
---|
| 230 | Generate the class attributes for the model. |
---|
| 231 | |
---|
| 232 | This should include all the information necessary to query the model |
---|
| 233 | details so that you do not need to instantiate a model to query it. |
---|
| 234 | |
---|
| 235 | All the attributes should be immutable to avoid accidents. |
---|
| 236 | """ |
---|
| 237 | |
---|
| 238 | # TODO: allow model to override axis labels input/output name/unit |
---|
| 239 | |
---|
[a18c5b3] | 240 | # Process multiplicity |
---|
[fa5fd8d] | 241 | non_fittable = [] # type: List[str] |
---|
[04045f4] | 242 | xlabel = model_info.profile_axes[0] if model_info.profile is not None else "" |
---|
| 243 | variants = MultiplicityInfo(0, "", [], xlabel) |
---|
[a18c5b3] | 244 | for p in model_info.parameters.kernel_parameters: |
---|
[04045f4] | 245 | if p.name == model_info.control: |
---|
[fa5fd8d] | 246 | non_fittable.append(p.name) |
---|
[04045f4] | 247 | variants = MultiplicityInfo( |
---|
[ce176ca] | 248 | len(p.choices) if p.choices else int(p.limits[1]), |
---|
| 249 | p.name, p.choices, xlabel |
---|
[fa5fd8d] | 250 | ) |
---|
| 251 | break |
---|
| 252 | |
---|
[50ec515] | 253 | # Only a single drop-down list parameter available |
---|
| 254 | fun_list = [] |
---|
| 255 | for p in model_info.parameters.kernel_parameters: |
---|
| 256 | if p.choices: |
---|
| 257 | fun_list = p.choices |
---|
| 258 | if p.length > 1: |
---|
| 259 | non_fittable.extend(p.id+str(k) for k in range(1, p.length+1)) |
---|
| 260 | break |
---|
| 261 | |
---|
[a18c5b3] | 262 | # Organize parameter sets |
---|
[fa5fd8d] | 263 | orientation_params = [] |
---|
| 264 | magnetic_params = [] |
---|
| 265 | fixed = [] |
---|
[85fe7f8] | 266 | for p in model_info.parameters.user_parameters({}, is2d=True): |
---|
[fa5fd8d] | 267 | if p.type == 'orientation': |
---|
| 268 | orientation_params.append(p.name) |
---|
| 269 | orientation_params.append(p.name+".width") |
---|
| 270 | fixed.append(p.name+".width") |
---|
[32e3c9b] | 271 | elif p.type == 'magnetic': |
---|
[fa5fd8d] | 272 | orientation_params.append(p.name) |
---|
| 273 | magnetic_params.append(p.name) |
---|
| 274 | fixed.append(p.name+".width") |
---|
[a18c5b3] | 275 | |
---|
[32e3c9b] | 276 | |
---|
[a18c5b3] | 277 | # Build class dictionary |
---|
| 278 | attrs = {} # type: Dict[str, Any] |
---|
| 279 | attrs['_model_info'] = model_info |
---|
| 280 | attrs['name'] = model_info.name |
---|
| 281 | attrs['id'] = model_info.id |
---|
| 282 | attrs['description'] = model_info.description |
---|
| 283 | attrs['category'] = model_info.category |
---|
| 284 | attrs['is_structure_factor'] = model_info.structure_factor |
---|
[6e7ba14] | 285 | attrs['is_form_factor'] = model_info.effective_radius_type is not None |
---|
[a18c5b3] | 286 | attrs['is_multiplicity_model'] = variants[0] > 1 |
---|
| 287 | attrs['multiplicity_info'] = variants |
---|
[fa5fd8d] | 288 | attrs['orientation_params'] = tuple(orientation_params) |
---|
| 289 | attrs['magnetic_params'] = tuple(magnetic_params) |
---|
| 290 | attrs['fixed'] = tuple(fixed) |
---|
| 291 | attrs['non_fittable'] = tuple(non_fittable) |
---|
[50ec515] | 292 | attrs['fun_list'] = tuple(fun_list) |
---|
[fa5fd8d] | 293 | |
---|
| 294 | return attrs |
---|
[4d76711] | 295 | |
---|
[ce27e21] | 296 | class SasviewModel(object): |
---|
| 297 | """ |
---|
| 298 | Sasview wrapper for opencl/ctypes model. |
---|
| 299 | """ |
---|
[fa5fd8d] | 300 | # Model parameters for the specific model are set in the class constructor |
---|
| 301 | # via the _generate_model_attributes function, which subclasses |
---|
| 302 | # SasviewModel. They are included here for typing and documentation |
---|
| 303 | # purposes. |
---|
| 304 | _model = None # type: KernelModel |
---|
| 305 | _model_info = None # type: ModelInfo |
---|
| 306 | #: load/save name for the model |
---|
| 307 | id = None # type: str |
---|
| 308 | #: display name for the model |
---|
| 309 | name = None # type: str |
---|
| 310 | #: short model description |
---|
| 311 | description = None # type: str |
---|
| 312 | #: default model category |
---|
| 313 | category = None # type: str |
---|
| 314 | |
---|
| 315 | #: names of the orientation parameters in the order they appear |
---|
[724257c] | 316 | orientation_params = None # type: List[str] |
---|
[fa5fd8d] | 317 | #: names of the magnetic parameters in the order they appear |
---|
[724257c] | 318 | magnetic_params = None # type: List[str] |
---|
[fa5fd8d] | 319 | #: names of the fittable parameters |
---|
[724257c] | 320 | fixed = None # type: List[str] |
---|
[fa5fd8d] | 321 | # TODO: the attribute fixed is ill-named |
---|
| 322 | |
---|
| 323 | # Axis labels |
---|
| 324 | input_name = "Q" |
---|
| 325 | input_unit = "A^{-1}" |
---|
| 326 | output_name = "Intensity" |
---|
| 327 | output_unit = "cm^{-1}" |
---|
| 328 | |
---|
| 329 | #: default cutoff for polydispersity |
---|
| 330 | cutoff = 1e-5 |
---|
| 331 | |
---|
| 332 | # Note: Use non-mutable values for class attributes to avoid errors |
---|
| 333 | #: parameters that are not fitted |
---|
| 334 | non_fittable = () # type: Sequence[str] |
---|
| 335 | |
---|
| 336 | #: True if model should appear as a structure factor |
---|
| 337 | is_structure_factor = False |
---|
| 338 | #: True if model should appear as a form factor |
---|
| 339 | is_form_factor = False |
---|
| 340 | #: True if model has multiplicity |
---|
| 341 | is_multiplicity_model = False |
---|
[1f35235] | 342 | #: Multiplicity information |
---|
[fa5fd8d] | 343 | multiplicity_info = None # type: MultiplicityInfoType |
---|
| 344 | |
---|
| 345 | # Per-instance variables |
---|
| 346 | #: parameter {name: value} mapping |
---|
| 347 | params = None # type: Dict[str, float] |
---|
| 348 | #: values for dispersion width, npts, nsigmas and type |
---|
| 349 | dispersion = None # type: Dict[str, Any] |
---|
| 350 | #: units and limits for each parameter |
---|
[60f03de] | 351 | details = None # type: Dict[str, Sequence[Any]] |
---|
| 352 | # # actual type is Dict[str, List[str, float, float]] |
---|
[04dc697] | 353 | #: multiplicity value, or None if no multiplicity on the model |
---|
[fa5fd8d] | 354 | multiplicity = None # type: Optional[int] |
---|
[04dc697] | 355 | #: memory for polydispersity array if using ArrayDispersion (used by sasview). |
---|
| 356 | _persistency_dict = None # type: Dict[str, Tuple[np.ndarray, np.ndarray]] |
---|
[fa5fd8d] | 357 | |
---|
| 358 | def __init__(self, multiplicity=None): |
---|
[04dc697] | 359 | # type: (Optional[int]) -> None |
---|
[2622b3f] | 360 | |
---|
[04045f4] | 361 | # TODO: _persistency_dict to persistency_dict throughout sasview |
---|
| 362 | # TODO: refactor multiplicity to encompass variants |
---|
| 363 | # TODO: dispersion should be a class |
---|
[fa5fd8d] | 364 | # TODO: refactor multiplicity info |
---|
| 365 | # TODO: separate profile view from multiplicity |
---|
| 366 | # The button label, x and y axis labels and scale need to be under |
---|
| 367 | # the control of the model, not the fit page. Maximum flexibility, |
---|
| 368 | # the fit page would supply the canvas and the profile could plot |
---|
| 369 | # how it wants, but this assumes matplotlib. Next level is that |
---|
| 370 | # we provide some sort of data description including title, labels |
---|
| 371 | # and lines to plot. |
---|
| 372 | |
---|
[1f35235] | 373 | # Get the list of hidden parameters given the multiplicity |
---|
[04045f4] | 374 | # Don't include multiplicity in the list of parameters |
---|
[fa5fd8d] | 375 | self.multiplicity = multiplicity |
---|
[04045f4] | 376 | if multiplicity is not None: |
---|
| 377 | hidden = self._model_info.get_hidden_parameters(multiplicity) |
---|
| 378 | hidden |= set([self.multiplicity_info.control]) |
---|
| 379 | else: |
---|
| 380 | hidden = set() |
---|
[8f93522] | 381 | if self._model_info.structure_factor: |
---|
| 382 | hidden.add('scale') |
---|
| 383 | hidden.add('background') |
---|
[04045f4] | 384 | |
---|
[bd547d0] | 385 | # Update the parameter lists to exclude any hidden parameters |
---|
| 386 | self.magnetic_params = tuple(pname for pname in self.magnetic_params |
---|
| 387 | if pname not in hidden) |
---|
| 388 | self.orientation_params = tuple(pname for pname in self.orientation_params |
---|
| 389 | if pname not in hidden) |
---|
| 390 | |
---|
[04dc697] | 391 | self._persistency_dict = {} |
---|
[fa5fd8d] | 392 | self.params = collections.OrderedDict() |
---|
[b3a85cd] | 393 | self.dispersion = collections.OrderedDict() |
---|
[fa5fd8d] | 394 | self.details = {} |
---|
[8977226] | 395 | for p in self._model_info.parameters.user_parameters({}, is2d=True): |
---|
[04045f4] | 396 | if p.name in hidden: |
---|
[fa5fd8d] | 397 | continue |
---|
[fcd7bbd] | 398 | self.params[p.name] = p.default |
---|
[c952e59] | 399 | self.details[p.id] = [p.units, p.limits[0], p.limits[1]] |
---|
[fb5914f] | 400 | if p.polydisperse: |
---|
[fa5fd8d] | 401 | self.details[p.id+".width"] = [ |
---|
| 402 | "", 0.0, 1.0 if p.relative_pd else np.inf |
---|
| 403 | ] |
---|
[fb5914f] | 404 | self.dispersion[p.name] = { |
---|
| 405 | 'width': 0, |
---|
| 406 | 'npts': 35, |
---|
| 407 | 'nsigmas': 3, |
---|
| 408 | 'type': 'gaussian', |
---|
| 409 | } |
---|
[ce27e21] | 410 | |
---|
[de97440] | 411 | def __get_state__(self): |
---|
[fa5fd8d] | 412 | # type: () -> Dict[str, Any] |
---|
[de97440] | 413 | state = self.__dict__.copy() |
---|
[4d76711] | 414 | state.pop('_model') |
---|
[de97440] | 415 | # May need to reload model info on set state since it has pointers |
---|
| 416 | # to python implementations of Iq, etc. |
---|
| 417 | #state.pop('_model_info') |
---|
| 418 | return state |
---|
| 419 | |
---|
| 420 | def __set_state__(self, state): |
---|
[fa5fd8d] | 421 | # type: (Dict[str, Any]) -> None |
---|
[de97440] | 422 | self.__dict__ = state |
---|
[fb5914f] | 423 | self._model = None |
---|
[de97440] | 424 | |
---|
[ce27e21] | 425 | def __str__(self): |
---|
[fa5fd8d] | 426 | # type: () -> str |
---|
[ce27e21] | 427 | """ |
---|
| 428 | :return: string representation |
---|
| 429 | """ |
---|
| 430 | return self.name |
---|
| 431 | |
---|
| 432 | def is_fittable(self, par_name): |
---|
[fa5fd8d] | 433 | # type: (str) -> bool |
---|
[ce27e21] | 434 | """ |
---|
| 435 | Check if a given parameter is fittable or not |
---|
| 436 | |
---|
| 437 | :param par_name: the parameter name to check |
---|
| 438 | """ |
---|
[e758662] | 439 | return par_name in self.fixed |
---|
[ce27e21] | 440 | #For the future |
---|
| 441 | #return self.params[str(par_name)].is_fittable() |
---|
| 442 | |
---|
| 443 | |
---|
| 444 | def getProfile(self): |
---|
[fa5fd8d] | 445 | # type: () -> (np.ndarray, np.ndarray) |
---|
[ce27e21] | 446 | """ |
---|
| 447 | Get SLD profile |
---|
| 448 | |
---|
| 449 | : return: (z, beta) where z is a list of depth of the transition points |
---|
| 450 | beta is a list of the corresponding SLD values |
---|
| 451 | """ |
---|
[745b7bb] | 452 | args = {} # type: Dict[str, Any] |
---|
[fa5fd8d] | 453 | for p in self._model_info.parameters.kernel_parameters: |
---|
| 454 | if p.id == self.multiplicity_info.control: |
---|
[745b7bb] | 455 | value = float(self.multiplicity) |
---|
[fa5fd8d] | 456 | elif p.length == 1: |
---|
[745b7bb] | 457 | value = self.params.get(p.id, np.NaN) |
---|
[fa5fd8d] | 458 | else: |
---|
[745b7bb] | 459 | value = np.array([self.params.get(p.id+str(k), np.NaN) |
---|
[b32dafd] | 460 | for k in range(1, p.length+1)]) |
---|
[745b7bb] | 461 | args[p.id] = value |
---|
| 462 | |
---|
[e7fe459] | 463 | x, y = self._model_info.profile(**args) |
---|
| 464 | return x, 1e-6*y |
---|
[ce27e21] | 465 | |
---|
| 466 | def setParam(self, name, value): |
---|
[fa5fd8d] | 467 | # type: (str, float) -> None |
---|
[ce27e21] | 468 | """ |
---|
| 469 | Set the value of a model parameter |
---|
| 470 | |
---|
| 471 | :param name: name of the parameter |
---|
| 472 | :param value: value of the parameter |
---|
| 473 | |
---|
| 474 | """ |
---|
| 475 | # Look for dispersion parameters |
---|
| 476 | toks = name.split('.') |
---|
[de0c4ba] | 477 | if len(toks) == 2: |
---|
[ce27e21] | 478 | for item in self.dispersion.keys(): |
---|
[e758662] | 479 | if item == toks[0]: |
---|
[ce27e21] | 480 | for par in self.dispersion[item]: |
---|
[e758662] | 481 | if par == toks[1]: |
---|
[ce27e21] | 482 | self.dispersion[item][par] = value |
---|
| 483 | return |
---|
| 484 | else: |
---|
| 485 | # Look for standard parameter |
---|
| 486 | for item in self.params.keys(): |
---|
[e758662] | 487 | if item == name: |
---|
[ce27e21] | 488 | self.params[item] = value |
---|
| 489 | return |
---|
| 490 | |
---|
[63b32bb] | 491 | raise ValueError("Model does not contain parameter %s" % name) |
---|
[ce27e21] | 492 | |
---|
| 493 | def getParam(self, name): |
---|
[fa5fd8d] | 494 | # type: (str) -> float |
---|
[ce27e21] | 495 | """ |
---|
| 496 | Set the value of a model parameter |
---|
| 497 | |
---|
| 498 | :param name: name of the parameter |
---|
| 499 | |
---|
| 500 | """ |
---|
| 501 | # Look for dispersion parameters |
---|
| 502 | toks = name.split('.') |
---|
[de0c4ba] | 503 | if len(toks) == 2: |
---|
[ce27e21] | 504 | for item in self.dispersion.keys(): |
---|
[e758662] | 505 | if item == toks[0]: |
---|
[ce27e21] | 506 | for par in self.dispersion[item]: |
---|
[e758662] | 507 | if par == toks[1]: |
---|
[ce27e21] | 508 | return self.dispersion[item][par] |
---|
| 509 | else: |
---|
| 510 | # Look for standard parameter |
---|
| 511 | for item in self.params.keys(): |
---|
[e758662] | 512 | if item == name: |
---|
[ce27e21] | 513 | return self.params[item] |
---|
| 514 | |
---|
[63b32bb] | 515 | raise ValueError("Model does not contain parameter %s" % name) |
---|
[ce27e21] | 516 | |
---|
| 517 | def getParamList(self): |
---|
[04dc697] | 518 | # type: () -> Sequence[str] |
---|
[ce27e21] | 519 | """ |
---|
| 520 | Return a list of all available parameters for the model |
---|
| 521 | """ |
---|
[04dc697] | 522 | param_list = list(self.params.keys()) |
---|
[ce27e21] | 523 | # WARNING: Extending the list with the dispersion parameters |
---|
[de0c4ba] | 524 | param_list.extend(self.getDispParamList()) |
---|
| 525 | return param_list |
---|
[ce27e21] | 526 | |
---|
| 527 | def getDispParamList(self): |
---|
[04dc697] | 528 | # type: () -> Sequence[str] |
---|
[ce27e21] | 529 | """ |
---|
[fb5914f] | 530 | Return a list of polydispersity parameters for the model |
---|
[ce27e21] | 531 | """ |
---|
[1780d59] | 532 | # TODO: fix test so that parameter order doesn't matter |
---|
[3bcb88c] | 533 | ret = ['%s.%s' % (p_name, ext) |
---|
| 534 | for p_name in self.dispersion.keys() |
---|
| 535 | for ext in ('npts', 'nsigmas', 'width')] |
---|
[9404dd3] | 536 | #print(ret) |
---|
[1780d59] | 537 | return ret |
---|
[ce27e21] | 538 | |
---|
| 539 | def clone(self): |
---|
[04dc697] | 540 | # type: () -> "SasviewModel" |
---|
[ce27e21] | 541 | """ Return a identical copy of self """ |
---|
| 542 | return deepcopy(self) |
---|
| 543 | |
---|
| 544 | def run(self, x=0.0): |
---|
[fa5fd8d] | 545 | # type: (Union[float, (float, float), List[float]]) -> float |
---|
[ce27e21] | 546 | """ |
---|
| 547 | Evaluate the model |
---|
| 548 | |
---|
| 549 | :param x: input q, or [q,phi] |
---|
| 550 | |
---|
| 551 | :return: scattering function P(q) |
---|
| 552 | |
---|
| 553 | **DEPRECATED**: use calculate_Iq instead |
---|
| 554 | """ |
---|
[de0c4ba] | 555 | if isinstance(x, (list, tuple)): |
---|
[3c56da87] | 556 | # pylint: disable=unpacking-non-sequence |
---|
[ce27e21] | 557 | q, phi = x |
---|
[84f2962] | 558 | result, _ = self.calculate_Iq([q*math.cos(phi)], [q*math.sin(phi)]) |
---|
| 559 | return result[0] |
---|
[ce27e21] | 560 | else: |
---|
[84f2962] | 561 | result, _ = self.calculate_Iq([x]) |
---|
| 562 | return result[0] |
---|
[ce27e21] | 563 | |
---|
| 564 | |
---|
| 565 | def runXY(self, x=0.0): |
---|
[fa5fd8d] | 566 | # type: (Union[float, (float, float), List[float]]) -> float |
---|
[ce27e21] | 567 | """ |
---|
| 568 | Evaluate the model in cartesian coordinates |
---|
| 569 | |
---|
| 570 | :param x: input q, or [qx, qy] |
---|
| 571 | |
---|
| 572 | :return: scattering function P(q) |
---|
| 573 | |
---|
| 574 | **DEPRECATED**: use calculate_Iq instead |
---|
| 575 | """ |
---|
[de0c4ba] | 576 | if isinstance(x, (list, tuple)): |
---|
[84f2962] | 577 | result, _ = self.calculate_Iq([x[0]], [x[1]]) |
---|
| 578 | return result[0] |
---|
[ce27e21] | 579 | else: |
---|
[84f2962] | 580 | result, _ = self.calculate_Iq([x]) |
---|
| 581 | return result[0] |
---|
[ce27e21] | 582 | |
---|
| 583 | def evalDistribution(self, qdist): |
---|
[04dc697] | 584 | # type: (Union[np.ndarray, Tuple[np.ndarray, np.ndarray], List[np.ndarray]]) -> np.ndarray |
---|
[d138d43] | 585 | r""" |
---|
[ce27e21] | 586 | Evaluate a distribution of q-values. |
---|
| 587 | |
---|
[d138d43] | 588 | :param qdist: array of q or a list of arrays [qx,qy] |
---|
[ce27e21] | 589 | |
---|
[d138d43] | 590 | * For 1D, a numpy array is expected as input |
---|
[ce27e21] | 591 | |
---|
[d138d43] | 592 | :: |
---|
[ce27e21] | 593 | |
---|
[d138d43] | 594 | evalDistribution(q) |
---|
[ce27e21] | 595 | |
---|
[d138d43] | 596 | where *q* is a numpy array. |
---|
[ce27e21] | 597 | |
---|
[d138d43] | 598 | * For 2D, a list of *[qx,qy]* is expected with 1D arrays as input |
---|
[ce27e21] | 599 | |
---|
[d138d43] | 600 | :: |
---|
[ce27e21] | 601 | |
---|
[d138d43] | 602 | qx = [ qx[0], qx[1], qx[2], ....] |
---|
| 603 | qy = [ qy[0], qy[1], qy[2], ....] |
---|
[ce27e21] | 604 | |
---|
[d138d43] | 605 | If the model is 1D only, then |
---|
[ce27e21] | 606 | |
---|
[d138d43] | 607 | .. math:: |
---|
[ce27e21] | 608 | |
---|
[d138d43] | 609 | q = \sqrt{q_x^2+q_y^2} |
---|
[ce27e21] | 610 | |
---|
| 611 | """ |
---|
[de0c4ba] | 612 | if isinstance(qdist, (list, tuple)): |
---|
[ce27e21] | 613 | # Check whether we have a list of ndarrays [qx,qy] |
---|
| 614 | qx, qy = qdist |
---|
[84f2962] | 615 | result, _ = self.calculate_Iq(qx, qy) |
---|
| 616 | return result |
---|
[ce27e21] | 617 | |
---|
| 618 | elif isinstance(qdist, np.ndarray): |
---|
| 619 | # We have a simple 1D distribution of q-values |
---|
[84f2962] | 620 | result, _ = self.calculate_Iq(qdist) |
---|
| 621 | return result |
---|
[ce27e21] | 622 | |
---|
| 623 | else: |
---|
[3c56da87] | 624 | raise TypeError("evalDistribution expects q or [qx, qy], not %r" |
---|
| 625 | % type(qdist)) |
---|
[ce27e21] | 626 | |
---|
[9dcb21d] | 627 | def calc_composition_models(self, qx): |
---|
[64614ad] | 628 | """ |
---|
[9dcb21d] | 629 | returns parts of the composition model or None if not a composition |
---|
| 630 | model. |
---|
[64614ad] | 631 | """ |
---|
[946c8d27] | 632 | # TODO: have calculate_Iq return the intermediates. |
---|
| 633 | # |
---|
| 634 | # The current interface causes calculate_Iq() to be called twice, |
---|
| 635 | # once to get the combined result and again to get the intermediate |
---|
| 636 | # results. This is necessary for now. |
---|
| 637 | # Long term, the solution is to change the interface to calculate_Iq |
---|
| 638 | # so that it returns a results object containing all the bits: |
---|
[9644b5a] | 639 | # the A, B, C, ... of the composition model (and any subcomponents?) |
---|
[d32de68] | 640 | # the P and S of the product model |
---|
[946c8d27] | 641 | # the combined model before resolution smearing, |
---|
| 642 | # the sasmodel before sesans conversion, |
---|
| 643 | # the oriented 2D model used to fit oriented usans data, |
---|
| 644 | # the final I(q), |
---|
| 645 | # ... |
---|
[9644b5a] | 646 | # |
---|
[946c8d27] | 647 | # Have the model calculator add all of these blindly to the data |
---|
| 648 | # tree, and update the graphs which contain them. The fitter |
---|
| 649 | # needs to be updated to use the I(q) value only, ignoring the rest. |
---|
| 650 | # |
---|
| 651 | # The simple fix of returning the existing intermediate results |
---|
| 652 | # will not work for a couple of reasons: (1) another thread may |
---|
| 653 | # sneak in to compute its own results before calc_composition_models |
---|
| 654 | # is called, and (2) calculate_Iq is currently called three times: |
---|
| 655 | # once with q, once with q values before qmin and once with q values |
---|
| 656 | # after q max. Both of these should be addressed before |
---|
| 657 | # replacing this code. |
---|
[9644b5a] | 658 | composition = self._model_info.composition |
---|
| 659 | if composition and composition[0] == 'product': # only P*S for now |
---|
| 660 | with calculation_lock: |
---|
[84f2962] | 661 | _, lazy_results = self._calculate_Iq(qx) |
---|
| 662 | # for compatibility with sasview 4.x |
---|
| 663 | results = lazy_results() |
---|
| 664 | pq_data = results.get("P(Q)") |
---|
| 665 | sq_data = results.get("S(Q)") |
---|
| 666 | return pq_data, sq_data |
---|
[9644b5a] | 667 | else: |
---|
| 668 | return None |
---|
[bf8c271] | 669 | |
---|
[84f2962] | 670 | def calculate_Iq(self, |
---|
| 671 | qx, # type: Sequence[float] |
---|
| 672 | qy=None # type: Optional[Sequence[float]] |
---|
| 673 | ): |
---|
| 674 | # type: (...) -> Tuple[np.ndarray, Callable[[], collections.OrderedDict[str, np.ndarray]]] |
---|
[ff7119b] | 675 | """ |
---|
| 676 | Calculate Iq for one set of q with the current parameters. |
---|
| 677 | |
---|
| 678 | If the model is 1D, use *q*. If 2D, use *qx*, *qy*. |
---|
| 679 | |
---|
| 680 | This should NOT be used for fitting since it copies the *q* vectors |
---|
| 681 | to the card for each evaluation. |
---|
[84f2962] | 682 | |
---|
| 683 | The returned tuple contains the scattering intensity followed by a |
---|
| 684 | callable which returns a dictionary of intermediate data from |
---|
| 685 | ProductKernel. |
---|
[ff7119b] | 686 | """ |
---|
[a38b065] | 687 | ## uncomment the following when trying to debug the uncoordinated calls |
---|
| 688 | ## to calculate_Iq |
---|
| 689 | #if calculation_lock.locked(): |
---|
[724257c] | 690 | # logger.info("calculation waiting for another thread to complete") |
---|
| 691 | # logger.info("\n".join(traceback.format_stack())) |
---|
[a38b065] | 692 | |
---|
| 693 | with calculation_lock: |
---|
| 694 | return self._calculate_Iq(qx, qy) |
---|
| 695 | |
---|
[3a1afed] | 696 | def _calculate_Iq(self, qx, qy=None): |
---|
[fb5914f] | 697 | if self._model is None: |
---|
[d2bb604] | 698 | self._model = core.build_model(self._model_info) |
---|
[fa5fd8d] | 699 | if qy is not None: |
---|
| 700 | q_vectors = [np.asarray(qx), np.asarray(qy)] |
---|
| 701 | else: |
---|
| 702 | q_vectors = [np.asarray(qx)] |
---|
[a738209] | 703 | calculator = self._model.make_kernel(q_vectors) |
---|
[6a0d6aa] | 704 | parameters = self._model_info.parameters |
---|
| 705 | pairs = [self._get_weights(p) for p in parameters.call_parameters] |
---|
[9c1a59c] | 706 | #weights.plot_weights(self._model_info, pairs) |
---|
[bde38b5] | 707 | call_details, values, is_magnetic = make_kernel_args(calculator, pairs) |
---|
[4edec6f] | 708 | #call_details.show() |
---|
[05df1de] | 709 | #print("================ parameters ==================") |
---|
| 710 | #for p, v in zip(parameters.call_parameters, pairs): print(p.name, v[0]) |
---|
[ce99754] | 711 | #for k, p in enumerate(self._model_info.parameters.call_parameters): |
---|
| 712 | # print(k, p.name, *pairs[k]) |
---|
[4edec6f] | 713 | #print("params", self.params) |
---|
| 714 | #print("values", values) |
---|
| 715 | #print("is_mag", is_magnetic) |
---|
[6a0d6aa] | 716 | result = calculator(call_details, values, cutoff=self.cutoff, |
---|
[9eb3632] | 717 | magnetic=is_magnetic) |
---|
[84f2962] | 718 | lazy_results = getattr(calculator, 'results', |
---|
| 719 | lambda: collections.OrderedDict()) |
---|
[ce99754] | 720 | #print("result", result) |
---|
[84f2962] | 721 | |
---|
[a738209] | 722 | calculator.release() |
---|
[d533590] | 723 | #self._model.release() |
---|
[84f2962] | 724 | |
---|
| 725 | return result, lazy_results |
---|
[ce27e21] | 726 | |
---|
[39a06c9] | 727 | |
---|
| 728 | def calculate_ER(self, mode=1): |
---|
[fa5fd8d] | 729 | # type: () -> float |
---|
[ce27e21] | 730 | """ |
---|
| 731 | Calculate the effective radius for P(q)*S(q) |
---|
| 732 | |
---|
[3a1afed] | 733 | *mode* is the R_eff type, which defaults to 1 to match the ER |
---|
| 734 | calculation for sasview models from version 3.x. |
---|
| 735 | |
---|
[ce27e21] | 736 | :return: the value of the effective radius |
---|
| 737 | """ |
---|
[3a1afed] | 738 | # ER and VR are only needed for old multiplication models, based on |
---|
| 739 | # sas.sascalc.fit.MultiplicationModel. Fail for now. If we want to |
---|
| 740 | # continue supporting them then add some test cases so that the code |
---|
| 741 | # is exercised. We can access ER/VR using the kernel Fq function by |
---|
| 742 | # extending _calculate_Iq so that it calls: |
---|
| 743 | # if er_mode > 0: |
---|
| 744 | # res = calculator.Fq(call_details, values, cutoff=self.cutoff, |
---|
| 745 | # magnetic=False, effective_radius_type=mode) |
---|
| 746 | # R_eff, form_shell_ratio = res[2], res[4] |
---|
| 747 | # return R_eff, form_shell_ratio |
---|
| 748 | # Then use the following in calculate_ER: |
---|
| 749 | # ER, VR = self._calculate_Iq(q=[0.1], er_mode=mode) |
---|
| 750 | # return ER |
---|
| 751 | # Similarly, for calculate_VR: |
---|
| 752 | # ER, VR = self._calculate_Iq(q=[0.1], er_mode=1) |
---|
| 753 | # return VR |
---|
| 754 | # Obviously a combined calculate_ER_VR method would be better, but |
---|
| 755 | # we only need them to support very old models, so ignore the 2x |
---|
| 756 | # performance hit. |
---|
| 757 | raise NotImplementedError("ER function is no longer available.") |
---|
[ce27e21] | 758 | |
---|
| 759 | def calculate_VR(self): |
---|
[fa5fd8d] | 760 | # type: () -> float |
---|
[ce27e21] | 761 | """ |
---|
| 762 | Calculate the volf ratio for P(q)*S(q) |
---|
| 763 | |
---|
[39a06c9] | 764 | :return: the value of the form:shell volume ratio |
---|
[ce27e21] | 765 | """ |
---|
[3a1afed] | 766 | # See comments in calculate_ER. |
---|
| 767 | raise NotImplementedError("VR function is no longer available.") |
---|
[ce27e21] | 768 | |
---|
| 769 | def set_dispersion(self, parameter, dispersion): |
---|
[7c3fb15] | 770 | # type: (str, weights.Dispersion) -> None |
---|
[ce27e21] | 771 | """ |
---|
| 772 | Set the dispersion object for a model parameter |
---|
| 773 | |
---|
| 774 | :param parameter: name of the parameter [string] |
---|
| 775 | :param dispersion: dispersion object of type Dispersion |
---|
| 776 | """ |
---|
[fa800e72] | 777 | if parameter in self.params: |
---|
[1780d59] | 778 | # TODO: Store the disperser object directly in the model. |
---|
[56b2687] | 779 | # The current method of relying on the sasview GUI to |
---|
[fa800e72] | 780 | # remember them is kind of funky. |
---|
[1780d59] | 781 | # Note: can't seem to get disperser parameters from sasview |
---|
[9c1a59c] | 782 | # (1) Could create a sasview model that has not yet been |
---|
[1780d59] | 783 | # converted, assign the disperser to one of its polydisperse |
---|
| 784 | # parameters, then retrieve the disperser parameters from the |
---|
[9c1a59c] | 785 | # sasview model. |
---|
| 786 | # (2) Could write a disperser parameter retriever in sasview. |
---|
| 787 | # (3) Could modify sasview to use sasmodels.weights dispersers. |
---|
[1780d59] | 788 | # For now, rely on the fact that the sasview only ever uses |
---|
| 789 | # new dispersers in the set_dispersion call and create a new |
---|
| 790 | # one instead of trying to assign parameters. |
---|
[ce27e21] | 791 | self.dispersion[parameter] = dispersion.get_pars() |
---|
| 792 | else: |
---|
[7c3fb15] | 793 | raise ValueError("%r is not a dispersity or orientation parameter" |
---|
| 794 | % parameter) |
---|
[ce27e21] | 795 | |
---|
[aa4946b] | 796 | def _dispersion_mesh(self): |
---|
[fa5fd8d] | 797 | # type: () -> List[Tuple[np.ndarray, np.ndarray]] |
---|
[ce27e21] | 798 | """ |
---|
| 799 | Create a mesh grid of dispersion parameters and weights. |
---|
| 800 | |
---|
| 801 | Returns [p1,p2,...],w where pj is a vector of values for parameter j |
---|
| 802 | and w is a vector containing the products for weights for each |
---|
| 803 | parameter set in the vector. |
---|
| 804 | """ |
---|
[4bfd277] | 805 | pars = [self._get_weights(p) |
---|
| 806 | for p in self._model_info.parameters.call_parameters |
---|
| 807 | if p.type == 'volume'] |
---|
[9eb3632] | 808 | return dispersion_mesh(self._model_info, pars) |
---|
[ce27e21] | 809 | |
---|
| 810 | def _get_weights(self, par): |
---|
[fa5fd8d] | 811 | # type: (Parameter) -> Tuple[np.ndarray, np.ndarray] |
---|
[de0c4ba] | 812 | """ |
---|
[fb5914f] | 813 | Return dispersion weights for parameter |
---|
[de0c4ba] | 814 | """ |
---|
[fa5fd8d] | 815 | if par.name not in self.params: |
---|
| 816 | if par.name == self.multiplicity_info.control: |
---|
[32f87a5] | 817 | return self.multiplicity, [self.multiplicity], [1.0] |
---|
[fa5fd8d] | 818 | else: |
---|
[17db833] | 819 | # For hidden parameters use default values. This sets |
---|
| 820 | # scale=1 and background=0 for structure factors |
---|
| 821 | default = self._model_info.parameters.defaults.get(par.name, np.NaN) |
---|
| 822 | return default, [default], [1.0] |
---|
[fa5fd8d] | 823 | elif par.polydisperse: |
---|
[32f87a5] | 824 | value = self.params[par.name] |
---|
[fb5914f] | 825 | dis = self.dispersion[par.name] |
---|
[9c1a59c] | 826 | if dis['type'] == 'array': |
---|
[32f87a5] | 827 | dispersity, weight = dis['values'], dis['weights'] |
---|
[9c1a59c] | 828 | else: |
---|
[32f87a5] | 829 | dispersity, weight = weights.get_weights( |
---|
[9c1a59c] | 830 | dis['type'], dis['npts'], dis['width'], dis['nsigmas'], |
---|
[32f87a5] | 831 | value, par.limits, par.relative_pd) |
---|
| 832 | return value, dispersity, weight |
---|
[fb5914f] | 833 | else: |
---|
[32f87a5] | 834 | value = self.params[par.name] |
---|
[ce99754] | 835 | return value, [value], [1.0] |
---|
[ce27e21] | 836 | |
---|
[12eec1e] | 837 | @classmethod |
---|
| 838 | def runTests(cls): |
---|
| 839 | """ |
---|
| 840 | Run any tests built into the model and captures the test output. |
---|
| 841 | |
---|
| 842 | Returns success flag and output |
---|
| 843 | """ |
---|
| 844 | from .model_test import check_model |
---|
| 845 | return check_model(cls._model_info) |
---|
| 846 | |
---|
[749a7d4] | 847 | def test_cylinder(): |
---|
[fa5fd8d] | 848 | # type: () -> float |
---|
[4d76711] | 849 | """ |
---|
[749a7d4] | 850 | Test that the cylinder model runs, returning the value at [0.1,0.1]. |
---|
[4d76711] | 851 | """ |
---|
| 852 | Cylinder = _make_standard_model('cylinder') |
---|
[fb5914f] | 853 | cylinder = Cylinder() |
---|
[b32dafd] | 854 | return cylinder.evalDistribution([0.1, 0.1]) |
---|
[de97440] | 855 | |
---|
[8f93522] | 856 | def test_structure_factor(): |
---|
| 857 | # type: () -> float |
---|
| 858 | """ |
---|
[749a7d4] | 859 | Test that 2-D hardsphere model runs and doesn't produce NaN. |
---|
[8f93522] | 860 | """ |
---|
| 861 | Model = _make_standard_model('hardsphere') |
---|
| 862 | model = Model() |
---|
[17db833] | 863 | value2d = model.evalDistribution([0.1, 0.1]) |
---|
| 864 | value1d = model.evalDistribution(np.array([0.1*np.sqrt(2)])) |
---|
| 865 | #print("hardsphere", value1d, value2d) |
---|
| 866 | if np.isnan(value1d) or np.isnan(value2d): |
---|
| 867 | raise ValueError("hardsphere returns nan") |
---|
[8f93522] | 868 | |
---|
[ce99754] | 869 | def test_product(): |
---|
| 870 | # type: () -> float |
---|
| 871 | """ |
---|
| 872 | Test that 2-D hardsphere model runs and doesn't produce NaN. |
---|
| 873 | """ |
---|
| 874 | S = _make_standard_model('hayter_msa')() |
---|
| 875 | P = _make_standard_model('cylinder')() |
---|
| 876 | model = MultiplicationModel(P, S) |
---|
[5024a56] | 877 | model.setParam(product.RADIUS_MODE_ID, 1.0) |
---|
[ce99754] | 878 | value = model.evalDistribution([0.1, 0.1]) |
---|
| 879 | if np.isnan(value): |
---|
| 880 | raise ValueError("cylinder*hatyer_msa returns null") |
---|
| 881 | |
---|
[04045f4] | 882 | def test_rpa(): |
---|
| 883 | # type: () -> float |
---|
| 884 | """ |
---|
[749a7d4] | 885 | Test that the 2-D RPA model runs |
---|
[04045f4] | 886 | """ |
---|
| 887 | RPA = _make_standard_model('rpa') |
---|
| 888 | rpa = RPA(3) |
---|
[b32dafd] | 889 | return rpa.evalDistribution([0.1, 0.1]) |
---|
[04045f4] | 890 | |
---|
[749a7d4] | 891 | def test_empty_distribution(): |
---|
| 892 | # type: () -> None |
---|
| 893 | """ |
---|
| 894 | Make sure that sasmodels returns NaN when there are no polydispersity points |
---|
| 895 | """ |
---|
| 896 | Cylinder = _make_standard_model('cylinder') |
---|
| 897 | cylinder = Cylinder() |
---|
| 898 | cylinder.setParam('radius', -1.0) |
---|
| 899 | cylinder.setParam('background', 0.) |
---|
| 900 | Iq = cylinder.evalDistribution(np.asarray([0.1])) |
---|
[2d81cfe] | 901 | assert Iq[0] == 0., "empty distribution fails" |
---|
[4d76711] | 902 | |
---|
| 903 | def test_model_list(): |
---|
[fa5fd8d] | 904 | # type: () -> None |
---|
[4d76711] | 905 | """ |
---|
[749a7d4] | 906 | Make sure that all models build as sasview models |
---|
[4d76711] | 907 | """ |
---|
| 908 | from .exception import annotate_exception |
---|
| 909 | for name in core.list_models(): |
---|
| 910 | try: |
---|
| 911 | _make_standard_model(name) |
---|
| 912 | except: |
---|
| 913 | annotate_exception("when loading "+name) |
---|
| 914 | raise |
---|
| 915 | |
---|
[c95dfc63] | 916 | def test_old_name(): |
---|
| 917 | # type: () -> None |
---|
| 918 | """ |
---|
[a69d8cd] | 919 | Load and run cylinder model as sas-models-CylinderModel |
---|
[c95dfc63] | 920 | """ |
---|
| 921 | if not SUPPORT_OLD_STYLE_PLUGINS: |
---|
| 922 | return |
---|
| 923 | try: |
---|
| 924 | # if sasview is not on the path then don't try to test it |
---|
| 925 | import sas |
---|
| 926 | except ImportError: |
---|
| 927 | return |
---|
| 928 | load_standard_models() |
---|
| 929 | from sas.models.CylinderModel import CylinderModel |
---|
| 930 | CylinderModel().evalDistribution([0.1, 0.1]) |
---|
| 931 | |
---|
[293fee5] | 932 | def test_structure_factor_background(): |
---|
| 933 | # type: () -> None |
---|
| 934 | """ |
---|
| 935 | Check that sasview model and direct model match, with background=0. |
---|
| 936 | """ |
---|
| 937 | from .data import empty_data1D |
---|
| 938 | from .core import load_model_info, build_model |
---|
| 939 | from .direct_model import DirectModel |
---|
| 940 | |
---|
| 941 | model_name = "hardsphere" |
---|
| 942 | q = [0.0] |
---|
| 943 | |
---|
| 944 | sasview_model = _make_standard_model(model_name)() |
---|
| 945 | sasview_value = sasview_model.evalDistribution(np.array(q))[0] |
---|
| 946 | |
---|
| 947 | data = empty_data1D(q) |
---|
| 948 | model_info = load_model_info(model_name) |
---|
| 949 | model = build_model(model_info) |
---|
| 950 | direct_model = DirectModel(data, model) |
---|
| 951 | direct_value_zero_background = direct_model(background=0.0) |
---|
| 952 | |
---|
| 953 | assert sasview_value == direct_value_zero_background |
---|
| 954 | |
---|
| 955 | # Additionally check that direct value background defaults to zero |
---|
| 956 | direct_value_default = direct_model() |
---|
| 957 | assert sasview_value == direct_value_default |
---|
| 958 | |
---|
| 959 | |
---|
[05df1de] | 960 | def magnetic_demo(): |
---|
| 961 | Model = _make_standard_model('sphere') |
---|
| 962 | model = Model() |
---|
[610ef23] | 963 | model.setParam('sld_M0', 8) |
---|
[05df1de] | 964 | q = np.linspace(-0.35, 0.35, 500) |
---|
| 965 | qx, qy = np.meshgrid(q, q) |
---|
[84f2962] | 966 | result, _ = model.calculate_Iq(qx.flatten(), qy.flatten()) |
---|
[05df1de] | 967 | result = result.reshape(qx.shape) |
---|
| 968 | |
---|
| 969 | import pylab |
---|
| 970 | pylab.imshow(np.log(result + 0.001)) |
---|
| 971 | pylab.show() |
---|
| 972 | |
---|
[fb5914f] | 973 | if __name__ == "__main__": |
---|
[749a7d4] | 974 | print("cylinder(0.1,0.1)=%g"%test_cylinder()) |
---|
[05df1de] | 975 | #magnetic_demo() |
---|
[ce99754] | 976 | #test_product() |
---|
[17db833] | 977 | #test_structure_factor() |
---|
| 978 | #print("rpa:", test_rpa()) |
---|
[749a7d4] | 979 | #test_empty_distribution() |
---|
[293fee5] | 980 | #test_structure_factor_background() |
---|