source: sasmodels/sasmodels/sasview_model.py @ eafc9fa

core_shell_microgelscostrafo411magnetic_modelrelease_v0.94release_v0.95ticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since eafc9fa was eafc9fa, checked in by Paul Kienzle <pkienzle@…>, 8 years ago

refactor kernel wrappers to simplify q input handling

  • Property mode set to 100644
File size: 12.2 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 make_class
8    from sasmodels.models import cylinder
9    CylinderModel = make_class(cylinder, dtype='single')
10
11The model parameters for sasmodels are different from those in sasview.
12When reloading previously saved models, the parameters should be converted
13using :func:`sasmodels.convert.convert`.
14"""
15
16import math
17from copy import deepcopy
18import warnings
19
20import numpy as np
21
22from . import core
23
24def make_class(model_definition, dtype='single', namestyle='name'):
25    """
26    Load the sasview model defined in *kernel_module*.
27
28    Returns a class that can be used directly as a sasview model.
29
30    Defaults to using the new name for a model.  Setting
31    *namestyle='oldname'* will produce a class with a name
32    compatible with SasView.
33    """
34    model = core.load_model(model_definition, dtype=dtype)
35    def __init__(self, multfactor=1):
36        SasviewModel.__init__(self, model)
37    attrs = dict(__init__=__init__)
38    ConstructedModel = type(model.info[namestyle], (SasviewModel,), attrs)
39    return ConstructedModel
40
41class SasviewModel(object):
42    """
43    Sasview wrapper for opencl/ctypes model.
44    """
45    def __init__(self, model):
46        """Initialization"""
47        self._model = model
48
49        self.name = model.info['name']
50        self.oldname = model.info['oldname']
51        self.description = model.info['description']
52        self.category = None
53        self.multiplicity_info = None
54        self.is_multifunc = False
55
56        ## interpret the parameters
57        ## TODO: reorganize parameter handling
58        self.details = dict()
59        self.params = dict()
60        self.dispersion = dict()
61        partype = model.info['partype']
62        for name, units, default, limits, _, _ in model.info['parameters']:
63            self.params[name] = default
64            self.details[name] = [units] + limits
65
66        for name in partype['pd-2d']:
67            self.dispersion[name] = {
68                'width': 0,
69                'npts': 35,
70                'nsigmas': 3,
71                'type': 'gaussian',
72            }
73
74        self.orientation_params = (
75            partype['orientation']
76            + [n + '.width' for n in partype['orientation']]
77            + partype['magnetic'])
78        self.magnetic_params = partype['magnetic']
79        self.fixed = [n + '.width' for n in partype['pd-2d']]
80        self.non_fittable = []
81
82        ## independent parameter name and unit [string]
83        self.input_name = model.info.get("input_name", "Q")
84        self.input_unit = model.info.get("input_unit", "A^{-1}")
85        self.output_name = model.info.get("output_name", "Intensity")
86        self.output_unit = model.info.get("output_unit", "cm^{-1}")
87
88        ## _persistency_dict is used by sas.perspectives.fitting.basepage
89        ## to store dispersity reference.
90        ## TODO: _persistency_dict to persistency_dict throughout sasview
91        self._persistency_dict = {}
92
93        ## New fields introduced for opencl rewrite
94        self.cutoff = 1e-5
95
96    def __str__(self):
97        """
98        :return: string representation
99        """
100        return self.name
101
102    def is_fittable(self, par_name):
103        """
104        Check if a given parameter is fittable or not
105
106        :param par_name: the parameter name to check
107        """
108        return par_name.lower() in self.fixed
109        #For the future
110        #return self.params[str(par_name)].is_fittable()
111
112
113    # pylint: disable=no-self-use
114    def getProfile(self):
115        """
116        Get SLD profile
117
118        : return: (z, beta) where z is a list of depth of the transition points
119                beta is a list of the corresponding SLD values
120        """
121        return None, None
122
123    def setParam(self, name, value):
124        """
125        Set the value of a model parameter
126
127        :param name: name of the parameter
128        :param value: value of the parameter
129
130        """
131        # Look for dispersion parameters
132        toks = name.split('.')
133        if len(toks) == 2:
134            for item in self.dispersion.keys():
135                if item.lower() == toks[0].lower():
136                    for par in self.dispersion[item]:
137                        if par.lower() == toks[1].lower():
138                            self.dispersion[item][par] = value
139                            return
140        else:
141            # Look for standard parameter
142            for item in self.params.keys():
143                if item.lower() == name.lower():
144                    self.params[item] = value
145                    return
146
147        raise ValueError("Model does not contain parameter %s" % name)
148
149    def getParam(self, name):
150        """
151        Set the value of a model parameter
152
153        :param name: name of the parameter
154
155        """
156        # Look for dispersion parameters
157        toks = name.split('.')
158        if len(toks) == 2:
159            for item in self.dispersion.keys():
160                if item.lower() == toks[0].lower():
161                    for par in self.dispersion[item]:
162                        if par.lower() == toks[1].lower():
163                            return self.dispersion[item][par]
164        else:
165            # Look for standard parameter
166            for item in self.params.keys():
167                if item.lower() == name.lower():
168                    return self.params[item]
169
170        raise ValueError("Model does not contain parameter %s" % name)
171
172    def getParamList(self):
173        """
174        Return a list of all available parameters for the model
175        """
176        param_list = self.params.keys()
177        # WARNING: Extending the list with the dispersion parameters
178        param_list.extend(self.getDispParamList())
179        return param_list
180
181    def getDispParamList(self):
182        """
183        Return a list of all available parameters for the model
184        """
185        # TODO: fix test so that parameter order doesn't matter
186        ret = ['%s.%s' % (d.lower(), p)
187               for d in self._model.info['partype']['pd-2d']
188               for p in ('npts', 'nsigmas', 'width')]
189        #print(ret)
190        return ret
191
192    def clone(self):
193        """ Return a identical copy of self """
194        return deepcopy(self)
195
196    def run(self, x=0.0):
197        """
198        Evaluate the model
199
200        :param x: input q, or [q,phi]
201
202        :return: scattering function P(q)
203
204        **DEPRECATED**: use calculate_Iq instead
205        """
206        if isinstance(x, (list, tuple)):
207            # pylint: disable=unpacking-non-sequence
208            q, phi = x
209            return self.calculate_Iq([q * math.cos(phi)],
210                                     [q * math.sin(phi)])[0]
211        else:
212            return self.calculate_Iq([float(x)])[0]
213
214
215    def runXY(self, x=0.0):
216        """
217        Evaluate the model in cartesian coordinates
218
219        :param x: input q, or [qx, qy]
220
221        :return: scattering function P(q)
222
223        **DEPRECATED**: use calculate_Iq instead
224        """
225        if isinstance(x, (list, tuple)):
226            return self.calculate_Iq([float(x[0])], [float(x[1])])[0]
227        else:
228            return self.calculate_Iq([float(x)])[0]
229
230    def evalDistribution(self, qdist):
231        r"""
232        Evaluate a distribution of q-values.
233
234        :param qdist: array of q or a list of arrays [qx,qy]
235
236        * For 1D, a numpy array is expected as input
237
238        ::
239
240            evalDistribution(q)
241
242          where *q* is a numpy array.
243
244        * For 2D, a list of *[qx,qy]* is expected with 1D arrays as input
245
246        ::
247
248              qx = [ qx[0], qx[1], qx[2], ....]
249              qy = [ qy[0], qy[1], qy[2], ....]
250
251        If the model is 1D only, then
252
253        .. math::
254
255            q = \sqrt{q_x^2+q_y^2}
256
257        """
258        if isinstance(qdist, (list, tuple)):
259            # Check whether we have a list of ndarrays [qx,qy]
260            qx, qy = qdist
261            partype = self._model.info['partype']
262            if not partype['orientation'] and not partype['magnetic']:
263                return self.calculate_Iq(np.sqrt(qx ** 2 + qy ** 2))
264            else:
265                return self.calculate_Iq(qx, qy)
266
267        elif isinstance(qdist, np.ndarray):
268            # We have a simple 1D distribution of q-values
269            return self.calculate_Iq(qdist)
270
271        else:
272            raise TypeError("evalDistribution expects q or [qx, qy], not %r"
273                            % type(qdist))
274
275    def calculate_Iq(self, *args):
276        """
277        Calculate Iq for one set of q with the current parameters.
278
279        If the model is 1D, use *q*.  If 2D, use *qx*, *qy*.
280
281        This should NOT be used for fitting since it copies the *q* vectors
282        to the card for each evaluation.
283        """
284        q_vectors = [np.asarray(q) for q in args]
285        fn = self._model(q_vectors)
286        pars = [self.params[v] for v in fn.fixed_pars]
287        pd_pars = [self._get_weights(p) for p in fn.pd_pars]
288        result = fn(pars, pd_pars, self.cutoff)
289        fn.input.release()
290        fn.release()
291        return result
292
293    def calculate_ER(self):
294        """
295        Calculate the effective radius for P(q)*S(q)
296
297        :return: the value of the effective radius
298        """
299        ER = self._model.info.get('ER', None)
300        if ER is None:
301            return 1.0
302        else:
303            values, weights = self._dispersion_mesh()
304            fv = ER(*values)
305            #print(values[0].shape, weights.shape, fv.shape)
306            return np.sum(weights * fv) / np.sum(weights)
307
308    def calculate_VR(self):
309        """
310        Calculate the volf ratio for P(q)*S(q)
311
312        :return: the value of the volf ratio
313        """
314        VR = self._model.info.get('VR', None)
315        if VR is None:
316            return 1.0
317        else:
318            values, weights = self._dispersion_mesh()
319            whole, part = VR(*values)
320            return np.sum(weights * part) / np.sum(weights * whole)
321
322    def set_dispersion(self, parameter, dispersion):
323        """
324        Set the dispersion object for a model parameter
325
326        :param parameter: name of the parameter [string]
327        :param dispersion: dispersion object of type Dispersion
328        """
329        if parameter.lower() in (s.lower() for s in self.params.keys()):
330            # TODO: Store the disperser object directly in the model.
331            # The current method of creating one on the fly whenever it is
332            # needed is kind of funky.
333            # Note: can't seem to get disperser parameters from sasview
334            # (1) Could create a sasview model that has not yet # been
335            # converted, assign the disperser to one of its polydisperse
336            # parameters, then retrieve the disperser parameters from the
337            # sasview model.  (2) Could write a disperser parameter retriever
338            # in sasview.  (3) Could modify sasview to use sasmodels.weights
339            # dispersers.
340            # For now, rely on the fact that the sasview only ever uses
341            # new dispersers in the set_dispersion call and create a new
342            # one instead of trying to assign parameters.
343            from . import weights
344            disperser = weights.dispersers[dispersion.__class__.__name__]
345            dispersion = weights.models[disperser]()
346            self.dispersion[parameter] = dispersion.get_pars()
347        else:
348            raise ValueError("%r is not a dispersity or orientation parameter")
349
350    def _dispersion_mesh(self):
351        """
352        Create a mesh grid of dispersion parameters and weights.
353
354        Returns [p1,p2,...],w where pj is a vector of values for parameter j
355        and w is a vector containing the products for weights for each
356        parameter set in the vector.
357        """
358        pars = self._model.info['partype']['volume']
359        return core.dispersion_mesh([self._get_weights(p) for p in pars])
360
361    def _get_weights(self, par):
362        """
363            Return dispersion weights
364            :param par parameter name
365        """
366        from . import weights
367
368        relative = self._model.info['partype']['pd-rel']
369        limits = self._model.info['limits']
370        dis = self.dispersion[par]
371        value, weight = weights.get_weights(
372            dis['type'], dis['npts'], dis['width'], dis['nsigmas'],
373            self.params[par], limits[par], par in relative)
374        return value, weight / np.sum(weight)
375
Note: See TracBrowser for help on using the repository browser.