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

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 fd62331 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
RevLine 
[cb4ef58]1import copy
2
3import numpy
[08959b8]4
5from sas.sascalc.calculator.BaseComponent import BaseComponent
[cb4ef58]6
[08959b8]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):
[fd62331]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
[08959b8]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 = {}
[fd62331]36
37        ## Define parameters to exclude from multiplication model
38        self.excluded_params={'radius_effective','scale','background'}
39
40        ##models
[08959b8]41        self.p_model = p_model
[fd62331]42        self.s_model = s_model
[08959b8]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
[fd62331]50        self.params['background']  = 0
51
[08959b8]52        ## Parameter details [units, min, max]
53        self._set_details()
[cb4ef58]54        self.details['scale_factor'] = ['', 0.0, numpy.inf]
[fd62331]55        self.details['background'] = ['',-numpy.inf,numpy.inf]
56
[08959b8]57        #list of parameter that can be fitted
[fd62331]58        self._set_fixed_params()
[08959b8]59        ## parameters with orientation
60        for item in self.p_model.orientation_params:
61            self.orientation_params.append(item)
[fd62331]62        for item in self.p_model.magnetic_params:
63            self.magnetic_params.append(item)
[08959b8]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
[fd62331]73        self.multiplicity = multiplicity
74
[08959b8]75        # non-fittable parameters
[fd62331]76        self.non_fittable = p_model.non_fittable
77        self.multiplicity_info = []
[08959b8]78        self.fun_list = {}
79        if self.non_fittable > 1:
80            try:
[fd62331]81                self.multiplicity_info = p_model.multiplicity_info
[08959b8]82                self.fun_list = p_model.fun_list
[cb4ef58]83                self.is_multiplicity_model = True
[08959b8]84            except:
85                pass
86        else:
[cb4ef58]87            self.is_multiplicity_model = False
88            self.multiplicity_info = [0]
[fd62331]89
[08959b8]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
[fd62331]103
104
[08959b8]105    def _set_dispersion(self):
106        """
107        combine the two models' dispersions. Polydispersity should not be
108        applied to s_model
109        """
[fd62331]110        ##set dispersion only from p_model
[08959b8]111        for name , value in self.p_model.dispersion.iteritems():
[fd62331]112            self.dispersion[name] = value
113
[08959b8]114    def getProfile(self):
115        """
116        Get SLD profile of p_model if exists
[fd62331]117
[08959b8]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
[fd62331]128
[08959b8]129        return x, y
[fd62331]130
[08959b8]131    def _set_params(self):
132        """
133        Concatenate the parameters of the two models to create
[fd62331]134        these model parameters
[08959b8]135        """
136
137        for name , value in self.p_model.params.iteritems():
[fd62331]138            if not name in self.params.keys() and name not in self.excluded_params:
[08959b8]139                self.params[name] = value
[fd62331]140
[08959b8]141        for name , value in self.s_model.params.iteritems():
[fd62331]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:
[08959b8]144                self.params[name] = value
[fd62331]145
[08959b8]146        # Set "scale and effec_radius to P and S model as initializing
147        # since run P*S comes from P and S separately.
[fd62331]148        self._set_backgrounds()
[08959b8]149        self._set_scale_factor()
[fd62331]150        self._set_radius_effective()
151
[08959b8]152    def _set_details(self):
153        """
154        Concatenate details of the two models to create
[fd62331]155        this model's details
[08959b8]156        """
157        for name, detail in self.p_model.details.iteritems():
[fd62331]158            if name not in self.excluded_params:
[08959b8]159                self.details[name] = detail
[fd62331]160
[08959b8]161        for name , detail in self.s_model.details.iteritems():
[fd62331]162            if not name in self.details.keys() or name not in self.exluded_params:
[08959b8]163                self.details[name] = detail
[fd62331]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
[08959b8]173    def _set_scale_factor(self):
174        """
175        Set scale=volfraction for P model
176        """
177        value = self.params['volfraction']
[fd62331]178        if value != None:
[08959b8]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)
[fd62331]186
187    def _set_radius_effective(self):
[08959b8]188        """
189        Set effective radius to S(Q) model
190        """
[fd62331]191        if not 'radius_effective' in self.s_model.params.keys():
[08959b8]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:
[fd62331]196            self.s_model.setParam('radius_effective', effective_radius)
197
[08959b8]198    def setParam(self, name, value):
[fd62331]199        """
[08959b8]200        Set the value of a model parameter
[fd62331]201
[08959b8]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)
[fd62331]207
208        ## setParam to p model
209        # set 'scale' in P(Q) equal to volfraction
[08959b8]210        if name == 'volfraction':
211            self._set_scale_factor()
[fd62331]212        elif name in self.p_model.getParamList() and name not in self.excluded_params:
[08959b8]213            self.p_model.setParam( name, value)
[fd62331]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:
[08959b8]219            if name != 'volfraction':
220                self.s_model.setParam( name, value)
[fd62331]221
[08959b8]222
223        #self._setParamHelper( name, value)
[fd62331]224
[08959b8]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
[fd62331]244
[08959b8]245        raise ValueError, "Model does not contain parameter %s" % name
[fd62331]246
247
[08959b8]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()
[fd62331]256
257
[08959b8]258    def run(self, x = 0.0):
[fd62331]259        """
[08959b8]260        Evaluate the model
[fd62331]261
[08959b8]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
[fd62331]266        self._set_radius_effective()
[08959b8]267        self._set_scale_factor()
268        return self.params['scale_factor'] * self.p_model.run(x) * \
[fd62331]269                            self.s_model.run(x) + self.params['background']
[08959b8]270
271    def runXY(self, x = 0.0):
[fd62331]272        """
[08959b8]273        Evaluate the model
[fd62331]274
[08959b8]275        :param x: input q-value (float or [float, float] as [qx, qy])
276        :return: scattering function value
[fd62331]277        """
[08959b8]278        # set effective radius and scaling factor before run
[fd62331]279        self._set_radius_effective()
[08959b8]280        self._set_scale_factor()
281        out = self.params['scale_factor'] * self.p_model.runXY(x) * \
[fd62331]282                        self.s_model.runXY(x) + self.params['background']
[08959b8]283        return out
[fd62331]284
285    ## Now (May27,10) directly uses the model eval function
[08959b8]286    ## instead of the for-loop in Base Component.
287    def evalDistribution(self, x = []):
[fd62331]288        """
[08959b8]289        Evaluate the model in cartesian coordinates
[fd62331]290
[08959b8]291        :param x: input q[], or [qx[], qy[]]
292        :return: scattering function P(q[])
293        """
294        # set effective radius and scaling factor before run
[fd62331]295        self._set_radius_effective()
[08959b8]296        self._set_scale_factor()
297        out = self.params['scale_factor'] * self.p_model.evalDistribution(x) * \
[fd62331]298                        self.s_model.evalDistribution(x) + self.params['background']
[08959b8]299        return out
300
301    def set_dispersion(self, parameter, dispersion):
302        """
303        Set the dispersion object for a model parameter
[fd62331]304
[08959b8]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:
[fd62331]315            raise
[08959b8]316
317    def fill_description(self, p_model, s_model):
318        """
319        Fill the description for P(Q)*S(Q)
320        """
321        description = ""
[fd62331]322        description += "Note:1) The radius_effective (effective radius) of %s \n"%\
[08959b8]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.