This is an archival dump of old wiki content --- see scipy.org for current material.
Please see http://scipy-cookbook.readthedocs.org/

Examples showing how to rebin data to produce a smaller or bigger array without (and with) using interpolation.

Example 1

Here we deal with the simplest case where any desired new shape is valid and no interpolation is done on the data to determine the new values.

   1 def rebin( a, newshape ):
   2         '''Rebin an array to a new shape.
   3         '''
   4         assert len(a.shape) == len(newshape)
   5 
   6         slices = [ slice(0,old, float(old)/new) for old,new in zip(a.shape,newshape) ]
   7         coordinates = mgrid[slices]
   8         indices = coordinates.astype('i')   #choose the biggest smaller integer index
   9         return a[tuple(indices)]

If we were only interested in reducing the sizes by some integer factor then we could use:

   1 def rebin_factor( a, newshape ):
   2         '''Rebin an array to a new shape.
   3         newshape must be a factor of a.shape.
   4         '''
   5         assert len(a.shape) == len(newshape)
   6         assert not sometrue(mod( a.shape, newshape ))
   7 
   8         slices = [ slice(None,None, old/new) for old,new in zip(a.shape,newshape) ]
   9         return a[slices]

Example 2

Here is an other way to deal with the reducing case for ndarrays. This acts identically to IDL's rebin command where all values in the original array are summed and divided amongst the entries in the new array. As in IDL, the new shape must be a factor of the old one. The ugly 'evList trick' builds and executes a python command of the form

a.reshape(args[0],factor[0],).sum(1)/factor[0] a.reshape(args[0],factor[0],args[1],factor[1],).sum(1).sum(2)/factor[0]/factor[1]

etc. This general form is extended to cover the number of required dimensions.

   1 def rebin(a, *args):
   2     '''rebin ndarray data into a smaller ndarray of the same rank whose dimensions
   3     are factors of the original dimensions. eg. An array with 6 columns and 4 rows
   4     can be reduced to have 6,3,2 or 1 columns and 4,2 or 1 rows.
   5     example usages:
   6     >>> a=rand(6,4); b=rebin(a,3,2)
   7     >>> a=rand(6); b=rebin(a,2)
   8     '''
   9     shape = a.shape
  10     lenShape = len(shape)
  11     factor = asarray(shape)/asarray(args)
  12     evList = ['a.reshape('] + \
  13              ['args[%d],factor[%d],'%(i,i) for i in range(lenShape)] + \
  14              [')'] + ['.sum(%d)'%(i+1) for i in range(lenShape)] + \
  15              ['/factor[%d]'%i for i in range(lenShape)]
  16     print ''.join(evList)
  17     return eval(''.join(evList))

The above code returns an array of the same type as the input array. If the input is an integer array, the output values will be rounded down. If you want a float array which correctly averages the input values without rounding, you can do the following instead.

a.reshape(args[0],factor[0],).mean(1)
a.reshape(args[0],factor[0],args[1],factor[1],).mean(1).mean(2)

   1 def rebin(a, *args):
   2     shape = a.shape
   3     lenShape = len(shape)
   4     factor = asarray(shape)/asarray(args)
   5     evList = ['a.reshape('] + \
   6              ['args[%d],factor[%d],'%(i,i) for i in range(lenShape)] + \
   7              [')'] + ['.mean(%d)'%(i+1) for i in range(lenShape)]
   8     print ''.join(evList)
   9     return eval(''.join(evList))

Some test cases:

   1 # 2-D case
   2 a=rand(6,4)
   3 print a
   4 b=rebin(a,6,4)
   5 print b
   6 b=rebin(a,6,2)
   7 print b
   8 b=rebin(a,3,2)
   9 print b
  10 b=rebin(a,1,1)
  11 
  12 # 1-D case
  13 print b
  14 a=rand(4)
  15 print a
  16 b=rebin(a,4)
  17 print b
  18 b=rebin(a,2)
  19 print b
  20 b=rebin(a,1)
  21 print b

Example 3

