| 1 |
from pypy.interpreter.error import OperationError, oefmt |
| 2 |
from pypy.interpreter.baseobjspace import BufferInterfaceNotFound |
| 3 |
from pypy.interpreter.gateway import unwrap_spec, WrappedDefault |
| 4 |
from pypy.interpreter.buffer import SubBuffer |
| 5 |
from rpython.rlib.rstring import strip_spaces |
| 6 |
from rpython.rlib.rawstorage import RAW_STORAGE_PTR |
| 7 |
from rpython.rtyper.lltypesystem import lltype, rffi |
| 8 |
|
| 9 |
from pypy.module.micronumpy import descriptor, loop, support |
| 10 |
from pypy.module.micronumpy.base import (wrap_impl, |
| 11 |
W_NDimArray, convert_to_array, W_NumpyObject) |
| 12 |
from pypy.module.micronumpy.converters import shape_converter, order_converter |
| 13 |
import pypy.module.micronumpy.constants as NPY |
| 14 |
from .casting import scalar2dtype |
| 15 |
|
| 16 |
|
| 17 |
def build_scalar(space, w_dtype, w_state): |
| 18 |
if not isinstance(w_dtype, descriptor.W_Dtype): |
| 19 |
raise oefmt(space.w_TypeError, |
| 20 |
"argument 1 must be numpy.dtype, not %T", w_dtype) |
| 21 |
if w_dtype.elsize == 0: |
| 22 |
raise oefmt(space.w_TypeError, "Empty data-type") |
| 23 |
if not space.isinstance_w(w_state, space.w_bytes): |
| 24 |
raise oefmt(space.w_TypeError, "initializing object must be a string") |
| 25 |
if space.len_w(w_state) != w_dtype.elsize: |
| 26 |
raise oefmt(space.w_ValueError, "initialization string is too small") |
| 27 |
state = rffi.str2charp(space.text_w(w_state)) |
| 28 |
box = w_dtype.itemtype.box_raw_data(state) |
| 29 |
lltype.free(state, flavor="raw") |
| 30 |
return box |
| 31 |
|
| 32 |
|
| 33 |
def try_array_method(space, w_object, w_dtype=None): |
| 34 |
w___array__ = space.lookup(w_object, "__array__") |
| 35 |
if w___array__ is None: |
| 36 |
return None |
| 37 |
if w_dtype is None: |
| 38 |
w_dtype = space.w_None |
| 39 |
w_array = space.get_and_call_function(w___array__, w_object, w_dtype) |
| 40 |
if isinstance(w_array, W_NDimArray): |
| 41 |
return w_array |
| 42 |
else: |
| 43 |
raise oefmt(space.w_ValueError, |
| 44 |
"object __array__ method not producing an array") |
| 45 |
|
| 46 |
def try_interface_method(space, w_object, copy): |
| 47 |
try: |
| 48 |
w_interface = space.getattr(w_object, space.newtext("__array_interface__")) |
| 49 |
if w_interface is None: |
| 50 |
return None, False |
| 51 |
version_w = space.finditem(w_interface, space.newtext("version")) |
| 52 |
if version_w is None: |
| 53 |
raise oefmt(space.w_ValueError, "__array_interface__ found without" |
| 54 |
" 'version' key") |
| 55 |
if not space.isinstance_w(version_w, space.w_int): |
| 56 |
raise oefmt(space.w_ValueError, "__array_interface__ found with" |
| 57 |
" non-int 'version' key") |
| 58 |
version = space.int_w(version_w) |
| 59 |
if version < 3: |
| 60 |
raise oefmt(space.w_ValueError, |
| 61 |
"__array_interface__ version %d not supported", version) |
| 62 |
|
| 63 |
w_shape = space.finditem(w_interface, space.newtext('shape')) |
| 64 |
w_dtype = space.finditem(w_interface, space.newtext('typestr')) |
| 65 |
w_descr = space.finditem(w_interface, space.newtext('descr')) |
| 66 |
w_data = space.finditem(w_interface, space.newtext('data')) |
| 67 |
w_strides = space.finditem(w_interface, space.newtext('strides')) |
| 68 |
if w_shape is None or w_dtype is None: |
| 69 |
raise oefmt(space.w_ValueError, |
| 70 |
"__array_interface__ missing one or more required keys: shape, typestr" |
| 71 |
) |
| 72 |
if w_descr is not None: |
| 73 |
raise oefmt(space.w_NotImplementedError, |
| 74 |
"__array_interface__ descr not supported yet") |
| 75 |
if w_strides is None or space.is_w(w_strides, space.w_None): |
| 76 |
strides = None |
| 77 |
else: |
| 78 |
strides = [space.int_w(i) for i in space.listview(w_strides)] |
| 79 |
shape = [space.int_w(i) for i in space.listview(w_shape)] |
| 80 |
dtype = descriptor.decode_w_dtype(space, w_dtype) |
| 81 |
if dtype is None: |
| 82 |
raise oefmt(space.w_ValueError, |
| 83 |
"__array_interface__ could not decode dtype %R", w_dtype |
| 84 |
) |
| 85 |
if w_data is not None and (space.isinstance_w(w_data, space.w_tuple) or |
| 86 |
space.isinstance_w(w_data, space.w_list)): |
| 87 |
data_w = space.listview(w_data) |
| 88 |
w_data = rffi.cast(RAW_STORAGE_PTR, space.int_w(data_w[0])) |
| 89 |
read_only = space.is_true(data_w[1]) or copy |
| 90 |
offset = 0 |
| 91 |
w_base = w_object |
| 92 |
if read_only: |
| 93 |
w_base = None |
| 94 |
return W_NDimArray.from_shape_and_storage(space, shape, w_data, |
| 95 |
dtype, w_base=w_base, strides=strides, |
| 96 |
start=offset), read_only |
| 97 |
if w_data is None: |
| 98 |
w_data = w_object |
| 99 |
w_offset = space.finditem(w_interface, space.newtext('offset')) |
| 100 |
if w_offset is None: |
| 101 |
offset = 0 |
| 102 |
else: |
| 103 |
offset = space.int_w(w_offset) |
| 104 |
|
| 105 |
if strides is not None: |
| 106 |
raise oefmt(space.w_NotImplementedError, |
| 107 |
"__array_interface__ strides not fully supported yet") |
| 108 |
arr = frombuffer(space, w_data, dtype, support.product(shape), offset) |
| 109 |
new_impl = arr.implementation.reshape(arr, shape) |
| 110 |
return W_NDimArray(new_impl), False |
| 111 |
|
| 112 |
except OperationError as e: |
| 113 |
if e.match(space, space.w_AttributeError): |
| 114 |
return None, False |
| 115 |
raise |
| 116 |
|
| 117 |
def _descriptor_from_pep3118_format(space, c_format): |
| 118 |
descr = descriptor.decode_w_dtype(space, space.newtext(c_format)) |
| 119 |
if descr: |
| 120 |
return descr |
| 121 |
msg = "invalid PEP 3118 format string: '%s'" % c_format |
| 122 |
space.warn(space.newtext(msg), space.w_RuntimeWarning) |
| 123 |
return None |
| 124 |
|
| 125 |
def _array_from_buffer_3118(space, w_object, dtype): |
| 126 |
try: |
| 127 |
w_buf = space.call_method(space.builtin, "memoryview", w_object) |
| 128 |
except OperationError as e: |
| 129 |
if e.match(space, space.w_TypeError): |
| 130 |
|
| 131 |
return w_object |
| 132 |
raise |
| 133 |
format = space.getattr(w_buf, space.newtext('format')) |
| 134 |
if format: |
| 135 |
descr = _descriptor_from_pep3118_format(space, space.text_w(format)) |
| 136 |
if not descr: |
| 137 |
return w_object |
| 138 |
if dtype and descr: |
| 139 |
raise oefmt(space.w_NotImplementedError, |
| 140 |
"creating an array from a memoryview while specifying dtype " |
| 141 |
"not supported") |
| 142 |
if descr.elsize != space.int_w(space.getattr(w_buf, space.newbytes('itemsize'))): |
| 143 |
msg = ("Item size computed from the PEP 3118 buffer format " |
| 144 |
"string does not match the actual item size.") |
| 145 |
space.warn(space.newtext(msg), space.w_RuntimeWarning) |
| 146 |
return w_object |
| 147 |
dtype = descr |
| 148 |
elif not dtype: |
| 149 |
dtype = descriptor.get_dtype_cache(space).w_stringdtype |
| 150 |
dtype.elsize = space.int_w(space.getattr(w_buf, space.newbytes('itemsize'))) |
| 151 |
nd = space.int_w(space.getattr(w_buf, space.newbytes('ndim'))) |
| 152 |
shape = [space.int_w(d) for d in space.listview( |
| 153 |
space.getattr(w_buf, space.newbytes('shape')))] |
| 154 |
strides = [] |
| 155 |
buflen = space.len_w(w_buf) * dtype.elsize |
| 156 |
if shape: |
| 157 |
strides = [space.int_w(d) for d in space.listview( |
| 158 |
space.getattr(w_buf, space.newbytes('strides')))] |
| 159 |
if not strides: |
| 160 |
d = buflen |
| 161 |
strides = [0] * nd |
| 162 |
for k in range(nd): |
| 163 |
if shape[k] > 0: |
| 164 |
d /= shape[k] |
| 165 |
strides[k] = d |
| 166 |
else: |
| 167 |
if nd == 1: |
| 168 |
shape = [buflen / dtype.elsize, ] |
| 169 |
strides = [dtype.elsize, ] |
| 170 |
elif nd > 1: |
| 171 |
msg = ("ndim computed from the PEP 3118 buffer format " |
| 172 |
"is greater than 1, but shape is NULL.") |
| 173 |
space.warn(space.newtext(msg), space.w_RuntimeWarning) |
| 174 |
return w_object |
| 175 |
try: |
| 176 |
w_data = rffi.cast(RAW_STORAGE_PTR, space.int_w(space.call_method(w_buf, '_pypy_raw_address'))) |
| 177 |
except OperationError as e: |
| 178 |
if e.match(space, space.w_ValueError): |
| 179 |
return w_object |
| 180 |
else: |
| 181 |
raise e |
| 182 |
writable = not space.bool_w(space.getattr(w_buf, space.newbytes('readonly'))) |
| 183 |
w_ret = W_NDimArray.from_shape_and_storage(space, shape, w_data, |
| 184 |
storage_bytes=buflen, dtype=dtype, w_base=w_object, |
| 185 |
writable=writable, strides=strides) |
| 186 |
if w_ret: |
| 187 |
return w_ret |
| 188 |
return w_object |
| 189 |
|
| 190 |
@unwrap_spec(ndmin=int, copy=bool, subok=bool) |
| 191 |
def array(space, w_object, w_dtype=None, copy=True, w_order=None, subok=False, |
| 192 |
ndmin=0): |
| 193 |
w_res = _array(space, w_object, w_dtype, copy, w_order, subok) |
| 194 |
shape = w_res.get_shape() |
| 195 |
if len(shape) < ndmin: |
| 196 |
shape = [1] * (ndmin - len(shape)) + shape |
| 197 |
impl = w_res.implementation.set_shape(space, w_res, shape) |
| 198 |
if w_res is w_object: |
| 199 |
return W_NDimArray(impl) |
| 200 |
else: |
| 201 |
w_res.implementation = impl |
| 202 |
return w_res |
| 203 |
|
| 204 |
def _array(space, w_object, w_dtype=None, copy=True, w_order=None, subok=False): |
| 205 |
|
| 206 |
from pypy.module.micronumpy.boxes import W_GenericBox |
| 207 |
|
| 208 |
if space.isinstance_w(w_object, space.w_type): |
| 209 |
raise oefmt(space.w_ValueError, "cannot create ndarray from type instance") |
| 210 |
|
| 211 |
dtype = descriptor.decode_w_dtype(space, w_dtype) |
| 212 |
if not isinstance(w_object, W_NDimArray): |
| 213 |
w_array = try_array_method(space, w_object, w_dtype) |
| 214 |
if w_array is None: |
| 215 |
if ( not space.isinstance_w(w_object, space.w_bytes) and |
| 216 |
not space.isinstance_w(w_object, space.w_unicode) and |
| 217 |
not isinstance(w_object, W_GenericBox)): |
| 218 |
|
| 219 |
w_object = _array_from_buffer_3118(space, w_object, dtype) |
| 220 |
else: |
| 221 |
|
| 222 |
w_object = w_array |
| 223 |
copy = False |
| 224 |
dtype = w_object.get_dtype() |
| 225 |
if not isinstance(w_object, W_NDimArray): |
| 226 |
w_array, _copy = try_interface_method(space, w_object, copy) |
| 227 |
if w_array is not None: |
| 228 |
w_object = w_array |
| 229 |
copy = _copy |
| 230 |
dtype = w_object.get_dtype() |
| 231 |
|
| 232 |
if isinstance(w_object, W_NDimArray): |
| 233 |
npy_order = order_converter(space, w_order, NPY.ANYORDER) |
| 234 |
if (dtype is None or w_object.get_dtype() is dtype) and (subok or |
| 235 |
type(w_object) is W_NDimArray): |
| 236 |
flags = w_object.get_flags() |
| 237 |
must_copy = copy |
| 238 |
must_copy |= (npy_order == NPY.CORDER and not flags & NPY.ARRAY_C_CONTIGUOUS) |
| 239 |
must_copy |= (npy_order == NPY.FORTRANORDER and not flags & NPY.ARRAY_F_CONTIGUOUS) |
| 240 |
if must_copy: |
| 241 |
return w_object.descr_copy(space, space.newint(npy_order)) |
| 242 |
else: |
| 243 |
return w_object |
| 244 |
if subok and not type(w_object) is W_NDimArray: |
| 245 |
raise oefmt(space.w_NotImplementedError, |
| 246 |
"array(..., subok=True) only partially implemented") |
| 247 |
|
| 248 |
if dtype is None: |
| 249 |
dtype = w_object.get_dtype() |
| 250 |
if dtype != w_object.get_dtype(): |
| 251 |
|
| 252 |
copy = True |
| 253 |
if copy: |
| 254 |
shape = w_object.get_shape() |
| 255 |
order = support.get_order_as_CF(w_object.get_order(), npy_order) |
| 256 |
w_arr = W_NDimArray.from_shape(space, shape, dtype, order=order) |
| 257 |
if support.product(shape) == 1: |
| 258 |
w_arr.set_scalar_value(dtype.coerce(space, |
| 259 |
w_object.implementation.getitem(0))) |
| 260 |
else: |
| 261 |
loop.setslice(space, shape, w_arr.implementation, w_object.implementation) |
| 262 |
return w_arr |
| 263 |
else: |
| 264 |
imp = w_object.implementation |
| 265 |
w_base = w_object |
| 266 |
sz = w_base.get_size() * dtype.elsize |
| 267 |
if imp.base() is not None: |
| 268 |
w_base = imp.base() |
| 269 |
if type(w_base) is W_NDimArray: |
| 270 |
sz = w_base.get_size() * dtype.elsize |
| 271 |
else: |
| 272 |
|
| 273 |
sz = space.int_w(space.call_method(w_base, 'size')) |
| 274 |
with imp as storage: |
| 275 |
return W_NDimArray.from_shape_and_storage(space, |
| 276 |
w_object.get_shape(), storage, dtype, storage_bytes=sz, |
| 277 |
w_base=w_base, strides=imp.strides, start=imp.start) |
| 278 |
else: |
| 279 |
|
| 280 |
npy_order = order_converter(space, w_order, NPY.CORDER) |
| 281 |
shape, elems_w = find_shape_and_elems(space, w_object, dtype) |
| 282 |
if dtype is None and space.isinstance_w(w_object, space.w_memoryview): |
| 283 |
dtype = descriptor.get_dtype_cache(space).w_uint8dtype |
| 284 |
if dtype is None or (dtype.is_str_or_unicode() and dtype.elsize < 1): |
| 285 |
dtype = find_dtype_for_seq(space, elems_w, dtype) |
| 286 |
|
| 287 |
w_arr = W_NDimArray.from_shape(space, shape, dtype, order=npy_order) |
| 288 |
if support.product(shape) == 1: |
| 289 |
w_arr.set_scalar_value(dtype.coerce(space, elems_w[0])) |
| 290 |
else: |
| 291 |
loop.assign(space, w_arr, elems_w) |
| 292 |
return w_arr |
| 293 |
|
| 294 |
|
| 295 |
def numpify(space, w_object): |
| 296 |
"""Convert the object to a W_NumpyObject""" |
| 297 |
|
| 298 |
if isinstance(w_object, W_NumpyObject): |
| 299 |
return w_object |
| 300 |
|
| 301 |
w_array = try_array_method(space, w_object) |
| 302 |
if w_array is not None: |
| 303 |
return w_array |
| 304 |
|
| 305 |
if is_scalar_like(space, w_object, dtype=None): |
| 306 |
dtype = scalar2dtype(space, w_object) |
| 307 |
if dtype.is_str_or_unicode() and dtype.elsize < 1: |
| 308 |
|
| 309 |
dtype = descriptor.variable_dtype(space, dtype.char + '1') |
| 310 |
return dtype.coerce(space, w_object) |
| 311 |
|
| 312 |
shape, elems_w = _find_shape_and_elems(space, w_object) |
| 313 |
dtype = find_dtype_for_seq(space, elems_w, None) |
| 314 |
w_arr = W_NDimArray.from_shape(space, shape, dtype) |
| 315 |
loop.assign(space, w_arr, elems_w) |
| 316 |
return w_arr |
| 317 |
|
| 318 |
|
| 319 |
def find_shape_and_elems(space, w_iterable, dtype): |
| 320 |
if is_scalar_like(space, w_iterable, dtype): |
| 321 |
return [], [w_iterable] |
| 322 |
is_rec_type = dtype is not None and dtype.is_record() |
| 323 |
return _find_shape_and_elems(space, w_iterable, is_rec_type) |
| 324 |
|
| 325 |
def is_scalar_like(space, w_obj, dtype): |
| 326 |
isstr = space.isinstance_w(w_obj, space.w_bytes) |
| 327 |
if not support.issequence_w(space, w_obj) or isstr: |
| 328 |
if dtype is None or dtype.char != NPY.CHARLTR: |
| 329 |
return True |
| 330 |
is_rec_type = dtype is not None and dtype.is_record() |
| 331 |
if is_rec_type and is_single_elem(space, w_obj, is_rec_type): |
| 332 |
return True |
| 333 |
if isinstance(w_obj, W_NDimArray) and w_obj.is_scalar(): |
| 334 |
return True |
| 335 |
return False |
| 336 |
|
| 337 |
def _find_shape_and_elems(space, w_iterable, is_rec_type=False): |
| 338 |
from pypy.objspace.std.bufferobject import W_Buffer |
| 339 |
shape = [space.len_w(w_iterable)] |
| 340 |
if space.isinstance_w(w_iterable, space.w_buffer): |
| 341 |
batch = [space.newint(0)] * shape[0] |
| 342 |
for i in range(shape[0]): |
| 343 |
batch[i] = space.ord(space.getitem(w_iterable, space.newint(i))) |
| 344 |
else: |
| 345 |
batch = space.listview(w_iterable) |
| 346 |
while True: |
| 347 |
if not batch: |
| 348 |
return shape[:], [] |
| 349 |
if is_single_elem(space, batch[0], is_rec_type): |
| 350 |
for w_elem in batch: |
| 351 |
if not is_single_elem(space, w_elem, is_rec_type): |
| 352 |
raise oefmt(space.w_ValueError, |
| 353 |
"setting an array element with a sequence") |
| 354 |
return shape[:], batch |
| 355 |
new_batch = [] |
| 356 |
size = space.len_w(batch[0]) |
| 357 |
for w_elem in batch: |
| 358 |
if (is_single_elem(space, w_elem, is_rec_type) or |
| 359 |
space.len_w(w_elem) != size): |
| 360 |
raise oefmt(space.w_ValueError, |
| 361 |
"setting an array element with a sequence") |
| 362 |
w_array = space.lookup(w_elem, '__array__') |
| 363 |
if w_array is not None: |
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
w_elem = space.get_and_call_function(w_array, w_elem, space.w_None) |
| 368 |
new_batch += space.listview(w_elem) |
| 369 |
shape.append(size) |
| 370 |
batch = new_batch |
| 371 |
|
| 372 |
def is_single_elem(space, w_elem, is_rec_type): |
| 373 |
if (is_rec_type and space.isinstance_w(w_elem, space.w_tuple)): |
| 374 |
return True |
| 375 |
if (space.isinstance_w(w_elem, space.w_tuple) or |
| 376 |
space.isinstance_w(w_elem, space.w_list)): |
| 377 |
return False |
| 378 |
if isinstance(w_elem, W_NDimArray) and not w_elem.is_scalar(): |
| 379 |
return False |
| 380 |
return True |
| 381 |
|
| 382 |
def _dtype_guess(space, dtype, w_elem): |
| 383 |
from .casting import scalar2dtype, find_binop_result_dtype |
| 384 |
if isinstance(w_elem, W_NDimArray) and w_elem.is_scalar(): |
| 385 |
w_elem = w_elem.get_scalar_value() |
| 386 |
elem_dtype = scalar2dtype(space, w_elem) |
| 387 |
return find_binop_result_dtype(space, elem_dtype, dtype) |
| 388 |
|
| 389 |
def find_dtype_for_seq(space, elems_w, dtype): |
| 390 |
if len(elems_w) == 1: |
| 391 |
w_elem = elems_w[0] |
| 392 |
return _dtype_guess(space, dtype, w_elem) |
| 393 |
for w_elem in elems_w: |
| 394 |
dtype = _dtype_guess(space, dtype, w_elem) |
| 395 |
if dtype is None: |
| 396 |
dtype = descriptor.get_dtype_cache(space).w_float64dtype |
| 397 |
elif dtype.is_str_or_unicode() and dtype.elsize < 1: |
| 398 |
|
| 399 |
dtype = descriptor.variable_dtype(space, dtype.char + '1') |
| 400 |
return dtype |
| 401 |
|
| 402 |
|
| 403 |
def _zeros_or_empty(space, w_shape, w_dtype, w_order, zero): |
| 404 |
|
| 405 |
order = order_converter(space, w_order, NPY.CORDER) |
| 406 |
dtype = space.interp_w(descriptor.W_Dtype, |
| 407 |
space.call_function(space.gettypefor(descriptor.W_Dtype), w_dtype)) |
| 408 |
if dtype.is_str_or_unicode() and dtype.elsize < 1: |
| 409 |
dtype = descriptor.variable_dtype(space, dtype.char + '1') |
| 410 |
shape = shape_converter(space, w_shape, dtype) |
| 411 |
for dim in shape: |
| 412 |
if dim < 0: |
| 413 |
raise oefmt(space.w_ValueError, |
| 414 |
"negative dimensions are not allowed") |
| 415 |
try: |
| 416 |
support.product_check(shape) |
| 417 |
except OverflowError: |
| 418 |
raise oefmt(space.w_ValueError, "array is too big.") |
| 419 |
return W_NDimArray.from_shape(space, shape, dtype, order, zero=zero) |
| 420 |
|
| 421 |
def empty(space, w_shape, w_dtype=None, w_order=None): |
| 422 |
return _zeros_or_empty(space, w_shape, w_dtype, w_order, zero=False) |
| 423 |
|
| 424 |
def zeros(space, w_shape, w_dtype=None, w_order=None): |
| 425 |
return _zeros_or_empty(space, w_shape, w_dtype, w_order, zero=True) |
| 426 |
|
| 427 |
|
| 428 |
@unwrap_spec(subok=bool) |
| 429 |
def empty_like(space, w_a, w_dtype=None, w_order=None, subok=True): |
| 430 |
w_a = convert_to_array(space, w_a) |
| 431 |
npy_order = order_converter(space, w_order, w_a.get_order()) |
| 432 |
if space.is_none(w_dtype): |
| 433 |
dtype = w_a.get_dtype() |
| 434 |
else: |
| 435 |
dtype = space.interp_w(descriptor.W_Dtype, |
| 436 |
space.call_function(space.gettypefor(descriptor.W_Dtype), w_dtype)) |
| 437 |
if dtype.is_str_or_unicode() and dtype.elsize < 1: |
| 438 |
dtype = descriptor.variable_dtype(space, dtype.char + '1') |
| 439 |
if npy_order in (NPY.KEEPORDER, NPY.ANYORDER): |
| 440 |
|
| 441 |
impl = w_a.implementation.astype(space, dtype, NPY.KEEPORDER) |
| 442 |
if subok: |
| 443 |
w_type = space.type(w_a) |
| 444 |
else: |
| 445 |
w_type = None |
| 446 |
return wrap_impl(space, w_type, w_a, impl) |
| 447 |
return W_NDimArray.from_shape(space, w_a.get_shape(), dtype=dtype, |
| 448 |
order=npy_order, |
| 449 |
w_instance=w_a if subok else None, |
| 450 |
zero=False) |
| 451 |
|
| 452 |
|
| 453 |
def _fromstring_text(space, s, count, sep, length, dtype): |
| 454 |
sep_stripped = strip_spaces(sep) |
| 455 |
skip_bad_vals = len(sep_stripped) == 0 |
| 456 |
|
| 457 |
items = [] |
| 458 |
num_items = 0 |
| 459 |
idx = 0 |
| 460 |
|
| 461 |
while (num_items < count or count == -1) and idx < len(s): |
| 462 |
nextidx = s.find(sep, idx) |
| 463 |
if nextidx < 0: |
| 464 |
nextidx = length |
| 465 |
piece = strip_spaces(s[idx:nextidx]) |
| 466 |
if len(piece) > 0 or not skip_bad_vals: |
| 467 |
if len(piece) == 0 and not skip_bad_vals: |
| 468 |
val = dtype.itemtype.default_fromstring(space) |
| 469 |
else: |
| 470 |
try: |
| 471 |
val = dtype.coerce(space, space.newtext(piece)) |
| 472 |
except OperationError as e: |
| 473 |
if not e.match(space, space.w_ValueError): |
| 474 |
raise |
| 475 |
gotit = False |
| 476 |
while not gotit and len(piece) > 0: |
| 477 |
piece = piece[:-1] |
| 478 |
try: |
| 479 |
val = dtype.coerce(space, space.newtext(piece)) |
| 480 |
gotit = True |
| 481 |
except OperationError as e: |
| 482 |
if not e.match(space, space.w_ValueError): |
| 483 |
raise |
| 484 |
if not gotit: |
| 485 |
val = dtype.itemtype.default_fromstring(space) |
| 486 |
nextidx = length |
| 487 |
items.append(val) |
| 488 |
num_items += 1 |
| 489 |
idx = nextidx + 1 |
| 490 |
|
| 491 |
if count > num_items: |
| 492 |
raise oefmt(space.w_ValueError, |
| 493 |
"string is smaller than requested size") |
| 494 |
|
| 495 |
a = W_NDimArray.from_shape(space, [num_items], dtype=dtype) |
| 496 |
ai, state = a.create_iter() |
| 497 |
for val in items: |
| 498 |
ai.setitem(state, val) |
| 499 |
state = ai.next(state) |
| 500 |
|
| 501 |
return a |
| 502 |
|
| 503 |
|
| 504 |
def _fromstring_bin(space, s, count, length, dtype): |
| 505 |
itemsize = dtype.elsize |
| 506 |
assert itemsize >= 0 |
| 507 |
if count == -1: |
| 508 |
count = length / itemsize |
| 509 |
if length % itemsize != 0: |
| 510 |
raise oefmt(space.w_ValueError, |
| 511 |
"string length %d not divisable by item size %d", |
| 512 |
length, itemsize) |
| 513 |
if count * itemsize > length: |
| 514 |
raise oefmt(space.w_ValueError, |
| 515 |
"string is smaller than requested size") |
| 516 |
|
| 517 |
a = W_NDimArray.from_shape(space, [count], dtype=dtype) |
| 518 |
loop.fromstring_loop(space, a, dtype, itemsize, s) |
| 519 |
return a |
| 520 |
|
| 521 |
|
| 522 |
@unwrap_spec(s='text', count=int, sep='text', w_dtype=WrappedDefault(None)) |
| 523 |
def fromstring(space, s, w_dtype=None, count=-1, sep=''): |
| 524 |
dtype = space.interp_w(descriptor.W_Dtype, |
| 525 |
space.call_function(space.gettypefor(descriptor.W_Dtype), w_dtype)) |
| 526 |
length = len(s) |
| 527 |
if sep == '': |
| 528 |
return _fromstring_bin(space, s, count, length, dtype) |
| 529 |
else: |
| 530 |
return _fromstring_text(space, s, count, sep, length, dtype) |
| 531 |
|
| 532 |
|
| 533 |
def _getbuffer(space, w_buffer): |
| 534 |
try: |
| 535 |
return space.writebuf_w(w_buffer) |
| 536 |
except OperationError as e: |
| 537 |
if not e.match(space, space.w_TypeError): |
| 538 |
raise |
| 539 |
return space.readbuf_w(w_buffer) |
| 540 |
|
| 541 |
|
| 542 |
@unwrap_spec(count=int, offset=int) |
| 543 |
def frombuffer(space, w_buffer, w_dtype=None, count=-1, offset=0): |
| 544 |
dtype = space.interp_w(descriptor.W_Dtype, |
| 545 |
space.call_function(space.gettypefor(descriptor.W_Dtype), w_dtype)) |
| 546 |
if dtype.elsize == 0: |
| 547 |
raise oefmt(space.w_ValueError, "itemsize cannot be zero in type") |
| 548 |
|
| 549 |
try: |
| 550 |
buf = _getbuffer(space, w_buffer) |
| 551 |
except OperationError as e: |
| 552 |
if not e.match(space, space.w_TypeError): |
| 553 |
raise |
| 554 |
w_buffer = space.call_method(w_buffer, '__buffer__', |
| 555 |
space.newint(space.BUF_FULL_RO)) |
| 556 |
buf = _getbuffer(space, w_buffer) |
| 557 |
|
| 558 |
ts = buf.getlength() |
| 559 |
if offset < 0 or offset > ts: |
| 560 |
raise oefmt(space.w_ValueError, |
| 561 |
"offset must be non-negative and no greater than " |
| 562 |
"buffer length (%d)", ts) |
| 563 |
|
| 564 |
s = ts - offset |
| 565 |
if offset: |
| 566 |
buf = SubBuffer(buf, offset, s) |
| 567 |
|
| 568 |
n = count |
| 569 |
itemsize = dtype.elsize |
| 570 |
assert itemsize > 0 |
| 571 |
if n < 0: |
| 572 |
if s % itemsize != 0: |
| 573 |
raise oefmt(space.w_ValueError, |
| 574 |
"buffer size must be a multiple of element size") |
| 575 |
n = s / itemsize |
| 576 |
else: |
| 577 |
if s < n * itemsize: |
| 578 |
raise oefmt(space.w_ValueError, |
| 579 |
"buffer is smaller than requested size") |
| 580 |
|
| 581 |
try: |
| 582 |
storage = buf.get_raw_address() |
| 583 |
except ValueError: |
| 584 |
a = W_NDimArray.from_shape(space, [n], dtype=dtype) |
| 585 |
loop.fromstring_loop(space, a, dtype, itemsize, buf.as_str()) |
| 586 |
return a |
| 587 |
else: |
| 588 |
writable = not buf.readonly |
| 589 |
return W_NDimArray.from_shape_and_storage(space, [n], storage, storage_bytes=s, |
| 590 |
dtype=dtype, w_base=w_buffer, writable=writable) |