source: sasview/DataLoader/manipulations.py @ 79ac6f8

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

working on documentation

  • Property mode set to 100644
File size: 34.6 KB
Line 
1
2#####################################################################
3#This software was developed by the University of Tennessee as part of the
4#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
5#project funded by the US National Science Foundation.
6#See the license text in license.txt
7#copyright 2008, University of Tennessee
8######################################################################
9
10"""
11    Data manipulations for 2D data sets.
12    Using the meta data information, various types of averaging
13    are performed in Q-space
14"""
15
16
17#TODO: copy the meta data from the 2D object to the resulting 1D object
18
19from data_info import plottable_2D, Data1D
20import math
21import numpy
22
23def get_q(dx, dy, det_dist, wavelength):
24    """
25    :param dx: x-distance from beam center [mm]
26    :param dy: y-distance from beam center [mm]
27   
28    :return: q-value at the given position
29    """
30    # Distance from beam center in the plane of detector
31    plane_dist = math.sqrt(dx*dx + dy*dy)
32    # Half of the scattering angle
33    theta      = 0.5*math.atan(plane_dist/det_dist)
34    return (4.0*math.pi/wavelength)*math.sin(theta)
35
36def get_q_compo(dx, dy, det_dist, wavelength,compo=None):
37    """
38    This reduces tiny error at very large q.
39    Implementation of this func is not started yet.<--ToDo
40    """
41    if dy==0:
42        if dx>=0:
43            angle_xy=0
44        else:
45            angle_xy=math.pi
46    else:
47        angle_xy=math.atan(dx/dy)
48       
49    if compo=="x":
50        out=get_q(dx, dy, det_dist, wavelength)*cos(angle_xy)
51    elif compo=="y":
52        out=get_q(dx, dy, det_dist, wavelength)*sin(angle_xy)
53    else:
54        out=get_q(dx, dy, det_dist, wavelength)
55    return out
56
57def flip_phi(phi):
58    """
59    Correct phi to within the 0 <= to <= 2pi range
60   
61    :return: phi in >=0 and <=2Pi
62    """
63    Pi = math.pi
64    if phi < 0:
65        phi_out = phi  + 2*Pi
66    elif phi > 2*Pi:
67        phi_out = phi  - 2*Pi
68    else:
69        phi_out = phi
70    return phi_out
71
72def reader2D_converter(data2d=None):
73    """
74    convert old 2d format opened by IhorReader or danse_reader to new Data2D format
75   
76    :param data2d: 2d array of Data2D object
77   
78    :return: 1d arrays of Data2D object
79   
80    """
81    if data2d.data==None or data2d.x_bins==None or data2d.y_bins==None:
82        raise ValueError,"Can't convert this data: data=None..."
83   
84    from DataLoader.data_info import Data2D
85
86    new_x = numpy.tile(data2d.x_bins, (len(data2d.y_bins),1))
87    new_y = numpy.tile(data2d.y_bins, (len(data2d.x_bins),1))
88    new_y = new_y.swapaxes(0,1)
89
90    new_data = data2d.data.flatten()
91    qx_data = new_x.flatten()
92    qy_data = new_y.flatten()
93    q_data = numpy.sqrt(qx_data*qx_data+qy_data*qy_data)
94    if data2d.err_data == None or numpy.any(data2d.err_data<=0): 
95        new_err_data = numpy.sqrt(numpy.abs(new_data))
96    else:
97        new_err_data = data2d.err_data.flatten()
98    mask    = numpy.ones(len(new_data), dtype = bool)
99
100    output = Data2D()
101    output = data2d
102    output.data = new_data
103    output.err_data = new_err_data
104    output.qx_data = qx_data
105    output.qy_data = qy_data
106    output.q_data = q_data
107    output.mask = mask
108
109    return output
110
111class _Slab(object):
112    """
113    Compute average I(Q) for a region of interest
114    """
115    def __init__(self, x_min=0.0, x_max=0.0, y_min=0.0, y_max=0.0, bin_width=0.001):
116        # Minimum Qx value [A-1]
117        self.x_min = x_min
118        # Maximum Qx value [A-1]
119        self.x_max = x_max
120        # Minimum Qy value [A-1]
121        self.y_min = y_min
122        # Maximum Qy value [A-1]
123        self.y_max = y_max
124        # Bin width (step size) [A-1]
125        self.bin_width = bin_width
126        # If True, I(|Q|) will be return, otherwise, negative q-values are allowed
127        self.fold = False
128       
129    def __call__(self, data2D): return NotImplemented
130       
131    def _avg(self, data2D, maj):
132        """
133        Compute average I(Q_maj) for a region of interest.
134        The major axis is defined as the axis of Q_maj.
135        The minor axis is the axis that we average over.
136         
137        :param data2D: Data2D object
138        :param maj_min: min value on the major axis
139       
140        :return: Data1D object
141        """
142        if len(data2D.detector) != 1:
143            raise RuntimeError, "_Slab._avg: invalid number of detectors: %g" % len(data2D.detector)
144       
145        # Get data
146        data = data2D.data[numpy.isfinite(data2D.data)]
147        q_data = data2D.q_data[numpy.isfinite(data2D.data)]
148        err_data = data2D.err_data[numpy.isfinite(data2D.data)]
149        qx_data = data2D.qx_data[numpy.isfinite(data2D.data)] 
150        qy_data = data2D.qy_data[numpy.isfinite(data2D.data)]
151             
152        # Build array of Q intervals
153        if maj=='x':
154            if self.fold: x_min = 0     
155            else:  x_min = self.x_min
156            nbins = int(math.ceil((self.x_max-x_min)/self.bin_width))
157            qbins = self.bin_width*numpy.arange(nbins)+ x_min
158        elif maj=='y':
159            if self.fold: y_min = 0     
160            else:  y_min = self.y_min
161            nbins = int(math.ceil((self.y_max-y_min)/self.bin_width))
162            qbins = self.bin_width*numpy.arange(nbins)+ y_min         
163        else:
164            raise RuntimeError, "_Slab._avg: unrecognized axis %s" % str(maj)
165                               
166        x  = numpy.zeros(nbins)
167        y  = numpy.zeros(nbins)
168        err_y = numpy.zeros(nbins)
169        y_counts = numpy.zeros(nbins)
170
171        # Average pixelsize in q space                                               
172        for npts in range(len(data)): 
173            # default frac                                               
174            frac_x = 0
175            frac_y = 0
176            # get ROI
177            if self.x_min <= qx_data[npts] and self.x_max > qx_data[npts]:
178                frac_x = 1
179            if self.y_min <= qy_data[npts] and self.y_max > qy_data[npts]:
180                frac_y = 1
181           
182            frac = frac_x * frac_y
183           
184            if frac == 0: continue
185
186            # binning: find axis of q
187            if maj=='x': 
188                q_value = qx_data[npts]
189                min = x_min
190            if maj=='y': 
191                q_value = qy_data[npts] 
192                min = y_min
193            if self.fold and q_value<0: q_value = -q_value   
194           
195            # bin
196            i_q = int(math.ceil((q_value-min)/self.bin_width)) - 1
197           
198            # skip outside of max bins
199            if i_q<0 or i_q>=nbins: continue
200           
201            # give it full weight
202            #frac = 1
203           
204            #TODO: find better definition of x[i_q] based on q_data
205            x[i_q]         = min +(i_q+1)*self.bin_width/2.0
206            y[i_q]         += frac * data[npts]
207           
208            if err_data == None or err_data[npts]==0.0:
209                if data[npts] <0: data[npts] = -data[npts]
210                err_y[i_q] += frac * frac * data[npts]
211            else:
212                err_y[i_q] += frac * frac * err_data[npts] * err_data[npts]
213            y_counts[i_q]  += frac
214               
215        # Average the sums       
216        for n in range(nbins):
217            err_y[n] = math.sqrt(err_y[n])
218         
219        err_y = err_y/y_counts
220        y    = y/y_counts
221       
222        idx = (numpy.isfinite(y)& numpy.isfinite(x)) 
223       
224        if not idx.any(): 
225            raise ValueError, "Average Error: No points inside ROI to average..." 
226        elif len(y[idx])!= nbins:
227            print "resulted",nbins- len(y[idx]),"empty bin(s) due to tight binning..."
228        return Data1D(x=x[idx], y=y[idx], dy=err_y[idx])
229       
230class SlabY(_Slab):
231    """
232    Compute average I(Qy) for a region of interest
233    """
234    def __call__(self, data2D):
235        """
236        Compute average I(Qy) for a region of interest
237         
238        :param data2D: Data2D object
239       
240        :return: Data1D object
241        """
242        return self._avg(data2D, 'y')
243       
244class SlabX(_Slab):
245    """
246    Compute average I(Qx) for a region of interest
247    """
248    def __call__(self, data2D):
249        """
250        Compute average I(Qx) for a region of interest
251         
252        :param data2D: Data2D object
253       
254        :return: Data1D object
255       
256        """
257        return self._avg(data2D, 'x') 
258       
259class Boxsum(object):
260    """
261    Perform the sum of counts in a 2D region of interest.
262    """
263    def __init__(self, x_min=0.0, x_max=0.0, y_min=0.0, y_max=0.0):
264        # Minimum Qx value [A-1]
265        self.x_min = x_min
266        # Maximum Qx value [A-1]
267        self.x_max = x_max
268        # Minimum Qy value [A-1]
269        self.y_min = y_min
270        # Maximum Qy value [A-1]
271        self.y_max = y_max
272
273    def __call__(self, data2D):
274        """
275        Perform the sum in the region of interest
276         
277        :param data2D: Data2D object
278       
279        :return: number of counts, error on number of counts
280       
281        """
282        y, err_y, y_counts = self._sum(data2D)
283       
284        # Average the sums
285        counts = 0 if y_counts==0 else y
286        error  = 0 if y_counts==0 else math.sqrt(err_y)
287       
288        return counts, error
289       
290    def _sum(self, data2D):
291        """
292        Perform the sum in the region of interest
293       
294        :param data2D: Data2D object
295       
296        :return: number of counts, error on number of counts, number of entries summed
297       
298        """
299        if len(data2D.detector) != 1:
300            raise RuntimeError, "Circular averaging: invalid number of detectors: %g" % len(data2D.detector)
301       
302        # Get data
303        data = data2D.data[numpy.isfinite(data2D.data)]
304        q_data = data2D.q_data[numpy.isfinite(data2D.data)]
305        err_data = data2D.err_data[numpy.isfinite(data2D.data)]
306        qx_data = data2D.qx_data[numpy.isfinite(data2D.data)] 
307        qy_data = data2D.qy_data[numpy.isfinite(data2D.data)]
308   
309        y  = 0.0
310        err_y = 0.0
311        y_counts = 0.0
312
313        # Average pixelsize in q space                                               
314        for npts in range(len(data)): 
315            # default frac                                               
316            frac_x = 0 
317            frac_y = 0                 
318           
319            # get min and max at each points
320            qx = qx_data[npts]
321            qy = qy_data[npts]
322           
323            # get the ROI
324            if self.x_min <= qx and self.x_max > qx:
325                frac_x = 1
326            if self.y_min <= qy and self.y_max > qy:
327                frac_y = 1
328               
329            #Find the fraction along each directions           
330            frac = frac_x * frac_y
331            if frac == 0: continue
332
333            y += frac * data[npts]
334            if err_data == None or err_data[npts]==0.0:
335                if data[npts] <0: data[npts] = -data[npts]
336                err_y += frac * frac * data[npts]
337            else:
338                err_y += frac * frac * err_data[npts] * err_data[npts]
339            y_counts += frac
340               
341        return y, err_y, y_counts
342
343
344     
345class Boxavg(Boxsum):
346    """
347    Perform the average of counts in a 2D region of interest.
348    """
349    def __init__(self, x_min=0.0, x_max=0.0, y_min=0.0, y_max=0.0):
350        super(Boxavg, self).__init__(x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max)
351
352    def __call__(self, data2D):
353        """
354        Perform the sum in the region of interest
355         
356        :param data2D: Data2D object
357       
358        :return: average counts, error on average counts
359       
360        """
361        y, err_y, y_counts = self._sum(data2D)
362       
363        # Average the sums
364        counts = 0 if y_counts==0 else y/y_counts
365        error  = 0 if y_counts==0 else math.sqrt(err_y)/y_counts
366       
367        return counts, error
368       
369def get_pixel_fraction_square(x, xmin, xmax):
370    """
371    Return the fraction of the length
372    from xmin to x.::
373   
374     
375           A            B
376       +-----------+---------+
377       xmin        x         xmax
378     
379    :param x: x-value
380    :param xmin: minimum x for the length considered
381    :param xmax: minimum x for the length considered
382   
383    :return: (x-xmin)/(xmax-xmin) when xmin < x < xmax
384   
385    """
386    if x<=xmin:
387        return 0.0
388    if x>xmin and x<xmax:
389        return (x-xmin)/(xmax-xmin)
390    else:
391        return 1.0
392
393
394class CircularAverage(object):
395    """
396    Perform circular averaging on 2D data
397   
398    The data returned is the distribution of counts
399    as a function of Q
400    """
401    def __init__(self, r_min=0.0, r_max=0.0, bin_width=0.0005):
402        # Minimum radius included in the average [A-1]
403        self.r_min = r_min
404        # Maximum radius included in the average [A-1]
405        self.r_max = r_max
406        # Bin width (step size) [A-1]
407        self.bin_width = bin_width
408
409    def __call__(self, data2D):
410        """
411        Perform circular averaging on the data
412       
413        :param data2D: Data2D object
414       
415        :return: Data1D object
416        """
417        # Get data
418        data = data2D.data[numpy.isfinite(data2D.data)]
419        q_data = data2D.q_data[numpy.isfinite(data2D.data)]
420        err_data = data2D.err_data[numpy.isfinite(data2D.data)]
421   
422        q_data_max = numpy.max(q_data)
423
424        if len(data2D.q_data) == None:
425            raise RuntimeError, "Circular averaging: invalid q_data: %g" % data2D.q_data
426
427        # Build array of Q intervals
428        nbins = int(math.ceil((self.r_max-self.r_min)/self.bin_width))
429        qbins = self.bin_width*numpy.arange(nbins)+self.r_min
430
431        x  = numpy.zeros(nbins)
432        y  = numpy.zeros(nbins)
433        err_y = numpy.zeros(nbins)
434        y_counts = numpy.zeros(nbins)
435
436        for npt in range(len(data)):         
437            frac = 0
438           
439            # q-value at the pixel (j,i)
440            q_value = q_data[npt]
441               
442            data_n = data[npt]               
443           
444            ## No need to calculate the frac when all data are within range
445            if self.r_min >= self.r_max:
446                raise ValueError, "Limit Error: min > max ???" 
447           
448            if self.r_min <= q_value and q_value <= self.r_max: frac = 1                       
449
450            if frac == 0: continue
451                       
452            i_q = int(math.floor((q_value-self.r_min)/self.bin_width))   
453
454            # Take care of the edge case at phi = 2pi.
455            if i_q == nbins: 
456                i_q = nbins -1 
457                                   
458            y[i_q] += frac * data_n
459
460            if err_data == None or err_data[npt]==0.0:
461                if data_n <0: data_n = -data_n
462                err_y[i_q] += frac * frac * data_n
463            else:
464                err_y[i_q] += frac * frac * err_data[npt] * err_data[npt]
465            y_counts[i_q]  += frac
466       
467        ## x should be the center value of each bins       
468        x = qbins+self.bin_width/2 
469       
470        # Average the sums       
471        for n in range(nbins):
472            if err_y[n] <0: err_y[n] = -err_y[n]
473            err_y[n] = math.sqrt(err_y[n])
474                     
475        err_y = err_y/y_counts
476        y    = y/y_counts
477        idx = (numpy.isfinite(y))&(numpy.isfinite(x)) 
478       
479        if not idx.any(): 
480            raise ValueError, "Average Error: No points inside ROI to average..." 
481        elif len(y[idx])!= nbins:
482            print "resulted",nbins- len(y[idx]),"empty bin(s) due to tight binning..."
483       
484        return Data1D(x=x[idx], y=y[idx], dy=err_y[idx])
485   
486
487class Ring(object):
488    """
489    Defines a ring on a 2D data set.
490    The ring is defined by r_min, r_max, and
491    the position of the center of the ring.
492   
493    The data returned is the distribution of counts
494    around the ring as a function of phi.
495   
496    Phi_min and phi_max should be defined between 0 and 2*pi
497    in anti-clockwise starting from the x- axis on the left-hand side
498    """
499    #Todo: remove center.
500    def __init__(self, r_min=0, r_max=0, center_x=0, center_y=0,nbins=20 ):
501        # Minimum radius
502        self.r_min = r_min
503        # Maximum radius
504        self.r_max = r_max
505        # Center of the ring in x
506        self.center_x = center_x
507        # Center of the ring in y
508        self.center_y = center_y
509        # Number of angular bins
510        self.nbins_phi = nbins
511       
512    def __call__(self, data2D):
513        """
514        Apply the ring to the data set.
515        Returns the angular distribution for a given q range
516       
517        :param data2D: Data2D object
518       
519        :return: Data1D object
520        """
521        if data2D.__class__.__name__ not in ["Data2D", "plottable_2D"]:
522            raise RuntimeError, "Ring averaging only take plottable_2D objects"
523       
524        Pi = math.pi
525 
526        # Get data
527        data = data2D.data[numpy.isfinite(data2D.data)]
528        q_data = data2D.q_data[numpy.isfinite(data2D.data)]
529        err_data = data2D.err_data[numpy.isfinite(data2D.data)]
530        qx_data = data2D.qx_data[numpy.isfinite(data2D.data)] 
531        qy_data = data2D.qy_data[numpy.isfinite(data2D.data)]
532       
533        q_data_max = numpy.max(q_data)
534       
535        # Set space for 1d outputs
536        phi_bins   = numpy.zeros(self.nbins_phi)
537        phi_counts = numpy.zeros(self.nbins_phi)
538        phi_values = numpy.zeros(self.nbins_phi)
539        phi_err    = numpy.zeros(self.nbins_phi)
540       
541        for npt in range(len(data)):         
542            frac = 0
543           
544            # q-value at the point (npt)
545            q_value = q_data[npt]
546               
547            data_n = data[npt]   
548                       
549            # phi-value at the point (npt)
550            phi_value=math.atan2(qy_data[npt],qx_data[npt])+Pi
551           
552            if self.r_min <= q_value and q_value <= self.r_max: frac = 1                       
553
554            if frac == 0: continue
555           
556            # binning           
557            i_phi = int(math.floor((self.nbins_phi)*phi_value/(2*Pi)))
558           
559            # Take care of the edge case at phi = 2pi.
560            if i_phi == self.nbins_phi: 
561                i_phi =  self.nbins_phi -1 
562                                             
563            phi_bins[i_phi] += frac * data[npt]
564           
565            if err_data == None or err_data[npt] ==0.0:
566                if data_n <0: data_n = -data_n
567                phi_err[i_phi] += frac * frac * math.fabs(data_n)
568            else:
569                phi_err[i_phi] += frac * frac *err_data[npt]*err_data[npt]
570            phi_counts[i_phi] += frac
571                         
572        for i in range(self.nbins_phi):
573            phi_bins[i] = phi_bins[i] / phi_counts[i]
574            phi_err[i] = math.sqrt(phi_err[i]) / phi_counts[i]
575            phi_values[i] = 2.0*math.pi/self.nbins_phi*(1.0*i + 0.5)
576           
577        idx = (numpy.isfinite(phi_bins)) 
578
579        if not idx.any(): 
580            raise ValueError, "Average Error: No points inside ROI to average..." 
581        elif len(phi_bins[idx])!= self.nbins_phi:
582            print "resulted",self.nbins_phi- len(phi_bins[idx]),"empty bin(s) due to tight binning..."
583        return Data1D(x=phi_values[idx], y=phi_bins[idx], dy=phi_err[idx])
584   
585def get_pixel_fraction(qmax, q_00, q_01, q_10, q_11):
586    """
587    Returns the fraction of the pixel defined by
588    the four corners (q_00, q_01, q_10, q_11) that
589    has q < qmax.::
590   
591                q_01                q_11
592        y=1         +--------------+
593                    |              |
594                    |              |
595                    |              |
596        y=0         +--------------+
597                q_00                q_10
598       
599                    x=0            x=1
600   
601    """
602   
603    # y side for x = minx
604    x_0 = get_intercept(qmax, q_00, q_01)
605    # y side for x = maxx
606    x_1 = get_intercept(qmax, q_10, q_11)
607   
608    # x side for y = miny
609    y_0 = get_intercept(qmax, q_00, q_10)
610    # x side for y = maxy
611    y_1 = get_intercept(qmax, q_01, q_11)
612   
613    # surface fraction for a 1x1 pixel
614    frac_max = 0
615   
616    if x_0 and x_1:
617        frac_max = (x_0+x_1)/2.0
618   
619    elif y_0 and y_1:
620        frac_max = (y_0+y_1)/2.0
621   
622    elif x_0 and y_0:
623        if q_00 < q_10:
624            frac_max = x_0*y_0/2.0
625        else:
626            frac_max = 1.0-x_0*y_0/2.0
627   
628    elif x_0 and y_1:
629        if q_00 < q_10:
630            frac_max = x_0*y_1/2.0
631        else:
632            frac_max = 1.0-x_0*y_1/2.0
633   
634    elif x_1 and y_0:
635        if q_00 > q_10:
636            frac_max = x_1*y_0/2.0
637        else:
638            frac_max = 1.0-x_1*y_0/2.0
639   
640    elif x_1 and y_1:
641        if q_00 < q_10:
642            frac_max = 1.0 - (1.0-x_1)*(1.0-y_1)/2.0
643        else:
644            frac_max = (1.0-x_1)*(1.0-y_1)/2.0
645           
646    # If we make it here, there is no intercept between
647    # this pixel and the constant-q ring. We only need
648    # to know if we have to include it or exclude it.
649    elif (q_00+q_01+q_10+q_11)/4.0 < qmax:
650        frac_max = 1.0
651
652    return frac_max
653             
654def get_intercept(q, q_0, q_1):
655    """
656    Returns the fraction of the side at which the
657    q-value intercept the pixel, None otherwise.
658    The values returned is the fraction ON THE SIDE
659    OF THE LOWEST Q. ::
660   
661   
662            A           B   
663        +-----------+--------+    <--- pixel size
664        0                    1     
665        Q_0 -------- Q ----- Q_1   <--- equivalent Q range
666        if Q_1 > Q_0, A is returned
667        if Q_1 < Q_0, B is returned
668        if Q is outside the range of [Q_0, Q_1], None is returned
669         
670    """
671    if q_1 > q_0:
672        if (q > q_0 and q <= q_1):
673            return (q-q_0)/(q_1 - q_0)   
674    else:
675        if (q > q_1 and q <= q_0):
676            return (q-q_1)/(q_0 - q_1)
677    return None
678     
679class _Sector:
680    """
681    Defines a sector region on a 2D data set.
682    The sector is defined by r_min, r_max, phi_min, phi_max,
683    and the position of the center of the ring
684    where phi_min and phi_max are defined by the right and left lines wrt central line
685    and phi_max could be less than phi_min.
686   
687    Phi is defined between 0 and 2*pi in anti-clockwise starting from the x- axis on the left-hand side
688    """
689    def __init__(self, r_min, r_max, phi_min=0, phi_max=2*math.pi,nbins=20):
690        self.r_min = r_min
691        self.r_max = r_max
692        self.phi_min = phi_min
693        self.phi_max = phi_max
694        self.nbins = nbins
695       
696   
697    def _agv(self, data2D, run='phi'):
698        """
699        Perform sector averaging.
700       
701        :param data2D: Data2D object
702        :param run:  define the varying parameter ('phi' , 'q' , or 'q2')
703       
704        :return: Data1D object
705        """
706        if data2D.__class__.__name__ not in ["Data2D", "plottable_2D"]:
707            raise RuntimeError, "Ring averaging only take plottable_2D objects"
708        Pi = math.pi
709
710        # Get the all data & info
711        data = data2D.data[numpy.isfinite(data2D.data)]
712        q_data = data2D.q_data[numpy.isfinite(data2D.data)]
713        err_data = data2D.err_data[numpy.isfinite(data2D.data)]
714        qx_data = data2D.qx_data[numpy.isfinite(data2D.data)] 
715        qy_data = data2D.qy_data[numpy.isfinite(data2D.data)]
716       
717        #set space for 1d outputs
718        x        = numpy.zeros(self.nbins)
719        y        = numpy.zeros(self.nbins)
720        y_err    = numpy.zeros(self.nbins)         
721        y_counts = numpy.zeros(self.nbins)
722                     
723        # Get the min and max into the region: 0 <= phi < 2Pi
724        phi_min = flip_phi(self.phi_min)
725        phi_max = flip_phi(self.phi_max)
726       
727        q_data_max = numpy.max(q_data)
728                     
729        for n in range(len(data)):     
730                frac = 0
731               
732                # q-value at the pixel (j,i)
733                q_value = q_data[n]
734               
735   
736                data_n = data[n]
737               
738                # Is pixel within range?
739                is_in = False
740               
741                # phi-value of the pixel (j,i)
742                phi_value=math.atan2(qy_data[n],qx_data[n])+Pi
743               
744                ## No need to calculate the frac when all data are within range
745                if self.r_min <= q_value and q_value <= self.r_max: frac = 1                       
746
747                if frac == 0: continue
748 
749                #In case of two ROIs (symmetric major and minor regions)(for 'q2')
750                if run.lower()=='q2':
751                    ## For minor sector wing
752                    # Calculate the minor wing phis
753                    phi_min_minor = flip_phi(phi_min-Pi)
754                    phi_max_minor = flip_phi(phi_max-Pi)
755                    # Check if phis of the minor ring is within 0 to 2pi
756                    if phi_min_minor > phi_max_minor:
757                        is_in = (phi_value > phi_min_minor or phi_value < phi_max_minor)
758                    else:
759                        is_in = (phi_value > phi_min_minor and phi_value < phi_max_minor)
760
761                #For all cases(i.e.,for 'q', 'q2', and 'phi')
762                #Find pixels within ROI 
763                if phi_min > phi_max: 
764                    is_in = is_in or (phi_value > phi_min or phi_value < phi_max)         
765                else:
766                    is_in = is_in or (phi_value>= phi_min  and  phi_value <phi_max)
767               
768                if not is_in: frac = 0                                                       
769                if frac == 0: continue
770               
771                # Check which type of averaging we need
772                if run.lower()=='phi': 
773                    i_bin    = int(math.floor((self.nbins)*(phi_value-self.phi_min)\
774                                              /(self.phi_max-self.phi_min)))
775                else:
776                    i_bin = int(math.floor((self.nbins)*(q_value-self.r_min)/(self.r_max-self.r_min)))
777
778                # Take care of the edge case at phi = 2pi.
779                if i_bin == self.nbins: 
780                    i_bin =  self.nbins -1
781                   
782                ## Get the total y         
783                y[i_bin] += frac * data_n
784
785                if err_data == None or err_data[n] ==0.0:
786                    if data_n<0: data_n= -data_n
787                    y_err[i_bin] += frac * frac * data_n
788                else:
789                    y_err[i_bin] += frac * frac * err_data[n]*err_data[n]
790                y_counts[i_bin] += frac
791       
792        # Organize the results
793        for i in range(self.nbins):
794            y[i] = y[i] / y_counts[i]
795            y_err[i] = math.sqrt(y_err[i]) / y_counts[i]
796           
797            # The type of averaging: phi,q2, or q
798            # Calculate x[i]should be at the center of the bin
799            if run.lower()=='phi':               
800                x[i] = (self.phi_max-self.phi_min)/self.nbins*(1.0*i + 0.5)+self.phi_min
801            else:
802                x[i] = (self.r_max-self.r_min)/self.nbins*(1.0*i + 0.5)+self.r_min
803               
804        idx = (numpy.isfinite(y)& numpy.isfinite(y_err))
805       
806        if not idx.any(): 
807            raise ValueError, "Average Error: No points inside sector of ROI to average..." 
808        elif len(y[idx])!= self.nbins:
809            print "resulted",self.nbins- len(y[idx]),"empty bin(s) due to tight binning..."
810        return Data1D(x=x[idx], y=y[idx], dy=y_err[idx])
811               
812class SectorPhi(_Sector):
813    """
814    Sector average as a function of phi.
815    I(phi) is return and the data is averaged over Q.
816   
817    A sector is defined by r_min, r_max, phi_min, phi_max.
818    The number of bin in phi also has to be defined.
819    """
820    def __call__(self, data2D):
821        """
822        Perform sector average and return I(phi).
823       
824        :param data2D: Data2D object
825        :return: Data1D object
826        """
827
828        return self._agv(data2D, 'phi')
829   
830class SectorQ(_Sector):
831    """
832    Sector average as a function of Q for both symatric wings.
833    I(Q) is return and the data is averaged over phi.
834   
835    A sector is defined by r_min, r_max, phi_min, phi_max.
836    r_min, r_max, phi_min, phi_max >0. 
837    The number of bin in Q also has to be defined.
838    """
839    def __call__(self, data2D):
840        """
841        Perform sector average and return I(Q).
842       
843        :param data2D: Data2D object
844       
845        :return: Data1D object
846        """
847        return self._agv(data2D, 'q2')
848
849class Ringcut(object):
850    """
851    Defines a ring on a 2D data set.
852    The ring is defined by r_min, r_max, and
853    the position of the center of the ring.
854   
855    The data returned is the region inside the ring
856   
857    Phi_min and phi_max should be defined between 0 and 2*pi
858    in anti-clockwise starting from the x- axis on the left-hand side
859    """
860    def __init__(self, r_min=0, r_max=0, center_x=0, center_y=0 ):
861        # Minimum radius
862        self.r_min = r_min
863        # Maximum radius
864        self.r_max = r_max
865        # Center of the ring in x
866        self.center_x = center_x
867        # Center of the ring in y
868        self.center_y = center_y
869
870       
871    def __call__(self, data2D):
872        """
873        Apply the ring to the data set.
874        Returns the angular distribution for a given q range
875       
876        :param data2D: Data2D object
877       
878        :return: index array in the range
879        """
880        if data2D.__class__.__name__ not in ["Data2D", "plottable_2D"]:
881            raise RuntimeError, "Ring cut only take plottable_2D objects"
882
883        # Get data
884        qx_data = data2D.qx_data
885        qy_data = data2D.qy_data
886        mask = data2D.mask
887        q_data = numpy.sqrt(qx_data*qx_data+qy_data*qy_data)
888        #q_data_max = numpy.max(q_data)
889
890        # check whether or not the data point is inside ROI
891        out = (self.r_min <= q_data) & (self.r_max >= q_data)
892
893        return (out)
894       
895
896class Boxcut(object):
897    """
898    Find a rectangular 2D region of interest.
899    """
900    def __init__(self, x_min=0.0, x_max=0.0, y_min=0.0, y_max=0.0):
901        # Minimum Qx value [A-1]
902        self.x_min = x_min
903        # Maximum Qx value [A-1]
904        self.x_max = x_max
905        # Minimum Qy value [A-1]
906        self.y_min = y_min
907        # Maximum Qy value [A-1]
908        self.y_max = y_max
909
910    def __call__(self, data2D):
911        """
912       Find a rectangular 2D region of interest.
913         
914       :param data2D: Data2D object
915       :return: mask, 1d array (len = len(data))
916           with Trues where the data points are inside ROI, otherwise False
917        """
918        mask = self._find(data2D)
919       
920        return mask
921       
922    def _find(self, data2D):
923        """
924        Find a rectangular 2D region of interest.
925       
926        :param data2D: Data2D object
927       
928        :return: out, 1d array (length = len(data))
929           with Trues where the data points are inside ROI, otherwise Falses
930        """
931        if data2D.__class__.__name__ not in ["Data2D", "plottable_2D"]:
932            raise RuntimeError, "Boxcut take only plottable_2D objects"
933        # Get qx_ and qy_data
934        qx_data = data2D.qx_data
935        qy_data = data2D.qy_data
936        mask = data2D.mask
937       
938        # check whether or not the data point is inside ROI
939        outx = (self.x_min <= qx_data) & (self.x_max > qx_data)
940        outy = (self.y_min <= qy_data) & (self.y_max > qy_data)
941
942        return (outx & outy)
943
944class Sectorcut(object):
945    """
946    Defines a sector (major + minor) region on a 2D data set.
947    The sector is defined by phi_min, phi_max,
948    where phi_min and phi_max are defined by the right and left lines wrt central line.
949   
950    Phi_min and phi_max are given in units of radian
951    and (phi_max-phi_min) should not be larger than pi
952    """
953    def __init__(self,phi_min=0, phi_max=math.pi):
954        self.phi_min = phi_min
955        self.phi_max = phi_max
956             
957    def __call__(self, data2D):
958        """
959        Find a rectangular 2D region of interest.
960       
961        :param data2D: Data2D object
962       
963        :return: mask, 1d array (len = len(data))
964       
965        with Trues where the data points are inside ROI, otherwise False
966        """
967        mask = self._find(data2D)
968       
969        return mask
970       
971    def _find(self, data2D):
972        """
973        Find a rectangular 2D region of interest.
974       
975        :param data2D: Data2D object
976       
977        :return: out, 1d array (length = len(data))
978       
979        with Trues where the data points are inside ROI, otherwise Falses
980        """
981        if data2D.__class__.__name__ not in ["Data2D", "plottable_2D"]:
982            raise RuntimeError, "Sectorcut take only plottable_2D objects" 
983        Pi = math.pi
984        # Get data
985        qx_data = data2D.qx_data
986        qy_data = data2D.qy_data       
987        phi_data = numpy.zeros(len(qx_data))
988
989        # get phi from data
990        phi_data = numpy.arctan2(qy_data, qx_data)
991       
992        # Get the min and max into the region: -pi <= phi < Pi
993        phi_min_major = flip_phi(self.phi_min+Pi)-Pi
994        phi_max_major = flip_phi(self.phi_max+Pi)-Pi 
995        # check for major sector
996        if phi_min_major > phi_max_major:
997            out_major = (phi_min_major <= phi_data) + (phi_max_major > phi_data)
998        else:
999            out_major = (phi_min_major <= phi_data) & (phi_max_major > phi_data)
1000         
1001        # minor sector
1002        # Get the min and max into the region: -pi <= phi < Pi
1003        phi_min_minor = flip_phi(self.phi_min)-Pi
1004        phi_max_minor = flip_phi(self.phi_max)-Pi
1005             
1006        # check for minor sector
1007        if phi_min_minor > phi_max_minor:
1008            out_minor= (phi_min_minor <= phi_data) + (phi_max_minor>= phi_data) 
1009        else:
1010            out_minor = (phi_min_minor <= phi_data) & (phi_max_minor >= phi_data) 
1011        out = out_major + out_minor
1012       
1013        return out
1014
1015if __name__ == "__main__": 
1016
1017    from loader import Loader
1018   
1019
1020    d = Loader().load('test/MAR07232_rest.ASC')
1021    #d = Loader().load('test/MP_New.sans')
1022
1023   
1024    r = SectorQ(r_min=.000001, r_max=.01, phi_min=0.0, phi_max=2*math.pi)
1025    o = r(d)
1026   
1027    s = Ring(r_min=.000001, r_max=.01) 
1028    p = s(d)
1029   
1030    for i in range(len(o.x)):
1031        print o.x[i], o.y[i], o.dy[i]
1032   
1033 
1034   
Note: See TracBrowser for help on using the repository browser.