Debian Codegraph @

pypy/module/micronumpy/types.py

raw symbols SCIP
1 import functools
2 import math
3 from rpython.rlib.unroll import unrolling_iterable
4 from rpython.rlib.rutf8 import Utf8StringIterator, codepoints_in_utf8, Utf8StringBuilder
5 from pypy.interpreter.error import OperationError, oefmt
6 from pypy.objspace.std.floatobject import float2string
7 from pypy.objspace.std.complexobject import format_float
8 from pypy.interpreter.baseobjspace import W_Root, ObjSpace
9 from rpython.rlib import clibffi, jit, rfloat, rcomplex
10 from rpython.rlib.objectmodel import specialize, we_are_translated
11 from rpython.rlib.rarithmetic import widen, byteswap, r_ulonglong, \
12 most_neg_value_of, LONG_BIT
13 from rpython.rlib.rawstorage import (alloc_raw_storage,
14 raw_storage_getitem_unaligned, raw_storage_setitem_unaligned)
15 from rpython.rlib.rstring import StringBuilder, UnicodeBuilder
16 from rpython.rlib.rstruct.ieee import (float_pack, float_unpack, unpack_float,
17 pack_float80, unpack_float80)
18 from rpython.rlib.rstruct.nativefmttable import native_is_bigendian
19 from rpython.rlib.rstruct.runpack import runpack
20 from rpython.rtyper.annlowlevel import cast_instance_to_gcref,\
21 cast_gcref_to_instance
22 from rpython.rtyper.lltypesystem import lltype, rffi, llmemory
23 from rpython.tool.sourcetools import func_with_new_name
24 from pypy.module.micronumpy import boxes, support
25 from pypy.module.micronumpy.concrete import SliceArray, VoidBoxStorage, V_OBJECTSTORE
26 from pypy.module.micronumpy.strides import calc_strides
27 from . import constants as NPY
28
29 degToRad = math.pi / 180.0
30 log2 = math.log(2)
31 log2e = 1. / log2
32 log10 = math.log(10)
33
34 '''
35 if not we_are_translated():
36 _raw_storage_setitem_unaligned = raw_storage_setitem_unaligned
37 _raw_storage_getitem_unaligned = raw_storage_getitem_unaligned
38 def raw_storage_setitem_unaligned(storage, offset, value):
39 assert offset >=0
40 try:
41 assert offset < storage._obj.getlength()
42 except AttributeError:
43 pass
44 return _raw_storage_setitem_unaligned(storage, offset, value)
45
46 def raw_storage_getitem_unaligned(T, storage, offset):
47 assert offset >=0
48 try:
49 assert offset < storage._obj.getlength()
50 except AttributeError:
51 pass
52 return _raw_storage_getitem_unaligned(T, storage, offset)
53 '''
54
55 def simple_unary_op(func):
56 specialize.argtype(1)(func)
57 @functools.wraps(func)
58 def dispatcher(self, v):
59 return self.box(
60 func(
61 self,
62 self.for_computation(self.unbox(v)),
63 )
64 )
65 return dispatcher
66
67 def complex_unary_op(func):
68 specialize.argtype(1)(func)
69 @functools.wraps(func)
70 def dispatcher(self, v):
71 return self.box_complex(
72 *func(
73 self,
74 self.for_computation(self.unbox(v))
75 )
76 )
77 return dispatcher
78
79 def complex_to_real_unary_op(func):
80 specialize.argtype(1)(func)
81 @functools.wraps(func)
82 def dispatcher(self, v):
83 return self.box_component(
84 func(
85 self,
86 self.for_computation(self.unbox(v))
87 )
88 )
89 return dispatcher
90
91 def raw_unary_op(func):
92 specialize.argtype(1)(func)
93 @functools.wraps(func)
94 def dispatcher(self, v):
95 return func(
96 self,
97 self.for_computation(self.unbox(v))
98 )
99 return dispatcher
100
101 def simple_binary_op(func):
102 specialize.argtype(1, 2)(func)
103 @functools.wraps(func)
104 def dispatcher(self, v1, v2):
105 return self.box(
106 func(
107 self,
108 self.for_computation(self.unbox(v1)),
109 self.for_computation(self.unbox(v2)),
110 )
111 )
112 return dispatcher
113
114 def complex_binary_op(func):
115 specialize.argtype(1, 2)(func)
116 @functools.wraps(func)
117 def dispatcher(self, v1, v2):
118 return self.box_complex(
119 *func(
120 self,
121 self.for_computation(self.unbox(v1)),
122 self.for_computation(self.unbox(v2)),
123 )
124 )
125 return dispatcher
126
127 def raw_binary_op(func):
128 specialize.argtype(1, 2)(func)
129 @functools.wraps(func)
130 def dispatcher(self, v1, v2):
131 return func(self,
132 self.for_computation(self.unbox(v1)),
133 self.for_computation(self.unbox(v2))
134 )
135 return dispatcher
136
137 class BaseType(object):
138 _immutable_fields_ = ['space']
139 strlen = 0 # chars needed to print any possible value of the type
140
141 def __init__(self, space):
142 assert isinstance(space, ObjSpace)
143 self.space = space
144
145 def __repr__(self):
146 return self.__class__.__name__
147
148 def malloc(self, size, zero=True):
149 if zero:
150 return alloc_raw_storage(size, track_allocation=False, zero=True)
151 else:
152 return alloc_raw_storage(size, track_allocation=False, zero=False)
153
154 @classmethod
155 def basesize(cls):
156 return rffi.sizeof(cls.T)
157
158 class Primitive(object):
159 _mixin_ = True
160
161 def get_element_size(self):
162 return rffi.sizeof(self.T)
163
164 @specialize.argtype(1)
165 def box(self, value):
166 return self.BoxType(rffi.cast(self.T, value))
167
168 @specialize.argtype(1, 2)
169 def box_complex(self, real, imag):
170 #XXX this is the place to display a warning
171 return self.box(real)
172
173 def box_raw_data(self, data):
174 # For pickle
175 array = rffi.cast(rffi.CArrayPtr(self.T), data)
176 return self.box(array[0])
177
178 def unbox(self, box):
179 if isinstance(box, self.BoxType):
180 return box.value
181 elif isinstance(box, boxes.W_ObjectBox):
182 return self._coerce(self.space, box).value
183 else:
184 raise oefmt(self.space.w_NotImplementedError,
185 "%s dtype cannot unbox %s", str(self), str(box))
186
187 def coerce(self, space, dtype, w_item):
188 if isinstance(w_item, self.BoxType):
189 return w_item
190 return self.coerce_subtype(space, space.gettypefor(self.BoxType), w_item)
191
192 def coerce_subtype(self, space, w_subtype, w_item):
193 # XXX: ugly
194 w_obj = space.allocate_instance(self.BoxType, w_subtype)
195 assert isinstance(w_obj, self.BoxType)
196 w_obj.__init__(self._coerce(space, w_item).value)
197 return w_obj
198
199 def to_builtin_type(self, space, box):
200 raise NotImplementedError("has to be provided by subclass")
201
202 def _coerce(self, space, w_item):
203 raise NotImplementedError
204
205 def default_fromstring(self, space):
206 raise NotImplementedError
207
208 def _read(self, storage, i, offset, native):
209 res = raw_storage_getitem_unaligned(self.T, storage, i + offset)
210 if not native:
211 res = byteswap(res)
212 return res
213
214 def _write(self, storage, i, offset, value, native):
215 if not native:
216 value = byteswap(value)
217 raw_storage_setitem_unaligned(storage, i + offset, value)
218
219 def read(self, arr, i, offset, dtype):
220 with arr as storage:
221 return self.box(self._read(storage, i, offset, dtype.is_native()))
222
223 def read_bool(self, arr, i, offset, dtype):
224 with arr as storage:
225 return bool(self.for_computation(
226 self._read(storage, i, offset, dtype.is_native())))
227
228 def store(self, arr, i, offset, box, native):
229 with arr as storage:
230 self._write(storage, i, offset, self.unbox(box), native)
231
232 def fill(self, storage, width, native, box, start, stop, offset, gcstruct):
233 value = self.unbox(box)
234 for i in xrange(start, stop, width):
235 self._write(storage, i, offset, value, native)
236
237 def runpack_str(self, space, s, native):
238 v = rffi.cast(self.T, runpack(self.format_code, s))
239 if not native:
240 v = byteswap(v)
241 return self.box(v)
242
243 @simple_binary_op
244 def add(self, v1, v2):
245 return v1 + v2
246
247 @simple_binary_op
248 def sub(self, v1, v2):
249 return v1 - v2
250
251 @simple_binary_op
252 def mul(self, v1, v2):
253 return v1 * v2
254
255 @simple_unary_op
256 def pos(self, v):
257 return +v
258
259 @simple_unary_op
260 def neg(self, v):
261 return -v
262
263 def byteswap(self, w_v):
264 # no for_computation here
265 return self.box(byteswap(self.unbox(w_v)))
266
267 @simple_unary_op
268 def conj(self, v):
269 return v
270
271 @simple_unary_op
272 def real(self, v):
273 return v
274
275 @simple_unary_op
276 def imag(self, v):
277 return 0
278
279 @simple_unary_op
280 def abs(self, v):
281 return abs(v)
282
283 @raw_unary_op
284 def isnan(self, v):
285 return False
286
287 @raw_unary_op
288 def isinf(self, v):
289 return False
290
291 @raw_binary_op
292 def eq(self, v1, v2):
293 return v1 == v2
294
295 @raw_binary_op
296 def ne(self, v1, v2):
297 return v1 != v2
298
299 @raw_binary_op
300 def lt(self, v1, v2):
301 return v1 < v2
302
303 @raw_binary_op
304 def le(self, v1, v2):
305 return v1 <= v2
306
307 @raw_binary_op
308 def gt(self, v1, v2):
309 return v1 > v2
310
311 @raw_binary_op
312 def ge(self, v1, v2):
313 return v1 >= v2
314
315 @raw_binary_op
316 def logical_and(self, v1, v2):
317 if bool(v1) and bool(v2):
318 return Bool._True
319 return Bool._False
320
321 @raw_binary_op
322 def logical_or(self, v1, v2):
323 if bool(v1) or bool(v2):
324 return Bool._True
325 return Bool._False
326
327 @raw_unary_op
328 def logical_not(self, v):
329 return not bool(v)
330
331 @raw_binary_op
332 def logical_xor(self, v1, v2):
333 a = bool(v1)
334 b = bool(v2)
335 return (not b and a) or (not a and b)
336
337 @raw_unary_op
338 def bool(self, v):
339 return bool(v)
340
341 @simple_binary_op
342 def max(self, v1, v2):
343 return max(v1, v2)
344
345 @simple_binary_op
346 def min(self, v1, v2):
347 return min(v1, v2)
348
349 @raw_binary_op
350 def argmax(self, v1, v2):
351 return v1 >= v2
352
353 @raw_binary_op
354 def argmin(self, v1, v2):
355 return v1 <= v2
356
357 @raw_unary_op
358 def rint(self, v):
359 float64 = Float64(self.space)
360 return float64.rint(float64.box(v))
361
362 class Bool(BaseType, Primitive):
363 T = lltype.Bool
364 num = NPY.BOOL
365 kind = NPY.GENBOOLLTR
366 char = NPY.BOOLLTR
367 BoxType = boxes.W_BoolBox
368 format_code = "?"
369 strlen = 5 # "False"
370
371 _True = BoxType(True)
372 _False = BoxType(False)
373
374 @specialize.argtype(1)
375 def box(self, value):
376 boolean = rffi.cast(self.T, value)
377 if boolean:
378 return self._True
379 else:
380 return self._False
381
382 @specialize.argtype(1, 2)
383 def box_complex(self, real, imag):
384 box = Primitive.box(self, real)
385 if box.value:
386 return self._True
387 box = Primitive.box(self, imag)
388 if box.value:
389 return self._True
390 return self._False
391
392 def coerce_subtype(self, space, w_subtype, w_item):
393 # Doesn't return subclasses so it can return the constants.
394 return self._coerce(space, w_item)
395
396 def _coerce(self, space, w_item):
397 if space.is_none(w_item):
398 return self.box(False)
399 return self.box(space.is_true(w_item))
400
401 def to_builtin_type(self, space, w_item):
402 return space.newbool(self.unbox(w_item))
403
404 def str_format(self, box, add_quotes=True):
405 return "True" if self.unbox(box) else "False"
406
407 @staticmethod
408 def for_computation(v):
409 return int(v)
410
411 def default_fromstring(self, space):
412 return self.box(True)
413
414 @simple_binary_op
415 def lshift(self, v1, v2):
416 return v1 << v2
417
418 @simple_binary_op
419 def rshift(self, v1, v2):
420 return v1 >> v2
421
422 @simple_binary_op
423 def bitwise_and(self, v1, v2):
424 return v1 & v2
425
426 @simple_binary_op
427 def bitwise_or(self, v1, v2):
428 return v1 | v2
429
430 @simple_binary_op
431 def bitwise_xor(self, v1, v2):
432 return v1 ^ v2
433
434 @simple_unary_op
435 def invert(self, v):
436 return not v
437
438 @raw_unary_op
439 def isfinite(self, v):
440 return True
441
442 @raw_unary_op
443 def signbit(self, v):
444 return False
445
446 @simple_unary_op
447 def reciprocal(self, v):
448 if v:
449 return 1
450 return 0
451
452 @specialize.argtype(1)
453 def round(self, v, decimals=0):
454 if decimals == 0:
455 return Float64(self.space).box(self.unbox(v))
456 # numpy 1.10 compatibility
457 raise oefmt(self.space.w_TypeError, "ufunc casting failure")
458
459
460
461 class Integer(Primitive):
462 _mixin_ = True
463 signed = True
464
465 def to_builtin_type(self, space, box):
466 return space.newint(self.for_computation(self.unbox(box)))
467
468 def _base_coerce(self, space, w_item):
469 if w_item is None:
470 return self.box(0)
471 return self.box(space.int_w(space.call_function(space.w_int, w_item)))
472
473 def _coerce(self, space, w_item):
474 return self._base_coerce(space, w_item)
475
476 def str_format(self, box, add_quotes=True):
477 return str(self.for_computation(self.unbox(box)))
478
479 @staticmethod
480 def for_computation(v):
481 return widen(v)
482
483 def default_fromstring(self, space):
484 return self.box(0)
485
486 @specialize.argtype(1, 2)
487 def div(self, b1, b2):
488 v1 = self.for_computation(self.unbox(b1))
489 v2 = self.for_computation(self.unbox(b2))
490 if v2 == 0:
491 return self.box(0)
492 if (self.T is rffi.SIGNEDCHAR or self.T is rffi.SHORT or self.T is rffi.INT or
493 self.T is rffi.LONG or self.T is rffi.LONGLONG):
494 if v2 == -1 and v1 == self.for_computation(most_neg_value_of(self.T)):
495 return self.box(0)
496 return self.box(v1 / v2)
497
498 @specialize.argtype(1, 2)
499 def floordiv(self, b1, b2):
500 v1 = self.for_computation(self.unbox(b1))
501 v2 = self.for_computation(self.unbox(b2))
502 if v2 == 0:
503 return self.box(0)
504 if (self.T is rffi.SIGNEDCHAR or self.T is rffi.SHORT or self.T is rffi.INT or
505 self.T is rffi.LONG or self.T is rffi.LONGLONG):
506 if v2 == -1 and v1 == self.for_computation(most_neg_value_of(self.T)):
507 return self.box(0)
508 return self.box(v1 / v2)
509
510 @simple_binary_op
511 def mod(self, v1, v2):
512 return v1 % v2
513
514 @simple_binary_op
515 @jit.look_inside_iff(lambda self, v1, v2: jit.isconstant(v2))
516 def pow(self, v1, v2):
517 if v2 < 0:
518 return 0
519 res = 1
520 while v2 > 0:
521 if v2 & 1:
522 res *= v1
523 v2 >>= 1
524 if v2 == 0:
525 break
526 v1 *= v1
527 return res
528
529 @simple_binary_op
530 def lshift(self, v1, v2):
531 return v1 << v2
532
533 @simple_binary_op
534 def rshift(self, v1, v2):
535 return v1 >> v2
536
537 @simple_unary_op
538 def sign(self, v):
539 if v > 0:
540 return 1
541 elif v < 0:
542 return -1
543 else:
544 assert v == 0
545 return 0
546
547 @raw_unary_op
548 def isfinite(self, v):
549 return True
550
551 @raw_unary_op
552 def isnan(self, v):
553 return False
554
555 @raw_unary_op
556 def isinf(self, v):
557 return False
558
559 @simple_binary_op
560 def bitwise_and(self, v1, v2):
561 return v1 & v2
562
563 @simple_binary_op
564 def bitwise_or(self, v1, v2):
565 return v1 | v2
566
567 @simple_binary_op
568 def bitwise_xor(self, v1, v2):
569 return v1 ^ v2
570
571 @simple_unary_op
572 def invert(self, v):
573 return ~v
574
575 @specialize.argtype(1)
576 def reciprocal(self, v):
577 raw = self.for_computation(self.unbox(v))
578 ans = 0
579 if raw == 0:
580 # XXX good place to warn
581 if self.T is rffi.INT or self.T is rffi.LONG or self.T is rffi.LONGLONG:
582 ans = most_neg_value_of(self.T)
583 elif abs(raw) == 1:
584 ans = raw
585 return self.box(ans)
586
587 @specialize.argtype(1)
588 def round(self, v, decimals=0):
589 raw = self.for_computation(self.unbox(v))
590 if decimals < 0:
591 # No ** in rpython
592 factor = 1
593 for i in xrange(-decimals):
594 factor *=10
595 #int does floor division, we want toward zero
596 if raw < 0:
597 ans = - (-raw / factor * factor)
598 else:
599 ans = raw / factor * factor
600 else:
601 ans = raw
602 return self.box(ans)
603
604 @raw_unary_op
605 def signbit(self, v):
606 return v < 0
607
608 class Int8(BaseType, Integer):
609 T = rffi.SIGNEDCHAR
610 num = NPY.BYTE
611 kind = NPY.SIGNEDLTR
612 char = NPY.BYTELTR
613 BoxType = boxes.W_Int8Box
614 format_code = "b"
615
616 class UInt8(BaseType, Integer):
617 T = rffi.UCHAR
618 num = NPY.UBYTE
619 kind = NPY.UNSIGNEDLTR
620 char = NPY.UBYTELTR
621 BoxType = boxes.W_UInt8Box
622 format_code = "B"
623 signed = False
624
625 class Int16(BaseType, Integer):
626 T = rffi.SHORT
627 num = NPY.SHORT
628 kind = NPY.SIGNEDLTR
629 char = NPY.SHORTLTR
630 BoxType = boxes.W_Int16Box
631 format_code = "h"
632
633 class UInt16(BaseType, Integer):
634 T = rffi.USHORT
635 num = NPY.USHORT
636 kind = NPY.UNSIGNEDLTR
637 char = NPY.USHORTLTR
638 BoxType = boxes.W_UInt16Box
639 format_code = "H"
640 signed = False
641
642 class Int32(BaseType, Integer):
643 T = rffi.INT
644 num = NPY.INT
645 kind = NPY.SIGNEDLTR
646 char = NPY.INTLTR
647 BoxType = boxes.W_Int32Box
648 format_code = "i"
649
650 class UInt32(BaseType, Integer):
651 T = rffi.UINT
652 num = NPY.UINT
653 kind = NPY.UNSIGNEDLTR
654 char = NPY.UINTLTR
655 BoxType = boxes.W_UInt32Box
656 format_code = "I"
657 signed = False
658
659 def _int64_coerce(self, space, w_item):
660 try:
661 return self._base_coerce(space, w_item)
662 except OperationError as e:
663 if not e.match(space, space.w_OverflowError):
664 raise
665 bigint = space.bigint_w(w_item)
666 try:
667 value = bigint.tolonglong()
668 except OverflowError:
669 raise OperationError(space.w_OverflowError, space.w_None)
670 return self.box(value)
671
672 class Int64(BaseType, Integer):
673 T = rffi.LONGLONG
674 num = NPY.LONGLONG
675 kind = NPY.SIGNEDLTR
676 char = NPY.LONGLONGLTR
677 BoxType = boxes.W_Int64Box
678 format_code = "q"
679
680 if LONG_BIT == 32:
681 _coerce = func_with_new_name(_int64_coerce, '_coerce')
682
683 def _uint64_coerce(self, space, w_item):
684 try:
685 return self._base_coerce(space, w_item)
686 except OperationError as e:
687 if not e.match(space, space.w_OverflowError):
688 raise
689 bigint = space.bigint_w(w_item)
690 try:
691 value = bigint.toulonglong()
692 except OverflowError:
693 raise OperationError(space.w_OverflowError, space.w_None)
694 return self.box(value)
695
696 class UInt64(BaseType, Integer):
697 T = rffi.ULONGLONG
698 num = NPY.ULONGLONG
699 kind = NPY.UNSIGNEDLTR
700 char = NPY.ULONGLONGLTR
701 BoxType = boxes.W_UInt64Box
702 format_code = "Q"
703 signed = False
704
705 _coerce = func_with_new_name(_uint64_coerce, '_coerce')
706
707 class Long(BaseType, Integer):
708 T = rffi.LONG
709 num = NPY.LONG
710 kind = NPY.SIGNEDLTR
711 char = NPY.LONGLTR
712 BoxType = boxes.W_LongBox
713 format_code = "l"
714
715 def _ulong_coerce(self, space, w_item):
716 try:
717 return self._base_coerce(space, w_item)
718 except OperationError as e:
719 if not e.match(space, space.w_OverflowError):
720 raise
721 bigint = space.bigint_w(w_item)
722 try:
723 value = bigint.touint()
724 except OverflowError:
725 raise OperationError(space.w_OverflowError, space.w_None)
726 return self.box(value)
727
728 class ULong(BaseType, Integer):
729 T = rffi.ULONG
730 num = NPY.ULONG
731 kind = NPY.UNSIGNEDLTR
732 char = NPY.ULONGLTR
733 BoxType = boxes.W_ULongBox
734 format_code = "L"
735 signed = False
736
737 _coerce = func_with_new_name(_ulong_coerce, '_coerce')
738
739 class Float(Primitive):
740 _mixin_ = True
741 strlen = 32
742
743 def to_builtin_type(self, space, box):
744 return space.newfloat(self.for_computation(self.unbox(box)))
745
746 def _coerce(self, space, w_item):
747 if w_item is None:
748 return self.box(0.0)
749 if space.is_none(w_item):
750 return self.box(rfloat.NAN)
751 return self.box(space.float_w(space.call_function(space.w_float, w_item)))
752
753 def str_format(self, box, add_quotes=True):
754 return float2string(self.for_computation(self.unbox(box)), "g",
755 rfloat.DTSF_STR_PRECISION)
756
757 @staticmethod
758 def for_computation(v):
759 return float(v)
760
761 def default_fromstring(self, space):
762 return self.box(-1.0)
763
764 @simple_binary_op
765 def div(self, v1, v2):
766 try:
767 return v1 / v2
768 except ZeroDivisionError:
769 if v1 == v2 == 0.0:
770 return rfloat.NAN
771 return math.copysign(rfloat.INFINITY, v1 * v2)
772
773 @simple_binary_op
774 def floordiv(self, v1, v2):
775 try:
776 return math.floor(v1 / v2)
777 except ZeroDivisionError:
778 if v1 == v2 == 0.0:
779 return rfloat.NAN
780 return math.copysign(rfloat.INFINITY, v1 * v2)
781
782 @simple_binary_op
783 def mod(self, v1, v2):
784 # partial copy of pypy.objspace.std.floatobject.W_FloatObject.descr_mod
785 if v2 == 0.0:
786 return rfloat.NAN
787 mod = math.fmod(v1, v2)
788 if mod:
789 # ensure the remainder has the same sign as the denominator
790 if (v2 < 0.0) != (mod < 0.0):
791 mod += v2
792 else:
793 # the remainder is zero, and in the presence of signed zeroes
794 # fmod returns different results across platforms; ensure
795 # it has the same sign as the denominator; we'd like to do
796 # "mod = v2 * 0.0", but that may get optimized away
797 mod = math.copysign(0.0, v2)
798 return mod
799
800 @simple_binary_op
801 def pow(self, v1, v2):
802 try:
803 return math.pow(v1, v2)
804 except ValueError:
805 return rfloat.NAN
806 except OverflowError:
807 if math.modf(v2)[0] == 0 and math.modf(v2 / 2)[0] != 0:
808 # Odd integer powers result in the same sign as the base
809 return math.copysign(rfloat.INFINITY, v1)
810 return rfloat.INFINITY
811
812 @simple_binary_op
813 def copysign(self, v1, v2):
814 return math.copysign(v1, v2)
815
816 @simple_unary_op
817 def sign(self, v):
818 if v == 0.0:
819 return 0.0
820 if math.isnan(v):
821 return rfloat.NAN
822 return math.copysign(1.0, v)
823
824 @raw_unary_op
825 def signbit(self, v):
826 return math.copysign(1.0, v) < 0.0
827
828 @simple_unary_op
829 def fabs(self, v):
830 return math.fabs(v)
831
832 @simple_binary_op
833 def max(self, v1, v2):
834 return v1 if v1 >= v2 or math.isnan(v1) else v2
835
836 @simple_binary_op
837 def min(self, v1, v2):
838 return v1 if v1 <= v2 or math.isnan(v1) else v2
839
840 @raw_binary_op
841 def argmax(self, v1, v2):
842 return v1 >= v2 or math.isnan(v1)
843
844 @raw_binary_op
845 def argmin(self, v1, v2):
846 return v1 <= v2 or math.isnan(v1)
847
848 @simple_binary_op
849 def fmax(self, v1, v2):
850 return v1 if v1 >= v2 or math.isnan(v2) else v2
851
852 @simple_binary_op
853 def fmin(self, v1, v2):
854 return v1 if v1 <= v2 or math.isnan(v2) else v2
855
856 @simple_binary_op
857 def fmod(self, v1, v2):
858 try:
859 return math.fmod(v1, v2)
860 except ValueError:
861 return rfloat.NAN
862
863 @simple_unary_op
864 def reciprocal(self, v):
865 if v == 0.0:
866 return math.copysign(rfloat.INFINITY, v)
867 return 1.0 / v
868
869 @simple_unary_op
870 def floor(self, v):
871 return math.floor(v)
872
873 @simple_unary_op
874 def ceil(self, v):
875 return math.ceil(v)
876
877 @specialize.argtype(1)
878 def round(self, v, decimals=0):
879 raw = self.for_computation(self.unbox(v))
880 if math.isinf(raw):
881 return v
882 elif math.isnan(raw):
883 return v
884 ans = rfloat.round_double(raw, decimals, half_even=True)
885 return self.box(ans)
886
887 @simple_unary_op
888 def trunc(self, v):
889 if v < 0:
890 return math.ceil(v)
891 else:
892 return math.floor(v)
893
894 @simple_unary_op
895 def exp(self, v):
896 try:
897 return math.exp(v)
898 except OverflowError:
899 return rfloat.INFINITY
900
901 @simple_unary_op
902 def exp2(self, v):
903 try:
904 return math.pow(2, v)
905 except OverflowError:
906 return rfloat.INFINITY
907
908 @simple_unary_op
909 def expm1(self, v):
910 try:
911 return rfloat.expm1(v)
912 except OverflowError:
913 return rfloat.INFINITY
914
915 @simple_unary_op
916 def sin(self, v):
917 return math.sin(v)
918
919 @simple_unary_op
920 def cos(self, v):
921 return math.cos(v)
922
923 @simple_unary_op
924 def tan(self, v):
925 return math.tan(v)
926
927 @simple_unary_op
928 def arcsin(self, v):
929 if not -1.0 <= v <= 1.0:
930 return rfloat.NAN
931 return math.asin(v)
932
933 @simple_unary_op
934 def arccos(self, v):
935 if not -1.0 <= v <= 1.0:
936 return rfloat.NAN
937 return math.acos(v)
938
939 @simple_unary_op
940 def arctan(self, v):
941 return math.atan(v)
942
943 @simple_binary_op
944 def arctan2(self, v1, v2):
945 return math.atan2(v1, v2)
946
947 @simple_unary_op
948 def sinh(self, v):
949 return math.sinh(v)
950
951 @simple_unary_op
952 def cosh(self, v):
953 return math.cosh(v)
954
955 @simple_unary_op
956 def tanh(self, v):
957 return math.tanh(v)
958
959 @simple_unary_op
960 def arcsinh(self, v):
961 return math.asinh(v)
962
963 @simple_unary_op
964 def arccosh(self, v):
965 if v < 1.0:
966 return rfloat.NAN
967 return math.acosh(v)
968
969 @simple_unary_op
970 def arctanh(self, v):
971 if v == 1.0 or v == -1.0:
972 return math.copysign(rfloat.INFINITY, v)
973 if not -1.0 < v < 1.0:
974 return rfloat.NAN
975 return math.atanh(v)
976
977 @simple_unary_op
978 def sqrt(self, v):
979 try:
980 return math.sqrt(v)
981 except ValueError:
982 return rfloat.NAN
983
984 @simple_unary_op
985 def square(self, v):
986 return v*v
987
988 @raw_unary_op
989 def isnan(self, v):
990 return math.isnan(v)
991
992 @raw_unary_op
993 def isinf(self, v):
994 return math.isinf(v)
995
996 @raw_unary_op
997 def isfinite(self, v):
998 return rfloat.isfinite(v)
999
1000 @simple_unary_op
1001 def radians(self, v):
1002 return v * degToRad
1003 deg2rad = radians
1004
1005 @simple_unary_op
1006 def degrees(self, v):
1007 return v / degToRad
1008
1009 @simple_unary_op
1010 def log(self, v):
1011 try:
1012 return math.log(v)
1013 except ValueError:
1014 if v == 0.0:
1015 # CPython raises ValueError here, so we have to check
1016 # the value to find the correct numpy return value
1017 return -rfloat.INFINITY
1018 return rfloat.NAN
1019
1020 @simple_unary_op
1021 def log2(self, v):
1022 try:
1023 return math.log(v) / log2
1024 except ValueError:
1025 if v == 0.0:
1026 # CPython raises ValueError here, so we have to check
1027 # the value to find the correct numpy return value
1028 return -rfloat.INFINITY
1029 return rfloat.NAN
1030
1031 @simple_unary_op
1032 def log10(self, v):
1033 try:
1034 return math.log10(v)
1035 except ValueError:
1036 if v == 0.0:
1037 # CPython raises ValueError here, so we have to check
1038 # the value to find the correct numpy return value
1039 return -rfloat.INFINITY
1040 return rfloat.NAN
1041
1042 @simple_unary_op
1043 def log1p(self, v):
1044 try:
1045 return rfloat.log1p(v)
1046 except OverflowError:
1047 return -rfloat.INFINITY
1048 except ValueError:
1049 return rfloat.NAN
1050
1051 @simple_binary_op
1052 def logaddexp(self, v1, v2):
1053 tmp = v1 - v2
1054 if tmp > 0:
1055 return v1 + rfloat.log1p(math.exp(-tmp))
1056 elif tmp <= 0:
1057 return v2 + rfloat.log1p(math.exp(tmp))
1058 else:
1059 return v1 + v2
1060
1061 def npy_log2_1p(self, v):
1062 return log2e * rfloat.log1p(v)
1063
1064 @simple_binary_op
1065 def logaddexp2(self, v1, v2):
1066 tmp = v1 - v2
1067 if tmp > 0:
1068 return v1 + self.npy_log2_1p(math.pow(2, -tmp))
1069 if tmp <= 0:
1070 return v2 + self.npy_log2_1p(math.pow(2, tmp))
1071 else:
1072 return v1 + v2
1073
1074 @simple_unary_op
1075 def rint(self, v):
1076 x = float(v)
1077 if rfloat.isfinite(x):
1078 import math
1079 y = math.floor(x)
1080 r = x - y
1081
1082 if r > 0.5:
1083 y += 1.0
1084
1085 if r == 0.5:
1086 r = y - 2.0 * math.floor(0.5 * y)
1087 if r == 1.0:
1088 y += 1.0
1089 return y
1090 else:
1091 return x
1092
1093 class Float16(Float, BaseType):
1094 _STORAGE_T = rffi.USHORT
1095 T = rffi.SHORT
1096 num = NPY.HALF
1097 kind = NPY.FLOATINGLTR
1098 char = NPY.HALFLTR
1099 BoxType = boxes.W_Float16Box
1100 max_value = 65000.
1101
1102 @specialize.argtype(1)
1103 def box(self, value):
1104 return self.BoxType(rffi.cast(rffi.DOUBLE, value))
1105
1106 def runpack_str(self, space, s, native):
1107 assert len(s) == 2
1108 fval = self.box(unpack_float(s, native_is_bigendian))
1109 if not native:
1110 fval = self.byteswap(fval)
1111 return fval
1112
1113 def default_fromstring(self, space):
1114 return self.box(-1.0)
1115
1116 def byteswap(self, w_v):
1117 value = self.unbox(w_v)
1118 hbits = float_pack(value, 2)
1119 swapped = byteswap(rffi.cast(self._STORAGE_T, hbits))
1120 return self.box(float_unpack(r_ulonglong(swapped), 2))
1121
1122 def _read(self, storage, i, offset, native):
1123 hbits = raw_storage_getitem_unaligned(self._STORAGE_T, storage, i + offset)
1124 if not native:
1125 hbits = byteswap(hbits)
1126 return float_unpack(r_ulonglong(hbits), 2)
1127
1128 def _write(self, storage, i, offset, value, native):
1129 try:
1130 hbits = float_pack(value, 2)
1131 except OverflowError:
1132 hbits = float_pack(rfloat.INFINITY, 2)
1133 hbits = rffi.cast(self._STORAGE_T, hbits)
1134 if not native:
1135 hbits = byteswap(hbits)
1136 raw_storage_setitem_unaligned(storage, i + offset, hbits)
1137
1138 class Float32(Float, BaseType):
1139 T = rffi.FLOAT
1140 num = NPY.FLOAT
1141 kind = NPY.FLOATINGLTR
1142 char = NPY.FLOATLTR
1143 BoxType = boxes.W_Float32Box
1144 format_code = "f"
1145 max_value = 3.4e38
1146
1147 class Float64(Float, BaseType):
1148 T = rffi.DOUBLE
1149 num = NPY.DOUBLE
1150 kind = NPY.FLOATINGLTR
1151 char = NPY.DOUBLELTR
1152 BoxType = boxes.W_Float64Box
1153 format_code = "d"
1154 max_value = 1.7e308
1155
1156 class ComplexFloating(object):
1157 _mixin_ = True
1158 strlen = 64
1159
1160 def _coerce(self, space, w_item):
1161 if w_item is None:
1162 return self.box_complex(0.0, 0.0)
1163 if space.is_none(w_item):
1164 return self.box_complex(rfloat.NAN, rfloat.NAN)
1165 w_item = space.call_function(space.w_complex, w_item)
1166 real, imag = space.unpackcomplex(w_item)
1167 return self.box_complex(real, imag)
1168
1169 def coerce(self, space, dtype, w_item):
1170 if isinstance(w_item, self.BoxType):
1171 return w_item
1172 return self.coerce_subtype(space, space.gettypefor(self.BoxType), w_item)
1173
1174 def coerce_subtype(self, space, w_subtype, w_item):
1175 w_tmpobj = self._coerce(space, w_item)
1176 w_obj = space.allocate_instance(self.BoxType, w_subtype)
1177 assert isinstance(w_obj, self.BoxType)
1178 w_obj.__init__(w_tmpobj.real, w_tmpobj.imag)
1179 return w_obj
1180
1181 def str_format(self, box, add_quotes=True):
1182 real, imag = self.for_computation(self.unbox(box))
1183 imag_str = format_float(imag, 'g', rfloat.DTSF_STR_PRECISION)
1184 if not rfloat.isfinite(imag):
1185 imag_str += '*'
1186 imag_str += 'j'
1187
1188 # (0+2j) => 2j
1189 if real == 0 and math.copysign(1, real) == 1:
1190 return imag_str
1191
1192 real_str = format_float(real, 'g', rfloat.DTSF_STR_PRECISION)
1193 op = '+' if imag >= 0 or math.isnan(imag) else ''
1194 return ''.join(['(', real_str, op, imag_str, ')'])
1195
1196 def runpack_str(self, space, s, native):
1197 comp = self.ComponentBoxType._get_dtype(space)
1198 l = len(s) // 2
1199 real = comp.runpack_str(space, s[:l])
1200 imag = comp.runpack_str(space, s[l:])
1201 if not native:
1202 real = comp.itemtype.byteswap(real)
1203 imag = comp.itemtype.byteswap(imag)
1204 return self.composite(real, imag)
1205
1206 @staticmethod
1207 def for_computation(v):
1208 return float(v[0]), float(v[1])
1209
1210 @raw_unary_op
1211 def _to_builtin_type(self, v):
1212 return v
1213
1214 def to_builtin_type(self, space, box):
1215 real, imag = self.for_computation(self.unbox(box))
1216 return space.newcomplex(real, imag)
1217
1218 def bool(self, v):
1219 real, imag = self.for_computation(self.unbox(v))
1220 return bool(real) or bool(imag)
1221
1222 def read_bool(self, arr, i, offset, dtype):
1223 with arr as storage:
1224 v = self.for_computation(
1225 self._read(storage, i, offset, dtype.is_native()))
1226 return bool(v[0]) or bool(v[1])
1227
1228 def get_element_size(self):
1229 return 2 * rffi.sizeof(self.T)
1230
1231 def byteswap(self, w_v):
1232 real, imag = self.unbox(w_v)
1233 return self.box_complex(byteswap(real), byteswap(imag))
1234
1235 @specialize.argtype(1)
1236 def box(self, value):
1237 return self.BoxType(
1238 rffi.cast(self.T, value),
1239 rffi.cast(self.T, 0.0))
1240
1241 @specialize.argtype(1)
1242 def box_component(self, value):
1243 return self.ComponentBoxType(
1244 rffi.cast(self.T, value))
1245
1246 @specialize.argtype(1, 2)
1247 def box_complex(self, real, imag):
1248 return self.BoxType(
1249 rffi.cast(self.T, real),
1250 rffi.cast(self.T, imag))
1251
1252 def box_raw_data(self, data):
1253 # For pickle
1254 array = rffi.cast(rffi.CArrayPtr(self.T), data)
1255 return self.box_complex(array[0], array[1])
1256
1257 def composite(self, v1, v2):
1258 assert isinstance(v1, self.ComponentBoxType)
1259 assert isinstance(v2, self.ComponentBoxType)
1260 real = v1.value
1261 imag = v2.value
1262 return self.box_complex(real, imag)
1263
1264 def unbox(self, box):
1265 if isinstance(box, self.BoxType):
1266 return box.real, box.imag
1267 elif isinstance(box, boxes.W_ObjectBox):
1268 retval = self._coerce(self.space, box)
1269 return retval.real, retval.imag
1270 else:
1271 raise oefmt(self.space.w_NotImplementedError,
1272 "%s dtype cannot unbox %s", str(self), str(box))
1273
1274 def _read(self, storage, i, offset, native):
1275 real = raw_storage_getitem_unaligned(self.T, storage, i + offset)
1276 imag = raw_storage_getitem_unaligned(self.T, storage, i + offset + rffi.sizeof(self.T))
1277 if not native:
1278 real = byteswap(real)
1279 imag = byteswap(imag)
1280 return real, imag
1281
1282 def read(self, arr, i, offset, dtype):
1283 with arr as storage:
1284 real, imag = self._read(storage, i, offset, dtype.is_native())
1285 return self.box_complex(real, imag)
1286
1287 def _write(self, storage, i, offset, value, native):
1288 real, imag = value
1289 if not native:
1290 real = byteswap(real)
1291 imag = byteswap(imag)
1292 raw_storage_setitem_unaligned(storage, i + offset, real)
1293 raw_storage_setitem_unaligned(storage, i + offset + rffi.sizeof(self.T), imag)
1294
1295 def store(self, arr, i, offset, box, native):
1296 with arr as storage:
1297 self._write(storage, i, offset, self.unbox(box), native)
1298
1299 def fill(self, storage, width, native, box, start, stop, offset, gcstruct):
1300 value = self.unbox(box)
1301 for i in xrange(start, stop, width):
1302 self._write(storage, i, offset, value, native)
1303
1304 @complex_binary_op
1305 def add(self, v1, v2):
1306 return rcomplex.c_add(v1, v2)
1307
1308 @complex_binary_op
1309 def sub(self, v1, v2):
1310 return rcomplex.c_sub(v1, v2)
1311
1312 @complex_binary_op
1313 def mul(self, v1, v2):
1314 return rcomplex.c_mul(v1, v2)
1315
1316 @complex_binary_op
1317 def div(self, v1, v2):
1318 try:
1319 return rcomplex.c_div(v1, v2)
1320 except ZeroDivisionError:
1321 if rcomplex.c_abs(*v1) == 0 or \
1322 (math.isnan(v1[0]) and math.isnan(v1[1])):
1323 return rfloat.NAN, rfloat.NAN
1324 return rfloat.INFINITY, rfloat.INFINITY
1325
1326 @complex_unary_op
1327 def pos(self, v):
1328 return v
1329
1330 @complex_unary_op
1331 def neg(self, v):
1332 return -v[0], -v[1]
1333
1334 @complex_unary_op
1335 def conj(self, v):
1336 return v[0], -v[1]
1337
1338 @complex_to_real_unary_op
1339 def real(self, v):
1340 return v[0]
1341
1342 @complex_to_real_unary_op
1343 def imag(self, v):
1344 return v[1]
1345
1346 @complex_to_real_unary_op
1347 def abs(self, v):
1348 try:
1349 return rcomplex.c_abs(v[0], v[1])
1350 except OverflowError:
1351 # warning ...
1352 return rfloat.INFINITY
1353
1354 @raw_unary_op
1355 def isnan(self, v):
1356 '''a complex number is nan if one of the parts is nan'''
1357 return math.isnan(v[0]) or math.isnan(v[1])
1358
1359 @raw_unary_op
1360 def isinf(self, v):
1361 '''a complex number is inf if one of the parts is inf'''
1362 return math.isinf(v[0]) or math.isinf(v[1])
1363
1364 def _eq(self, v1, v2):
1365 return v1[0] == v2[0] and v1[1] == v2[1]
1366
1367 @raw_binary_op
1368 def eq(self, v1, v2):
1369 #compare the parts, so nan == nan is False
1370 return self._eq(v1, v2)
1371
1372 @raw_binary_op
1373 def ne(self, v1, v2):
1374 return not self._eq(v1, v2)
1375
1376 def _lt(self, v1, v2):
1377 (r1, i1), (r2, i2) = v1, v2
1378 if r1 < r2 and not math.isnan(i1) and not math.isnan(i2):
1379 return True
1380 if r1 == r2 and i1 < i2:
1381 return True
1382 return False
1383
1384 @raw_binary_op
1385 def lt(self, v1, v2):
1386 return self._lt(v1, v2)
1387
1388 @raw_binary_op
1389 def le(self, v1, v2):
1390 return self._lt(v1, v2) or self._eq(v1, v2)
1391
1392 @raw_binary_op
1393 def gt(self, v1, v2):
1394 return self._lt(v2, v1)
1395
1396 @raw_binary_op
1397 def ge(self, v1, v2):
1398 return self._lt(v2, v1) or self._eq(v2, v1)
1399
1400 def _cbool(self, v):
1401 return bool(v[0]) or bool(v[1])
1402
1403 @raw_binary_op
1404 def logical_and(self, v1, v2):
1405 if self._cbool(v1) and self._cbool(v2):
1406 return Bool._True
1407 return Bool._False
1408
1409 @raw_binary_op
1410 def logical_or(self, v1, v2):
1411 if self._cbool(v1) or self._cbool(v2):
1412 return Bool._True
1413 return Bool._False
1414
1415 @raw_unary_op
1416 def logical_not(self, v):
1417 return not self._cbool(v)
1418
1419 @raw_binary_op
1420 def logical_xor(self, v1, v2):
1421 a = self._cbool(v1)
1422 b = self._cbool(v2)
1423 return (not b and a) or (not a and b)
1424
1425 def min(self, v1, v2):
1426 if self.le(v1, v2) or self.isnan(v1):
1427 return v1
1428 return v2
1429
1430 def max(self, v1, v2):
1431 if self.ge(v1, v2) or self.isnan(v1):
1432 return v1
1433 return v2
1434
1435 def argmin(self, v1, v2):
1436 if self.le(v1, v2) or self.isnan(v1):
1437 return True
1438 return False
1439
1440 def argmax(self, v1, v2):
1441 if self.ge(v1, v2) or self.isnan(v1):
1442 return True
1443 return False
1444
1445 @complex_binary_op
1446 def floordiv(self, v1, v2):
1447 (r1, i1), (r2, i2) = v1, v2
1448 if r2 < 0:
1449 abs_r2 = -r2
1450 else:
1451 abs_r2 = r2
1452 if i2 < 0:
1453 abs_i2 = -i2
1454 else:
1455 abs_i2 = i2
1456 if abs_r2 >= abs_i2:
1457 if abs_r2 == 0.0:
1458 return rfloat.NAN, 0.
1459 else:
1460 ratio = i2 / r2
1461 denom = r2 + i2 * ratio
1462 rr = (r1 + i1 * ratio) / denom
1463 elif math.isnan(r2):
1464 rr = rfloat.NAN
1465 else:
1466 ratio = r2 / i2
1467 denom = r2 * ratio + i2
1468 assert i2 != 0.0
1469 rr = (r1 * ratio + i1) / denom
1470 return math.floor(rr), 0.
1471
1472 #complex mod does not exist in numpy
1473 #@simple_binary_op
1474 #def mod(self, v1, v2):
1475 # return math.fmod(v1, v2)
1476
1477 def pow(self, v1, v2):
1478 y = self.for_computation(self.unbox(v2))
1479 if y[1] == 0:
1480 if y[0] == 0:
1481 return self.box_complex(1, 0)
1482 if y[0] == 1:
1483 return v1
1484 if y[0] == 2:
1485 return self.mul(v1, v1)
1486 x = self.for_computation(self.unbox(v1))
1487 if x[0] == 0 and x[1] == 0:
1488 if y[0] > 0 and y[1] == 0:
1489 return self.box_complex(0, 0)
1490 return self.box_complex(rfloat.NAN, rfloat.NAN)
1491 b = self.for_computation(self.unbox(self.log(v1)))
1492 return self.exp(self.box_complex(b[0] * y[0] - b[1] * y[1],
1493 b[0] * y[1] + b[1] * y[0]))
1494
1495 #complex copysign does not exist in numpy
1496 #@complex_binary_op
1497 #def copysign(self, v1, v2):
1498 # return (rfloat.copysign(v1[0], v2[0]),
1499 # rfloat.copysign(v1[1], v2[1]))
1500
1501 @complex_unary_op
1502 def sign(self, v):
1503 '''
1504 sign of complex number could be either the point closest to the unit circle
1505 or {-1,0,1}, for compatability with numpy we choose the latter
1506 '''
1507 if math.isnan(v[0]) or math.isnan(v[1]):
1508 return rfloat.NAN, 0
1509 if v[0] == 0.0:
1510 if v[1] == 0:
1511 return 0, 0
1512 if v[1] > 0:
1513 return 1, 0
1514 return -1, 0
1515 if v[0] > 0:
1516 return 1, 0
1517 return -1, 0
1518
1519 def fmax(self, v1, v2):
1520 if self.ge(v1, v2) or self.isnan(v2):
1521 return v1
1522 return v2
1523
1524 def fmin(self, v1, v2):
1525 if self.le(v1, v2) or self.isnan(v2):
1526 return v1
1527 return v2
1528
1529 #@simple_binary_op
1530 #def fmod(self, v1, v2):
1531 # try:
1532 # return math.fmod(v1, v2)
1533 # except ValueError:
1534 # return rfloat.NAN
1535
1536 @complex_unary_op
1537 def reciprocal(self, v):
1538 if math.isinf(v[1]) and math.isinf(v[0]):
1539 return rfloat.NAN, rfloat.NAN
1540 if math.isinf(v[0]):
1541 return (math.copysign(0., v[0]),
1542 math.copysign(0., -v[1]))
1543 a2 = v[0]*v[0] + v[1]*v[1]
1544 try:
1545 return rcomplex.c_div((v[0], -v[1]), (a2, 0.))
1546 except ZeroDivisionError:
1547 return rfloat.NAN, rfloat.NAN
1548
1549 @specialize.argtype(1)
1550 def round(self, v, decimals=0):
1551 ans = list(self.for_computation(self.unbox(v)))
1552 if rfloat.isfinite(ans[0]):
1553 ans[0] = rfloat.round_double(ans[0], decimals, half_even=True)
1554 if rfloat.isfinite(ans[1]):
1555 ans[1] = rfloat.round_double(ans[1], decimals, half_even=True)
1556 return self.box_complex(ans[0], ans[1])
1557
1558 def rint(self, v):
1559 return self.round(v)
1560
1561 # No floor, ceil, trunc in numpy for complex
1562 #@simple_unary_op
1563 #def floor(self, v):
1564 # return math.floor(v)
1565
1566 #@simple_unary_op
1567 #def ceil(self, v):
1568 # return math.ceil(v)
1569
1570 #@simple_unary_op
1571 #def trunc(self, v):
1572 # if v < 0:
1573 # return math.ceil(v)
1574 # else:
1575 # return math.floor(v)
1576
1577 @complex_unary_op
1578 def exp(self, v):
1579 if math.isinf(v[1]):
1580 if math.isinf(v[0]):
1581 if v[0] < 0:
1582 return 0., 0.
1583 return rfloat.INFINITY, rfloat.NAN
1584 elif (rfloat.isfinite(v[0]) or \
1585 (math.isinf(v[0]) and v[0] > 0)):
1586 return rfloat.NAN, rfloat.NAN
1587 try:
1588 return rcomplex.c_exp(*v)
1589 except OverflowError:
1590 if v[1] == 0:
1591 return rfloat.INFINITY, 0.0
1592 return rfloat.INFINITY, rfloat.NAN
1593
1594 @complex_unary_op
1595 def exp2(self, v):
1596 try:
1597 return rcomplex.c_pow((2,0), v)
1598 except OverflowError:
1599 return rfloat.INFINITY, rfloat.NAN
1600 except ValueError:
1601 return rfloat.NAN, rfloat.NAN
1602
1603 @complex_unary_op
1604 def expm1(self, v):
1605 # duplicate exp() so in the future it will be easier
1606 # to implement seterr
1607 if math.isinf(v[1]):
1608 if math.isinf(v[0]):
1609 if v[0] < 0:
1610 return -1., 0.
1611 return rfloat.NAN, rfloat.NAN
1612 elif (rfloat.isfinite(v[0]) or \
1613 (math.isinf(v[0]) and v[0] > 0)):
1614 return rfloat.NAN, rfloat.NAN
1615 try:
1616 res = rcomplex.c_exp(*v)
1617 res = (res[0]-1, res[1])
1618 return res
1619 except OverflowError:
1620 if v[1] == 0:
1621 return rfloat.INFINITY, 0.0
1622 return rfloat.INFINITY, rfloat.NAN
1623
1624 @complex_unary_op
1625 def sin(self, v):
1626 if math.isinf(v[0]):
1627 if v[1] == 0.:
1628 return rfloat.NAN, 0.
1629 if rfloat.isfinite(v[1]):
1630 return rfloat.NAN, rfloat.NAN
1631 elif not math.isnan(v[1]):
1632 return rfloat.NAN, rfloat.INFINITY
1633 return rcomplex.c_sin(*v)
1634
1635 @complex_unary_op
1636 def cos(self, v):
1637 if math.isinf(v[0]):
1638 if v[1] == 0.:
1639 return rfloat.NAN, 0.0
1640 if rfloat.isfinite(v[1]):
1641 return rfloat.NAN, rfloat.NAN
1642 elif not math.isnan(v[1]):
1643 return rfloat.INFINITY, rfloat.NAN
1644 return rcomplex.c_cos(*v)
1645
1646 @complex_unary_op
1647 def tan(self, v):
1648 if math.isinf(v[0]) and rfloat.isfinite(v[1]):
1649 return rfloat.NAN, rfloat.NAN
1650 return rcomplex.c_tan(*v)
1651
1652 @complex_unary_op
1653 def arcsin(self, v):
1654 return rcomplex.c_asin(*v)
1655
1656 @complex_unary_op
1657 def arccos(self, v):
1658 return rcomplex.c_acos(*v)
1659
1660 @complex_unary_op
1661 def arctan(self, v):
1662 if v[0] == 0 and (v[1] == 1 or v[1] == -1):
1663 #This is the place to print a "runtime warning"
1664 return rfloat.NAN, math.copysign(rfloat.INFINITY, v[1])
1665 return rcomplex.c_atan(*v)
1666
1667 #@complex_binary_op
1668 #def arctan2(self, v1, v2):
1669 # return rcomplex.c_atan2(v1, v2)
1670
1671 @complex_unary_op
1672 def sinh(self, v):
1673 if math.isinf(v[1]):
1674 if rfloat.isfinite(v[0]):
1675 if v[0] == 0.0:
1676 return 0.0, rfloat.NAN
1677 return rfloat.NAN, rfloat.NAN
1678 elif not math.isnan(v[0]):
1679 return rfloat.INFINITY, rfloat.NAN
1680 return rcomplex.c_sinh(*v)
1681
1682 @complex_unary_op
1683 def cosh(self, v):
1684 if math.isinf(v[1]):
1685 if rfloat.isfinite(v[0]):
1686 if v[0] == 0.0:
1687 return rfloat.NAN, 0.0
1688 return rfloat.NAN, rfloat.NAN
1689 elif not math.isnan(v[0]):
1690 return rfloat.INFINITY, rfloat.NAN
1691 return rcomplex.c_cosh(*v)
1692
1693 @complex_unary_op
1694 def tanh(self, v):
1695 if math.isinf(v[1]) and rfloat.isfinite(v[0]):
1696 return rfloat.NAN, rfloat.NAN
1697 return rcomplex.c_tanh(*v)
1698
1699 @complex_unary_op
1700 def arcsinh(self, v):
1701 return rcomplex.c_asinh(*v)
1702
1703 @complex_unary_op
1704 def arccosh(self, v):
1705 return rcomplex.c_acosh(*v)
1706
1707 @complex_unary_op
1708 def arctanh(self, v):
1709 if v[1] == 0 and (v[0] == 1.0 or v[0] == -1.0):
1710 return (math.copysign(rfloat.INFINITY, v[0]),
1711 math.copysign(0., v[1]))
1712 return rcomplex.c_atanh(*v)
1713
1714 @complex_unary_op
1715 def sqrt(self, v):
1716 return rcomplex.c_sqrt(*v)
1717
1718 @complex_unary_op
1719 def square(self, v):
1720 return rcomplex.c_mul(v,v)
1721
1722 @raw_unary_op
1723 def isfinite(self, v):
1724 return rfloat.isfinite(v[0]) and rfloat.isfinite(v[1])
1725
1726 #@simple_unary_op
1727 #def radians(self, v):
1728 # return v * degToRad
1729 #deg2rad = radians
1730
1731 #@simple_unary_op
1732 #def degrees(self, v):
1733 # return v / degToRad
1734
1735 @complex_unary_op
1736 def log(self, v):
1737 try:
1738 return rcomplex.c_log(*v)
1739 except ValueError:
1740 return -rfloat.INFINITY, math.atan2(v[1], v[0])
1741
1742 @complex_unary_op
1743 def log2(self, v):
1744 try:
1745 r = rcomplex.c_log(*v)
1746 except ValueError:
1747 r = -rfloat.INFINITY, math.atan2(v[1], v[0])
1748 return r[0] / log2, r[1] / log2
1749
1750 @complex_unary_op
1751 def log10(self, v):
1752 try:
1753 return rcomplex.c_log10(*v)
1754 except ValueError:
1755 return -rfloat.INFINITY, math.atan2(v[1], v[0]) / log10
1756
1757 @complex_unary_op
1758 def log1p(self, v):
1759 try:
1760 return rcomplex.c_log(v[0] + 1, v[1])
1761 except OverflowError:
1762 return -rfloat.INFINITY, 0
1763 except ValueError:
1764 return rfloat.NAN, rfloat.NAN
1765
1766 class Complex64(ComplexFloating, BaseType):
1767 T = rffi.FLOAT
1768 num = NPY.CFLOAT
1769 kind = NPY.COMPLEXLTR
1770 char = NPY.CFLOATLTR
1771 BoxType = boxes.W_Complex64Box
1772 ComponentBoxType = boxes.W_Float32Box
1773 ComponentType = Float32
1774
1775 class Complex128(ComplexFloating, BaseType):
1776 T = rffi.DOUBLE
1777 num = NPY.CDOUBLE
1778 kind = NPY.COMPLEXLTR
1779 char = NPY.CDOUBLELTR
1780 BoxType = boxes.W_Complex128Box
1781 ComponentBoxType = boxes.W_Float64Box
1782 ComponentType = Float64
1783
1784 if boxes.long_double_size == 8:
1785 class FloatLong(Float, BaseType):
1786 T = rffi.DOUBLE
1787 num = NPY.LONGDOUBLE
1788 kind = NPY.FLOATINGLTR
1789 char = NPY.LONGDOUBLELTR
1790 BoxType = boxes.W_FloatLongBox
1791 format_code = "d"
1792
1793 class ComplexLong(ComplexFloating, BaseType):
1794 T = rffi.DOUBLE
1795 num = NPY.CLONGDOUBLE
1796 kind = NPY.COMPLEXLTR
1797 char = NPY.CLONGDOUBLELTR
1798 BoxType = boxes.W_ComplexLongBox
1799 ComponentBoxType = boxes.W_FloatLongBox
1800 ComponentType = FloatLong
1801
1802 elif boxes.long_double_size in (12, 16):
1803 class FloatLong(Float, BaseType):
1804 T = rffi.LONGDOUBLE
1805 num = NPY.LONGDOUBLE
1806 kind = NPY.FLOATINGLTR
1807 char = NPY.LONGDOUBLELTR
1808 BoxType = boxes.W_FloatLongBox
1809
1810 def runpack_str(self, space, s, native):
1811 assert len(s) == boxes.long_double_size
1812 fval = self.box(unpack_float80(s, native_is_bigendian))
1813 if not native:
1814 fval = self.byteswap(fval)
1815 return fval
1816
1817 def byteswap(self, w_v):
1818 value = self.unbox(w_v)
1819 result = StringBuilder(10)
1820 pack_float80(result, value, 10, not native_is_bigendian)
1821 return self.box(unpack_float80(result.build(), native_is_bigendian))
1822
1823 class ComplexLong(ComplexFloating, BaseType):
1824 T = rffi.LONGDOUBLE
1825 num = NPY.CLONGDOUBLE
1826 kind = NPY.COMPLEXLTR
1827 char = NPY.CLONGDOUBLELTR
1828 BoxType = boxes.W_ComplexLongBox
1829 ComponentBoxType = boxes.W_FloatLongBox
1830 ComponentType = FloatLong
1831
1832 _all_objs_for_tests = [] # for tests
1833
1834 class ObjectType(Primitive, BaseType):
1835 T = lltype.Signed
1836 num = NPY.OBJECT
1837 kind = NPY.OBJECTLTR
1838 char = NPY.OBJECTLTR
1839 BoxType = boxes.W_ObjectBox
1840
1841 def get_element_size(self):
1842 return rffi.sizeof(lltype.Signed)
1843
1844 def coerce(self, space, dtype, w_item):
1845 if isinstance(w_item, boxes.W_ObjectBox):
1846 return w_item
1847 return boxes.W_ObjectBox(w_item)
1848
1849 def coerce_subtype(self, space, w_subtype, w_item):
1850 # return the item itself
1851 return self.unbox(self.box(w_item))
1852
1853 def store(self, arr, i, offset, box, native):
1854 if arr.gcstruct is V_OBJECTSTORE:
1855 raise oefmt(self.space.w_NotImplementedError,
1856 "cannot store object in array with no gc hook")
1857 self._write(arr.storage, i, offset, self.unbox(box),
1858 arr.gcstruct)
1859
1860 def read(self, arr, i, offset, dtype):
1861 if arr.gcstruct is V_OBJECTSTORE and not arr.base():
1862 raise oefmt(self.space.w_NotImplementedError,
1863 "cannot read object from array with no gc hook")
1864 return self.box(self._read(arr.storage, i, offset))
1865
1866 def byteswap(self, w_v):
1867 return w_v
1868
1869 @jit.dont_look_inside
1870 def _write(self, storage, i, offset, w_obj, gcstruct):
1871 # no GC anywhere in this function!
1872 if we_are_translated():
1873 from rpython.rlib import rgc
1874 rgc.ll_writebarrier(gcstruct)
1875 value = rffi.cast(lltype.Signed, cast_instance_to_gcref(w_obj))
1876 else:
1877 value = len(_all_objs_for_tests)
1878 _all_objs_for_tests.append(w_obj)
1879 raw_storage_setitem_unaligned(storage, i + offset, value)
1880
1881 @jit.dont_look_inside
1882 def _read(self, storage, i, offset, native=True):
1883 res = raw_storage_getitem_unaligned(self.T, storage, i + offset)
1884 if we_are_translated():
1885 gcref = rffi.cast(llmemory.GCREF, res)
1886 w_obj = cast_gcref_to_instance(W_Root, gcref)
1887 else:
1888 w_obj = _all_objs_for_tests[res]
1889 return w_obj
1890
1891 def fill(self, storage, width, native, box, start, stop, offset, gcstruct):
1892 value = self.unbox(box)
1893 for i in xrange(start, stop, width):
1894 self._write(storage, i, offset, value, gcstruct)
1895
1896 def unbox(self, box):
1897 if isinstance(box, self.BoxType):
1898 return box.w_obj
1899 else:
1900 raise oefmt(self.space.w_NotImplementedError,
1901 "object dtype cannot unbox %s", str(box))
1902
1903 @specialize.argtype(1)
1904 def box(self, w_obj):
1905 if isinstance(w_obj, W_Root):
1906 pass
1907 elif isinstance(w_obj, bool):
1908 w_obj = self.space.newbool(w_obj)
1909 elif isinstance(w_obj, int):
1910 w_obj = self.space.newint(w_obj)
1911 elif isinstance(w_obj, lltype.Number):
1912 w_obj = self.space.newint(w_obj)
1913 elif isinstance(w_obj, float):
1914 w_obj = self.space.newfloat(w_obj)
1915 elif w_obj is None:
1916 w_obj = self.space.w_None
1917 else:
1918 raise oefmt(self.space.w_NotImplementedError,
1919 "cannot create object array/scalar from lltype")
1920 return self.BoxType(w_obj)
1921
1922 @specialize.argtype(1, 2)
1923 def box_complex(self, real, imag):
1924 if isinstance(real, rffi.r_singlefloat):
1925 real = rffi.cast(rffi.DOUBLE, real)
1926 if isinstance(imag, rffi.r_singlefloat):
1927 imag = rffi.cast(rffi.DOUBLE, imag)
1928 w_obj = self.space.newcomplex(real, imag)
1929 return self.BoxType(w_obj)
1930
1931 def str_format(self, box, add_quotes=True):
1932 if not add_quotes:
1933 as_str = self.space.text_w(self.space.repr(self.unbox(box)))
1934 as_strl = len(as_str) - 1
1935 if as_strl>1 and as_str[0] == "'" and as_str[as_strl] == "'":
1936 as_str = as_str[1:as_strl]
1937 return as_str
1938 return self.space.text_w(self.space.repr(self.unbox(box)))
1939
1940 def runpack_str(self, space, s, native):
1941 raise oefmt(space.w_NotImplementedError,
1942 "fromstring not implemented for object type")
1943
1944 def to_builtin_type(self, space, box):
1945 assert isinstance(box, self.BoxType)
1946 return box.w_obj
1947
1948 @staticmethod
1949 def for_computation(v):
1950 return v
1951
1952 @raw_binary_op
1953 def eq(self, v1, v2):
1954 return self.space.eq_w(v1, v2)
1955
1956 @simple_binary_op
1957 def max(self, v1, v2):
1958 if self.space.is_true(self.space.ge(v1, v2)):
1959 return v1
1960 return v2
1961
1962 @simple_binary_op
1963 def min(self, v1, v2):
1964 if self.space.is_true(self.space.le(v1, v2)):
1965 return v1
1966 return v2
1967
1968 @raw_binary_op
1969 def argmax(self, v1, v2):
1970 if self.space.is_true(self.space.ge(v1, v2)):
1971 return True
1972 return False
1973
1974 @raw_binary_op
1975 def argmin(self, v1, v2):
1976 if self.space.is_true(self.space.le(v1, v2)):
1977 return True
1978 return False
1979
1980 @raw_unary_op
1981 def bool(self,v):
1982 return self._obool(v)
1983
1984 def _obool(self, v):
1985 if self.space.is_true(v):
1986 return True
1987 return False
1988
1989 @raw_binary_op
1990 def logical_and(self, v1, v2):
1991 if self._obool(v1):
1992 return self.box(v2)
1993 return self.box(v1)
1994
1995 @raw_binary_op
1996 def logical_or(self, v1, v2):
1997 if self._obool(v1):
1998 return self.box(v1)
1999 return self.box(v2)
2000
2001 @raw_unary_op
2002 def logical_not(self, v):
2003 return not self._obool(v)
2004
2005 @raw_binary_op
2006 def logical_xor(self, v1, v2):
2007 a = self._obool(v1)
2008 b = self._obool(v2)
2009 return (not b and a) or (not a and b)
2010
2011 @simple_binary_op
2012 def bitwise_and(self, v1, v2):
2013 return self.space.and_(v1, v2)
2014
2015 @simple_binary_op
2016 def bitwise_or(self, v1, v2):
2017 return self.space.or_(v1, v2)
2018
2019 @simple_binary_op
2020 def bitwise_xor(self, v1, v2):
2021 return self.space.xor(v1, v2)
2022
2023 @simple_binary_op
2024 def pow(self, v1, v2):
2025 return self.space.pow(v1, v2, self.space.newint(1))
2026
2027 @simple_unary_op
2028 def reciprocal(self, v1):
2029 return self.space.div(self.space.newfloat(1.0), v1)
2030
2031 @simple_unary_op
2032 def sign(self, v):
2033 zero = self.space.newint(0)
2034 one = self.space.newint(1)
2035 m_one = self.space.newint(-1)
2036 if self.space.is_true(self.space.gt(v, zero)):
2037 return one
2038 elif self.space.is_true(self.space.lt(v, zero)):
2039 return m_one
2040 else:
2041 return zero
2042
2043 @simple_unary_op
2044 def real(self, v):
2045 return v
2046
2047 @simple_unary_op
2048 def imag(self, v):
2049 return 0
2050
2051 @simple_unary_op
2052 def square(self, v):
2053 return self.space.mul(v, v)
2054
2055 @raw_binary_op
2056 def le(self, v1, v2):
2057 return self.space.bool_w(self.space.le(v1, v2))
2058
2059 @raw_binary_op
2060 def ge(self, v1, v2):
2061 return self.space.bool_w(self.space.ge(v1, v2))
2062
2063 @raw_binary_op
2064 def lt(self, v1, v2):
2065 return self.space.bool_w(self.space.lt(v1, v2))
2066
2067 @raw_binary_op
2068 def gt(self, v1, v2):
2069 return self.space.bool_w(self.space.gt(v1, v2))
2070
2071 @raw_binary_op
2072 def ne(self, v1, v2):
2073 return self.space.bool_w(self.space.ne(v1, v2))
2074
2075 def add_attributeerr_op(cls, op):
2076 def func(self, *args):
2077 raise oefmt(self.space.w_AttributeError,
2078 "%s", op)
2079 func.__name__ = 'object_' + op
2080 setattr(cls, op, func)
2081
2082 def add_unsupported_op(cls, op):
2083 def func(self, *args):
2084 raise oefmt(self.space.w_TypeError,
2085 "ufunc '%s' not supported for input types", op)
2086 func.__name__ = 'object_' + op
2087 setattr(cls, op, func)
2088
2089 def add_unary_op(cls, op, method):
2090 @simple_unary_op
2091 def func(self, w_v):
2092 space = self.space
2093 w_impl = space.lookup(w_v, method)
2094 if w_impl is None:
2095 raise oefmt(space.w_AttributeError, 'unknown op "%s" on object' % op)
2096 return space.get_and_call_function(w_impl, w_v)
2097 func.__name__ = 'object_' + op
2098 setattr(cls, op, func)
2099
2100 def add_space_unary_op(cls, op):
2101 @simple_unary_op
2102 def func(self, v):
2103 return getattr(self.space, op)(v)
2104 func.__name__ = 'object_' + op
2105 setattr(cls, op, func)
2106
2107 def add_space_binary_op(cls, op):
2108 @simple_binary_op
2109 def func(self, v1, v2):
2110 return getattr(self.space, op)(v1, v2)
2111 func.__name__ = 'object_' + op
2112 setattr(cls, op, func)
2113
2114 for op in ('copysign', 'isfinite', 'isinf', 'isnan', 'logaddexp', 'logaddexp2',
2115 'signbit'):
2116 add_unsupported_op(ObjectType, op)
2117 for op in ('arctan2', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan',
2118 'arctanh', 'ceil', 'floor', 'cos', 'sin', 'tan', 'cosh', 'sinh',
2119 'tanh', 'radians', 'degrees', 'exp','exp2', 'expm1', 'fabs',
2120 'log', 'log10', 'log1p', 'log2', 'sqrt', 'trunc'):
2121 add_attributeerr_op(ObjectType, op)
2122 for op in ('abs', 'neg', 'pos', 'invert'):
2123 add_space_unary_op(ObjectType, op)
2124 for op, method in (('conj', 'descr_conjugate'), ('rint', 'descr_rint')):
2125 add_unary_op(ObjectType, op, method)
2126 for op in ('add', 'floordiv', 'div', 'mod', 'mul', 'sub', 'lshift', 'rshift'):
2127 add_space_binary_op(ObjectType, op)
2128
2129 ObjectType.fmax = ObjectType.max
2130 ObjectType.fmin = ObjectType.min
2131 ObjectType.fmod = ObjectType.mod
2132
2133 class FlexibleType(BaseType):
2134 def get_element_size(self):
2135 return rffi.sizeof(self.T)
2136
2137 def to_str(self, item):
2138 return item.raw_str()
2139
2140 def str_unary_op(func):
2141 specialize.argtype(1)(func)
2142 @functools.wraps(func)
2143 def dispatcher(self, v1):
2144 return func(self, self.to_str(v1))
2145 return dispatcher
2146
2147 def str_binary_op(func):
2148 specialize.argtype(1, 2)(func)
2149 @functools.wraps(func)
2150 def dispatcher(self, v1, v2):
2151 return func(self,
2152 self.to_str(v1),
2153 self.to_str(v2)
2154 )
2155 return dispatcher
2156
2157 class StringType(FlexibleType):
2158 T = lltype.Char
2159 num = NPY.STRING
2160 kind = NPY.STRINGLTR
2161 char = NPY.STRINGLTR
2162
2163 @jit.unroll_safe
2164 def coerce(self, space, dtype, w_item):
2165 if isinstance(w_item, boxes.W_StringBox):
2166 return w_item
2167 if w_item is None:
2168 w_item = space.newbytes('')
2169 arg = space.text_w(space.str(w_item))
2170 arr = VoidBoxStorage(dtype.elsize, dtype)
2171 with arr as storage:
2172 j = min(len(arg), dtype.elsize)
2173 for i in range(j):
2174 storage[i] = arg[i]
2175 for j in range(j, dtype.elsize):
2176 storage[j] = '\x00'
2177 return boxes.W_StringBox(arr, 0, arr.dtype)
2178
2179 def store(self, arr, i, offset, box, native):
2180 assert isinstance(box, boxes.W_StringBox)
2181 size = min(arr.dtype.elsize - offset, box.arr.size - box.ofs)
2182 with arr as storage:
2183 return self._store(storage, i, offset, box, size)
2184
2185 @jit.unroll_safe
2186 def _store(self, storage, i, offset, box, size):
2187 assert isinstance(box, boxes.W_StringBox)
2188 with box.arr as box_storage:
2189 for k in range(size):
2190 storage[k + offset + i] = box_storage[k + box.ofs]
2191
2192 def read(self, arr, i, offset, dtype):
2193 return boxes.W_StringBox(arr, i + offset, dtype)
2194
2195 def str_format(self, item, add_quotes=True):
2196 builder = StringBuilder()
2197 if add_quotes:
2198 builder.append("'")
2199 builder.append(self.to_str(item))
2200 if add_quotes:
2201 builder.append("'")
2202 return builder.build()
2203
2204 # XXX move the rest of this to base class when UnicodeType is supported
2205 def to_builtin_type(self, space, box):
2206 return space.newbytes(self.to_str(box))
2207
2208 @str_binary_op
2209 def eq(self, v1, v2):
2210 return v1 == v2
2211
2212 @str_binary_op
2213 def ne(self, v1, v2):
2214 return v1 != v2
2215
2216 @str_binary_op
2217 def lt(self, v1, v2):
2218 return v1 < v2
2219
2220 @str_binary_op
2221 def le(self, v1, v2):
2222 return v1 <= v2
2223
2224 @str_binary_op
2225 def gt(self, v1, v2):
2226 return v1 > v2
2227
2228 @str_binary_op
2229 def ge(self, v1, v2):
2230 return v1 >= v2
2231
2232 @str_binary_op
2233 def logical_and(self, v1, v2):
2234 if bool(v1) and bool(v2):
2235 return Bool._True
2236 return Bool._False
2237
2238 @str_binary_op
2239 def logical_or(self, v1, v2):
2240 if bool(v1) or bool(v2):
2241 return Bool._True
2242 return Bool._False
2243
2244 @str_unary_op
2245 def logical_not(self, v):
2246 return not bool(v)
2247
2248 @str_binary_op
2249 def logical_xor(self, v1, v2):
2250 a = bool(v1)
2251 b = bool(v2)
2252 return (not b and a) or (not a and b)
2253
2254 def bool(self, v):
2255 return bool(self.to_str(v))
2256
2257 def fill(self, storage, width, native, box, start, stop, offset, gcstruct):
2258 for i in xrange(start, stop, width):
2259 self._store(storage, i, offset, box, width)
2260
2261 class UnicodeType(FlexibleType):
2262 T = lltype.UniChar
2263 num = NPY.UNICODE
2264 kind = NPY.UNICODELTR
2265 char = NPY.UNICODELTR
2266
2267 def get_element_size(self):
2268 return 4 # always UTF-32
2269
2270 @jit.unroll_safe
2271 def coerce(self, space, dtype, w_item):
2272 if isinstance(w_item, boxes.W_UnicodeBox):
2273 return w_item
2274 if isinstance(w_item, boxes.W_ObjectBox):
2275 value = space.utf8_w(space.unicode_from_object(w_item.w_obj))
2276 else:
2277 value = space.utf8_w(space.unicode_from_object(w_item))
2278 return boxes.W_UnicodeBox(value)
2279
2280 def convert_utf8_to_unichar_list(self, utf8):
2281 l = []
2282 for ch in Utf8StringIterator(utf8):
2283 l.append(unichr(ch))
2284 return l
2285
2286 def store(self, arr, i, offset, box, native):
2287 assert isinstance(box, boxes.W_UnicodeBox)
2288 with arr as storage:
2289 self._store(storage, i, offset, box, arr.dtype.elsize)
2290
2291 @jit.unroll_safe
2292 def _store(self, storage, i, offset, box, width):
2293 v = self.convert_utf8_to_unichar_list(box._value)
2294 size = min(width // 4, len(v))
2295 for k in range(size):
2296 index = i + offset + 4*k
2297 data = rffi.cast(Int32.T, ord(v[k]))
2298 raw_storage_setitem_unaligned(storage, index, data)
2299 # zero out the remaining memory
2300 for index in range(size * 4 + i + offset, width):
2301 data = rffi.cast(Int8.T, 0)
2302 raw_storage_setitem_unaligned(storage, index, data)
2303
2304 def read(self, arr, i, offset, dtype):
2305 if dtype is None:
2306 dtype = arr.dtype
2307 size = dtype.elsize // 4
2308 builder = Utf8StringBuilder(size)
2309 with arr as storage:
2310 for k in range(size):
2311 index = i + offset + 4*k
2312 codepoint = rffi.cast(lltype.Signed,
2313 raw_storage_getitem_unaligned(
2314 Int32.T, arr.storage, index))
2315 if codepoint == 0:
2316 break
2317 builder.append_code(codepoint)
2318 return boxes.W_UnicodeBox(builder.build())
2319
2320 def str_format(self, item, add_quotes=True):
2321 assert isinstance(item, boxes.W_UnicodeBox)
2322 if add_quotes:
2323 w_unicode = self.to_builtin_type(self.space, item)
2324 return self.space.text_w(self.space.repr(w_unicode))
2325 else:
2326 # Same as W_UnicodeBox.descr_repr() but without quotes and prefix
2327 from rpython.rlib.runicode import unicode_encode_unicode_escape
2328 return unicode_encode_unicode_escape(item._value,
2329 len(item._value), 'strict')
2330
2331 def to_builtin_type(self, space, box):
2332 assert isinstance(box, boxes.W_UnicodeBox)
2333 return space.newutf8(box._value, codepoints_in_utf8(box._value))
2334
2335 def eq(self, v1, v2):
2336 assert isinstance(v1, boxes.W_UnicodeBox)
2337 assert isinstance(v2, boxes.W_UnicodeBox)
2338 return v1._value == v2._value
2339
2340 def ne(self, v1, v2):
2341 assert isinstance(v1, boxes.W_UnicodeBox)
2342 assert isinstance(v2, boxes.W_UnicodeBox)
2343 return v1._value != v2._value
2344
2345 def lt(self, v1, v2):
2346 assert isinstance(v1, boxes.W_UnicodeBox)
2347 assert isinstance(v2, boxes.W_UnicodeBox)
2348 return v1._value < v2._value
2349
2350 def le(self, v1, v2):
2351 assert isinstance(v1, boxes.W_UnicodeBox)
2352 assert isinstance(v2, boxes.W_UnicodeBox)
2353 return v1._value <= v2._value
2354
2355 def gt(self, v1, v2):
2356 assert isinstance(v1, boxes.W_UnicodeBox)
2357 assert isinstance(v2, boxes.W_UnicodeBox)
2358 return v1._value > v2._value
2359
2360 def ge(self, v1, v2):
2361 assert isinstance(v1, boxes.W_UnicodeBox)
2362 assert isinstance(v2, boxes.W_UnicodeBox)
2363 return v1._value >= v2._value
2364
2365 def logical_and(self, v1, v2):
2366 assert isinstance(v1, boxes.W_UnicodeBox)
2367 assert isinstance(v2, boxes.W_UnicodeBox)
2368 if bool(v1) and bool(v2):
2369 return Bool._True
2370 return Bool._False
2371
2372 def logical_or(self, v1, v2):
2373 assert isinstance(v1, boxes.W_UnicodeBox)
2374 assert isinstance(v2, boxes.W_UnicodeBox)
2375 if bool(v1) or bool(v2):
2376 return Bool._True
2377 return Bool._False
2378
2379 def logical_not(self, v):
2380 assert isinstance(v, boxes.W_UnicodeBox)
2381 return not bool(v)
2382
2383 def logical_xor(self, v1, v2):
2384 assert isinstance(v1, boxes.W_UnicodeBox)
2385 assert isinstance(v2, boxes.W_UnicodeBox)
2386 a = bool(v1)
2387 b = bool(v2)
2388 return (not b and a) or (not a and b)
2389
2390 def bool(self, v):
2391 assert isinstance(v, boxes.W_UnicodeBox)
2392 return bool(v._value)
2393
2394 def fill(self, storage, width, native, box, start, stop, offset, gcstruct):
2395 assert isinstance(box, boxes.W_UnicodeBox)
2396 for i in xrange(start, stop, width):
2397 self._store(storage, i, offset, box, width)
2398
2399
2400 class VoidType(FlexibleType):
2401 T = lltype.Char
2402 num = NPY.VOID
2403 kind = NPY.VOIDLTR
2404 char = NPY.VOIDLTR
2405
2406 def _coerce(self, space, arr, ofs, dtype, w_items, shape):
2407 # TODO: Make sure the shape and the array match
2408 from pypy.module.micronumpy.descriptor import W_Dtype
2409 if w_items is None:
2410 items_w = [None] * shape[0]
2411 elif support.issequence_w(space, w_items):
2412 items_w = space.fixedview(w_items)
2413 else:
2414 items_w = [w_items] * shape[0]
2415 subdtype = dtype.subdtype
2416 assert isinstance(subdtype, W_Dtype)
2417 itemtype = subdtype.itemtype
2418 if len(shape) <= 1:
2419 for i in range(len(items_w)):
2420 w_box = subdtype.coerce(space, items_w[i])
2421 subdtype.store(arr, 0, ofs, w_box)
2422 ofs += itemtype.get_element_size()
2423 else:
2424 for w_item in items_w:
2425 size = 1
2426 for dimension in shape[1:]:
2427 size *= dimension
2428 size *= itemtype.get_element_size()
2429 self._coerce(space, arr, ofs, dtype, w_item, shape[1:])
2430 ofs += size
2431
2432 def coerce(self, space, dtype, w_items):
2433 if dtype.is_record():
2434 # the dtype is a union of a void and a record,
2435 return record_coerce(self, space, dtype, w_items)
2436 arr = VoidBoxStorage(dtype.elsize, dtype)
2437 self._coerce(space, arr, 0, dtype, w_items, dtype.shape)
2438 return boxes.W_VoidBox(arr, 0, dtype)
2439
2440 @jit.unroll_safe
2441 def store(self, arr, i, offset, box, native):
2442 assert isinstance(box, boxes.W_VoidBox)
2443 assert box.dtype is box.arr.dtype
2444 with arr as arr_storage, box.arr as box_storage:
2445 for k in range(box.arr.dtype.elsize):
2446 arr_storage[i + k + offset] = box_storage[k + box.ofs]
2447
2448 def readarray(self, arr, i, offset, dtype=None):
2449 from pypy.module.micronumpy.base import W_NDimArray
2450 if dtype is None:
2451 dtype = arr.dtype
2452 strides, backstrides = calc_strides(dtype.shape, dtype.subdtype,
2453 arr.order)
2454 implementation = SliceArray(i + offset, strides, backstrides,
2455 dtype.shape, arr, W_NDimArray(arr),
2456 dtype.subdtype)
2457 return W_NDimArray(implementation)
2458
2459 def read(self, arr, i, offset, dtype):
2460 return boxes.W_VoidBox(arr, i + offset, dtype)
2461
2462 @jit.unroll_safe
2463 def str_format(self, box, add_quotes=True):
2464 assert isinstance(box, boxes.W_VoidBox)
2465 arr = self.readarray(box.arr, box.ofs, 0, box.dtype)
2466 return arr.dump_data(prefix='', suffix='')
2467
2468 def to_builtin_type(self, space, item):
2469 ''' From the documentation of ndarray.item():
2470 "Void arrays return a buffer object for item(),
2471 unless fields are defined, in which case a tuple is returned."
2472 '''
2473 assert isinstance(item, boxes.W_VoidBox)
2474 dt = item.arr.dtype
2475 ret_unwrapped = []
2476 for name in dt.names:
2477 ofs, dtype = dt.fields[name[0]]
2478 # XXX: code duplication with W_VoidBox.descr_getitem()
2479 if isinstance(dtype.itemtype, VoidType):
2480 read_val = dtype.itemtype.readarray(item.arr, ofs, 0, dtype)
2481 else:
2482 read_val = dtype.read(item.arr, ofs, 0)
2483 if isinstance (read_val, boxes.W_StringBox):
2484 # StringType returns a str
2485 read_val = space.newbytes(dtype.itemtype.to_str(read_val))
2486 ret_unwrapped = ret_unwrapped + [read_val,]
2487 if len(ret_unwrapped) == 0:
2488 raise oefmt(space.w_NotImplementedError,
2489 "item() for Void aray with no fields not implemented")
2490 return space.newtuple(ret_unwrapped)
2491
2492 class CharType(StringType):
2493 char = NPY.CHARLTR
2494
2495 def record_coerce(typ, space, dtype, w_item):
2496 from pypy.module.micronumpy.base import W_NDimArray
2497 if isinstance(w_item, boxes.W_VoidBox):
2498 if dtype == w_item.dtype:
2499 return w_item
2500 else:
2501 # match up the field names
2502 items_w = [None] * len(dtype.names)
2503 for i in range(len(dtype.names)):
2504 name = dtype.names[i]
2505 if name in w_item.dtype.names:
2506 items_w[i] = w_item.descr_getitem(space, space.newtext(name[0]))
2507 elif w_item is not None:
2508 if space.isinstance_w(w_item, space.w_tuple):
2509 if len(dtype.names) != space.len_w(w_item):
2510 raise oefmt(space.w_ValueError,
2511 "size of tuple must match number of fields.")
2512 items_w = space.fixedview(w_item)
2513 elif isinstance(w_item, W_NDimArray) and w_item.is_scalar():
2514 items_w = space.fixedview(w_item.get_scalar_value())
2515 elif space.isinstance_w(w_item, space.w_list):
2516 raise oefmt(space.w_TypeError,
2517 "expected a readable buffer object")
2518 else:
2519 # XXX support initializing from readable buffers
2520 items_w = [w_item] * len(dtype.names)
2521 else:
2522 items_w = [None] * len(dtype.fields)
2523 arr = VoidBoxStorage(dtype.elsize, dtype)
2524 for i in range(len(dtype.names)):
2525 ofs, subdtype = dtype.fields[dtype.names[i][0]]
2526 try:
2527 w_box = subdtype.coerce(space, items_w[i])
2528 except IndexError:
2529 w_box = subdtype.coerce(space, None)
2530 subdtype.store(arr, 0, ofs, w_box)
2531 return boxes.W_VoidBox(arr, 0, dtype)
2532
2533 class RecordType(FlexibleType):
2534 T = lltype.Char
2535 num = NPY.VOID
2536 kind = NPY.VOIDLTR
2537 char = NPY.VOIDLTR
2538
2539 def read(self, arr, i, offset, dtype):
2540 return boxes.W_VoidBox(arr, i + offset, dtype)
2541
2542 @jit.unroll_safe
2543 def coerce(self, space, dtype, w_item):
2544 return record_coerce(self, space, dtype, w_item)
2545
2546 def runpack_str(self, space, s, native):
2547 raise oefmt(space.w_NotImplementedError,
2548 "fromstring not implemented for record types")
2549
2550 def store(self, arr, i, offset, box, native):
2551 assert isinstance(box, boxes.W_VoidBox)
2552 with arr as storage:
2553 self._store(storage, i, offset, box, box.dtype.elsize)
2554
2555 @jit.unroll_safe
2556 def _store(self, storage, i, ofs, box, size):
2557 with box.arr as box_storage:
2558 for k in range(size):
2559 storage[k + i + ofs] = box_storage[k + box.ofs]
2560
2561 def fill(self, storage, width, native, box, start, stop, offset, gcstruct):
2562 assert isinstance(box, boxes.W_VoidBox)
2563 assert width == box.dtype.elsize
2564 for i in xrange(start, stop, width):
2565 self._store(storage, i, offset, box, width)
2566
2567 def byteswap(self, w_v):
2568 # XXX implement
2569 return w_v
2570
2571 def to_builtin_type(self, space, box):
2572 assert isinstance(box, boxes.W_VoidBox)
2573 items = []
2574 dtype = box.dtype
2575 for name in dtype.names:
2576 ofs, subdtype = dtype.fields[name[0]]
2577 subbox = subdtype.read(box.arr, box.ofs, ofs)
2578 items.append(subdtype.itemtype.to_builtin_type(space, subbox))
2579 return space.newtuple(items)
2580
2581 @jit.unroll_safe
2582 def str_format(self, box, add_quotes=True):
2583 assert isinstance(box, boxes.W_VoidBox)
2584 pieces = ["("]
2585 first = True
2586 for name in box.dtype.names:
2587 ofs, subdtype = box.dtype.fields[name[0]]
2588 if first:
2589 first = False
2590 else:
2591 pieces.append(", ")
2592 val = subdtype.read(box.arr, box.ofs, ofs)
2593 tp = subdtype.itemtype
2594 pieces.append(tp.str_format(val, add_quotes=add_quotes))
2595 pieces.append(")")
2596 return "".join(pieces)
2597
2598 def eq(self, v1, v2):
2599 assert isinstance(v1, boxes.W_VoidBox)
2600 assert isinstance(v2, boxes.W_VoidBox)
2601 s1 = v1.dtype.elsize
2602 s2 = v2.dtype.elsize
2603 assert s1 == s2
2604 with v1.arr as v1_storage, v2.arr as v2_storage:
2605 for i in range(s1):
2606 if v1_storage[v1.ofs + i] != v2_storage[v2.ofs + i]:
2607 return False
2608 return True
2609
2610 def ne(self, v1, v2):
2611 return not self.eq(v1, v2)
2612
2613 for tp in [Int32, Int64]:
2614 if tp.T == lltype.Signed:
2615 IntP = tp
2616 break
2617 for tp in [UInt32, UInt64]:
2618 if tp.T == lltype.Unsigned:
2619 UIntP = tp
2620 break
2621 del tp
2622
2623 all_float_types = []
2624 float_types = []
2625 all_int_types = []
2626 int_types = []
2627 all_complex_types = []
2628 complex_types = []
2629
2630 _REQ_STRLEN = [0, 3, 5, 10, 10, 20, 20, 20, 20] # data for can_cast_to()
2631 def _setup():
2632 # compute alignment
2633 dummyspace = ObjSpace()
2634 for tp in globals().values():
2635 if isinstance(tp, type) and hasattr(tp, 'T'):
2636 tp.alignment = widen(clibffi.cast_type_to_ffitype(tp.T).c_alignment)
2637 if issubclass(tp, Float):
2638 all_float_types.append((tp, 'float'))
2639 float_types.append(tp)
2640 if issubclass(tp, Integer):
2641 all_int_types.append((tp, 'int'))
2642 int_types.append(tp)
2643 elsize = tp(dummyspace).get_element_size()
2644 tp.strlen = _REQ_STRLEN[elsize]
2645 if tp.kind == NPY.SIGNEDLTR:
2646 tp.strlen += 1
2647 if issubclass(tp, ComplexFloating):
2648 all_complex_types.append((tp, 'complex'))
2649 complex_types.append(tp)
2650 for l in [float_types, int_types, complex_types]:
2651 l.sort(key=lambda tp: tp.num)
2652 _setup()
2653 del _setup
2654
2655 number_types = int_types + float_types + complex_types
2656 all_types = [Bool] + number_types + [ObjectType, StringType, UnicodeType, VoidType]
2657
2658
2659
2660 _int_types = [(Int8, UInt8), (Int16, UInt16), (Int32, UInt32),
2661 (Int64, UInt64), (Long, ULong)]
2662 for Int_t, UInt_t in _int_types:
2663 Int_t.Unsigned = UInt_t
2664 UInt_t.Signed = Int_t
2665 size = rffi.sizeof(Int_t.T)
2666 Int_t.min_value = rffi.cast(Int_t.T, -1) << (8*size - 1)
2667 Int_t.max_value = ~Int_t.min_value
2668 UInt_t.max_value = ~rffi.cast(UInt_t.T, 0)
2669
2670
2671 signed_types = [Int8, Int16, Int32, Int64, Long]
2672
2673 def make_integer_min_dtype(Int_t, UInt_t):
2674 smaller_types = [tp for tp in signed_types
2675 if rffi.sizeof(tp.T) < rffi.sizeof(Int_t.T)]
2676 smaller_types = unrolling_iterable(
2677 [(tp, tp.Unsigned) for tp in smaller_types])
2678 def min_dtype(self):
2679 value = rffi.cast(UInt64.T, self.value)
2680 for Small, USmall in smaller_types:
2681 signed_max = rffi.cast(UInt64.T, Small.max_value)
2682 unsigned_max = rffi.cast(UInt64.T, USmall.max_value)
2683 if value <= unsigned_max:
2684 if value <= signed_max:
2685 return Small.num, USmall.num
2686 else:
2687 return USmall.num, USmall.num
2688 if value <= rffi.cast(UInt64.T, Int_t.max_value):
2689 return Int_t.num, UInt_t.num
2690 else:
2691 return UInt_t.num, UInt_t.num
2692 UInt_t.BoxType.min_dtype = min_dtype
2693
2694 def min_dtype(self):
2695 value = rffi.cast(Int64.T, self.value)
2696 if value >= 0:
2697 for Small, USmall in smaller_types:
2698 signed_max = rffi.cast(Int64.T, Small.max_value)
2699 unsigned_max = rffi.cast(Int64.T, USmall.max_value)
2700 if value <= unsigned_max:
2701 if value <= signed_max:
2702 return Small.num, USmall.num
2703 else:
2704 return USmall.num, USmall.num
2705 return Int_t.num, UInt_t.num
2706 else:
2707 for Small, USmall in smaller_types:
2708 signed_min = rffi.cast(Int64.T, Small.min_value)
2709 if value >= signed_min:
2710 return Small.num, Small.num
2711 return Int_t.num, Int_t.num
2712 Int_t.BoxType.min_dtype = min_dtype
2713
2714 for Int_t in signed_types:
2715 UInt_t = Int_t.Unsigned
2716 make_integer_min_dtype(Int_t, UInt_t)
2717
2718
2719 smaller_float_types = {
2720 Float16: [], Float32: [Float16], Float64: [Float16, Float32],
2721 FloatLong: [Float16, Float32, Float64]}
2722
2723 def make_float_min_dtype(Float_t):
2724 smaller_types = unrolling_iterable(smaller_float_types[Float_t])
2725 smallest_type = Float16
2726
2727 def min_dtype(self):
2728 value = float(self.value)
2729 if not rfloat.isfinite(value):
2730 tp = smallest_type
2731 else:
2732 for SmallFloat in smaller_types:
2733 if -SmallFloat.max_value < value < SmallFloat.max_value:
2734 tp = SmallFloat
2735 break
2736 else:
2737 tp = Float_t
2738 return tp.num, tp.num
2739 Float_t.BoxType.min_dtype = min_dtype
2740
2741 for Float_t in float_types:
2742 make_float_min_dtype(Float_t)
2743
2744 smaller_complex_types = {
2745 Complex64: [], Complex128: [Complex64],
2746 ComplexLong: [Complex64, Complex128]}
2747
2748 def make_complex_min_dtype(Complex_t):
2749 smaller_types = unrolling_iterable(smaller_complex_types[Complex_t])
2750
2751 def min_dtype(self):
2752 real, imag = float(self.real), float(self.imag)
2753 for CSmall in smaller_types:
2754 max_value = CSmall.ComponentType.max_value
2755
2756 if -max_value < real < max_value and -max_value < imag < max_value:
2757 tp = CSmall
2758 break
2759 else:
2760 tp = Complex_t
2761 return tp.num, tp.num
2762 Complex_t.BoxType.min_dtype = min_dtype
2763
2764 for Complex_t in complex_types:
2765 make_complex_min_dtype(Complex_t)
2766
2767 def min_dtype(self):
2768 return Bool.num, Bool.num
2769 Bool.BoxType.min_dtype = min_dtype