[0d99a6a] | 1 | """ |
---|
| 2 | Model Info and Parameter Tables |
---|
| 3 | =============================== |
---|
| 4 | |
---|
| 5 | Defines :class:`ModelInfo` and :class:`ParameterTable` and the routines for |
---|
| 6 | manipulating them. In particular, :func:`make_model_info` converts a kernel |
---|
| 7 | module into the model info block as seen by the rest of the sasmodels library. |
---|
| 8 | """ |
---|
[04045f4] | 9 | from __future__ import print_function |
---|
| 10 | |
---|
[6d6508e] | 11 | from copy import copy |
---|
| 12 | from os.path import abspath, basename, splitext |
---|
[da63656] | 13 | import inspect |
---|
[69aa451] | 14 | |
---|
[7ae2b7f] | 15 | import numpy as np # type: ignore |
---|
[69aa451] | 16 | |
---|
[a86f6c0] | 17 | # Optional typing |
---|
[2d81cfe] | 18 | # pylint: disable=unused-import |
---|
[a86f6c0] | 19 | try: |
---|
[04045f4] | 20 | from typing import Tuple, List, Union, Dict, Optional, Any, Callable, Sequence, Set |
---|
[e65c3ba] | 21 | from types import ModuleType |
---|
[a86f6c0] | 22 | except ImportError: |
---|
| 23 | pass |
---|
| 24 | else: |
---|
| 25 | Limits = Tuple[float, float] |
---|
[04dc697] | 26 | #LimitsOrChoice = Union[Limits, Tuple[Sequence[str]]] |
---|
[9a943d0] | 27 | ParameterDef = Tuple[str, str, float, Limits, str, str] |
---|
[a86f6c0] | 28 | ParameterSetUser = Dict[str, Union[float, List[float]]] |
---|
| 29 | ParameterSet = Dict[str, float] |
---|
| 30 | TestInput = Union[str, float, List[float], Tuple[float, float], List[Tuple[float, float]]] |
---|
| 31 | TestValue = Union[float, List[float]] |
---|
| 32 | TestCondition = Tuple[ParameterSetUser, TestInput, TestValue] |
---|
[2d81cfe] | 33 | # pylint: enable=unused-import |
---|
[a86f6c0] | 34 | |
---|
[6aee3ab] | 35 | # If MAX_PD changes, need to change the loop macros in kernel_iq.c |
---|
| 36 | MAX_PD = 5 #: Maximum number of simultaneously polydisperse parameters |
---|
[d19962c] | 37 | |
---|
[69aa451] | 38 | # assumptions about common parameters exist throughout the code, such as: |
---|
[108e70e] | 39 | # (1) kernel functions Iq, Iqxy, Iqac, Iqabc, form_volume, ... don't see them |
---|
[69aa451] | 40 | # (2) kernel drivers assume scale is par[0] and background is par[1] |
---|
| 41 | # (3) mixture models drop the background on components and replace the scale |
---|
| 42 | # with a scale that varies from [-inf, inf] |
---|
| 43 | # (4) product models drop the background and reassign scale |
---|
| 44 | # and maybe other places. |
---|
| 45 | # Note that scale and background cannot be coordinated parameters whose value |
---|
| 46 | # depends on the some polydisperse parameter with the current implementation |
---|
[7b9e4dd] | 47 | DEFAULT_BACKGROUND = 1e-3 |
---|
[7edce22] | 48 | COMMON_PARAMETERS = [ |
---|
[9a943d0] | 49 | ("scale", "", 1, (0.0, np.inf), "", "Source intensity"), |
---|
[7b9e4dd] | 50 | ("background", "1/cm", DEFAULT_BACKGROUND, (-np.inf, np.inf), "", "Source background"), |
---|
[7edce22] | 51 | ] |
---|
| 52 | assert (len(COMMON_PARAMETERS) == 2 |
---|
[40a87fa] | 53 | and COMMON_PARAMETERS[0][0] == "scale" |
---|
| 54 | and COMMON_PARAMETERS[1][0] == "background"), "don't change common parameters" |
---|
[69aa451] | 55 | |
---|
[a86f6c0] | 56 | |
---|
[69aa451] | 57 | def make_parameter_table(pars): |
---|
[f6029fd] | 58 | # type: (List[ParameterDef]) -> ParameterTable |
---|
[7edce22] | 59 | """ |
---|
| 60 | Construct a parameter table from a list of parameter definitions. |
---|
| 61 | |
---|
| 62 | This is used by the module processor to convert the parameter block into |
---|
| 63 | the parameter table seen in the :class:`ModelInfo` for the module. |
---|
| 64 | """ |
---|
[69aa451] | 65 | processed = [] |
---|
| 66 | for p in pars: |
---|
[a86f6c0] | 67 | if not isinstance(p, (list, tuple)) or len(p) != 6: |
---|
[69aa451] | 68 | raise ValueError("Parameter should be [name, units, default, limits, type, desc], but got %r" |
---|
| 69 | %str(p)) |
---|
| 70 | processed.append(parse_parameter(*p)) |
---|
| 71 | partable = ParameterTable(processed) |
---|
[95498a3] | 72 | partable.check_angles() |
---|
[69aa451] | 73 | return partable |
---|
| 74 | |
---|
[a86f6c0] | 75 | def parse_parameter(name, units='', default=np.NaN, |
---|
[04045f4] | 76 | user_limits=None, ptype='', description=''): |
---|
[60f03de] | 77 | # type: (str, str, float, Sequence[Any], str, str) -> Parameter |
---|
[7edce22] | 78 | """ |
---|
| 79 | Parse an individual parameter from the parameter definition block. |
---|
| 80 | |
---|
| 81 | This does type and value checking on the definition, leading |
---|
| 82 | to early failure in the model loading process and easier debugging. |
---|
| 83 | """ |
---|
[69aa451] | 84 | # Parameter is a user facing class. Do robust type checking. |
---|
| 85 | if not isstr(name): |
---|
| 86 | raise ValueError("expected string for parameter name %r"%name) |
---|
| 87 | if not isstr(units): |
---|
| 88 | raise ValueError("expected units to be a string for %s"%name) |
---|
[04045f4] | 89 | |
---|
| 90 | # Process limits as [float, float] or [[str, str, ...]] |
---|
[c1a888b] | 91 | choices = [] # type: List[str] |
---|
[04045f4] | 92 | if user_limits is None: |
---|
| 93 | limits = (-np.inf, np.inf) |
---|
| 94 | elif not isinstance(user_limits, (tuple, list)): |
---|
| 95 | raise ValueError("invalid limits for %s"%name) |
---|
| 96 | else: |
---|
| 97 | # if limits is [[str,...]], then this is a choice list field, |
---|
| 98 | # and limits are 1 to length of string list |
---|
| 99 | if isinstance(user_limits[0], (tuple, list)): |
---|
| 100 | choices = user_limits[0] |
---|
| 101 | limits = (0., len(choices)-1.) |
---|
| 102 | if not all(isstr(k) for k in choices): |
---|
| 103 | raise ValueError("choices must be strings for %s"%name) |
---|
| 104 | else: |
---|
| 105 | try: |
---|
| 106 | low, high = user_limits |
---|
| 107 | limits = (float(low), float(high)) |
---|
| 108 | except Exception: |
---|
[bb4b509] | 109 | raise ValueError("invalid limits for %s: %r"%(name, user_limits)) |
---|
[50ec515] | 110 | if low >= high: |
---|
| 111 | raise ValueError("require lower limit < upper limit") |
---|
[69aa451] | 112 | |
---|
[04045f4] | 113 | # Process default value as float, making sure it is in range |
---|
[69aa451] | 114 | if not isinstance(default, (int, float)): |
---|
| 115 | raise ValueError("expected default %r to be a number for %s" |
---|
| 116 | % (default, name)) |
---|
[04045f4] | 117 | if default < limits[0] or default > limits[1]: |
---|
[69aa451] | 118 | raise ValueError("default value %r not in range for %s" |
---|
| 119 | % (default, name)) |
---|
| 120 | |
---|
[04045f4] | 121 | # Check for valid parameter type |
---|
[a86f6c0] | 122 | if ptype not in ("volume", "orientation", "sld", "magnetic", ""): |
---|
| 123 | raise ValueError("unexpected type %r for %s" % (ptype, name)) |
---|
[69aa451] | 124 | |
---|
[04045f4] | 125 | # Check for valid parameter description |
---|
[69aa451] | 126 | if not isstr(description): |
---|
| 127 | raise ValueError("expected description to be a string") |
---|
| 128 | |
---|
| 129 | # Parameter id for name[n] does not include [n] |
---|
| 130 | if "[" in name: |
---|
| 131 | if not name.endswith(']'): |
---|
| 132 | raise ValueError("Expected name[len] for vector parameter %s"%name) |
---|
| 133 | pid, ref = name[:-1].split('[', 1) |
---|
| 134 | ref = ref.strip() |
---|
| 135 | else: |
---|
| 136 | pid, ref = name, None |
---|
| 137 | |
---|
| 138 | # automatically identify sld types |
---|
[40a87fa] | 139 | if ptype == '' and (pid.startswith('sld') or pid.endswith('sld')): |
---|
[a86f6c0] | 140 | ptype = 'sld' |
---|
[69aa451] | 141 | |
---|
| 142 | # Check if using a vector definition, name[k], as the parameter name |
---|
| 143 | if ref: |
---|
| 144 | if ref == '': |
---|
| 145 | raise ValueError("Need to specify vector length for %s"%name) |
---|
| 146 | try: |
---|
| 147 | length = int(ref) |
---|
| 148 | control = None |
---|
[a86f6c0] | 149 | except ValueError: |
---|
[69aa451] | 150 | length = None |
---|
| 151 | control = ref |
---|
| 152 | else: |
---|
| 153 | length = 1 |
---|
| 154 | control = None |
---|
| 155 | |
---|
| 156 | # Build the parameter |
---|
| 157 | parameter = Parameter(name=name, units=units, default=default, |
---|
[a86f6c0] | 158 | limits=limits, ptype=ptype, description=description) |
---|
[69aa451] | 159 | |
---|
| 160 | # TODO: need better control over whether a parameter is polydisperse |
---|
[a86f6c0] | 161 | parameter.polydisperse = ptype in ('orientation', 'volume') |
---|
| 162 | parameter.relative_pd = ptype == 'volume' |
---|
[69aa451] | 163 | parameter.choices = choices |
---|
| 164 | parameter.length = length |
---|
| 165 | parameter.length_control = control |
---|
| 166 | |
---|
| 167 | return parameter |
---|
| 168 | |
---|
[ce896fd] | 169 | |
---|
[4bfd277] | 170 | def expand_pars(partable, pars): |
---|
[a86f6c0] | 171 | # type: (ParameterTable, ParameterSetUser) -> ParameterSet |
---|
[ce896fd] | 172 | """ |
---|
[6d6508e] | 173 | Create demo parameter set from key-value pairs. |
---|
[ce896fd] | 174 | |
---|
[4bfd277] | 175 | *pars* are the key-value pairs to use for the parameters. Any |
---|
| 176 | parameters not specified in *pars* are set from the *partable* defaults. |
---|
[ce896fd] | 177 | |
---|
[4bfd277] | 178 | If *pars* references vector fields, such as thickness[n], then support |
---|
[ce896fd] | 179 | different ways of assigning the demo values, including assigning a |
---|
| 180 | specific value (e.g., thickness3=50.0), assigning a new value to all |
---|
| 181 | (e.g., thickness=50.0) or assigning values using list notation. |
---|
| 182 | """ |
---|
[4bfd277] | 183 | if pars is None: |
---|
[ce896fd] | 184 | result = partable.defaults |
---|
| 185 | else: |
---|
[4bfd277] | 186 | lookup = dict((p.id, p) for p in partable.kernel_parameters) |
---|
[ce896fd] | 187 | result = partable.defaults.copy() |
---|
[9a943d0] | 188 | scalars = dict((name, value) for name, value in pars.items() |
---|
| 189 | if name not in lookup or lookup[name].length == 1) |
---|
[40a87fa] | 190 | vectors = dict((name, value) for name, value in pars.items() |
---|
[4bfd277] | 191 | if name in lookup and lookup[name].length > 1) |
---|
[256dfe1] | 192 | #print("lookup", lookup) |
---|
| 193 | #print("scalars", scalars) |
---|
| 194 | #print("vectors", vectors) |
---|
[ce896fd] | 195 | if vectors: |
---|
| 196 | for name, value in vectors.items(): |
---|
| 197 | if np.isscalar(value): |
---|
| 198 | # support for the form |
---|
[4bfd277] | 199 | # dict(thickness=0, thickness2=50) |
---|
| 200 | for k in range(1, lookup[name].length+1): |
---|
[ce896fd] | 201 | key = name+str(k) |
---|
| 202 | if key not in scalars: |
---|
[256dfe1] | 203 | scalars[key] = value |
---|
[ce896fd] | 204 | else: |
---|
| 205 | # supoprt for the form |
---|
[4bfd277] | 206 | # dict(thickness=[20,10,3]) |
---|
[40a87fa] | 207 | for (k, v) in enumerate(value): |
---|
[256dfe1] | 208 | scalars[name+str(k+1)] = v |
---|
[9a943d0] | 209 | result.update(scalars) |
---|
[256dfe1] | 210 | #print("expanded", result) |
---|
[ce896fd] | 211 | |
---|
[6d6508e] | 212 | return result |
---|
| 213 | |
---|
| 214 | def prefix_parameter(par, prefix): |
---|
[a86f6c0] | 215 | # type: (Parameter, str) -> Parameter |
---|
[6d6508e] | 216 | """ |
---|
| 217 | Return a copy of the parameter with its name prefixed. |
---|
| 218 | """ |
---|
| 219 | new_par = copy(par) |
---|
| 220 | new_par.name = prefix + par.name |
---|
| 221 | new_par.id = prefix + par.id |
---|
| 222 | |
---|
| 223 | def suffix_parameter(par, suffix): |
---|
[a86f6c0] | 224 | # type: (Parameter, str) -> Parameter |
---|
[6d6508e] | 225 | """ |
---|
| 226 | Return a copy of the parameter with its name prefixed. |
---|
| 227 | """ |
---|
| 228 | new_par = copy(par) |
---|
| 229 | # If name has the form x[n], replace with x_suffix[n] |
---|
| 230 | new_par.name = par.id + suffix + par.name[len(par.id):] |
---|
| 231 | new_par.id = par.id + suffix |
---|
[ce896fd] | 232 | |
---|
[69aa451] | 233 | class Parameter(object): |
---|
| 234 | """ |
---|
| 235 | The available kernel parameters are defined as a list, with each parameter |
---|
| 236 | defined as a sublist with the following elements: |
---|
| 237 | |
---|
[f88e248] | 238 | *name* is the name that will be displayed to the user. Names |
---|
[69aa451] | 239 | should be lower case, with words separated by underscore. If |
---|
[f88e248] | 240 | acronyms are used, the whole acronym should be upper case. For vector |
---|
| 241 | parameters, the name will be followed by *[len]* where *len* is an |
---|
| 242 | integer length of the vector, or the name of the parameter which |
---|
| 243 | controls the length. The attribute *id* will be created from name |
---|
| 244 | without the length. |
---|
[69aa451] | 245 | |
---|
| 246 | *units* should be one of *degrees* for angles, *Ang* for lengths, |
---|
| 247 | *1e-6/Ang^2* for SLDs. |
---|
| 248 | |
---|
| 249 | *default value* will be the initial value for the model when it |
---|
| 250 | is selected, or when an initial value is not otherwise specified. |
---|
| 251 | |
---|
| 252 | *limits = [lb, ub]* are the hard limits on the parameter value, used to |
---|
| 253 | limit the polydispersity density function. In the fit, the parameter limits |
---|
| 254 | given to the fit are the limits on the central value of the parameter. |
---|
| 255 | If there is polydispersity, it will evaluate parameter values outside |
---|
| 256 | the fit limits, but not outside the hard limits specified in the model. |
---|
| 257 | If there are no limits, use +/-inf imported from numpy. |
---|
| 258 | |
---|
| 259 | *type* indicates how the parameter will be used. "volume" parameters |
---|
[108e70e] | 260 | will be used in all functions. "orientation" parameters are not passed, |
---|
| 261 | but will be used to convert from *qx*, *qy* to *qa*, *qb*, *qc* in calls to |
---|
| 262 | *Iqxy* and *Imagnetic*. If *type* is the empty string, the parameter will |
---|
[69aa451] | 263 | be used in all of *Iq*, *Iqxy* and *Imagnetic*. "sld" parameters |
---|
| 264 | can automatically be promoted to magnetic parameters, each of which |
---|
| 265 | will have a magnitude and a direction, which may be different from |
---|
[6e7ff6d] | 266 | other sld parameters. The volume parameters are used for calls |
---|
| 267 | to form_volume within the kernel (required for volume normalization) |
---|
| 268 | and for calls to ER and VR for effective radius and volume ratio |
---|
| 269 | respectively. |
---|
[69aa451] | 270 | |
---|
| 271 | *description* is a short description of the parameter. This will |
---|
| 272 | be displayed in the parameter table and used as a tool tip for the |
---|
| 273 | parameter value in the user interface. |
---|
| 274 | |
---|
| 275 | Additional values can be set after the parameter is created: |
---|
| 276 | |
---|
[6e7ff6d] | 277 | * *length* is the length of the field if it is a vector field |
---|
| 278 | |
---|
| 279 | * *length_control* is the parameter which sets the vector length |
---|
| 280 | |
---|
| 281 | * *is_control* is True if the parameter is a control parameter for a vector |
---|
| 282 | |
---|
| 283 | * *polydisperse* is true if the parameter accepts a polydispersity |
---|
| 284 | |
---|
| 285 | * *relative_pd* is true if that polydispersity is a portion of the |
---|
[40a87fa] | 286 | value (so a 10% length dipsersity would use a polydispersity value |
---|
| 287 | of 0.1) rather than absolute dispersisity (such as an angle plus or |
---|
| 288 | minus 15 degrees). |
---|
[69aa451] | 289 | |
---|
[50ec515] | 290 | *choices* is the option names for a drop down list of options, as for |
---|
| 291 | example, might be used to set the value of a shape parameter. |
---|
| 292 | |
---|
[a5b8477] | 293 | These values are set by :func:`make_parameter_table` and |
---|
| 294 | :func:`parse_parameter` therein. |
---|
[69aa451] | 295 | """ |
---|
| 296 | def __init__(self, name, units='', default=None, limits=(-np.inf, np.inf), |
---|
[a86f6c0] | 297 | ptype='', description=''): |
---|
[c1a888b] | 298 | # type: (str, str, float, Limits, str, str) -> None |
---|
[a86f6c0] | 299 | self.id = name.split('[')[0].strip() # type: str |
---|
| 300 | self.name = name # type: str |
---|
| 301 | self.units = units # type: str |
---|
| 302 | self.default = default # type: float |
---|
| 303 | self.limits = limits # type: Limits |
---|
| 304 | self.type = ptype # type: str |
---|
| 305 | self.description = description # type: str |
---|
[69aa451] | 306 | |
---|
[d19962c] | 307 | # Length and length_control will be filled in once the complete |
---|
[69aa451] | 308 | # parameter table is available. |
---|
[a86f6c0] | 309 | self.length = 1 # type: int |
---|
| 310 | self.length_control = None # type: Optional[str] |
---|
| 311 | self.is_control = False # type: bool |
---|
[69aa451] | 312 | |
---|
| 313 | # TODO: need better control over whether a parameter is polydisperse |
---|
[a86f6c0] | 314 | self.polydisperse = False # type: bool |
---|
| 315 | self.relative_pd = False # type: bool |
---|
[69aa451] | 316 | |
---|
[ce896fd] | 317 | # choices are also set externally. |
---|
[a86f6c0] | 318 | self.choices = [] # type: List[str] |
---|
[ce896fd] | 319 | |
---|
[69aa451] | 320 | def as_definition(self): |
---|
[a86f6c0] | 321 | # type: () -> str |
---|
[69aa451] | 322 | """ |
---|
| 323 | Declare space for the variable in a parameter structure. |
---|
| 324 | |
---|
| 325 | For example, the parameter thickness with length 3 will |
---|
| 326 | return "double thickness[3];", with no spaces before and |
---|
| 327 | no new line character afterward. |
---|
| 328 | """ |
---|
| 329 | if self.length == 1: |
---|
| 330 | return "double %s;"%self.id |
---|
| 331 | else: |
---|
| 332 | return "double %s[%d];"%(self.id, self.length) |
---|
| 333 | |
---|
| 334 | def as_function_argument(self): |
---|
[a86f6c0] | 335 | # type: () -> str |
---|
[40a87fa] | 336 | r""" |
---|
[69aa451] | 337 | Declare the variable as a function argument. |
---|
| 338 | |
---|
| 339 | For example, the parameter thickness with length 3 will |
---|
[40a87fa] | 340 | return "double \*thickness", with no spaces before and |
---|
[69aa451] | 341 | no comma afterward. |
---|
| 342 | """ |
---|
| 343 | if self.length == 1: |
---|
| 344 | return "double %s"%self.id |
---|
| 345 | else: |
---|
| 346 | return "double *%s"%self.id |
---|
| 347 | |
---|
| 348 | def as_call_reference(self, prefix=""): |
---|
[c1a888b] | 349 | # type: (str) -> str |
---|
[bb4b509] | 350 | """ |
---|
| 351 | Return *prefix* + parameter name. For struct references, use "v." |
---|
| 352 | as the prefix. |
---|
| 353 | """ |
---|
[69aa451] | 354 | # Note: if the parameter is a struct type, then we will need to use |
---|
| 355 | # &prefix+id. For scalars and vectors we can just use prefix+id. |
---|
| 356 | return prefix + self.id |
---|
| 357 | |
---|
| 358 | def __str__(self): |
---|
[a86f6c0] | 359 | # type: () -> str |
---|
[69aa451] | 360 | return "<%s>"%self.name |
---|
| 361 | |
---|
| 362 | def __repr__(self): |
---|
[a86f6c0] | 363 | # type: () -> str |
---|
[69aa451] | 364 | return "P<%s>"%self.name |
---|
| 365 | |
---|
[d19962c] | 366 | |
---|
[69aa451] | 367 | class ParameterTable(object): |
---|
[d19962c] | 368 | """ |
---|
| 369 | ParameterTable manages the list of available parameters. |
---|
| 370 | |
---|
| 371 | There are a couple of complications which mean that the list of parameters |
---|
| 372 | for the kernel differs from the list of parameters that the user sees. |
---|
| 373 | |
---|
| 374 | (1) Common parameters. Scale and background are implicit to every model, |
---|
| 375 | but are not passed to the kernel. |
---|
| 376 | |
---|
| 377 | (2) Vector parameters. Vector parameters are passed to the kernel as a |
---|
| 378 | pointer to an array, e.g., thick[], but they are seen by the user as n |
---|
| 379 | separate parameters thick1, thick2, ... |
---|
| 380 | |
---|
| 381 | Therefore, the parameter table is organized by how it is expected to be |
---|
| 382 | used. The following information is needed to set up the kernel functions: |
---|
| 383 | |
---|
| 384 | * *kernel_parameters* is the list of parameters in the kernel parameter |
---|
[40a87fa] | 385 | table, with vector parameter p declared as p[]. |
---|
[d19962c] | 386 | |
---|
| 387 | * *iq_parameters* is the list of parameters to the Iq(q, ...) function, |
---|
[40a87fa] | 388 | with vector parameter p sent as p[]. |
---|
[d19962c] | 389 | |
---|
| 390 | * *form_volume_parameters* is the list of parameters to the form_volume(...) |
---|
[40a87fa] | 391 | function, with vector parameter p sent as p[]. |
---|
[d19962c] | 392 | |
---|
| 393 | Problem details, which sets up the polydispersity loops, requires the |
---|
| 394 | following: |
---|
| 395 | |
---|
| 396 | * *theta_offset* is the offset of the theta parameter in the kernel parameter |
---|
[40a87fa] | 397 | table, with vector parameters counted as n individual parameters |
---|
| 398 | p1, p2, ..., or offset is -1 if there is no theta parameter. |
---|
[d19962c] | 399 | |
---|
| 400 | * *max_pd* is the maximum number of polydisperse parameters, with vector |
---|
[40a87fa] | 401 | parameters counted as n individual parameters p1, p2, ... Note that |
---|
| 402 | this number is limited to sasmodels.modelinfo.MAX_PD. |
---|
[d19962c] | 403 | |
---|
| 404 | * *npars* is the total number of parameters to the kernel, with vector |
---|
[40a87fa] | 405 | parameters counted as n individual parameters p1, p2, ... |
---|
[d19962c] | 406 | |
---|
| 407 | * *call_parameters* is the complete list of parameters to the kernel, |
---|
[40a87fa] | 408 | including scale and background, with vector parameters recorded as |
---|
| 409 | individual parameters p1, p2, ... |
---|
[d19962c] | 410 | |
---|
| 411 | * *active_1d* is the set of names that may be polydisperse for 1d data |
---|
| 412 | |
---|
| 413 | * *active_2d* is the set of names that may be polydisperse for 2d data |
---|
| 414 | |
---|
| 415 | User parameters are the set of parameters visible to the user, including |
---|
| 416 | the scale and background parameters that the kernel does not see. User |
---|
| 417 | parameters don't use vector notation, and instead use p1, p2, ... |
---|
| 418 | """ |
---|
[69aa451] | 419 | # scale and background are implicit parameters |
---|
| 420 | COMMON = [Parameter(*p) for p in COMMON_PARAMETERS] |
---|
| 421 | |
---|
| 422 | def __init__(self, parameters): |
---|
[a86f6c0] | 423 | # type: (List[Parameter]) -> None |
---|
[d19962c] | 424 | self.kernel_parameters = parameters |
---|
[60eab2a] | 425 | self._set_vector_lengths() |
---|
[32e3c9b] | 426 | |
---|
| 427 | self.npars = sum(p.length for p in self.kernel_parameters) |
---|
[9eb3632] | 428 | self.nmagnetic = sum(p.length for p in self.kernel_parameters |
---|
[bb4b509] | 429 | if p.type == 'sld') |
---|
[9eb3632] | 430 | self.nvalues = 2 + self.npars |
---|
| 431 | if self.nmagnetic: |
---|
| 432 | self.nvalues += 3 + 3*self.nmagnetic |
---|
[32e3c9b] | 433 | |
---|
[a86f6c0] | 434 | self.call_parameters = self._get_call_parameters() |
---|
| 435 | self.defaults = self._get_defaults() |
---|
[d19962c] | 436 | #self._name_table= dict((p.id, p) for p in parameters) |
---|
[60eab2a] | 437 | |
---|
[d19962c] | 438 | # Set the kernel parameters. Assumes background and scale are the |
---|
| 439 | # first two parameters in the parameter list, but these are not sent |
---|
| 440 | # to the underlying kernel functions. |
---|
| 441 | self.iq_parameters = [p for p in self.kernel_parameters |
---|
| 442 | if p.type not in ('orientation', 'magnetic')] |
---|
[108e70e] | 443 | self.orientation_parameters = [p for p in self.kernel_parameters |
---|
| 444 | if p.type == 'orientation'] |
---|
[d19962c] | 445 | self.form_volume_parameters = [p for p in self.kernel_parameters |
---|
| 446 | if p.type == 'volume'] |
---|
| 447 | |
---|
| 448 | # Theta offset |
---|
| 449 | offset = 0 |
---|
| 450 | for p in self.kernel_parameters: |
---|
| 451 | if p.name == 'theta': |
---|
| 452 | self.theta_offset = offset |
---|
| 453 | break |
---|
| 454 | offset += p.length |
---|
| 455 | else: |
---|
| 456 | self.theta_offset = -1 |
---|
[69aa451] | 457 | |
---|
[d19962c] | 458 | # number of polydisperse parameters |
---|
| 459 | num_pd = sum(p.length for p in self.kernel_parameters if p.polydisperse) |
---|
| 460 | # Don't use more polydisperse parameters than are available in the model |
---|
| 461 | self.max_pd = min(num_pd, MAX_PD) |
---|
[69aa451] | 462 | |
---|
[d19962c] | 463 | # true if has 2D parameters |
---|
| 464 | self.has_2d = any(p.type in ('orientation', 'magnetic') |
---|
| 465 | for p in self.kernel_parameters) |
---|
[8698a0d] | 466 | self.is_asymmetric = any(p.name == 'psi' for p in self.kernel_parameters) |
---|
[bb4b509] | 467 | self.magnetism_index = [k for k, p in enumerate(self.call_parameters) |
---|
[610ef23] | 468 | if p.id.endswith('_M0')] |
---|
[69aa451] | 469 | |
---|
[d19962c] | 470 | self.pd_1d = set(p.name for p in self.call_parameters |
---|
[a86f6c0] | 471 | if p.polydisperse and p.type not in ('orientation', 'magnetic')) |
---|
[32e3c9b] | 472 | self.pd_2d = set(p.name for p in self.call_parameters if p.polydisperse) |
---|
[69aa451] | 473 | |
---|
[95498a3] | 474 | def check_angles(self): |
---|
| 475 | """ |
---|
| 476 | Check that orientation angles are theta, phi and possibly psi. |
---|
| 477 | """ |
---|
[8698a0d] | 478 | theta = phi = psi = -1 |
---|
| 479 | for k, p in enumerate(self.kernel_parameters): |
---|
| 480 | if p.name == 'theta': |
---|
| 481 | theta = k |
---|
| 482 | if p.type != 'orientation': |
---|
| 483 | raise TypeError("theta must be an orientation parameter") |
---|
| 484 | elif p.name == 'phi': |
---|
| 485 | phi = k |
---|
| 486 | if p.type != 'orientation': |
---|
| 487 | raise TypeError("phi must be an orientation parameter") |
---|
| 488 | elif p.name == 'psi': |
---|
| 489 | psi = k |
---|
| 490 | if p.type != 'orientation': |
---|
| 491 | raise TypeError("psi must be an orientation parameter") |
---|
[108e70e] | 492 | elif p.type == 'orientation': |
---|
| 493 | raise TypeError("only theta, phi and psi can be orientation parameters") |
---|
[8698a0d] | 494 | if theta >= 0 and phi >= 0: |
---|
[108e70e] | 495 | last_par = len(self.kernel_parameters) - 1 |
---|
[8698a0d] | 496 | if phi != theta+1: |
---|
| 497 | raise TypeError("phi must follow theta") |
---|
| 498 | if psi >= 0 and psi != phi+1: |
---|
| 499 | raise TypeError("psi must follow phi") |
---|
[95498a3] | 500 | if (psi >= 0 and psi != last_par) or (psi < 0 and phi != last_par): |
---|
| 501 | raise TypeError("orientation parameters must appear at the " |
---|
| 502 | "end of the parameter table") |
---|
[8698a0d] | 503 | elif theta >= 0 or phi >= 0 or psi >= 0: |
---|
| 504 | raise TypeError("oriented shapes must have both theta and phi and maybe psi") |
---|
| 505 | |
---|
[0bdddc2] | 506 | def __getitem__(self, key): |
---|
| 507 | # Find the parameter definition |
---|
| 508 | for par in self.call_parameters: |
---|
| 509 | if par.name == key: |
---|
[e65c3ba] | 510 | return par |
---|
| 511 | raise KeyError("unknown parameter %r"%key) |
---|
[0bdddc2] | 512 | |
---|
[e3571cb] | 513 | def __contains__(self, key): |
---|
| 514 | for par in self.call_parameters: |
---|
| 515 | if par.name == key: |
---|
| 516 | return True |
---|
[e65c3ba] | 517 | return False |
---|
[e3571cb] | 518 | |
---|
[a86f6c0] | 519 | def _set_vector_lengths(self): |
---|
[256dfe1] | 520 | # type: () -> List[str] |
---|
[a86f6c0] | 521 | """ |
---|
| 522 | Walk the list of kernel parameters, setting the length field of the |
---|
| 523 | vector parameters from the upper limit of the reference parameter. |
---|
| 524 | |
---|
| 525 | This needs to be done once the entire parameter table is available |
---|
| 526 | since the reference may still be undefined when the parameter is |
---|
| 527 | initially created. |
---|
| 528 | |
---|
[256dfe1] | 529 | Returns the list of control parameter names. |
---|
| 530 | |
---|
[a86f6c0] | 531 | Note: This modifies the underlying parameter object. |
---|
| 532 | """ |
---|
| 533 | # Sort out the length of the vector parameters such as thickness[n] |
---|
| 534 | for p in self.kernel_parameters: |
---|
| 535 | if p.length_control: |
---|
[e65c3ba] | 536 | ref = self._get_ref(p) |
---|
[a86f6c0] | 537 | ref.is_control = True |
---|
[256dfe1] | 538 | ref.polydisperse = False |
---|
[a86f6c0] | 539 | low, high = ref.limits |
---|
| 540 | if int(low) != low or int(high) != high or low < 0 or high > 20: |
---|
| 541 | raise ValueError("expected limits on %s to be within [0, 20]" |
---|
| 542 | % ref.name) |
---|
[04045f4] | 543 | p.length = int(high) |
---|
[a86f6c0] | 544 | |
---|
[e65c3ba] | 545 | def _get_ref(self, p): |
---|
| 546 | # type: (Parameter) -> Parameter |
---|
| 547 | for ref in self.kernel_parameters: |
---|
| 548 | if ref.id == p.length_control: |
---|
| 549 | return ref |
---|
| 550 | raise ValueError("no reference variable %r for %s" |
---|
| 551 | % (p.length_control, p.name)) |
---|
| 552 | |
---|
[a86f6c0] | 553 | def _get_defaults(self): |
---|
| 554 | # type: () -> ParameterSet |
---|
| 555 | """ |
---|
| 556 | Get a list of parameter defaults from the parameters. |
---|
| 557 | |
---|
| 558 | Expands vector parameters into parameter id+number. |
---|
| 559 | """ |
---|
| 560 | # Construct default values, including vector defaults |
---|
| 561 | defaults = {} |
---|
| 562 | for p in self.call_parameters: |
---|
| 563 | if p.length == 1: |
---|
| 564 | defaults[p.id] = p.default |
---|
| 565 | else: |
---|
| 566 | for k in range(1, p.length+1): |
---|
| 567 | defaults["%s%d"%(p.id, k)] = p.default |
---|
| 568 | return defaults |
---|
| 569 | |
---|
| 570 | def _get_call_parameters(self): |
---|
| 571 | # type: () -> List[Parameter] |
---|
| 572 | full_list = self.COMMON[:] |
---|
| 573 | for p in self.kernel_parameters: |
---|
| 574 | if p.length == 1: |
---|
| 575 | full_list.append(p) |
---|
| 576 | else: |
---|
| 577 | for k in range(1, p.length+1): |
---|
| 578 | pk = Parameter(p.id+str(k), p.units, p.default, |
---|
| 579 | p.limits, p.type, p.description) |
---|
| 580 | pk.polydisperse = p.polydisperse |
---|
| 581 | pk.relative_pd = p.relative_pd |
---|
[50ec515] | 582 | pk.choices = p.choices |
---|
[a86f6c0] | 583 | full_list.append(pk) |
---|
[32e3c9b] | 584 | |
---|
| 585 | # Add the magnetic parameters to the end of the call parameter list. |
---|
[9eb3632] | 586 | if self.nmagnetic > 0: |
---|
[32e3c9b] | 587 | full_list.extend([ |
---|
[610ef23] | 588 | Parameter('up_frac_i', '', 0., [0., 1.], |
---|
[32e3c9b] | 589 | 'magnetic', 'fraction of spin up incident'), |
---|
[610ef23] | 590 | Parameter('up_frac_f', '', 0., [0., 1.], |
---|
[32e3c9b] | 591 | 'magnetic', 'fraction of spin up final'), |
---|
[610ef23] | 592 | Parameter('up_angle', 'degrees', 0., [0., 360.], |
---|
[32e3c9b] | 593 | 'magnetic', 'spin up angle'), |
---|
| 594 | ]) |
---|
| 595 | slds = [p for p in full_list if p.type == 'sld'] |
---|
| 596 | for p in slds: |
---|
| 597 | full_list.extend([ |
---|
[610ef23] | 598 | Parameter(p.id+'_M0', '1e-6/Ang^2', 0., [-np.inf, np.inf], |
---|
[32e3c9b] | 599 | 'magnetic', 'magnetic amplitude for '+p.description), |
---|
[610ef23] | 600 | Parameter(p.id+'_mtheta', 'degrees', 0., [-90., 90.], |
---|
[bb4b509] | 601 | 'magnetic', 'magnetic latitude for '+p.description), |
---|
[610ef23] | 602 | Parameter(p.id+'_mphi', 'degrees', 0., [-180., 180.], |
---|
[bb4b509] | 603 | 'magnetic', 'magnetic longitude for '+p.description), |
---|
[32e3c9b] | 604 | ]) |
---|
| 605 | #print("call parameters", full_list) |
---|
[a86f6c0] | 606 | return full_list |
---|
| 607 | |
---|
[85fe7f8] | 608 | def user_parameters(self, pars, is2d=True): |
---|
[0d99a6a] | 609 | # type: (Dict[str, float], bool) -> List[Parameter] |
---|
[69aa451] | 610 | """ |
---|
[d19962c] | 611 | Return the list of parameters for the given data type. |
---|
| 612 | |
---|
[c5ac2b2] | 613 | Vector parameters are expanded in place. If multiple parameters |
---|
[d19962c] | 614 | share the same vector length, then the parameters will be interleaved |
---|
| 615 | in the result. The control parameters come first. For example, |
---|
| 616 | if the parameter table is ordered as:: |
---|
| 617 | |
---|
| 618 | sld_core |
---|
| 619 | sld_shell[num_shells] |
---|
| 620 | sld_solvent |
---|
| 621 | thickness[num_shells] |
---|
| 622 | num_shells |
---|
| 623 | |
---|
| 624 | and *pars[num_shells]=2* then the returned list will be:: |
---|
| 625 | |
---|
| 626 | num_shells |
---|
| 627 | scale |
---|
| 628 | background |
---|
| 629 | sld_core |
---|
| 630 | sld_shell1 |
---|
| 631 | thickness1 |
---|
| 632 | sld_shell2 |
---|
| 633 | thickness2 |
---|
| 634 | sld_solvent |
---|
| 635 | |
---|
| 636 | Note that shell/thickness pairs are grouped together in the result |
---|
| 637 | even though they were not grouped in the incoming table. The control |
---|
| 638 | parameter is always returned first since the GUI will want to set it |
---|
| 639 | early, and rerender the table when it is changed. |
---|
[32e3c9b] | 640 | |
---|
| 641 | Parameters marked as sld will automatically have a set of associated |
---|
[610ef23] | 642 | magnetic parameters (p_M0, p_mtheta, p_mphi), as well as polarization |
---|
| 643 | information (up_theta, up_frac_i, up_frac_f). |
---|
[69aa451] | 644 | """ |
---|
[04045f4] | 645 | # control parameters go first |
---|
[d19962c] | 646 | control = [p for p in self.kernel_parameters if p.is_control] |
---|
| 647 | |
---|
| 648 | # Gather entries such as name[n] into groups of the same n |
---|
[04045f4] | 649 | dependent = {} # type: Dict[str, List[Parameter]] |
---|
| 650 | dependent.update((p.id, []) for p in control) |
---|
[d19962c] | 651 | for p in self.kernel_parameters: |
---|
| 652 | if p.length_control is not None: |
---|
| 653 | dependent[p.length_control].append(p) |
---|
| 654 | |
---|
| 655 | # Gather entries such as name[4] into groups of the same length |
---|
[32e3c9b] | 656 | fixed_length = {} # type: Dict[int, List[Parameter]] |
---|
[d19962c] | 657 | for p in self.kernel_parameters: |
---|
| 658 | if p.length > 1 and p.length_control is None: |
---|
[32e3c9b] | 659 | fixed_length.setdefault(p.length, []).append(p) |
---|
[d19962c] | 660 | |
---|
| 661 | # Using the call_parameters table, we already have expanded forms |
---|
| 662 | # for each of the vector parameters; put them in a lookup table |
---|
[f88e248] | 663 | # Note: p.id and p.name are currently identical for the call parameters |
---|
| 664 | expanded_pars = dict((p.id, p) for p in self.call_parameters) |
---|
[d19962c] | 665 | |
---|
[32e3c9b] | 666 | def append_group(name): |
---|
| 667 | """add the named parameter, and related magnetic parameters if any""" |
---|
| 668 | result.append(expanded_pars[name]) |
---|
| 669 | if is2d: |
---|
[610ef23] | 670 | for tag in '_M0', '_mtheta', '_mphi': |
---|
| 671 | if name+tag in expanded_pars: |
---|
| 672 | result.append(expanded_pars[name+tag]) |
---|
[32e3c9b] | 673 | |
---|
[d19962c] | 674 | # Gather the user parameters in order |
---|
| 675 | result = control + self.COMMON |
---|
| 676 | for p in self.kernel_parameters: |
---|
| 677 | if not is2d and p.type in ('orientation', 'magnetic'): |
---|
| 678 | pass |
---|
| 679 | elif p.is_control: |
---|
| 680 | pass # already added |
---|
| 681 | elif p.length_control is not None: |
---|
| 682 | table = dependent.get(p.length_control, []) |
---|
| 683 | if table: |
---|
| 684 | # look up length from incoming parameters |
---|
[fb5914f] | 685 | table_length = int(pars.get(p.length_control, p.length)) |
---|
[d19962c] | 686 | del dependent[p.length_control] # first entry seen |
---|
| 687 | for k in range(1, table_length+1): |
---|
| 688 | for entry in table: |
---|
[32e3c9b] | 689 | append_group(entry.id+str(k)) |
---|
[d19962c] | 690 | else: |
---|
| 691 | pass # already processed all entries |
---|
| 692 | elif p.length > 1: |
---|
[32e3c9b] | 693 | table = fixed_length.get(p.length, []) |
---|
[d19962c] | 694 | if table: |
---|
| 695 | table_length = p.length |
---|
[32e3c9b] | 696 | del fixed_length[p.length] |
---|
[d19962c] | 697 | for k in range(1, table_length+1): |
---|
| 698 | for entry in table: |
---|
[32e3c9b] | 699 | append_group(entry.id+str(k)) |
---|
[d19962c] | 700 | else: |
---|
| 701 | pass # already processed all entries |
---|
| 702 | else: |
---|
[32e3c9b] | 703 | append_group(p.id) |
---|
| 704 | |
---|
[610ef23] | 705 | if is2d and 'up_angle' in expanded_pars: |
---|
[32e3c9b] | 706 | result.extend([ |
---|
[610ef23] | 707 | expanded_pars['up_frac_i'], |
---|
| 708 | expanded_pars['up_frac_f'], |
---|
| 709 | expanded_pars['up_angle'], |
---|
[32e3c9b] | 710 | ]) |
---|
[d19962c] | 711 | |
---|
| 712 | return result |
---|
[69aa451] | 713 | |
---|
| 714 | def isstr(x): |
---|
[a86f6c0] | 715 | # type: (Any) -> bool |
---|
[7edce22] | 716 | """ |
---|
| 717 | Return True if the object is a string. |
---|
| 718 | """ |
---|
[69aa451] | 719 | # TODO: 2-3 compatible tests for str, including unicode strings |
---|
| 720 | return isinstance(x, str) |
---|
| 721 | |
---|
[da63656] | 722 | |
---|
[108e70e] | 723 | #: Set of variables defined in the model that might contain C code |
---|
| 724 | C_SYMBOLS = ['Imagnetic', 'Iq', 'Iqxy', 'Iqac', 'Iqabc', 'form_volume', 'c_code'] |
---|
| 725 | |
---|
[da63656] | 726 | def _find_source_lines(model_info, kernel_module): |
---|
[e65c3ba] | 727 | # type: (ModelInfo, ModuleType) -> None |
---|
[da63656] | 728 | """ |
---|
| 729 | Identify the location of the C source inside the model definition file. |
---|
| 730 | |
---|
[108e70e] | 731 | This code runs through the source of the kernel module looking for lines |
---|
| 732 | that contain C code (because it is a c function definition). Clearly |
---|
| 733 | there are all sorts of reasons why this might not work (e.g., code |
---|
| 734 | commented out in a triple-quoted line block, code built using string |
---|
| 735 | concatenation, code defined in the branch of an 'if' block, code imported |
---|
| 736 | from another file), but it should work properly in the 95% case, and for |
---|
| 737 | the remainder, getting the incorrect line number will merely be |
---|
| 738 | inconvenient. |
---|
[da63656] | 739 | """ |
---|
[108e70e] | 740 | # Only need line numbers if we are creating a C module and the C symbols |
---|
| 741 | # are defined. |
---|
| 742 | if (callable(model_info.Iq) |
---|
| 743 | or not any(hasattr(model_info, s) for s in C_SYMBOLS)): |
---|
[da63656] | 744 | return |
---|
| 745 | |
---|
[108e70e] | 746 | # load the module source if we can |
---|
[98ba1fc] | 747 | try: |
---|
| 748 | source = inspect.getsource(kernel_module) |
---|
| 749 | except IOError: |
---|
| 750 | return |
---|
[da63656] | 751 | |
---|
[108e70e] | 752 | # look for symbol at the start of the line |
---|
| 753 | for lineno, line in enumerate(source.split('\n')): |
---|
| 754 | for name in C_SYMBOLS: |
---|
| 755 | if line.startswith(name): |
---|
| 756 | # Add 1 since some compilers complain about "#line 0" |
---|
| 757 | model_info.lineno[name] = lineno + 1 |
---|
| 758 | break |
---|
[da63656] | 759 | |
---|
[6d6508e] | 760 | def make_model_info(kernel_module): |
---|
[7edce22] | 761 | # type: (module) -> ModelInfo |
---|
| 762 | """ |
---|
| 763 | Extract the model definition from the loaded kernel module. |
---|
| 764 | |
---|
| 765 | Fill in default values for parts of the module that are not provided. |
---|
| 766 | |
---|
[108e70e] | 767 | Note: vectorized Iq and Iqac/Iqabc functions will be created for python |
---|
[7edce22] | 768 | models when the model is first called, not when the model is loaded. |
---|
| 769 | """ |
---|
[65314f7] | 770 | if hasattr(kernel_module, "model_info"): |
---|
| 771 | # Custom sum/multi models |
---|
| 772 | return kernel_module.model_info |
---|
[6d6508e] | 773 | info = ModelInfo() |
---|
| 774 | #print("make parameter table", kernel_module.parameters) |
---|
[c1a888b] | 775 | parameters = make_parameter_table(getattr(kernel_module, 'parameters', [])) |
---|
[4bfd277] | 776 | demo = expand_pars(parameters, getattr(kernel_module, 'demo', None)) |
---|
[724257c] | 777 | filename = abspath(kernel_module.__file__).replace('.pyc', '.py') |
---|
[6d6508e] | 778 | kernel_id = splitext(basename(filename))[0] |
---|
| 779 | name = getattr(kernel_module, 'name', None) |
---|
| 780 | if name is None: |
---|
| 781 | name = " ".join(w.capitalize() for w in kernel_id.split('_')) |
---|
| 782 | |
---|
| 783 | info.id = kernel_id # string used to load the kernel |
---|
[724257c] | 784 | info.filename = filename |
---|
[6d6508e] | 785 | info.name = name |
---|
| 786 | info.title = getattr(kernel_module, 'title', name+" model") |
---|
| 787 | info.description = getattr(kernel_module, 'description', 'no description') |
---|
| 788 | info.parameters = parameters |
---|
| 789 | info.demo = demo |
---|
| 790 | info.composition = None |
---|
| 791 | info.docs = kernel_module.__doc__ |
---|
| 792 | info.category = getattr(kernel_module, 'category', None) |
---|
| 793 | info.structure_factor = getattr(kernel_module, 'structure_factor', False) |
---|
[04045f4] | 794 | info.profile_axes = getattr(kernel_module, 'profile_axes', ['x', 'y']) |
---|
[d321747] | 795 | # Note: custom.load_custom_kernel_module assumes the C sources are defined |
---|
| 796 | # by this attribute. |
---|
[6d6508e] | 797 | info.source = getattr(kernel_module, 'source', []) |
---|
[108e70e] | 798 | info.c_code = getattr(kernel_module, 'c_code', None) |
---|
[e62a134] | 799 | # TODO: check the structure of the tests |
---|
[6d6508e] | 800 | info.tests = getattr(kernel_module, 'tests', []) |
---|
[9a943d0] | 801 | info.ER = getattr(kernel_module, 'ER', None) # type: ignore |
---|
| 802 | info.VR = getattr(kernel_module, 'VR', None) # type: ignore |
---|
| 803 | info.form_volume = getattr(kernel_module, 'form_volume', None) # type: ignore |
---|
| 804 | info.Iq = getattr(kernel_module, 'Iq', None) # type: ignore |
---|
| 805 | info.Iqxy = getattr(kernel_module, 'Iqxy', None) # type: ignore |
---|
[108e70e] | 806 | info.Iqac = getattr(kernel_module, 'Iqac', None) # type: ignore |
---|
| 807 | info.Iqabc = getattr(kernel_module, 'Iqabc', None) # type: ignore |
---|
[32e3c9b] | 808 | info.Imagnetic = getattr(kernel_module, 'Imagnetic', None) # type: ignore |
---|
[9a943d0] | 809 | info.profile = getattr(kernel_module, 'profile', None) # type: ignore |
---|
| 810 | info.sesans = getattr(kernel_module, 'sesans', None) # type: ignore |
---|
[5124c969] | 811 | # Default single and opencl to True for C models. Python models have callable Iq. |
---|
| 812 | info.opencl = getattr(kernel_module, 'opencl', not callable(info.Iq)) |
---|
| 813 | info.single = getattr(kernel_module, 'single', not callable(info.Iq)) |
---|
[0bdddc2] | 814 | info.random = getattr(kernel_module, 'random', None) |
---|
[256dfe1] | 815 | |
---|
| 816 | # multiplicity info |
---|
| 817 | control_pars = [p.id for p in parameters.kernel_parameters if p.is_control] |
---|
| 818 | default_control = control_pars[0] if control_pars else None |
---|
| 819 | info.control = getattr(kernel_module, 'control', default_control) |
---|
[04045f4] | 820 | info.hidden = getattr(kernel_module, 'hidden', None) # type: ignore |
---|
[6d6508e] | 821 | |
---|
[108e70e] | 822 | if callable(info.Iq) and parameters.has_2d: |
---|
| 823 | raise ValueError("oriented python models not supported") |
---|
| 824 | |
---|
| 825 | info.lineno = {} |
---|
[da63656] | 826 | _find_source_lines(info, kernel_module) |
---|
| 827 | |
---|
[6d6508e] | 828 | return info |
---|
| 829 | |
---|
| 830 | class ModelInfo(object): |
---|
| 831 | """ |
---|
| 832 | Interpret the model definition file, categorizing the parameters. |
---|
| 833 | |
---|
| 834 | The module can be loaded with a normal python import statement if you |
---|
| 835 | know which module you need, or with __import__('sasmodels.model.'+name) |
---|
| 836 | if the name is in a string. |
---|
| 837 | |
---|
[7edce22] | 838 | The structure should be mostly static, other than the delayed definition |
---|
[108e70e] | 839 | of *Iq*, *Iqac* and *Iqabc* if they need to be defined. |
---|
[6d6508e] | 840 | """ |
---|
[a5b8477] | 841 | #: Full path to the file defining the kernel, if any. |
---|
[340428e] | 842 | filename = None # type: Optional[str] |
---|
[a5b8477] | 843 | #: Id of the kernel used to load it from the filesystem. |
---|
[a86f6c0] | 844 | id = None # type: str |
---|
[a5b8477] | 845 | #: Display name of the model, which defaults to the model id but with |
---|
| 846 | #: capitalization of the parts so for example core_shell defaults to |
---|
| 847 | #: "Core Shell". |
---|
[a86f6c0] | 848 | name = None # type: str |
---|
[a5b8477] | 849 | #: Short description of the model. |
---|
[a86f6c0] | 850 | title = None # type: str |
---|
[a5b8477] | 851 | #: Long description of the model. |
---|
[a86f6c0] | 852 | description = None # type: str |
---|
[a5b8477] | 853 | #: Model parameter table. Parameters are defined using a list of parameter |
---|
| 854 | #: definitions, each of which is contains parameter name, units, |
---|
| 855 | #: default value, limits, type and description. See :class:`Parameter` |
---|
| 856 | #: for details on the individual parameters. The parameters are gathered |
---|
| 857 | #: into a :class:`ParameterTable`, which provides various views into the |
---|
| 858 | #: parameter list. |
---|
[a86f6c0] | 859 | parameters = None # type: ParameterTable |
---|
[a5b8477] | 860 | #: Demo parameters as a *parameter:value* map used as the default values |
---|
| 861 | #: for :mod:`compare`. Any parameters not set in *demo* will use the |
---|
| 862 | #: defaults from the parameter table. That means no polydispersity, and |
---|
| 863 | #: in the case of multiplicity models, a minimal model with no interesting |
---|
| 864 | #: scattering. |
---|
[a86f6c0] | 865 | demo = None # type: Dict[str, float] |
---|
[a5b8477] | 866 | #: Composition is None if this is an independent model, or it is a |
---|
| 867 | #: tuple with comoposition type ('product' or 'misture') and a list of |
---|
| 868 | #: :class:`ModelInfo` blocks for the composed objects. This allows us |
---|
| 869 | #: to rebuild a complete mixture or product model from the info block. |
---|
| 870 | #: *composition* is not given in the model definition file, but instead |
---|
| 871 | #: arises when the model is constructed using names such as |
---|
| 872 | #: *sphere*hardsphere* or *cylinder+sphere*. |
---|
[a86f6c0] | 873 | composition = None # type: Optional[Tuple[str, List[ModelInfo]]] |
---|
[a5b8477] | 874 | #: Name of the control parameter for a variant model such as :ref:`rpa`. |
---|
| 875 | #: The *control* parameter should appear in the parameter table, with |
---|
| 876 | #: limits defined as *[CASES]*, for case names such as |
---|
| 877 | #: *CASES = ["diblock copolymer", "triblock copolymer", ...]*. |
---|
| 878 | #: This should give *limits=[[case1, case2, ...]]*, but the |
---|
| 879 | #: model loader translates this to *limits=[0, len(CASES)-1]*, and adds |
---|
| 880 | #: *choices=CASES* to the :class:`Parameter` definition. Note that |
---|
| 881 | #: models can use a list of cases as a parameter without it being a |
---|
| 882 | #: control parameter. Either way, the parameter is sent to the model |
---|
| 883 | #: evaluator as *float(choice_num)*, where choices are numbered from 0. |
---|
| 884 | #: See also :attr:`hidden`. |
---|
[04045f4] | 885 | control = None # type: str |
---|
[a5b8477] | 886 | #: Different variants require different parameters. In order to show |
---|
| 887 | #: just the parameters needed for the variant selected by :attr:`control`, |
---|
| 888 | #: you should provide a function *hidden(control) -> set(['a', 'b', ...])* |
---|
| 889 | #: indicating which parameters need to be hidden. For multiplicity |
---|
| 890 | #: models, you need to use the complete name of the parameter, including |
---|
| 891 | #: its number. So for example, if variant "a" uses only *sld1* and *sld2*, |
---|
| 892 | #: then *sld3*, *sld4* and *sld5* of multiplicity parameter *sld[5]* |
---|
| 893 | #: should be in the hidden set. |
---|
| 894 | hidden = None # type: Optional[Callable[[int], Set[str]]] |
---|
| 895 | #: Doc string from the top of the model file. This should be formatted |
---|
| 896 | #: using ReStructuredText format, with latex markup in ".. math" |
---|
| 897 | #: environments, or in dollar signs. This will be automatically |
---|
| 898 | #: extracted to a .rst file by :func:`generate.make_docs`, then |
---|
| 899 | #: converted to HTML or PDF by Sphinx. |
---|
[a86f6c0] | 900 | docs = None # type: str |
---|
[a5b8477] | 901 | #: Location of the model description in the documentation. This takes the |
---|
| 902 | #: form of "section" or "section:subsection". So for example, |
---|
| 903 | #: :ref:`porod` uses *category="shape-independent"* so it is in the |
---|
[40a87fa] | 904 | #: :ref:`shape-independent` section whereas |
---|
| 905 | #: :ref:`capped-cylinder` uses: *category="shape:cylinder"*, which puts |
---|
[a5b8477] | 906 | #: it in the :ref:`shape-cylinder` section. |
---|
[a86f6c0] | 907 | category = None # type: Optional[str] |
---|
[a5b8477] | 908 | #: True if the model can be computed accurately with single precision. |
---|
[40a87fa] | 909 | #: This is True by default, but models such as :ref:`bcc-paracrystal` set |
---|
[a5b8477] | 910 | #: it to False because they require double precision calculations. |
---|
[a86f6c0] | 911 | single = None # type: bool |
---|
[bb4b509] | 912 | #: True if the model can be run as an opencl model. If for some reason |
---|
| 913 | #: the model cannot be run in opencl (e.g., because the model passes |
---|
| 914 | #: functions by reference), then set this to false. |
---|
| 915 | opencl = None # type: bool |
---|
[a5b8477] | 916 | #: True if the model is a structure factor used to model the interaction |
---|
| 917 | #: between form factor models. This will default to False if it is not |
---|
| 918 | #: provided in the file. |
---|
[a86f6c0] | 919 | structure_factor = None # type: bool |
---|
[a5b8477] | 920 | #: List of C source files used to define the model. The source files |
---|
[108e70e] | 921 | #: should define the *Iq* function, and possibly *Iqac* or *Iqabc* if the |
---|
| 922 | #: model defines orientation parameters. Files containing the most basic |
---|
| 923 | #: functions must appear first in the list, followed by the files that |
---|
| 924 | #: use those functions. Form factors are indicated by providing |
---|
| 925 | #: an :attr:`ER` function. |
---|
[a86f6c0] | 926 | source = None # type: List[str] |
---|
[a5b8477] | 927 | #: The set of tests that must pass. The format of the tests is described |
---|
| 928 | #: in :mod:`model_test`. |
---|
[a86f6c0] | 929 | tests = None # type: List[TestCondition] |
---|
[a5b8477] | 930 | #: Returns the effective radius of the model given its volume parameters. |
---|
| 931 | #: The presence of *ER* indicates that the model is a form factor model |
---|
| 932 | #: that may be used together with a structure factor to form an implicit |
---|
| 933 | #: multiplication model. |
---|
| 934 | #: |
---|
| 935 | #: The parameters to the *ER* function must be marked with type *volume*. |
---|
| 936 | #: in the parameter table. They will appear in the same order as they |
---|
| 937 | #: do in the table. The values passed to *ER* will be vectors, with one |
---|
| 938 | #: value for each polydispersity condition. For example, if the model |
---|
| 939 | #: is polydisperse over both length and radius, then both length and |
---|
| 940 | #: radius will have the same number of values in the vector, with one |
---|
| 941 | #: value for each *length X radius*. If only *radius* is polydisperse, |
---|
| 942 | #: then the value for *length* will be repeated once for each value of |
---|
| 943 | #: *radius*. The *ER* function should return one effective radius for |
---|
| 944 | #: each parameter set. Multiplicity parameters will be received as |
---|
| 945 | #: arrays, with one row per polydispersity condition. |
---|
[c1a888b] | 946 | ER = None # type: Optional[Callable[[np.ndarray], np.ndarray]] |
---|
[a5b8477] | 947 | #: Returns the occupied volume and the total volume for each parameter set. |
---|
| 948 | #: See :attr:`ER` for details on the parameters. |
---|
[c1a888b] | 949 | VR = None # type: Optional[Callable[[np.ndarray], Tuple[np.ndarray, np.ndarray]]] |
---|
[108e70e] | 950 | #: Arbitrary C code containing supporting functions, etc., to be inserted |
---|
| 951 | #: after everything in source. This can include Iq and Iqxy functions with |
---|
| 952 | #: the full function signature, including all parameters. |
---|
| 953 | c_code = None |
---|
[a5b8477] | 954 | #: Returns the form volume for python-based models. Form volume is needed |
---|
| 955 | #: for volume normalization in the polydispersity integral. If no |
---|
| 956 | #: parameters are *volume* parameters, then form volume is not needed. |
---|
| 957 | #: For C-based models, (with :attr:`sources` defined, or with :attr:`Iq` |
---|
| 958 | #: defined using a string containing C code), form_volume must also be |
---|
| 959 | #: C code, either defined as a string, or in the sources. |
---|
[f619de7] | 960 | form_volume = None # type: Union[None, str, Callable[[np.ndarray], float]] |
---|
[a5b8477] | 961 | #: Returns *I(q, a, b, ...)* for parameters *a*, *b*, etc. defined |
---|
| 962 | #: by the parameter table. *Iq* can be defined as a python function, or |
---|
| 963 | #: as a C function. If it is defined in C, then set *Iq* to the body of |
---|
| 964 | #: the C function, including the return statement. This function takes |
---|
| 965 | #: values for *q* and each of the parameters as separate *double* values |
---|
| 966 | #: (which may be converted to float or long double by sasmodels). All |
---|
| 967 | #: source code files listed in :attr:`sources` will be loaded before the |
---|
| 968 | #: *Iq* function is defined. If *Iq* is not present, then sources should |
---|
| 969 | #: define *static double Iq(double q, double a, double b, ...)* which |
---|
| 970 | #: will return *I(q, a, b, ...)*. Multiplicity parameters are sent as |
---|
| 971 | #: pointers to doubles. Constants in floating point expressions should |
---|
| 972 | #: include the decimal point. See :mod:`generate` for more details. |
---|
[f619de7] | 973 | Iq = None # type: Union[None, str, Callable[[np.ndarray], np.ndarray]] |
---|
[108e70e] | 974 | #: Returns *I(qab, qc, a, b, ...)*. The interface follows :attr:`Iq`. |
---|
| 975 | Iqac = None # type: Union[None, str, Callable[[np.ndarray], np.ndarray]] |
---|
| 976 | #: Returns *I(qa, qb, qc, a, b, ...)*. The interface follows :attr:`Iq`. |
---|
| 977 | Iqabc = None # type: Union[None, str, Callable[[np.ndarray], np.ndarray]] |
---|
[32e3c9b] | 978 | #: Returns *I(qx, qy, a, b, ...)*. The interface follows :attr:`Iq`. |
---|
| 979 | Imagnetic = None # type: Union[None, str, Callable[[np.ndarray], np.ndarray]] |
---|
[a5b8477] | 980 | #: Returns a model profile curve *x, y*. If *profile* is defined, this |
---|
| 981 | #: curve will appear in response to the *Show* button in SasView. Use |
---|
| 982 | #: :attr:`profile_axes` to set the axis labels. Note that *y* values |
---|
| 983 | #: will be scaled by 1e6 before plotting. |
---|
[c1a888b] | 984 | profile = None # type: Optional[Callable[[np.ndarray], None]] |
---|
[a5b8477] | 985 | #: Axis labels for the :attr:`profile` plot. The default is *['x', 'y']*. |
---|
| 986 | #: Only the *x* component is used for now. |
---|
| 987 | profile_axes = None # type: Tuple[str, str] |
---|
| 988 | #: Returns *sesans(z, a, b, ...)* for models which can directly compute |
---|
| 989 | #: the SESANS correlation function. Note: not currently implemented. |
---|
[c1a888b] | 990 | sesans = None # type: Optional[Callable[[np.ndarray], np.ndarray]] |
---|
[e65c3ba] | 991 | #: Returns a random parameter set for the model |
---|
| 992 | random = None # type: Optional[Callable[[], Dict[str, float]]] |
---|
[108e70e] | 993 | #: Line numbers for symbols defining C code |
---|
| 994 | lineno = None # type: Dict[str, int] |
---|
[da63656] | 995 | |
---|
[6d6508e] | 996 | def __init__(self): |
---|
[a86f6c0] | 997 | # type: () -> None |
---|
[6d6508e] | 998 | pass |
---|
| 999 | |
---|
[04045f4] | 1000 | def get_hidden_parameters(self, control): |
---|
[a5b8477] | 1001 | """ |
---|
| 1002 | Returns the set of hidden parameters for the model. *control* is the |
---|
| 1003 | value of the control parameter. Note that multiplicity models have |
---|
| 1004 | an implicit control parameter, which is the parameter that controls |
---|
| 1005 | the multiplicity. |
---|
| 1006 | """ |
---|
[04045f4] | 1007 | if self.hidden is not None: |
---|
| 1008 | hidden = self.hidden(control) |
---|
| 1009 | else: |
---|
[ce176ca] | 1010 | controls = [p for p in self.parameters.kernel_parameters |
---|
| 1011 | if p.is_control] |
---|
[04045f4] | 1012 | if len(controls) != 1: |
---|
| 1013 | raise ValueError("more than one control parameter") |
---|
| 1014 | hidden = set(p.id+str(k) |
---|
| 1015 | for p in self.parameters.kernel_parameters |
---|
| 1016 | for k in range(control+1, p.length+1) |
---|
| 1017 | if p.length > 1) |
---|
[bd547d0] | 1018 | for p in self.parameters.kernel_parameters: |
---|
| 1019 | if p.length > 1 and p.type == "sld": |
---|
| 1020 | for k in range(control+1, p.length+1): |
---|
| 1021 | base = p.id+str(k) |
---|
| 1022 | hidden.update((base+"_M0", base+"_mtheta", base+"_mphi")) |
---|
[04045f4] | 1023 | return hidden |
---|