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