source: sasmodels/sasmodels/sasview_model.py @ 0a82216

core_shell_microgelscostrafo411magnetic_modelrelease_v0.94release_v0.95ticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 0a82216 was 0a82216, checked in by ajj, 9 years ago

making delivery of class with new name the default. now have to pass parameter to get the old SasView? name

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