source: sasview/src/sas/sascalc/calculator/BaseComponent.py @ 5876f7e

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.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 5876f7e was 9e531f2, checked in by krzywon, 9 years ago

Code Cleanup - Fix build?!?!

  • Property mode set to 100644
File size: 8.7 KB
Line 
1#!/usr/bin/env python
2
3"""
4Provide base functionality for all model components
5"""
6
7# imports
8import copy
9import numpy
10#TO DO: that about a way to make the parameter
11#is self return if it is fittable or not
12
13class BaseComponent:
14    """
15    Basic model component
16
17    Since version 0.5.0, basic operations are no longer supported.
18    """
19
20    def __init__(self):
21        """ Initialization"""
22
23        ## Name of the model
24        self.name = "BaseComponent"
25
26        ## Parameters to be accessed by client
27        self.params = {}
28        self.details = {}
29        ## Dictionary used to store the dispersity/averaging
30        #  parameters of dispersed/averaged parameters.
31        self.dispersion = {}
32        # string containing information about the model such as the equation
33        #of the given model, exception or possible use
34        self.description = ''
35        #list of parameter that can be fitted
36        self.fixed = []
37        #list of non-fittable parameter
38        self.non_fittable = []
39        ## parameters with orientation
40        self.orientation_params = []
41        ## magnetic parameters
42        self.magnetic_params = []
43        ## store dispersity reference
44        self._persistency_dict = {}
45        ## independent parameter name and unit [string]
46        self.input_name = "Q"
47        self.input_unit = "A^{-1}"
48        ## output name and unit  [string]
49        self.output_name = "Intensity"
50        self.output_unit = "cm^{-1}"
51
52    def __str__(self):
53        """
54        :return: string representatio
55        """
56        return self.name
57
58    def is_fittable(self, par_name):
59        """
60        Check if a given parameter is fittable or not
61
62        :param par_name: the parameter name to check
63
64        """
65        return par_name.lower() in self.fixed
66        #For the future
67        #return self.params[str(par_name)].is_fittable()
68
69    def run(self, x):
70        """
71        run 1d
72        """
73        return NotImplemented
74
75    def runXY(self, x):
76        """
77        run 2d
78        """
79        return NotImplemented
80
81    def calculate_ER(self):
82        """
83        Calculate effective radius
84        """
85        return NotImplemented
86
87    def calculate_VR(self):
88        """
89        Calculate volume fraction ratio
90        """
91        return NotImplemented
92
93    def evalDistribution(self, qdist):
94        """
95        Evaluate a distribution of q-values.
96
97        * For 1D, a numpy array is expected as input: ::
98
99            evalDistribution(q)
100
101          where q is a numpy array.
102
103
104        * For 2D, a list of numpy arrays are expected: [qx_prime,qy_prime],
105          where 1D arrays, ::
106
107              qx_prime = [ qx[0], qx[1], qx[2], ....]
108          and ::
109              qy_prime = [ qy[0], qy[1], qy[2], ....]
110
111        Then get ::
112            q = numpy.sqrt(qx_prime^2+qy_prime^2)
113
114        that is a qr in 1D array; ::
115            q = [q[0], q[1], q[2], ....]
116
117        ..note::
118          Due to 2D speed issue, no anisotropic scattering
119          is supported for python models, thus C-models should have
120          their own evalDistribution methods.
121
122        The method is then called the following way: ::
123
124            evalDistribution(q)
125        where q is a numpy array.
126
127        :param qdist: ndarray of scalar q-values or list [qx,qy] where qx,qy are 1D ndarrays
128        """
129        if qdist.__class__.__name__ == 'list':
130            # Check whether we have a list of ndarrays [qx,qy]
131            if len(qdist)!=2 or \
132                qdist[0].__class__.__name__ != 'ndarray' or \
133                qdist[1].__class__.__name__ != 'ndarray':
134                msg = "evalDistribution expects a list of 2 ndarrays"
135                raise RuntimeError, msg
136
137            # Extract qx and qy for code clarity
138            qx = qdist[0]
139            qy = qdist[1]
140
141            # calculate q_r component for 2D isotropic
142            q = numpy.sqrt(qx**2+qy**2)
143            # vectorize the model function runXY
144            v_model = numpy.vectorize(self.runXY, otypes=[float])
145            # calculate the scattering
146            iq_array = v_model(q)
147
148            return iq_array
149
150        elif qdist.__class__.__name__ == 'ndarray':
151            # We have a simple 1D distribution of q-values
152            v_model = numpy.vectorize(self.runXY, otypes=[float])
153            iq_array = v_model(qdist)
154            return iq_array
155
156        else:
157            mesg = "evalDistribution is expecting an ndarray of scalar q-values"
158            mesg += " or a list [qx,qy] where qx,qy are 2D ndarrays."
159            raise RuntimeError, mesg
160
161
162
163    def clone(self):
164        """ Returns a new object identical to the current object """
165        obj = copy.deepcopy(self)
166        return self._clone(obj)
167
168    def _clone(self, obj):
169        """
170        Internal utility function to copy the internal
171        data members to a fresh copy.
172        """
173        obj.params     = copy.deepcopy(self.params)
174        obj.details    = copy.deepcopy(self.details)
175        obj.dispersion = copy.deepcopy(self.dispersion)
176        obj._persistency_dict = copy.deepcopy( self._persistency_dict)
177        return obj
178
179    def set_dispersion(self, parameter, dispersion):
180        """
181        model dispersions
182        """
183        ##Not Implemented
184        return None
185
186    def getProfile(self):
187        """
188        Get SLD profile
189
190        : return: (z, beta) where z is a list of depth of the transition points
191                beta is a list of the corresponding SLD values
192        """
193        #Not Implemented
194        return None, None
195
196    def setParam(self, name, value):
197        """
198        Set the value of a model parameter
199
200        :param name: name of the parameter
201        :param value: value of the parameter
202
203        """
204        # Look for dispersion parameters
205        toks = name.split('.')
206        if len(toks)==2:
207            for item in self.dispersion.keys():
208                if item.lower()==toks[0].lower():
209                    for par in self.dispersion[item]:
210                        if par.lower() == toks[1].lower():
211                            self.dispersion[item][par] = value
212                            return
213        else:
214            # Look for standard parameter
215            for item in self.params.keys():
216                if item.lower()==name.lower():
217                    self.params[item] = value
218                    return
219
220        raise ValueError, "Model does not contain parameter %s" % name
221
222    def getParam(self, name):
223        """
224        Set the value of a model parameter
225        :param name: name of the parameter
226
227        """
228        # Look for dispersion parameters
229        toks = name.split('.')
230        if len(toks)==2:
231            for item in self.dispersion.keys():
232                if item.lower()==toks[0].lower():
233                    for par in self.dispersion[item]:
234                        if par.lower() == toks[1].lower():
235                            return self.dispersion[item][par]
236        else:
237            # Look for standard parameter
238            for item in self.params.keys():
239                if item.lower()==name.lower():
240                    return self.params[item]
241
242        raise ValueError, "Model does not contain parameter %s" % name
243
244    def getParamList(self):
245        """
246        Return a list of all available parameters for the model
247        """
248        list = self.params.keys()
249        # WARNING: Extending the list with the dispersion parameters
250        list.extend(self.getDispParamList())
251        return list
252
253    def getDispParamList(self):
254        """
255        Return a list of all available parameters for the model
256        """
257        list = []
258
259        for item in self.dispersion.keys():
260            for p in self.dispersion[item].keys():
261                if p not in ['type']:
262                    list.append('%s.%s' % (item.lower(), p.lower()))
263
264        return list
265
266    # Old-style methods that are no longer used
267    def setParamWithToken(self, name, value, token, member):
268        """
269        set Param With Token
270        """
271        return NotImplemented
272    def getParamWithToken(self, name, token, member):
273        """
274        get Param With Token
275        """
276        return NotImplemented
277
278    def getParamListWithToken(self, token, member):
279        """
280        get Param List With Token
281        """
282        return NotImplemented
283    def __add__(self, other):
284        """
285        add
286        """
287        raise ValueError, "Model operation are no longer supported"
288    def __sub__(self, other):
289        """
290        sub
291        """
292        raise ValueError, "Model operation are no longer supported"
293    def __mul__(self, other):
294        """
295        mul
296        """
297        raise ValueError, "Model operation are no longer supported"
298    def __div__(self, other):
299        """
300        div
301        """
302        raise ValueError, "Model operation are no longer supported"
Note: See TracBrowser for help on using the repository browser.