source: sasmodels/sasmodels/sasview_model.py @ 44ca3e1

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

Merge branch 'master' into ticket-741

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