A python version of congrid, used in IDL, for resampling of data to arbitrary sizes, using a variety of nearest-neighbour and interpolation routines.

   1 import numpy as n
   2 import scipy.interpolate
   3 import scipy.ndimage
   4 
   5 def congrid(a, newdims, method='linear', centre=False, minusone=False):
   6     '''Arbitrary resampling of source array to new dimension sizes.
   7     Currently only supports maintaining the same number of dimensions.
   8     To use 1-D arrays, first promote them to shape (x,1).
   9     
  10     Uses the same parameters and creates the same co-ordinate lookup points
  11     as IDL''s congrid routine, which apparently originally came from a VAX/VMS
  12     routine of the same name.
  13 
  14     method:
  15     neighbour - closest value from original data
  16     nearest and linear - uses n x 1-D interpolations using
  17                          scipy.interpolate.interp1d
  18     (see Numerical Recipes for validity of use of n 1-D interpolations)
  19     spline - uses ndimage.map_coordinates
  20 
  21     centre:
  22     True - interpolation points are at the centres of the bins
  23     False - points are at the front edge of the bin
  24 
  25     minusone:
  26     For example- inarray.shape = (i,j) & new dimensions = (x,y)
  27     False - inarray is resampled by factors of (i/x) * (j/y)
  28     True - inarray is resampled by(i-1)/(x-1) * (j-1)/(y-1)
  29     This prevents extrapolation one element beyond bounds of input array.
  30     '''
  31     if not a.dtype in [n.float64, n.float32]:
  32         a = n.cast[float](a)
  33     
  34     m1 = n.cast[int](minusone)
  35     ofs = n.cast[int](centre) * 0.5
  36     old = n.array( a.shape )
  37     ndims = len( a.shape )
  38     if len( newdims ) != ndims:
  39         print "[congrid] dimensions error. " \
  40               "This routine currently only support " \
  41               "rebinning to the same number of dimensions."
  42         return None
  43     newdims = n.asarray( newdims, dtype=float )    
  44     dimlist = []
  45 
  46     if method == 'neighbour':
  47         for i in range( ndims ):
  48             base = n.indices(newdims)[i]
  49             dimlist.append( (old[i] - m1) / (newdims[i] - m1) \
  50                             * (base + ofs) - ofs )
  51         cd = n.array( dimlist ).round().astype(int)
  52         newa = a[list( cd )]
  53         return newa
  54     
  55     elif method in ['nearest','linear']:
  56         # calculate new dims
  57         for i in range( ndims ):
  58             base = n.arange( newdims[i] )
  59             dimlist.append( (old[i] - m1) / (newdims[i] - m1) \
  60                             * (base + ofs) - ofs )
  61         # specify old dims
  62         olddims = [n.arange(i, dtype = n.float) for i in list( a.shape )]
  63 
  64         # first interpolation - for ndims = any
  65         mint = scipy.interpolate.interp1d( olddims[-1], a, kind=method )
  66         newa = mint( dimlist[-1] )
  67 
  68         trorder = [ndims - 1] + range( ndims - 1 )
  69         for i in range( ndims - 2, -1, -1 ):
  70             newa = newa.transpose( trorder )
  71 
  72             mint = scipy.interpolate.interp1d( olddims[i], newa, kind=method )
  73             newa = mint( dimlist[i] )
  74 
  75         if ndims > 1:
  76             # need one more transpose to return to original dimensions
  77             newa = newa.transpose( trorder )
  78 
  79         return newa
  80     elif method in ['spline']:
  81         oslices = [ slice(0,j) for j in old ]
  82         oldcoords = n.ogrid[oslices]
  83         nslices = [ slice(0,j) for j in list(newdims) ]
  84         newcoords = n.mgrid[nslices]
  85 
  86         newcoords_dims = range(n.rank(newcoords))
  87         #make first index last
  88         newcoords_dims.append(newcoords_dims.pop(0))
  89         newcoords_tr = newcoords.transpose(newcoords_dims)
  90         # makes a view that affects newcoords
  91 
  92         newcoords_tr += ofs        
  93 
  94         deltas = (n.asarray(old) - m1) / (newdims - m1)
  95         newcoords_tr *= deltas
  96 
  97         newcoords_tr -= ofs
  98 
  99         newa = scipy.ndimage.map_coordinates(a, newcoords)
 100         return newa
 101     else:
 102         print "Congrid error: Unrecognized interpolation type.\n", \
 103               "Currently only \'neighbour\', \'nearest\',\'linear\',", \
 104               "and \'spline\' are supported."
 105         return None 


CategoryCookbook

SciPy: Cookbook/Rebinning (last edited 2015-10-24 17:48:24 by anonymous)