source: sasview/DataLoader/manipulations.py @ 14cd91b1

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 14cd91b1 was 729bcf6, checked in by Jae Cho <jhjcho@…>, 14 years ago

for circular and sectot average, calculate qvalues and dq values more accurately.

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