[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 |
---|
[9457498] | 17 | from os.path import basename, splitext |
---|
[ce27e21] | 18 | |
---|
[7ae2b7f] | 19 | import numpy as np # type: ignore |
---|
[ce27e21] | 20 | |
---|
[aa4946b] | 21 | from . import core |
---|
[4d76711] | 22 | from . import custom |
---|
[72a081d] | 23 | from . import generate |
---|
[fb5914f] | 24 | from . import weights |
---|
[6d6508e] | 25 | from . import modelinfo |
---|
[bde38b5] | 26 | from .details import make_kernel_args, dispersion_mesh |
---|
[ff7119b] | 27 | |
---|
[fa5fd8d] | 28 | try: |
---|
[60f03de] | 29 | from typing import Dict, Mapping, Any, Sequence, Tuple, NamedTuple, List, Optional, Union, Callable |
---|
[fa5fd8d] | 30 | from .modelinfo import ModelInfo, Parameter |
---|
| 31 | from .kernel import KernelModel |
---|
| 32 | MultiplicityInfoType = NamedTuple( |
---|
| 33 | 'MuliplicityInfo', |
---|
| 34 | [("number", int), ("control", str), ("choices", List[str]), |
---|
| 35 | ("x_axis_label", str)]) |
---|
[60f03de] | 36 | SasviewModelType = Callable[[int], "SasviewModel"] |
---|
[fa5fd8d] | 37 | except ImportError: |
---|
| 38 | pass |
---|
| 39 | |
---|
[c95dfc63] | 40 | SUPPORT_OLD_STYLE_PLUGINS = True |
---|
| 41 | |
---|
| 42 | def _register_old_models(): |
---|
| 43 | # type: () -> None |
---|
| 44 | """ |
---|
| 45 | Place the new models into sasview under the old names. |
---|
| 46 | |
---|
| 47 | Monkey patch sas.sascalc.fit as sas.models so that sas.models.pluginmodel |
---|
| 48 | is available to the plugin modules. |
---|
| 49 | """ |
---|
| 50 | import sys |
---|
| 51 | import sas |
---|
| 52 | import sas.sascalc.fit |
---|
| 53 | sys.modules['sas.models'] = sas.sascalc.fit |
---|
| 54 | sas.models = sas.sascalc.fit |
---|
| 55 | |
---|
| 56 | import sas.models |
---|
| 57 | from sasmodels.conversion_table import CONVERSION_TABLE |
---|
| 58 | for new_name, conversion in CONVERSION_TABLE.items(): |
---|
| 59 | old_name = conversion[0] |
---|
[fd19811] | 60 | module_attrs = {old_name: find_model(new_name)} |
---|
[c95dfc63] | 61 | ConstructedModule = type(old_name, (), module_attrs) |
---|
| 62 | old_path = 'sas.models.' + old_name |
---|
| 63 | setattr(sas.models, old_path, ConstructedModule) |
---|
| 64 | sys.modules[old_path] = ConstructedModule |
---|
| 65 | |
---|
[9457498] | 66 | |
---|
[fa5fd8d] | 67 | # TODO: separate x_axis_label from multiplicity info |
---|
| 68 | MultiplicityInfo = collections.namedtuple( |
---|
| 69 | 'MultiplicityInfo', |
---|
| 70 | ["number", "control", "choices", "x_axis_label"], |
---|
| 71 | ) |
---|
| 72 | |
---|
[92d38285] | 73 | MODELS = {} |
---|
| 74 | def find_model(modelname): |
---|
[b32dafd] | 75 | # type: (str) -> SasviewModelType |
---|
| 76 | """ |
---|
| 77 | Find a model by name. If the model name ends in py, try loading it from |
---|
| 78 | custom models, otherwise look for it in the list of builtin models. |
---|
| 79 | """ |
---|
[92d38285] | 80 | # TODO: used by sum/product model to load an existing model |
---|
| 81 | # TODO: doesn't handle custom models properly |
---|
| 82 | if modelname.endswith('.py'): |
---|
| 83 | return load_custom_model(modelname) |
---|
| 84 | elif modelname in MODELS: |
---|
| 85 | return MODELS[modelname] |
---|
| 86 | else: |
---|
| 87 | raise ValueError("unknown model %r"%modelname) |
---|
| 88 | |
---|
[56b2687] | 89 | |
---|
[fa5fd8d] | 90 | # TODO: figure out how to say that the return type is a subclass |
---|
[4d76711] | 91 | def load_standard_models(): |
---|
[60f03de] | 92 | # type: () -> List[SasviewModelType] |
---|
[4d76711] | 93 | """ |
---|
| 94 | Load and return the list of predefined models. |
---|
| 95 | |
---|
| 96 | If there is an error loading a model, then a traceback is logged and the |
---|
| 97 | model is not returned. |
---|
| 98 | """ |
---|
| 99 | models = [] |
---|
| 100 | for name in core.list_models(): |
---|
| 101 | try: |
---|
[92d38285] | 102 | MODELS[name] = _make_standard_model(name) |
---|
| 103 | models.append(MODELS[name]) |
---|
[ee8f734] | 104 | except Exception: |
---|
[4d76711] | 105 | logging.error(traceback.format_exc()) |
---|
[c95dfc63] | 106 | if SUPPORT_OLD_STYLE_PLUGINS: |
---|
| 107 | _register_old_models() |
---|
| 108 | |
---|
[4d76711] | 109 | return models |
---|
[de97440] | 110 | |
---|
[4d76711] | 111 | |
---|
| 112 | def load_custom_model(path): |
---|
[60f03de] | 113 | # type: (str) -> SasviewModelType |
---|
[4d76711] | 114 | """ |
---|
| 115 | Load a custom model given the model path. |
---|
[ff7119b] | 116 | """ |
---|
[300a2f7] | 117 | #print("load custom", path) |
---|
[4d76711] | 118 | kernel_module = custom.load_custom_kernel_module(path) |
---|
[92d38285] | 119 | try: |
---|
| 120 | model = kernel_module.Model |
---|
[9457498] | 121 | # Old style models do not set the name in the class attributes, so |
---|
| 122 | # set it here; this name will be overridden when the object is created |
---|
| 123 | # with an instance variable that has the same value. |
---|
| 124 | if model.name == "": |
---|
| 125 | model.name = splitext(basename(path))[0] |
---|
[92d38285] | 126 | except AttributeError: |
---|
[56b2687] | 127 | model_info = modelinfo.make_model_info(kernel_module) |
---|
[92d38285] | 128 | model = _make_model_from_info(model_info) |
---|
| 129 | MODELS[model.name] = model |
---|
| 130 | return model |
---|
[4d76711] | 131 | |
---|
[87985ca] | 132 | |
---|
[4d76711] | 133 | def _make_standard_model(name): |
---|
[60f03de] | 134 | # type: (str) -> SasviewModelType |
---|
[ff7119b] | 135 | """ |
---|
[4d76711] | 136 | Load the sasview model defined by *name*. |
---|
[72a081d] | 137 | |
---|
[4d76711] | 138 | *name* can be a standard model name or a path to a custom model. |
---|
[87985ca] | 139 | |
---|
[4d76711] | 140 | Returns a class that can be used directly as a sasview model. |
---|
[ff7119b] | 141 | """ |
---|
[4d76711] | 142 | kernel_module = generate.load_kernel_module(name) |
---|
[fa5fd8d] | 143 | model_info = modelinfo.make_model_info(kernel_module) |
---|
[4d76711] | 144 | return _make_model_from_info(model_info) |
---|
[72a081d] | 145 | |
---|
| 146 | |
---|
[4d76711] | 147 | def _make_model_from_info(model_info): |
---|
[60f03de] | 148 | # type: (ModelInfo) -> SasviewModelType |
---|
[4d76711] | 149 | """ |
---|
| 150 | Convert *model_info* into a SasView model wrapper. |
---|
| 151 | """ |
---|
[fa5fd8d] | 152 | def __init__(self, multiplicity=None): |
---|
| 153 | SasviewModel.__init__(self, multiplicity=multiplicity) |
---|
| 154 | attrs = _generate_model_attributes(model_info) |
---|
| 155 | attrs['__init__'] = __init__ |
---|
[60f03de] | 156 | ConstructedModel = type(model_info.name, (SasviewModel,), attrs) # type: SasviewModelType |
---|
[ce27e21] | 157 | return ConstructedModel |
---|
| 158 | |
---|
[fa5fd8d] | 159 | def _generate_model_attributes(model_info): |
---|
| 160 | # type: (ModelInfo) -> Dict[str, Any] |
---|
| 161 | """ |
---|
| 162 | Generate the class attributes for the model. |
---|
| 163 | |
---|
| 164 | This should include all the information necessary to query the model |
---|
| 165 | details so that you do not need to instantiate a model to query it. |
---|
| 166 | |
---|
| 167 | All the attributes should be immutable to avoid accidents. |
---|
| 168 | """ |
---|
| 169 | |
---|
| 170 | # TODO: allow model to override axis labels input/output name/unit |
---|
| 171 | |
---|
[a18c5b3] | 172 | # Process multiplicity |
---|
[fa5fd8d] | 173 | non_fittable = [] # type: List[str] |
---|
[04045f4] | 174 | xlabel = model_info.profile_axes[0] if model_info.profile is not None else "" |
---|
| 175 | variants = MultiplicityInfo(0, "", [], xlabel) |
---|
[a18c5b3] | 176 | for p in model_info.parameters.kernel_parameters: |
---|
[04045f4] | 177 | if p.name == model_info.control: |
---|
[fa5fd8d] | 178 | non_fittable.append(p.name) |
---|
[04045f4] | 179 | variants = MultiplicityInfo( |
---|
[ce176ca] | 180 | len(p.choices) if p.choices else int(p.limits[1]), |
---|
| 181 | p.name, p.choices, xlabel |
---|
[fa5fd8d] | 182 | ) |
---|
| 183 | break |
---|
| 184 | |
---|
[50ec515] | 185 | # Only a single drop-down list parameter available |
---|
| 186 | fun_list = [] |
---|
| 187 | for p in model_info.parameters.kernel_parameters: |
---|
| 188 | if p.choices: |
---|
| 189 | fun_list = p.choices |
---|
| 190 | if p.length > 1: |
---|
| 191 | non_fittable.extend(p.id+str(k) for k in range(1, p.length+1)) |
---|
| 192 | break |
---|
| 193 | |
---|
[a18c5b3] | 194 | # Organize parameter sets |
---|
[fa5fd8d] | 195 | orientation_params = [] |
---|
| 196 | magnetic_params = [] |
---|
| 197 | fixed = [] |
---|
[a18c5b3] | 198 | for p in model_info.parameters.user_parameters(): |
---|
[fa5fd8d] | 199 | if p.type == 'orientation': |
---|
| 200 | orientation_params.append(p.name) |
---|
| 201 | orientation_params.append(p.name+".width") |
---|
| 202 | fixed.append(p.name+".width") |
---|
[32e3c9b] | 203 | elif p.type == 'magnetic': |
---|
[fa5fd8d] | 204 | orientation_params.append(p.name) |
---|
| 205 | magnetic_params.append(p.name) |
---|
| 206 | fixed.append(p.name+".width") |
---|
[a18c5b3] | 207 | |
---|
[32e3c9b] | 208 | |
---|
[a18c5b3] | 209 | # Build class dictionary |
---|
| 210 | attrs = {} # type: Dict[str, Any] |
---|
| 211 | attrs['_model_info'] = model_info |
---|
| 212 | attrs['name'] = model_info.name |
---|
| 213 | attrs['id'] = model_info.id |
---|
| 214 | attrs['description'] = model_info.description |
---|
| 215 | attrs['category'] = model_info.category |
---|
| 216 | attrs['is_structure_factor'] = model_info.structure_factor |
---|
| 217 | attrs['is_form_factor'] = model_info.ER is not None |
---|
| 218 | attrs['is_multiplicity_model'] = variants[0] > 1 |
---|
| 219 | attrs['multiplicity_info'] = variants |
---|
[fa5fd8d] | 220 | attrs['orientation_params'] = tuple(orientation_params) |
---|
| 221 | attrs['magnetic_params'] = tuple(magnetic_params) |
---|
| 222 | attrs['fixed'] = tuple(fixed) |
---|
| 223 | attrs['non_fittable'] = tuple(non_fittable) |
---|
[50ec515] | 224 | attrs['fun_list'] = tuple(fun_list) |
---|
[fa5fd8d] | 225 | |
---|
| 226 | return attrs |
---|
[4d76711] | 227 | |
---|
[ce27e21] | 228 | class SasviewModel(object): |
---|
| 229 | """ |
---|
| 230 | Sasview wrapper for opencl/ctypes model. |
---|
| 231 | """ |
---|
[fa5fd8d] | 232 | # Model parameters for the specific model are set in the class constructor |
---|
| 233 | # via the _generate_model_attributes function, which subclasses |
---|
| 234 | # SasviewModel. They are included here for typing and documentation |
---|
| 235 | # purposes. |
---|
| 236 | _model = None # type: KernelModel |
---|
| 237 | _model_info = None # type: ModelInfo |
---|
| 238 | #: load/save name for the model |
---|
| 239 | id = None # type: str |
---|
| 240 | #: display name for the model |
---|
| 241 | name = None # type: str |
---|
| 242 | #: short model description |
---|
| 243 | description = None # type: str |
---|
| 244 | #: default model category |
---|
| 245 | category = None # type: str |
---|
| 246 | |
---|
| 247 | #: names of the orientation parameters in the order they appear |
---|
| 248 | orientation_params = None # type: Sequence[str] |
---|
| 249 | #: names of the magnetic parameters in the order they appear |
---|
| 250 | magnetic_params = None # type: Sequence[str] |
---|
| 251 | #: names of the fittable parameters |
---|
| 252 | fixed = None # type: Sequence[str] |
---|
| 253 | # TODO: the attribute fixed is ill-named |
---|
| 254 | |
---|
| 255 | # Axis labels |
---|
| 256 | input_name = "Q" |
---|
| 257 | input_unit = "A^{-1}" |
---|
| 258 | output_name = "Intensity" |
---|
| 259 | output_unit = "cm^{-1}" |
---|
| 260 | |
---|
| 261 | #: default cutoff for polydispersity |
---|
| 262 | cutoff = 1e-5 |
---|
| 263 | |
---|
| 264 | # Note: Use non-mutable values for class attributes to avoid errors |
---|
| 265 | #: parameters that are not fitted |
---|
| 266 | non_fittable = () # type: Sequence[str] |
---|
| 267 | |
---|
| 268 | #: True if model should appear as a structure factor |
---|
| 269 | is_structure_factor = False |
---|
| 270 | #: True if model should appear as a form factor |
---|
| 271 | is_form_factor = False |
---|
| 272 | #: True if model has multiplicity |
---|
| 273 | is_multiplicity_model = False |
---|
| 274 | #: Mulitplicity information |
---|
| 275 | multiplicity_info = None # type: MultiplicityInfoType |
---|
| 276 | |
---|
| 277 | # Per-instance variables |
---|
| 278 | #: parameter {name: value} mapping |
---|
| 279 | params = None # type: Dict[str, float] |
---|
| 280 | #: values for dispersion width, npts, nsigmas and type |
---|
| 281 | dispersion = None # type: Dict[str, Any] |
---|
| 282 | #: units and limits for each parameter |
---|
[60f03de] | 283 | details = None # type: Dict[str, Sequence[Any]] |
---|
| 284 | # # actual type is Dict[str, List[str, float, float]] |
---|
[04dc697] | 285 | #: multiplicity value, or None if no multiplicity on the model |
---|
[fa5fd8d] | 286 | multiplicity = None # type: Optional[int] |
---|
[04dc697] | 287 | #: memory for polydispersity array if using ArrayDispersion (used by sasview). |
---|
| 288 | _persistency_dict = None # type: Dict[str, Tuple[np.ndarray, np.ndarray]] |
---|
[fa5fd8d] | 289 | |
---|
| 290 | def __init__(self, multiplicity=None): |
---|
[04dc697] | 291 | # type: (Optional[int]) -> None |
---|
[2622b3f] | 292 | |
---|
[04045f4] | 293 | # TODO: _persistency_dict to persistency_dict throughout sasview |
---|
| 294 | # TODO: refactor multiplicity to encompass variants |
---|
| 295 | # TODO: dispersion should be a class |
---|
[fa5fd8d] | 296 | # TODO: refactor multiplicity info |
---|
| 297 | # TODO: separate profile view from multiplicity |
---|
| 298 | # The button label, x and y axis labels and scale need to be under |
---|
| 299 | # the control of the model, not the fit page. Maximum flexibility, |
---|
| 300 | # the fit page would supply the canvas and the profile could plot |
---|
| 301 | # how it wants, but this assumes matplotlib. Next level is that |
---|
| 302 | # we provide some sort of data description including title, labels |
---|
| 303 | # and lines to plot. |
---|
| 304 | |
---|
[04045f4] | 305 | # Get the list of hidden parameters given the mulitplicity |
---|
| 306 | # Don't include multiplicity in the list of parameters |
---|
[fa5fd8d] | 307 | self.multiplicity = multiplicity |
---|
[04045f4] | 308 | if multiplicity is not None: |
---|
| 309 | hidden = self._model_info.get_hidden_parameters(multiplicity) |
---|
| 310 | hidden |= set([self.multiplicity_info.control]) |
---|
| 311 | else: |
---|
| 312 | hidden = set() |
---|
| 313 | |
---|
[04dc697] | 314 | self._persistency_dict = {} |
---|
[fa5fd8d] | 315 | self.params = collections.OrderedDict() |
---|
[b3a85cd] | 316 | self.dispersion = collections.OrderedDict() |
---|
[fa5fd8d] | 317 | self.details = {} |
---|
[04045f4] | 318 | for p in self._model_info.parameters.user_parameters(): |
---|
| 319 | if p.name in hidden: |
---|
[fa5fd8d] | 320 | continue |
---|
[fcd7bbd] | 321 | self.params[p.name] = p.default |
---|
[fa5fd8d] | 322 | self.details[p.id] = [p.units, p.limits[0], p.limits[1]] |
---|
[fb5914f] | 323 | if p.polydisperse: |
---|
[fa5fd8d] | 324 | self.details[p.id+".width"] = [ |
---|
| 325 | "", 0.0, 1.0 if p.relative_pd else np.inf |
---|
| 326 | ] |
---|
[fb5914f] | 327 | self.dispersion[p.name] = { |
---|
| 328 | 'width': 0, |
---|
| 329 | 'npts': 35, |
---|
| 330 | 'nsigmas': 3, |
---|
| 331 | 'type': 'gaussian', |
---|
| 332 | } |
---|
[ce27e21] | 333 | |
---|
[de97440] | 334 | def __get_state__(self): |
---|
[fa5fd8d] | 335 | # type: () -> Dict[str, Any] |
---|
[de97440] | 336 | state = self.__dict__.copy() |
---|
[4d76711] | 337 | state.pop('_model') |
---|
[de97440] | 338 | # May need to reload model info on set state since it has pointers |
---|
| 339 | # to python implementations of Iq, etc. |
---|
| 340 | #state.pop('_model_info') |
---|
| 341 | return state |
---|
| 342 | |
---|
| 343 | def __set_state__(self, state): |
---|
[fa5fd8d] | 344 | # type: (Dict[str, Any]) -> None |
---|
[de97440] | 345 | self.__dict__ = state |
---|
[fb5914f] | 346 | self._model = None |
---|
[de97440] | 347 | |
---|
[ce27e21] | 348 | def __str__(self): |
---|
[fa5fd8d] | 349 | # type: () -> str |
---|
[ce27e21] | 350 | """ |
---|
| 351 | :return: string representation |
---|
| 352 | """ |
---|
| 353 | return self.name |
---|
| 354 | |
---|
| 355 | def is_fittable(self, par_name): |
---|
[fa5fd8d] | 356 | # type: (str) -> bool |
---|
[ce27e21] | 357 | """ |
---|
| 358 | Check if a given parameter is fittable or not |
---|
| 359 | |
---|
| 360 | :param par_name: the parameter name to check |
---|
| 361 | """ |
---|
[e758662] | 362 | return par_name in self.fixed |
---|
[ce27e21] | 363 | #For the future |
---|
| 364 | #return self.params[str(par_name)].is_fittable() |
---|
| 365 | |
---|
| 366 | |
---|
| 367 | def getProfile(self): |
---|
[fa5fd8d] | 368 | # type: () -> (np.ndarray, np.ndarray) |
---|
[ce27e21] | 369 | """ |
---|
| 370 | Get SLD profile |
---|
| 371 | |
---|
| 372 | : return: (z, beta) where z is a list of depth of the transition points |
---|
| 373 | beta is a list of the corresponding SLD values |
---|
| 374 | """ |
---|
[745b7bb] | 375 | args = {} # type: Dict[str, Any] |
---|
[fa5fd8d] | 376 | for p in self._model_info.parameters.kernel_parameters: |
---|
| 377 | if p.id == self.multiplicity_info.control: |
---|
[745b7bb] | 378 | value = float(self.multiplicity) |
---|
[fa5fd8d] | 379 | elif p.length == 1: |
---|
[745b7bb] | 380 | value = self.params.get(p.id, np.NaN) |
---|
[fa5fd8d] | 381 | else: |
---|
[745b7bb] | 382 | value = np.array([self.params.get(p.id+str(k), np.NaN) |
---|
[b32dafd] | 383 | for k in range(1, p.length+1)]) |
---|
[745b7bb] | 384 | args[p.id] = value |
---|
| 385 | |
---|
[e7fe459] | 386 | x, y = self._model_info.profile(**args) |
---|
| 387 | return x, 1e-6*y |
---|
[ce27e21] | 388 | |
---|
| 389 | def setParam(self, name, value): |
---|
[fa5fd8d] | 390 | # type: (str, float) -> None |
---|
[ce27e21] | 391 | """ |
---|
| 392 | Set the value of a model parameter |
---|
| 393 | |
---|
| 394 | :param name: name of the parameter |
---|
| 395 | :param value: value of the parameter |
---|
| 396 | |
---|
| 397 | """ |
---|
| 398 | # Look for dispersion parameters |
---|
| 399 | toks = name.split('.') |
---|
[de0c4ba] | 400 | if len(toks) == 2: |
---|
[ce27e21] | 401 | for item in self.dispersion.keys(): |
---|
[e758662] | 402 | if item == toks[0]: |
---|
[ce27e21] | 403 | for par in self.dispersion[item]: |
---|
[e758662] | 404 | if par == toks[1]: |
---|
[ce27e21] | 405 | self.dispersion[item][par] = value |
---|
| 406 | return |
---|
| 407 | else: |
---|
| 408 | # Look for standard parameter |
---|
| 409 | for item in self.params.keys(): |
---|
[e758662] | 410 | if item == name: |
---|
[ce27e21] | 411 | self.params[item] = value |
---|
| 412 | return |
---|
| 413 | |
---|
[63b32bb] | 414 | raise ValueError("Model does not contain parameter %s" % name) |
---|
[ce27e21] | 415 | |
---|
| 416 | def getParam(self, name): |
---|
[fa5fd8d] | 417 | # type: (str) -> float |
---|
[ce27e21] | 418 | """ |
---|
| 419 | Set the value of a model parameter |
---|
| 420 | |
---|
| 421 | :param name: name of the parameter |
---|
| 422 | |
---|
| 423 | """ |
---|
| 424 | # Look for dispersion parameters |
---|
| 425 | toks = name.split('.') |
---|
[de0c4ba] | 426 | if len(toks) == 2: |
---|
[ce27e21] | 427 | for item in self.dispersion.keys(): |
---|
[e758662] | 428 | if item == toks[0]: |
---|
[ce27e21] | 429 | for par in self.dispersion[item]: |
---|
[e758662] | 430 | if par == toks[1]: |
---|
[ce27e21] | 431 | return self.dispersion[item][par] |
---|
| 432 | else: |
---|
| 433 | # Look for standard parameter |
---|
| 434 | for item in self.params.keys(): |
---|
[e758662] | 435 | if item == name: |
---|
[ce27e21] | 436 | return self.params[item] |
---|
| 437 | |
---|
[63b32bb] | 438 | raise ValueError("Model does not contain parameter %s" % name) |
---|
[ce27e21] | 439 | |
---|
| 440 | def getParamList(self): |
---|
[04dc697] | 441 | # type: () -> Sequence[str] |
---|
[ce27e21] | 442 | """ |
---|
| 443 | Return a list of all available parameters for the model |
---|
| 444 | """ |
---|
[04dc697] | 445 | param_list = list(self.params.keys()) |
---|
[ce27e21] | 446 | # WARNING: Extending the list with the dispersion parameters |
---|
[de0c4ba] | 447 | param_list.extend(self.getDispParamList()) |
---|
| 448 | return param_list |
---|
[ce27e21] | 449 | |
---|
| 450 | def getDispParamList(self): |
---|
[04dc697] | 451 | # type: () -> Sequence[str] |
---|
[ce27e21] | 452 | """ |
---|
[fb5914f] | 453 | Return a list of polydispersity parameters for the model |
---|
[ce27e21] | 454 | """ |
---|
[1780d59] | 455 | # TODO: fix test so that parameter order doesn't matter |
---|
[3bcb88c] | 456 | ret = ['%s.%s' % (p_name, ext) |
---|
| 457 | for p_name in self.dispersion.keys() |
---|
| 458 | for ext in ('npts', 'nsigmas', 'width')] |
---|
[9404dd3] | 459 | #print(ret) |
---|
[1780d59] | 460 | return ret |
---|
[ce27e21] | 461 | |
---|
| 462 | def clone(self): |
---|
[04dc697] | 463 | # type: () -> "SasviewModel" |
---|
[ce27e21] | 464 | """ Return a identical copy of self """ |
---|
| 465 | return deepcopy(self) |
---|
| 466 | |
---|
| 467 | def run(self, x=0.0): |
---|
[fa5fd8d] | 468 | # type: (Union[float, (float, float), List[float]]) -> float |
---|
[ce27e21] | 469 | """ |
---|
| 470 | Evaluate the model |
---|
| 471 | |
---|
| 472 | :param x: input q, or [q,phi] |
---|
| 473 | |
---|
| 474 | :return: scattering function P(q) |
---|
| 475 | |
---|
| 476 | **DEPRECATED**: use calculate_Iq instead |
---|
| 477 | """ |
---|
[de0c4ba] | 478 | if isinstance(x, (list, tuple)): |
---|
[3c56da87] | 479 | # pylint: disable=unpacking-non-sequence |
---|
[ce27e21] | 480 | q, phi = x |
---|
[60f03de] | 481 | return self.calculate_Iq([q*math.cos(phi)], [q*math.sin(phi)])[0] |
---|
[ce27e21] | 482 | else: |
---|
[60f03de] | 483 | return self.calculate_Iq([x])[0] |
---|
[ce27e21] | 484 | |
---|
| 485 | |
---|
| 486 | def runXY(self, x=0.0): |
---|
[fa5fd8d] | 487 | # type: (Union[float, (float, float), List[float]]) -> float |
---|
[ce27e21] | 488 | """ |
---|
| 489 | Evaluate the model in cartesian coordinates |
---|
| 490 | |
---|
| 491 | :param x: input q, or [qx, qy] |
---|
| 492 | |
---|
| 493 | :return: scattering function P(q) |
---|
| 494 | |
---|
| 495 | **DEPRECATED**: use calculate_Iq instead |
---|
| 496 | """ |
---|
[de0c4ba] | 497 | if isinstance(x, (list, tuple)): |
---|
[60f03de] | 498 | return self.calculate_Iq([x[0]], [x[1]])[0] |
---|
[ce27e21] | 499 | else: |
---|
[60f03de] | 500 | return self.calculate_Iq([x])[0] |
---|
[ce27e21] | 501 | |
---|
| 502 | def evalDistribution(self, qdist): |
---|
[04dc697] | 503 | # type: (Union[np.ndarray, Tuple[np.ndarray, np.ndarray], List[np.ndarray]]) -> np.ndarray |
---|
[d138d43] | 504 | r""" |
---|
[ce27e21] | 505 | Evaluate a distribution of q-values. |
---|
| 506 | |
---|
[d138d43] | 507 | :param qdist: array of q or a list of arrays [qx,qy] |
---|
[ce27e21] | 508 | |
---|
[d138d43] | 509 | * For 1D, a numpy array is expected as input |
---|
[ce27e21] | 510 | |
---|
[d138d43] | 511 | :: |
---|
[ce27e21] | 512 | |
---|
[d138d43] | 513 | evalDistribution(q) |
---|
[ce27e21] | 514 | |
---|
[d138d43] | 515 | where *q* is a numpy array. |
---|
[ce27e21] | 516 | |
---|
[d138d43] | 517 | * For 2D, a list of *[qx,qy]* is expected with 1D arrays as input |
---|
[ce27e21] | 518 | |
---|
[d138d43] | 519 | :: |
---|
[ce27e21] | 520 | |
---|
[d138d43] | 521 | qx = [ qx[0], qx[1], qx[2], ....] |
---|
| 522 | qy = [ qy[0], qy[1], qy[2], ....] |
---|
[ce27e21] | 523 | |
---|
[d138d43] | 524 | If the model is 1D only, then |
---|
[ce27e21] | 525 | |
---|
[d138d43] | 526 | .. math:: |
---|
[ce27e21] | 527 | |
---|
[d138d43] | 528 | q = \sqrt{q_x^2+q_y^2} |
---|
[ce27e21] | 529 | |
---|
| 530 | """ |
---|
[de0c4ba] | 531 | if isinstance(qdist, (list, tuple)): |
---|
[ce27e21] | 532 | # Check whether we have a list of ndarrays [qx,qy] |
---|
| 533 | qx, qy = qdist |
---|
[6d6508e] | 534 | if not self._model_info.parameters.has_2d: |
---|
[de0c4ba] | 535 | return self.calculate_Iq(np.sqrt(qx ** 2 + qy ** 2)) |
---|
[5d4777d] | 536 | else: |
---|
| 537 | return self.calculate_Iq(qx, qy) |
---|
[ce27e21] | 538 | |
---|
| 539 | elif isinstance(qdist, np.ndarray): |
---|
| 540 | # We have a simple 1D distribution of q-values |
---|
| 541 | return self.calculate_Iq(qdist) |
---|
| 542 | |
---|
| 543 | else: |
---|
[3c56da87] | 544 | raise TypeError("evalDistribution expects q or [qx, qy], not %r" |
---|
| 545 | % type(qdist)) |
---|
[ce27e21] | 546 | |
---|
[fa5fd8d] | 547 | def calculate_Iq(self, qx, qy=None): |
---|
| 548 | # type: (Sequence[float], Optional[Sequence[float]]) -> np.ndarray |
---|
[ff7119b] | 549 | """ |
---|
| 550 | Calculate Iq for one set of q with the current parameters. |
---|
| 551 | |
---|
| 552 | If the model is 1D, use *q*. If 2D, use *qx*, *qy*. |
---|
| 553 | |
---|
| 554 | This should NOT be used for fitting since it copies the *q* vectors |
---|
| 555 | to the card for each evaluation. |
---|
| 556 | """ |
---|
[6a0d6aa] | 557 | #core.HAVE_OPENCL = False |
---|
[fb5914f] | 558 | if self._model is None: |
---|
[d2bb604] | 559 | self._model = core.build_model(self._model_info) |
---|
[fa5fd8d] | 560 | if qy is not None: |
---|
| 561 | q_vectors = [np.asarray(qx), np.asarray(qy)] |
---|
| 562 | else: |
---|
| 563 | q_vectors = [np.asarray(qx)] |
---|
[a738209] | 564 | calculator = self._model.make_kernel(q_vectors) |
---|
[6a0d6aa] | 565 | parameters = self._model_info.parameters |
---|
| 566 | pairs = [self._get_weights(p) for p in parameters.call_parameters] |
---|
[9c1a59c] | 567 | #weights.plot_weights(self._model_info, pairs) |
---|
[bde38b5] | 568 | call_details, values, is_magnetic = make_kernel_args(calculator, pairs) |
---|
[4edec6f] | 569 | #call_details.show() |
---|
| 570 | #print("pairs", pairs) |
---|
| 571 | #print("params", self.params) |
---|
| 572 | #print("values", values) |
---|
| 573 | #print("is_mag", is_magnetic) |
---|
[6a0d6aa] | 574 | result = calculator(call_details, values, cutoff=self.cutoff, |
---|
[9eb3632] | 575 | magnetic=is_magnetic) |
---|
[a738209] | 576 | calculator.release() |
---|
[ce27e21] | 577 | return result |
---|
| 578 | |
---|
| 579 | def calculate_ER(self): |
---|
[fa5fd8d] | 580 | # type: () -> float |
---|
[ce27e21] | 581 | """ |
---|
| 582 | Calculate the effective radius for P(q)*S(q) |
---|
| 583 | |
---|
| 584 | :return: the value of the effective radius |
---|
| 585 | """ |
---|
[4bfd277] | 586 | if self._model_info.ER is None: |
---|
[ce27e21] | 587 | return 1.0 |
---|
| 588 | else: |
---|
[4bfd277] | 589 | value, weight = self._dispersion_mesh() |
---|
| 590 | fv = self._model_info.ER(*value) |
---|
[9404dd3] | 591 | #print(values[0].shape, weights.shape, fv.shape) |
---|
[4bfd277] | 592 | return np.sum(weight * fv) / np.sum(weight) |
---|
[ce27e21] | 593 | |
---|
| 594 | def calculate_VR(self): |
---|
[fa5fd8d] | 595 | # type: () -> float |
---|
[ce27e21] | 596 | """ |
---|
| 597 | Calculate the volf ratio for P(q)*S(q) |
---|
| 598 | |
---|
| 599 | :return: the value of the volf ratio |
---|
| 600 | """ |
---|
[4bfd277] | 601 | if self._model_info.VR is None: |
---|
[ce27e21] | 602 | return 1.0 |
---|
| 603 | else: |
---|
[4bfd277] | 604 | value, weight = self._dispersion_mesh() |
---|
| 605 | whole, part = self._model_info.VR(*value) |
---|
| 606 | return np.sum(weight * part) / np.sum(weight * whole) |
---|
[ce27e21] | 607 | |
---|
| 608 | def set_dispersion(self, parameter, dispersion): |
---|
[fa5fd8d] | 609 | # type: (str, weights.Dispersion) -> Dict[str, Any] |
---|
[ce27e21] | 610 | """ |
---|
| 611 | Set the dispersion object for a model parameter |
---|
| 612 | |
---|
| 613 | :param parameter: name of the parameter [string] |
---|
| 614 | :param dispersion: dispersion object of type Dispersion |
---|
| 615 | """ |
---|
[fa800e72] | 616 | if parameter in self.params: |
---|
[1780d59] | 617 | # TODO: Store the disperser object directly in the model. |
---|
[56b2687] | 618 | # The current method of relying on the sasview GUI to |
---|
[fa800e72] | 619 | # remember them is kind of funky. |
---|
[1780d59] | 620 | # Note: can't seem to get disperser parameters from sasview |
---|
[9c1a59c] | 621 | # (1) Could create a sasview model that has not yet been |
---|
[1780d59] | 622 | # converted, assign the disperser to one of its polydisperse |
---|
| 623 | # parameters, then retrieve the disperser parameters from the |
---|
[9c1a59c] | 624 | # sasview model. |
---|
| 625 | # (2) Could write a disperser parameter retriever in sasview. |
---|
| 626 | # (3) Could modify sasview to use sasmodels.weights dispersers. |
---|
[1780d59] | 627 | # For now, rely on the fact that the sasview only ever uses |
---|
| 628 | # new dispersers in the set_dispersion call and create a new |
---|
| 629 | # one instead of trying to assign parameters. |
---|
[ce27e21] | 630 | self.dispersion[parameter] = dispersion.get_pars() |
---|
| 631 | else: |
---|
| 632 | raise ValueError("%r is not a dispersity or orientation parameter") |
---|
| 633 | |
---|
[aa4946b] | 634 | def _dispersion_mesh(self): |
---|
[fa5fd8d] | 635 | # type: () -> List[Tuple[np.ndarray, np.ndarray]] |
---|
[ce27e21] | 636 | """ |
---|
| 637 | Create a mesh grid of dispersion parameters and weights. |
---|
| 638 | |
---|
| 639 | Returns [p1,p2,...],w where pj is a vector of values for parameter j |
---|
| 640 | and w is a vector containing the products for weights for each |
---|
| 641 | parameter set in the vector. |
---|
| 642 | """ |
---|
[4bfd277] | 643 | pars = [self._get_weights(p) |
---|
| 644 | for p in self._model_info.parameters.call_parameters |
---|
| 645 | if p.type == 'volume'] |
---|
[9eb3632] | 646 | return dispersion_mesh(self._model_info, pars) |
---|
[ce27e21] | 647 | |
---|
| 648 | def _get_weights(self, par): |
---|
[fa5fd8d] | 649 | # type: (Parameter) -> Tuple[np.ndarray, np.ndarray] |
---|
[de0c4ba] | 650 | """ |
---|
[fb5914f] | 651 | Return dispersion weights for parameter |
---|
[de0c4ba] | 652 | """ |
---|
[fa5fd8d] | 653 | if par.name not in self.params: |
---|
| 654 | if par.name == self.multiplicity_info.control: |
---|
[4edec6f] | 655 | return [self.multiplicity], [1.0] |
---|
[fa5fd8d] | 656 | else: |
---|
[4edec6f] | 657 | return [np.NaN], [1.0] |
---|
[fa5fd8d] | 658 | elif par.polydisperse: |
---|
[fb5914f] | 659 | dis = self.dispersion[par.name] |
---|
[9c1a59c] | 660 | if dis['type'] == 'array': |
---|
| 661 | value, weight = dis['values'], dis['weights'] |
---|
| 662 | else: |
---|
| 663 | value, weight = weights.get_weights( |
---|
| 664 | dis['type'], dis['npts'], dis['width'], dis['nsigmas'], |
---|
| 665 | self.params[par.name], par.limits, par.relative_pd) |
---|
[fb5914f] | 666 | return value, weight / np.sum(weight) |
---|
| 667 | else: |
---|
[4edec6f] | 668 | return [self.params[par.name]], [1.0] |
---|
[ce27e21] | 669 | |
---|
[fb5914f] | 670 | def test_model(): |
---|
[fa5fd8d] | 671 | # type: () -> float |
---|
[4d76711] | 672 | """ |
---|
| 673 | Test that a sasview model (cylinder) can be run. |
---|
| 674 | """ |
---|
| 675 | Cylinder = _make_standard_model('cylinder') |
---|
[fb5914f] | 676 | cylinder = Cylinder() |
---|
[b32dafd] | 677 | return cylinder.evalDistribution([0.1, 0.1]) |
---|
[de97440] | 678 | |
---|
[04045f4] | 679 | def test_rpa(): |
---|
| 680 | # type: () -> float |
---|
| 681 | """ |
---|
| 682 | Test that a sasview model (cylinder) can be run. |
---|
| 683 | """ |
---|
| 684 | RPA = _make_standard_model('rpa') |
---|
| 685 | rpa = RPA(3) |
---|
[b32dafd] | 686 | return rpa.evalDistribution([0.1, 0.1]) |
---|
[04045f4] | 687 | |
---|
[4d76711] | 688 | |
---|
| 689 | def test_model_list(): |
---|
[fa5fd8d] | 690 | # type: () -> None |
---|
[4d76711] | 691 | """ |
---|
| 692 | Make sure that all models build as sasview models. |
---|
| 693 | """ |
---|
| 694 | from .exception import annotate_exception |
---|
| 695 | for name in core.list_models(): |
---|
| 696 | try: |
---|
| 697 | _make_standard_model(name) |
---|
| 698 | except: |
---|
| 699 | annotate_exception("when loading "+name) |
---|
| 700 | raise |
---|
| 701 | |
---|
[c95dfc63] | 702 | def test_old_name(): |
---|
| 703 | # type: () -> None |
---|
| 704 | """ |
---|
| 705 | Load and run cylinder model from sas.models.CylinderModel |
---|
| 706 | """ |
---|
| 707 | if not SUPPORT_OLD_STYLE_PLUGINS: |
---|
| 708 | return |
---|
| 709 | try: |
---|
| 710 | # if sasview is not on the path then don't try to test it |
---|
| 711 | import sas |
---|
| 712 | except ImportError: |
---|
| 713 | return |
---|
| 714 | load_standard_models() |
---|
| 715 | from sas.models.CylinderModel import CylinderModel |
---|
| 716 | CylinderModel().evalDistribution([0.1, 0.1]) |
---|
| 717 | |
---|
[fb5914f] | 718 | if __name__ == "__main__": |
---|
[ea05c87] | 719 | print("cylinder(0.1,0.1)=%g"%test_model()) |
---|