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