[Numpy-discussion] Response to PEP suggestions
Duncan Child
duncan at enthought.com
Thu Feb 17 14:23:17 EST 2005
Here are a couple of issues that are important to me that might be
relevant to the design discussion.
I have attached some code that illustrates part of the pain we have
experienced developing libraries of algorithms that can handle both
arrays and scalars. The attached library is the reusable part. The other
part of this problem is that we have lots of logic sprinkled throughout
our algorithms to enable them to handle both arrays and scalars.
Secondly, I have just been bitten by this declaration which suggests
that the new Numeric might handle default values better:.
_vp_mod = zeros(num_pts)
It would be less surprising to someone developing numeric algorithms if
functions like this defaulted to creating a double precision array
rather than integers.
Regards,
Duncan
>
>
>>3) Always returning rank-0 arrays.
>>
>>This may be a bit controversial as it is a bit of a change.
>>
>>
>
>Indeed. So you really do intend that if foo=array([1,2]), foo[0]
>should evaluate to array(1) rather than 1?
>
>
>
import scipy
from scipy import take, amin, amax, arange, asarray, PyObject, mean, \
product, shape, array, Float64, nonzero
"""
The following safe_ methods were written to handle both arrays amd
scalars to
save the developer of numerical methods having to clutter their code
with tests
to determine the type of the data.
"""
def safe_take(a,indices):
# Slice the input if it is an array but not if it is a scalar
try:
a = take(a,indices)
except ValueError:
# a is scalar
pass
return a
def safe_copy(a):
# Return a copy for both scalar and array input
try:
b = a.copy()
except AttributeError:
# a is a scalar
b = a
return b
# Note: if x is a scalar and y = asarray(x), amin(y) FAILS but min(y) works
# Note: BUT IF z=convert(y,frac,frac), THEN min(z) FAILS!!!
def safe_min(a):
# Return the minimum of the input array or the input if it is a scalar
try:
safemin = amin(a)
except:
safemin = a
return safemin
def safe_max(a):
# Return the maximum of the input array or the input if it is a scalar
try:
safemax = amax(a)
except:
safemax = a
return safemax
def safe_mean(a):
# Return the mean of the input array or the input if it is a scalar
try:
safemean = mean(a)
except:
safemean = a
return safemean
def safe_len(a):
# Return the length of the input array or 1 if it is a scalar
try:
safelen = len(a)
except:
safelen = 1
return safelen
def safe_flat(a):
# Return a flat version of the input array or input if it is a scalar
try:
safeflat = a.flat
except:
safeflat = a
return safeflat
More information about the NumPy-Discussion
mailing list