|
| 1 | +from numpy cimport * |
| 2 | +import numpy as np |
| 3 | + |
| 4 | +cdef class Reducer: |
| 5 | + ''' |
| 6 | + Performs generic reduction operation on a C or Fortran-contiguous ndarray |
| 7 | + while avoiding ndarray construction overhead |
| 8 | + ''' |
| 9 | + cdef: |
| 10 | + Py_ssize_t increment, chunksize, nresults |
| 11 | + object arr, dummy, f |
| 12 | + |
| 13 | + def __init__(self, object arr, object f, axis=1, dummy=None): |
| 14 | + n, k = arr.shape |
| 15 | + |
| 16 | + if axis == 0: |
| 17 | + if not arr.flags.f_contiguous: |
| 18 | + arr = arr.copy('F') |
| 19 | + |
| 20 | + self.nresults = k |
| 21 | + self.chunksize = n |
| 22 | + self.increment = n * arr.dtype.itemsize |
| 23 | + else: |
| 24 | + if not arr.flags.c_contiguous: |
| 25 | + arr = arr.copy('C') |
| 26 | + |
| 27 | + self.nresults = n |
| 28 | + self.chunksize = k |
| 29 | + self.increment = k * arr.dtype.itemsize |
| 30 | + |
| 31 | + self.f = f |
| 32 | + self.arr = arr |
| 33 | + self.dummy = self._check_dummy(dummy) |
| 34 | + |
| 35 | + def _check_dummy(self, dummy=None): |
| 36 | + if dummy is None: |
| 37 | + dummy = np.empty(self.chunksize, dtype=self.arr.dtype) |
| 38 | + else: |
| 39 | + if dummy.dtype != self.arr.dtype: |
| 40 | + raise ValueError('Dummy array must be same dtype') |
| 41 | + if len(dummy) != self.chunksize: |
| 42 | + raise ValueError('Dummy array must be length %d' % |
| 43 | + self.chunksize) |
| 44 | + |
| 45 | + return dummy |
| 46 | + |
| 47 | + def get_result(self): |
| 48 | + cdef: |
| 49 | + char* dummy_buf |
| 50 | + ndarray arr, result, chunk |
| 51 | + Py_ssize_t i |
| 52 | + flatiter it |
| 53 | + |
| 54 | + arr = self.arr |
| 55 | + chunk = self.dummy |
| 56 | + |
| 57 | + result = np.empty(self.nresults, dtype=self.arr.dtype) |
| 58 | + it = <flatiter> PyArray_IterNew(result) |
| 59 | + |
| 60 | + test = self.f(self.chunk) |
| 61 | + try: |
| 62 | + result[0] = test |
| 63 | + except Exception: |
| 64 | + raise ValueError('function does not reduce') |
| 65 | + |
| 66 | + dummy_buf = chunk.data |
| 67 | + chunk.data = arr.data |
| 68 | + |
| 69 | + try: |
| 70 | + for i in range(self.nresults): |
| 71 | + PyArray_SETITEM(result, PyArray_ITER_DATA(it), |
| 72 | + self.f(self.dummy)) |
| 73 | + chunk.data = chunk.data + self.increment |
| 74 | + PyArray_ITER_NEXT(it) |
| 75 | + finally: |
| 76 | + # so we don't free the wrong memory |
| 77 | + chunk.data = dummy_buf |
| 78 | + |
| 79 | + return result |
| 80 | + |
| 81 | +def reduce(arr, f, axis=0, dummy=None): |
| 82 | + reducer = Reducer(arr, f, axis=axis, dummy=dummy) |
| 83 | + return reducer.get_result() |
0 commit comments