source: sasmodels/sasmodels/modelinfo.py @ 8698a0d

core_shell_microgelsmagnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 8698a0d was 8698a0d, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

revise api for oriented shapes, allowing jitter in the frame of the sample

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