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

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 92a52ff2 was e08bd5b, checked in by Jae Cho <jhjcho@…>, 13 years ago

c models fix: scale fix for P*S

  • Property mode set to 100644
File size: 8.1 KB
RevLine 
[ae3ce4e]1#!/usr/bin/env python
[79ac6f8]2
[ae60f86]3"""
[79ac6f8]4Provide base functionality for all model components
[ae3ce4e]5"""
6
7# imports   
8import copy
[83a25da]9import numpy
[988130c6]10#TO DO: that about a way to make the parameter
11#is self return if it is fittable or not 
[836fe6e]12
[ae3ce4e]13class BaseComponent:
[ae60f86]14    """
[79ac6f8]15    Basic model component
16   
17    Since version 0.5.0, basic operations are no longer supported.
[ae3ce4e]18    """
19
20    def __init__(self):
21        """ Initialization"""
22       
23        ## Name of the model
[79ac6f8]24        self.name = "BaseComponent"
[ae3ce4e]25       
26        ## Parameters to be accessed by client
27        self.params = {}
[3db3895]28        self.details = {}
[d30fdde]29        ## Dictionary used to store the dispersity/averaging
30        #  parameters of dispersed/averaged parameters.
31        self.dispersion = {}
[5f89fb8]32        # string containing information about the model such as the equation
33        #of the given model, exception or possible use
34        self.description=''
[c9636f7]35        #list of parameter that can be fitted
[35aface]36        self.fixed = []
37        #list of non-fittable parameter
38        self.non_fittable = []
[25a608f5]39        ## parameters with orientation
[35aface]40        self.orientation_params = []
[c3e4a7fa]41        ## store dispersity reference
42        self._persistency_dict = {}
[0145a25]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       
[ae3ce4e]50    def __str__(self):
[ae60f86]51        """
[79ac6f8]52        :return: string representatio
53
[ae3ce4e]54        """
55        return self.name
56   
[988130c6]57    def is_fittable(self, par_name):
[c9636f7]58        """
[79ac6f8]59        Check if a given parameter is fittable or not
60       
61        :param par_name: the parameter name to check
62       
[c9636f7]63        """
64        return par_name.lower() in self.fixed
[988130c6]65        #For the future
[836fe6e]66        #return self.params[str(par_name)].is_fittable()
[988130c6]67   
[ae60f86]68    def run(self, x): return NotImplemented
69    def runXY(self, x): return NotImplemented 
[f9bf661]70    def calculate_ER(self): return NotImplemented 
[e08bd5b]71    def calculate_VR(self): return NotImplemented 
[83a25da]72    def evalDistribution(self, qdist):
73        """
[79ac6f8]74        Evaluate a distribution of q-values.
75       
76        * For 1D, a numpy array is expected as input:
77       
[2f1a0dc]78            evalDistribution(q)
[ecc58e72]79           
[79ac6f8]80        where q is a numpy array.
81       
82       
83        * For 2D, a list of numpy arrays are expected: [qx_prime,qy_prime],
84          where 1D arrays,
85       
86        qx_prime = [ qx[0], qx[1], qx[2], ....]
87        and
88        qy_prime = [ qy[0], qy[1], qy[2], ....]
89       
90        Then get
91        q = numpy.sqrt(qx_prime^2+qy_prime^2)
92       
93        that is a qr in 1D array;
94        q = [q[0], q[1], q[2], ....]
95       
96        :Note: Due to 2D speed issue, no anisotropic scattering
97            is supported for python models, thus C-models should have
98             their own evalDistribution methods.
99       
100        The method is then called the following way:
101       
102        evalDistribution(q)
103        where q is a numpy array.
104       
105        :param qdist: ndarray of scalar q-values or list [qx,qy]
106                    where qx,qy are 1D ndarrays
107       
[83a25da]108        """
[ecc58e72]109        if qdist.__class__.__name__ == 'list':
110            # Check whether we have a list of ndarrays [qx,qy]
111            if len(qdist)!=2 or \
112                qdist[0].__class__.__name__ != 'ndarray' or \
113                qdist[1].__class__.__name__ != 'ndarray':
114                    raise RuntimeError, "evalDistribution expects a list of 2 ndarrays"
115               
116            # Extract qx and qy for code clarity
117            qx = qdist[0]
118            qy = qdist[1]
119           
[2f1a0dc]120            # calculate q_r component for 2D isotropic
121            q = numpy.sqrt(qx**2+qy**2)
122            # vectorize the model function runXY
123            v_model = numpy.vectorize(self.runXY,otypes=[float])
124            # calculate the scattering
125            iq_array = v_model(q)
126
[ecc58e72]127            return iq_array
128               
129        elif qdist.__class__.__name__ == 'ndarray':
130                # We have a simple 1D distribution of q-values
[2f1a0dc]131                v_model = numpy.vectorize(self.runXY,otypes=[float])
132                iq_array = v_model(qdist)
133
[ecc58e72]134                return iq_array
[83a25da]135           
[ecc58e72]136        else:
137            mesg = "evalDistribution is expecting an ndarray of scalar q-values"
138            mesg += " or a list [qx,qy] where qx,qy are 2D ndarrays."
139            raise RuntimeError, mesg
[2f1a0dc]140       
141   
[83a25da]142   
[ae3ce4e]143    def clone(self):
144        """ Returns a new object identical to the current object """
145        obj = copy.deepcopy(self)
[8809e48]146        return self._clone(obj)
147   
148    def _clone(self, obj):
149        """
[79ac6f8]150        Internal utility function to copy the internal
151        data members to a fresh copy.
[8809e48]152        """
[ae60f86]153        obj.params     = copy.deepcopy(self.params)
154        obj.details    = copy.deepcopy(self.details)
155        obj.dispersion = copy.deepcopy(self.dispersion)
[138c139]156        obj._persistency_dict = copy.deepcopy( self._persistency_dict)
[ae3ce4e]157        return obj
158
159    def setParam(self, name, value):
[ae60f86]160        """
[79ac6f8]161        Set the value of a model parameter
162   
163        :param name: name of the parameter
164        :param value: value of the parameter
[ae3ce4e]165       
166        """
[ae60f86]167        # Look for dispersion parameters
168        toks = name.split('.')
169        if len(toks)==2:
170            for item in self.dispersion.keys():
171                if item.lower()==toks[0].lower():
172                    for par in self.dispersion[item]:
173                        if par.lower() == toks[1].lower():
174                            self.dispersion[item][par] = value
175                            return
176        else:
177            # Look for standard parameter
178            for item in self.params.keys():
179                if item.lower()==name.lower():
180                    self.params[item] = value
181                    return
182           
183        raise ValueError, "Model does not contain parameter %s" % name
[ae3ce4e]184       
[ae60f86]185    def getParam(self, name):
186        """
[79ac6f8]187        Set the value of a model parameter
[ae60f86]188
[79ac6f8]189        :param name: name of the parameter
190       
[ae3ce4e]191        """
[ae60f86]192        # Look for dispersion parameters
[ae3ce4e]193        toks = name.split('.')
[ae60f86]194        if len(toks)==2:
195            for item in self.dispersion.keys():
196                if item.lower()==toks[0].lower():
197                    for par in self.dispersion[item]:
198                        if par.lower() == toks[1].lower():
199                            return self.dispersion[item][par]
200        else:
201            # Look for standard parameter
202            for item in self.params.keys():
203                if item.lower()==name.lower():
204                    return self.params[item]
205           
206        raise ValueError, "Model does not contain parameter %s" % name
207     
[ae3ce4e]208    def getParamList(self):
209        """
[79ac6f8]210        Return a list of all available parameters for the model
[ae60f86]211        """ 
212        list = self.params.keys()
213        # WARNING: Extending the list with the dispersion parameters
214        list.extend(self.getDispParamList())
215        return list
216   
217    def getDispParamList(self):
218        """
[79ac6f8]219        Return a list of all available parameters for the model
[ae60f86]220        """ 
221        list = []
222       
223        for item in self.dispersion.keys():
224            for p in self.dispersion[item].keys():
225                if p not in ['type']:
226                    list.append('%s.%s' % (item.lower(), p.lower()))
227                   
228        return list
229   
230    # Old-style methods that are no longer used
231    def setParamWithToken(self, name, value, token, member): return NotImplemented
232    def getParamWithToken(self, name, token, member): return NotImplemented
233    def getParamListWithToken(self, token, member): return NotImplemented
234    def __add__(self, other): raise ValueError, "Model operation are no longer supported"
235    def __sub__(self, other): raise ValueError, "Model operation are no longer supported"
236    def __mul__(self, other): raise ValueError, "Model operation are no longer supported"
237    def __div__(self, other): raise ValueError, "Model operation are no longer supported"
238       
Note: See TracBrowser for help on using the repository browser.