[pypy-svn] r71014 - in pypy/branch/micronumpy/pypy/module/micronumpy: . test
electronicru at codespeak.net
electronicru at codespeak.net
Sun Jan 31 06:53:33 CET 2010
Author: electronicru
Date: Sun Jan 31 06:53:32 2010
New Revision: 71014
Removed:
pypy/branch/micronumpy/pypy/module/micronumpy/app_numarray.py
Modified:
pypy/branch/micronumpy/pypy/module/micronumpy/__init__.py
pypy/branch/micronumpy/pypy/module/micronumpy/array.py
pypy/branch/micronumpy/pypy/module/micronumpy/dtype.py
pypy/branch/micronumpy/pypy/module/micronumpy/mdarray.py
pypy/branch/micronumpy/pypy/module/micronumpy/sdarray.py
pypy/branch/micronumpy/pypy/module/micronumpy/test/test_numpy.py
Log:
Added slices, sdarray/sdarray operators, multidimension shape/type detection and quick test for them.
Added instance attributes dtype and shape.
file app_numarray.py deleted because of unnecessarity.
Modified: pypy/branch/micronumpy/pypy/module/micronumpy/__init__.py
==============================================================================
--- pypy/branch/micronumpy/pypy/module/micronumpy/__init__.py (original)
+++ pypy/branch/micronumpy/pypy/module/micronumpy/__init__.py Sun Jan 31 06:53:32 2010
@@ -1,4 +1,4 @@
-
+
from pypy.interpreter.mixedmodule import MixedModule
class Module(MixedModule):
Modified: pypy/branch/micronumpy/pypy/module/micronumpy/array.py
==============================================================================
--- pypy/branch/micronumpy/pypy/module/micronumpy/array.py (original)
+++ pypy/branch/micronumpy/pypy/module/micronumpy/array.py Sun Jan 31 06:53:32 2010
@@ -1,8 +1,8 @@
-from pypy.interpreter.baseobjspace import ObjSpace, W_Root, Wrappable
+from pypy.interpreter.baseobjspace import ObjSpace, W_Root, Wrappable
from pypy.interpreter.error import OperationError
from pypy.interpreter.typedef import TypeDef
from pypy.interpreter.gateway import NoneNotWrapped
-from pypy.interpreter.gateway import interp2app, NoneNotWrapped
+from pypy.interpreter.gateway import interp2app
from pypy.module.micronumpy.dtype import iterable_type
@@ -15,7 +15,9 @@
array_dimensionality = len(array.shape)
if index_dimensionality > array_dimensionality:
raise OperationError(space.w_IndexError,
- space.wrap("Index dimensionality (%d) greater than array dimensionality (%d)." % (index_dimensionality, array_dimensionality)))
+ space.wrap("Index dimensionality (%d) "
+ "greater than array dimensionality (%d)."
+ % (index_dimensionality, array_dimensionality)))
except OperationError, e:
if e.match(space, space.w_TypeError): pass
else: raise
@@ -67,8 +69,21 @@
shape_w = space.fixedview(w_shape)
return [space.int_w(w_i) for w_i in shape_w]
-def infer_shape(space, w_values):
- return [space.int_w(space.len(w_values))] #TODO: handle multi-dimensional arrays...
+def infer_shape(space, w_values):
+ shape = []
+ while True:
+ try:
+ shape.append(space.int_w(space.len(w_values)))
+ except OperationError, e:
+ if e.match(space, space.w_TypeError):
+ break
+ elif e.match(space, space.IndexError):
+ break #as numpy does
+ else:
+ raise
+ else:
+ w_values = space.getitem(w_values, space.wrap(0))
+ return shape
def construct_array(space, shape, w_dtype):
from pypy.module.micronumpy.sdarray import sdresult
@@ -78,7 +93,7 @@
length = shape[0]
return sdresult(space, w_dtype)(space, length, w_dtype)
else:
- return mdresult(space, w_dtype)(space, shape)
+ return mdresult(space, w_dtype)(space, shape, w_dtype)
except KeyError, e:
raise OperationError(space.w_NotImplementedError,
space.wrap("Haven't implemented generic array yet!"))
Modified: pypy/branch/micronumpy/pypy/module/micronumpy/dtype.py
==============================================================================
--- pypy/branch/micronumpy/pypy/module/micronumpy/dtype.py (original)
+++ pypy/branch/micronumpy/pypy/module/micronumpy/dtype.py Sun Jan 31 06:53:32 2010
@@ -1,3 +1,4 @@
+from pypy.interpreter.error import OperationError
def unwrap_int(space, w_x):
return space.int_w(w_x)
def coerce_int(space, w_x):
@@ -27,5 +28,13 @@
xs = space.fixedview(w_xs)
result_type = space.w_int
for i in range(len(xs)):
- result_type = result_mapping(space, (result_type, space.type(xs[i])))
+ try:
+ space.iter(xs[i])
+ except OperationError, e:
+ if not e.match(space, space.w_TypeError):
+ raise
+ atype = space.type(xs[i])
+ else:
+ atype = iterable_type(space, xs[i])
+ result_type = result_mapping(space, (result_type, atype))
return result_type
Modified: pypy/branch/micronumpy/pypy/module/micronumpy/mdarray.py
==============================================================================
--- pypy/branch/micronumpy/pypy/module/micronumpy/mdarray.py (original)
+++ pypy/branch/micronumpy/pypy/module/micronumpy/mdarray.py Sun Jan 31 06:53:32 2010
@@ -1,11 +1,14 @@
-from pypy.interpreter.error import OperationError
-from pypy.interpreter.typedef import TypeDef
-from pypy.interpreter.gateway import interp2app, NoneNotWrapped
-from pypy.interpreter.baseobjspace import ObjSpace, W_Root, Wrappable
+from pypy.interpreter.error import OperationError
+from pypy.interpreter.typedef import TypeDef, GetSetProperty
+from pypy.interpreter.gateway import interp2app
+from pypy.interpreter.baseobjspace import W_Root
from pypy.rlib.debug import make_sure_not_resized
from pypy.module.micronumpy.array import BaseNumArray
from pypy.module.micronumpy.array import base_typedef
+from pypy.module.micronumpy.array import construct_array
+from pypy.module.micronumpy.array import array as array_fromseq
+from pypy.module.micronumpy.array import validate_index
from pypy.module.micronumpy.dtype import unwrap_int, coerce_int
from pypy.module.micronumpy.dtype import unwrap_float, coerce_float
@@ -13,6 +16,7 @@
def compute_pos(space, indexes, dim):
current = 1
pos = 0
+ indexes.reverse()
for i in range(len(indexes)):
index = indexes[i]
d = dim[i]
@@ -25,13 +29,78 @@
current *= d
return pos
+def compute_slices(space, slices, dims):
+ slices = space.fixedview(slices)
+ if len(slices) > len(dims):
+ raise OperationError(space.w_IndexError,
+ space.wrap('too many indices'))
+ strides = []
+ i = 1
+ for dim in dims:
+ strides.append(i)
+ i *= dim
+ shape = dims[:]
+ strides.reverse()
+ newshape = []
+ extract = [0]
+ slicelen = i #saved
+ for i in range(len(slices)):
+ w_index = slices[i]
+ if space.is_true(space.isinstance(w_index, space.w_slice)):
+ newextract = []
+ l = shape[i]
+ stride = strides[i]
+ start, stop, step, slen = w_index.indices4(space, l)
+ if slen == 0:
+ extract = []
+ continue #as in numpy
+ newshape.append(slen)
+ if step == 1:
+ for i in range(len(extract)):
+ extract[i] += start*stride
+ slicelen = stride*slen
+ else:
+ for i in range(len(extract)):
+ st = extract[i]
+ for j in range(slicelength):
+ newextract.append(st+start*stride)
+ start += step
+ extract = newextract
+ slicelen = stride
+ elif space.is_w(w_index, space.w_Ellipsis):
+ newshape.append(shape[i])
+ else: #Must be integer
+ try:
+ index = space.int_w(w_index)
+ except TypeError, e:
+ raise OperationError(space.w_IndexError,
+ space.wrap('Wrong index'))
+ stride = strides[i]
+ start = index*stride
+ for i in range(len(extract)):
+ extract[i] += start
+ #No adding for shape
+ slicelen = stride
+
+ newshape.extend(shape[i+1:]) #add rest of shape
+ #all slices are absolutely eqi-length
+ return newshape, extract, slicelen
+
+
class BaseMultiDimArray(BaseNumArray): pass
+def descr_dtype(space, self):
+ return self.dtype
+
+def descr_shape(space, self):
+ return space.wrap(self.shape)
+
def create_mdarray(data_type, unwrap, coerce):
class MultiDimArray(BaseMultiDimArray):
- def __init__(self, space, shape):
+ def __init__(self, space, shape, w_dtype):
self.shape = shape
self.space = space
+ self.dtype = w_dtype
size = 1
for dimension in shape:
size *= dimension
@@ -39,43 +108,120 @@
make_sure_not_resized(self.storage)
def load_iterable(self, w_xs):
- self._internal_load(w_xs, self.shape)
+ self._internal_load(w_xs, self.shape, [])
- def _internal_load(self, w_xs, shape):
+ def _internal_load(self, w_xs, shape, indexes):
space = self.space
length = shape[0]
xs = space.fixedview(w_xs, length)
-
- #FIXME: brain no work, do later
- #for x in xs:
- #self
+ shapemismatch = OperationError(space.w_ValueError,
+ space.wrap('shape mismatch'))
+ for i in range(length):
+ try:
+ w_x = xs[i]
+ except IndexError:
+ raise shapemismatch
+ try:
+ space.iter(w_x)
+ except OperationError, e:
+ if e.match(space, space.w_TypeError):
+ if len(shape)>1:
+ raise shapemismatch
+ else:
+ pos = compute_pos(space, indexes+[i], self.shape)
+ self.storage[pos]=coerce(space, w_x)
+ elif e.match(space, space.w_IndexError):
+ raise shapemismatch
+ else:
+ raise
+ else:
+ self._internal_load(w_x, shape[1:], indexes+[i])
def _unpack_indexes(self, space, w_index):
indexes = [space.int_w(w_i) for w_i in space.fixedview(w_index)]
if len(indexes) != len(self.shape):
- raise OperationError(space.w_IndexError, space.wrap(
- 'Wrong index'))
+ raise OperationError(space.w_IndexError,
+ space.wrap('shape mismatch'))
return indexes
def descr_getitem(self, w_index):
space = self.space
- indexes = self._unpack_indexes(space, w_index)
- pos = compute_pos(space, indexes, self.shape)
- return space.wrap(self.storage[pos])
+ validate_index(self, space, w_index)
+ try:
+ space.iter(w_index)
+ except OperationError, e:
+ if not e.match(space, space.w_TypeError):
+ raise
+ w_index = space.newlist([w_index])
+ try:
+ indexes = self._unpack_indexes(space, w_index)
+ except OperationError, e:
+ if not (e.match(space, space.w_IndexError) or
+ e.match(space, space.w_TypeError)):
+ raise
+ shape, regions, l = compute_slices(space, w_index, self.shape)
+ res = construct_array(space, shape, self.dtype)
+ i = 0
+ if len(regions) > 0:
+ for start in regions:
+ res.storage[i:i+l] = self.storage[start:start+l]
+ i += l
+ return space.wrap(res)
+ else:
+ pos = compute_pos(space, indexes, self.shape)
+ return space.wrap(self.storage[pos])
descr_getitem.unwrap_spec = ['self', W_Root]
def descr_setitem(self, w_index, w_value):
space = self.space
- indexes = self._unpack_indexes(space, w_index)
- pos = compute_pos(space, indexes, self.shape)
- self.storage[pos] = coerce(space, w_value)
+ try:
+ indexes = self._unpack_indexes(space, w_index)
+ except OperationError, e:
+ if not e.match(space, space.w_IndexError):
+ #not raised by _unpack_indexes
+ raise
+ shape, regions, lslice = \
+ compute_slices(space, w_index, self.shape)
+ try:
+ space.iter(w_value)
+ except OperationError, e:
+ if not e.match(space, space.w_TypeError):
+ raise
+ value = coerce(space, w_value)
+ for start in regions:
+ self.storage[start:start+lslice]=[value]*lslice
+ return
+ arr = array_fromseq(space, w_value)
+ ls = len(arr.shape)
+ lss = len(self.shape)
+ if not (ls <= lss and arr.shape == self.shape[lss-ls:lss]):
+ raise OperationError(space.w_ValueError,
+ space.wrap('array dimensions '
+ 'are not compatible for copy'))
+ #exactly as in numpy
+ # /S\ - DO NOT EDIT if you're not sure!
+ #we may exit earlier, but we are true purists and wonna check
+ if len(regions) == 0: return
+ l = len(arr.storage)
+ if lslice > l: #long slice
+ iters = lslice//l
+ assert lslice == l*iters
+ for start in regions:
+ for i in range(iters):
+ self.storage[start:start+l] = arr.storage
+ start += l
+ else:
+ i = 0
+ for start in regions:
+ self.storage[start:start+l] = arr.storage[i:i+lslice]
+ if i > l:
+ i = i-l
+ #Looks like perfect
+ else:
+ pos = compute_pos(space, indexes, self.shape)
+ self.storage[pos] = coerce(space, w_value)
descr_setitem.unwrap_spec = ['self', W_Root, W_Root]
- def load_iterable(self, w_xs):
- space = self.space
- raise OperationError(space.w_NotImplementedError,
- space.wrap("Haven't implemented iterable loading yet!"))
-
def len(self):
return self.shape[0]
@@ -84,11 +230,19 @@
return space.wrap(self.len())
descr_len.unwrap_spec = ['self']
- MultiDimArray.typedef = TypeDef('ndarray', base_typedef,
- __len__ = interp2app(MultiDimArray.descr_len),
- __getitem__ = interp2app(MultiDimArray.descr_getitem),
- __setitem__ = interp2app(MultiDimArray.descr_setitem),
- )
+ def descr_str(self):
+ return self.space.str(self.space.wrap(self.storage))
+ descr_str.unwrap_spec = ['self']
+
+ MultiDimArray.typedef = \
+ TypeDef('ndarray', base_typedef,
+ __len__ = interp2app(MultiDimArray.descr_len),
+ __getitem__ = interp2app(MultiDimArray.descr_getitem),
+ __setitem__ = interp2app(MultiDimArray.descr_setitem),
+ __str__ = interp2app(MultiDimArray.descr_str),
+ dtype = GetSetProperty(descr_dtype, cls = MultiDimArray),
+ shape = GetSetProperty(descr_shape, cls = MultiDimArray),
+ )
return MultiDimArray
MultiDimIntArray = create_mdarray(int, unwrap_int, coerce_int)
Modified: pypy/branch/micronumpy/pypy/module/micronumpy/sdarray.py
==============================================================================
--- pypy/branch/micronumpy/pypy/module/micronumpy/sdarray.py (original)
+++ pypy/branch/micronumpy/pypy/module/micronumpy/sdarray.py Sun Jan 31 06:53:32 2010
@@ -1,23 +1,33 @@
-from pypy.interpreter.baseobjspace import ObjSpace, W_Root, Wrappable
+from pypy.interpreter.baseobjspace import W_Root, Wrappable
from pypy.interpreter.error import OperationError
-from pypy.interpreter.typedef import TypeDef
-from pypy.interpreter.gateway import interp2app, NoneNotWrapped
+from pypy.interpreter.typedef import TypeDef, GetSetProperty
+from pypy.interpreter.gateway import interp2app
from pypy.rlib.debug import make_sure_not_resized
from pypy.module.micronumpy.array import BaseNumArray
from pypy.module.micronumpy.array import base_typedef
-from pypy.module.micronumpy.array import mul_operation, div_operation, add_operation, sub_operation
+from pypy.module.micronumpy.array import \
+ mul_operation, div_operation, add_operation, sub_operation
from pypy.module.micronumpy.array import copy_operation
from pypy.module.micronumpy.dtype import unwrap_int, coerce_int
from pypy.module.micronumpy.dtype import unwrap_float, coerce_float
-from pypy.module.micronumpy.dtype import unwrap_float32, coerce_float32, float32
-from pypy.module.micronumpy.dtype import result_mapping
+from pypy.module.micronumpy.dtype import\
+ unwrap_float32, coerce_float32, float32
+from pypy.module.micronumpy.dtype import result_mapping, iterable_type
+
+#TODO: merge unwrap_spec decorator
+# from pypy.interpreter.gateway import unwrap_spec
-# from pypy.interpreter.gateway import unwrap_spec #TODO: merge unwrap_spec decorator
class BaseSingleDimArray(BaseNumArray): pass
+def descr_dtype(space, self):
+ return self.dtype
+
+def descr_shape(space, self):
+ return space.newtuple([space.wrap(self.len())])
+
def create_sdarray(data_type, unwrap, coerce):
class SingleDimIterator(Wrappable):
def __init__(self, space, array, i):
@@ -26,7 +36,7 @@
self.i = i
def descr_iter(self):
- self.space = space
+ space = self.space
return space.wrap(self)
descr_iter.unwrap_spec = ['self']
@@ -41,9 +51,9 @@
descr_iter.unwrap_spec = ['self']
SingleDimIterator.typedef = TypeDef('iterator',
- __iter__ = interp2app(SingleDimIterator.descr_iter),
- next = interp2app(SingleDimIterator.descr_next)
- )
+ __iter__ = interp2app(SingleDimIterator.descr_iter),
+ next = interp2app(SingleDimIterator.descr_next)
+ )
mul = mul_operation()
div = div_operation()
@@ -51,61 +61,77 @@
sub = sub_operation()
copy = copy_operation()
+ def create_client_math_operation(f):
+ def scalar_operation(self, source, x):
+ for i in range(len(source.storage)):
+ self.storage[i] = data_type(f(source.storage[i], x))
+
+ def fixedview_operation(self, source1, source2):
+ for i in range(self.len()):
+ self.storage[i] = \
+ data_type(f(source1.storage[i], source2.storage[i]))
+ return scalar_operation, fixedview_operation
+
+ def create_math_operation(f):
+ opname = f.__name__
+ def math_operation(self, w_x):
+ space = self.space
+ try:
+ space.iter(w_x)
+ except OperationError, e:
+ if not e.match(space, space.w_TypeError):
+ raise
+ result_t = result_mapping(space,
+ (space.type(w_x), self.dtype))
+ op2 = coerce(space, w_x)
+ result = sdresult(space, result_t)(
+ space, self.len(), result_t
+ )
+ operation = result.__class__.client_scalar[opname]
+ else:
+ lop = space.int_w(space.len(w_x))
+ if lop != self.len():
+ raise OperationError(space.w_ValueError,
+ space.wrap("shape mismatch: objects cannot be"
+ " broadcast to the same shape"))
+ dtype = iterable_type(space, w_x)
+ result_t = result_mapping(space, (dtype, self.dtype))
+ op2 = sdresult(space, dtype)(space, lop, dtype)
+ op2.load_iterable(w_x)
+ result = sdresult(space, result_t)(
+ space, self.len(), result_t
+ )
+ operation = result.__class__.client_fixedview[opname]
+
+ operation(result, self, op2)
+
+ w_result = space.wrap(result)
+ return w_result
+ math_operation.unwrap_spec = ['self', W_Root]
+ return math_operation
+
+
class NumArray(BaseSingleDimArray):
def __init__(self, space, length, dtype):
self.shape = (length,)
self.space = space
- self.storage = [data_type()] * length
+ self.storage = [data_type(0.0)] * length
self.dtype = dtype
make_sure_not_resized(self.storage)
- def create_client_math_operation(f):
- def scalar_operation(result, source, w_x):
- space = result.space
- x = coerce(space, w_x)
- for i in range(len(source.storage)):
- result.storage[i] = f(data_type(source.storage[i]), x)
+
+ client_scalar = {}
+ client_fixedview = {}
+
+ client_scalar['mul'], client_fixedview['mul'] = \
+ create_client_math_operation(mul)
+ client_scalar['div'], client_fixedview['div'] = \
+ create_client_math_operation(div)
+ client_scalar['add'], client_fixedview['add'] = \
+ create_client_math_operation(add)
+ client_scalar['sub'], client_fixedview['sub'] = \
+ create_client_math_operation(sub)
- def fixedview_operation(self, w_xs):
- space = self.space
- try:
- xs = space.fixedview(w_xs, len(self.storage))
- except UnpackValueError, e:
- # w_xs is of the wrong size
- raise OperationError(space.w_ValueError,
- space.wrap("shape mismatch: objects cannot be broadcast to the same shape"))
-
- i = 0
- for w_x in xs:
- self.storage[i] = f(source.storage[i], self.coerce(w_x)) #TODO: probably shouldn't coerce
- i += 1
- return result
- return scalar_operation, fixedview_operation
-
- client_mul_scalar, client_mul_fixedview = create_client_math_operation(mul)
- client_div_scalar, client_div_fixedview = create_client_math_operation(div)
- client_add_scalar, client_add_fixedview = create_client_math_operation(add)
- client_sub_scalar, client_sub_fixedview = create_client_math_operation(sub)
-
- def create_math_operation(f):
- scalar_operation_name = '_'.join(['client', f.__name__, 'scalar'])
- fixedview_operation_name = '_'.join(['client', f.__name__, 'fixedview'])
- def math_operation(self, w_x):
- space = self.space
- if space.type(w_x) in (space.w_list, space.w_tuple):
- raise OperationError(space.w_NotImplementedError,
- space.wrap("Haven't implemented array %s iterable yet!" % f.__name__))
- result_t = result_mapping(space, (self.dtype, space.w_None))
- else:
- result_t = result_mapping(space, (space.type(w_x), self.dtype))
-
- result = sdresult(space, result_t)(space, self.len(), self.dtype)
- getattr(result, scalar_operation_name)(self, w_x)
-
- w_result = space.wrap(result)
- return w_result
- math_operation.unwrap_spec = ['self', W_Root]
- return math_operation
descr_mul = create_math_operation(mul)
descr_mul.__name__ = 'descr_mul'
@@ -127,27 +153,78 @@
i += 1
def descr_iter(self):
- return space.wrap(SingleDimIterator(space, self, 0))
+ return self.space.wrap(SingleDimIterator(self.space, self, 0))
descr_iter.unwrap_spec = ['self']
- def descr_getitem(self, index):
+ def descr_getitem(self, w_index):
space = self.space
+ if space.is_true(space.isinstance(w_index, space.w_slice)):
+ start, stop, step, slen = w_index.indices4(space, self.len())
+ res = sdresult(space, self.dtype)(space, slen, self.dtype)
+ if step == 1:
+ res.storage[:] = self.storage[start:stop]
+ else:
+ for i in range(slen):
+ res.storage[i] = self.storage[start]
+ start += step
+ return space.wrap(res)
+ else:
+ try:
+ index = space.int_w(w_index)
+ except TypeError, e:
+ raise OperationError(space.w_IndexError,
+ space.wrap('Wrong index'))
try:
return space.wrap(self.storage[index])
except IndexError:
raise OperationError(space.w_IndexError,
space.wrap("list index out of range"))
- descr_getitem.unwrap_spec = ['self', int]
+ descr_getitem.unwrap_spec = ['self', W_Root]
- def descr_setitem(self, index, w_value):
+ def descr_setitem(self, w_index, w_value):
space = self.space
+ if space.is_true(space.isinstance(w_index, space.w_slice)):
+ start, stop, step, slen = w_index.indices4(space, self.len())
+ try:
+ space.iter(w_value)
+ except OperationError, e:
+ if not e.match(space, space.w_TypeError):
+ raise
+ if not slen:
+ return
+ value = coerce(space, w_value)
+ if step == 1:
+ self.storage[start:stop] = [value]*slen
+ else:
+ for i in range(start, stop, step):
+ self.storage[i] = value
+ return
+ lop = space.int_w(space.len(w_value))
+ if lop != slen:
+ raise OperationError(space.w_TypeError,
+ space.wrap('shape mismatch'))
+ value = space.fixedview(w_value)
+ if step == 1:
+ self.storage[start:stop] = \
+ [coerce(space, w_value) for w_value in value]
+ else:
+ for i in range(slen):
+ self.storage[start] = coerce(space, value[i])
+ start += step
+ return
+ else:
+ try:
+ index = space.int_w(w_index)
+ except TypeError, e:
+ raise OperationError(space.w_IndexError,
+ space.wrap('Wrong index'))
try:
self.storage[index] = coerce(space, w_value)
except IndexError:
raise OperationError(space.w_IndexError,
space.wrap("list index out of range"))
return space.w_None
- descr_setitem.unwrap_spec = ['self', int, W_Root]
+ descr_setitem.unwrap_spec = ['self', W_Root, W_Root]
def len(self):
return len(self.storage)
@@ -162,7 +239,12 @@
def descr_str(self):
space = self.space
- return space.wrap("[%s]" % self.str())
+ #beautiful, as in numpy
+ strs=[str(x) for x in self.storage]
+ maxlen=max([len(x) for x in strs])
+ return space.wrap(
+ "[%s]" % ' '.join(["%-*s"%(maxlen, s) for s in strs])
+ )
descr_str.unwrap_spec = ['self']
def descr_repr(self):
@@ -175,11 +257,19 @@
__div__ = interp2app(NumArray.descr_div),
__add__ = interp2app(NumArray.descr_add),
__sub__ = interp2app(NumArray.descr_sub),
+ __rmul__ = interp2app(NumArray.descr_mul),
+ __rdiv__ = interp2app(NumArray.descr_div),
+ __radd__ = interp2app(NumArray.descr_add),
+ __rsub__ = interp2app(NumArray.descr_sub),
__getitem__ = interp2app(NumArray.descr_getitem),
__setitem__ = interp2app(NumArray.descr_setitem),
__len__ = interp2app(NumArray.descr_len),
__str__ = interp2app(NumArray.descr_str),
__repr__ = interp2app(NumArray.descr_repr),
+ dtype = GetSetProperty(descr_dtype,
+ cls = NumArray),
+ shape = GetSetProperty(descr_shape,
+ cls = NumArray),
)
return NumArray
Modified: pypy/branch/micronumpy/pypy/module/micronumpy/test/test_numpy.py
==============================================================================
--- pypy/branch/micronumpy/pypy/module/micronumpy/test/test_numpy.py (original)
+++ pypy/branch/micronumpy/pypy/module/micronumpy/test/test_numpy.py Sun Jan 31 06:53:32 2010
@@ -1,4 +1,4 @@
-
+
from pypy.conftest import gettestobjspace
class AppTestSDArray(object):
@@ -24,19 +24,23 @@
assert compare(ar, data)
def test_sdarray_operators(self):
+ from numpy import array
from operator import mul, div, add, sub
+ d = range(1, self.length)
#FIXME: overkill...
for data_type in (int, float):
+ data = [data_type(x) for x in d]
+ ar = array(data)
+ data.reverse()
+ ar2 = array(data)
for operator in (mul, div, add, sub):
for value in xrange(1, 16):
compare = self.compare
- from numpy import array
- data = [data_type(x) for x in range(self.length)]
- ar = array(data)
- assert compare(operator(ar, value), [operator(x, value) for x in data])
+ assert compare(operator(ar2, value), [operator(x, value) for x in data])
+ assert compare(operator(ar, ar2), [operator(x, y) for (x, y) in zip(ar, ar2)])
def test_operator_result_types(self):
- skip("Haven't implemented dispatching for array/array operations")
+ #skip("Haven't implemented dispatching for array/array operations")
from operator import mul, div, add, sub
from numpy import array
types = {
@@ -98,6 +102,14 @@
assert ar[-7] == 3
assert len(ar) == 8
+ ar[2:3] = [5]
+ assert ar[2] == 5
+ compare = self.compare
+ assert compare(ar[1:3], [3, 5])
+ assert compare(ar[-6:-4], [5, 0])
+ assert compare(ar[-6:-8:-1], [5, 3])
+
+
def test_minimum(self):
from numpy import zeros, minimum
ar = zeros(5, dtype=int)
@@ -139,3 +151,21 @@
def test_len(self):
from numpy import zeros
assert len(zeros((3, 2, 1), dtype=int)) == 3
+
+ def test_shape_detect(self):
+ from numpy import array
+ ar = array([range(i*3, i*3+3) for i in range(3)])
+ assert len(ar) == 3
+ for i in range(3):
+ for j in range(3):
+ assert ar[i, j] == i*3+j
+
+ def test_various_slices(self):
+ from numpy import array
+ ar = array([range(i*3, i*3+3) for i in range(3)])
+ s1 = ar[0]
+ assert s1[1]==1
+ s2 = ar[1:3]
+ assert s2[0][0] == 3
+
+
More information about the Pypy-commit
mailing list