| 1 |
from pypy.interpreter.error import OperationError, oefmt |
| 2 |
from pypy.interpreter.gateway import interp2app, unwrap_spec, applevel, \ |
| 3 |
WrappedDefault |
| 4 |
from pypy.interpreter.typedef import TypeDef, GetSetProperty, \ |
| 5 |
make_weakref_descr |
| 6 |
from pypy.interpreter.buffer import SimpleView |
| 7 |
from rpython.rlib import jit |
| 8 |
from rpython.rlib.rstring import StringBuilder |
| 9 |
from rpython.rlib.rawstorage import RAW_STORAGE_PTR |
| 10 |
from rpython.rlib.rarithmetic import ovfcheck |
| 11 |
from rpython.rtyper.lltypesystem import rffi |
| 12 |
from rpython.tool.sourcetools import func_with_new_name |
| 13 |
from pypy.module.micronumpy import descriptor, ufuncs, boxes, arrayops, loop, \ |
| 14 |
support, constants as NPY |
| 15 |
from pypy.module.micronumpy.appbridge import get_appbridge_cache |
| 16 |
from pypy.module.micronumpy.arrayops import repeat, choose, put |
| 17 |
from pypy.module.micronumpy.base import W_NDimArray, convert_to_array, \ |
| 18 |
ArrayArgumentException, wrap_impl |
| 19 |
from pypy.module.micronumpy.concrete import BaseConcreteArray, V_OBJECTSTORE |
| 20 |
from pypy.module.micronumpy.converters import ( |
| 21 |
multi_axis_converter, order_converter, shape_converter, |
| 22 |
searchside_converter, out_converter) |
| 23 |
from pypy.module.micronumpy.flagsobj import W_FlagsObject |
| 24 |
from pypy.module.micronumpy.strides import ( |
| 25 |
get_shape_from_iterable, shape_agreement, shape_agreement_multiple, |
| 26 |
is_c_contiguous, is_f_contiguous, calc_strides, new_view, BooleanChunk, |
| 27 |
SliceChunk) |
| 28 |
from pypy.module.micronumpy.casting import can_cast_array |
| 29 |
from pypy.module.micronumpy.descriptor import get_dtype_cache |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
def _match_dot_shapes(space, left, right): |
| 34 |
left_shape = left.get_shape() |
| 35 |
right_shape = right.get_shape() |
| 36 |
my_critical_dim_size = left_shape[-1] |
| 37 |
right_critical_dim_size = right_shape[0] |
| 38 |
right_critical_dim = 0 |
| 39 |
out_shape = [] |
| 40 |
if len(right_shape) > 1: |
| 41 |
right_critical_dim = len(right_shape) - 2 |
| 42 |
right_critical_dim_size = right_shape[right_critical_dim] |
| 43 |
assert right_critical_dim >= 0 |
| 44 |
out_shape = (out_shape + left_shape[:-1] + |
| 45 |
right_shape[0:right_critical_dim] + |
| 46 |
right_shape[right_critical_dim + 1:]) |
| 47 |
elif len(right_shape) > 0: |
| 48 |
|
| 49 |
out_shape = out_shape + left_shape[:-1] |
| 50 |
if my_critical_dim_size != right_critical_dim_size: |
| 51 |
raise oefmt(space.w_ValueError, "objects are not aligned") |
| 52 |
return out_shape, right_critical_dim |
| 53 |
|
| 54 |
class __extend__(W_NDimArray): |
| 55 |
@jit.unroll_safe |
| 56 |
def descr_get_shape(self, space): |
| 57 |
shape = self.get_shape() |
| 58 |
return space.newtuple([space.newint(i) for i in shape]) |
| 59 |
|
| 60 |
def descr_set_shape(self, space, w_new_shape): |
| 61 |
shape = get_shape_from_iterable(space, self.get_size(), w_new_shape) |
| 62 |
self.implementation = self.implementation.set_shape(space, self, shape) |
| 63 |
w_cls = space.type(self) |
| 64 |
if not space.is_w(w_cls, space.gettypefor(W_NDimArray)): |
| 65 |
|
| 66 |
|
| 67 |
wrap_impl(space, w_cls, self, self.implementation) |
| 68 |
|
| 69 |
def descr_get_strides(self, space): |
| 70 |
strides = self.implementation.get_strides() |
| 71 |
return space.newtuple([space.newint(i) for i in strides]) |
| 72 |
|
| 73 |
def descr_get_dtype(self, space): |
| 74 |
return self.implementation.dtype |
| 75 |
|
| 76 |
def descr_set_dtype(self, space, w_dtype): |
| 77 |
dtype = space.interp_w(descriptor.W_Dtype, space.call_function( |
| 78 |
space.gettypefor(descriptor.W_Dtype), w_dtype)) |
| 79 |
if (dtype.elsize != self.get_dtype().elsize or |
| 80 |
(not dtype.is_record() and self.get_dtype().is_flexible())): |
| 81 |
raise oefmt(space.w_ValueError, |
| 82 |
"new type not compatible with array.") |
| 83 |
self.implementation.set_dtype(space, dtype) |
| 84 |
|
| 85 |
def descr_del_dtype(self, space): |
| 86 |
raise oefmt(space.w_AttributeError, "Cannot delete array dtype") |
| 87 |
|
| 88 |
def descr_get_ndim(self, space): |
| 89 |
return space.newint(self.ndims()) |
| 90 |
|
| 91 |
def descr_get_itemsize(self, space): |
| 92 |
return space.newint(self.get_dtype().elsize) |
| 93 |
|
| 94 |
def descr_get_nbytes(self, space): |
| 95 |
return space.newint(self.get_size() * self.get_dtype().elsize) |
| 96 |
|
| 97 |
def descr_fill(self, space, w_value): |
| 98 |
self.fill(space, self.get_dtype().coerce(space, w_value)) |
| 99 |
|
| 100 |
def descr_tostring(self, space, w_order=None): |
| 101 |
try: |
| 102 |
order = order_converter(space, w_order, NPY.CORDER) |
| 103 |
except: |
| 104 |
raise oefmt(space.w_TypeError, "order not understood") |
| 105 |
order = support.get_order_as_CF(self.get_order(), order) |
| 106 |
arr = self |
| 107 |
if order != arr.get_order(): |
| 108 |
arr = W_NDimArray(self.implementation.transpose(self, None)) |
| 109 |
return space.newtext(loop.tostring(space, arr)) |
| 110 |
|
| 111 |
def getitem_filter(self, space, arr, axis=0): |
| 112 |
shape = self.get_shape() |
| 113 |
if arr.ndims() > 1 and arr.get_shape() != shape: |
| 114 |
raise oefmt(space.w_IndexError, |
| 115 |
"boolean index array should have 1 dimension") |
| 116 |
if arr.get_size() > self.get_size(): |
| 117 |
raise oefmt(space.w_IndexError, "index out of range for array") |
| 118 |
size = loop.count_all_true(arr) |
| 119 |
if arr.ndims() == 1: |
| 120 |
if self.ndims() > 1 and arr.get_shape()[0] != shape[axis]: |
| 121 |
msg = ("boolean index did not match indexed array along" |
| 122 |
" dimension %d; dimension is %d but corresponding" |
| 123 |
" boolean dimension is %d" % (axis, shape[axis], |
| 124 |
arr.get_shape()[0])) |
| 125 |
|
| 126 |
space.warn(space.newtext(msg), space.w_VisibleDeprecationWarning) |
| 127 |
res_shape = shape[:axis] + [size] + shape[axis+1:] |
| 128 |
else: |
| 129 |
res_shape = [size] |
| 130 |
w_res = W_NDimArray.from_shape(space, res_shape, self.get_dtype(), |
| 131 |
w_instance=self) |
| 132 |
return loop.getitem_filter(w_res, self, arr) |
| 133 |
|
| 134 |
def setitem_filter(self, space, idx, val): |
| 135 |
if idx.ndims() > 1 and idx.get_shape() != self.get_shape(): |
| 136 |
raise oefmt(space.w_IndexError, |
| 137 |
"boolean index array should have 1 dimension") |
| 138 |
if idx.get_size() > self.get_size(): |
| 139 |
raise oefmt(space.w_IndexError, "index out of range for array") |
| 140 |
size = loop.count_all_true(idx) |
| 141 |
if size > val.get_size() and val.get_size() != 1: |
| 142 |
raise oefmt(space.w_ValueError, |
| 143 |
"NumPy boolean array indexing assignment " |
| 144 |
"cannot assign %d input values to " |
| 145 |
"the %d output values where the mask is true", |
| 146 |
val.get_size(), size) |
| 147 |
loop.setitem_filter(space, self, idx, val) |
| 148 |
|
| 149 |
def _prepare_array_index(self, space, w_index): |
| 150 |
if isinstance(w_index, W_NDimArray): |
| 151 |
return [], w_index.get_shape(), w_index.get_shape(), [w_index] |
| 152 |
if isinstance(w_index, boxes.W_GenericBox): |
| 153 |
return [], [1], [1], [w_index] |
| 154 |
w_lst = space.listview(w_index) |
| 155 |
for w_item in w_lst: |
| 156 |
if not (space.isinstance_w(w_item, space.w_int) or space.isinstance_w(w_item, space.w_float)): |
| 157 |
break |
| 158 |
else: |
| 159 |
arr = convert_to_array(space, w_index) |
| 160 |
return [], arr.get_shape(), arr.get_shape(), [arr] |
| 161 |
shape = None |
| 162 |
indexes_w = [None] * len(w_lst) |
| 163 |
res_shape = [] |
| 164 |
arr_index_in_shape = False |
| 165 |
prefix = [] |
| 166 |
for i, w_item in enumerate(w_lst): |
| 167 |
if isinstance(w_item, W_NDimArray) and w_item.get_dtype().is_bool(): |
| 168 |
if w_item.ndims() > 0: |
| 169 |
indexes_w[i] = w_item |
| 170 |
else: |
| 171 |
raise oefmt(space.w_IndexError, |
| 172 |
"in the future, 0-d boolean arrays will be " |
| 173 |
"interpreted as a valid boolean index") |
| 174 |
elif (isinstance(w_item, W_NDimArray) or |
| 175 |
space.isinstance_w(w_item, space.w_list)): |
| 176 |
w_item = convert_to_array(space, w_item) |
| 177 |
if shape is None: |
| 178 |
shape = w_item.get_shape() |
| 179 |
else: |
| 180 |
shape = shape_agreement(space, shape, w_item) |
| 181 |
indexes_w[i] = w_item |
| 182 |
if not arr_index_in_shape: |
| 183 |
res_shape.append(-1) |
| 184 |
arr_index_in_shape = True |
| 185 |
else: |
| 186 |
if space.isinstance_w(w_item, space.w_slice): |
| 187 |
lgt = space.decode_index4_unsafe(w_item, self.get_shape()[i])[3] |
| 188 |
if not arr_index_in_shape: |
| 189 |
prefix.append(w_item) |
| 190 |
res_shape.append(lgt) |
| 191 |
indexes_w[i] = w_item |
| 192 |
real_shape = [] |
| 193 |
for i in res_shape: |
| 194 |
if i == -1: |
| 195 |
real_shape += shape |
| 196 |
else: |
| 197 |
real_shape.append(i) |
| 198 |
return prefix, real_shape[:], shape, indexes_w |
| 199 |
|
| 200 |
def getitem_array_int(self, space, w_index): |
| 201 |
prefix, res_shape, iter_shape, indexes = \ |
| 202 |
self._prepare_array_index(space, w_index) |
| 203 |
if iter_shape is None: |
| 204 |
|
| 205 |
chunks = self.implementation._prepare_slice_args(space, w_index) |
| 206 |
copy = False |
| 207 |
if isinstance(chunks[0], BooleanChunk): |
| 208 |
copy = True |
| 209 |
w_ret = new_view(space, self, chunks) |
| 210 |
if copy: |
| 211 |
w_ret = w_ret.descr_copy(space, space.newint(w_ret.get_order())) |
| 212 |
return w_ret |
| 213 |
shape = res_shape + self.get_shape()[len(indexes):] |
| 214 |
w_res = W_NDimArray.from_shape(space, shape, self.get_dtype(), |
| 215 |
self.get_order(), w_instance=self) |
| 216 |
if not w_res.get_size(): |
| 217 |
return w_res |
| 218 |
return loop.getitem_array_int(space, self, w_res, iter_shape, indexes, |
| 219 |
prefix) |
| 220 |
|
| 221 |
def setitem_array_int(self, space, w_index, w_value): |
| 222 |
val_arr = convert_to_array(space, w_value) |
| 223 |
prefix, _, iter_shape, indexes = \ |
| 224 |
self._prepare_array_index(space, w_index) |
| 225 |
if iter_shape is None: |
| 226 |
|
| 227 |
chunks = self.implementation._prepare_slice_args(space, w_index) |
| 228 |
dim = -1 |
| 229 |
view = self |
| 230 |
for i, c in enumerate(chunks): |
| 231 |
if isinstance(c, BooleanChunk): |
| 232 |
dim = i |
| 233 |
idx = c.w_idx |
| 234 |
chunks.pop(i) |
| 235 |
chunks.insert(0, SliceChunk(space.newslice(space.newint(0), |
| 236 |
space.w_None, space.w_None))) |
| 237 |
break |
| 238 |
if dim > 0: |
| 239 |
view = self.implementation.swapaxes(space, self, 0, dim) |
| 240 |
if dim >= 0: |
| 241 |
view = new_view(space, self, chunks) |
| 242 |
view.setitem_filter(space, idx, val_arr) |
| 243 |
else: |
| 244 |
view = new_view(space, self, chunks) |
| 245 |
view.implementation.setslice(space, val_arr) |
| 246 |
return |
| 247 |
if support.product(iter_shape) == 0: |
| 248 |
return |
| 249 |
loop.setitem_array_int(space, self, iter_shape, indexes, val_arr, |
| 250 |
prefix) |
| 251 |
|
| 252 |
def descr_getitem(self, space, w_idx): |
| 253 |
if self.get_dtype().is_record(): |
| 254 |
if space.isinstance_w(w_idx, space.w_text): |
| 255 |
idx = space.text_w(w_idx) |
| 256 |
return self.getfield(space, idx) |
| 257 |
if space.is_w(w_idx, space.w_Ellipsis): |
| 258 |
return self.descr_view(space, space.type(self)) |
| 259 |
elif isinstance(w_idx, W_NDimArray) and w_idx.get_dtype().is_bool(): |
| 260 |
if w_idx.ndims() > 0: |
| 261 |
w_ret = self.getitem_filter(space, w_idx) |
| 262 |
else: |
| 263 |
raise oefmt(space.w_IndexError, |
| 264 |
"in the future, 0-d boolean arrays will be " |
| 265 |
"interpreted as a valid boolean index") |
| 266 |
elif isinstance(w_idx, boxes.W_GenericBox): |
| 267 |
w_ret = self.getitem_array_int(space, w_idx) |
| 268 |
|
| 269 |
if isinstance(w_idx, boxes.W_IntegerBox): |
| 270 |
|
| 271 |
|
| 272 |
w_ret = w_ret.implementation.descr_getitem(space, self, space.newint(0)) |
| 273 |
else: |
| 274 |
try: |
| 275 |
w_ret = self.implementation.descr_getitem(space, self, w_idx) |
| 276 |
except ArrayArgumentException: |
| 277 |
w_ret = self.getitem_array_int(space, w_idx) |
| 278 |
if isinstance(w_ret, boxes.W_ObjectBox): |
| 279 |
|
| 280 |
w_ret = w_ret.w_obj |
| 281 |
return w_ret |
| 282 |
|
| 283 |
def getitem(self, space, index_list): |
| 284 |
return self.implementation.getitem_index(space, index_list) |
| 285 |
|
| 286 |
def setitem(self, space, index_list, w_value): |
| 287 |
self.implementation.setitem_index(space, index_list, w_value) |
| 288 |
|
| 289 |
def descr_setitem(self, space, w_idx, w_value): |
| 290 |
if self.get_dtype().is_record(): |
| 291 |
if space.isinstance_w(w_idx, space.w_text): |
| 292 |
idx = space.text_w(w_idx) |
| 293 |
view = self.getfield(space, idx) |
| 294 |
w_value = convert_to_array(space, w_value) |
| 295 |
view.implementation.setslice(space, w_value) |
| 296 |
return |
| 297 |
if space.is_w(w_idx, space.w_Ellipsis): |
| 298 |
self.implementation.setslice(space, convert_to_array(space, w_value)) |
| 299 |
return |
| 300 |
|
| 301 |
|
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
|
| 307 |
|
| 308 |
|
| 309 |
|
| 310 |
|
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
elif isinstance(w_idx, W_NDimArray) and w_idx.get_dtype().is_bool() \ |
| 315 |
and w_idx.ndims() > 0: |
| 316 |
self.setitem_filter(space, w_idx, convert_to_array(space, w_value)) |
| 317 |
return |
| 318 |
try: |
| 319 |
self.implementation.descr_setitem(space, self, w_idx, w_value) |
| 320 |
except ArrayArgumentException: |
| 321 |
self.setitem_array_int(space, w_idx, w_value) |
| 322 |
|
| 323 |
def getfield(self, space, field): |
| 324 |
dtype = self.get_dtype() |
| 325 |
if field not in dtype.fields: |
| 326 |
raise oefmt(space.w_ValueError, "no field of name %s", field) |
| 327 |
arr = self.implementation |
| 328 |
ofs, subdtype = arr.dtype.fields[field][:2] |
| 329 |
if subdtype.is_object() and arr.gcstruct is V_OBJECTSTORE: |
| 330 |
raise oefmt(space.w_NotImplementedError, |
| 331 |
"cannot read object from array with no gc hook") |
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
strides, backstrides = calc_strides(subdtype.shape, |
| 336 |
subdtype.subdtype, arr.order) |
| 337 |
final_shape = arr.shape + subdtype.shape |
| 338 |
final_strides = arr.get_strides() + strides |
| 339 |
final_backstrides = arr.get_backstrides() + backstrides |
| 340 |
final_dtype = subdtype |
| 341 |
if subdtype.subdtype: |
| 342 |
final_dtype = subdtype.subdtype |
| 343 |
return W_NDimArray.new_slice(space, arr.start + ofs, final_strides, |
| 344 |
final_backstrides, |
| 345 |
final_shape, arr, self, final_dtype) |
| 346 |
|
| 347 |
|
| 348 |
def descr_delitem(self, space, w_idx): |
| 349 |
raise oefmt(space.w_ValueError, "cannot delete array elements") |
| 350 |
|
| 351 |
def descr_len(self, space): |
| 352 |
shape = self.get_shape() |
| 353 |
if len(shape): |
| 354 |
return space.newint(shape[0]) |
| 355 |
raise oefmt(space.w_TypeError, "len() of unsized object") |
| 356 |
|
| 357 |
def descr_repr(self, space): |
| 358 |
cache = get_appbridge_cache(space) |
| 359 |
if cache.w_array_repr is None: |
| 360 |
return space.newtext(self.dump_data()) |
| 361 |
return space.call_function(cache.w_array_repr, self) |
| 362 |
|
| 363 |
def descr_str(self, space): |
| 364 |
cache = get_appbridge_cache(space) |
| 365 |
if cache.w_array_str is None: |
| 366 |
return space.newtext(self.dump_data(prefix='', separator='', suffix='')) |
| 367 |
return space.call_function(cache.w_array_str, self) |
| 368 |
|
| 369 |
def dump_data(self, prefix='array(', separator=',', suffix=')'): |
| 370 |
i, state = self.create_iter() |
| 371 |
first = True |
| 372 |
dtype = self.get_dtype() |
| 373 |
s = StringBuilder() |
| 374 |
s.append(prefix) |
| 375 |
if not self.is_scalar(): |
| 376 |
s.append('[') |
| 377 |
while not i.done(state): |
| 378 |
if first: |
| 379 |
first = False |
| 380 |
else: |
| 381 |
s.append(separator) |
| 382 |
s.append(' ') |
| 383 |
if self.is_scalar() and dtype.is_str(): |
| 384 |
s.append(i.getitem(state).raw_str()) |
| 385 |
else: |
| 386 |
s.append(dtype.itemtype.str_format(i.getitem(state), add_quotes=True)) |
| 387 |
state = i.next(state) |
| 388 |
if not self.is_scalar(): |
| 389 |
s.append(']') |
| 390 |
s.append(suffix) |
| 391 |
return s.build() |
| 392 |
|
| 393 |
def create_iter(self, shape=None, backward_broadcast=False): |
| 394 |
assert isinstance(self.implementation, BaseConcreteArray) |
| 395 |
return self.implementation.create_iter( |
| 396 |
shape=shape, backward_broadcast=backward_broadcast) |
| 397 |
|
| 398 |
def is_scalar(self): |
| 399 |
return self.ndims() == 0 |
| 400 |
|
| 401 |
def set_scalar_value(self, w_val): |
| 402 |
return self.implementation.setitem(self.implementation.start, w_val) |
| 403 |
|
| 404 |
def fill(self, space, box): |
| 405 |
self.implementation.fill(space, box) |
| 406 |
|
| 407 |
def descr_get_size(self, space): |
| 408 |
return space.newint(self.get_size()) |
| 409 |
|
| 410 |
def get_size(self): |
| 411 |
return self.implementation.get_size() |
| 412 |
|
| 413 |
def get_scalar_value(self): |
| 414 |
assert self.get_size() == 1 |
| 415 |
return self.implementation.getitem(self.implementation.start) |
| 416 |
|
| 417 |
def descr_copy(self, space, w_order=None): |
| 418 |
if w_order is None: |
| 419 |
order = NPY.CORDER |
| 420 |
elif space.isinstance_w(w_order, space.w_int): |
| 421 |
order = space.int_w(w_order) |
| 422 |
else: |
| 423 |
order = order_converter(space, w_order, NPY.CORDER) |
| 424 |
copy = self.implementation.copy(space, order) |
| 425 |
w_subtype = space.type(self) |
| 426 |
return wrap_impl(space, w_subtype, self, copy) |
| 427 |
|
| 428 |
def descr_get_real(self, space): |
| 429 |
ret = self.implementation.get_real(space, self) |
| 430 |
return wrap_impl(space, space.type(self), self, ret) |
| 431 |
|
| 432 |
def descr_get_imag(self, space): |
| 433 |
ret = self.implementation.get_imag(space, self) |
| 434 |
return wrap_impl(space, space.type(self), self, ret) |
| 435 |
|
| 436 |
def descr_set_real(self, space, w_value): |
| 437 |
|
| 438 |
self.implementation.set_real(space, self, w_value) |
| 439 |
|
| 440 |
def descr_set_imag(self, space, w_value): |
| 441 |
|
| 442 |
if not self.get_dtype().is_complex(): |
| 443 |
raise oefmt(space.w_TypeError, |
| 444 |
'array does not have imaginary part to set') |
| 445 |
self.implementation.set_imag(space, self, w_value) |
| 446 |
|
| 447 |
def reshape(self, space, w_shape, order=NPY.ANYORDER): |
| 448 |
new_shape = get_shape_from_iterable(space, self.get_size(), w_shape) |
| 449 |
new_impl = self.implementation.reshape(self, new_shape, order) |
| 450 |
if new_impl is not None: |
| 451 |
return wrap_impl(space, space.type(self), self, new_impl) |
| 452 |
|
| 453 |
arr = self.descr_copy(space, space.newint(order)) |
| 454 |
if arr.get_size() > 0: |
| 455 |
new_implementation = arr.implementation.reshape(self, new_shape, order) |
| 456 |
if new_implementation is None: |
| 457 |
raise oefmt(space.w_ValueError, |
| 458 |
'could not reshape array of size %d to shape %s', |
| 459 |
arr.get_size(), str(new_shape)) |
| 460 |
arr.implementation = new_implementation |
| 461 |
else: |
| 462 |
arr.implementation.shape = new_shape |
| 463 |
return arr |
| 464 |
|
| 465 |
def descr_reshape(self, space, __args__): |
| 466 |
"""reshape(...) |
| 467 |
a.reshape(shape) |
| 468 |
|
| 469 |
Returns an array containing the same data with a new shape. |
| 470 |
|
| 471 |
Refer to `numpy.reshape` for full documentation. |
| 472 |
|
| 473 |
See Also |
| 474 |
-------- |
| 475 |
numpy.reshape : equivalent function |
| 476 |
""" |
| 477 |
args_w, kw_w = __args__.unpack() |
| 478 |
order = NPY.CORDER |
| 479 |
if kw_w: |
| 480 |
if "order" in kw_w: |
| 481 |
order = order_converter(space, kw_w["order"], order) |
| 482 |
del kw_w["order"] |
| 483 |
if kw_w: |
| 484 |
raise oefmt(space.w_TypeError, |
| 485 |
"reshape() got unexpected keyword argument(s)") |
| 486 |
if order == NPY.KEEPORDER: |
| 487 |
raise oefmt(space.w_ValueError, |
| 488 |
"order 'K' is not permitted for reshaping") |
| 489 |
if len(args_w) == 1: |
| 490 |
if space.is_none(args_w[0]): |
| 491 |
return self.descr_view(space) |
| 492 |
w_shape = args_w[0] |
| 493 |
else: |
| 494 |
w_shape = space.newtuple(args_w) |
| 495 |
return self.reshape(space, w_shape, order) |
| 496 |
|
| 497 |
def descr_get_transpose(self, space, axes=None): |
| 498 |
return W_NDimArray(self.implementation.transpose(self, axes)) |
| 499 |
|
| 500 |
def descr_transpose(self, space, args_w): |
| 501 |
if len(args_w) == 0 or len(args_w) == 1 and space.is_none(args_w[0]): |
| 502 |
return self.descr_get_transpose(space) |
| 503 |
else: |
| 504 |
if len(args_w) > 1: |
| 505 |
axes = args_w |
| 506 |
else: |
| 507 |
axes = space.fixedview(args_w[0]) |
| 508 |
|
| 509 |
axes = self._checked_axes(axes, space) |
| 510 |
return self.descr_get_transpose(space, axes) |
| 511 |
|
| 512 |
def _checked_axes(self, axes_raw, space): |
| 513 |
if len(axes_raw) != self.ndims(): |
| 514 |
raise oefmt(space.w_ValueError, "axes don't match array") |
| 515 |
axes = [] |
| 516 |
axes_seen = [False] * self.ndims() |
| 517 |
for elem in axes_raw: |
| 518 |
try: |
| 519 |
axis = support.index_w(space, elem) |
| 520 |
except OperationError: |
| 521 |
raise oefmt(space.w_TypeError, "an integer is required") |
| 522 |
if axis < 0 or axis >= self.ndims(): |
| 523 |
raise oefmt(space.w_ValueError, "invalid axis for this array") |
| 524 |
if axes_seen[axis] is True: |
| 525 |
raise oefmt(space.w_ValueError, "repeated axis in transpose") |
| 526 |
axes.append(axis) |
| 527 |
axes_seen[axis] = True |
| 528 |
return axes |
| 529 |
|
| 530 |
@unwrap_spec(axis1=int, axis2=int) |
| 531 |
def descr_swapaxes(self, space, axis1, axis2): |
| 532 |
"""a.swapaxes(axis1, axis2) |
| 533 |
|
| 534 |
Return a view of the array with `axis1` and `axis2` interchanged. |
| 535 |
|
| 536 |
Refer to `numpy.swapaxes` for full documentation. |
| 537 |
|
| 538 |
See Also |
| 539 |
-------- |
| 540 |
numpy.swapaxes : equivalent function |
| 541 |
""" |
| 542 |
if axis1 == axis2: |
| 543 |
return self.descr_view(space) |
| 544 |
n = self.ndims() |
| 545 |
if axis1 < 0: |
| 546 |
axis1 += n |
| 547 |
if axis2 < 0: |
| 548 |
axis2 += n |
| 549 |
if axis1 < 0 or axis1 >= n: |
| 550 |
raise oefmt(space.w_ValueError, "bad axis1 argument to swapaxes") |
| 551 |
if axis2 < 0 or axis2 >= n: |
| 552 |
raise oefmt(space.w_ValueError, "bad axis2 argument to swapaxes") |
| 553 |
if n <= 1: |
| 554 |
return self |
| 555 |
return self.implementation.swapaxes(space, self, axis1, axis2) |
| 556 |
|
| 557 |
def descr_nonzero(self, space): |
| 558 |
index_type = get_dtype_cache(space).w_int64dtype |
| 559 |
return self.implementation.nonzero(space, index_type) |
| 560 |
|
| 561 |
def descr_tolist(self, space): |
| 562 |
if self.ndims() == 0: |
| 563 |
return self.get_scalar_value().item(space) |
| 564 |
l_w = [] |
| 565 |
for i in range(self.get_shape()[0]): |
| 566 |
item_w = self.descr_getitem(space, space.newint(i)) |
| 567 |
if (isinstance(item_w, W_NDimArray) or |
| 568 |
isinstance(item_w, boxes.W_GenericBox)): |
| 569 |
l_w.append(space.call_method(item_w, "tolist")) |
| 570 |
else: |
| 571 |
l_w.append(item_w) |
| 572 |
return space.newlist(l_w) |
| 573 |
|
| 574 |
def descr_ravel(self, space, w_order=None): |
| 575 |
order = order_converter(space, w_order, self.get_order()) |
| 576 |
return self.reshape(space, space.newint(-1), order) |
| 577 |
|
| 578 |
@unwrap_spec(w_axis=WrappedDefault(None), |
| 579 |
w_out=WrappedDefault(None), |
| 580 |
w_mode=WrappedDefault('raise')) |
| 581 |
def descr_take(self, space, w_obj, w_axis=None, w_out=None, w_mode=None): |
| 582 |
return app_take(space, self, w_obj, w_axis, w_out, w_mode) |
| 583 |
|
| 584 |
def descr_compress(self, space, w_obj, w_axis=None): |
| 585 |
if not space.is_none(w_axis): |
| 586 |
raise oefmt(space.w_NotImplementedError, |
| 587 |
"axis unsupported for compress") |
| 588 |
arr = self |
| 589 |
else: |
| 590 |
arr = self.reshape(space, space.newint(-1), self.get_order()) |
| 591 |
index = convert_to_array(space, w_obj) |
| 592 |
return arr.getitem_filter(space, index) |
| 593 |
|
| 594 |
def descr_flatten(self, space, w_order=None): |
| 595 |
order = order_converter(space, w_order, self.get_order()) |
| 596 |
if self.is_scalar(): |
| 597 |
|
| 598 |
return self.reshape(space, space.newint(1), order) |
| 599 |
w_res = self.descr_ravel(space, w_order) |
| 600 |
if w_res.implementation.storage == self.implementation.storage: |
| 601 |
return w_res.descr_copy(space) |
| 602 |
return w_res |
| 603 |
|
| 604 |
@unwrap_spec(repeats=int) |
| 605 |
def descr_repeat(self, space, repeats, w_axis=None): |
| 606 |
return repeat(space, self, repeats, w_axis) |
| 607 |
|
| 608 |
def descr_set_flatiter(self, space, w_obj): |
| 609 |
iter, state = self.create_iter() |
| 610 |
dtype = self.get_dtype() |
| 611 |
w_arr = convert_to_array(space, w_obj) |
| 612 |
if dtype.is_record(): |
| 613 |
return self.implementation.setslice(space, w_arr) |
| 614 |
loop.flatiter_setitem(space, dtype, w_arr, iter, state, 1, iter.size) |
| 615 |
|
| 616 |
def descr_get_flatiter(self, space): |
| 617 |
from .flatiter import W_FlatIterator |
| 618 |
return W_FlatIterator(self) |
| 619 |
|
| 620 |
def descr_item(self, space, args_w): |
| 621 |
if len(args_w) == 1 and space.isinstance_w(args_w[0], space.w_tuple): |
| 622 |
args_w = space.fixedview(args_w[0]) |
| 623 |
shape = self.get_shape() |
| 624 |
coords = [0] * len(shape) |
| 625 |
if len(args_w) == 0: |
| 626 |
if self.get_size() == 1: |
| 627 |
w_obj = self.get_scalar_value() |
| 628 |
assert isinstance(w_obj, boxes.W_GenericBox) |
| 629 |
return w_obj.item(space) |
| 630 |
raise oefmt(space.w_ValueError, |
| 631 |
"can only convert an array of size 1 to a Python scalar") |
| 632 |
elif len(args_w) == 1 and len(shape) != 1: |
| 633 |
value = support.index_w(space, args_w[0]) |
| 634 |
value = support.check_and_adjust_index(space, value, self.get_size(), -1) |
| 635 |
for idim in range(len(shape) - 1, -1, -1): |
| 636 |
coords[idim] = value % shape[idim] |
| 637 |
value //= shape[idim] |
| 638 |
elif len(args_w) == len(shape): |
| 639 |
for idim in range(len(shape)): |
| 640 |
coords[idim] = support.index_w(space, args_w[idim]) |
| 641 |
else: |
| 642 |
raise oefmt(space.w_ValueError, "incorrect number of indices for array") |
| 643 |
item = self.getitem(space, coords) |
| 644 |
assert isinstance(item, boxes.W_GenericBox) |
| 645 |
return item.item(space) |
| 646 |
|
| 647 |
def descr_itemset(self, space, args_w): |
| 648 |
if len(args_w) == 0: |
| 649 |
raise oefmt(space.w_ValueError, |
| 650 |
"itemset must have at least one argument") |
| 651 |
if len(args_w) != self.ndims() + 1: |
| 652 |
raise oefmt(space.w_ValueError, |
| 653 |
"incorrect number of indices for array") |
| 654 |
self.descr_setitem(space, space.newtuple(args_w[:-1]), args_w[-1]) |
| 655 |
|
| 656 |
def descr___array__(self, space, w_dtype=None): |
| 657 |
if not space.is_none(w_dtype): |
| 658 |
raise oefmt(space.w_NotImplementedError, |
| 659 |
"__array__(dtype) not implemented") |
| 660 |
if type(self) is W_NDimArray: |
| 661 |
return self |
| 662 |
|
| 663 |
sz = support.product(self.get_shape()) * self.get_dtype().elsize |
| 664 |
return W_NDimArray.from_shape_and_storage( |
| 665 |
space, self.get_shape(), self.implementation.storage, |
| 666 |
self.get_dtype(), storage_bytes=sz, w_base=self) |
| 667 |
|
| 668 |
def descr_array_iface(self, space): |
| 669 |
''' |
| 670 |
Note: arr.__array__.data[0] is a pointer so arr must be kept alive |
| 671 |
while it is in use |
| 672 |
''' |
| 673 |
with self.implementation as storage: |
| 674 |
addr = support.get_storage_as_int(storage, self.get_start()) |
| 675 |
|
| 676 |
w_d = space.newdict() |
| 677 |
space.setitem_str(w_d, 'data', |
| 678 |
space.newtuple([space.newint(addr), space.w_False])) |
| 679 |
space.setitem_str(w_d, 'shape', self.descr_get_shape(space)) |
| 680 |
space.setitem_str(w_d, 'typestr', self.get_dtype().descr_get_str(space)) |
| 681 |
if self.implementation.order == NPY.CORDER: |
| 682 |
|
| 683 |
strides = space.w_None |
| 684 |
else: |
| 685 |
strides = self.descr_get_strides(space) |
| 686 |
space.setitem_str(w_d, 'strides', strides) |
| 687 |
space.setitem_str(w_d, 'version', space.newint(3)) |
| 688 |
return w_d |
| 689 |
|
| 690 |
w_pypy_data = None |
| 691 |
|
| 692 |
def fget___pypy_data__(self, space): |
| 693 |
return self.w_pypy_data |
| 694 |
|
| 695 |
def fset___pypy_data__(self, space, w_data): |
| 696 |
self.w_pypy_data = w_data |
| 697 |
|
| 698 |
def fdel___pypy_data__(self, space): |
| 699 |
self.w_pypy_data = None |
| 700 |
|
| 701 |
__array_priority__ = 0.0 |
| 702 |
|
| 703 |
def descr___array_priority__(self, space): |
| 704 |
return space.newfloat(self.__array_priority__) |
| 705 |
|
| 706 |
def descr_argsort(self, space, w_axis=None, w_kind=None, w_order=None): |
| 707 |
|
| 708 |
|
| 709 |
|
| 710 |
|
| 711 |
|
| 712 |
if self.is_scalar(): |
| 713 |
return space.newint(0) |
| 714 |
dtype = self.get_dtype().descr_newbyteorder(space, NPY.NATIVE) |
| 715 |
contig = self.implementation.astype(space, dtype, self.get_order()) |
| 716 |
return contig.argsort(space, w_axis) |
| 717 |
|
| 718 |
@unwrap_spec(order='text', casting='text', subok=bool, copy=bool) |
| 719 |
def descr_astype(self, space, w_dtype, order='K', casting='unsafe', subok=True, copy=True): |
| 720 |
cur_dtype = self.get_dtype() |
| 721 |
new_dtype = space.interp_w(descriptor.W_Dtype, space.call_function( |
| 722 |
space.gettypefor(descriptor.W_Dtype), w_dtype)) |
| 723 |
if new_dtype.num == NPY.VOID: |
| 724 |
raise oefmt(space.w_NotImplementedError, |
| 725 |
"astype(%s) not implemented yet", |
| 726 |
new_dtype.get_name()) |
| 727 |
if new_dtype.is_str_or_unicode() and new_dtype.elsize == 0: |
| 728 |
elsize = 0 |
| 729 |
ch = new_dtype.char |
| 730 |
itype = cur_dtype.itemtype |
| 731 |
for i in range(self.get_size()): |
| 732 |
elsize = max(elsize, space.len_w(itype.to_builtin_type(space, self.implementation.getitem(i)))) |
| 733 |
new_dtype = descriptor.variable_dtype( |
| 734 |
space, ch + str(elsize)) |
| 735 |
if new_dtype.elsize == 0: |
| 736 |
|
| 737 |
raise oefmt(space.w_ValueError, "new dtype has elsize of 0") |
| 738 |
if not can_cast_array(space, self, new_dtype, casting): |
| 739 |
raise oefmt(space.w_TypeError, "Cannot cast array from %R to %R" |
| 740 |
"according to the rule %s", self.get_dtype(), |
| 741 |
new_dtype, casting) |
| 742 |
order = order_converter(space, space.newtext(order), self.get_order()) |
| 743 |
if (not copy and new_dtype == self.get_dtype() |
| 744 |
and (order in (NPY.KEEPORDER, NPY.ANYORDER) or order == self.get_order()) |
| 745 |
and (subok or type(self) is W_NDimArray)): |
| 746 |
return self |
| 747 |
impl = self.implementation |
| 748 |
new_impl = impl.astype(space, new_dtype, order) |
| 749 |
if new_impl is None: |
| 750 |
return self |
| 751 |
if subok: |
| 752 |
w_type = space.type(self) |
| 753 |
else: |
| 754 |
w_type = None |
| 755 |
return wrap_impl(space, w_type, self, new_impl) |
| 756 |
|
| 757 |
def descr_get_base(self, space): |
| 758 |
impl = self.implementation |
| 759 |
ret = impl.base() |
| 760 |
if ret is None: |
| 761 |
return space.w_None |
| 762 |
return ret |
| 763 |
|
| 764 |
@unwrap_spec(inplace=bool) |
| 765 |
def descr_byteswap(self, space, inplace=False): |
| 766 |
if inplace: |
| 767 |
loop.byteswap(self.implementation, self.implementation) |
| 768 |
return self |
| 769 |
else: |
| 770 |
w_res = W_NDimArray.from_shape(space, self.get_shape(), |
| 771 |
self.get_dtype(), w_instance=self) |
| 772 |
loop.byteswap(self.implementation, w_res.implementation) |
| 773 |
return w_res |
| 774 |
|
| 775 |
def descr_choose(self, space, w_choices, w_out=None, w_mode=None): |
| 776 |
return choose(space, self, w_choices, w_out, w_mode) |
| 777 |
|
| 778 |
def descr_clip(self, space, w_min=None, w_max=None, w_out=None): |
| 779 |
if space.is_none(w_min): |
| 780 |
w_min = None |
| 781 |
else: |
| 782 |
w_min = convert_to_array(space, w_min) |
| 783 |
if space.is_none(w_max): |
| 784 |
w_max = None |
| 785 |
else: |
| 786 |
w_max = convert_to_array(space, w_max) |
| 787 |
if space.is_none(w_out): |
| 788 |
w_out = None |
| 789 |
elif not isinstance(w_out, W_NDimArray): |
| 790 |
raise oefmt(space.w_TypeError, |
| 791 |
"return arrays must be of ArrayType") |
| 792 |
if not w_min and not w_max: |
| 793 |
raise oefmt(space.w_ValueError, "One of max or min must be given.") |
| 794 |
shape = shape_agreement_multiple(space, [self, w_min, w_max, w_out]) |
| 795 |
out = descriptor.dtype_agreement(space, [self, w_min, w_max], shape, w_out) |
| 796 |
loop.clip(space, self, shape, w_min, w_max, out) |
| 797 |
return out |
| 798 |
|
| 799 |
def descr_get_ctypes(self, space): |
| 800 |
w_result = space.appexec([self], """(arr): |
| 801 |
from numpy.core import _internal |
| 802 |
p_data = arr.__array_interface__['data'][0] |
| 803 |
return _internal._ctypes(arr, p_data) |
| 804 |
""") |
| 805 |
return w_result |
| 806 |
|
| 807 |
def buffer_w(self, space, flags): |
| 808 |
|
| 809 |
return self.implementation.get_buffer(space, flags) |
| 810 |
|
| 811 |
def descr_get_data(self, space): |
| 812 |
return space.newmemoryview( |
| 813 |
self.implementation.get_buffer(space, space.BUF_FULL)) |
| 814 |
|
| 815 |
@unwrap_spec(offset=int, axis1=int, axis2=int) |
| 816 |
def descr_diagonal(self, space, offset=0, axis1=0, axis2=1): |
| 817 |
if self.ndims() < 2: |
| 818 |
raise oefmt(space.w_ValueError, |
| 819 |
"need at least 2 dimensions for diagonal") |
| 820 |
if (axis1 < 0 or axis2 < 0 or axis1 >= self.ndims() or |
| 821 |
axis2 >= self.ndims()): |
| 822 |
raise oefmt(space.w_ValueError, |
| 823 |
"axis1(=%d) and axis2(=%d) must be within range " |
| 824 |
"(ndim=%d)", axis1, axis2, self.ndims()) |
| 825 |
if axis1 == axis2: |
| 826 |
raise oefmt(space.w_ValueError, |
| 827 |
"axis1 and axis2 cannot be the same") |
| 828 |
return arrayops.diagonal(space, self.implementation, offset, axis1, axis2) |
| 829 |
|
| 830 |
@unwrap_spec(offset=int, axis1=int, axis2=int) |
| 831 |
def descr_trace(self, space, offset=0, axis1=0, axis2=1, |
| 832 |
w_dtype=None, w_out=None): |
| 833 |
diag = self.descr_diagonal(space, offset, axis1, axis2) |
| 834 |
return diag.descr_sum(space, w_axis=space.newint(-1), w_dtype=w_dtype, w_out=w_out) |
| 835 |
|
| 836 |
def descr_dump(self, space, w_file): |
| 837 |
raise oefmt(space.w_NotImplementedError, "dump not implemented yet") |
| 838 |
|
| 839 |
def descr_dumps(self, space): |
| 840 |
raise oefmt(space.w_NotImplementedError, "dumps not implemented yet") |
| 841 |
|
| 842 |
w_flags = None |
| 843 |
|
| 844 |
def descr_get_flags(self, space): |
| 845 |
if self.w_flags is None: |
| 846 |
self.w_flags = W_FlagsObject(self) |
| 847 |
return self.w_flags |
| 848 |
|
| 849 |
@unwrap_spec(offset=int) |
| 850 |
def descr_getfield(self, space, w_dtype, offset): |
| 851 |
raise oefmt(space.w_NotImplementedError, |
| 852 |
"getfield not implemented yet") |
| 853 |
|
| 854 |
@unwrap_spec(new_order='text') |
| 855 |
def descr_newbyteorder(self, space, new_order=NPY.SWAP): |
| 856 |
return self.descr_view( |
| 857 |
space, self.get_dtype().descr_newbyteorder(space, new_order)) |
| 858 |
|
| 859 |
@unwrap_spec(w_axis=WrappedDefault(None), |
| 860 |
w_out=WrappedDefault(None)) |
| 861 |
def descr_ptp(self, space, w_axis=None, w_out=None): |
| 862 |
return app_ptp(space, self, w_axis, w_out) |
| 863 |
|
| 864 |
def descr_put(self, space, w_indices, w_values, w_mode=None): |
| 865 |
put(space, self, w_indices, w_values, w_mode) |
| 866 |
|
| 867 |
@unwrap_spec(w_refcheck=WrappedDefault(True)) |
| 868 |
def descr_resize(self, space, w_new_shape, w_refcheck=None): |
| 869 |
raise oefmt(space.w_NotImplementedError, "resize not implemented yet") |
| 870 |
|
| 871 |
@unwrap_spec(decimals=int) |
| 872 |
def descr_round(self, space, decimals=0, w_out=None): |
| 873 |
if space.is_none(w_out): |
| 874 |
if self.get_dtype().is_bool(): |
| 875 |
|
| 876 |
w_out = W_NDimArray.from_shape(space, self.get_shape(), |
| 877 |
get_dtype_cache(space).w_float16dtype) |
| 878 |
else: |
| 879 |
w_out = None |
| 880 |
elif not isinstance(w_out, W_NDimArray): |
| 881 |
raise oefmt(space.w_TypeError, |
| 882 |
"return arrays must be of ArrayType") |
| 883 |
out = descriptor.dtype_agreement(space, [self], self.get_shape(), w_out) |
| 884 |
if out.get_dtype().is_bool() and self.get_dtype().is_bool(): |
| 885 |
calc_dtype = get_dtype_cache(space).w_longdtype |
| 886 |
else: |
| 887 |
calc_dtype = out.get_dtype() |
| 888 |
|
| 889 |
if decimals == 0: |
| 890 |
out = out.descr_view(space, space.type(self)) |
| 891 |
loop.round(space, self, calc_dtype, self.get_shape(), decimals, out) |
| 892 |
return out |
| 893 |
|
| 894 |
@unwrap_spec(w_side=WrappedDefault('left'), w_sorter=WrappedDefault(None)) |
| 895 |
def descr_searchsorted(self, space, w_v, w_side=None, w_sorter=None): |
| 896 |
if not space.is_none(w_sorter): |
| 897 |
raise oefmt(space.w_NotImplementedError, |
| 898 |
'sorter not supported in searchsort') |
| 899 |
side = searchside_converter(space, w_side) |
| 900 |
if self.ndims() != 1: |
| 901 |
raise oefmt(space.w_ValueError, "a must be a 1-d array") |
| 902 |
v = convert_to_array(space, w_v) |
| 903 |
ret = W_NDimArray.from_shape( |
| 904 |
space, v.get_shape(), get_dtype_cache(space).w_longdtype) |
| 905 |
if ret.get_size() < 1: |
| 906 |
return ret |
| 907 |
if side == NPY.SEARCHLEFT: |
| 908 |
binsearch = loop.binsearch_left |
| 909 |
else: |
| 910 |
binsearch = loop.binsearch_right |
| 911 |
binsearch(space, self, v, ret) |
| 912 |
if ret.is_scalar(): |
| 913 |
return ret.get_scalar_value() |
| 914 |
return ret |
| 915 |
|
| 916 |
def descr_setasflat(self, space, w_v): |
| 917 |
raise oefmt(space.w_NotImplementedError, |
| 918 |
"setasflat not implemented yet") |
| 919 |
|
| 920 |
def descr_setfield(self, space, w_val, w_dtype, w_offset=0): |
| 921 |
raise oefmt(space.w_NotImplementedError, |
| 922 |
"setfield not implemented yet") |
| 923 |
|
| 924 |
def descr_setflags(self, space, w_write=None, w_align=None, w_uic=None): |
| 925 |
raise oefmt(space.w_NotImplementedError, |
| 926 |
"setflags not implemented yet") |
| 927 |
|
| 928 |
@unwrap_spec(kind='text') |
| 929 |
def descr_sort(self, space, w_axis=None, kind='quicksort', w_order=None): |
| 930 |
|
| 931 |
|
| 932 |
if self.is_scalar(): |
| 933 |
return |
| 934 |
return self.implementation.sort(space, w_axis, w_order) |
| 935 |
|
| 936 |
def descr_partition(self, space, __args__): |
| 937 |
return get_appbridge_cache(space).call_method( |
| 938 |
space, 'numpy.core._partition_use', 'partition', __args__.prepend(self)) |
| 939 |
|
| 940 |
def descr_squeeze(self, space, w_axis=None): |
| 941 |
cur_shape = self.get_shape() |
| 942 |
if not space.is_none(w_axis): |
| 943 |
axes = multi_axis_converter(space, w_axis, len(cur_shape)) |
| 944 |
new_shape = [] |
| 945 |
for i in range(len(cur_shape)): |
| 946 |
if axes[i]: |
| 947 |
if cur_shape[i] != 1: |
| 948 |
raise oefmt(space.w_ValueError, |
| 949 |
"cannot select an axis to squeeze out " |
| 950 |
"which has size not equal to one") |
| 951 |
else: |
| 952 |
new_shape.append(cur_shape[i]) |
| 953 |
else: |
| 954 |
new_shape = [s for s in cur_shape if s != 1] |
| 955 |
if len(cur_shape) == len(new_shape): |
| 956 |
return self |
| 957 |
|
| 958 |
return wrap_impl(space, space.type(self), self, |
| 959 |
self.implementation.get_view( |
| 960 |
space, self, self.get_dtype(), new_shape)) |
| 961 |
|
| 962 |
def descr_strides(self, space): |
| 963 |
raise oefmt(space.w_NotImplementedError, |
| 964 |
"strides not implemented yet") |
| 965 |
|
| 966 |
def descr_tofile(self, space, w_fid, w_sep="", w_format="%s"): |
| 967 |
raise oefmt(space.w_NotImplementedError, |
| 968 |
"tofile not implemented yet") |
| 969 |
|
| 970 |
def descr_view(self, space, w_dtype=None, w_type=None): |
| 971 |
if not w_type and w_dtype: |
| 972 |
try: |
| 973 |
if space.issubtype_w(w_dtype, space.gettypefor(W_NDimArray)): |
| 974 |
w_type = w_dtype |
| 975 |
w_dtype = None |
| 976 |
except OperationError as e: |
| 977 |
if e.match(space, space.w_TypeError): |
| 978 |
pass |
| 979 |
else: |
| 980 |
raise |
| 981 |
if w_dtype: |
| 982 |
dtype = space.interp_w(descriptor.W_Dtype, space.call_function( |
| 983 |
space.gettypefor(descriptor.W_Dtype), w_dtype)) |
| 984 |
else: |
| 985 |
dtype = self.get_dtype() |
| 986 |
old_itemsize = self.get_dtype().elsize |
| 987 |
new_itemsize = dtype.elsize |
| 988 |
impl = self.implementation |
| 989 |
if new_itemsize == 0: |
| 990 |
raise oefmt(space.w_TypeError, "data-type must not be 0-sized") |
| 991 |
if dtype.subdtype is None: |
| 992 |
new_shape = self.get_shape()[:] |
| 993 |
dims = len(new_shape) |
| 994 |
else: |
| 995 |
new_shape = self.get_shape() + dtype.shape |
| 996 |
dtype = dtype.subdtype |
| 997 |
dims = 0 |
| 998 |
if dims == 0: |
| 999 |
|
| 1000 |
if old_itemsize != new_itemsize: |
| 1001 |
raise oefmt(space.w_ValueError, |
| 1002 |
"new type not compatible with array.") |
| 1003 |
strides = None |
| 1004 |
backstrides = None |
| 1005 |
base = self |
| 1006 |
else: |
| 1007 |
base = impl.base() |
| 1008 |
if base is None: |
| 1009 |
base = self |
| 1010 |
strides = impl.get_strides()[:] |
| 1011 |
backstrides = impl.get_backstrides()[:] |
| 1012 |
if old_itemsize != new_itemsize: |
| 1013 |
if not is_c_contiguous(impl) and not is_f_contiguous(impl): |
| 1014 |
raise oefmt(space.w_ValueError, |
| 1015 |
"new type not compatible with array.") |
| 1016 |
|
| 1017 |
if self.get_order() == NPY.FORTRANORDER: |
| 1018 |
minstride = strides[0] |
| 1019 |
mini = 0 |
| 1020 |
else: |
| 1021 |
minstride = strides[-1] |
| 1022 |
mini = len(strides) - 1 |
| 1023 |
for i in range(len(strides)): |
| 1024 |
if strides[i] < minstride: |
| 1025 |
minstride = strides[i] |
| 1026 |
mini = i |
| 1027 |
if new_shape[mini] * old_itemsize % new_itemsize != 0: |
| 1028 |
raise oefmt(space.w_ValueError, |
| 1029 |
"new type not compatible with array.") |
| 1030 |
new_shape[mini] = new_shape[mini] * old_itemsize / new_itemsize |
| 1031 |
strides[mini] = strides[mini] * new_itemsize / old_itemsize |
| 1032 |
backstrides[mini] = strides[mini] * new_shape[mini] |
| 1033 |
if dtype.is_object() != impl.dtype.is_object(): |
| 1034 |
raise oefmt(space.w_ValueError, 'expect trouble in ndarray.view,' |
| 1035 |
' one of target dtype or dtype is object dtype') |
| 1036 |
w_type = w_type or space.type(self) |
| 1037 |
v = impl.get_view(space, base, dtype, new_shape, strides, backstrides) |
| 1038 |
w_ret = wrap_impl(space, w_type, self, v) |
| 1039 |
return w_ret |
| 1040 |
|
| 1041 |
|
| 1042 |
|
| 1043 |
sig = None |
| 1044 |
cast = 'safe' |
| 1045 |
extobj = None |
| 1046 |
|
| 1047 |
|
| 1048 |
def _unaryop_impl(ufunc_name): |
| 1049 |
def impl(self, space, w_out=None): |
| 1050 |
return getattr(ufuncs.get(space), ufunc_name).call( |
| 1051 |
space, [self, w_out], self.sig, self.cast, self.extobj) |
| 1052 |
return func_with_new_name(impl, "unaryop_%s_impl" % ufunc_name) |
| 1053 |
|
| 1054 |
descr_pos = _unaryop_impl("positive") |
| 1055 |
descr_neg = _unaryop_impl("negative") |
| 1056 |
descr_abs = _unaryop_impl("absolute") |
| 1057 |
descr_invert = _unaryop_impl("invert") |
| 1058 |
|
| 1059 |
descr_conj = _unaryop_impl('conjugate') |
| 1060 |
|
| 1061 |
def descr___nonzero__(self, space): |
| 1062 |
if self.get_size() > 1: |
| 1063 |
raise oefmt(space.w_ValueError, |
| 1064 |
"The truth value of an array with more than one " |
| 1065 |
"element is ambiguous. Use a.any() or a.all()") |
| 1066 |
iter, state = self.create_iter() |
| 1067 |
return space.newbool(space.is_true(iter.getitem(state))) |
| 1068 |
|
| 1069 |
def _binop_impl(ufunc_name): |
| 1070 |
def impl(self, space, w_other, w_out=None): |
| 1071 |
return getattr(ufuncs.get(space), ufunc_name).call( |
| 1072 |
space, [self, w_other, w_out], self.sig, self.cast, self.extobj) |
| 1073 |
return func_with_new_name(impl, "binop_%s_impl" % ufunc_name) |
| 1074 |
|
| 1075 |
descr_add = _binop_impl("add") |
| 1076 |
descr_sub = _binop_impl("subtract") |
| 1077 |
descr_mul = _binop_impl("multiply") |
| 1078 |
descr_div = _binop_impl("divide") |
| 1079 |
descr_truediv = _binop_impl("true_divide") |
| 1080 |
descr_floordiv = _binop_impl("floor_divide") |
| 1081 |
descr_mod = _binop_impl("mod") |
| 1082 |
descr_pow = _binop_impl("power") |
| 1083 |
descr_lshift = _binop_impl("left_shift") |
| 1084 |
descr_rshift = _binop_impl("right_shift") |
| 1085 |
descr_and = _binop_impl("bitwise_and") |
| 1086 |
descr_or = _binop_impl("bitwise_or") |
| 1087 |
descr_xor = _binop_impl("bitwise_xor") |
| 1088 |
|
| 1089 |
def descr_divmod(self, space, w_other): |
| 1090 |
w_quotient = self.descr_div(space, w_other) |
| 1091 |
w_remainder = self.descr_mod(space, w_other) |
| 1092 |
return space.newtuple([w_quotient, w_remainder]) |
| 1093 |
|
| 1094 |
def _binop_comp_impl(ufunc): |
| 1095 |
def impl(self, space, w_other, w_out=None): |
| 1096 |
try: |
| 1097 |
return ufunc(self, space, w_other, w_out) |
| 1098 |
except OperationError as e: |
| 1099 |
if e.match(space, space.w_ValueError): |
| 1100 |
|
| 1101 |
return space.w_False |
| 1102 |
raise e |
| 1103 |
|
| 1104 |
return func_with_new_name(impl, ufunc.func_name) |
| 1105 |
|
| 1106 |
descr_eq = _binop_comp_impl(_binop_impl("equal")) |
| 1107 |
descr_ne = _binop_comp_impl(_binop_impl("not_equal")) |
| 1108 |
descr_lt = _binop_comp_impl(_binop_impl("less")) |
| 1109 |
descr_le = _binop_comp_impl(_binop_impl("less_equal")) |
| 1110 |
descr_gt = _binop_comp_impl(_binop_impl("greater")) |
| 1111 |
descr_ge = _binop_comp_impl(_binop_impl("greater_equal")) |
| 1112 |
|
| 1113 |
def _binop_inplace_impl(ufunc_name): |
| 1114 |
def impl(self, space, w_other): |
| 1115 |
w_out = self |
| 1116 |
ufunc = getattr(ufuncs.get(space), ufunc_name) |
| 1117 |
return ufunc.call(space, [self, w_other, w_out], self.sig, self.cast, self.extobj) |
| 1118 |
return func_with_new_name(impl, "binop_inplace_%s_impl" % ufunc_name) |
| 1119 |
|
| 1120 |
descr_iadd = _binop_inplace_impl("add") |
| 1121 |
descr_isub = _binop_inplace_impl("subtract") |
| 1122 |
descr_imul = _binop_inplace_impl("multiply") |
| 1123 |
descr_idiv = _binop_inplace_impl("divide") |
| 1124 |
descr_itruediv = _binop_inplace_impl("true_divide") |
| 1125 |
descr_ifloordiv = _binop_inplace_impl("floor_divide") |
| 1126 |
descr_imod = _binop_inplace_impl("mod") |
| 1127 |
descr_ipow = _binop_inplace_impl("power") |
| 1128 |
descr_ilshift = _binop_inplace_impl("left_shift") |
| 1129 |
descr_irshift = _binop_inplace_impl("right_shift") |
| 1130 |
descr_iand = _binop_inplace_impl("bitwise_and") |
| 1131 |
descr_ior = _binop_inplace_impl("bitwise_or") |
| 1132 |
descr_ixor = _binop_inplace_impl("bitwise_xor") |
| 1133 |
|
| 1134 |
def _binop_right_impl(ufunc_name): |
| 1135 |
def impl(self, space, w_other, w_out=None): |
| 1136 |
w_other = convert_to_array(space, w_other) |
| 1137 |
return getattr(ufuncs.get(space), ufunc_name).call( |
| 1138 |
space, [w_other, self, w_out], self.sig, self.cast, self.extobj) |
| 1139 |
return func_with_new_name(impl, "binop_right_%s_impl" % ufunc_name) |
| 1140 |
|
| 1141 |
descr_radd = _binop_right_impl("add") |
| 1142 |
descr_rsub = _binop_right_impl("subtract") |
| 1143 |
descr_rmul = _binop_right_impl("multiply") |
| 1144 |
descr_rdiv = _binop_right_impl("divide") |
| 1145 |
descr_rtruediv = _binop_right_impl("true_divide") |
| 1146 |
descr_rfloordiv = _binop_right_impl("floor_divide") |
| 1147 |
descr_rmod = _binop_right_impl("mod") |
| 1148 |
descr_rpow = _binop_right_impl("power") |
| 1149 |
descr_rlshift = _binop_right_impl("left_shift") |
| 1150 |
descr_rrshift = _binop_right_impl("right_shift") |
| 1151 |
descr_rand = _binop_right_impl("bitwise_and") |
| 1152 |
descr_ror = _binop_right_impl("bitwise_or") |
| 1153 |
descr_rxor = _binop_right_impl("bitwise_xor") |
| 1154 |
|
| 1155 |
def descr_rdivmod(self, space, w_other): |
| 1156 |
w_quotient = self.descr_rdiv(space, w_other) |
| 1157 |
w_remainder = self.descr_rmod(space, w_other) |
| 1158 |
return space.newtuple([w_quotient, w_remainder]) |
| 1159 |
|
| 1160 |
def descr_dot(self, space, w_other, w_out=None): |
| 1161 |
from .casting import find_result_type |
| 1162 |
out = out_converter(space, w_out) |
| 1163 |
other = convert_to_array(space, w_other) |
| 1164 |
if other.is_scalar(): |
| 1165 |
|
| 1166 |
return self.descr_mul(space, other) |
| 1167 |
elif self.ndims() < 2 and other.ndims() < 2: |
| 1168 |
w_res = self.descr_mul(space, other) |
| 1169 |
assert isinstance(w_res, W_NDimArray) |
| 1170 |
return w_res.descr_sum(space, space.newint(-1), out) |
| 1171 |
dtype = find_result_type(space, [self, other], []) |
| 1172 |
if self.get_size() < 1 and other.get_size() < 1: |
| 1173 |
|
| 1174 |
return W_NDimArray.new_scalar(space, dtype, space.newint(0)) |
| 1175 |
|
| 1176 |
out_shape, other_critical_dim = _match_dot_shapes(space, self, other) |
| 1177 |
if out: |
| 1178 |
matches = True |
| 1179 |
if dtype != out.get_dtype(): |
| 1180 |
matches = False |
| 1181 |
elif not out.implementation.order == NPY.CORDER: |
| 1182 |
matches = False |
| 1183 |
elif out.ndims() != len(out_shape): |
| 1184 |
matches = False |
| 1185 |
else: |
| 1186 |
for i in range(len(out_shape)): |
| 1187 |
if out.get_shape()[i] != out_shape[i]: |
| 1188 |
matches = False |
| 1189 |
break |
| 1190 |
if not matches: |
| 1191 |
raise oefmt(space.w_ValueError, |
| 1192 |
"output array is not acceptable (must have the " |
| 1193 |
"right type, nr dimensions, and be a C-Array)") |
| 1194 |
w_res = out |
| 1195 |
w_res.fill(space, self.get_dtype().coerce(space, None)) |
| 1196 |
else: |
| 1197 |
w_res = W_NDimArray.from_shape(space, out_shape, dtype, w_instance=self) |
| 1198 |
|
| 1199 |
return loop.multidim_dot(space, self, other, w_res, dtype, |
| 1200 |
other_critical_dim) |
| 1201 |
|
| 1202 |
def descr_mean(self, space, __args__): |
| 1203 |
return get_appbridge_cache(space).call_method( |
| 1204 |
space, 'numpy.core._methods', '_mean', __args__.prepend(self)) |
| 1205 |
|
| 1206 |
def descr_var(self, space, __args__): |
| 1207 |
return get_appbridge_cache(space).call_method( |
| 1208 |
space, 'numpy.core._methods', '_var', __args__.prepend(self)) |
| 1209 |
|
| 1210 |
def descr_std(self, space, __args__): |
| 1211 |
return get_appbridge_cache(space).call_method( |
| 1212 |
space, 'numpy.core._methods', '_std', __args__.prepend(self)) |
| 1213 |
|
| 1214 |
|
| 1215 |
|
| 1216 |
def _reduce_ufunc_impl(ufunc_name, name, bool_result=False): |
| 1217 |
@unwrap_spec(keepdims=bool) |
| 1218 |
def impl(self, space, w_axis=None, w_dtype=None, w_out=None, keepdims=False): |
| 1219 |
out = out_converter(space, w_out) |
| 1220 |
if bool_result: |
| 1221 |
w_dtype = get_dtype_cache(space).w_booldtype |
| 1222 |
return getattr(ufuncs.get(space), ufunc_name).reduce( |
| 1223 |
space, self, w_axis, keepdims, out, w_dtype) |
| 1224 |
impl.__name__ = name |
| 1225 |
return impl |
| 1226 |
|
| 1227 |
descr_sum = _reduce_ufunc_impl("add", "descr_sum") |
| 1228 |
descr_prod = _reduce_ufunc_impl("multiply", "descr_prod") |
| 1229 |
descr_max = _reduce_ufunc_impl("maximum", "descr_max") |
| 1230 |
descr_min = _reduce_ufunc_impl("minimum", "descr_min") |
| 1231 |
descr_all = _reduce_ufunc_impl('logical_and', "descr_all", bool_result=True) |
| 1232 |
descr_any = _reduce_ufunc_impl('logical_or', "descr_any", bool_result=True) |
| 1233 |
|
| 1234 |
|
| 1235 |
def _accumulate_method(ufunc_name, name): |
| 1236 |
def method(self, space, w_axis=None, w_dtype=None, w_out=None): |
| 1237 |
out = out_converter(space, w_out) |
| 1238 |
if space.is_none(w_axis): |
| 1239 |
w_axis = space.newint(0) |
| 1240 |
arr = self.reshape(space, space.newint(-1), self.get_order()) |
| 1241 |
else: |
| 1242 |
arr = self |
| 1243 |
ufunc = getattr(ufuncs.get(space), ufunc_name) |
| 1244 |
return ufunc.reduce(space, arr, w_axis, False, out, w_dtype, |
| 1245 |
variant=ufuncs.ACCUMULATE) |
| 1246 |
method.__name__ = name |
| 1247 |
return method |
| 1248 |
|
| 1249 |
descr_cumsum = _accumulate_method('add', 'descr_cumsum') |
| 1250 |
descr_cumprod = _accumulate_method('multiply', 'descr_cumprod') |
| 1251 |
|
| 1252 |
def _reduce_argmax_argmin_impl(raw_name): |
| 1253 |
op_name = "arg%s" % raw_name |
| 1254 |
op_name_flat = "arg%s_flat" % raw_name |
| 1255 |
def impl(self, space, w_axis=None, w_out=None): |
| 1256 |
if self.get_size() == 0: |
| 1257 |
raise oefmt(space.w_ValueError, |
| 1258 |
"Can't call %s on zero-size arrays", op_name) |
| 1259 |
try: |
| 1260 |
getattr(self.get_dtype().itemtype, raw_name) |
| 1261 |
except AttributeError: |
| 1262 |
raise oefmt(space.w_NotImplementedError, |
| 1263 |
'%s not implemented for %s', |
| 1264 |
op_name, self.get_dtype().get_name()) |
| 1265 |
shape = self.get_shape() |
| 1266 |
if space.is_none(w_axis) or len(shape) <= 1: |
| 1267 |
return space.newint(getattr(loop, op_name_flat)(self)) |
| 1268 |
else: |
| 1269 |
axis = space.int_w(w_axis) |
| 1270 |
assert axis >= 0 |
| 1271 |
out_shape = shape[:axis] + shape[axis+1:] |
| 1272 |
dtype = get_dtype_cache(space).w_longdtype |
| 1273 |
w_out = W_NDimArray.from_shape(space, out_shape, dtype) |
| 1274 |
return getattr(loop, op_name)(space, self, w_out, axis) |
| 1275 |
|
| 1276 |
return func_with_new_name(impl, "reduce_%s_impl" % op_name) |
| 1277 |
|
| 1278 |
descr_argmax = _reduce_argmax_argmin_impl("max") |
| 1279 |
descr_argmin = _reduce_argmax_argmin_impl("min") |
| 1280 |
|
| 1281 |
def descr_int(self, space): |
| 1282 |
if self.get_size() != 1: |
| 1283 |
raise oefmt(space.w_TypeError, |
| 1284 |
"only length-1 arrays can be converted to Python " |
| 1285 |
"scalars") |
| 1286 |
if self.get_dtype().is_str_or_unicode(): |
| 1287 |
raise oefmt(space.w_TypeError, |
| 1288 |
"don't know how to convert scalar number to int") |
| 1289 |
value = self.get_scalar_value() |
| 1290 |
return space.int(value) |
| 1291 |
|
| 1292 |
def descr_float(self, space): |
| 1293 |
if self.get_size() != 1: |
| 1294 |
raise oefmt(space.w_TypeError, |
| 1295 |
"only length-1 arrays can be converted to Python " |
| 1296 |
"scalars") |
| 1297 |
if self.get_dtype().is_str_or_unicode(): |
| 1298 |
raise oefmt(space.w_TypeError, |
| 1299 |
"don't know how to convert scalar number to float") |
| 1300 |
value = self.get_scalar_value() |
| 1301 |
return space.float(value) |
| 1302 |
|
| 1303 |
def descr_hex(self, space): |
| 1304 |
if self.get_size() != 1: |
| 1305 |
raise oefmt(space.w_TypeError, |
| 1306 |
"only length-1 arrays can be converted to Python scalars") |
| 1307 |
if not self.get_dtype().is_int(): |
| 1308 |
raise oefmt(space.w_TypeError, |
| 1309 |
"don't know how to convert scalar number to hex") |
| 1310 |
value = self.get_scalar_value() |
| 1311 |
return space.call_method(space.builtin, 'hex', value) |
| 1312 |
|
| 1313 |
def descr_oct(self, space): |
| 1314 |
if self.get_size() != 1: |
| 1315 |
raise oefmt(space.w_TypeError, |
| 1316 |
"only length-1 arrays can be converted to Python scalars") |
| 1317 |
if not self.get_dtype().is_int(): |
| 1318 |
raise oefmt(space.w_TypeError, |
| 1319 |
"don't know how to convert scalar number to oct") |
| 1320 |
value = self.get_scalar_value() |
| 1321 |
return space.call_method(space.builtin, 'oct', value) |
| 1322 |
|
| 1323 |
def descr_index(self, space): |
| 1324 |
if self.get_size() != 1 or \ |
| 1325 |
not self.get_dtype().is_int() or self.get_dtype().is_bool(): |
| 1326 |
raise oefmt(space.w_TypeError, |
| 1327 |
"only integer arrays with one element can be " |
| 1328 |
"converted to an index") |
| 1329 |
value = self.get_scalar_value() |
| 1330 |
assert isinstance(value, boxes.W_GenericBox) |
| 1331 |
return value.item(space) |
| 1332 |
|
| 1333 |
def descr_reduce(self, space): |
| 1334 |
from rpython.rlib.rstring import StringBuilder |
| 1335 |
from pypy.interpreter.mixedmodule import MixedModule |
| 1336 |
from pypy.module.micronumpy.concrete import SliceArray |
| 1337 |
|
| 1338 |
_numpypy = space.getbuiltinmodule("_numpypy") |
| 1339 |
assert isinstance(_numpypy, MixedModule) |
| 1340 |
multiarray = _numpypy.get("multiarray") |
| 1341 |
assert isinstance(multiarray, MixedModule) |
| 1342 |
reconstruct = multiarray.get("_reconstruct") |
| 1343 |
parameters = space.newtuple([self.getclass(space), space.newtuple( |
| 1344 |
[space.newint(0)]), space.newtext("b")]) |
| 1345 |
|
| 1346 |
builder = StringBuilder() |
| 1347 |
if self.get_dtype().is_object(): |
| 1348 |
raise oefmt(space.w_NotImplementedError, |
| 1349 |
"reduce for 'object' dtype not supported yet") |
| 1350 |
if isinstance(self.implementation, SliceArray): |
| 1351 |
iter, state = self.implementation.create_iter() |
| 1352 |
while not iter.done(state): |
| 1353 |
box = iter.getitem(state) |
| 1354 |
builder.append(box.raw_str()) |
| 1355 |
state = iter.next(state) |
| 1356 |
else: |
| 1357 |
with self.implementation as storage: |
| 1358 |
builder.append_charpsize(storage, |
| 1359 |
self.implementation.get_storage_size()) |
| 1360 |
|
| 1361 |
state = space.newtuple([ |
| 1362 |
space.newint(1), |
| 1363 |
self.descr_get_shape(space), |
| 1364 |
self.get_dtype(), |
| 1365 |
space.newbool(False), |
| 1366 |
space.newbytes(builder.build()), |
| 1367 |
]) |
| 1368 |
|
| 1369 |
return space.newtuple([reconstruct, parameters, state]) |
| 1370 |
|
| 1371 |
def descr_setstate(self, space, w_state): |
| 1372 |
lens = space.len_w(w_state) |
| 1373 |
|
| 1374 |
if lens == 5: |
| 1375 |
base_index = 1 |
| 1376 |
elif lens == 4: |
| 1377 |
base_index = 0 |
| 1378 |
else: |
| 1379 |
raise oefmt(space.w_ValueError, |
| 1380 |
"__setstate__ called with len(args[1])==%d, not 5 or 4", |
| 1381 |
lens) |
| 1382 |
shape = space.getitem(w_state, space.newint(base_index)) |
| 1383 |
dtype = space.getitem(w_state, space.newint(base_index+1)) |
| 1384 |
|
| 1385 |
storage = space.getitem(w_state, space.newint(base_index+3)) |
| 1386 |
if not isinstance(dtype, descriptor.W_Dtype): |
| 1387 |
raise oefmt(space.w_ValueError, |
| 1388 |
"__setstate__(self, (shape, dtype, .. called with " |
| 1389 |
"improper dtype '%R'", dtype) |
| 1390 |
self.implementation = W_NDimArray.from_shape_and_storage( |
| 1391 |
space, [space.int_w(i) for i in space.listview(shape)], |
| 1392 |
rffi.str2charp(space.bytes_w(storage), track_allocation=False), |
| 1393 |
dtype, storage_bytes=space.len_w(storage), owning=True).implementation |
| 1394 |
|
| 1395 |
def descr___array_finalize__(self, space, w_obj): |
| 1396 |
pass |
| 1397 |
|
| 1398 |
def descr___array_wrap__(self, space, w_obj, w_context=None): |
| 1399 |
return w_obj |
| 1400 |
|
| 1401 |
def descr___array_prepare__(self, space, w_obj, w_context=None): |
| 1402 |
return w_obj |
| 1403 |
pass |
| 1404 |
|
| 1405 |
|
| 1406 |
@unwrap_spec(offset=int) |
| 1407 |
def descr_new_array(space, w_subtype, w_shape, w_dtype=None, w_buffer=None, |
| 1408 |
offset=0, w_strides=None, w_order=None): |
| 1409 |
from pypy.module.micronumpy.concrete import ConcreteArray |
| 1410 |
dtype = space.interp_w(descriptor.W_Dtype, space.call_function( |
| 1411 |
space.gettypefor(descriptor.W_Dtype), w_dtype)) |
| 1412 |
shape = shape_converter(space, w_shape, dtype) |
| 1413 |
if len(shape) > NPY.MAXDIMS: |
| 1414 |
raise oefmt(space.w_ValueError, |
| 1415 |
"sequence too large; cannot be greater than %d", NPY.MAXDIMS) |
| 1416 |
if not space.is_none(w_buffer): |
| 1417 |
if (not space.is_none(w_strides)): |
| 1418 |
strides = [space.int_w(w_i) for w_i in |
| 1419 |
space.unpackiterable(w_strides)] |
| 1420 |
else: |
| 1421 |
strides = None |
| 1422 |
|
| 1423 |
try: |
| 1424 |
buf = space.writebuf_w(w_buffer) |
| 1425 |
except OperationError: |
| 1426 |
buf = space.readbuf_w(w_buffer) |
| 1427 |
try: |
| 1428 |
raw_ptr = buf.get_raw_address() |
| 1429 |
except ValueError: |
| 1430 |
raise oefmt(space.w_TypeError, "Only raw buffers are supported") |
| 1431 |
if not shape: |
| 1432 |
raise oefmt(space.w_TypeError, |
| 1433 |
"numpy scalars from buffers not supported yet") |
| 1434 |
storage = rffi.cast(RAW_STORAGE_PTR, raw_ptr) |
| 1435 |
storage = rffi.ptradd(storage, offset) |
| 1436 |
return W_NDimArray.from_shape_and_storage(space, shape, storage, |
| 1437 |
dtype, w_base=w_buffer, |
| 1438 |
storage_bytes=buf.getlength()-offset, |
| 1439 |
w_subtype=w_subtype, |
| 1440 |
writable=not buf.readonly, |
| 1441 |
strides=strides) |
| 1442 |
|
| 1443 |
order = order_converter(space, w_order, NPY.CORDER) |
| 1444 |
if space.is_w(w_subtype, space.gettypefor(W_NDimArray)): |
| 1445 |
return W_NDimArray.from_shape(space, shape, dtype, order) |
| 1446 |
strides, backstrides = calc_strides(shape, dtype.base, order) |
| 1447 |
try: |
| 1448 |
totalsize = ovfcheck(support.product_check(shape) * dtype.base.elsize) |
| 1449 |
except OverflowError as e: |
| 1450 |
raise oefmt(space.w_ValueError, "array is too big.") |
| 1451 |
impl = ConcreteArray(shape, dtype.base, order, strides, backstrides) |
| 1452 |
w_ret = space.allocate_instance(W_NDimArray, w_subtype) |
| 1453 |
W_NDimArray.__init__(w_ret, impl) |
| 1454 |
space.call_function(space.getattr(w_ret, |
| 1455 |
space.newtext('__array_finalize__')), w_subtype) |
| 1456 |
return w_ret |
| 1457 |
|
| 1458 |
|
| 1459 |
@unwrap_spec(addr=int, buf_len=int) |
| 1460 |
def descr__from_shape_and_storage(space, w_cls, w_shape, addr, w_dtype, |
| 1461 |
buf_len=-1, w_subtype=None, w_strides=None): |
| 1462 |
""" |
| 1463 |
Create an array from an existing buffer, given its address as int. |
| 1464 |
PyPy-only implementation detail. |
| 1465 |
""" |
| 1466 |
storage = rffi.cast(RAW_STORAGE_PTR, addr) |
| 1467 |
dtype = space.interp_w(descriptor.W_Dtype, space.call_function( |
| 1468 |
space.gettypefor(descriptor.W_Dtype), w_dtype)) |
| 1469 |
shape = shape_converter(space, w_shape, dtype) |
| 1470 |
if not space.is_none(w_strides): |
| 1471 |
strides = [space.int_w(w_i) for w_i in |
| 1472 |
space.unpackiterable(w_strides)] |
| 1473 |
else: |
| 1474 |
strides = None |
| 1475 |
if w_subtype: |
| 1476 |
if not space.isinstance_w(w_subtype, space.w_type): |
| 1477 |
raise oefmt(space.w_ValueError, |
| 1478 |
"subtype must be a subtype of ndarray, not a class " |
| 1479 |
"instance") |
| 1480 |
return W_NDimArray.from_shape_and_storage(space, shape, storage, dtype, |
| 1481 |
buf_len, NPY.CORDER, False, w_subtype, |
| 1482 |
strides=strides) |
| 1483 |
else: |
| 1484 |
return W_NDimArray.from_shape_and_storage(space, shape, storage, dtype, |
| 1485 |
storage_bytes=buf_len, |
| 1486 |
strides=strides) |
| 1487 |
|
| 1488 |
app_take = applevel(r""" |
| 1489 |
def take(a, indices, axis, out, mode): |
| 1490 |
if mode != 'raise': |
| 1491 |
raise NotImplementedError("mode != raise not implemented") |
| 1492 |
if axis is None: |
| 1493 |
from numpy import array |
| 1494 |
indices = array(indices) |
| 1495 |
res = a.ravel()[indices.ravel()].reshape(indices.shape) |
| 1496 |
else: |
| 1497 |
from operator import mul |
| 1498 |
if axis < 0: axis += len(a.shape) |
| 1499 |
s0, s1 = a.shape[:axis], a.shape[axis+1:] |
| 1500 |
l0 = reduce(mul, s0) if s0 else 1 |
| 1501 |
l1 = reduce(mul, s1) if s1 else 1 |
| 1502 |
res = a.reshape((l0, -1, l1))[:,indices,:].reshape(s0 + (-1,) + s1) |
| 1503 |
if out is not None: |
| 1504 |
out[:] = res |
| 1505 |
return out |
| 1506 |
return res |
| 1507 |
""", filename=__file__).interphook('take') |
| 1508 |
|
| 1509 |
app_ptp = applevel(r""" |
| 1510 |
def ptp(a, axis, out): |
| 1511 |
res = a.max(axis) - a.min(axis) |
| 1512 |
if out is not None: |
| 1513 |
out[:] = res |
| 1514 |
return out |
| 1515 |
return res |
| 1516 |
""", filename=__file__).interphook('ptp') |
| 1517 |
|
| 1518 |
W_NDimArray.typedef = TypeDef("numpy.ndarray", None, None, 'read-write', |
| 1519 |
__new__ = interp2app(descr_new_array), |
| 1520 |
|
| 1521 |
__len__ = interp2app(W_NDimArray.descr_len), |
| 1522 |
__getitem__ = interp2app(W_NDimArray.descr_getitem), |
| 1523 |
__setitem__ = interp2app(W_NDimArray.descr_setitem), |
| 1524 |
__delitem__ = interp2app(W_NDimArray.descr_delitem), |
| 1525 |
|
| 1526 |
__repr__ = interp2app(W_NDimArray.descr_repr), |
| 1527 |
__str__ = interp2app(W_NDimArray.descr_str), |
| 1528 |
__int__ = interp2app(W_NDimArray.descr_int), |
| 1529 |
__float__ = interp2app(W_NDimArray.descr_float), |
| 1530 |
__hex__ = interp2app(W_NDimArray.descr_hex), |
| 1531 |
__oct__ = interp2app(W_NDimArray.descr_oct), |
| 1532 |
__index__ = interp2app(W_NDimArray.descr_index), |
| 1533 |
|
| 1534 |
__pos__ = interp2app(W_NDimArray.descr_pos), |
| 1535 |
__neg__ = interp2app(W_NDimArray.descr_neg), |
| 1536 |
__abs__ = interp2app(W_NDimArray.descr_abs), |
| 1537 |
__invert__ = interp2app(W_NDimArray.descr_invert), |
| 1538 |
__nonzero__ = interp2app(W_NDimArray.descr___nonzero__), |
| 1539 |
|
| 1540 |
__add__ = interp2app(W_NDimArray.descr_add), |
| 1541 |
__sub__ = interp2app(W_NDimArray.descr_sub), |
| 1542 |
__mul__ = interp2app(W_NDimArray.descr_mul), |
| 1543 |
__div__ = interp2app(W_NDimArray.descr_div), |
| 1544 |
__truediv__ = interp2app(W_NDimArray.descr_truediv), |
| 1545 |
__floordiv__ = interp2app(W_NDimArray.descr_floordiv), |
| 1546 |
__mod__ = interp2app(W_NDimArray.descr_mod), |
| 1547 |
__divmod__ = interp2app(W_NDimArray.descr_divmod), |
| 1548 |
__pow__ = interp2app(W_NDimArray.descr_pow), |
| 1549 |
__lshift__ = interp2app(W_NDimArray.descr_lshift), |
| 1550 |
__rshift__ = interp2app(W_NDimArray.descr_rshift), |
| 1551 |
__and__ = interp2app(W_NDimArray.descr_and), |
| 1552 |
__or__ = interp2app(W_NDimArray.descr_or), |
| 1553 |
__xor__ = interp2app(W_NDimArray.descr_xor), |
| 1554 |
|
| 1555 |
__radd__ = interp2app(W_NDimArray.descr_radd), |
| 1556 |
__rsub__ = interp2app(W_NDimArray.descr_rsub), |
| 1557 |
__rmul__ = interp2app(W_NDimArray.descr_rmul), |
| 1558 |
__rdiv__ = interp2app(W_NDimArray.descr_rdiv), |
| 1559 |
__rtruediv__ = interp2app(W_NDimArray.descr_rtruediv), |
| 1560 |
__rfloordiv__ = interp2app(W_NDimArray.descr_rfloordiv), |
| 1561 |
__rmod__ = interp2app(W_NDimArray.descr_rmod), |
| 1562 |
__rdivmod__ = interp2app(W_NDimArray.descr_rdivmod), |
| 1563 |
__rpow__ = interp2app(W_NDimArray.descr_rpow), |
| 1564 |
__rlshift__ = interp2app(W_NDimArray.descr_rlshift), |
| 1565 |
__rrshift__ = interp2app(W_NDimArray.descr_rrshift), |
| 1566 |
__rand__ = interp2app(W_NDimArray.descr_rand), |
| 1567 |
__ror__ = interp2app(W_NDimArray.descr_ror), |
| 1568 |
__rxor__ = interp2app(W_NDimArray.descr_rxor), |
| 1569 |
|
| 1570 |
__iadd__ = interp2app(W_NDimArray.descr_iadd), |
| 1571 |
__isub__ = interp2app(W_NDimArray.descr_isub), |
| 1572 |
__imul__ = interp2app(W_NDimArray.descr_imul), |
| 1573 |
__idiv__ = interp2app(W_NDimArray.descr_idiv), |
| 1574 |
__itruediv__ = interp2app(W_NDimArray.descr_itruediv), |
| 1575 |
__ifloordiv__ = interp2app(W_NDimArray.descr_ifloordiv), |
| 1576 |
__imod__ = interp2app(W_NDimArray.descr_imod), |
| 1577 |
__ipow__ = interp2app(W_NDimArray.descr_ipow), |
| 1578 |
__ilshift__ = interp2app(W_NDimArray.descr_ilshift), |
| 1579 |
__irshift__ = interp2app(W_NDimArray.descr_irshift), |
| 1580 |
__iand__ = interp2app(W_NDimArray.descr_iand), |
| 1581 |
__ior__ = interp2app(W_NDimArray.descr_ior), |
| 1582 |
__ixor__ = interp2app(W_NDimArray.descr_ixor), |
| 1583 |
|
| 1584 |
__eq__ = interp2app(W_NDimArray.descr_eq), |
| 1585 |
__ne__ = interp2app(W_NDimArray.descr_ne), |
| 1586 |
__lt__ = interp2app(W_NDimArray.descr_lt), |
| 1587 |
__le__ = interp2app(W_NDimArray.descr_le), |
| 1588 |
__gt__ = interp2app(W_NDimArray.descr_gt), |
| 1589 |
__ge__ = interp2app(W_NDimArray.descr_ge), |
| 1590 |
|
| 1591 |
dtype = GetSetProperty(W_NDimArray.descr_get_dtype, |
| 1592 |
W_NDimArray.descr_set_dtype, |
| 1593 |
W_NDimArray.descr_del_dtype), |
| 1594 |
shape = GetSetProperty(W_NDimArray.descr_get_shape, |
| 1595 |
W_NDimArray.descr_set_shape), |
| 1596 |
strides = GetSetProperty(W_NDimArray.descr_get_strides), |
| 1597 |
ndim = GetSetProperty(W_NDimArray.descr_get_ndim), |
| 1598 |
size = GetSetProperty(W_NDimArray.descr_get_size), |
| 1599 |
itemsize = GetSetProperty(W_NDimArray.descr_get_itemsize), |
| 1600 |
nbytes = GetSetProperty(W_NDimArray.descr_get_nbytes), |
| 1601 |
flags = GetSetProperty(W_NDimArray.descr_get_flags), |
| 1602 |
|
| 1603 |
fill = interp2app(W_NDimArray.descr_fill), |
| 1604 |
tobytes = interp2app(W_NDimArray.descr_tostring), |
| 1605 |
tostring = interp2app(W_NDimArray.descr_tostring), |
| 1606 |
|
| 1607 |
mean = interp2app(W_NDimArray.descr_mean), |
| 1608 |
sum = interp2app(W_NDimArray.descr_sum), |
| 1609 |
prod = interp2app(W_NDimArray.descr_prod), |
| 1610 |
max = interp2app(W_NDimArray.descr_max), |
| 1611 |
min = interp2app(W_NDimArray.descr_min), |
| 1612 |
put = interp2app(W_NDimArray.descr_put), |
| 1613 |
argmax = interp2app(W_NDimArray.descr_argmax), |
| 1614 |
argmin = interp2app(W_NDimArray.descr_argmin), |
| 1615 |
all = interp2app(W_NDimArray.descr_all), |
| 1616 |
any = interp2app(W_NDimArray.descr_any), |
| 1617 |
dot = interp2app(W_NDimArray.descr_dot), |
| 1618 |
var = interp2app(W_NDimArray.descr_var), |
| 1619 |
std = interp2app(W_NDimArray.descr_std), |
| 1620 |
searchsorted = interp2app(W_NDimArray.descr_searchsorted), |
| 1621 |
|
| 1622 |
cumsum = interp2app(W_NDimArray.descr_cumsum), |
| 1623 |
cumprod = interp2app(W_NDimArray.descr_cumprod), |
| 1624 |
|
| 1625 |
copy = interp2app(W_NDimArray.descr_copy), |
| 1626 |
reshape = interp2app(W_NDimArray.descr_reshape), |
| 1627 |
resize = interp2app(W_NDimArray.descr_resize), |
| 1628 |
squeeze = interp2app(W_NDimArray.descr_squeeze), |
| 1629 |
T = GetSetProperty(W_NDimArray.descr_get_transpose), |
| 1630 |
transpose = interp2app(W_NDimArray.descr_transpose), |
| 1631 |
tolist = interp2app(W_NDimArray.descr_tolist), |
| 1632 |
flatten = interp2app(W_NDimArray.descr_flatten), |
| 1633 |
ravel = interp2app(W_NDimArray.descr_ravel), |
| 1634 |
take = interp2app(W_NDimArray.descr_take), |
| 1635 |
ptp = interp2app(W_NDimArray.descr_ptp), |
| 1636 |
compress = interp2app(W_NDimArray.descr_compress), |
| 1637 |
repeat = interp2app(W_NDimArray.descr_repeat), |
| 1638 |
swapaxes = interp2app(W_NDimArray.descr_swapaxes), |
| 1639 |
nonzero = interp2app(W_NDimArray.descr_nonzero), |
| 1640 |
flat = GetSetProperty(W_NDimArray.descr_get_flatiter, |
| 1641 |
W_NDimArray.descr_set_flatiter), |
| 1642 |
item = interp2app(W_NDimArray.descr_item), |
| 1643 |
itemset = interp2app(W_NDimArray.descr_itemset), |
| 1644 |
real = GetSetProperty(W_NDimArray.descr_get_real, |
| 1645 |
W_NDimArray.descr_set_real), |
| 1646 |
imag = GetSetProperty(W_NDimArray.descr_get_imag, |
| 1647 |
W_NDimArray.descr_set_imag), |
| 1648 |
conj = interp2app(W_NDimArray.descr_conj), |
| 1649 |
conjugate = interp2app(W_NDimArray.descr_conj), |
| 1650 |
|
| 1651 |
argsort = interp2app(W_NDimArray.descr_argsort), |
| 1652 |
sort = interp2app(W_NDimArray.descr_sort), |
| 1653 |
partition = interp2app(W_NDimArray.descr_partition), |
| 1654 |
astype = interp2app(W_NDimArray.descr_astype), |
| 1655 |
base = GetSetProperty(W_NDimArray.descr_get_base), |
| 1656 |
byteswap = interp2app(W_NDimArray.descr_byteswap), |
| 1657 |
choose = interp2app(W_NDimArray.descr_choose), |
| 1658 |
clip = interp2app(W_NDimArray.descr_clip), |
| 1659 |
round = interp2app(W_NDimArray.descr_round), |
| 1660 |
data = GetSetProperty(W_NDimArray.descr_get_data), |
| 1661 |
diagonal = interp2app(W_NDimArray.descr_diagonal), |
| 1662 |
trace = interp2app(W_NDimArray.descr_trace), |
| 1663 |
view = interp2app(W_NDimArray.descr_view), |
| 1664 |
newbyteorder = interp2app(W_NDimArray.descr_newbyteorder), |
| 1665 |
|
| 1666 |
ctypes = GetSetProperty(W_NDimArray.descr_get_ctypes), |
| 1667 |
__array_interface__ = GetSetProperty(W_NDimArray.descr_array_iface), |
| 1668 |
__weakref__ = make_weakref_descr(W_NDimArray), |
| 1669 |
_from_shape_and_storage = interp2app(descr__from_shape_and_storage, |
| 1670 |
as_classmethod=True), |
| 1671 |
__pypy_data__ = GetSetProperty(W_NDimArray.fget___pypy_data__, |
| 1672 |
W_NDimArray.fset___pypy_data__, |
| 1673 |
W_NDimArray.fdel___pypy_data__), |
| 1674 |
__reduce__ = interp2app(W_NDimArray.descr_reduce), |
| 1675 |
__setstate__ = interp2app(W_NDimArray.descr_setstate), |
| 1676 |
__array_finalize__ = interp2app(W_NDimArray.descr___array_finalize__), |
| 1677 |
__array_prepare__ = interp2app(W_NDimArray.descr___array_prepare__), |
| 1678 |
__array_wrap__ = interp2app(W_NDimArray.descr___array_wrap__), |
| 1679 |
__array_priority__ = GetSetProperty(W_NDimArray.descr___array_priority__), |
| 1680 |
__array__ = interp2app(W_NDimArray.descr___array__), |
| 1681 |
) |
| 1682 |
|
| 1683 |
|
| 1684 |
def _reconstruct(space, w_subtype, w_shape, w_dtype): |
| 1685 |
return descr_new_array(space, w_subtype, w_shape, w_dtype) |