source: sasmodels/sasmodels/sasview_model.py @ a80e64c

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

add sasview compatible MultiplicationModel? interface to product model

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