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

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 fb071900 was 3080527, checked in by Jae Cho <jhjcho@…>, 15 years ago

changed classtemplate for 2d evaluation from matrix form to 1d array form

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