source: sasview/src/sas/sascalc/fit/MultiplicationModel.py @ ec72ceb

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since ec72ceb was fd62331, checked in by ajj, 8 years ago

Updating muliplicationmodel to be correct.

Fixes #750

  • Property mode set to 100644
File size: 11.6 KB
Line 
1import copy
2
3import numpy
4
5from sas.sascalc.calculator.BaseComponent import BaseComponent
6
7class MultiplicationModel(BaseComponent):
8    r"""
9        Use for P(Q)\*S(Q); function call must be in the order of P(Q) and then S(Q):
10        The model parameters are combined from both models, P(Q) and S(Q), except 1) 'radius_effective' of S(Q)
11        which will be calculated from P(Q) via calculate_ER(),
12        and 2) 'scale' in P model which is synchronized w/ volfraction in S
13        then P*S is multiplied by a new parameter, 'scale_factor'.
14        The polydispersion is applicable only to P(Q), not to S(Q).
15
16        .. note:: P(Q) refers to 'form factor' model while S(Q) does to 'structure factor'.
17    """
18    def __init__(self, p_model, s_model ):
19        BaseComponent.__init__(self)
20        """
21        :param p_model: form factor, P(Q)
22        :param s_model: structure factor, S(Q)
23        """
24
25        ## Setting  model name model description
26        self.description = ""
27        self.name = p_model.name +" * "+ s_model.name
28        self.description= self.name + "\n"
29        self.fill_description(p_model, s_model)
30
31        ## Define parameters
32        self.params = {}
33
34        ## Parameter details [units, min, max]
35        self.details = {}
36
37        ## Define parameters to exclude from multiplication model
38        self.excluded_params={'radius_effective','scale','background'}
39
40        ##models
41        self.p_model = p_model
42        self.s_model = s_model
43        self.magnetic_params = []
44        ## dispersion
45        self._set_dispersion()
46        ## Define parameters
47        self._set_params()
48        ## New parameter:Scaling factor
49        self.params['scale_factor'] = 1
50        self.params['background']  = 0
51
52        ## Parameter details [units, min, max]
53        self._set_details()
54        self.details['scale_factor'] = ['', 0.0, numpy.inf]
55        self.details['background'] = ['',-numpy.inf,numpy.inf]
56
57        #list of parameter that can be fitted
58        self._set_fixed_params()
59        ## parameters with orientation
60        for item in self.p_model.orientation_params:
61            self.orientation_params.append(item)
62        for item in self.p_model.magnetic_params:
63            self.magnetic_params.append(item)
64        for item in self.s_model.orientation_params:
65            if not item in self.orientation_params:
66                self.orientation_params.append(item)
67        # get multiplicity if model provide it, else 1.
68        try:
69            multiplicity = p_model.multiplicity
70        except:
71            multiplicity = 1
72        ## functional multiplicity of the model
73        self.multiplicity = multiplicity
74
75        # non-fittable parameters
76        self.non_fittable = p_model.non_fittable
77        self.multiplicity_info = []
78        self.fun_list = {}
79        if self.non_fittable > 1:
80            try:
81                self.multiplicity_info = p_model.multiplicity_info
82                self.fun_list = p_model.fun_list
83                self.is_multiplicity_model = True
84            except:
85                pass
86        else:
87            self.is_multiplicity_model = False
88            self.multiplicity_info = [0]
89
90    def _clone(self, obj):
91        """
92        Internal utility function to copy the internal data members to a
93        fresh copy.
94        """
95        obj.params     = copy.deepcopy(self.params)
96        obj.description     = copy.deepcopy(self.description)
97        obj.details    = copy.deepcopy(self.details)
98        obj.dispersion = copy.deepcopy(self.dispersion)
99        obj.p_model  = self.p_model.clone()
100        obj.s_model  = self.s_model.clone()
101        #obj = copy.deepcopy(self)
102        return obj
103
104
105    def _set_dispersion(self):
106        """
107        combine the two models' dispersions. Polydispersity should not be
108        applied to s_model
109        """
110        ##set dispersion only from p_model
111        for name , value in self.p_model.dispersion.iteritems():
112            self.dispersion[name] = value
113
114    def getProfile(self):
115        """
116        Get SLD profile of p_model if exists
117
118        :return: (r, beta) where r is a list of radius of the transition points\
119                beta is a list of the corresponding SLD values
120
121        .. note:: This works only for func_shell num = 2 (exp function).
122        """
123        try:
124            x, y = self.p_model.getProfile()
125        except:
126            x = None
127            y = None
128
129        return x, y
130
131    def _set_params(self):
132        """
133        Concatenate the parameters of the two models to create
134        these model parameters
135        """
136
137        for name , value in self.p_model.params.iteritems():
138            if not name in self.params.keys() and name not in self.excluded_params:
139                self.params[name] = value
140
141        for name , value in self.s_model.params.iteritems():
142            #Remove the radius_effective from the (P*S) model parameters.
143            if not name in self.params.keys() and name not in self.excluded_params:
144                self.params[name] = value
145
146        # Set "scale and effec_radius to P and S model as initializing
147        # since run P*S comes from P and S separately.
148        self._set_backgrounds()
149        self._set_scale_factor()
150        self._set_radius_effective()
151
152    def _set_details(self):
153        """
154        Concatenate details of the two models to create
155        this model's details
156        """
157        for name, detail in self.p_model.details.iteritems():
158            if name not in self.excluded_params:
159                self.details[name] = detail
160
161        for name , detail in self.s_model.details.iteritems():
162            if not name in self.details.keys() or name not in self.exluded_params:
163                self.details[name] = detail
164
165    def _set_backgrounds(self):
166        """
167        Set component backgrounds to zero
168        """
169        self.p_model.setParam('background',0)
170        self.s_model.setParam('background',0)
171
172
173    def _set_scale_factor(self):
174        """
175        Set scale=volfraction for P model
176        """
177        value = self.params['volfraction']
178        if value != None:
179            factor = self.p_model.calculate_VR()
180            if factor == None or factor == NotImplemented or factor == 0.0:
181                val = value
182            else:
183                val = value / factor
184            self.p_model.setParam('scale', value)
185            self.s_model.setParam('volfraction', val)
186
187    def _set_radius_effective(self):
188        """
189        Set effective radius to S(Q) model
190        """
191        if not 'radius_effective' in self.s_model.params.keys():
192            return
193        effective_radius = self.p_model.calculate_ER()
194        #Reset the effective_radius of s_model just before the run
195        if effective_radius != None and effective_radius != NotImplemented:
196            self.s_model.setParam('radius_effective', effective_radius)
197
198    def setParam(self, name, value):
199        """
200        Set the value of a model parameter
201
202        :param name: name of the parameter
203        :param value: value of the parameter
204        """
205        # set param to P*S model
206        self._setParamHelper( name, value)
207
208        ## setParam to p model
209        # set 'scale' in P(Q) equal to volfraction
210        if name == 'volfraction':
211            self._set_scale_factor()
212        elif name in self.p_model.getParamList() and name not in self.excluded_params:
213            self.p_model.setParam( name, value)
214
215        ## setParam to s model
216        # This is a little bit abundant: Todo: find better way
217        self._set_radius_effective()
218        if name in self.s_model.getParamList() and name not in self.excluded_params:
219            if name != 'volfraction':
220                self.s_model.setParam( name, value)
221
222
223        #self._setParamHelper( name, value)
224
225    def _setParamHelper(self, name, value):
226        """
227        Helper function to setparam
228        """
229        # Look for dispersion parameters
230        toks = name.split('.')
231        if len(toks)==2:
232            for item in self.dispersion.keys():
233                if item.lower()==toks[0].lower():
234                    for par in self.dispersion[item]:
235                        if par.lower() == toks[1].lower():
236                            self.dispersion[item][par] = value
237                            return
238        else:
239            # Look for standard parameter
240            for item in self.params.keys():
241                if item.lower() == name.lower():
242                    self.params[item] = value
243                    return
244
245        raise ValueError, "Model does not contain parameter %s" % name
246
247
248    def _set_fixed_params(self):
249        """
250        Fill the self.fixed list with the p_model fixed list
251        """
252        for item in self.p_model.fixed:
253            self.fixed.append(item)
254
255        self.fixed.sort()
256
257
258    def run(self, x = 0.0):
259        """
260        Evaluate the model
261
262        :param x: input q-value (float or [float, float] as [r, theta])
263        :return: (scattering function value)
264        """
265        # set effective radius and scaling factor before run
266        self._set_radius_effective()
267        self._set_scale_factor()
268        return self.params['scale_factor'] * self.p_model.run(x) * \
269                            self.s_model.run(x) + self.params['background']
270
271    def runXY(self, x = 0.0):
272        """
273        Evaluate the model
274
275        :param x: input q-value (float or [float, float] as [qx, qy])
276        :return: scattering function value
277        """
278        # set effective radius and scaling factor before run
279        self._set_radius_effective()
280        self._set_scale_factor()
281        out = self.params['scale_factor'] * self.p_model.runXY(x) * \
282                        self.s_model.runXY(x) + self.params['background']
283        return out
284
285    ## Now (May27,10) directly uses the model eval function
286    ## instead of the for-loop in Base Component.
287    def evalDistribution(self, x = []):
288        """
289        Evaluate the model in cartesian coordinates
290
291        :param x: input q[], or [qx[], qy[]]
292        :return: scattering function P(q[])
293        """
294        # set effective radius and scaling factor before run
295        self._set_radius_effective()
296        self._set_scale_factor()
297        out = self.params['scale_factor'] * self.p_model.evalDistribution(x) * \
298                        self.s_model.evalDistribution(x) + self.params['background']
299        return out
300
301    def set_dispersion(self, parameter, dispersion):
302        """
303        Set the dispersion object for a model parameter
304
305        :param parameter: name of the parameter [string]
306        :dispersion: dispersion object of type DispersionModel
307        """
308        value = None
309        try:
310            if parameter in self.p_model.dispersion.keys():
311                value = self.p_model.set_dispersion(parameter, dispersion)
312            self._set_dispersion()
313            return value
314        except:
315            raise
316
317    def fill_description(self, p_model, s_model):
318        """
319        Fill the description for P(Q)*S(Q)
320        """
321        description = ""
322        description += "Note:1) The radius_effective (effective radius) of %s \n"%\
323                                                                (s_model.name)
324        description += "             is automatically calculated "
325        description += "from size parameters (radius...).\n"
326        description += "         2) For non-spherical shape, "
327        description += "this approximation is valid \n"
328        description += "            only for limited systems. "
329        description += "Thus, use it at your own risk.\n"
330        description += "See %s description and %s description \n"% \
331                                                ( p_model.name, s_model.name )
332        description += "        for details of individual models."
333        self.description += description
Note: See TracBrowser for help on using the repository browser.