[Numpy-discussion] Further comments

Edward C. Jones edcjones at erols.com
Sat Dec 28 09:52:23 CST 2002

Should the variable "type" be used in numarray? It is an important 
function in Python.


There needs to be a function or method that returns the number of 
elements in an array.

def Elements(array):
     """Number of elements in an array.

     This version is slow.
     return numarray.multiply.reduce(array.shape)


I write code using both PIL and numarray. PIL uses strings for modes and
numarray uses (optionally) strings as typecodes. This causes problems.
One fix is to emit a DeprecationWarning when string typecodes are used. 
Two functions are needed: StringTypeWarningOn and StringTypeWarningOff. 
The default should be to ignore this warning.

In my code I use the following workarounds:

def SameType(x, y):
     """Are the two input the same object of NumericType?"""
     if isinstance(x, NumericType) and isinstance(y, NumericType) \
            and x == y:
         return True
     return False

def IsTypeInList(typecode, seq):
     """Is a NumericType object in a list of NumericType objects?"""
     if not isinstance(typecode, NumericType):
         return False
     for item in seq:
         if isinstance(item, NumericType) and typecode == item:
             return True
     return False


The following function is useful for downsizing arrays. I suggest that
it should be a ufunc method. This is how I have used reduceat in Numeric.

def blockreduce(array, blocksizes, ufunc):
     """Apply ufunc.reduce to blocks in an array."""
     dims = len(array.shape)
     if type(blocksizes) is IntType:
         blocksizes = dims * [blocksizes]
     if len(blocksizes) != dims:
         raise TypeError, 'blocksizes must be same length as shape'
     for i in range(dims):
         if array.shape[i] % blocksizes[i] != 0:
             raise ValueError, 'blocksizes must exactly divide ' \
                'the corresponding array dimension'
     for i in range(dims):
         array = array.copy()
         newshape = (array.shape[0] / blocksizes[i], blocksizes[i]) + \
         array.shape = newshape
         array = ufunc.reduce(array, 1)
         dims = len(array.shape)
         # (0,1,2,3) --> (1,2,3,0)
         perm =  tuple(range(1, dims)) + (0,)
         array = numarray.transpose(array, perm)
     return array

More information about the Numpy-discussion mailing list