source: sasview/sansmodels/src/sans/models/BaseComponent.py @ 5548954

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 5548954 was 0145a25, checked in by Jae Cho <jhjcho@…>, 13 years ago

minor changes for plot labeling

  • Property mode set to 100644
File size: 8.1 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        ## store dispersity reference
42        self._persistency_dict = {}
43        ## independent parameter name and unit [string]
44        self.input_name = "Q"
45        self.input_unit = "A^{-1}"
46        ## output name and unit  [string]
47        self.output_name = "Intensity"
48        self.output_unit = "cm^{-1}"
49       
50    def __str__(self):
51        """
52        :return: string representatio
53
54        """
55        return self.name
56   
57    def is_fittable(self, par_name):
58        """
59        Check if a given parameter is fittable or not
60       
61        :param par_name: the parameter name to check
62       
63        """
64        return par_name.lower() in self.fixed
65        #For the future
66        #return self.params[str(par_name)].is_fittable()
67   
68    def run(self, x): return NotImplemented
69    def runXY(self, x): return NotImplemented 
70    def calculate_ER(self): return NotImplemented 
71    def evalDistribution(self, qdist):
72        """
73        Evaluate a distribution of q-values.
74       
75        * For 1D, a numpy array is expected as input:
76       
77            evalDistribution(q)
78           
79        where q is a numpy array.
80       
81       
82        * For 2D, a list of numpy arrays are expected: [qx_prime,qy_prime],
83          where 1D arrays,
84       
85        qx_prime = [ qx[0], qx[1], qx[2], ....]
86        and
87        qy_prime = [ qy[0], qy[1], qy[2], ....]
88       
89        Then get
90        q = numpy.sqrt(qx_prime^2+qy_prime^2)
91       
92        that is a qr in 1D array;
93        q = [q[0], q[1], q[2], ....]
94       
95        :Note: Due to 2D speed issue, no anisotropic scattering
96            is supported for python models, thus C-models should have
97             their own evalDistribution methods.
98       
99        The method is then called the following way:
100       
101        evalDistribution(q)
102        where q is a numpy array.
103       
104        :param qdist: ndarray of scalar q-values or list [qx,qy]
105                    where qx,qy are 1D ndarrays
106       
107        """
108        if qdist.__class__.__name__ == 'list':
109            # Check whether we have a list of ndarrays [qx,qy]
110            if len(qdist)!=2 or \
111                qdist[0].__class__.__name__ != 'ndarray' or \
112                qdist[1].__class__.__name__ != 'ndarray':
113                    raise RuntimeError, "evalDistribution expects a list of 2 ndarrays"
114               
115            # Extract qx and qy for code clarity
116            qx = qdist[0]
117            qy = qdist[1]
118           
119            # calculate q_r component for 2D isotropic
120            q = numpy.sqrt(qx**2+qy**2)
121            # vectorize the model function runXY
122            v_model = numpy.vectorize(self.runXY,otypes=[float])
123            # calculate the scattering
124            iq_array = v_model(q)
125
126            return iq_array
127               
128        elif qdist.__class__.__name__ == 'ndarray':
129                # We have a simple 1D distribution of q-values
130                v_model = numpy.vectorize(self.runXY,otypes=[float])
131                iq_array = v_model(qdist)
132
133                return iq_array
134           
135        else:
136            mesg = "evalDistribution is expecting an ndarray of scalar q-values"
137            mesg += " or a list [qx,qy] where qx,qy are 2D ndarrays."
138            raise RuntimeError, mesg
139       
140   
141   
142    def clone(self):
143        """ Returns a new object identical to the current object """
144        obj = copy.deepcopy(self)
145        return self._clone(obj)
146   
147    def _clone(self, obj):
148        """
149        Internal utility function to copy the internal
150        data members to a fresh copy.
151        """
152        obj.params     = copy.deepcopy(self.params)
153        obj.details    = copy.deepcopy(self.details)
154        obj.dispersion = copy.deepcopy(self.dispersion)
155        obj._persistency_dict = copy.deepcopy( self._persistency_dict)
156        return obj
157
158    def setParam(self, name, value):
159        """
160        Set the value of a model parameter
161   
162        :param name: name of the parameter
163        :param value: value of the parameter
164       
165        """
166        # Look for dispersion parameters
167        toks = name.split('.')
168        if len(toks)==2:
169            for item in self.dispersion.keys():
170                if item.lower()==toks[0].lower():
171                    for par in self.dispersion[item]:
172                        if par.lower() == toks[1].lower():
173                            self.dispersion[item][par] = value
174                            return
175        else:
176            # Look for standard parameter
177            for item in self.params.keys():
178                if item.lower()==name.lower():
179                    self.params[item] = value
180                    return
181           
182        raise ValueError, "Model does not contain parameter %s" % name
183       
184    def getParam(self, name):
185        """
186        Set the value of a model parameter
187
188        :param name: name of the parameter
189       
190        """
191        # Look for dispersion parameters
192        toks = name.split('.')
193        if len(toks)==2:
194            for item in self.dispersion.keys():
195                if item.lower()==toks[0].lower():
196                    for par in self.dispersion[item]:
197                        if par.lower() == toks[1].lower():
198                            return self.dispersion[item][par]
199        else:
200            # Look for standard parameter
201            for item in self.params.keys():
202                if item.lower()==name.lower():
203                    return self.params[item]
204           
205        raise ValueError, "Model does not contain parameter %s" % name
206     
207    def getParamList(self):
208        """
209        Return a list of all available parameters for the model
210        """ 
211        list = self.params.keys()
212        # WARNING: Extending the list with the dispersion parameters
213        list.extend(self.getDispParamList())
214        return list
215   
216    def getDispParamList(self):
217        """
218        Return a list of all available parameters for the model
219        """ 
220        list = []
221       
222        for item in self.dispersion.keys():
223            for p in self.dispersion[item].keys():
224                if p not in ['type']:
225                    list.append('%s.%s' % (item.lower(), p.lower()))
226                   
227        return list
228   
229    # Old-style methods that are no longer used
230    def setParamWithToken(self, name, value, token, member): return NotImplemented
231    def getParamWithToken(self, name, token, member): return NotImplemented
232    def getParamListWithToken(self, token, member): return NotImplemented
233    def __add__(self, other): raise ValueError, "Model operation are no longer supported"
234    def __sub__(self, other): raise ValueError, "Model operation are no longer supported"
235    def __mul__(self, other): raise ValueError, "Model operation are no longer supported"
236    def __div__(self, other): raise ValueError, "Model operation are no longer supported"
237       
Note: See TracBrowser for help on using the repository browser.