source: sasview/DataLoader/smearing_2d.py @ cacbd7d

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 cacbd7d was 0997158f, checked in by Gervaise Alina <gervyh@…>, 15 years ago

working on documentation

  • Property mode set to 100644
File size: 9.7 KB
Line 
1#####################################################################
2#This software was developed by the University of Tennessee as part of the
3#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
4#project funded by the US National Science Foundation.
5#See the license text in license.txt
6#copyright 2008, University of Tennessee
7######################################################################
8
9## TODO: Need test,and check Gaussian averaging
10import numpy, math,time
11## Singular point
12SIGMA_ZERO = 1.0e-010
13## Limit of how many sigmas to be covered for the Gaussian smearing
14# default: 2.5 to cover 98.7% of Gaussian
15LIMIT = 2.5
16## Defaults
17R_BIN = {'Xhigh':10.0, 'High':5.0,'Med':5.0,'Low':3.0}
18PHI_BIN ={'Xhigh':20.0,'High':12.0,'Med':6.0,'Low':4.0}   
19
20class Smearer2D:
21    """
22    Gaussian Q smearing class for SANS 2d data
23    """
24     
25    def __init__(self, data=None, model=None, index=None, 
26                 limit=LIMIT, accuracy='Low'):
27        """
28        Assumption: equally spaced bins in dq_r, dq_phi space.
29       
30        :param data: 2d data used to set the smearing parameters
31        :param model: model function
32        :param index: 1d array with len(data) to define the range of the calculation: elements are given as True or False
33        :param nr: number of bins in dq_r-axis
34        :param nphi: number of bins in dq_phi-axis
35        """
36        ## data
37        self.data = data
38        ## model
39        self.model = model
40        ## Accuracy: Higher stands for more sampling points in both directions of r and phi.
41        self.accuracy = accuracy
42        ## number of bins in r axis for over-sampling
43        self.nr = R_BIN
44        ## number of bins in phi axis for over-sampling
45        self.nphi = PHI_BIN
46        ## maximum nsigmas
47        self.limit = limit
48        self.index = index
49        self.smearer = True
50       
51       
52    def get_data(self):   
53        """
54        get qx_data, qy_data, dqx_data,dqy_data,and calculate phi_data=arctan(qx_data/qy_data)
55        """
56        if self.data == None or self.data.__class__.__name__ == 'Data1D':
57            return None
58        if self.data.dqx_data == None or self.data.dqy_data == None:
59            return None
60        self.qx_data = self.data.qx_data[self.index]
61        self.qy_data = self.data.qy_data[self.index]
62        self.dqx_data = self.data.dqx_data[self.index]
63        self.dqy_data = self.data.dqy_data[self.index]
64        self.phi_data = numpy.arctan(self.qx_data/self.qy_data)
65        ## Remove singular points if exists
66        self.dqx_data[self.dqx_data<SIGMA_ZERO]=SIGMA_ZERO
67        self.dqy_data[self.dqy_data<SIGMA_ZERO]=SIGMA_ZERO
68        return True
69   
70    def set_accuracy(self, accuracy='Low'):   
71        """
72        Set accuracy.
73       
74        :param accuracy:  string
75        """
76        self.accuracy = accuracy
77
78    def set_smearer(self, smearer=True):
79        """
80        Set whether or not smearer will be used
81       
82        :param smearer: smear object
83       
84        """
85        self.smearer = smearer
86       
87    def set_data(self, data=None):   
88        """
89        Set data.
90       
91        :param data: DataLoader.Data_info type
92        """
93        self.data = data
94 
95           
96    def set_model(self, model=None):   
97        """
98        Set model.
99       
100        :param model: sans.models instance
101        """
102        self.model = model 
103           
104    def set_index(self, index=None):   
105        """
106        Set index.
107       
108        :param index: 1d arrays
109        """
110        self.index = index       
111   
112    def get_value(self):
113        """
114        Over sampling of r_nbins times phi_nbins, calculate Gaussian weights, then find smeared intensity
115        For the default values, this is equivalent (but by using numpy array
116        the speed optimized by a factor of ten)to the following: ::
117       
118       
119            Remove the singular points if exists
120            self.dqx_data[self.dqx_data==0]=SIGMA_ZERO
121            self.dqy_data[self.dqy_data==0]=SIGMA_ZERO
122           
123            for phi in range(0,4):
124                for r in range(0,5):
125                    n = (phi)*5+(r)
126                    r = r+0.25
127                    dphi = phi*2.0*math.pi/4.0 + numpy.arctan(self.qy_data[index_model]/self.dqy_data[index_model]/self.qx_data[index_model]*/self.dqx_data[index_model])
128                    dq = r*sqrt( self.dqx_data[index_model]*self.dqx_data[index_model] \
129                        + self.dqy_data[index_model]*self.dqy_data[index_model] )
130                    #integrant of exp(-0.5*r*r) r dr at each bins : The integration may not need.
131                    weight_res[n] = e^{(-0.5*((r-0.25)*(r-0.25)))}- e^{(-0.5*((r-0.25)*(r-0.25)))}
132                    #if phi != 0 and r != 0:
133                    qx_res = numpy.append(qx_res,self.qx_data[index_model]+ dq * cos(dphi))
134                    qy_res = numpy.append(qy_res,self.qy_data[index_model]+ dq * sin(dphi))
135                   
136        Then compute I(qx_res,qy_res) and do weighted averaging.
137       
138        """
139        valid = self.get_data()
140        if valid == None:
141            return valid
142        if self.smearer == False:
143            return self.model.evalDistribution([self.qx_data,self.qy_data]) 
144        st = time.time()
145        nr = self.nr[self.accuracy]
146        nphi = self.nphi[self.accuracy]
147
148        # data length in the range of self.index
149        len_data = len(self.qx_data)
150        len_datay = len(self.qy_data)
151
152        # Number of bins in the dqr direction (polar coordinate of dqx and dqy)
153        bin_size = self.limit/nr
154        # Total number of bins = # of bins in dq_r-direction times # of bins in dq_phi-direction
155        n_bins = nr * nphi
156        # Mean values of dqr at each bins ,starting from the half of bin size
157        r = bin_size/2.0+numpy.arange(nr)*bin_size
158        # mean values of qphi at each bines
159        phi = numpy.arange(nphi)
160        dphi = phi*2.0*math.pi/nphi
161        dphi = dphi.repeat(nr)
162        ## Transform to polar coordinate, and set dphi at each data points ; 1d array
163        dphi = dphi.repeat(len_data)+numpy.arctan(self.qy_data*self.dqx_data/self.qx_data/self.dqy_data).repeat(n_bins).reshape(len_data,n_bins).transpose().flatten()
164        ## Find Gaussian weight for each dq bins: The weight depends only on r-direction (The integration may not need)
165        weight_res = numpy.exp(-0.5*((r-bin_size/2.0)*(r-bin_size/2.0)))-numpy.exp(-0.5*((r+bin_size/2.0)*(r+bin_size/2.0)))
166        weight_res = weight_res.repeat(nphi).reshape(nr,nphi).transpose().flatten()
167       
168        ## Set dr for all dq bins for averaging
169        dr = r.repeat(nphi).reshape(nr,nphi).transpose().flatten()
170        ## Set dqr for all data points
171        dqx = numpy.outer(dr,self.dqx_data).flatten()
172        dqy = numpy.outer(dr,self.dqy_data).flatten()
173        qx = self.qx_data.repeat(n_bins).reshape(len_data,n_bins).transpose().flatten()
174        qy = self.qy_data.repeat(n_bins).reshape(len_data,n_bins).transpose().flatten()
175
176       
177        ## Over-sampled qx_data and qy_data.
178        qx_res = qx+ dqx*numpy.cos(dphi)
179        qy_res = qy+ dqy*numpy.sin(dphi)
180       
181        ## Evaluate all points
182        val = self.model.evalDistribution([qx_res,qy_res]) 
183
184        ## Reshape into 2d array to use numpy weighted averaging
185        value_res= val.reshape(n_bins,len(self.qx_data))
186
187        ## Averaging with Gaussian weighting: normalization included.
188        value =numpy.average(value_res,axis=0,weights=weight_res)
189
190        ## Return the smeared values in the range of self.index
191        return value
192   
193if __name__ == '__main__':
194    ## Test w/ 2D linear function
195    x = 0.001*numpy.arange(1,11)
196    dx = numpy.ones(len(x))*0.001
197    y = 0.001*numpy.arange(1,11)
198    dy = numpy.ones(len(x))*0.001
199    z = numpy.ones(10)
200    dz = numpy.sqrt(z)
201   
202    from DataLoader import Data2D
203    #for i in range(10): print i, 0.001 + i*0.008/9.0
204    #for i in range(100): print i, int(math.floor( (i/ (100/9.0)) ))
205    out = Data2D()
206    out.data = z
207    out.qx_data = x
208    out.qy_data = y
209    out.dqx_data = dx
210    out.dqy_data = dy
211    index = numpy.ones(len(x), dtype = bool)
212    out.mask = index
213    from sans.models.LineModel import LineModel
214    model = LineModel()
215    model.setParam("A", 0)
216
217    smear = Smearer2D(out,model,index)
218    #smear.set_accuracy('Xhigh')
219    value = smear.get_value()
220    ## All data are ones, so the smeared should also be ones.
221    print "Data length =",len(value)
222    print " 2D linear function, I = 0 + 1*qx*qy"
223    print " Gaussian weighted averaging on a 2D linear function will provides the results same as without the averaging."
224    print "qx_data", "qy_data", "I_nonsmear", "I_smeared"
225    for ind in range(len(value)):
226        print x[ind],y[ind],model.evalDistribution([x,y])[ind], value[ind]
227 
228"""   
229if __name__ == '__main__':
230    ## Another Test w/ constant function
231    x = 0.001*numpy.arange(1,11)
232    dx = numpy.ones(len(x))*0.001
233    y = 0.001*numpy.arange(1,11)
234    dy = numpy.ones(len(x))*0.001
235    z = numpy.ones(10)
236    dz = numpy.sqrt(z)
237   
238    from DataLoader import Data2D
239    #for i in range(10): print i, 0.001 + i*0.008/9.0
240    #for i in range(100): print i, int(math.floor( (i/ (100/9.0)) ))
241    out = Data2D()
242    out.data = z
243    out.qx_data = x
244    out.qy_data = y
245    out.dqx_data = dx
246    out.dqy_data = dy
247    index = numpy.ones(len(x), dtype = bool)
248    out.mask = index
249    from sans.models.Constant import Constant
250    model = Constant()
251
252    value = Smearer2D(out,model,index).get_value()
253    ## All data are ones, so the smeared values should also be ones.
254    print "Data length =",len(value), ", Data=",value
255"""   
Note: See TracBrowser for help on using the repository browser.