Debian Codegraph @

pypy/module/micronumpy/base.py

raw symbols SCIP
1 from pypy.interpreter.baseobjspace import W_Root
2 from pypy.interpreter.error import oefmt
3 from rpython.tool.pairtype import extendabletype
4 from rpython.rlib.rarithmetic import ovfcheck
5 from pypy.module.micronumpy import support
6 from pypy.module.micronumpy import constants as NPY
7
8 def wrap_impl(space, w_cls, w_instance, impl):
9 if w_cls is None or space.is_w(w_cls, space.gettypefor(W_NDimArray)):
10 w_ret = W_NDimArray(impl)
11 else:
12 w_ret = space.allocate_instance(W_NDimArray, w_cls)
13 W_NDimArray.__init__(w_ret, impl)
14 assert isinstance(w_ret, W_NDimArray)
15 space.call_method(w_ret, '__array_finalize__', w_instance)
16 return w_ret
17
18
19 class ArrayArgumentException(Exception):
20 pass
21
22
23 class W_NumpyObject(W_Root):
24 """Base class for ndarrays and scalars (aka boxes)."""
25 _attrs_ = []
26
27 def get_flags(self):
28 return 0
29
30
31 class W_NDimArray(W_NumpyObject):
32 __metaclass__ = extendabletype
33
34 def __init__(self, implementation):
35 from pypy.module.micronumpy.concrete import BaseConcreteArray
36 assert isinstance(implementation, BaseConcreteArray)
37 assert isinstance(self, W_NDimArray)
38 self.implementation = implementation
39
40 @staticmethod
41 def from_shape(space, shape, dtype, order=NPY.CORDER,
42 w_instance=None, zero=True):
43 from pypy.module.micronumpy import concrete, descriptor, boxes
44 from pypy.module.micronumpy.strides import calc_strides
45 if len(shape) > NPY.MAXDIMS:
46 raise oefmt(space.w_ValueError,
47 "sequence too large; cannot be greater than %d", NPY.MAXDIMS)
48 try:
49 ovfcheck(support.product_check(shape) * dtype.elsize)
50 except OverflowError as e:
51 raise oefmt(space.w_ValueError, "array is too big.")
52 strides, backstrides = calc_strides(shape, dtype.base, order)
53 impl = concrete.ConcreteArray(shape, dtype.base, order, strides,
54 backstrides, zero=zero)
55 if dtype == descriptor.get_dtype_cache(space).w_objectdtype:
56 impl.fill(space, boxes.W_ObjectBox(space.w_None))
57 if w_instance:
58 return wrap_impl(space, space.type(w_instance), w_instance, impl)
59 return W_NDimArray(impl)
60
61 @staticmethod
62 def from_shape_and_storage(space, shape, storage, dtype, storage_bytes=-1,
63 order=NPY.CORDER, owning=False, w_subtype=None,
64 w_base=None, writable=True, strides=None,
65 start=0):
66 from pypy.module.micronumpy import concrete
67 from pypy.module.micronumpy.strides import (calc_strides,
68 calc_backstrides)
69 isize = dtype.elsize
70 if len(shape) > NPY.MAXDIMS:
71 raise oefmt(space.w_ValueError,
72 "sequence too large; cannot be greater than %d", NPY.MAXDIMS)
73 try:
74 totalsize = ovfcheck(support.product_check(shape) * isize)
75 except OverflowError as e:
76 raise oefmt(space.w_ValueError, "array is too big.")
77 if storage_bytes > 0 :
78 if totalsize > storage_bytes:
79 raise oefmt(space.w_TypeError,
80 "buffer is too small for requested array")
81 else:
82 storage_bytes = totalsize
83 if strides is None:
84 strides, backstrides = calc_strides(shape, dtype, order)
85 else:
86 if len(strides) != len(shape):
87 raise oefmt(space.w_ValueError,
88 'strides, if given, must be the same length as shape')
89 last = 0
90 for i in range(len(strides)):
91 last += (shape[i] - 1) * strides[i]
92 if last > storage_bytes or start < 0 or \
93 start + dtype.elsize > storage_bytes:
94 raise oefmt(space.w_ValueError,
95 'strides is incompatible with shape of requested '
96 'array and size of buffer')
97 backstrides = calc_backstrides(strides, shape)
98 if w_base is not None:
99 if owning:
100 raise oefmt(space.w_ValueError,
101 "Cannot have owning=True when specifying a buffer")
102 if writable:
103 impl = concrete.ConcreteArrayWithBase(shape, dtype, order,
104 strides, backstrides, storage, w_base,
105 start=start)
106 else:
107 impl = concrete.ConcreteNonWritableArrayWithBase(shape, dtype, order,
108 strides, backstrides,
109 storage, w_base)
110 elif owning:
111 # Will free storage when GCd
112 impl = concrete.ConcreteArray(shape, dtype, order, strides,
113 backstrides, storage=storage)
114 else:
115 impl = concrete.ConcreteArrayNotOwning(shape, dtype, order, strides,
116 backstrides, storage)
117 if w_subtype:
118 w_ret = space.allocate_instance(W_NDimArray, w_subtype)
119 W_NDimArray.__init__(w_ret, impl)
120 space.call_method(w_ret, '__array_finalize__', w_subtype)
121 return w_ret
122 return W_NDimArray(impl)
123
124 @staticmethod
125 def new_slice(space, offset, strides, backstrides, shape, parent, w_arr, dtype=None):
126 from pypy.module.micronumpy import concrete
127 w_base = w_arr
128 if w_arr.implementation.base() is not None:
129 w_base = w_arr.implementation.base()
130 impl = concrete.SliceArray(offset, strides, backstrides, shape, parent,
131 w_base, dtype)
132 return wrap_impl(space, space.type(w_arr), w_arr, impl)
133
134 @staticmethod
135 def new_scalar(space, dtype, w_val=None):
136 if w_val is not None:
137 w_val = dtype.coerce(space, w_val)
138 else:
139 w_val = dtype.coerce(space, space.newint(0))
140 return convert_to_array(space, w_val)
141
142 @staticmethod
143 def from_scalar(space, w_scalar):
144 """Convert a scalar into a 0-dim array"""
145 dtype = w_scalar.get_dtype(space)
146 w_arr = W_NDimArray.from_shape(space, [], dtype)
147 w_arr.set_scalar_value(w_scalar)
148 return w_arr
149
150 def get_shape(self):
151 return self.implementation.get_shape()
152
153 def get_dtype(self, space=None):
154 return self.implementation.dtype
155
156 def get_order(self):
157 return self.implementation.order
158
159 def get_start(self):
160 return self.implementation.start
161
162 def get_flags(self):
163 return self.implementation.flags
164
165 def ndims(self):
166 return len(self.get_shape())
167 ndims._always_inline_ = True
168
169
170 def convert_to_array(space, w_obj):
171 from pypy.module.micronumpy.ctors import array
172 if isinstance(w_obj, W_NDimArray):
173 return w_obj
174 return array(space, w_obj)