[pypy-commit] pypy default: merge heads
arigo
noreply at buildbot.pypy.org
Thu Feb 27 08:28:45 CET 2014
Author: Armin Rigo <arigo at tunes.org>
Branch:
Changeset: r69499:1393c9dc8c7d
Date: 2014-02-27 08:27 +0100
http://bitbucket.org/pypy/pypy/changeset/1393c9dc8c7d/
Log: merge heads
diff too long, truncating to 2000 out of 20175 lines
diff --git a/pypy/module/cpyext/ndarrayobject.py b/pypy/module/cpyext/ndarrayobject.py
--- a/pypy/module/cpyext/ndarrayobject.py
+++ b/pypy/module/cpyext/ndarrayobject.py
@@ -7,10 +7,10 @@
from rpython.rtyper.lltypesystem import rffi, lltype
from pypy.module.cpyext.api import cpython_api, Py_ssize_t, CANNOT_FAIL
from pypy.module.cpyext.api import PyObject
-from pypy.module.micronumpy.interp_numarray import W_NDimArray, array
-from pypy.module.micronumpy.interp_dtype import get_dtype_cache, W_Dtype
-from pypy.module.micronumpy.arrayimpl.concrete import ConcreteArray
-from pypy.module.micronumpy.arrayimpl.scalar import Scalar
+from pypy.module.micronumpy.ndarray import W_NDimArray
+from pypy.module.micronumpy.ctors import array
+from pypy.module.micronumpy.descriptor import get_dtype_cache, W_Dtype
+from pypy.module.micronumpy.concrete import ConcreteArray
from rpython.rlib.rawstorage import RAW_STORAGE_PTR
NPY_C_CONTIGUOUS = 0x0001
@@ -167,7 +167,7 @@
# void *data = PyArray_DATA(arr);
impl = w_array.implementation
w_array = W_NDimArray.from_shape(space, [1], impl.dtype)
- w_array.implementation.setitem(0, impl.value)
+ w_array.implementation.setitem(0, impl.getitem(impl.start + 0))
w_array.implementation.shape = []
return w_array
@@ -214,12 +214,8 @@
order='C', owning=False, w_subtype=None):
shape, dtype = get_shape_and_dtype(space, nd, dims, typenum)
storage = rffi.cast(RAW_STORAGE_PTR, data)
- if nd == 0:
- w_val = dtype.itemtype.box_raw_data(storage)
- return W_NDimArray(Scalar(dtype, w_val))
- else:
- return W_NDimArray.from_shape_and_storage(space, shape, storage, dtype,
- order=order, owning=owning, w_subtype=w_subtype)
+ return W_NDimArray.from_shape_and_storage(space, shape, storage, dtype,
+ order=order, owning=owning, w_subtype=w_subtype)
@cpython_api([Py_ssize_t, rffi.LONGP, Py_ssize_t], PyObject)
diff --git a/pypy/module/cpyext/test/test_ndarrayobject.py b/pypy/module/cpyext/test/test_ndarrayobject.py
--- a/pypy/module/cpyext/test/test_ndarrayobject.py
+++ b/pypy/module/cpyext/test/test_ndarrayobject.py
@@ -2,8 +2,8 @@
from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
from rpython.rtyper.lltypesystem import rffi, lltype
-from pypy.module.micronumpy.interp_numarray import W_NDimArray
-from pypy.module.micronumpy.interp_dtype import get_dtype_cache
+from pypy.module.micronumpy.ndarray import W_NDimArray
+from pypy.module.micronumpy.descriptor import get_dtype_cache
def scalar(space):
dtype = get_dtype_cache(space).w_float64dtype
@@ -77,7 +77,7 @@
def test_FromAny_scalar(self, space, api):
a0 = scalar(space)
- assert a0.implementation.get_scalar_value().value == 10.
+ assert a0.get_scalar_value().value == 10.
a = api._PyArray_FromAny(a0, NULL, 0, 0, 0, NULL)
assert api._PyArray_NDIM(a) == 0
diff --git a/pypy/module/micronumpy/__init__.py b/pypy/module/micronumpy/__init__.py
--- a/pypy/module/micronumpy/__init__.py
+++ b/pypy/module/micronumpy/__init__.py
@@ -4,24 +4,24 @@
class MultiArrayModule(MixedModule):
appleveldefs = {'arange': 'app_numpy.arange'}
interpleveldefs = {
- 'ndarray': 'interp_numarray.W_NDimArray',
- 'dtype': 'interp_dtype.W_Dtype',
+ 'ndarray': 'ndarray.W_NDimArray',
+ 'dtype': 'descriptor.W_Dtype',
- 'array': 'interp_numarray.array',
- 'zeros': 'interp_numarray.zeros',
- 'empty': 'interp_numarray.zeros',
- 'empty_like': 'interp_numarray.empty_like',
- '_reconstruct' : 'interp_numarray._reconstruct',
- 'scalar' : 'interp_numarray.build_scalar',
- 'dot': 'interp_arrayops.dot',
- 'fromstring': 'interp_support.fromstring',
- 'flatiter': 'interp_flatiter.W_FlatIterator',
- 'concatenate': 'interp_arrayops.concatenate',
- 'where': 'interp_arrayops.where',
- 'count_nonzero': 'interp_arrayops.count_nonzero',
+ 'array': 'ctors.array',
+ 'zeros': 'ctors.zeros',
+ 'empty': 'ctors.zeros',
+ 'empty_like': 'ctors.empty_like',
+ '_reconstruct' : 'ndarray._reconstruct',
+ 'scalar' : 'ctors.build_scalar',
+ 'dot': 'arrayops.dot',
+ 'fromstring': 'ctors.fromstring',
+ 'flatiter': 'flatiter.W_FlatIterator',
+ 'concatenate': 'arrayops.concatenate',
+ 'where': 'arrayops.where',
+ 'count_nonzero': 'arrayops.count_nonzero',
'set_string_function': 'appbridge.set_string_function',
- 'typeinfo': 'interp_dtype.get_dtype_cache(space).w_typeinfo',
+ 'typeinfo': 'descriptor.get_dtype_cache(space).w_typeinfo',
}
@@ -107,7 +107,7 @@
('real', 'real'),
('imag', 'imag'),
]:
- interpleveldefs[exposed] = "interp_ufuncs.get(space).%s" % impl
+ interpleveldefs[exposed] = "ufuncs.get(space).%s" % impl
class Module(MixedModule):
diff --git a/pypy/module/micronumpy/appbridge.py b/pypy/module/micronumpy/appbridge.py
--- a/pypy/module/micronumpy/appbridge.py
+++ b/pypy/module/micronumpy/appbridge.py
@@ -1,5 +1,6 @@
from rpython.rlib.objectmodel import specialize
+
class AppBridgeCache(object):
w__mean = None
w__var = None
@@ -20,6 +21,7 @@
setattr(self, 'w_' + name, w_method)
return space.call_args(w_method, args)
+
def set_string_function(space, w_f, w_repr):
cache = get_appbridge_cache(space)
if space.is_true(w_repr):
@@ -27,5 +29,6 @@
else:
cache.w_array_str = w_f
+
def get_appbridge_cache(space):
return space.fromcache(AppBridgeCache)
diff --git a/pypy/module/micronumpy/arrayimpl/__init__.py b/pypy/module/micronumpy/arrayimpl/__init__.py
deleted file mode 100644
diff --git a/pypy/module/micronumpy/arrayimpl/base.py b/pypy/module/micronumpy/arrayimpl/base.py
deleted file mode 100644
--- a/pypy/module/micronumpy/arrayimpl/base.py
+++ /dev/null
@@ -1,20 +0,0 @@
-
-class BaseArrayImplementation(object):
- def is_scalar(self):
- return False
-
- def base(self):
- raise NotImplementedError
-
- def create_iter(self, shape=None, backward_broadcast=False, require_index=False):
- raise NotImplementedError
-
-class BaseArrayIterator(object):
- def next(self):
- raise NotImplementedError # purely abstract base class
-
- def setitem(self, elem):
- raise NotImplementedError
-
- def set_scalar_object(self, value):
- raise NotImplementedError # works only on scalars
diff --git a/pypy/module/micronumpy/arrayimpl/concrete.py b/pypy/module/micronumpy/arrayimpl/concrete.py
deleted file mode 100644
--- a/pypy/module/micronumpy/arrayimpl/concrete.py
+++ /dev/null
@@ -1,504 +0,0 @@
-from pypy.module.micronumpy.arrayimpl import base, scalar
-from pypy.module.micronumpy import support, loop, iter
-from pypy.module.micronumpy.base import convert_to_array, W_NDimArray,\
- ArrayArgumentException
-from pypy.module.micronumpy.strides import calc_new_strides, shape_agreement,\
- calculate_broadcast_strides, calculate_dot_strides
-from pypy.module.micronumpy.iter import Chunk, Chunks, NewAxisChunk, RecordChunk
-from pypy.interpreter.error import OperationError, oefmt
-from pypy.interpreter.buffer import RWBuffer
-from rpython.rlib import jit
-from rpython.rtyper.lltypesystem import rffi, lltype
-from rpython.rlib.rawstorage import free_raw_storage, raw_storage_getitem,\
- raw_storage_setitem, RAW_STORAGE
-from rpython.rlib.debug import make_sure_not_resized
-
-
-class BaseConcreteArray(base.BaseArrayImplementation):
- start = 0
- parent = None
-
- # JIT hints that length of all those arrays is a constant
-
- def get_shape(self):
- shape = self.shape
- jit.hint(len(shape), promote=True)
- return shape
-
- def get_strides(self):
- strides = self.strides
- jit.hint(len(strides), promote=True)
- return strides
-
- def get_backstrides(self):
- backstrides = self.backstrides
- jit.hint(len(backstrides), promote=True)
- return backstrides
-
- def getitem(self, index):
- return self.dtype.itemtype.read(self, index, 0)
-
- def getitem_bool(self, index):
- return self.dtype.itemtype.read_bool(self, index, 0)
-
- def setitem(self, index, value):
- self.dtype.itemtype.store(self, index, 0, value)
-
- def setslice(self, space, arr):
- impl = arr.implementation
- if impl.is_scalar():
- self.fill(space, impl.get_scalar_value())
- return
- shape = shape_agreement(space, self.get_shape(), arr)
- if impl.storage == self.storage:
- impl = impl.copy(space)
- loop.setslice(space, shape, self, impl)
-
- def get_size(self):
- return self.size // self.dtype.elsize
-
- def get_storage_size(self):
- return self.size
-
- def reshape(self, space, orig_array, new_shape):
- # Since we got to here, prod(new_shape) == self.size
- new_strides = None
- if self.size > 0:
- new_strides = calc_new_strides(new_shape, self.get_shape(),
- self.get_strides(), self.order)
- if new_strides:
- # We can create a view, strides somehow match up.
- ndims = len(new_shape)
- new_backstrides = [0] * ndims
- for nd in range(ndims):
- new_backstrides[nd] = (new_shape[nd] - 1) * new_strides[nd]
- assert isinstance(orig_array, W_NDimArray) or orig_array is None
- return SliceArray(self.start, new_strides, new_backstrides,
- new_shape, self, orig_array)
- else:
- if self.get_size() == 1 and len(new_shape) == 0:
- return scalar.Scalar(self.dtype, self.getitem(0))
- return None
-
- def get_view(self, space, orig_array, dtype, new_shape):
- strides, backstrides = support.calc_strides(new_shape, dtype,
- self.order)
- return SliceArray(self.start, strides, backstrides, new_shape,
- self, orig_array, dtype=dtype)
-
- def get_real(self, space, orig_array):
- strides = self.get_strides()
- backstrides = self.get_backstrides()
- if self.dtype.is_complex():
- dtype = self.dtype.get_float_dtype(space)
- return SliceArray(self.start, strides, backstrides,
- self.get_shape(), self, orig_array, dtype=dtype)
- return SliceArray(self.start, strides, backstrides,
- self.get_shape(), self, orig_array)
-
- def set_real(self, space, orig_array, w_value):
- tmp = self.get_real(space, orig_array)
- tmp.setslice(space, convert_to_array(space, w_value))
-
- def get_imag(self, space, orig_array):
- strides = self.get_strides()
- backstrides = self.get_backstrides()
- if self.dtype.is_complex():
- dtype = self.dtype.get_float_dtype(space)
- return SliceArray(self.start + dtype.elsize, strides,
- backstrides, self.get_shape(), self, orig_array, dtype=dtype)
- impl = NonWritableArray(self.get_shape(), self.dtype, self.order, strides,
- backstrides)
- if not self.dtype.is_flexible():
- impl.fill(space, self.dtype.box(0))
- return impl
-
- def set_imag(self, space, orig_array, w_value):
- tmp = self.get_imag(space, orig_array)
- tmp.setslice(space, convert_to_array(space, w_value))
-
- # -------------------- applevel get/setitem -----------------------
-
- @jit.unroll_safe
- def _lookup_by_index(self, space, view_w):
- item = self.start
- strides = self.get_strides()
- for i, w_index in enumerate(view_w):
- if space.isinstance_w(w_index, space.w_slice):
- raise IndexError
- idx = support.index_w(space, w_index)
- if idx < 0:
- idx = self.get_shape()[i] + idx
- if idx < 0 or idx >= self.get_shape()[i]:
- raise oefmt(space.w_IndexError,
- "index %d is out of bounds for axis %d with size "
- "%d", idx, i, self.get_shape()[i])
- item += idx * strides[i]
- return item
-
- @jit.unroll_safe
- def _lookup_by_unwrapped_index(self, space, lst):
- item = self.start
- shape = self.get_shape()
- strides = self.get_strides()
- assert len(lst) == len(shape)
- for i, idx in enumerate(lst):
- if idx < 0:
- idx = shape[i] + idx
- if idx < 0 or idx >= shape[i]:
- raise oefmt(space.w_IndexError,
- "index %d is out of bounds for axis %d with size "
- "%d", idx, i, self.get_shape()[i])
- item += idx * strides[i]
- return item
-
- def getitem_index(self, space, index):
- return self.getitem(self._lookup_by_unwrapped_index(space, index))
-
- def setitem_index(self, space, index, value):
- self.setitem(self._lookup_by_unwrapped_index(space, index), value)
-
- @jit.unroll_safe
- def _single_item_index(self, space, w_idx):
- """ Return an index of single item if possible, otherwise raises
- IndexError
- """
- if (space.isinstance_w(w_idx, space.w_str) or
- space.isinstance_w(w_idx, space.w_slice) or
- space.is_w(w_idx, space.w_None)):
- raise IndexError
- if isinstance(w_idx, W_NDimArray) and not isinstance(w_idx.implementation, scalar.Scalar):
- raise ArrayArgumentException
- shape = self.get_shape()
- shape_len = len(shape)
- view_w = None
- if space.isinstance_w(w_idx, space.w_list):
- raise ArrayArgumentException
- if space.isinstance_w(w_idx, space.w_tuple):
- view_w = space.fixedview(w_idx)
- if len(view_w) < shape_len:
- raise IndexError
- if len(view_w) > shape_len:
- # we can allow for one extra None
- count = len(view_w)
- for w_item in view_w:
- if space.is_w(w_item, space.w_None):
- count -= 1
- if count == shape_len:
- raise IndexError # but it's still not a single item
- raise OperationError(space.w_IndexError,
- space.wrap("invalid index"))
- # check for arrays
- for w_item in view_w:
- if (isinstance(w_item, W_NDimArray) or
- space.isinstance_w(w_item, space.w_list)):
- raise ArrayArgumentException
- return self._lookup_by_index(space, view_w)
- if shape_len > 1:
- raise IndexError
- idx = support.index_w(space, w_idx)
- return self._lookup_by_index(space, [space.wrap(idx)])
-
- @jit.unroll_safe
- def _prepare_slice_args(self, space, w_idx):
- if space.isinstance_w(w_idx, space.w_str):
- idx = space.str_w(w_idx)
- dtype = self.dtype
- if not dtype.is_record() or idx not in dtype.fields:
- raise OperationError(space.w_ValueError, space.wrap(
- "field named %s not found" % idx))
- return RecordChunk(idx)
- if (space.isinstance_w(w_idx, space.w_int) or
- space.isinstance_w(w_idx, space.w_slice)):
- return Chunks([Chunk(*space.decode_index4(w_idx, self.get_shape()[0]))])
- elif isinstance(w_idx, W_NDimArray) and \
- isinstance(w_idx.implementation, scalar.Scalar):
- w_idx = w_idx.get_scalar_value().item(space)
- if not space.isinstance_w(w_idx, space.w_int) and \
- not space.isinstance_w(w_idx, space.w_bool):
- raise OperationError(space.w_IndexError, space.wrap(
- "arrays used as indices must be of integer (or boolean) type"))
- return Chunks([Chunk(*space.decode_index4(w_idx, self.get_shape()[0]))])
- elif space.is_w(w_idx, space.w_None):
- return Chunks([NewAxisChunk()])
- result = []
- i = 0
- for w_item in space.fixedview(w_idx):
- if space.is_w(w_item, space.w_None):
- result.append(NewAxisChunk())
- else:
- result.append(Chunk(*space.decode_index4(w_item,
- self.get_shape()[i])))
- i += 1
- return Chunks(result)
-
- def descr_getitem(self, space, orig_arr, w_index):
- try:
- item = self._single_item_index(space, w_index)
- return self.getitem(item)
- except IndexError:
- # not a single result
- chunks = self._prepare_slice_args(space, w_index)
- return chunks.apply(space, orig_arr)
-
- def descr_setitem(self, space, orig_arr, w_index, w_value):
- try:
- item = self._single_item_index(space, w_index)
- self.setitem(item, self.dtype.coerce(space, w_value))
- except IndexError:
- w_value = convert_to_array(space, w_value)
- chunks = self._prepare_slice_args(space, w_index)
- view = chunks.apply(space, orig_arr)
- view.implementation.setslice(space, w_value)
-
- def transpose(self, orig_array):
- if len(self.get_shape()) < 2:
- return self
- strides = []
- backstrides = []
- shape = []
- for i in range(len(self.get_shape()) - 1, -1, -1):
- strides.append(self.get_strides()[i])
- backstrides.append(self.get_backstrides()[i])
- shape.append(self.get_shape()[i])
- return SliceArray(self.start, strides,
- backstrides, shape, self, orig_array)
-
- def copy(self, space):
- strides, backstrides = support.calc_strides(self.get_shape(), self.dtype,
- self.order)
- impl = ConcreteArray(self.get_shape(), self.dtype, self.order, strides,
- backstrides)
- return loop.setslice(space, self.get_shape(), impl, self)
-
- def create_axis_iter(self, shape, dim, cum):
- return iter.AxisIterator(self, shape, dim, cum)
-
- def create_dot_iter(self, shape, skip):
- r = calculate_dot_strides(self.get_strides(), self.get_backstrides(),
- shape, skip)
- return iter.MultiDimViewIterator(self, self.start, r[0], r[1], shape)
-
- def swapaxes(self, space, orig_arr, axis1, axis2):
- shape = self.get_shape()[:]
- strides = self.get_strides()[:]
- backstrides = self.get_backstrides()[:]
- shape[axis1], shape[axis2] = shape[axis2], shape[axis1]
- strides[axis1], strides[axis2] = strides[axis2], strides[axis1]
- backstrides[axis1], backstrides[axis2] = backstrides[axis2], backstrides[axis1]
- return W_NDimArray.new_slice(space, self.start, strides,
- backstrides, shape, self, orig_arr)
-
- def nonzero(self, space, index_type):
- s = loop.count_all_true_concrete(self)
- box = index_type.itemtype.box
- nd = len(self.get_shape())
- w_res = W_NDimArray.from_shape(space, [s, nd], index_type)
- loop.nonzero(w_res, self, box)
- w_res = w_res.implementation.swapaxes(space, w_res, 0, 1)
- l_w = [w_res.descr_getitem(space, space.wrap(d)) for d in range(nd)]
- return space.newtuple(l_w)
-
- def get_storage_as_int(self, space):
- return rffi.cast(lltype.Signed, self.storage) + self.start
-
- def get_storage(self):
- return self.storage
-
- def get_buffer(self, space):
- return ArrayBuffer(self)
-
- def astype(self, space, dtype):
- strides, backstrides = support.calc_strides(self.get_shape(), dtype,
- self.order)
- impl = ConcreteArray(self.get_shape(), dtype, self.order,
- strides, backstrides)
- loop.setslice(space, impl.get_shape(), impl, self)
- return impl
-
-
-class ConcreteArrayNotOwning(BaseConcreteArray):
- def __init__(self, shape, dtype, order, strides, backstrides, storage):
-
- make_sure_not_resized(shape)
- make_sure_not_resized(strides)
- make_sure_not_resized(backstrides)
- self.shape = shape
- self.size = support.product(shape) * dtype.elsize
- self.order = order
- self.dtype = dtype
- self.strides = strides
- self.backstrides = backstrides
- self.storage = storage
-
- def create_iter(self, shape=None, backward_broadcast=False, require_index=False):
- if shape is not None and \
- support.product(shape) > support.product(self.get_shape()):
- r = calculate_broadcast_strides(self.get_strides(),
- self.get_backstrides(),
- self.get_shape(), shape,
- backward_broadcast)
- return iter.MultiDimViewIterator(self, self.start,
- r[0], r[1], shape)
- if not require_index:
- return iter.ConcreteArrayIterator(self)
- if len(self.get_shape()) == 1:
- return iter.OneDimViewIterator(self, self.start,
- self.get_strides(),
- self.get_shape())
- return iter.MultiDimViewIterator(self, self.start,
- self.get_strides(),
- self.get_backstrides(),
- self.get_shape())
-
- def fill(self, space, box):
- self.dtype.itemtype.fill(self.storage, self.dtype.elsize,
- box, 0, self.size, 0)
-
- def set_shape(self, space, orig_array, new_shape):
- strides, backstrides = support.calc_strides(new_shape, self.dtype,
- self.order)
- return SliceArray(0, strides, backstrides, new_shape, self,
- orig_array)
-
- def set_dtype(self, space, dtype):
- self.dtype = dtype
-
- def argsort(self, space, w_axis):
- from pypy.module.micronumpy.arrayimpl.sort import argsort_array
- return argsort_array(self, space, w_axis)
-
- def sort(self, space, w_axis, w_order):
- from pypy.module.micronumpy.arrayimpl.sort import sort_array
- return sort_array(self, space, w_axis, w_order)
-
- def base(self):
- return None
-
-
-class ConcreteArray(ConcreteArrayNotOwning):
- def __init__(self, shape, dtype, order, strides, backstrides, storage=lltype.nullptr(RAW_STORAGE)):
- null_storage = lltype.nullptr(RAW_STORAGE)
- ConcreteArrayNotOwning.__init__(self, shape, dtype, order, strides, backstrides,
- null_storage)
- if storage == lltype.nullptr(RAW_STORAGE):
- self.storage = dtype.itemtype.malloc(self.size)
- else:
- self.storage = storage
-
- def __del__(self):
- free_raw_storage(self.storage, track_allocation=False)
-
-class ConcreteArrayWithBase(ConcreteArrayNotOwning):
- def __init__(self, shape, dtype, order, strides, backstrides, storage, orig_base):
- ConcreteArrayNotOwning.__init__(self, shape, dtype, order,
- strides, backstrides, storage)
- self.orig_base = orig_base
-
- def base(self):
- return self.orig_base
-
-
-class ConcreteNonWritableArrayWithBase(ConcreteArrayWithBase):
- def descr_setitem(self, space, orig_array, w_index, w_value):
- raise OperationError(space.w_ValueError, space.wrap(
- "assignment destination is read-only"))
-
-
-class NonWritableArray(ConcreteArray):
- def descr_setitem(self, space, orig_array, w_index, w_value):
- raise OperationError(space.w_ValueError, space.wrap(
- "assignment destination is read-only"))
-
-
-class SliceArray(BaseConcreteArray):
- def __init__(self, start, strides, backstrides, shape, parent, orig_arr,
- dtype=None):
- self.strides = strides
- self.backstrides = backstrides
- self.shape = shape
- if dtype is None:
- dtype = parent.dtype
- if isinstance(parent, SliceArray):
- parent = parent.parent # one level only
- self.parent = parent
- self.storage = parent.storage
- self.order = parent.order
- self.dtype = dtype
- self.size = support.product(shape) * self.dtype.elsize
- self.start = start
- self.orig_arr = orig_arr
-
- def base(self):
- return self.orig_arr
-
- def fill(self, space, box):
- loop.fill(self, box.convert_to(space, self.dtype))
-
- def create_iter(self, shape=None, backward_broadcast=False, require_index=False):
- if shape is not None and \
- support.product(shape) > support.product(self.get_shape()):
- r = calculate_broadcast_strides(self.get_strides(),
- self.get_backstrides(),
- self.get_shape(), shape,
- backward_broadcast)
- return iter.MultiDimViewIterator(self, self.start,
- r[0], r[1], shape)
- if len(self.get_shape()) == 1:
- return iter.OneDimViewIterator(self, self.start,
- self.get_strides(),
- self.get_shape())
- return iter.MultiDimViewIterator(self, self.start,
- self.get_strides(),
- self.get_backstrides(),
- self.get_shape())
-
- def set_shape(self, space, orig_array, new_shape):
- if len(self.get_shape()) < 2 or self.size == 0:
- # TODO: this code could be refactored into calc_strides
- # but then calc_strides would have to accept a stepping factor
- strides = []
- backstrides = []
- dtype = self.dtype
- s = self.get_strides()[0] // dtype.elsize
- if self.order == 'C':
- new_shape.reverse()
- for sh in new_shape:
- strides.append(s * dtype.elsize)
- backstrides.append(s * (sh - 1) * dtype.elsize)
- s *= max(1, sh)
- if self.order == 'C':
- strides.reverse()
- backstrides.reverse()
- new_shape.reverse()
- return SliceArray(self.start, strides, backstrides, new_shape,
- self, orig_array)
- new_strides = calc_new_strides(new_shape, self.get_shape(),
- self.get_strides(),
- self.order)
- if new_strides is None:
- raise OperationError(space.w_AttributeError, space.wrap(
- "incompatible shape for a non-contiguous array"))
- new_backstrides = [0] * len(new_shape)
- for nd in range(len(new_shape)):
- new_backstrides[nd] = (new_shape[nd] - 1) * new_strides[nd]
- return SliceArray(self.start, new_strides, new_backstrides, new_shape,
- self, orig_array)
-
-
-class ArrayBuffer(RWBuffer):
- def __init__(self, impl):
- self.impl = impl
-
- def getitem(self, item):
- return raw_storage_getitem(lltype.Char, self.impl.storage, item)
-
- def setitem(self, item, v):
- raw_storage_setitem(self.impl.storage, item,
- rffi.cast(lltype.Char, v))
-
- def getlength(self):
- return self.impl.size
-
- def get_raw_address(self):
- return self.impl.storage
diff --git a/pypy/module/micronumpy/arrayimpl/scalar.py b/pypy/module/micronumpy/arrayimpl/scalar.py
deleted file mode 100644
--- a/pypy/module/micronumpy/arrayimpl/scalar.py
+++ /dev/null
@@ -1,209 +0,0 @@
-from pypy.module.micronumpy.arrayimpl import base
-from pypy.module.micronumpy.base import W_NDimArray, convert_to_array
-from pypy.module.micronumpy import support
-from pypy.interpreter.error import OperationError
-
-class ScalarIterator(base.BaseArrayIterator):
- def __init__(self, v):
- self.v = v
- self.called_once = False
-
- def next(self):
- self.called_once = True
-
- def next_skip_x(self, n):
- self.called_once = True
-
- def getitem(self):
- return self.v.get_scalar_value()
-
- def getitem_bool(self):
- return self.v.dtype.itemtype.bool(self.v.value)
-
- def setitem(self, v):
- self.v.set_scalar_value(v)
-
- def done(self):
- return self.called_once
-
- def reset(self):
- pass
-
-class Scalar(base.BaseArrayImplementation):
- def __init__(self, dtype, value=None):
- self.dtype = dtype
- self.value = value
-
- def is_scalar(self):
- return True
-
- def get_shape(self):
- return []
-
- def get_strides(self):
- return []
-
- def get_backstrides(self):
- return []
-
- def create_iter(self, shape=None, backward_broadcast=False, require_index=False):
- return ScalarIterator(self)
-
- def get_scalar_value(self):
- return self.value
-
- def set_scalar_value(self, w_val):
- self.value = w_val
-
- def copy(self, space):
- scalar = Scalar(self.dtype)
- scalar.value = self.value
- return scalar
-
- def get_size(self):
- return 1
-
- def transpose(self, _):
- return self
-
- def get_view(self, space, orig_array, dtype, new_shape):
- scalar = Scalar(dtype)
- if dtype.is_str_or_unicode():
- scalar.value = dtype.coerce(space, space.wrap(self.value.raw_str()))
- elif dtype.is_record():
- raise OperationError(space.w_NotImplementedError, space.wrap(
- "viewing scalar as record not implemented"))
- else:
- scalar.value = dtype.itemtype.runpack_str(space, self.value.raw_str())
- return scalar
-
- def get_real(self, space, orig_array):
- if self.dtype.is_complex():
- scalar = Scalar(self.dtype.get_float_dtype(space))
- scalar.value = self.value.convert_real_to(scalar.dtype)
- return scalar
- return self
-
- def set_real(self, space, orig_array, w_val):
- w_arr = convert_to_array(space, w_val)
- if len(w_arr.get_shape()) > 0:
- raise OperationError(space.w_ValueError, space.wrap(
- "could not broadcast input array from shape " +
- "(%s) into shape ()" % (
- ','.join([str(x) for x in w_arr.get_shape()],))))
- if self.dtype.is_complex():
- dtype = self.dtype.get_float_dtype(space)
- self.value = self.dtype.itemtype.composite(
- w_arr.get_scalar_value().convert_to(space, dtype),
- self.value.convert_imag_to(dtype))
- else:
- self.value = w_arr.get_scalar_value()
-
- def get_imag(self, space, orig_array):
- if self.dtype.is_complex():
- scalar = Scalar(self.dtype.get_float_dtype(space))
- scalar.value = self.value.convert_imag_to(scalar.dtype)
- return scalar
- scalar = Scalar(self.dtype)
- scalar.value = scalar.dtype.coerce(space, None)
- return scalar
-
- def set_imag(self, space, orig_array, w_val):
- #Only called on complex dtype
- assert self.dtype.is_complex()
- w_arr = convert_to_array(space, w_val)
- if len(w_arr.get_shape()) > 0:
- raise OperationError(space.w_ValueError, space.wrap(
- "could not broadcast input array from shape " +
- "(%s) into shape ()" % (
- ','.join([str(x) for x in w_arr.get_shape()],))))
- dtype = self.dtype.get_float_dtype(space)
- self.value = self.dtype.itemtype.composite(
- self.value.convert_real_to(dtype),
- w_arr.get_scalar_value().convert_to(space, dtype))
-
- def descr_getitem(self, space, _, w_idx):
- if space.isinstance_w(w_idx, space.w_tuple):
- if space.len_w(w_idx) == 0:
- return self.get_scalar_value()
- elif space.isinstance_w(w_idx, space.w_str):
- if self.dtype.is_record():
- w_val = self.value.descr_getitem(space, w_idx)
- return convert_to_array(space, w_val)
- elif space.is_none(w_idx):
- new_shape = [1]
- arr = W_NDimArray.from_shape(space, new_shape, self.dtype)
- arr_iter = arr.create_iter(new_shape)
- arr_iter.setitem(self.value)
- return arr
- raise OperationError(space.w_IndexError,
- space.wrap("0-d arrays can't be indexed"))
-
- def getitem_index(self, space, idx):
- raise OperationError(space.w_IndexError,
- space.wrap("0-d arrays can't be indexed"))
-
- def descr_setitem(self, space, _, w_idx, w_val):
- if space.isinstance_w(w_idx, space.w_tuple):
- if space.len_w(w_idx) == 0:
- return self.set_scalar_value(self.dtype.coerce(space, w_val))
- elif space.isinstance_w(w_idx, space.w_str):
- if self.dtype.is_record():
- return self.value.descr_setitem(space, w_idx, w_val)
- raise OperationError(space.w_IndexError,
- space.wrap("0-d arrays can't be indexed"))
-
- def setitem_index(self, space, idx, w_val):
- raise OperationError(space.w_IndexError,
- space.wrap("0-d arrays can't be indexed"))
-
- def set_shape(self, space, orig_array, new_shape):
- if not new_shape:
- return self
- if support.product(new_shape) == 1:
- arr = W_NDimArray.from_shape(space, new_shape, self.dtype)
- arr_iter = arr.create_iter(new_shape)
- arr_iter.setitem(self.value)
- return arr.implementation
- raise OperationError(space.w_ValueError, space.wrap(
- "total size of the array must be unchanged"))
-
- def set_dtype(self, space, dtype):
- self.value = self.value.convert_to(space, dtype)
- self.dtype = dtype
-
- def reshape(self, space, orig_array, new_shape):
- return self.set_shape(space, orig_array, new_shape)
-
- def create_axis_iter(self, shape, dim, cum):
- raise Exception("axis iter should not happen on scalar")
-
- def swapaxes(self, space, orig_array, axis1, axis2):
- raise Exception("should not be called")
-
- def nonzero(self, space, index_type):
- s = self.dtype.itemtype.bool(self.value)
- w_res = W_NDimArray.from_shape(space, [s], index_type)
- if s == 1:
- w_res.implementation.setitem(0, index_type.itemtype.box(0))
- return space.newtuple([w_res])
-
- def fill(self, space, w_value):
- self.value = w_value
-
- def get_storage_as_int(self, space):
- raise OperationError(space.w_ValueError,
- space.wrap("scalars have no address"))
-
- def argsort(self, space, w_axis):
- return space.wrap(0)
-
- def astype(self, space, dtype):
- raise Exception("should not be called")
-
- def base(self):
- return None
-
- def get_buffer(self, space):
- raise OperationError(space.w_ValueError, space.wrap(
- "cannot point buffer to a scalar"))
diff --git a/pypy/module/micronumpy/arrayimpl/sort.py b/pypy/module/micronumpy/arrayimpl/sort.py
deleted file mode 100644
--- a/pypy/module/micronumpy/arrayimpl/sort.py
+++ /dev/null
@@ -1,361 +0,0 @@
-
-""" This is the implementation of various sorting routines in numpy. It's here
-because it only makes sense on a concrete array
-"""
-
-from rpython.rtyper.lltypesystem import rffi, lltype
-from rpython.rlib.listsort import make_timsort_class
-from rpython.rlib.rawstorage import raw_storage_getitem, raw_storage_setitem, \
- free_raw_storage, alloc_raw_storage
-from rpython.rlib.unroll import unrolling_iterable
-from rpython.rlib.rarithmetic import widen
-from rpython.rlib.objectmodel import specialize
-from pypy.interpreter.error import OperationError, oefmt
-from pypy.module.micronumpy.base import W_NDimArray
-from pypy.module.micronumpy import interp_dtype, types, constants as NPY
-from pypy.module.micronumpy.iter import AxisIterator
-
-INT_SIZE = rffi.sizeof(lltype.Signed)
-
-def make_argsort_function(space, itemtype, comp_type, count=1):
- TP = itemtype.T
- step = rffi.sizeof(TP)
-
- class Repr(object):
- def __init__(self, index_stride_size, stride_size, size, values,
- indexes, index_start, start):
- self.index_stride_size = index_stride_size
- self.stride_size = stride_size
- self.index_start = index_start
- self.start = start
- self.size = size
- self.values = values
- self.indexes = indexes
-
- def getitem(self, item):
- if count < 2:
- v = raw_storage_getitem(TP, self.values, item * self.stride_size
- + self.start)
- else:
- v = []
- for i in range(count):
- _v = raw_storage_getitem(TP, self.values, item * self.stride_size
- + self.start + step * i)
- v.append(_v)
- if comp_type == 'int':
- v = widen(v)
- elif comp_type == 'float':
- v = float(v)
- elif comp_type == 'complex':
- v = [float(v[0]),float(v[1])]
- else:
- raise NotImplementedError('cannot reach')
- return (v, raw_storage_getitem(lltype.Signed, self.indexes,
- item * self.index_stride_size +
- self.index_start))
-
- def setitem(self, idx, item):
- if count < 2:
- raw_storage_setitem(self.values, idx * self.stride_size +
- self.start, rffi.cast(TP, item[0]))
- else:
- i = 0
- for val in item[0]:
- raw_storage_setitem(self.values, idx * self.stride_size +
- self.start + i*step, rffi.cast(TP, val))
- i += 1
- raw_storage_setitem(self.indexes, idx * self.index_stride_size +
- self.index_start, item[1])
-
- class ArgArrayRepWithStorage(Repr):
- def __init__(self, index_stride_size, stride_size, size):
- start = 0
- dtype = interp_dtype.get_dtype_cache(space).w_longdtype
- indexes = dtype.itemtype.malloc(size * dtype.elsize)
- values = alloc_raw_storage(size * stride_size,
- track_allocation=False)
- Repr.__init__(self, dtype.elsize, stride_size,
- size, values, indexes, start, start)
-
- def __del__(self):
- free_raw_storage(self.indexes, track_allocation=False)
- free_raw_storage(self.values, track_allocation=False)
-
- def arg_getitem(lst, item):
- return lst.getitem(item)
-
- def arg_setitem(lst, item, value):
- lst.setitem(item, value)
-
- def arg_length(lst):
- return lst.size
-
- def arg_getitem_slice(lst, start, stop):
- retval = ArgArrayRepWithStorage(lst.index_stride_size, lst.stride_size,
- stop-start)
- for i in range(stop-start):
- retval.setitem(i, lst.getitem(i+start))
- return retval
-
- if count < 2:
- def arg_lt(a, b):
- # Does numpy do <= ?
- return a[0] < b[0] or b[0] != b[0] and a[0] == a[0]
- else:
- def arg_lt(a, b):
- for i in range(count):
- if b[0][i] != b[0][i] and a[0][i] == a[0][i]:
- return True
- elif b[0][i] == b[0][i] and a[0][i] != a[0][i]:
- return False
- for i in range(count):
- if a[0][i] < b[0][i]:
- return True
- elif a[0][i] > b[0][i]:
- return False
- # Does numpy do True?
- return False
-
- ArgSort = make_timsort_class(arg_getitem, arg_setitem, arg_length,
- arg_getitem_slice, arg_lt)
-
- def argsort(arr, space, w_axis, itemsize):
- if w_axis is space.w_None:
- # note that it's fine ot pass None here as we're not going
- # to pass the result around (None is the link to base in slices)
- if arr.get_size() > 0:
- arr = arr.reshape(space, None, [arr.get_size()])
- axis = 0
- elif w_axis is None:
- axis = -1
- else:
- axis = space.int_w(w_axis)
- # create array of indexes
- dtype = interp_dtype.get_dtype_cache(space).w_longdtype
- index_arr = W_NDimArray.from_shape(space, arr.get_shape(), dtype)
- storage = index_arr.implementation.get_storage()
- if len(arr.get_shape()) == 1:
- for i in range(arr.get_size()):
- raw_storage_setitem(storage, i * INT_SIZE, i)
- r = Repr(INT_SIZE, itemsize, arr.get_size(), arr.get_storage(),
- storage, 0, arr.start)
- ArgSort(r).sort()
- else:
- shape = arr.get_shape()
- if axis < 0:
- axis = len(shape) + axis
- if axis < 0 or axis >= len(shape):
- raise OperationError(space.w_IndexError, space.wrap(
- "Wrong axis %d" % axis))
- iterable_shape = shape[:axis] + [0] + shape[axis + 1:]
- iter = AxisIterator(arr, iterable_shape, axis, False)
- index_impl = index_arr.implementation
- index_iter = AxisIterator(index_impl, iterable_shape, axis, False)
- stride_size = arr.strides[axis]
- index_stride_size = index_impl.strides[axis]
- axis_size = arr.shape[axis]
- while not iter.done():
- for i in range(axis_size):
- raw_storage_setitem(storage, i * index_stride_size +
- index_iter.offset, i)
- r = Repr(index_stride_size, stride_size, axis_size,
- arr.get_storage(), storage, index_iter.offset, iter.offset)
- ArgSort(r).sort()
- iter.next()
- index_iter.next()
- return index_arr
-
- return argsort
-
-def argsort_array(arr, space, w_axis):
- cache = space.fromcache(ArgSortCache) # that populates ArgSortClasses
- itemtype = arr.dtype.itemtype
- for tp in all_types:
- if isinstance(itemtype, tp[0]):
- return cache._lookup(tp)(arr, space, w_axis,
- itemtype.get_element_size())
- # XXX this should probably be changed
- raise oefmt(space.w_NotImplementedError,
- "sorting of non-numeric types '%s' is not implemented",
- arr.dtype.get_name())
-
-all_types = (types.all_float_types + types.all_complex_types +
- types.all_int_types)
-all_types = [i for i in all_types if not '_mixin_' in i[0].__dict__]
-all_types = unrolling_iterable(all_types)
-
-def make_sort_function(space, itemtype, comp_type, count=1):
- TP = itemtype.T
- step = rffi.sizeof(TP)
-
- class Repr(object):
- def __init__(self, stride_size, size, values, start):
- self.stride_size = stride_size
- self.start = start
- self.size = size
- self.values = values
-
- def getitem(self, item):
- if count < 2:
- v = raw_storage_getitem(TP, self.values, item * self.stride_size
- + self.start)
- else:
- v = []
- for i in range(count):
- _v = raw_storage_getitem(TP, self.values, item * self.stride_size
- + self.start + step * i)
- v.append(_v)
- if comp_type == 'int':
- v = widen(v)
- elif comp_type == 'float':
- v = float(v)
- elif comp_type == 'complex':
- v = [float(v[0]),float(v[1])]
- else:
- raise NotImplementedError('cannot reach')
- return (v)
-
- def setitem(self, idx, item):
- if count < 2:
- raw_storage_setitem(self.values, idx * self.stride_size +
- self.start, rffi.cast(TP, item))
- else:
- i = 0
- for val in item:
- raw_storage_setitem(self.values, idx * self.stride_size +
- self.start + i*step, rffi.cast(TP, val))
- i += 1
-
- class ArgArrayRepWithStorage(Repr):
- def __init__(self, stride_size, size):
- start = 0
- values = alloc_raw_storage(size * stride_size,
- track_allocation=False)
- Repr.__init__(self, stride_size,
- size, values, start)
-
- def __del__(self):
- free_raw_storage(self.values, track_allocation=False)
-
- def arg_getitem(lst, item):
- return lst.getitem(item)
-
- def arg_setitem(lst, item, value):
- lst.setitem(item, value)
-
- def arg_length(lst):
- return lst.size
-
- def arg_getitem_slice(lst, start, stop):
- retval = ArgArrayRepWithStorage(lst.stride_size, stop-start)
- for i in range(stop-start):
- retval.setitem(i, lst.getitem(i+start))
- return retval
-
- if count < 2:
- def arg_lt(a, b):
- # handles NAN and INF
- return a < b or b != b and a == a
- else:
- def arg_lt(a, b):
- for i in range(count):
- if b[i] != b[i] and a[i] == a[i]:
- return True
- elif b[i] == b[i] and a[i] != a[i]:
- return False
- for i in range(count):
- if a[i] < b[i]:
- return True
- elif a[i] > b[i]:
- return False
- # Does numpy do True?
- return False
-
- ArgSort = make_timsort_class(arg_getitem, arg_setitem, arg_length,
- arg_getitem_slice, arg_lt)
-
- def sort(arr, space, w_axis, itemsize):
- if w_axis is space.w_None:
- # note that it's fine to pass None here as we're not going
- # to pass the result around (None is the link to base in slices)
- arr = arr.reshape(space, None, [arr.get_size()])
- axis = 0
- elif w_axis is None:
- axis = -1
- else:
- axis = space.int_w(w_axis)
- # create array of indexes
- if len(arr.get_shape()) == 1:
- r = Repr(itemsize, arr.get_size(), arr.get_storage(),
- arr.start)
- ArgSort(r).sort()
- else:
- shape = arr.get_shape()
- if axis < 0:
- axis = len(shape) + axis
- if axis < 0 or axis >= len(shape):
- raise OperationError(space.w_IndexError, space.wrap(
- "Wrong axis %d" % axis))
- iterable_shape = shape[:axis] + [0] + shape[axis + 1:]
- iter = AxisIterator(arr, iterable_shape, axis, False)
- stride_size = arr.strides[axis]
- axis_size = arr.shape[axis]
- while not iter.done():
- r = Repr(stride_size, axis_size, arr.get_storage(), iter.offset)
- ArgSort(r).sort()
- iter.next()
-
- return sort
-
-def sort_array(arr, space, w_axis, w_order):
- cache = space.fromcache(SortCache) # that populates SortClasses
- itemtype = arr.dtype.itemtype
- if arr.dtype.byteorder == NPY.OPPBYTE:
- raise oefmt(space.w_NotImplementedError,
- "sorting of non-native byteorder not supported yet")
- for tp in all_types:
- if isinstance(itemtype, tp[0]):
- return cache._lookup(tp)(arr, space, w_axis,
- itemtype.get_element_size())
- # XXX this should probably be changed
- raise oefmt(space.w_NotImplementedError,
- "sorting of non-numeric types '%s' is not implemented",
- arr.dtype.get_name())
-
-all_types = (types.all_float_types + types.all_complex_types +
- types.all_int_types)
-all_types = [i for i in all_types if not issubclass(i[0], types.Float16)]
-all_types = unrolling_iterable(all_types)
-
-class ArgSortCache(object):
- built = False
-
- def __init__(self, space):
- if self.built:
- return
- self.built = True
- cache = {}
- for cls, it in all_types._items:
- if it == 'complex':
- cache[cls] = make_argsort_function(space, cls, it, 2)
- else:
- cache[cls] = make_argsort_function(space, cls, it)
- self.cache = cache
- self._lookup = specialize.memo()(lambda tp : cache[tp[0]])
-
-
-class SortCache(object):
- built = False
-
- def __init__(self, space):
- if self.built:
- return
- self.built = True
- cache = {}
- for cls, it in all_types._items:
- if it == 'complex':
- cache[cls] = make_sort_function(space, cls, it, 2)
- else:
- cache[cls] = make_sort_function(space, cls, it)
- self.cache = cache
- self._lookup = specialize.memo()(lambda tp : cache[tp[0]])
diff --git a/pypy/module/micronumpy/arrayimpl/voidbox.py b/pypy/module/micronumpy/arrayimpl/voidbox.py
deleted file mode 100644
--- a/pypy/module/micronumpy/arrayimpl/voidbox.py
+++ /dev/null
@@ -1,12 +0,0 @@
-
-from pypy.module.micronumpy.arrayimpl.base import BaseArrayImplementation
-from rpython.rlib.rawstorage import free_raw_storage, alloc_raw_storage
-
-class VoidBoxStorage(BaseArrayImplementation):
- def __init__(self, size, dtype):
- self.storage = alloc_raw_storage(size)
- self.dtype = dtype
- self.size = size
-
- def __del__(self):
- free_raw_storage(self.storage)
diff --git a/pypy/module/micronumpy/arrayops.py b/pypy/module/micronumpy/arrayops.py
new file mode 100644
--- /dev/null
+++ b/pypy/module/micronumpy/arrayops.py
@@ -0,0 +1,281 @@
+from pypy.module.micronumpy.base import convert_to_array, W_NDimArray
+from pypy.module.micronumpy import loop, descriptor, ufuncs
+from pypy.module.micronumpy.strides import Chunk, Chunks, shape_agreement, \
+ shape_agreement_multiple
+from pypy.interpreter.error import OperationError, oefmt
+from pypy.interpreter.gateway import unwrap_spec
+from pypy.module.micronumpy.converters import clipmode_converter
+from pypy.module.micronumpy import support
+from pypy.module.micronumpy import constants as NPY
+
+def where(space, w_arr, w_x=None, w_y=None):
+ """where(condition, [x, y])
+
+ Return elements, either from `x` or `y`, depending on `condition`.
+
+ If only `condition` is given, return ``condition.nonzero()``.
+
+ Parameters
+ ----------
+ condition : array_like, bool
+ When True, yield `x`, otherwise yield `y`.
+ x, y : array_like, optional
+ Values from which to choose. `x` and `y` need to have the same
+ shape as `condition`.
+
+ Returns
+ -------
+ out : ndarray or tuple of ndarrays
+ If both `x` and `y` are specified, the output array contains
+ elements of `x` where `condition` is True, and elements from
+ `y` elsewhere.
+
+ If only `condition` is given, return the tuple
+ ``condition.nonzero()``, the indices where `condition` is True.
+
+ See Also
+ --------
+ nonzero, choose
+
+ Notes
+ -----
+ If `x` and `y` are given and input arrays are 1-D, `where` is
+ equivalent to::
+
+ [xv if c else yv for (c,xv,yv) in zip(condition,x,y)]
+
+ Examples
+ --------
+ >>> np.where([[True, False], [True, True]],
+ ... [[1, 2], [3, 4]],
+ ... [[9, 8], [7, 6]])
+ array([[1, 8],
+ [3, 4]])
+
+ >>> np.where([[0, 1], [1, 0]])
+ (array([0, 1]), array([1, 0]))
+
+ >>> x = np.arange(9.).reshape(3, 3)
+ >>> np.where( x > 5 )
+ (array([2, 2, 2]), array([0, 1, 2]))
+ >>> x[np.where( x > 3.0 )] # Note: result is 1D.
+ array([ 4., 5., 6., 7., 8.])
+ >>> np.where(x < 5, x, -1) # Note: broadcasting.
+ array([[ 0., 1., 2.],
+ [ 3., 4., -1.],
+ [-1., -1., -1.]])
+
+
+ NOTE: support for not passing x and y is unsupported
+ """
+ if space.is_none(w_y):
+ if space.is_none(w_x):
+ raise OperationError(space.w_NotImplementedError, space.wrap(
+ "1-arg where unsupported right now"))
+ raise OperationError(space.w_ValueError, space.wrap(
+ "Where should be called with either 1 or 3 arguments"))
+ if space.is_none(w_x):
+ raise OperationError(space.w_ValueError, space.wrap(
+ "Where should be called with either 1 or 3 arguments"))
+ arr = convert_to_array(space, w_arr)
+ x = convert_to_array(space, w_x)
+ y = convert_to_array(space, w_y)
+ if x.is_scalar() and y.is_scalar() and arr.is_scalar():
+ if arr.get_dtype().itemtype.bool(arr.get_scalar_value()):
+ return x
+ return y
+ dtype = ufuncs.find_binop_result_dtype(space, x.get_dtype(),
+ y.get_dtype())
+ shape = shape_agreement(space, arr.get_shape(), x)
+ shape = shape_agreement(space, shape, y)
+ out = W_NDimArray.from_shape(space, shape, dtype)
+ return loop.where(space, out, shape, arr, x, y, dtype)
+
+def dot(space, w_obj1, w_obj2, w_out=None):
+ w_arr = convert_to_array(space, w_obj1)
+ if w_arr.is_scalar():
+ return convert_to_array(space, w_obj2).descr_dot(space, w_arr, w_out)
+ return w_arr.descr_dot(space, w_obj2, w_out)
+
+
+def concatenate(space, w_args, w_axis=None):
+ args_w = space.listview(w_args)
+ if len(args_w) == 0:
+ raise oefmt(space.w_ValueError, "need at least one array to concatenate")
+ args_w = [convert_to_array(space, w_arg) for w_arg in args_w]
+ if w_axis is None:
+ w_axis = space.wrap(0)
+ if space.is_none(w_axis):
+ args_w = [w_arg.reshape(space,
+ space.newlist([w_arg.descr_get_size(space)]))
+ for w_arg in args_w]
+ w_axis = space.wrap(0)
+ dtype = args_w[0].get_dtype()
+ shape = args_w[0].get_shape()[:]
+ ndim = len(shape)
+ if ndim == 0:
+ raise oefmt(space.w_ValueError,
+ "zero-dimensional arrays cannot be concatenated")
+ axis = space.int_w(w_axis)
+ orig_axis = axis
+ if axis < 0:
+ axis = ndim + axis
+ if ndim == 1 and axis != 0:
+ axis = 0
+ if axis < 0 or axis >= ndim:
+ raise oefmt(space.w_IndexError, "axis %d out of bounds [0, %d)",
+ orig_axis, ndim)
+ for arr in args_w[1:]:
+ if len(arr.get_shape()) != ndim:
+ raise OperationError(space.w_ValueError, space.wrap(
+ "all the input arrays must have same number of dimensions"))
+ for i, axis_size in enumerate(arr.get_shape()):
+ if i == axis:
+ shape[i] += axis_size
+ elif axis_size != shape[i]:
+ raise OperationError(space.w_ValueError, space.wrap(
+ "all the input array dimensions except for the "
+ "concatenation axis must match exactly"))
+ a_dt = arr.get_dtype()
+ if dtype.is_record() and a_dt.is_record():
+ # Record types must match
+ for f in dtype.fields:
+ if f not in a_dt.fields or \
+ dtype.fields[f] != a_dt.fields[f]:
+ raise OperationError(space.w_TypeError,
+ space.wrap("invalid type promotion"))
+ elif dtype.is_record() or a_dt.is_record():
+ raise OperationError(space.w_TypeError,
+ space.wrap("invalid type promotion"))
+ dtype = ufuncs.find_binop_result_dtype(space, dtype,
+ arr.get_dtype())
+ # concatenate does not handle ndarray subtypes, it always returns a ndarray
+ res = W_NDimArray.from_shape(space, shape, dtype, 'C')
+ chunks = [Chunk(0, i, 1, i) for i in shape]
+ axis_start = 0
+ for arr in args_w:
+ if arr.get_shape()[axis] == 0:
+ continue
+ chunks[axis] = Chunk(axis_start, axis_start + arr.get_shape()[axis], 1,
+ arr.get_shape()[axis])
+ Chunks(chunks).apply(space, res).implementation.setslice(space, arr)
+ axis_start += arr.get_shape()[axis]
+ return res
+
+ at unwrap_spec(repeats=int)
+def repeat(space, w_arr, repeats, w_axis):
+ arr = convert_to_array(space, w_arr)
+ if space.is_none(w_axis):
+ arr = arr.descr_flatten(space)
+ orig_size = arr.get_shape()[0]
+ shape = [arr.get_shape()[0] * repeats]
+ w_res = W_NDimArray.from_shape(space, shape, arr.get_dtype(), w_instance=arr)
+ for i in range(repeats):
+ Chunks([Chunk(i, shape[0] - repeats + i, repeats,
+ orig_size)]).apply(space, w_res).implementation.setslice(space, arr)
+ else:
+ axis = space.int_w(w_axis)
+ shape = arr.get_shape()[:]
+ chunks = [Chunk(0, i, 1, i) for i in shape]
+ orig_size = shape[axis]
+ shape[axis] *= repeats
+ w_res = W_NDimArray.from_shape(space, shape, arr.get_dtype(), w_instance=arr)
+ for i in range(repeats):
+ chunks[axis] = Chunk(i, shape[axis] - repeats + i, repeats,
+ orig_size)
+ Chunks(chunks).apply(space, w_res).implementation.setslice(space, arr)
+ return w_res
+
+def count_nonzero(space, w_obj):
+ return space.wrap(loop.count_all_true(convert_to_array(space, w_obj)))
+
+def choose(space, w_arr, w_choices, w_out, w_mode):
+ arr = convert_to_array(space, w_arr)
+ choices = [convert_to_array(space, w_item) for w_item
+ in space.listview(w_choices)]
+ if not choices:
+ raise OperationError(space.w_ValueError,
+ space.wrap("choices list cannot be empty"))
+ if space.is_none(w_out):
+ w_out = None
+ elif not isinstance(w_out, W_NDimArray):
+ raise OperationError(space.w_TypeError, space.wrap(
+ "return arrays must be of ArrayType"))
+ shape = shape_agreement_multiple(space, choices + [w_out])
+ out = descriptor.dtype_agreement(space, choices, shape, w_out)
+ dtype = out.get_dtype()
+ mode = clipmode_converter(space, w_mode)
+ loop.choose(space, arr, choices, shape, dtype, out, mode)
+ return out
+
+def put(space, w_arr, w_indices, w_values, w_mode):
+ arr = convert_to_array(space, w_arr)
+ mode = clipmode_converter(space, w_mode)
+
+ if not w_indices:
+ raise OperationError(space.w_ValueError,
+ space.wrap("indice list cannot be empty"))
+ if not w_values:
+ raise OperationError(space.w_ValueError,
+ space.wrap("value list cannot be empty"))
+
+ dtype = arr.get_dtype()
+
+ if space.isinstance_w(w_indices, space.w_list):
+ indices = space.listview(w_indices)
+ else:
+ indices = [w_indices]
+
+ if space.isinstance_w(w_values, space.w_list):
+ values = space.listview(w_values)
+ else:
+ values = [w_values]
+
+ v_idx = 0
+ for idx in indices:
+ index = support.index_w(space, idx)
+
+ if index < 0 or index >= arr.get_size():
+ if mode == NPY.RAISE:
+ raise OperationError(space.w_IndexError, space.wrap(
+ "index %d is out of bounds for axis 0 with size %d" % (index, arr.get_size())))
+ elif mode == NPY.WRAP:
+ index = index % arr.get_size()
+ elif mode == NPY.CLIP:
+ if index < 0:
+ index = 0
+ else:
+ index = arr.get_size() - 1
+ else:
+ assert False
+
+ value = values[v_idx]
+
+ if v_idx + 1 < len(values):
+ v_idx += 1
+
+ arr.setitem(space, [index], dtype.coerce(space, value))
+
+def diagonal(space, arr, offset, axis1, axis2):
+ shape = arr.get_shape()
+ shapelen = len(shape)
+ if offset < 0:
+ offset = -offset
+ axis1, axis2 = axis2, axis1
+ size = min(shape[axis1], shape[axis2] - offset)
+ dtype = arr.dtype
+ if axis1 < axis2:
+ shape = (shape[:axis1] + shape[axis1 + 1:axis2] +
+ shape[axis2 + 1:] + [size])
+ else:
+ shape = (shape[:axis2] + shape[axis2 + 1:axis1] +
+ shape[axis1 + 1:] + [size])
+ out = W_NDimArray.from_shape(space, shape, dtype)
+ if size == 0:
+ return out
+ if shapelen == 2:
+ # simple case
+ loop.diagonal_simple(space, arr, out, offset, axis1, axis2, size)
+ else:
+ loop.diagonal_array(space, arr, out, offset, axis1, axis2, shape)
+ return out
diff --git a/pypy/module/micronumpy/base.py b/pypy/module/micronumpy/base.py
--- a/pypy/module/micronumpy/base.py
+++ b/pypy/module/micronumpy/base.py
@@ -1,16 +1,9 @@
-
from pypy.interpreter.error import OperationError
from pypy.interpreter.baseobjspace import W_Root
from rpython.tool.pairtype import extendabletype
from pypy.module.micronumpy.support import calc_strides
-from pypy.module.micronumpy.arrayimpl.base import BaseArrayImplementation
-def issequence_w(space, w_obj):
- return (space.isinstance_w(w_obj, space.w_tuple) or
- space.isinstance_w(w_obj, space.w_list) or
- isinstance(w_obj, W_NDimArray))
-
def wrap_impl(space, w_cls, w_instance, impl):
if w_cls is None or space.is_w(w_cls, space.gettypefor(W_NDimArray)):
w_ret = W_NDimArray(impl)
@@ -21,6 +14,7 @@
space.call_method(w_ret, '__array_finalize__', w_instance)
return w_ret
+
class ArrayArgumentException(Exception):
pass
@@ -29,21 +23,17 @@
__metaclass__ = extendabletype
def __init__(self, implementation):
- assert isinstance(implementation, BaseArrayImplementation)
+ from pypy.module.micronumpy.concrete import BaseConcreteArray
+ assert isinstance(implementation, BaseConcreteArray)
assert isinstance(self, W_NDimArray)
self.implementation = implementation
@staticmethod
def from_shape(space, shape, dtype, order='C', w_instance=None):
- from pypy.module.micronumpy.arrayimpl import concrete, scalar
-
- if not shape:
- w_val = dtype.base.coerce(space, None)
- impl = scalar.Scalar(dtype.base, w_val)
- else:
- strides, backstrides = calc_strides(shape, dtype.base, order)
- impl = concrete.ConcreteArray(shape, dtype.base, order, strides,
- backstrides)
+ from pypy.module.micronumpy import concrete
+ strides, backstrides = calc_strides(shape, dtype.base, order)
+ impl = concrete.ConcreteArray(shape, dtype.base, order, strides,
+ backstrides)
if w_instance:
return wrap_impl(space, space.type(w_instance), w_instance, impl)
return W_NDimArray(impl)
@@ -51,12 +41,11 @@
@staticmethod
def from_shape_and_storage(space, shape, storage, dtype, order='C', owning=False,
w_subtype=None, w_base=None, writable=True):
- from pypy.module.micronumpy.arrayimpl import concrete
- assert shape
+ from pypy.module.micronumpy import concrete
strides, backstrides = calc_strides(shape, dtype, order)
if w_base is not None:
if owning:
- raise OperationError(space.w_ValueError,
+ raise OperationError(space.w_ValueError,
space.wrap("Cannot have owning=True when specifying a buffer"))
if writable:
impl = concrete.ConcreteArrayWithBase(shape, dtype, order, strides,
@@ -65,7 +54,6 @@
impl = concrete.ConcreteNonWritableArrayWithBase(shape, dtype, order,
strides, backstrides,
storage, w_base)
-
elif owning:
# Will free storage when GCd
impl = concrete.ConcreteArray(shape, dtype, order, strides,
@@ -82,7 +70,7 @@
@staticmethod
def new_slice(space, offset, strides, backstrides, shape, parent, orig_arr, dtype=None):
- from pypy.module.micronumpy.arrayimpl import concrete
+ from pypy.module.micronumpy import concrete
impl = concrete.SliceArray(offset, strides, backstrides, shape, parent,
orig_arr, dtype)
@@ -90,36 +78,15 @@
@staticmethod
def new_scalar(space, dtype, w_val=None):
- from pypy.module.micronumpy.arrayimpl import scalar
-
if w_val is not None:
w_val = dtype.coerce(space, w_val)
else:
w_val = dtype.coerce(space, space.wrap(0))
- return W_NDimArray(scalar.Scalar(dtype, w_val))
+ return convert_to_array(space, w_val)
def convert_to_array(space, w_obj):
- #XXX: This whole routine should very likely simply be array()
- from pypy.module.micronumpy.interp_numarray import array
- from pypy.module.micronumpy import interp_ufuncs
-
+ from pypy.module.micronumpy.ctors import array
if isinstance(w_obj, W_NDimArray):
return w_obj
- else:
- # Use __array__() method if it exists
- w_array = space.lookup(w_obj, "__array__")
- if w_array is not None:
- w_result = space.get_and_call_function(w_array, w_obj)
- if isinstance(w_result, W_NDimArray):
- return w_result
- else:
- raise OperationError(space.w_ValueError,
- space.wrap("object __array__ method not producing an array"))
- elif issequence_w(space, w_obj):
- # Convert to array.
- return array(space, w_obj, w_order=None)
- else:
- # If it's a scalar
- dtype = interp_ufuncs.find_dtype_for_scalar(space, w_obj)
- return W_NDimArray.new_scalar(space, dtype, w_obj)
+ return array(space, w_obj)
diff --git a/pypy/module/micronumpy/boxes.py b/pypy/module/micronumpy/boxes.py
new file mode 100644
--- /dev/null
+++ b/pypy/module/micronumpy/boxes.py
@@ -0,0 +1,815 @@
+from pypy.interpreter.baseobjspace import W_Root
+from pypy.interpreter.error import OperationError, oefmt
+from pypy.interpreter.gateway import interp2app, unwrap_spec
+from pypy.interpreter.typedef import TypeDef, GetSetProperty
+from pypy.objspace.std.bytesobject import W_BytesObject
+from pypy.objspace.std.floattype import float_typedef
+from pypy.objspace.std.unicodeobject import W_UnicodeObject
+from pypy.objspace.std.intobject import W_IntObject
+from pypy.objspace.std.complextype import complex_typedef
+from rpython.rlib.rarithmetic import LONG_BIT
+from rpython.rtyper.lltypesystem import rffi
+from rpython.tool.sourcetools import func_with_new_name
+from pypy.module.micronumpy.concrete import VoidBoxStorage
+from pypy.module.micronumpy.base import W_NDimArray
+from pypy.module.micronumpy.flagsobj import W_FlagsObject
+from pypy.interpreter.mixedmodule import MixedModule
+from rpython.rtyper.lltypesystem import lltype
+from rpython.rlib.rstring import StringBuilder
+from rpython.rlib.objectmodel import specialize
+from pypy.module.micronumpy import constants as NPY
+
+
+MIXIN_32 = (W_IntObject.typedef,) if LONG_BIT == 32 else ()
+MIXIN_64 = (W_IntObject.typedef,) if LONG_BIT == 64 else ()
+
+#long_double_size = rffi.sizeof_c_type('long double', ignore_errors=True)
+#import os
+#if long_double_size == 8 and os.name == 'nt':
+# # this is a lie, or maybe a wish, MS fakes longdouble math with double
+# long_double_size = 12
+
+# hardcode to 8 for now (simulate using normal double) until long double works
+long_double_size = 8
+
+
+def new_dtype_getter(num):
+ @specialize.memo()
+ def _get_dtype(space):
+ from pypy.module.micronumpy.descriptor import get_dtype_cache
+ return get_dtype_cache(space).dtypes_by_num[num]
+
+ def descr__new__(space, w_subtype, w_value=None):
+ from pypy.module.micronumpy.ctors import array
+ dtype = _get_dtype(space)
+ if not space.is_none(w_value):
+ w_arr = array(space, w_value, dtype, copy=False)
+ if len(w_arr.get_shape()) != 0:
+ return w_arr
+ w_value = w_arr.get_scalar_value().item(space)
+ return dtype.itemtype.coerce_subtype(space, w_subtype, w_value)
+
+ def descr_reduce(self, space):
+ return self.reduce(space)
+
+ return (func_with_new_name(descr__new__, 'descr__new__%d' % num),
+ staticmethod(_get_dtype),
+ descr_reduce)
+
+
+class Box(object):
+ _mixin_ = True
+
+ def reduce(self, space):
+ numpypy = space.getbuiltinmodule("_numpypy")
+ assert isinstance(numpypy, MixedModule)
+ multiarray = numpypy.get("multiarray")
+ assert isinstance(multiarray, MixedModule)
+ scalar = multiarray.get("scalar")
+
+ ret = space.newtuple([scalar, space.newtuple([space.wrap(self._get_dtype(space)), space.wrap(self.raw_str())])])
+ return ret
+
+class PrimitiveBox(Box):
+ _mixin_ = True
+ _immutable_fields_ = ['value']
+
+ def __init__(self, value):
+ self.value = value
+
+ def convert_to(self, space, dtype):
+ return dtype.box(self.value)
+
+ def __repr__(self):
+ return '%s(%s)' % (self.__class__.__name__, self.value)
+
+ def raw_str(self):
+ value = lltype.malloc(rffi.CArray(lltype.typeOf(self.value)), 1, flavor="raw")
+ value[0] = self.value
+
+ builder = StringBuilder()
+ builder.append_charpsize(rffi.cast(rffi.CCHARP, value), rffi.sizeof(lltype.typeOf(self.value)))
+ ret = builder.build()
+
+ lltype.free(value, flavor="raw")
+ return ret
+
+class ComplexBox(Box):
+ _mixin_ = True
+ _immutable_fields_ = ['real', 'imag']
+
+ def __init__(self, real, imag=0.):
+ self.real = real
+ self.imag = imag
+
+ def convert_to(self, space, dtype):
+ return dtype.box_complex(self.real, self.imag)
+
+ def convert_real_to(self, dtype):
+ return dtype.box(self.real)
+
+ def convert_imag_to(self, dtype):
+ return dtype.box(self.imag)
+
+ def raw_str(self):
+ value = lltype.malloc(rffi.CArray(lltype.typeOf(self.real)), 2, flavor="raw")
+ value[0] = self.real
+ value[1] = self.imag
+
+ builder = StringBuilder()
+ builder.append_charpsize(rffi.cast(rffi.CCHARP, value), rffi.sizeof(lltype.typeOf(self.real)) * 2)
+ ret = builder.build()
+
+ lltype.free(value, flavor="raw")
+ return ret
+
+
+class W_GenericBox(W_Root):
+ _attrs_ = ['w_flags']
+
+ def descr__new__(space, w_subtype, __args__):
+ raise oefmt(space.w_TypeError,
+ "cannot create '%N' instances", w_subtype)
+
+ def get_dtype(self, space):
+ return self._get_dtype(space)
+
+ def item(self, space):
+ return self.get_dtype(space).itemtype.to_builtin_type(space, self)
+
+ def descr_getitem(self, space, w_item):
+ from pypy.module.micronumpy.base import convert_to_array
+ if space.is_w(w_item, space.w_Ellipsis) or \
+ (space.isinstance_w(w_item, space.w_tuple) and
+ space.len_w(w_item) == 0):
+ return convert_to_array(space, self)
+ raise OperationError(space.w_IndexError, space.wrap(
+ "invalid index to scalar variable"))
+
+ def descr_str(self, space):
+ return space.wrap(self.get_dtype(space).itemtype.str_format(self))
+
+ def descr_format(self, space, w_spec):
+ return space.format(self.item(space), w_spec)
+
+ def descr_hash(self, space):
+ return space.hash(self.item(space))
+
+ def descr_index(self, space):
+ return space.index(self.item(space))
+
+ def descr_int(self, space):
+ if isinstance(self, W_UnsignedIntegerBox):
+ box = self.convert_to(space, W_UInt64Box._get_dtype(space))
+ else:
+ box = self.convert_to(space, W_Int64Box._get_dtype(space))
+ return space.int(box.item(space))
+
+ def descr_long(self, space):
+ if isinstance(self, W_UnsignedIntegerBox):
+ box = self.convert_to(space, W_UInt64Box._get_dtype(space))
+ else:
+ box = self.convert_to(space, W_Int64Box._get_dtype(space))
+ return space.long(box.item(space))
+
+ def descr_float(self, space):
+ box = self.convert_to(space, W_Float64Box._get_dtype(space))
+ return space.float(box.item(space))
+
+ def descr_oct(self, space):
+ return space.oct(self.descr_int(space))
+
+ def descr_hex(self, space):
+ return space.hex(self.descr_int(space))
+
+ def descr_nonzero(self, space):
+ dtype = self.get_dtype(space)
+ return space.wrap(dtype.itemtype.bool(self))
+
+ def _binop_impl(ufunc_name):
+ def impl(self, space, w_other, w_out=None):
+ from pypy.module.micronumpy import ufuncs
+ return getattr(ufuncs.get(space), ufunc_name).call(space,
+ [self, w_other, w_out])
+ return func_with_new_name(impl, "binop_%s_impl" % ufunc_name)
+
+ def _binop_right_impl(ufunc_name):
+ def impl(self, space, w_other, w_out=None):
+ from pypy.module.micronumpy import ufuncs
+ return getattr(ufuncs.get(space), ufunc_name).call(space,
+ [w_other, self, w_out])
+ return func_with_new_name(impl, "binop_right_%s_impl" % ufunc_name)
+
+ def _unaryop_impl(ufunc_name):
+ def impl(self, space, w_out=None):
+ from pypy.module.micronumpy import ufuncs
+ return getattr(ufuncs.get(space), ufunc_name).call(space,
+ [self, w_out])
+ return func_with_new_name(impl, "unaryop_%s_impl" % ufunc_name)
+
+ descr_add = _binop_impl("add")
+ descr_sub = _binop_impl("subtract")
+ descr_mul = _binop_impl("multiply")
+ descr_div = _binop_impl("divide")
+ descr_truediv = _binop_impl("true_divide")
+ descr_floordiv = _binop_impl("floor_divide")
+ descr_mod = _binop_impl("mod")
+ descr_pow = _binop_impl("power")
+ descr_lshift = _binop_impl("left_shift")
+ descr_rshift = _binop_impl("right_shift")
+ descr_and = _binop_impl("bitwise_and")
+ descr_or = _binop_impl("bitwise_or")
+ descr_xor = _binop_impl("bitwise_xor")
+
+ descr_eq = _binop_impl("equal")
+ descr_ne = _binop_impl("not_equal")
+ descr_lt = _binop_impl("less")
+ descr_le = _binop_impl("less_equal")
+ descr_gt = _binop_impl("greater")
+ descr_ge = _binop_impl("greater_equal")
+
+ descr_radd = _binop_right_impl("add")
+ descr_rsub = _binop_right_impl("subtract")
+ descr_rmul = _binop_right_impl("multiply")
+ descr_rdiv = _binop_right_impl("divide")
+ descr_rtruediv = _binop_right_impl("true_divide")
+ descr_rfloordiv = _binop_right_impl("floor_divide")
+ descr_rmod = _binop_right_impl("mod")
+ descr_rpow = _binop_right_impl("power")
+ descr_rlshift = _binop_right_impl("left_shift")
+ descr_rrshift = _binop_right_impl("right_shift")
+ descr_rand = _binop_right_impl("bitwise_and")
+ descr_ror = _binop_right_impl("bitwise_or")
+ descr_rxor = _binop_right_impl("bitwise_xor")
+
+ descr_pos = _unaryop_impl("positive")
+ descr_neg = _unaryop_impl("negative")
+ descr_abs = _unaryop_impl("absolute")
+ descr_invert = _unaryop_impl("invert")
+ descr_conjugate = _unaryop_impl("conjugate")
+
+ def descr_divmod(self, space, w_other):
+ w_quotient = self.descr_div(space, w_other)
+ w_remainder = self.descr_mod(space, w_other)
+ return space.newtuple([w_quotient, w_remainder])
+
+ def descr_rdivmod(self, space, w_other):
+ w_quotient = self.descr_rdiv(space, w_other)
+ w_remainder = self.descr_rmod(space, w_other)
+ return space.newtuple([w_quotient, w_remainder])
+
+ def descr_any(self, space):
+ from pypy.module.micronumpy.descriptor import get_dtype_cache
+ value = space.is_true(self)
+ return get_dtype_cache(space).w_booldtype.box(value)
+
+ def descr_all(self, space):
+ from pypy.module.micronumpy.descriptor import get_dtype_cache
+ value = space.is_true(self)
+ return get_dtype_cache(space).w_booldtype.box(value)
+
+ def descr_zero(self, space):
+ from pypy.module.micronumpy.descriptor import get_dtype_cache
+ return get_dtype_cache(space).w_longdtype.box(0)
+
+ def descr_ravel(self, space):
+ from pypy.module.micronumpy.base import convert_to_array
+ w_values = space.newtuple([self])
+ return convert_to_array(space, w_values)
+
+ @unwrap_spec(decimals=int)
+ def descr_round(self, space, decimals=0, w_out=None):
+ if not space.is_none(w_out):
+ raise OperationError(space.w_NotImplementedError, space.wrap(
+ "out not supported"))
+ return self.get_dtype(space).itemtype.round(self, decimals)
+
+ def descr_astype(self, space, w_dtype):
+ from pypy.module.micronumpy.descriptor import W_Dtype
+ dtype = space.interp_w(W_Dtype,
+ space.call_function(space.gettypefor(W_Dtype), w_dtype))
+ return self.convert_to(space, dtype)
+
+ def descr_view(self, space, w_dtype):
+ from pypy.module.micronumpy.descriptor import W_Dtype
+ try:
+ subclass = space.is_true(space.issubtype(
+ w_dtype, space.gettypefor(W_NDimArray)))
+ except OperationError, e:
+ if e.match(space, space.w_TypeError):
+ subclass = False
+ else:
+ raise
+ if subclass:
+ dtype = self.get_dtype(space)
+ else:
+ dtype = space.interp_w(W_Dtype,
More information about the pypy-commit
mailing list