source: sasview/src/sas/sascalc/dataloader/manipulations.py @ 9dda8cc

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.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 9dda8cc was 9dda8cc, checked in by Ricardo Ferraz Leal <ricleal@…>, 7 years ago

New style exceptions

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