| 1 |
from pypy.interpreter.baseobjspace import W_Root |
| 2 |
from pypy.interpreter.error import OperationError, oefmt |
| 3 |
from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault |
| 4 |
from pypy.interpreter.typedef import TypeDef, GetSetProperty, interp_attrproperty |
| 5 |
from pypy.interpreter.argument import Arguments |
| 6 |
from rpython.rlib import jit, rgc |
| 7 |
from rpython.rlib.rarithmetic import LONG_BIT, maxint, _get_bitsize |
| 8 |
from rpython.tool.sourcetools import func_with_new_name |
| 9 |
from rpython.rlib.rawstorage import ( |
| 10 |
raw_storage_setitem, free_raw_storage, alloc_raw_storage) |
| 11 |
from rpython.rtyper.lltypesystem import rffi, lltype |
| 12 |
from rpython.rlib.objectmodel import keepalive_until_here, specialize |
| 13 |
|
| 14 |
from pypy.module.micronumpy import loop, constants as NPY |
| 15 |
from pypy.module.micronumpy.descriptor import ( |
| 16 |
get_dtype_cache, decode_w_dtype, num2dtype) |
| 17 |
from pypy.module.micronumpy.base import convert_to_array, W_NDimArray |
| 18 |
from pypy.module.micronumpy.ctors import numpify |
| 19 |
from pypy.module.micronumpy.nditer import W_NDIter, coalesce_iter |
| 20 |
from pypy.module.micronumpy.strides import shape_agreement |
| 21 |
from pypy.module.micronumpy.support import (_parse_signature, product, |
| 22 |
get_storage_as_int, is_rhs_priority_higher) |
| 23 |
from .converters import out_converter |
| 24 |
from .casting import ( |
| 25 |
can_cast_type, can_cast_array, can_cast_to, |
| 26 |
find_result_type, promote_types) |
| 27 |
from .boxes import W_GenericBox, W_ObjectBox |
| 28 |
|
| 29 |
REDUCE, ACCUMULATE, REDUCEAT = range(3) |
| 30 |
_reduce_type = ["reduce", "acccumulate", "reduceat"] |
| 31 |
|
| 32 |
def done_if_true(dtype, val): |
| 33 |
return dtype.itemtype.bool(val) |
| 34 |
|
| 35 |
|
| 36 |
def done_if_false(dtype, val): |
| 37 |
return not dtype.itemtype.bool(val) |
| 38 |
|
| 39 |
|
| 40 |
def _find_array_wrap(*args, **kwds): |
| 41 |
'''determine an appropriate __array_wrap__ function to call for the outputs. |
| 42 |
If an output argument is provided, then it is wrapped |
| 43 |
with its own __array_wrap__ not with the one determined by |
| 44 |
the input arguments. |
| 45 |
|
| 46 |
if the provided output argument is already an array, |
| 47 |
the wrapping function is None (which means no wrapping will |
| 48 |
be done --- not even PyArray_Return). |
| 49 |
|
| 50 |
A NULL is placed in output_wrap for outputs that |
| 51 |
should just have PyArray_Return called. |
| 52 |
''' |
| 53 |
raise NotImplementedError() |
| 54 |
|
| 55 |
|
| 56 |
def array_priority(space, w_lhs, w_rhs): |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
w_ndarray = space.gettypefor(W_NDimArray) |
| 64 |
lhs_type = space.type(w_lhs) |
| 65 |
rhs_type = space.type(w_rhs) |
| 66 |
lhs_for_subtype = w_lhs |
| 67 |
rhs_for_subtype = w_rhs |
| 68 |
|
| 69 |
if not space.issubtype_w(lhs_type, w_ndarray): |
| 70 |
lhs_type = space.type(w_lhs.base) |
| 71 |
lhs_for_subtype = w_lhs.base |
| 72 |
if not space.issubtype_w(rhs_type, w_ndarray): |
| 73 |
rhs_type = space.type(w_rhs.base) |
| 74 |
rhs_for_subtype = w_rhs.base |
| 75 |
|
| 76 |
w_highpriority = w_lhs |
| 77 |
highpriority_subtype = lhs_for_subtype |
| 78 |
if space.is_w(lhs_type, w_ndarray) and not space.is_w(rhs_type, w_ndarray): |
| 79 |
highpriority_subtype = rhs_for_subtype |
| 80 |
w_highpriority = w_rhs |
| 81 |
if is_rhs_priority_higher(space, w_lhs, w_rhs): |
| 82 |
highpriority_subtype = rhs_for_subtype |
| 83 |
w_highpriority = w_rhs |
| 84 |
return w_highpriority, highpriority_subtype |
| 85 |
|
| 86 |
|
| 87 |
class W_Ufunc(W_Root): |
| 88 |
_immutable_fields_ = [ |
| 89 |
"name", "promote_to_largest", "promote_to_float", "promote_bools", "nin", |
| 90 |
"identity", "int_only", "allow_bool", "allow_complex", |
| 91 |
"complex_to_float", "nargs", "nout", "signature" |
| 92 |
] |
| 93 |
w_doc = None |
| 94 |
|
| 95 |
def __init__(self, name, promote_to_largest, promote_to_float, promote_bools, |
| 96 |
identity, int_only, allow_bool, allow_complex, complex_to_float): |
| 97 |
self.name = name |
| 98 |
self.promote_to_largest = promote_to_largest |
| 99 |
self.promote_to_float = promote_to_float |
| 100 |
self.promote_bools = promote_bools |
| 101 |
self.identity = identity |
| 102 |
self.int_only = int_only |
| 103 |
self.allow_bool = allow_bool |
| 104 |
self.allow_complex = allow_complex |
| 105 |
self.complex_to_float = complex_to_float |
| 106 |
|
| 107 |
def descr_get_name(self, space): |
| 108 |
return space.newtext(self.name) |
| 109 |
|
| 110 |
def descr_repr(self, space): |
| 111 |
return space.newtext("<ufunc '%s'>" % self.name) |
| 112 |
|
| 113 |
def get_doc(self, space): |
| 114 |
|
| 115 |
if self.w_doc is None: |
| 116 |
return space.w_None |
| 117 |
return self.w_doc |
| 118 |
|
| 119 |
def set_doc(self, space, w_doc): |
| 120 |
self.w_doc = w_doc |
| 121 |
|
| 122 |
def descr_get_identity(self, space): |
| 123 |
if self.identity is None: |
| 124 |
return space.w_None |
| 125 |
return self.identity |
| 126 |
|
| 127 |
def descr_call(self, space, __args__): |
| 128 |
args_w, kwds_w = __args__.unpack() |
| 129 |
|
| 130 |
w_subok, w_out, sig, w_casting, extobj = self.parse_kwargs(space, kwds_w) |
| 131 |
out = out_converter(space, w_out) |
| 132 |
if (w_subok is not None and space.is_true(w_subok)): |
| 133 |
raise oefmt(space.w_NotImplementedError, "parameter subok unsupported") |
| 134 |
if kwds_w: |
| 135 |
|
| 136 |
kw = kwds_w.keys()[0] |
| 137 |
raise oefmt(space.w_TypeError, |
| 138 |
"'%s' is an invalid keyword to ufunc '%s'", kw, self.name) |
| 139 |
if len(args_w) < self.nin: |
| 140 |
raise oefmt(space.w_ValueError, "invalid number of arguments" |
| 141 |
", expected %d got %d", len(args_w), self.nin) |
| 142 |
elif (len(args_w) > self.nin and out is not None) or \ |
| 143 |
(len(args_w) > self.nin + 1): |
| 144 |
raise oefmt(space.w_TypeError, "invalid number of arguments") |
| 145 |
|
| 146 |
if len(args_w) > self.nin: |
| 147 |
if out: |
| 148 |
raise oefmt(space.w_ValueError, "cannot specify 'out' as both " |
| 149 |
"a positional and keyword argument") |
| 150 |
out = args_w[-1] |
| 151 |
else: |
| 152 |
args_w = args_w + [out] |
| 153 |
if w_casting is None: |
| 154 |
casting = 'unsafe' |
| 155 |
else: |
| 156 |
casting = space.text_w(w_casting) |
| 157 |
retval = self.call(space, args_w, sig, casting, extobj) |
| 158 |
keepalive_until_here(args_w) |
| 159 |
return retval |
| 160 |
|
| 161 |
def descr_accumulate(self, space, w_obj, w_axis=None, w_dtype=None, w_out=None): |
| 162 |
if w_axis is None: |
| 163 |
w_axis = space.newint(0) |
| 164 |
out = out_converter(space, w_out) |
| 165 |
return self.reduce(space, w_obj, w_axis, True, |
| 166 |
out, w_dtype, variant=ACCUMULATE) |
| 167 |
|
| 168 |
@unwrap_spec(keepdims=bool) |
| 169 |
def descr_reduce(self, space, w_obj, w_axis=None, w_dtype=None, |
| 170 |
w_out=None, keepdims=False): |
| 171 |
from pypy.module.micronumpy.ndarray import W_NDimArray |
| 172 |
if w_axis is None: |
| 173 |
w_axis = space.newint(0) |
| 174 |
out = out_converter(space, w_out) |
| 175 |
return self.reduce(space, w_obj, w_axis, keepdims, out, w_dtype) |
| 176 |
|
| 177 |
@specialize.arg(7) |
| 178 |
def reduce(self, space, w_obj, w_axis, keepdims=False, out=None, dtype=None, |
| 179 |
variant=REDUCE): |
| 180 |
if self.nin != 2: |
| 181 |
raise oefmt(space.w_ValueError, |
| 182 |
"%s only supported for binary functions", |
| 183 |
_reduce_type[variant]) |
| 184 |
assert isinstance(self, W_Ufunc2) |
| 185 |
obj = convert_to_array(space, w_obj) |
| 186 |
if obj.get_dtype().is_flexible(): |
| 187 |
raise oefmt(space.w_TypeError, |
| 188 |
"cannot perform %s with flexible type", |
| 189 |
_reduce_type[variant]) |
| 190 |
obj_shape = obj.get_shape() |
| 191 |
if obj.is_scalar(): |
| 192 |
return obj.get_scalar_value() |
| 193 |
shapelen = len(obj_shape) |
| 194 |
|
| 195 |
if space.is_none(w_axis): |
| 196 |
axes = range(shapelen) |
| 197 |
axis = maxint |
| 198 |
elif space.isinstance_w(w_axis, space.w_tuple): |
| 199 |
axes_w = space.listview(w_axis) |
| 200 |
axes = [0] * len(axes_w) |
| 201 |
for i in range(len(axes_w)): |
| 202 |
x = space.int_w(axes_w[i]) |
| 203 |
if x < 0: |
| 204 |
x += shapelen |
| 205 |
if x < 0 or x >= shapelen: |
| 206 |
raise oefmt(space.w_ValueError, "'axis' entry is out of bounds") |
| 207 |
axes[i] = x |
| 208 |
else: |
| 209 |
if space.isinstance_w(w_axis, space.w_tuple) and space.len_w(w_axis) == 1: |
| 210 |
w_axis = space.getitem(w_axis, space.newint(0)) |
| 211 |
axis = space.int_w(w_axis) |
| 212 |
if axis < -shapelen or axis >= shapelen: |
| 213 |
raise oefmt(space.w_ValueError, "'axis' entry is out of bounds") |
| 214 |
if axis < 0: |
| 215 |
axis += shapelen |
| 216 |
axes = [axis] |
| 217 |
dtype = decode_w_dtype(space, dtype) |
| 218 |
|
| 219 |
if dtype is None and out is not None: |
| 220 |
dtype = out.get_dtype() |
| 221 |
|
| 222 |
if dtype is None: |
| 223 |
obj_dtype = obj.get_dtype() |
| 224 |
num = obj_dtype.num |
| 225 |
if ((obj_dtype.is_bool() or obj_dtype.is_int()) and |
| 226 |
self.promote_to_largest): |
| 227 |
if obj_dtype.is_bool(): |
| 228 |
num = NPY.LONG |
| 229 |
elif obj_dtype.elsize * 8 < LONG_BIT: |
| 230 |
if obj_dtype.is_unsigned(): |
| 231 |
num = NPY.ULONG |
| 232 |
else: |
| 233 |
num = NPY.LONG |
| 234 |
dtype = num2dtype(space, num) |
| 235 |
|
| 236 |
if self.identity is None: |
| 237 |
for i in axes: |
| 238 |
if obj_shape[i] == 0: |
| 239 |
raise oefmt(space.w_ValueError, |
| 240 |
"zero-size array to reduction operation %s " |
| 241 |
"which has no identity", self.name) |
| 242 |
|
| 243 |
if variant == ACCUMULATE: |
| 244 |
if len(axes) != 1: |
| 245 |
raise oefmt(space.w_ValueError, |
| 246 |
"accumulate does not allow multiple axes") |
| 247 |
axis = axes[0] |
| 248 |
assert axis >= 0 |
| 249 |
dtype = self.find_binop_type(space, dtype) |
| 250 |
shape = obj_shape[:] |
| 251 |
if out: |
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
if out.get_shape() != obj_shape: |
| 256 |
raise oefmt(space.w_ValueError, |
| 257 |
"output parameter shape mismatch, expecting " |
| 258 |
"[%s], got [%s]", |
| 259 |
",".join([str(x) for x in shape]), |
| 260 |
",".join([str(x) for x in out.get_shape()]), |
| 261 |
) |
| 262 |
dtype = out.get_dtype() |
| 263 |
call__array_wrap__ = False |
| 264 |
else: |
| 265 |
out = W_NDimArray.from_shape(space, shape, dtype, |
| 266 |
w_instance=obj) |
| 267 |
call__array_wrap__ = True |
| 268 |
if shapelen > 1: |
| 269 |
if obj.get_size() == 0: |
| 270 |
if self.identity is not None: |
| 271 |
out.fill(space, self.identity.convert_to(space, dtype)) |
| 272 |
return out |
| 273 |
loop.accumulate( |
| 274 |
space, self.func, obj, axis, dtype, out, self.identity) |
| 275 |
else: |
| 276 |
loop.accumulate_flat( |
| 277 |
space, self.func, obj, dtype, out, self.identity) |
| 278 |
if call__array_wrap__: |
| 279 |
out = space.call_method(obj, '__array_wrap__', out, space.w_None) |
| 280 |
return out |
| 281 |
|
| 282 |
axis_flags = [False] * shapelen |
| 283 |
for i in axes: |
| 284 |
if axis_flags[i]: |
| 285 |
raise oefmt(space.w_ValueError, "duplicate value in 'axis'") |
| 286 |
axis_flags[i] = True |
| 287 |
|
| 288 |
|
| 289 |
_, dtype, _ = self.find_specialization(space, dtype, dtype, out, |
| 290 |
casting='unsafe') |
| 291 |
if shapelen == len(axes): |
| 292 |
if out: |
| 293 |
if out.ndims() > 0: |
| 294 |
raise oefmt(space.w_ValueError, |
| 295 |
"output parameter for reduction operation %s has " |
| 296 |
"too many dimensions", self.name) |
| 297 |
dtype = out.get_dtype() |
| 298 |
res = loop.reduce_flat( |
| 299 |
space, self.func, obj, dtype, self.done_func, self.identity) |
| 300 |
if out: |
| 301 |
out.set_scalar_value(res) |
| 302 |
return out |
| 303 |
w_NDimArray = space.gettypefor(W_NDimArray) |
| 304 |
call__array_wrap__ = False |
| 305 |
if keepdims: |
| 306 |
shape = [1] * len(obj_shape) |
| 307 |
out = W_NDimArray.from_shape(space, shape, dtype, w_instance=obj) |
| 308 |
out.implementation.setitem(0, res) |
| 309 |
call__array_wrap__ = True |
| 310 |
res = out |
| 311 |
elif (space.issubtype_w(space.type(w_obj), w_NDimArray) and |
| 312 |
not space.is_w(space.type(w_obj), w_NDimArray)): |
| 313 |
|
| 314 |
out = W_NDimArray.from_shape(space, [1], dtype, w_instance=obj) |
| 315 |
out.implementation.setitem(0, res) |
| 316 |
call__array_wrap__ = True |
| 317 |
res = out |
| 318 |
if call__array_wrap__: |
| 319 |
res = space.call_method(obj, '__array_wrap__', res, space.w_None) |
| 320 |
return res |
| 321 |
|
| 322 |
else: |
| 323 |
temp = None |
| 324 |
if keepdims: |
| 325 |
shape = obj_shape[:] |
| 326 |
for axis in axes: |
| 327 |
shape[axis] = 1 |
| 328 |
else: |
| 329 |
shape = [0] * (shapelen - len(axes)) |
| 330 |
j = 0 |
| 331 |
for i in range(shapelen): |
| 332 |
if not axis_flags[i]: |
| 333 |
shape[j] = obj_shape[i] |
| 334 |
j += 1 |
| 335 |
if out: |
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
if out.ndims() > len(shape): |
| 340 |
raise oefmt(space.w_ValueError, |
| 341 |
"output parameter for reduction operation %s " |
| 342 |
"has too many dimensions", self.name) |
| 343 |
elif out.ndims() < len(shape): |
| 344 |
raise oefmt(space.w_ValueError, |
| 345 |
"output parameter for reduction operation %s " |
| 346 |
"does not have enough dimensions", self.name) |
| 347 |
elif out.get_shape() != shape: |
| 348 |
raise oefmt(space.w_ValueError, |
| 349 |
"output parameter shape mismatch, expecting " |
| 350 |
"[%s], got [%s]", |
| 351 |
",".join([str(x) for x in shape]), |
| 352 |
",".join([str(x) for x in out.get_shape()]), |
| 353 |
) |
| 354 |
call__array_wrap__ = False |
| 355 |
dtype = out.get_dtype() |
| 356 |
else: |
| 357 |
out = W_NDimArray.from_shape(space, shape, dtype, |
| 358 |
w_instance=obj) |
| 359 |
if obj.get_size() == 0: |
| 360 |
if self.identity is not None: |
| 361 |
out.fill(space, self.identity.convert_to(space, dtype)) |
| 362 |
return out |
| 363 |
loop.reduce( |
| 364 |
space, self.func, obj, axis_flags, dtype, out, self.identity) |
| 365 |
out = space.call_method(obj, '__array_wrap__', out, space.w_None) |
| 366 |
return out |
| 367 |
|
| 368 |
def descr_outer(self, space, args_w): |
| 369 |
if self.nin != 2: |
| 370 |
raise oefmt(space.w_ValueError, |
| 371 |
"outer product only supported for binary functions") |
| 372 |
if len(args_w) != 2: |
| 373 |
raise oefmt(space.w_ValueError, |
| 374 |
"exactly two arguments expected") |
| 375 |
args = [convert_to_array(space, w_obj) for w_obj in args_w] |
| 376 |
w_outshape = [space.newint(i) for i in args[0].get_shape() + [1]*args[1].ndims()] |
| 377 |
args0 = args[0].reshape(space, space.newtuple(w_outshape)) |
| 378 |
return self.descr_call(space, Arguments.frompacked(space, |
| 379 |
space.newlist([args0, args[1]]))) |
| 380 |
|
| 381 |
def parse_kwargs(self, space, kwds_w): |
| 382 |
w_casting = kwds_w.pop('casting', None) |
| 383 |
w_subok = kwds_w.pop('subok', None) |
| 384 |
w_out = kwds_w.pop('out', space.w_None) |
| 385 |
sig = None |
| 386 |
|
| 387 |
|
| 388 |
extobj_w = kwds_w.pop('extobj', get_extobj(space)) |
| 389 |
if not space.isinstance_w(extobj_w, space.w_list) or space.len_w(extobj_w) != 3: |
| 390 |
raise oefmt(space.w_TypeError, "'extobj' must be a list of 3 values") |
| 391 |
return w_subok, w_out, sig, w_casting, extobj_w |
| 392 |
|
| 393 |
def get_extobj(space): |
| 394 |
extobj_w = space.newlist([space.newint(8192), space.newint(0), space.w_None]) |
| 395 |
return extobj_w |
| 396 |
|
| 397 |
|
| 398 |
_reflected_ops = { |
| 399 |
'add': 'radd', |
| 400 |
'subtract': 'rsub', |
| 401 |
'multiply': 'rmul', |
| 402 |
'divide': 'rdiv', |
| 403 |
'true_divide': 'rtruediv', |
| 404 |
'floor_divide': 'rfloordiv', |
| 405 |
'remainder': 'rmod', |
| 406 |
'power': 'rpow', |
| 407 |
'left_shift': 'rlshift', |
| 408 |
'right_shift': 'rrshift', |
| 409 |
'bitwise_and': 'rand', |
| 410 |
'bitwise_xor': 'rxor', |
| 411 |
'bitwise_or': 'ror', |
| 412 |
|
| 413 |
'equal': 'eq', |
| 414 |
'not_equal': 'ne', |
| 415 |
'greater': 'lt', |
| 416 |
'less': 'gt', |
| 417 |
'greater_equal': 'le', |
| 418 |
'less_equal': 'ge', |
| 419 |
} |
| 420 |
|
| 421 |
for key, value in _reflected_ops.items(): |
| 422 |
_reflected_ops[key] = "__" + value + "__" |
| 423 |
del key |
| 424 |
del value |
| 425 |
|
| 426 |
def _has_reflected_op(space, w_obj, op): |
| 427 |
if op not in _reflected_ops: |
| 428 |
return False |
| 429 |
return space.getattr(w_obj, space.newtext(_reflected_ops[op])) is not None |
| 430 |
|
| 431 |
def safe_casting_mode(casting): |
| 432 |
assert casting is not None |
| 433 |
if casting in ('unsafe', 'same_kind'): |
| 434 |
return 'safe' |
| 435 |
else: |
| 436 |
return casting |
| 437 |
|
| 438 |
class W_Ufunc1(W_Ufunc): |
| 439 |
_immutable_fields_ = ["func", "bool_result", "dtypes[*]"] |
| 440 |
nin = 1 |
| 441 |
nout = 1 |
| 442 |
nargs = 2 |
| 443 |
signature = None |
| 444 |
|
| 445 |
def __init__(self, func, name, promote_to_largest=False, promote_to_float=False, |
| 446 |
promote_bools=False, identity=None, bool_result=False, int_only=False, |
| 447 |
allow_bool=True, allow_complex=True, complex_to_float=False): |
| 448 |
W_Ufunc.__init__(self, name, promote_to_largest, promote_to_float, promote_bools, |
| 449 |
identity, int_only, allow_bool, allow_complex, complex_to_float) |
| 450 |
self.func = func |
| 451 |
self.bool_result = bool_result |
| 452 |
|
| 453 |
def call(self, space, args_w, sig, casting, extobj): |
| 454 |
w_obj = args_w[0] |
| 455 |
out = None |
| 456 |
if len(args_w) > 1: |
| 457 |
out = out_converter(space, args_w[1]) |
| 458 |
w_obj = numpify(space, w_obj) |
| 459 |
dtype = w_obj.get_dtype(space) |
| 460 |
calc_dtype, dt_out, func = self.find_specialization(space, dtype, out, casting) |
| 461 |
if isinstance(w_obj, W_GenericBox): |
| 462 |
if out is None: |
| 463 |
return self.call_scalar(space, w_obj, calc_dtype) |
| 464 |
else: |
| 465 |
w_obj = W_NDimArray.from_scalar(space, w_obj) |
| 466 |
assert isinstance(w_obj, W_NDimArray) |
| 467 |
shape = shape_agreement(space, w_obj.get_shape(), out, |
| 468 |
broadcast_down=False) |
| 469 |
if out is None: |
| 470 |
w_res = W_NDimArray.from_shape( |
| 471 |
space, shape, dt_out, w_instance=w_obj) |
| 472 |
else: |
| 473 |
w_res = out |
| 474 |
w_res = loop.call1(space, shape, func, calc_dtype, w_obj, w_res) |
| 475 |
if out is None: |
| 476 |
if w_res.is_scalar(): |
| 477 |
return w_res.get_scalar_value() |
| 478 |
ctxt = space.newtuple([self, space.newtuple([w_obj]), space.newint(0)]) |
| 479 |
w_res = space.call_method(w_obj, '__array_wrap__', w_res, ctxt) |
| 480 |
return w_res |
| 481 |
|
| 482 |
def call_scalar(self, space, w_arg, in_dtype): |
| 483 |
w_val = self.func(in_dtype, w_arg.convert_to(space, in_dtype)) |
| 484 |
if isinstance(w_val, W_ObjectBox): |
| 485 |
return w_val.w_obj |
| 486 |
return w_val |
| 487 |
|
| 488 |
def find_specialization(self, space, dtype, out, casting): |
| 489 |
if dtype.is_flexible(): |
| 490 |
raise oefmt(space.w_TypeError, "ufunc '%s' did not contain a loop", |
| 491 |
self.name) |
| 492 |
if (not self.allow_bool and dtype.is_bool() or |
| 493 |
not self.allow_complex and dtype.is_complex()): |
| 494 |
raise oefmt(space.w_TypeError, |
| 495 |
"ufunc %s not supported for the input type", self.name) |
| 496 |
dt_in, dt_out = self._calc_dtype(space, dtype, out, casting) |
| 497 |
return dt_in, dt_out, self.func |
| 498 |
|
| 499 |
@jit.unroll_safe |
| 500 |
def _calc_dtype(self, space, arg_dtype, out=None, casting='unsafe'): |
| 501 |
if arg_dtype.is_object(): |
| 502 |
return arg_dtype, arg_dtype |
| 503 |
in_casting = safe_casting_mode(casting) |
| 504 |
for dt_in, dt_out in self.dtypes: |
| 505 |
if not can_cast_type(space, arg_dtype, dt_in, in_casting): |
| 506 |
continue |
| 507 |
if out is not None: |
| 508 |
res_dtype = out.get_dtype() |
| 509 |
if not can_cast_type(space, dt_out, res_dtype, casting): |
| 510 |
continue |
| 511 |
return dt_in, dt_out |
| 512 |
|
| 513 |
else: |
| 514 |
raise oefmt(space.w_TypeError, |
| 515 |
"ufunc '%s' not supported for the input types", self.name) |
| 516 |
|
| 517 |
|
| 518 |
class W_Ufunc2(W_Ufunc): |
| 519 |
_immutable_fields_ = ["func", "bool_result", "done_func", "dtypes[*]", |
| 520 |
"simple_binary"] |
| 521 |
nin = 2 |
| 522 |
nout = 1 |
| 523 |
nargs = 3 |
| 524 |
signature = None |
| 525 |
|
| 526 |
def __init__(self, func, name, promote_to_largest=False, promote_to_float=False, |
| 527 |
promote_bools=False, identity=None, bool_result=False, int_only=False, |
| 528 |
allow_bool=True, allow_complex=True, complex_to_float=False): |
| 529 |
W_Ufunc.__init__(self, name, promote_to_largest, promote_to_float, promote_bools, |
| 530 |
identity, int_only, allow_bool, allow_complex, complex_to_float) |
| 531 |
self.func = func |
| 532 |
if name == 'logical_and': |
| 533 |
self.done_func = done_if_false |
| 534 |
elif name == 'logical_or': |
| 535 |
self.done_func = done_if_true |
| 536 |
else: |
| 537 |
self.done_func = None |
| 538 |
self.bool_result = bool_result or (self.done_func is not None) |
| 539 |
self.simple_binary = ( |
| 540 |
allow_complex and allow_bool and not self.bool_result and not int_only |
| 541 |
and not complex_to_float and not promote_to_float |
| 542 |
and not promote_bools) |
| 543 |
|
| 544 |
def are_common_types(self, dtype1, dtype2): |
| 545 |
if dtype1.is_bool() or dtype2.is_bool(): |
| 546 |
return False |
| 547 |
if (dtype1.is_int() and dtype2.is_int() or |
| 548 |
dtype1.is_float() and dtype2.is_float() or |
| 549 |
dtype1.is_complex() and dtype2.is_complex()): |
| 550 |
return True |
| 551 |
return False |
| 552 |
|
| 553 |
@jit.unroll_safe |
| 554 |
def call(self, space, args_w, sig, casting, extobj): |
| 555 |
if len(args_w) > 2: |
| 556 |
[w_lhs, w_rhs, out] = args_w |
| 557 |
out = out_converter(space, out) |
| 558 |
else: |
| 559 |
[w_lhs, w_rhs] = args_w |
| 560 |
out = None |
| 561 |
if not isinstance(w_rhs, W_NDimArray): |
| 562 |
|
| 563 |
|
| 564 |
|
| 565 |
|
| 566 |
|
| 567 |
r_greater = is_rhs_priority_higher(space, w_lhs, w_rhs) |
| 568 |
if r_greater and _has_reflected_op(space, w_rhs, self.name): |
| 569 |
return space.w_NotImplemented |
| 570 |
w_lhs = numpify(space, w_lhs) |
| 571 |
w_rhs = numpify(space, w_rhs) |
| 572 |
w_ldtype = w_lhs.get_dtype(space) |
| 573 |
w_rdtype = w_rhs.get_dtype(space) |
| 574 |
if w_ldtype.is_object() or w_rdtype.is_object(): |
| 575 |
if ((w_ldtype.is_object() and w_ldtype.is_record()) and |
| 576 |
(w_rdtype.is_object() and w_rdtype.is_record())): |
| 577 |
pass |
| 578 |
elif ((w_ldtype.is_object() and w_ldtype.is_record()) or |
| 579 |
(w_rdtype.is_object() and w_rdtype.is_record())): |
| 580 |
if self.name == 'not_equal': |
| 581 |
return space.w_True |
| 582 |
elif self.name == 'equal': |
| 583 |
return space.w_False |
| 584 |
else: |
| 585 |
msg = ("ufunc '%s' not supported for the input types, " |
| 586 |
"and the inputs could not be safely coerced to " |
| 587 |
"any supported types according to the casting " |
| 588 |
"rule '%s'") |
| 589 |
raise oefmt(space.w_TypeError, msg, self.name, casting) |
| 590 |
else: |
| 591 |
pass |
| 592 |
elif w_ldtype.is_str() and w_rdtype.is_str() and \ |
| 593 |
self.bool_result: |
| 594 |
pass |
| 595 |
elif (w_ldtype.is_str()) and \ |
| 596 |
self.bool_result and out is None: |
| 597 |
if self.name in ('equal', 'less_equal', 'less'): |
| 598 |
return space.w_False |
| 599 |
return space.w_True |
| 600 |
elif (w_rdtype.is_str()) and \ |
| 601 |
self.bool_result and out is None: |
| 602 |
if self.name in ('not_equal','less', 'less_equal'): |
| 603 |
return space.w_True |
| 604 |
return space.w_False |
| 605 |
elif w_ldtype.is_flexible() or w_rdtype.is_flexible(): |
| 606 |
if self.bool_result: |
| 607 |
if self.name == 'equal' or self.name == 'not_equal': |
| 608 |
res = w_ldtype.eq(space, w_rdtype) |
| 609 |
if not res: |
| 610 |
return space.newbool(self.name == 'not_equal') |
| 611 |
else: |
| 612 |
return space.w_NotImplemented |
| 613 |
else: |
| 614 |
raise oefmt(space.w_TypeError, |
| 615 |
'unsupported operand dtypes %s and %s for "%s"', |
| 616 |
w_rdtype.get_name(), w_ldtype.get_name(), |
| 617 |
self.name) |
| 618 |
|
| 619 |
if (isinstance(w_lhs, W_GenericBox) and |
| 620 |
isinstance(w_rhs, W_GenericBox) and out is None): |
| 621 |
return self.call_scalar(space, w_lhs, w_rhs, casting) |
| 622 |
if isinstance(w_lhs, W_GenericBox): |
| 623 |
w_lhs = W_NDimArray.from_scalar(space, w_lhs) |
| 624 |
assert isinstance(w_lhs, W_NDimArray) |
| 625 |
if isinstance(w_rhs, W_GenericBox): |
| 626 |
w_rhs = W_NDimArray.from_scalar(space, w_rhs) |
| 627 |
assert isinstance(w_rhs, W_NDimArray) |
| 628 |
calc_dtype, dt_out, func = self.find_specialization( |
| 629 |
space, w_ldtype, w_rdtype, out, casting, w_lhs, w_rhs) |
| 630 |
|
| 631 |
new_shape = shape_agreement(space, w_lhs.get_shape(), w_rhs) |
| 632 |
new_shape = shape_agreement(space, new_shape, out, broadcast_down=False) |
| 633 |
w_highpriority, out_subtype = array_priority(space, w_lhs, w_rhs) |
| 634 |
if out is None: |
| 635 |
w_res = W_NDimArray.from_shape(space, new_shape, dt_out, |
| 636 |
w_instance=out_subtype) |
| 637 |
else: |
| 638 |
w_res = out |
| 639 |
w_res = loop.call2(space, new_shape, self.func, calc_dtype, |
| 640 |
w_lhs, w_rhs, w_res) |
| 641 |
if out is None: |
| 642 |
if w_res.is_scalar(): |
| 643 |
return w_res.get_scalar_value() |
| 644 |
ctxt = space.newtuple([self, space.newtuple([w_lhs, w_rhs]), space.newint(0)]) |
| 645 |
w_res = space.call_method(w_highpriority, '__array_wrap__', w_res, ctxt) |
| 646 |
return w_res |
| 647 |
|
| 648 |
def call_scalar(self, space, w_lhs, w_rhs, casting): |
| 649 |
in_dtype, out_dtype, func = self.find_specialization( |
| 650 |
space, w_lhs.get_dtype(space), w_rhs.get_dtype(space), |
| 651 |
out=None, casting=casting) |
| 652 |
w_val = self.func(in_dtype, |
| 653 |
w_lhs.convert_to(space, in_dtype), |
| 654 |
w_rhs.convert_to(space, in_dtype)) |
| 655 |
if isinstance(w_val, W_ObjectBox): |
| 656 |
return w_val.w_obj |
| 657 |
return w_val |
| 658 |
|
| 659 |
def _find_specialization(self, space, l_dtype, r_dtype, out, casting, |
| 660 |
w_arg1, w_arg2): |
| 661 |
if (not self.allow_bool and (l_dtype.is_bool() or |
| 662 |
r_dtype.is_bool()) or |
| 663 |
not self.allow_complex and (l_dtype.is_complex() or |
| 664 |
r_dtype.is_complex())): |
| 665 |
raise oefmt(space.w_TypeError, |
| 666 |
"ufunc '%s' not supported for the input types", self.name) |
| 667 |
if self.bool_result and not self.done_func: |
| 668 |
|
| 669 |
dtype = find_result_type(space, [], [l_dtype, r_dtype]) |
| 670 |
bool_dtype = get_dtype_cache(space).w_booldtype |
| 671 |
return dtype, bool_dtype, self.func |
| 672 |
dt_in, dt_out = self._calc_dtype( |
| 673 |
space, l_dtype, r_dtype, out, casting, w_arg1, w_arg2) |
| 674 |
return dt_in, dt_out, self.func |
| 675 |
|
| 676 |
def find_specialization(self, space, l_dtype, r_dtype, out, casting, |
| 677 |
w_arg1=None, w_arg2=None): |
| 678 |
if self.simple_binary: |
| 679 |
if out is None and not (l_dtype.is_object() or r_dtype.is_object()): |
| 680 |
if w_arg1 is not None and w_arg2 is not None: |
| 681 |
w_arg1 = convert_to_array(space, w_arg1) |
| 682 |
w_arg2 = convert_to_array(space, w_arg2) |
| 683 |
dtype = find_result_type(space, [w_arg1, w_arg2], []) |
| 684 |
else: |
| 685 |
dtype = promote_types(space, l_dtype, r_dtype) |
| 686 |
return dtype, dtype, self.func |
| 687 |
return self._find_specialization( |
| 688 |
space, l_dtype, r_dtype, out, casting, w_arg1, w_arg2) |
| 689 |
|
| 690 |
def find_binop_type(self, space, dtype): |
| 691 |
"""Find a valid dtype signature of the form xx->x""" |
| 692 |
if dtype.is_object(): |
| 693 |
return dtype |
| 694 |
for dt_in, dt_out in self.dtypes: |
| 695 |
if can_cast_to(dtype, dt_in): |
| 696 |
if dt_out == dt_in: |
| 697 |
return dt_in |
| 698 |
else: |
| 699 |
dtype = dt_out |
| 700 |
break |
| 701 |
for dt_in, dt_out in self.dtypes: |
| 702 |
if can_cast_to(dtype, dt_in) and dt_out == dt_in: |
| 703 |
return dt_in |
| 704 |
raise oefmt(space.w_ValueError, |
| 705 |
"could not find a matching type for %s.accumulate, " |
| 706 |
"requested type has type code '%s'", self.name, dtype.char) |
| 707 |
|
| 708 |
|
| 709 |
@jit.unroll_safe |
| 710 |
def _calc_dtype(self, space, l_dtype, r_dtype, out, casting, |
| 711 |
w_arg1, w_arg2): |
| 712 |
if l_dtype.is_object() or r_dtype.is_object(): |
| 713 |
dtype = get_dtype_cache(space).w_objectdtype |
| 714 |
return dtype, dtype |
| 715 |
use_min_scalar = (w_arg1 is not None and w_arg2 is not None and |
| 716 |
((w_arg1.is_scalar() and not w_arg2.is_scalar()) or |
| 717 |
(not w_arg1.is_scalar() and w_arg2.is_scalar()))) |
| 718 |
in_casting = safe_casting_mode(casting) |
| 719 |
if use_min_scalar: |
| 720 |
w_arg1 = convert_to_array(space, w_arg1) |
| 721 |
w_arg2 = convert_to_array(space, w_arg2) |
| 722 |
elif (in_casting == 'safe' and l_dtype.num == 7 and r_dtype.num == 7 and |
| 723 |
out is None and not self.promote_to_float): |
| 724 |
|
| 725 |
return l_dtype, l_dtype |
| 726 |
for dt_in, dt_out in self.dtypes: |
| 727 |
if use_min_scalar: |
| 728 |
if not (can_cast_array(space, w_arg1, dt_in, in_casting) and |
| 729 |
can_cast_array(space, w_arg2, dt_in, in_casting)): |
| 730 |
continue |
| 731 |
else: |
| 732 |
if not (can_cast_type(space, l_dtype, dt_in, in_casting) and |
| 733 |
can_cast_type(space, r_dtype, dt_in, in_casting)): |
| 734 |
continue |
| 735 |
if out is not None: |
| 736 |
res_dtype = out.get_dtype() |
| 737 |
if not can_cast_type(space, dt_out, res_dtype, casting): |
| 738 |
continue |
| 739 |
return dt_in, dt_out |
| 740 |
|
| 741 |
else: |
| 742 |
raise oefmt(space.w_TypeError, |
| 743 |
"ufunc '%s' not supported for the input types", self.name) |
| 744 |
|
| 745 |
def _match_dtypes(space, indtypes, targetdtypes, i_target, casting): |
| 746 |
allok = True |
| 747 |
for i in range(len(indtypes)): |
| 748 |
origin = indtypes[i] |
| 749 |
target = targetdtypes[i + i_target] |
| 750 |
if origin is None: |
| 751 |
continue |
| 752 |
if target is None: |
| 753 |
continue |
| 754 |
if not can_cast_type(space, origin, target, casting): |
| 755 |
allok = False |
| 756 |
break |
| 757 |
return allok |
| 758 |
|
| 759 |
def _raise_err_msg(self, space, dtypes0, dtypes1): |
| 760 |
dtypesstr = '' |
| 761 |
for d in dtypes0: |
| 762 |
if d is None: |
| 763 |
dtypesstr += 'None,' |
| 764 |
else: |
| 765 |
dtypesstr += '%s%s%s,' % (d.byteorder, d.kind, d.elsize) |
| 766 |
_dtypesstr = ','.join(['%s%s%s' % (d.byteorder, d.kind, d.elsize) \ |
| 767 |
for d in dtypes1]) |
| 768 |
raise oefmt(space.w_TypeError, |
| 769 |
"input dtype [%s] did not match any known dtypes [%s] ", |
| 770 |
dtypesstr,_dtypesstr) |
| 771 |
|
| 772 |
|
| 773 |
class W_UfuncGeneric(W_Ufunc): |
| 774 |
''' |
| 775 |
Handle a number of python functions, each with a signature and dtypes. |
| 776 |
The signature can specify how to create the inner loop, i.e. |
| 777 |
(i,j),(j,k)->(i,k) for a dot-like matrix multiplication, and the dtypes |
| 778 |
can specify the input, output args for the function. When called, the actual |
| 779 |
function used will be resolved by examining the input arg's dtypes. |
| 780 |
|
| 781 |
If dtypes == 'match', only one argument is provided and the output dtypes |
| 782 |
will match the input dtype (not cpython numpy compatible) |
| 783 |
|
| 784 |
This is the parallel to PyUFuncOjbect, see include/numpy/ufuncobject.h |
| 785 |
''' |
| 786 |
_immutable_fields_ = ["funcs", "dtypes", "data", "match_dtypes"] |
| 787 |
|
| 788 |
def __init__(self, space, funcs, name, identity, nin, nout, dtypes, |
| 789 |
signature, match_dtypes=False, stack_inputs=False, |
| 790 |
external_loop=False): |
| 791 |
|
| 792 |
|
| 793 |
|
| 794 |
|
| 795 |
promote_to_largest = promote_to_float = promote_bools = False |
| 796 |
allow_bool = allow_complex = True |
| 797 |
int_only = complex_to_float = False |
| 798 |
W_Ufunc.__init__(self, name, promote_to_largest, promote_to_float, promote_bools, |
| 799 |
identity, int_only, allow_bool, allow_complex, complex_to_float) |
| 800 |
self.funcs = funcs |
| 801 |
self.dtypes = dtypes |
| 802 |
self.nin = nin |
| 803 |
self.nout = nout |
| 804 |
self.match_dtypes = match_dtypes |
| 805 |
self.nargs = nin + max(nout, 1) |
| 806 |
if not match_dtypes and (len(dtypes) % len(funcs) != 0 or |
| 807 |
len(dtypes) / len(funcs) != self.nargs): |
| 808 |
raise oefmt(space.w_ValueError, |
| 809 |
"generic ufunc with %d functions, %d arguments, but %d dtypes", |
| 810 |
len(funcs), self.nargs, len(dtypes)) |
| 811 |
self.signature = signature |
| 812 |
|
| 813 |
self.core_enabled = True |
| 814 |
self.stack_inputs = stack_inputs |
| 815 |
self.core_num_dim_ix = 0 |
| 816 |
self.core_num_dims = [0] * self.nargs |
| 817 |
self.core_offsets = [0] * self.nargs |
| 818 |
self.core_dim_ixs = [] |
| 819 |
self.external_loop = external_loop |
| 820 |
|
| 821 |
def reduce(self, space, w_obj, w_axis, keepdims=False, out=None, dtype=None, |
| 822 |
variant=REDUCE): |
| 823 |
raise oefmt(space.w_NotImplementedError, 'not implemented yet') |
| 824 |
|
| 825 |
def call(self, space, args_w, sig, casting, extobj): |
| 826 |
if len(args_w) < self.nin: |
| 827 |
raise oefmt(space.w_ValueError, |
| 828 |
'%s called with too few input args, expected at least %d got %d', |
| 829 |
self.name, self.nin, len(args_w)) |
| 830 |
inargs = [convert_to_array(space, args_w[i]) for i in range(self.nin)] |
| 831 |
outargs = [None] * self.nout |
| 832 |
for i in range(len(args_w)-self.nin): |
| 833 |
out = args_w[i+self.nin] |
| 834 |
if space.is_w(out, space.w_None) or out is None: |
| 835 |
continue |
| 836 |
else: |
| 837 |
if not isinstance(out, W_NDimArray): |
| 838 |
raise oefmt(space.w_TypeError, |
| 839 |
'output arg %d must be an array, not %s', i+self.nin, str(args_w[i+self.nin])) |
| 840 |
outargs[i] = out |
| 841 |
_dtypes = self.dtypes |
| 842 |
if self.match_dtypes: |
| 843 |
_dtypes = [i.get_dtype() for i in inargs if isinstance(i, W_NDimArray)] |
| 844 |
for i in outargs: |
| 845 |
if isinstance(i, W_NDimArray): |
| 846 |
_dtypes.append(i.get_dtype()) |
| 847 |
else: |
| 848 |
_dtypes.append(_dtypes[0]) |
| 849 |
index, dtypes = self.type_resolver(space, inargs, outargs, sig, _dtypes) |
| 850 |
func = self.funcs[index] |
| 851 |
iter_shape, arg_shapes, matched_dims = self.verify_args(space, inargs, outargs) |
| 852 |
inargs, outargs, need_to_cast = self.alloc_args(space, inargs, outargs, dtypes, |
| 853 |
arg_shapes) |
| 854 |
if not self.external_loop: |
| 855 |
inargs0 = inargs[0] |
| 856 |
outargs0 = outargs[0] |
| 857 |
assert isinstance(inargs0, W_NDimArray) |
| 858 |
assert isinstance(outargs0, W_NDimArray) |
| 859 |
nin = self.nin |
| 860 |
assert nin >= 0 |
| 861 |
res_dtype = outargs0.get_dtype() |
| 862 |
new_shape = inargs0.get_shape() |
| 863 |
|
| 864 |
if self.stack_inputs: |
| 865 |
loop.call_many_to_many(space, new_shape, func, |
| 866 |
dtypes, [], inargs + outargs, []) |
| 867 |
if len(outargs) < 2: |
| 868 |
return outargs[0] |
| 869 |
return space.newtuple(outargs) |
| 870 |
if len(outargs) < 2: |
| 871 |
return loop.call_many_to_one(space, new_shape, func, |
| 872 |
dtypes[:nin], dtypes[-1], inargs, outargs[0]) |
| 873 |
return loop.call_many_to_many(space, new_shape, func, |
| 874 |
dtypes[:nin], dtypes[nin:], inargs, outargs) |
| 875 |
w_casting = space.w_None |
| 876 |
w_op_dtypes = space.w_None |
| 877 |
for tf in need_to_cast: |
| 878 |
if tf: |
| 879 |
w_casting = space.newtext('safe') |
| 880 |
w_op_dtypes = space.newtuple([d for d in dtypes]) |
| 881 |
|
| 882 |
w_flags = space.w_None |
| 883 |
w_ro = space.newtuple([space.newtext('readonly'), space.newtext('copy')]) |
| 884 |
w_rw = space.newtuple([space.newtext('readwrite'), space.newtext('updateifcopy')]) |
| 885 |
|
| 886 |
w_op_flags = space.newtuple([w_ro] * len(inargs) + [w_rw] * len(outargs)) |
| 887 |
w_op_axes = space.w_None |
| 888 |
|
| 889 |
if isinstance(func, W_GenericUFuncCaller): |
| 890 |
|
| 891 |
|
| 892 |
|
| 893 |
|
| 894 |
dims = [1] + matched_dims |
| 895 |
steps = [] |
| 896 |
allargs = inargs + outargs |
| 897 |
for i in range(len(allargs)): |
| 898 |
steps.append(0) |
| 899 |
for i in range(len(allargs)): |
| 900 |
_arg = allargs[i] |
| 901 |
assert isinstance(_arg, W_NDimArray) |
| 902 |
start_dim = len(iter_shape) |
| 903 |
steps += _arg.implementation.strides[start_dim:] |
| 904 |
func.set_dims_and_steps(space, dims, steps) |
| 905 |
else: |
| 906 |
|
| 907 |
|
| 908 |
pass |
| 909 |
|
| 910 |
w_itershape = space.newlist([space.newint(i) for i in iter_shape]) |
| 911 |
nd_it = W_NDIter(space, space.newlist(inargs + outargs), w_flags, |
| 912 |
w_op_flags, w_op_dtypes, w_casting, w_op_axes, |
| 913 |
w_itershape, allow_backward=False) |
| 914 |
|
| 915 |
for i in range(len(inargs) + len(outargs)): |
| 916 |
for j in range(self.core_num_dims[i]): |
| 917 |
new_iter = coalesce_iter(nd_it.iters[i][0], nd_it.op_flags[i], |
| 918 |
nd_it, nd_it.order, flat=False) |
| 919 |
nd_it.iters[i] = (new_iter, new_iter.reset()) |
| 920 |
|
| 921 |
if self.stack_inputs: |
| 922 |
while not nd_it.done: |
| 923 |
|
| 924 |
for it, st in nd_it.iters: |
| 925 |
if not it.done(st): |
| 926 |
break |
| 927 |
else: |
| 928 |
nd_it.done = True |
| 929 |
break |
| 930 |
args = [] |
| 931 |
for i, (it, st) in enumerate(nd_it.iters): |
| 932 |
args.append(nd_it.getitem(it, st)) |
| 933 |
nd_it.iters[i] = (it, it.next(st)) |
| 934 |
space.call_args(func, Arguments.frompacked(space, space.newlist(args))) |
| 935 |
else: |
| 936 |
|
| 937 |
while not nd_it.done: |
| 938 |
|
| 939 |
for it, st in nd_it.iters: |
| 940 |
if not it.done(st): |
| 941 |
break |
| 942 |
else: |
| 943 |
nd_it.done = True |
| 944 |
break |
| 945 |
initers = [] |
| 946 |
outiters = [] |
| 947 |
nin = len(inargs) |
| 948 |
for i, (it, st) in enumerate(nd_it.iters[:nin]): |
| 949 |
initers.append(nd_it.getitem(it, st)) |
| 950 |
nd_it.iters[i] = (it, it.next(st)) |
| 951 |
for i, (it, st) in enumerate(nd_it.iters[nin:]): |
| 952 |
outiters.append(nd_it.getitem(it, st)) |
| 953 |
nd_it.iters[i + nin] = (it, it.next(st)) |
| 954 |
outs = space.call_args(func, Arguments.frompacked(space, space.newlist(initers))) |
| 955 |
if len(outiters) < 2: |
| 956 |
outiters[0].descr_setitem(space, space.w_Ellipsis, outs) |
| 957 |
else: |
| 958 |
for i in range(self.nout): |
| 959 |
w_val = space.getitem(outs, space.newint(i)) |
| 960 |
outiters[i].descr_setitem(space, space.w_Ellipsis, w_val) |
| 961 |
|
| 962 |
if len(outargs) > 1: |
| 963 |
return space.newtuple([convert_to_array(space, o) for o in outargs]) |
| 964 |
return outargs[0] |
| 965 |
|
| 966 |
def parse_kwargs(self, space, kwargs_w): |
| 967 |
w_subok, w_out, sig, w_casting, extobj = \ |
| 968 |
W_Ufunc.parse_kwargs(self, space, kwargs_w) |
| 969 |
|
| 970 |
dtype_w = kwargs_w.pop('dtype', None) |
| 971 |
if not space.is_w(dtype_w, space.w_None) and not dtype_w is None: |
| 972 |
if sig: |
| 973 |
raise oefmt(space.w_RuntimeError, |
| 974 |
"cannot specify both 'sig' and 'dtype'") |
| 975 |
dtype = decode_w_dtype(space, dtype_w) |
| 976 |
sig = dtype.char |
| 977 |
order = kwargs_w.pop('order', None) |
| 978 |
if not space.is_w(order, space.w_None) and not order is None: |
| 979 |
raise oefmt(space.w_NotImplementedError, '"order" keyword not implemented') |
| 980 |
parsed_kw = [] |
| 981 |
for kw in kwargs_w: |
| 982 |
if kw.startswith('sig'): |
| 983 |
if sig: |
| 984 |
raise oefmt(space.w_RuntimeError, |
| 985 |
"cannot specify both 'sig' and 'dtype'") |
| 986 |
sig = space.text_w(kwargs_w[kw]) |
| 987 |
parsed_kw.append(kw) |
| 988 |
elif kw.startswith('where'): |
| 989 |
raise oefmt(space.w_NotImplementedError, |
| 990 |
'"where" keyword not implemented') |
| 991 |
parsed_kw.append(kw) |
| 992 |
for kw in parsed_kw: |
| 993 |
kwargs_w.pop(kw) |
| 994 |
return w_subok, w_out, sig, w_casting, extobj |
| 995 |
|
| 996 |
def type_resolver(self, space, inargs, outargs, type_tup, _dtypes): |
| 997 |
|
| 998 |
|
| 999 |
|
| 1000 |
|
| 1001 |
|
| 1002 |
|
| 1003 |
|
| 1004 |
dtypes = [] |
| 1005 |
for i in inargs: |
| 1006 |
if isinstance(i, W_NDimArray): |
| 1007 |
dtypes.append(i.get_dtype()) |
| 1008 |
else: |
| 1009 |
dtypes.append(None) |
| 1010 |
for i in outargs: |
| 1011 |
if isinstance(i, W_NDimArray): |
| 1012 |
dtypes.append(i.get_dtype()) |
| 1013 |
else: |
| 1014 |
dtypes.append(None) |
| 1015 |
if isinstance(type_tup, str) and len(type_tup) > 0: |
| 1016 |
try: |
| 1017 |
if len(type_tup) == 1: |
| 1018 |
s_dtypes = [get_dtype_cache(space).dtypes_by_name[type_tup]] * self.nargs |
| 1019 |
elif len(type_tup) == self.nargs + 2: |
| 1020 |
s_dtypes = [] |
| 1021 |
for i in range(self.nin): |
| 1022 |
s_dtypes.append(get_dtype_cache(space).dtypes_by_name[type_tup[i]]) |
| 1023 |
|
| 1024 |
for i in range(self.nout): |
| 1025 |
j = i + self.nin + 2 |
| 1026 |
s_dtypes.append(get_dtype_cache(space).dtypes_by_name[type_tup[j]]) |
| 1027 |
else: |
| 1028 |
raise oefmt(space.w_TypeError, "a type-string for %s " \ |
| 1029 |
"requires 1 typecode or %d typecode(s) before and %d" \ |
| 1030 |
" after the -> sign, not '%s'", self.name, self.nin, |
| 1031 |
self.nout, type_tup) |
| 1032 |
except KeyError: |
| 1033 |
raise oefmt(space.w_ValueError, "unknown typecode in" \ |
| 1034 |
" call to %s with type-string '%s'", self.name, type_tup) |
| 1035 |
|
| 1036 |
if not _match_dtypes(space, dtypes, s_dtypes, 0, "safe"): |
| 1037 |
_raise_err_msg(self, space, dtypes, s_dtypes) |
| 1038 |
dtypes = s_dtypes |
| 1039 |
|
| 1040 |
for i in range(0, len(_dtypes), self.nargs): |
| 1041 |
allok = _match_dtypes(space, dtypes, _dtypes, i, "no") |
| 1042 |
if allok: |
| 1043 |
break |
| 1044 |
else: |
| 1045 |
|
| 1046 |
for i in range(0, len(_dtypes), self.nargs): |
| 1047 |
allok = _match_dtypes(space, dtypes, _dtypes, i, "safe") |
| 1048 |
if allok: |
| 1049 |
end = i + self.nargs |
| 1050 |
assert i >= 0 |
| 1051 |
assert end >=0 |
| 1052 |
dtypes = _dtypes[i:end] |
| 1053 |
break |
| 1054 |
else: |
| 1055 |
if len(self.funcs) > 1: |
| 1056 |
_raise_err_msg(self, space, dtypes, _dtypes) |
| 1057 |
i = 0 |
| 1058 |
|
| 1059 |
for j in range(self.nargs): |
| 1060 |
if dtypes[j] is None: |
| 1061 |
dtypes[j] = _dtypes[i+j] |
| 1062 |
return i / self.nargs, dtypes |
| 1063 |
|
| 1064 |
def alloc_args(self, space, inargs, outargs, dtypes, arg_shapes): |
| 1065 |
|
| 1066 |
inargs0 = inargs[0] |
| 1067 |
assert isinstance(inargs0, W_NDimArray) |
| 1068 |
order = inargs0.get_order() |
| 1069 |
need_to_cast = [] |
| 1070 |
for i in range(self.nin): |
| 1071 |
curarg = inargs[i] |
| 1072 |
assert isinstance(curarg, W_NDimArray) |
| 1073 |
if len(arg_shapes[i]) != curarg.ndims(): |
| 1074 |
|
| 1075 |
sz = product(curarg.get_shape()) * curarg.get_dtype().elsize |
| 1076 |
with curarg.implementation as storage: |
| 1077 |
inargs[i] = W_NDimArray.from_shape_and_storage( |
| 1078 |
space, arg_shapes[i], storage, |
| 1079 |
curarg.get_dtype(), storage_bytes=sz, w_base=curarg) |
| 1080 |
need_to_cast.append(curarg.get_dtype() != dtypes[i]) |
| 1081 |
for i in range(len(outargs)): |
| 1082 |
j = self.nin + i |
| 1083 |
curarg = outargs[i] |
| 1084 |
if not isinstance(curarg, W_NDimArray): |
| 1085 |
outargs[i] = W_NDimArray.from_shape(space, arg_shapes[j], dtypes[j], order) |
| 1086 |
curarg = outargs[i] |
| 1087 |
elif len(arg_shapes[i]) != curarg.ndims(): |
| 1088 |
|
| 1089 |
sz = product(curarg.get_shape()) * curarg.get_dtype().elsize |
| 1090 |
with curarg.implementation as storage: |
| 1091 |
outargs[i] = W_NDimArray.from_shape_and_storage( |
| 1092 |
space, arg_shapes[i], storage, |
| 1093 |
curarg.get_dtype(), storage_bytes=sz, w_base=curarg) |
| 1094 |
curarg = outargs[i] |
| 1095 |
assert isinstance(curarg, W_NDimArray) |
| 1096 |
need_to_cast.append(curarg.get_dtype() != dtypes[j]) |
| 1097 |
return inargs, outargs, need_to_cast |
| 1098 |
|
| 1099 |
def verify_args(self, space, inargs, outargs): |
| 1100 |
|
| 1101 |
|
| 1102 |
|
| 1103 |
iter_shape = [] |
| 1104 |
arg_shapes = [] |
| 1105 |
max_matched_dims = 0 |
| 1106 |
for i in self.core_dim_ixs: |
| 1107 |
if i > max_matched_dims: |
| 1108 |
max_matched_dims = i |
| 1109 |
matched_dims = [-1] * (1 + max_matched_dims) |
| 1110 |
for i in range(len(inargs) + len(outargs)): |
| 1111 |
if i < len(inargs): |
| 1112 |
_i = i |
| 1113 |
name = 'Input' |
| 1114 |
curarg = inargs[i] |
| 1115 |
else: |
| 1116 |
_i = i - self.nin |
| 1117 |
name = 'Output' |
| 1118 |
curarg = outargs[_i] |
| 1119 |
dim_offset = self.core_offsets[i] |
| 1120 |
num_dims = self.core_num_dims[i] |
| 1121 |
if not isinstance(curarg, W_NDimArray): |
| 1122 |
target_dims = [] |
| 1123 |
for j in range(num_dims): |
| 1124 |
core_dim_index = self.core_dim_ixs[dim_offset + j] |
| 1125 |
v = matched_dims[core_dim_index] |
| 1126 |
if v < 0: |
| 1127 |
raise oefmt(space.w_ValueError, "%s: %s operand %d " |
| 1128 |
"is empty but unique core dimension %d in signature " |
| 1129 |
"%s of gufunc was not specified", |
| 1130 |
self.name, name, _i, core_dim_index, self.signature) |
| 1131 |
target_dims.append(v) |
| 1132 |
arg_shapes.append(iter_shape + target_dims) |
| 1133 |
continue |
| 1134 |
n = len(curarg.get_shape()) - num_dims |
| 1135 |
if n < 0: |
| 1136 |
raise oefmt(space.w_ValueError, "%s: %s operand %d does " |
| 1137 |
"not have enough dimensions (has %d, gufunc with " |
| 1138 |
"signature %s requires %d)", self.name, name, _i, |
| 1139 |
num_dims+n, self.signature, num_dims) |
| 1140 |
dims_to_match = curarg.get_shape()[n:] |
| 1141 |
dims_to_broadcast = curarg.get_shape()[:n] |
| 1142 |
offset = n - len(iter_shape) |
| 1143 |
if offset > 0: |
| 1144 |
|
| 1145 |
iter_shape = dims_to_broadcast[:offset] + iter_shape |
| 1146 |
arg_shapes = [dims_to_broadcast[:offset] + asp for asp in arg_shapes] |
| 1147 |
offset = 0 |
| 1148 |
|
| 1149 |
offset = abs(offset) |
| 1150 |
for j in range(offset, len(iter_shape)): |
| 1151 |
x = iter_shape[j + offset] |
| 1152 |
y = dims_to_broadcast[j] |
| 1153 |
if y > 1 and x != 0 and ((x > y and x % y) or y %x): |
| 1154 |
raise oefmt(space.w_ValueError, "%s: %s operand %d has a " |
| 1155 |
"mismatch in its broadcast dimension %d " |
| 1156 |
"(size %d is different from %d)", |
| 1157 |
self.name, name, _i, j, x, y) |
| 1158 |
iter_shape[offset + j] = max(x, y) |
| 1159 |
|
| 1160 |
|
| 1161 |
for j in range(num_dims): |
| 1162 |
core_dim_index = self.core_dim_ixs[dim_offset + j] |
| 1163 |
if core_dim_index > len(dims_to_match): |
| 1164 |
raise oefmt(space.w_ValueError, "%s: %s operand %d has a " |
| 1165 |
"mismatch in its core dimension %d, with gufunc " |
| 1166 |
"signature %s (index is larger than input shape)", |
| 1167 |
self.name, name, _i, j, self.signature, core_dim_index) |
| 1168 |
if matched_dims[core_dim_index] < 0: |
| 1169 |
matched_dims[core_dim_index] = dims_to_match[j] |
| 1170 |
elif matched_dims[core_dim_index] != dims_to_match[j]: |
| 1171 |
raise oefmt(space.w_ValueError, "%s: %s operand %d has a " |
| 1172 |
"mismatch in its core dimension %d, with gufunc " |
| 1173 |
"signature %s (expected %d, got %d)", |
| 1174 |
self.name, name, _i, j, |
| 1175 |
self.signature, matched_dims[core_dim_index], |
| 1176 |
dims_to_match[core_dim_index]) |
| 1177 |
|
| 1178 |
if n < len(iter_shape): |
| 1179 |
|
| 1180 |
broadcast_dims = len(iter_shape) - n |
| 1181 |
arg_shapes.append(iter_shape[:n] + [1] * broadcast_dims + dims_to_match) |
| 1182 |
else: |
| 1183 |
arg_shapes.append(iter_shape + dims_to_match) |
| 1184 |
|
| 1185 |
|
| 1186 |
|
| 1187 |
|
| 1188 |
|
| 1189 |
|
| 1190 |
|
| 1191 |
|
| 1192 |
return iter_shape, arg_shapes, matched_dims |
| 1193 |
|
| 1194 |
W_Ufunc.typedef = TypeDef("numpy.ufunc", |
| 1195 |
__call__ = interp2app(W_Ufunc.descr_call), |
| 1196 |
__repr__ = interp2app(W_Ufunc.descr_repr), |
| 1197 |
__name__ = GetSetProperty(W_Ufunc.descr_get_name), |
| 1198 |
__doc__ = GetSetProperty(W_Ufunc.get_doc, W_Ufunc.set_doc), |
| 1199 |
|
| 1200 |
identity = GetSetProperty(W_Ufunc.descr_get_identity), |
| 1201 |
accumulate = interp2app(W_Ufunc.descr_accumulate), |
| 1202 |
nin = interp_attrproperty("nin", cls=W_Ufunc, |
| 1203 |
wrapfn="newint"), |
| 1204 |
nout = interp_attrproperty("nout", cls=W_Ufunc, |
| 1205 |
wrapfn="newint"), |
| 1206 |
nargs = interp_attrproperty("nargs", cls=W_Ufunc, |
| 1207 |
wrapfn="newint"), |
| 1208 |
signature = interp_attrproperty("signature", cls=W_Ufunc, |
| 1209 |
wrapfn="newtext_or_none"), |
| 1210 |
|
| 1211 |
reduce = interp2app(W_Ufunc.descr_reduce), |
| 1212 |
outer = interp2app(W_Ufunc.descr_outer), |
| 1213 |
) |
| 1214 |
|
| 1215 |
|
| 1216 |
def ufunc_dtype_caller(space, ufunc_name, op_name, nin, bool_result): |
| 1217 |
def get_op(dtype): |
| 1218 |
try: |
| 1219 |
return getattr(dtype.itemtype, op_name) |
| 1220 |
except AttributeError: |
| 1221 |
raise oefmt(space.w_NotImplementedError, |
| 1222 |
"%s not implemented for %s", |
| 1223 |
ufunc_name, dtype.get_name()) |
| 1224 |
dtype_cache = get_dtype_cache(space) |
| 1225 |
if nin == 1: |
| 1226 |
def impl(res_dtype, value): |
| 1227 |
res = get_op(res_dtype)(value) |
| 1228 |
if bool_result: |
| 1229 |
return dtype_cache.w_booldtype.box(res) |
| 1230 |
return res |
| 1231 |
elif nin == 2: |
| 1232 |
def impl(res_dtype, lvalue, rvalue): |
| 1233 |
res = get_op(res_dtype)(lvalue, rvalue) |
| 1234 |
if bool_result: |
| 1235 |
return dtype_cache.w_booldtype.box(res) |
| 1236 |
return res |
| 1237 |
return func_with_new_name(impl, ufunc_name) |
| 1238 |
|
| 1239 |
|
| 1240 |
class UfuncState(object): |
| 1241 |
def __init__(self, space): |
| 1242 |
"NOT_RPYTHON" |
| 1243 |
for ufunc_def in [ |
| 1244 |
("add", "add", 2, {"identity": 0, "promote_to_largest": True}), |
| 1245 |
("subtract", "sub", 2), |
| 1246 |
("multiply", "mul", 2, {"identity": 1, "promote_to_largest": True}), |
| 1247 |
("bitwise_and", "bitwise_and", 2, {"identity": 1, |
| 1248 |
"int_only": True}), |
| 1249 |
("bitwise_or", "bitwise_or", 2, {"identity": 0, |
| 1250 |
"int_only": True}), |
| 1251 |
("bitwise_xor", "bitwise_xor", 2, {"int_only": True}), |
| 1252 |
("invert", "invert", 1, {"int_only": True}), |
| 1253 |
("floor_divide", "floordiv", 2, {"promote_bools": True}), |
| 1254 |
("divide", "div", 2, {"promote_bools": True}), |
| 1255 |
("true_divide", "div", 2, {"promote_to_float": True}), |
| 1256 |
("mod", "mod", 2, {"promote_bools": True, 'allow_complex': False}), |
| 1257 |
("power", "pow", 2, {"promote_bools": True}), |
| 1258 |
("left_shift", "lshift", 2, {"int_only": True}), |
| 1259 |
("right_shift", "rshift", 2, {"int_only": True}), |
| 1260 |
|
| 1261 |
("equal", "eq", 2, {"bool_result": True}), |
| 1262 |
("not_equal", "ne", 2, {"bool_result": True}), |
| 1263 |
("less", "lt", 2, {"bool_result": True}), |
| 1264 |
("less_equal", "le", 2, {"bool_result": True}), |
| 1265 |
("greater", "gt", 2, {"bool_result": True}), |
| 1266 |
("greater_equal", "ge", 2, {"bool_result": True}), |
| 1267 |
("isnan", "isnan", 1, {"bool_result": True}), |
| 1268 |
("isinf", "isinf", 1, {"bool_result": True}), |
| 1269 |
("isfinite", "isfinite", 1, {"bool_result": True}), |
| 1270 |
|
| 1271 |
('logical_and', 'logical_and', 2, {'identity': 1}), |
| 1272 |
('logical_or', 'logical_or', 2, {'identity': 0}), |
| 1273 |
('logical_xor', 'logical_xor', 2, {'bool_result': True}), |
| 1274 |
('logical_not', 'logical_not', 1, {'bool_result': True}), |
| 1275 |
|
| 1276 |
("maximum", "max", 2), |
| 1277 |
("minimum", "min", 2), |
| 1278 |
|
| 1279 |
("copysign", "copysign", 2, {"promote_to_float": True, |
| 1280 |
"allow_complex": False}), |
| 1281 |
|
| 1282 |
("positive", "pos", 1), |
| 1283 |
("negative", "neg", 1), |
| 1284 |
("absolute", "abs", 1, {"complex_to_float": True}), |
| 1285 |
("rint", "rint", 1), |
| 1286 |
("sign", "sign", 1, {"allow_bool": False}), |
| 1287 |
("signbit", "signbit", 1, {"bool_result": True, |
| 1288 |
"allow_complex": False}), |
| 1289 |
("reciprocal", "reciprocal", 1), |
| 1290 |
("conjugate", "conj", 1), |
| 1291 |
("real", "real", 1, {"complex_to_float": True}), |
| 1292 |
("imag", "imag", 1, {"complex_to_float": True}), |
| 1293 |
|
| 1294 |
("fabs", "fabs", 1, {"promote_to_float": True, |
| 1295 |
"allow_complex": False}), |
| 1296 |
("fmax", "fmax", 2, {"promote_to_float": True}), |
| 1297 |
("fmin", "fmin", 2, {"promote_to_float": True}), |
| 1298 |
("fmod", "fmod", 2, {"promote_to_float": True, |
| 1299 |
'allow_complex': False}), |
| 1300 |
("floor", "floor", 1, {"promote_to_float": True, |
| 1301 |
"allow_complex": False}), |
| 1302 |
("ceil", "ceil", 1, {"promote_to_float": True, |
| 1303 |
"allow_complex": False}), |
| 1304 |
("trunc", "trunc", 1, {"promote_to_float": True, |
| 1305 |
"allow_complex": False}), |
| 1306 |
("exp", "exp", 1, {"promote_to_float": True}), |
| 1307 |
("exp2", "exp2", 1, {"promote_to_float": True}), |
| 1308 |
("expm1", "expm1", 1, {"promote_to_float": True}), |
| 1309 |
|
| 1310 |
('sqrt', 'sqrt', 1, {'promote_to_float': True}), |
| 1311 |
('square', 'square', 1, {'promote_to_float': True}), |
| 1312 |
|
| 1313 |
("sin", "sin", 1, {"promote_to_float": True}), |
| 1314 |
("cos", "cos", 1, {"promote_to_float": True}), |
| 1315 |
("tan", "tan", 1, {"promote_to_float": True}), |
| 1316 |
("arcsin", "arcsin", 1, {"promote_to_float": True}), |
| 1317 |
("arccos", "arccos", 1, {"promote_to_float": True}), |
| 1318 |
("arctan", "arctan", 1, {"promote_to_float": True}), |
| 1319 |
("arctan2", "arctan2", 2, {"promote_to_float": True, |
| 1320 |
"allow_complex": False}), |
| 1321 |
("sinh", "sinh", 1, {"promote_to_float": True}), |
| 1322 |
("cosh", "cosh", 1, {"promote_to_float": True}), |
| 1323 |
("tanh", "tanh", 1, {"promote_to_float": True}), |
| 1324 |
("arcsinh", "arcsinh", 1, {"promote_to_float": True}), |
| 1325 |
("arccosh", "arccosh", 1, {"promote_to_float": True}), |
| 1326 |
("arctanh", "arctanh", 1, {"promote_to_float": True}), |
| 1327 |
|
| 1328 |
("radians", "radians", 1, {"promote_to_float": True, |
| 1329 |
"allow_complex": False}), |
| 1330 |
("degrees", "degrees", 1, {"promote_to_float": True, |
| 1331 |
"allow_complex": False}), |
| 1332 |
|
| 1333 |
("log", "log", 1, {"promote_to_float": True}), |
| 1334 |
("log2", "log2", 1, {"promote_to_float": True}), |
| 1335 |
("log10", "log10", 1, {"promote_to_float": True}), |
| 1336 |
("log1p", "log1p", 1, {"promote_to_float": True}), |
| 1337 |
("logaddexp", "logaddexp", 2, {"promote_to_float": True, |
| 1338 |
"allow_complex": False}), |
| 1339 |
("logaddexp2", "logaddexp2", 2, {"promote_to_float": True, |
| 1340 |
"allow_complex": False}), |
| 1341 |
]: |
| 1342 |
self.add_ufunc(space, *ufunc_def) |
| 1343 |
|
| 1344 |
def add_ufunc(self, space, ufunc_name, op_name, nin, extra_kwargs=None): |
| 1345 |
if extra_kwargs is None: |
| 1346 |
extra_kwargs = {} |
| 1347 |
|
| 1348 |
identity = extra_kwargs.get("identity") |
| 1349 |
if identity is not None: |
| 1350 |
identity = \ |
| 1351 |
get_dtype_cache(space).w_longdtype.box(identity) |
| 1352 |
extra_kwargs["identity"] = identity |
| 1353 |
|
| 1354 |
func = ufunc_dtype_caller(space, ufunc_name, op_name, nin, |
| 1355 |
bool_result=extra_kwargs.get("bool_result", False), |
| 1356 |
) |
| 1357 |
if nin == 1: |
| 1358 |
ufunc = unary_ufunc(space, func, ufunc_name, **extra_kwargs) |
| 1359 |
elif nin == 2: |
| 1360 |
ufunc = binary_ufunc(space, func, ufunc_name, **extra_kwargs) |
| 1361 |
setattr(self, ufunc_name, ufunc) |
| 1362 |
|
| 1363 |
def unary_ufunc(space, func, ufunc_name, **kwargs): |
| 1364 |
ufunc = W_Ufunc1(func, ufunc_name, **kwargs) |
| 1365 |
ufunc.dtypes = _ufunc1_dtypes(ufunc, space) |
| 1366 |
return ufunc |
| 1367 |
|
| 1368 |
def _ufunc1_dtypes(ufunc, space): |
| 1369 |
dtypes = [] |
| 1370 |
cache = get_dtype_cache(space) |
| 1371 |
if not ufunc.promote_bools and not ufunc.promote_to_float: |
| 1372 |
dtypes.append((cache.w_booldtype, cache.w_booldtype)) |
| 1373 |
if not ufunc.promote_to_float: |
| 1374 |
for dt in cache.integer_dtypes: |
| 1375 |
dtypes.append((dt, dt)) |
| 1376 |
if not ufunc.int_only: |
| 1377 |
for dt in cache.float_dtypes: |
| 1378 |
dtypes.append((dt, dt)) |
| 1379 |
for dt in cache.complex_dtypes: |
| 1380 |
if ufunc.complex_to_float: |
| 1381 |
if dt.num == NPY.CFLOAT: |
| 1382 |
dt_out = get_dtype_cache(space).w_float32dtype |
| 1383 |
else: |
| 1384 |
dt_out = get_dtype_cache(space).w_float64dtype |
| 1385 |
dtypes.append((dt, dt_out)) |
| 1386 |
else: |
| 1387 |
dtypes.append((dt, dt)) |
| 1388 |
if ufunc.bool_result: |
| 1389 |
dtypes = [(dt_in, cache.w_booldtype) for dt_in, _ in dtypes] |
| 1390 |
return dtypes |
| 1391 |
|
| 1392 |
def binary_ufunc(space, func, ufunc_name, **kwargs): |
| 1393 |
ufunc = W_Ufunc2(func, ufunc_name, **kwargs) |
| 1394 |
ufunc.dtypes = _ufunc2_dtypes(ufunc, space) |
| 1395 |
return ufunc |
| 1396 |
|
| 1397 |
def _ufunc2_dtypes(ufunc, space): |
| 1398 |
dtypes = [] |
| 1399 |
cache = get_dtype_cache(space) |
| 1400 |
if not ufunc.promote_bools and not ufunc.promote_to_float: |
| 1401 |
dtypes.append((cache.w_booldtype, cache.w_booldtype)) |
| 1402 |
if not ufunc.promote_to_float: |
| 1403 |
for dt in cache.integer_dtypes: |
| 1404 |
dtypes.append((dt, dt)) |
| 1405 |
if not ufunc.int_only: |
| 1406 |
for dt in cache.float_dtypes: |
| 1407 |
dtypes.append((dt, dt)) |
| 1408 |
for dt in cache.complex_dtypes: |
| 1409 |
if ufunc.complex_to_float: |
| 1410 |
if dt.num == NPY.CFLOAT: |
| 1411 |
dt_out = get_dtype_cache(space).w_float32dtype |
| 1412 |
else: |
| 1413 |
dt_out = get_dtype_cache(space).w_float64dtype |
| 1414 |
dtypes.append((dt, dt_out)) |
| 1415 |
else: |
| 1416 |
dtypes.append((dt, dt)) |
| 1417 |
if ufunc.bool_result: |
| 1418 |
dtypes = [(dt_in, cache.w_booldtype) for dt_in, _ in dtypes] |
| 1419 |
return dtypes |
| 1420 |
|
| 1421 |
|
| 1422 |
def get(space): |
| 1423 |
return space.fromcache(UfuncState) |
| 1424 |
|
| 1425 |
@unwrap_spec(nin=int, nout=int, signature='text', w_identity=WrappedDefault(None), |
| 1426 |
name='text', doc='text', stack_inputs=bool) |
| 1427 |
def frompyfunc(space, w_func, nin, nout, w_dtypes=None, signature='', |
| 1428 |
w_identity=None, name='', doc='', stack_inputs=False): |
| 1429 |
''' frompyfunc(func, nin, nout) #cpython numpy compatible |
| 1430 |
frompyfunc(func, nin, nout, dtypes=None, signature='', |
| 1431 |
identity=None, name='', doc='', |
| 1432 |
stack_inputs=False) |
| 1433 |
|
| 1434 |
Takes an arbitrary Python function and returns a ufunc. |
| 1435 |
|
| 1436 |
Can be used, for example, to add broadcasting to a built-in Python |
| 1437 |
function (see Examples section). |
| 1438 |
|
| 1439 |
Parameters |
| 1440 |
---------- |
| 1441 |
func : Python function object |
| 1442 |
An arbitrary Python function or list of functions (if dtypes is specified). |
| 1443 |
nin : int |
| 1444 |
The number of input arguments. |
| 1445 |
nout : int |
| 1446 |
The number of arrays returned by `func`. |
| 1447 |
dtypes: None or [dtype, ...] of the input, output args for each function, |
| 1448 |
or 'match' to force output to exactly match input dtype |
| 1449 |
Note that 'match' is a pypy-only extension to allow non-object |
| 1450 |
return dtypes |
| 1451 |
signature*: str, default='' |
| 1452 |
The mapping of input args to output args, defining the |
| 1453 |
inner-loop indexing. If it is empty, the func operates on scalars |
| 1454 |
identity*: None (default) or int |
| 1455 |
For reduce-type ufuncs, the default value |
| 1456 |
name: str, default='' |
| 1457 |
doc: str, default='' |
| 1458 |
stack_inputs*: boolean, whether the function is of the form |
| 1459 |
out = func(*in) False |
| 1460 |
or |
| 1461 |
func(*[in + out]) True |
| 1462 |
|
| 1463 |
only one of out_dtype or signature may be specified |
| 1464 |
|
| 1465 |
Returns |
| 1466 |
------- |
| 1467 |
out : ufunc |
| 1468 |
Returns a Numpy universal function (``ufunc``) object. |
| 1469 |
|
| 1470 |
Notes |
| 1471 |
----- |
| 1472 |
If the signature and dtype are both missing, the returned ufunc |
| 1473 |
always returns PyObject arrays (cpython numpy compatability). |
| 1474 |
Input arguments marked with a * are pypy-only extensions |
| 1475 |
|
| 1476 |
Examples |
| 1477 |
-------- |
| 1478 |
Use frompyfunc to add broadcasting to the Python function ``oct``: |
| 1479 |
|
| 1480 |
>>> oct_obj_array = np.frompyfunc(oct, 1, 1) |
| 1481 |
>>> oct_obj_array(np.array((10, 30, 100))) |
| 1482 |
array([012, 036, 0144], dtype=object) |
| 1483 |
>>> np.array((oct(10), oct(30), oct(100))) # for comparison |
| 1484 |
array(['012', '036', '0144'], |
| 1485 |
dtype='|S4') |
| 1486 |
>>> oct_array = np.frompyfunc(oct, 1, 1, out_dtype=str) |
| 1487 |
>>> oct_obj_array(np.array((10, 30, 100))) |
| 1488 |
array([012, 036, 0144], dtype='|S4') |
| 1489 |
''' |
| 1490 |
if (space.isinstance_w(w_func, space.w_tuple) or |
| 1491 |
space.isinstance_w(w_func, space.w_list)): |
| 1492 |
func = space.listview(w_func) |
| 1493 |
for w_f in func: |
| 1494 |
if not space.is_true(space.callable(w_f)): |
| 1495 |
raise oefmt(space.w_TypeError, 'func must be callable') |
| 1496 |
else: |
| 1497 |
if not space.is_true(space.callable(w_func)): |
| 1498 |
raise oefmt(space.w_TypeError, 'func must be callable') |
| 1499 |
func = [w_func] |
| 1500 |
match_dtypes = False |
| 1501 |
if space.is_none(w_dtypes) and not signature: |
| 1502 |
raise oefmt(space.w_NotImplementedError, |
| 1503 |
'object dtype requested but not implemented') |
| 1504 |
elif (space.isinstance_w(w_dtypes, space.w_tuple) or |
| 1505 |
space.isinstance_w(w_dtypes, space.w_list)): |
| 1506 |
_dtypes = space.listview(w_dtypes) |
| 1507 |
if space.isinstance_w(_dtypes[0], space.w_text) and space.text_w(_dtypes[0]) == 'match': |
| 1508 |
dtypes = [] |
| 1509 |
match_dtypes = True |
| 1510 |
else: |
| 1511 |
dtypes = [None]*len(_dtypes) |
| 1512 |
for i in range(len(dtypes)): |
| 1513 |
dtypes[i] = decode_w_dtype(space, _dtypes[i]) |
| 1514 |
else: |
| 1515 |
raise oefmt(space.w_ValueError, |
| 1516 |
'dtypes must be None or a list of dtypes') |
| 1517 |
|
| 1518 |
if space.is_none(w_identity): |
| 1519 |
identity = None |
| 1520 |
elif space.isinstance_w(w_identity, space.w_int): |
| 1521 |
identity = \ |
| 1522 |
get_dtype_cache(space).w_longdtype.box(space.int_w(w_identity)) |
| 1523 |
else: |
| 1524 |
raise oefmt(space.w_ValueError, |
| 1525 |
'identity must be None or an int') |
| 1526 |
|
| 1527 |
if len(signature) == 0: |
| 1528 |
external_loop=False |
| 1529 |
else: |
| 1530 |
external_loop=True |
| 1531 |
|
| 1532 |
w_ret = W_UfuncGeneric(space, func, name, identity, nin, nout, dtypes, |
| 1533 |
signature, match_dtypes=match_dtypes, |
| 1534 |
stack_inputs=stack_inputs, external_loop=external_loop) |
| 1535 |
if w_ret.external_loop: |
| 1536 |
_parse_signature(space, w_ret, w_ret.signature) |
| 1537 |
if doc: |
| 1538 |
w_ret.set_doc(space, space.newtext(doc)) |
| 1539 |
return w_ret |
| 1540 |
|
| 1541 |
|
| 1542 |
|
| 1543 |
|
| 1544 |
Py_ssize_t = lltype.Typedef(rffi.SSIZE_T, 'Py_ssize_t') |
| 1545 |
npy_intpp = rffi.CArrayPtr(Py_ssize_t) |
| 1546 |
LONG_SIZE = LONG_BIT / 8 |
| 1547 |
CCHARP_SIZE = _get_bitsize('P') / 8 |
| 1548 |
|
| 1549 |
class W_GenericUFuncCaller(W_Root): |
| 1550 |
_attrs_ = ['func', 'data', 'dims', 'steps', 'dims_steps_set'] |
| 1551 |
def __init__(self, func, data): |
| 1552 |
self.func = func |
| 1553 |
self.data = data |
| 1554 |
self.dims = alloc_raw_storage(0, track_allocation=False) |
| 1555 |
self.steps = alloc_raw_storage(0, track_allocation=False) |
| 1556 |
self.dims_steps_set = False |
| 1557 |
|
| 1558 |
@rgc.must_be_light_finalizer |
| 1559 |
def __del__(self): |
| 1560 |
free_raw_storage(self.dims, track_allocation=False) |
| 1561 |
free_raw_storage(self.steps, track_allocation=False) |
| 1562 |
|
| 1563 |
def descr_call(self, space, __args__): |
| 1564 |
args_w, kwds_w = __args__.unpack() |
| 1565 |
|
| 1566 |
|
| 1567 |
|
| 1568 |
|
| 1569 |
|
| 1570 |
|
| 1571 |
dataps = alloc_raw_storage(CCHARP_SIZE * len(args_w), track_allocation=False) |
| 1572 |
if self.dims_steps_set is False: |
| 1573 |
self.dims = alloc_raw_storage(LONG_SIZE * len(args_w), track_allocation=False) |
| 1574 |
self.steps = alloc_raw_storage(LONG_SIZE * len(args_w), track_allocation=False) |
| 1575 |
for i in range(len(args_w)): |
| 1576 |
arg_i = args_w[i] |
| 1577 |
if not isinstance(arg_i, W_NDimArray): |
| 1578 |
raise OperationError(space.w_NotImplementedError, |
| 1579 |
space.newtext("cannot mix ndarray and %r (arg %d) in call to ufunc" % ( |
| 1580 |
arg_i, i))) |
| 1581 |
with arg_i.implementation as storage: |
| 1582 |
addr = get_storage_as_int(storage, arg_i.get_start()) |
| 1583 |
raw_storage_setitem(dataps, CCHARP_SIZE * i, rffi.cast(rffi.CCHARP, addr)) |
| 1584 |
|
| 1585 |
raw_storage_setitem(self.dims, LONG_SIZE * i, rffi.cast(rffi.LONG, arg_i.get_size())) |
| 1586 |
raw_storage_setitem(self.steps, LONG_SIZE * i, rffi.cast(rffi.LONG, arg_i.get_dtype().elsize)) |
| 1587 |
else: |
| 1588 |
for i in range(len(args_w)): |
| 1589 |
arg_i = args_w[i] |
| 1590 |
assert isinstance(arg_i, W_NDimArray) |
| 1591 |
with arg_i.implementation as storage: |
| 1592 |
addr = get_storage_as_int(storage, arg_i.get_start()) |
| 1593 |
raw_storage_setitem(dataps, CCHARP_SIZE * i, rffi.cast(rffi.CCHARP, addr)) |
| 1594 |
try: |
| 1595 |
arg1 = rffi.cast(rffi.CArrayPtr(rffi.CCHARP), dataps) |
| 1596 |
arg2 = rffi.cast(npy_intpp, self.dims) |
| 1597 |
arg3 = rffi.cast(npy_intpp, self.steps) |
| 1598 |
self.func(arg1, arg2, arg3, self.data) |
| 1599 |
finally: |
| 1600 |
free_raw_storage(dataps, track_allocation=False) |
| 1601 |
keepalive_until_here(args_w) |
| 1602 |
|
| 1603 |
def set_dims_and_steps(self, space, dims, steps): |
| 1604 |
if not isinstance(dims, list) or not isinstance(steps, list): |
| 1605 |
raise oefmt(space.w_RuntimeError, |
| 1606 |
"set_dims_and_steps called inappropriately") |
| 1607 |
if self.dims_steps_set: |
| 1608 |
free_raw_storage(self.dims, track_allocation=False) |
| 1609 |
free_raw_storage(self.steps, track_allocation=False) |
| 1610 |
self.dims = alloc_raw_storage(LONG_SIZE * len(dims), track_allocation=False) |
| 1611 |
self.steps = alloc_raw_storage(LONG_SIZE * len(steps), track_allocation=False) |
| 1612 |
for i in range(len(dims)): |
| 1613 |
raw_storage_setitem(self.dims, LONG_SIZE * i, rffi.cast(rffi.LONG, dims[i])) |
| 1614 |
for i in range(len(steps)): |
| 1615 |
raw_storage_setitem(self.steps, LONG_SIZE * i, rffi.cast(rffi.LONG, steps[i])) |
| 1616 |
self.dims_steps_set = True |
| 1617 |
|
| 1618 |
W_GenericUFuncCaller.typedef = TypeDef("hiddenclass", |
| 1619 |
__call__ = interp2app(W_GenericUFuncCaller.descr_call), |
| 1620 |
) |
| 1621 |
|
| 1622 |
GenericUfunc = lltype.FuncType([rffi.CArrayPtr(rffi.CCHARP), npy_intpp, npy_intpp, |
| 1623 |
rffi.VOIDP], lltype.Void) |