Commits

Philip Jenvey committed b396f95 Merge

merge default

  • Participants
  • Parent commits c17b5f2, 0138c06
  • Branches py3k

Comments (0)

Files changed (25)

File lib_pypy/numpypy/core/arrayprint.py

     formatdict = {'bool' : _boolFormatter,
                   'int' : IntegerFormat(data),
                   'float' : FloatFormat(data, precision, suppress_small),
-                  'longfloat' : LongFloatFormat(precision),
+                  'longfloat' : FloatFormat(data, precision, suppress_small),
                   'complexfloat' : ComplexFormat(data, precision,
                                                  suppress_small),
-                  'longcomplexfloat' : LongComplexFormat(precision),
+                  'longcomplexfloat' : ComplexFormat(data, precision,
+                                                     suppress_small),
                   'datetime' : DatetimeFormat(data),
                   'timedelta' : TimedeltaFormat(data),
                   'numpystr' : repr_format,

File lib_pypy/numpypy/core/numerictypes.py

                   ('int_', 'long'),
                   ('uint', 'ulong'),
                   ('cfloat', 'cdouble'),
+                  ('longfloat', 'longdouble'),
+                  ('clongfloat', 'clongdouble'),
+                  ('longcomplex', 'clongdouble'),
                   ('bool_', 'bool'),
                   ('unicode_', 'unicode'),
                   ]

File lib_pypy/numpypy/lib/__init__.py

 from .function_base import *
 from .shape_base import *
 from .twodim_base import *
+from .ufunclike import *
 from .utils import *
 
 __all__ = ['math']
 __all__ += function_base.__all__
 __all__ += shape_base.__all__
 __all__ += twodim_base.__all__
+__all__ += ufunclike.__all__
 __all__ += utils.__all__

File lib_pypy/numpypy/lib/ufunclike.py

+"""
+Module of functions that are like ufuncs in acting on arrays and optionally
+storing results in an output array.
+
+"""
+from __future__ import division, absolute_import, print_function
+
+__all__ = ['fix', 'isneginf', 'isposinf']
+
+from ..core import numeric as nx
+
+def fix(x, y=None):
+    """
+    Round to nearest integer towards zero.
+
+    Round an array of floats element-wise to nearest integer towards zero.
+    The rounded values are returned as floats.
+
+    Parameters
+    ----------
+    x : array_like
+        An array of floats to be rounded
+    y : ndarray, optional
+        Output array
+
+    Returns
+    -------
+    out : ndarray of floats
+        The array of rounded numbers
+
+    See Also
+    --------
+    trunc, floor, ceil
+    around : Round to given number of decimals
+
+    Examples
+    --------
+    >>> np.fix(3.14)
+    3.0
+    >>> np.fix(3)
+    3.0
+    >>> np.fix([2.1, 2.9, -2.1, -2.9])
+    array([ 2.,  2., -2., -2.])
+
+    """
+    x = nx.asanyarray(x)
+    y1 = nx.floor(x)
+    y2 = nx.ceil(x)
+    if y is None:
+        y = nx.asanyarray(y1)
+    y[...] = nx.where(x >= 0, y1, y2)
+    return y
+
+def isposinf(x, y=None):
+    """
+    Test element-wise for positive infinity, return result as bool array.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    y : array_like, optional
+        A boolean array with the same shape as `x` to store the result.
+
+    Returns
+    -------
+    y : ndarray
+        A boolean array with the same dimensions as the input.
+        If second argument is not supplied then a boolean array is returned
+        with values True where the corresponding element of the input is
+        positive infinity and values False where the element of the input is
+        not positive infinity.
+
+        If a second argument is supplied the result is stored there. If the
+        type of that array is a numeric type the result is represented as zeros
+        and ones, if the type is boolean then as False and True.
+        The return value `y` is then a reference to that array.
+
+    See Also
+    --------
+    isinf, isneginf, isfinite, isnan
+
+    Notes
+    -----
+    Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+    (IEEE 754).
+
+    Errors result if the second argument is also supplied when `x` is a
+    scalar input, or if first and second arguments have different shapes.
+
+    Examples
+    --------
+    >>> np.isposinf(np.PINF)
+    array(True, dtype=bool)
+    >>> np.isposinf(np.inf)
+    array(True, dtype=bool)
+    >>> np.isposinf(np.NINF)
+    array(False, dtype=bool)
+    >>> np.isposinf([-np.inf, 0., np.inf])
+    array([False, False,  True], dtype=bool)
+
+    >>> x = np.array([-np.inf, 0., np.inf])
+    >>> y = np.array([2, 2, 2])
+    >>> np.isposinf(x, y)
+    array([0, 0, 1])
+    >>> y
+    array([0, 0, 1])
+
+    """
+    if y is None:
+        x = nx.asarray(x)
+        y = nx.empty(x.shape, dtype=nx.bool_)
+    nx.logical_and(nx.isinf(x), ~nx.signbit(x), y)
+    return y
+
+def isneginf(x, y=None):
+    """
+    Test element-wise for negative infinity, return result as bool array.
+
+    Parameters
+    ----------
+    x : array_like
+        The input array.
+    y : array_like, optional
+        A boolean array with the same shape and type as `x` to store the
+        result.
+
+    Returns
+    -------
+    y : ndarray
+        A boolean array with the same dimensions as the input.
+        If second argument is not supplied then a numpy boolean array is
+        returned with values True where the corresponding element of the
+        input is negative infinity and values False where the element of
+        the input is not negative infinity.
+
+        If a second argument is supplied the result is stored there. If the
+        type of that array is a numeric type the result is represented as
+        zeros and ones, if the type is boolean then as False and True. The
+        return value `y` is then a reference to that array.
+
+    See Also
+    --------
+    isinf, isposinf, isnan, isfinite
+
+    Notes
+    -----
+    Numpy uses the IEEE Standard for Binary Floating-Point for Arithmetic
+    (IEEE 754).
+
+    Errors result if the second argument is also supplied when x is a scalar
+    input, or if first and second arguments have different shapes.
+
+    Examples
+    --------
+    >>> np.isneginf(np.NINF)
+    array(True, dtype=bool)
+    >>> np.isneginf(np.inf)
+    array(False, dtype=bool)
+    >>> np.isneginf(np.PINF)
+    array(False, dtype=bool)
+    >>> np.isneginf([-np.inf, 0., np.inf])
+    array([ True, False, False], dtype=bool)
+
+    >>> x = np.array([-np.inf, 0., np.inf])
+    >>> y = np.array([2, 2, 2])
+    >>> np.isneginf(x, y)
+    array([1, 0, 0])
+    >>> y
+    array([1, 0, 0])
+
+    """
+    if y is None:
+        x = nx.asarray(x)
+        y = nx.empty(x.shape, dtype=nx.bool_)
+    nx.logical_and(nx.isinf(x), nx.signbit(x), y)
+    return y

File pypy/doc/whatsnew-head.rst

 .. branch: file-support-in-rpython
 make open() and friends rpython
 
-
+.. branch: incremental-gc
+Added the new incminimark GC which performs GC in incremental steps

File pypy/module/micronumpy/__init__.py

 from pypy.interpreter.mixedmodule import MixedModule
-from pypy.module.micronumpy.interp_boxes import long_double_size, ENABLED_LONG_DOUBLE
 
 
 class MultiArrayModule(MixedModule):
         ("less_equal", "less_equal"),
         ("maximum", "maximum"),
         ("minimum", "minimum"),
+        ("mod", "mod"),
         ("multiply", "multiply"),
         ("negative", "negative"),
         ("not_equal", "not_equal"),
         ('invert', 'invert'),
         ('isnan', 'isnan'),
         ('isinf', 'isinf'),
-        ('isneginf', 'isneginf'),
-        ('isposinf', 'isposinf'),
         ('isfinite', 'isfinite'),
         ('logical_and', 'logical_and'),
         ('logical_xor', 'logical_xor'),

File pypy/module/micronumpy/arrayimpl/concrete.py

             dtype =  self.dtype.float_type
             return SliceArray(self.start + dtype.get_size(), strides,
                     backstrides, self.get_shape(), self, orig_array, dtype=dtype)
-        if self.dtype.is_flexible_type():
-            # numpy returns self for self.imag
-            return SliceArray(self.start, strides, backstrides,
-                    self.get_shape(), self, orig_array)
         impl = NonWritableArray(self.get_shape(), self.dtype, self.order, strides,
                              backstrides)
-        impl.fill(self.dtype.box(0))
+        if not self.dtype.is_flexible_type():
+            impl.fill(self.dtype.box(0))
         return impl
 
     def set_imag(self, space, orig_array, w_value):
                 idx = self.get_shape()[i] + idx
             if idx < 0 or idx >= self.get_shape()[i]:
                 raise operationerrfmt(space.w_IndexError,
-                      "index (%d) out of range (0<=index<%d", i, self.get_shape()[i],
+                      "index %d is out of bounds for axis %d with size %d",
+                      idx, i, self.get_shape()[i],
                 )
             item += idx * strides[i]
         return item
                 idx = shape[i] + idx
             if idx < 0 or idx >= shape[i]:
                 raise operationerrfmt(space.w_IndexError,
-                      "index (%d) out of range (0<=index<%d", i, shape[i],
+                      "index %d is out of bounds for axis %d with size %d",
+                      idx, i, self.get_shape()[i],
                 )
             item += idx * strides[i]
         return item
 
 class NonWritableArray(ConcreteArray):
     def descr_setitem(self, space, orig_array, w_index, w_value):
-        raise OperationError(space.w_RuntimeError, space.wrap(
-            "array is not writable"))
+        raise OperationError(space.w_ValueError, space.wrap(
+            "assignment destination is read-only"))
 
 
 class SliceArray(BaseConcreteArray):

File pypy/module/micronumpy/constants.py

+from pypy.interpreter.error import OperationError
 
-MODE_WRAP, MODE_RAISE, MODE_CLIP = range(3)
+MODE_CLIP, MODE_WRAP, MODE_RAISE = range(3)
 
-MODES = {'wrap': MODE_WRAP, 'raise': MODE_RAISE, 'clip': MODE_CLIP}
+def clipmode_converter(space, w_mode):
+    if space.is_none(w_mode):
+        return MODE_RAISE
+    if space.isinstance_w(w_mode, space.w_str):
+        mode = space.str_w(w_mode)
+        if mode.startswith('C') or mode.startswith('c'):
+            return MODE_CLIP
+        if mode.startswith('W') or mode.startswith('w'):
+            return MODE_WRAP
+        if mode.startswith('R') or mode.startswith('r'):
+            return MODE_RAISE
+    elif space.isinstance_w(w_mode, space.w_int):
+        mode = space.int_w(w_mode)
+        if MODE_CLIP <= mode <= MODE_RAISE:
+            return mode
+    raise OperationError(space.w_TypeError,
+                         space.wrap("clipmode not understood"))

File pypy/module/micronumpy/interp_arrayops.py

-
 from pypy.module.micronumpy.base import convert_to_array, W_NDimArray
-from pypy.module.micronumpy import loop, interp_dtype, interp_ufuncs
+from pypy.module.micronumpy import loop, interp_dtype, interp_ufuncs, constants
 from pypy.module.micronumpy.iter import Chunk, Chunks
 from pypy.module.micronumpy.strides import shape_agreement,\
      shape_agreement_multiple
-from pypy.module.micronumpy.constants import MODES
+from pypy.module.micronumpy.constants import clipmode_converter
 from pypy.interpreter.error import OperationError, operationerrfmt
 from pypy.interpreter.gateway import unwrap_spec
 
 def count_nonzero(space, w_obj):
     return space.wrap(loop.count_all_true(convert_to_array(space, w_obj)))
 
-@unwrap_spec(mode=str)
-def choose(space, w_arr, w_choices, w_out, mode):
+def choose(space, w_arr, w_choices, w_out, w_mode):
     arr = convert_to_array(space, w_arr)
     choices = [convert_to_array(space, w_item) for w_item
                in space.listview(w_choices)]
     shape = shape_agreement_multiple(space, choices + [w_out])
     out = interp_dtype.dtype_agreement(space, choices, shape, w_out)
     dtype = out.get_dtype()
-    if mode not in MODES:
-        raise OperationError(space.w_ValueError,
-                             space.wrap("mode %s not known" % (mode,)))
-    loop.choose(space, arr, choices, shape, dtype, out, MODES[mode])
+    mode = clipmode_converter(space, w_mode)
+    loop.choose(space, arr, choices, shape, dtype, out, mode)
     return out
 
-
-@unwrap_spec(mode=str)
-def put(space, w_arr, w_indices, w_values, mode='raise'):
-    from pypy.module.micronumpy import constants
+def put(space, w_arr, w_indices, w_values, w_mode):
     from pypy.module.micronumpy.support import int_w
 
     arr = convert_to_array(space, w_arr)
+    mode = clipmode_converter(space, w_mode)
 
-    if mode not in constants.MODES:
-        raise OperationError(space.w_ValueError,
-                             space.wrap("mode %s not known" % (mode,)))
     if not w_indices:
         raise OperationError(space.w_ValueError,
                              space.wrap("indice list cannot be empty"))
         index = int_w(space, idx)
 
         if index < 0 or index >= arr.get_size():
-            if constants.MODES[mode] == constants.MODE_RAISE:
-                raise OperationError(space.w_ValueError, space.wrap(
-                    "invalid entry in choice array"))
-            elif constants.MODES[mode] == constants.MODE_WRAP:
+            if mode == constants.MODE_RAISE:
+                raise OperationError(space.w_IndexError, space.wrap(
+                    "index %d is out of bounds for axis 0 with size %d" % (index, arr.get_size())))
+            elif mode == constants.MODE_WRAP:
                 index = index % arr.get_size()
             else:
-                assert constants.MODES[mode] == constants.MODE_CLIP
+                assert mode == constants.MODE_CLIP
                 if index < 0:
                     index = 0
                 else:
 
         arr.setitem(space, [index], dtype.coerce(space, value))
 
-
 def diagonal(space, arr, offset, axis1, axis2):
     shape = arr.get_shape()
     shapelen = len(shape)

File pypy/module/micronumpy/interp_boxes.py

 MIXIN_32 = (long_typedef,) if LONG_BIT == 32 else ()
 MIXIN_64 = (long_typedef,) if LONG_BIT == 64 else ()
 
-# Is this the proper place for this?
-ENABLED_LONG_DOUBLE = False
-long_double_size = rffi.sizeof_c_type('long double', ignore_errors=True)
+#long_double_size = rffi.sizeof_c_type('long double', ignore_errors=True)
+#import os
+#if long_double_size == 8 and os.name == 'nt':
+#    # this is a lie, or maybe a wish, MS fakes longdouble math with double
+#    long_double_size = 12
 
-import os
-if long_double_size == 8 and os.name == 'nt':
-    # this is a lie, or maybe a wish, MS fakes longdouble math with double
-    long_double_size = 12
+# hardcode to 8 for now (simulate using normal double) until long double works
+long_double_size = 8
 
 
 def new_dtype_getter(name):
 
     def descr_any(self, space):
         value = space.is_true(self)
-        return space.wrap(W_BoolBox(value))
+        return self.get_dtype(space).box(value)
 
     def descr_all(self, space):
         value = space.is_true(self)
-        return space.wrap(W_BoolBox(value))
+        return self.get_dtype(space).box(value)
 
     def descr_ravel(self, space):
         from pypy.module.micronumpy.base import convert_to_array
     descr__new__, _get_dtype, descr_reduce = new_dtype_getter("complex128")
     _COMPONENTS_BOX = W_Float64Box
 
-if ENABLED_LONG_DOUBLE and long_double_size == 12:
-    class W_Float96Box(W_FloatingBox, PrimitiveBox):
-        descr__new__, _get_dtype, descr_reduce = new_dtype_getter("float96")
 
-    W_LongDoubleBox = W_Float96Box
+if long_double_size == 8:
+    W_FloatLongBox = W_Float64Box
+    W_ComplexLongBox = W_Complex128Box
 
-    class W_Complex192Box(ComplexBox, W_ComplexFloatingBox):
-        descr__new__, _get_dtype, descr_reduce = new_dtype_getter("complex192")
-        _COMPONENTS_BOX = W_Float96Box
+elif long_double_size in (12, 16):
+    class W_FloatLongBox(W_FloatingBox, PrimitiveBox):
+        descr__new__, _get_dtype, descr_reduce = new_dtype_getter("float%d" % (long_double_size * 8))
 
-    W_CLongDoubleBox = W_Complex192Box
-
-elif ENABLED_LONG_DOUBLE and long_double_size == 16:
-    class W_Float128Box(W_FloatingBox, PrimitiveBox):
-        descr__new__, _get_dtype, descr_reduce = new_dtype_getter("float128")
-    W_LongDoubleBox = W_Float128Box
-
-    class W_Complex256Box(ComplexBox, W_ComplexFloatingBox):
-        descr__new__, _get_dtype, descr_reduce = new_dtype_getter("complex256")
-        _COMPONENTS_BOX = W_Float128Box
-
-    W_CLongDoubleBox = W_Complex256Box
-
-elif ENABLED_LONG_DOUBLE:
-    W_LongDoubleBox = W_Float64Box
-    W_CLongDoubleBox = W_Complex64Box
+    class W_ComplexLongBox(ComplexBox, W_ComplexFloatingBox):
+        descr__new__, _get_dtype, descr_reduce = new_dtype_getter("complex%d" % (long_double_size * 16))
+        _COMPONENTS_BOX = W_FloatLongBox
 
 
 W_GenericBox.typedef = TypeDef("generic",
 
 W_Float16Box.typedef = TypeDef("float16", W_FloatingBox.typedef,
     __module__ = "numpypy",
-
     __new__ = interp2app(W_Float16Box.descr__new__.im_func),
     __reduce__ = interp2app(W_Float16Box.descr_reduce),
 )
 
 W_Float32Box.typedef = TypeDef("float32", W_FloatingBox.typedef,
     __module__ = "numpypy",
-
     __new__ = interp2app(W_Float32Box.descr__new__.im_func),
     __reduce__ = interp2app(W_Float32Box.descr_reduce),
 )
 
 W_Float64Box.typedef = TypeDef("float64", (W_FloatingBox.typedef, float_typedef),
     __module__ = "numpypy",
-
     __new__ = interp2app(W_Float64Box.descr__new__.im_func),
     __reduce__ = interp2app(W_Float64Box.descr_reduce),
 )
 
-if ENABLED_LONG_DOUBLE and long_double_size == 12:
-    W_Float96Box.typedef = TypeDef("float96", (W_FloatingBox.typedef),
+W_ComplexFloatingBox.typedef = TypeDef("complexfloating", W_InexactBox.typedef,
+    __module__ = "numpypy",
+)
+
+W_Complex64Box.typedef = TypeDef("complex64", (W_ComplexFloatingBox.typedef),
+    __module__ = "numpypy",
+    __new__ = interp2app(W_Complex64Box.descr__new__.im_func),
+    __reduce__ = interp2app(W_Complex64Box.descr_reduce),
+    real = GetSetProperty(W_ComplexFloatingBox .descr_get_real),
+    imag = GetSetProperty(W_ComplexFloatingBox.descr_get_imag),
+)
+
+W_Complex128Box.typedef = TypeDef("complex128", (W_ComplexFloatingBox.typedef, complex_typedef),
+    __module__ = "numpypy",
+    __new__ = interp2app(W_Complex128Box.descr__new__.im_func),
+    __reduce__ = interp2app(W_Complex128Box.descr_reduce),
+    real = GetSetProperty(W_ComplexFloatingBox.descr_get_real),
+    imag = GetSetProperty(W_ComplexFloatingBox.descr_get_imag),
+)
+
+if long_double_size in (12, 16):
+    W_FloatLongBox.typedef = TypeDef("float%d" % (long_double_size * 8), (W_FloatingBox.typedef),
         __module__ = "numpypy",
-        __reduce__ = interp2app(W_Float96Box.descr_reduce),
-
-        __new__ = interp2app(W_Float96Box.descr__new__.im_func),
+        __new__ = interp2app(W_FloatLongBox.descr__new__.im_func),
+        __reduce__ = interp2app(W_FloatLongBox.descr_reduce),
     )
 
-    W_Complex192Box.typedef = TypeDef("complex192", (W_ComplexFloatingBox.typedef, complex_typedef),
+    W_ComplexLongBox.typedef = TypeDef("complex%d" % (long_double_size * 16), (W_ComplexFloatingBox.typedef, complex_typedef),
         __module__ = "numpypy",
-        __new__ = interp2app(W_Complex192Box.descr__new__.im_func),
-        __reduce__ = interp2app(W_Complex192Box.descr_reduce),
-        real = GetSetProperty(W_ComplexFloatingBox.descr_get_real),
-        imag = GetSetProperty(W_ComplexFloatingBox.descr_get_imag),
-    )
-
-elif ENABLED_LONG_DOUBLE and long_double_size == 16:
-    W_Float128Box.typedef = TypeDef("float128", (W_FloatingBox.typedef),
-        __module__ = "numpypy",
-
-        __new__ = interp2app(W_Float128Box.descr__new__.im_func),
-        __reduce__ = interp2app(W_Float128Box.descr_reduce),
-    )
-
-    W_Complex256Box.typedef = TypeDef("complex256", (W_ComplexFloatingBox.typedef, complex_typedef),
-        __module__ = "numpypy",
-        __new__ = interp2app(W_Complex256Box.descr__new__.im_func),
-        __reduce__ = interp2app(W_Complex256Box.descr_reduce),
+        __new__ = interp2app(W_ComplexLongBox.descr__new__.im_func),
+        __reduce__ = interp2app(W_ComplexLongBox.descr_reduce),
         real = GetSetProperty(W_ComplexFloatingBox.descr_get_real),
         imag = GetSetProperty(W_ComplexFloatingBox.descr_get_imag),
     )
     __module__ = "numpypy",
     __new__ = interp2app(W_UnicodeBox.descr__new__unicode_box.im_func),
 )
-
-W_ComplexFloatingBox.typedef = TypeDef("complexfloating", W_InexactBox.typedef,
-    __module__ = "numpypy",
-)
-
-
-W_Complex128Box.typedef = TypeDef("complex128", (W_ComplexFloatingBox.typedef, complex_typedef),
-    __module__ = "numpypy",
-    __new__ = interp2app(W_Complex128Box.descr__new__.im_func),
-    __reduce__ = interp2app(W_Complex128Box.descr_reduce),
-    real = GetSetProperty(W_ComplexFloatingBox.descr_get_real),
-    imag = GetSetProperty(W_ComplexFloatingBox.descr_get_imag),
-)
-
-W_Complex64Box.typedef = TypeDef("complex64", (W_ComplexFloatingBox.typedef),
-    __module__ = "numpypy",
-    __new__ = interp2app(W_Complex64Box.descr__new__.im_func),
-    __reduce__ = interp2app(W_Complex64Box.descr_reduce),
-    real = GetSetProperty(W_ComplexFloatingBox .descr_get_real),
-    imag = GetSetProperty(W_ComplexFloatingBox.descr_get_imag),
-)

File pypy/module/micronumpy/interp_dtype.py

         builder_args = space.newtuple([space.wrap("%s%d" % (kind, elemsize)), space.wrap(0), space.wrap(1)])
 
         version = space.wrap(3)
-        order = space.wrap(byteorder_prefix if self.native else nonnative_byteorder_prefix)
         names = self.descr_get_names(space)
         values = self.descr_get_fields(space)
         if self.fields:
+            order = space.wrap('|')
             #TODO: Implement this when subarrays are implemented
             subdescr = space.w_None
-            #TODO: Change this when alignment is implemented :
             size = 0
             for key in self.fields:
                 dtype = self.fields[key][1]
                 assert isinstance(dtype, W_Dtype)
                 size += dtype.get_size()
             w_size = space.wrap(size)
+            #TODO: Change this when alignment is implemented
             alignment = space.wrap(1)
         else:
+            order = space.wrap(byteorder_prefix if self.native else nonnative_byteorder_prefix)
             subdescr = space.w_None
             w_size = space.wrap(-1)
             alignment = space.wrap(-1)
             char="I",
             w_box_type=space.gettypefor(interp_boxes.W_UInt32Box),
         )
-        if LONG_BIT == 32:
-            name = "int32"
-        elif LONG_BIT == 64:
-            name = "int64"
         self.w_longdtype = W_Dtype(
             types.Long(),
             num=7,
             kind=SIGNEDLTR,
-            name=name,
+            name="int%d" % LONG_BIT,
             char="l",
             w_box_type=space.gettypefor(interp_boxes.W_LongBox),
             alternate_constructors=[space.w_int,
             types.ULong(),
             num=8,
             kind=UNSIGNEDLTR,
-            name="u" + name,
+            name="uint%d" % LONG_BIT,
             char="L",
             w_box_type=space.gettypefor(interp_boxes.W_ULongBox),
             alternate_constructors=[ space.gettypefor(interp_boxes.W_UnsignedIntegerBox),
                                    ],
             aliases=["float", "double"],
         )
+        self.w_floatlongdtype = W_Dtype(
+            types.FloatLong(),
+            num=13,
+            kind=FLOATINGLTR,
+            name="float%d" % (interp_boxes.long_double_size * 8),
+            char="g",
+            w_box_type=space.gettypefor(interp_boxes.W_FloatLongBox),
+            aliases=["longdouble", "longfloat"],
+        )
         self.w_complex64dtype = W_ComplexDtype(
             types.Complex64(),
             num=14,
             aliases=["complex"],
             float_type = self.w_float64dtype,
         )
-        if interp_boxes.ENABLED_LONG_DOUBLE and interp_boxes.long_double_size == 12:
-            self.w_float96dtype = W_Dtype(
-                types.Float96(),
-                num=13,
-                kind=FLOATINGLTR,
-                name="float96",
-                char="g",
-                w_box_type=space.gettypefor(interp_boxes.W_Float96Box),
-                aliases=["longdouble", "longfloat"],
-            )
-            self.w_complex192dtype = W_ComplexDtype(
-                types.Complex192(),
-                num=16,
-                kind=COMPLEXLTR,
-                name="complex192",
-                char="G",
-                w_box_type = space.gettypefor(interp_boxes.W_Complex192Box),
-                alternate_constructors=[space.w_complex],
-                aliases=["clongdouble", "clongfloat"],
-                float_type = self.w_float96dtype,
-            )
-            self.w_longdouble = self.w_float96dtype
-            self.w_clongdouble = self.w_complex192dtype
-        elif interp_boxes.ENABLED_LONG_DOUBLE and interp_boxes.long_double_size == 16:
-            self.w_float128dtype = W_Dtype(
-                types.Float128(),
-                num=13,
-                kind=FLOATINGLTR,
-                name="float128",
-                char="g",
-                w_box_type=space.gettypefor(interp_boxes.W_Float128Box),
-                aliases=["longdouble", "longfloat"],
-            )
-            self.w_complex256dtype = W_ComplexDtype(
-                types.Complex256(),
-                num=16,
-                kind=COMPLEXLTR,
-                name="complex256",
-                char="G",
-                w_box_type = space.gettypefor(interp_boxes.W_Complex256Box),
-                alternate_constructors=[space.w_complex],
-                aliases=["clongdouble", "clongfloat"],
-                float_type = self.w_float128dtype,
-            )
-            self.w_longdouble = self.w_float128dtype
-            self.w_clongdouble = self.w_complex256dtype
-        elif interp_boxes.ENABLED_LONG_DOUBLE:
-            self.w_float64dtype.aliases += ["longdouble", "longfloat"]
-            self.w_complex128dtype.aliases += ["clongdouble", "clongfloat"]
-            self.w_longdouble = self.w_float64dtype
-            self.w_clongdouble = self.w_complex128dtype
+        self.w_complexlongdtype = W_ComplexDtype(
+            types.ComplexLong(),
+            num=16,
+            kind=COMPLEXLTR,
+            name="complex%d" % (interp_boxes.long_double_size * 16),
+            char="G",
+            w_box_type = space.gettypefor(interp_boxes.W_ComplexLongBox),
+            aliases=["clongdouble", "clongfloat"],
+            float_type = self.w_floatlongdtype,
+        )
         self.w_stringdtype = W_Dtype(
             types.StringType(0),
             num=18,
             char=UINTPLTR,
             w_box_type = space.gettypefor(uintp_box),
         )
-        float_dtypes = [self.w_float16dtype,
-                self.w_float32dtype, self.w_float64dtype,
-                ]
-        complex_dtypes =  [self.w_complex64dtype, self.w_complex128dtype]
-        if interp_boxes.ENABLED_LONG_DOUBLE:
-            float_dtypes.append(self.w_longdouble)
-            complex_dtypes.append(self.w_clongdouble)
+        float_dtypes = [self.w_float16dtype, self.w_float32dtype,
+                        self.w_float64dtype, self.w_floatlongdtype]
+        complex_dtypes = [self.w_complex64dtype, self.w_complex128dtype,
+                          self.w_complexlongdtype]
         self.builtin_dtypes = [
             self.w_booldtype,
             self.w_int8dtype, self.w_uint8dtype,
             self.w_int16dtype, self.w_uint16dtype,
             self.w_longdtype, self.w_ulongdtype,
             self.w_int32dtype, self.w_uint32dtype,
-            self.w_int64dtype, self.w_uint64dtype] + \
-            float_dtypes + complex_dtypes + [
+            self.w_int64dtype, self.w_uint64dtype,
+            ] + float_dtypes + complex_dtypes + [
             self.w_stringdtype, self.w_unicodedtype, self.w_voiddtype,
             self.w_intpdtype, self.w_uintpdtype,
         ]
             'STRING': self.w_stringdtype,
             'CFLOAT': self.w_complex64dtype,
             'CDOUBLE': self.w_complex128dtype,
+            'CLONGDOUBLE': self.w_complexlongdtype,
             #'DATETIME',
             'UINT': self.w_uint32dtype,
             'INTP': self.w_intpdtype,
             #'TIMEDELTA',
             'INT': self.w_int32dtype,
             'DOUBLE': self.w_float64dtype,
+            'LONGDOUBLE': self.w_floatlongdtype,
             'USHORT': self.w_uint16dtype,
             'FLOAT': self.w_float32dtype,
             'BOOL': self.w_booldtype,
         }
-        if interp_boxes.ENABLED_LONG_DOUBLE:
-            typeinfo_full['LONGDOUBLE'] = self.w_longdouble
-            typeinfo_full['CLONGDOUBLE'] = self.w_clongdouble
 
         typeinfo_partial = {
             'Generic': interp_boxes.W_GenericBox,

File pypy/module/micronumpy/interp_numarray.py

-
 from pypy.interpreter.error import operationerrfmt, OperationError
 from pypy.interpreter.typedef import TypeDef, GetSetProperty, make_weakref_descr
 from pypy.interpreter.gateway import interp2app, unwrap_spec, WrappedDefault
 from pypy.module.micronumpy.appbridge import get_appbridge_cache
 from pypy.module.micronumpy import loop
 from pypy.module.micronumpy.dot import match_dot_shapes
-from pypy.module.micronumpy.interp_arrayops import repeat, choose
+from pypy.module.micronumpy.interp_arrayops import repeat, choose, put
 from pypy.module.micronumpy.arrayimpl import scalar
 from rpython.tool.sourcetools import func_with_new_name
 from rpython.rlib import jit
                                      [0] * len(self.get_shape()))
                 assert isinstance(w_obj, interp_boxes.W_GenericBox)
                 return w_obj.item(space)
-            raise OperationError(space.w_IndexError,
-                                 space.wrap("index out of bounds"))
+            raise OperationError(space.w_ValueError,
+                                 space.wrap("can only convert an array of size 1 to a Python scalar"))
         if space.isinstance_w(w_arg, space.w_int):
             if self.is_scalar():
                 raise OperationError(space.w_IndexError,
             loop.byteswap(self.implementation, w_res.implementation)
             return w_res
 
-    @unwrap_spec(mode=str)
-    def descr_choose(self, space, w_choices, w_out=None, mode='raise'):
-        return choose(space, self, w_choices, w_out, mode)
+    def descr_choose(self, space, w_choices, w_out=None, w_mode=None):
+        return choose(space, self, w_choices, w_out, w_mode)
 
     def descr_clip(self, space, w_min, w_max, w_out=None):
         if space.is_none(w_out):
         return interp_arrayops.diagonal(space, self.implementation, offset,
                                         axis1, axis2)
 
+    @unwrap_spec(offset=int, axis1=int, axis2=int)
+    def descr_trace(self, space, offset=0, axis1=0, axis2=1,
+                    w_dtype=None, w_out=None):
+        diag = self.descr_diagonal(space, offset, axis1, axis2)
+        return diag.descr_sum(space, w_axis=space.wrap(-1), w_dtype=w_dtype, w_out=w_out)
+
     def descr_dump(self, space, w_file):
         raise OperationError(space.w_NotImplementedError, space.wrap(
             "dump not implemented yet"))
         raise OperationError(space.w_NotImplementedError, space.wrap(
             "ptp (peak to peak) not implemented yet"))
 
-    @unwrap_spec(mode=str)
-    def descr_put(self, space, w_indices, w_values, mode='raise'):
-        from pypy.module.micronumpy.interp_arrayops import put
-        put(space, self, w_indices, w_values, mode)
+    def descr_put(self, space, w_indices, w_values, w_mode=None):
+        put(space, self, w_indices, w_values, w_mode)
 
     def descr_resize(self, space, w_new_shape, w_refcheck=True):
         raise OperationError(space.w_NotImplementedError, space.wrap(
         raise OperationError(space.w_NotImplementedError, space.wrap(
             "tofile not implemented yet"))
 
-    def descr_trace(self, space, w_offset=0, w_axis1=0, w_axis2=1,
-                    w_dtype=None, w_out=None):
-        raise OperationError(space.w_NotImplementedError, space.wrap(
-            "trace not implemented yet"))
-
     def descr_view(self, space, w_dtype=None, w_type=None) :
         if not w_type and w_dtype:
             try:
 
     def _reduce_ufunc_impl(ufunc_name, promote_to_largest=False,
                            cumultative=False):
-        def impl(self, space, w_axis=None, w_out=None, w_dtype=None):
+        def impl(self, space, w_axis=None, w_dtype=None, w_out=None):
             if space.is_none(w_out):
                 out = None
             elif not isinstance(w_out, W_NDimArray):
     round    = interp2app(W_NDimArray.descr_round),
     data     = GetSetProperty(W_NDimArray.descr_get_data),
     diagonal = interp2app(W_NDimArray.descr_diagonal),
+    trace = interp2app(W_NDimArray.descr_trace),
     view = interp2app(W_NDimArray.descr_view),
 
     ctypes = GetSetProperty(W_NDimArray.descr_get_ctypes), # XXX unimplemented

File pypy/module/micronumpy/interp_ufuncs.py

 def done_if_false(dtype, val):
     return not dtype.itemtype.bool(val)
 
+
 class W_Ufunc(W_Root):
     _attrs_ = ["name", "promote_to_float", "promote_bools", "identity",
-               "allow_complex", "complex_to_float"]
+               "allow_bool", "allow_complex", "complex_to_float"]
     _immutable_fields_ = ["promote_to_float", "promote_bools", "name",
-            "allow_complex", "complex_to_float"]
+            "allow_bool", "allow_complex", "complex_to_float"]
 
     def __init__(self, name, promote_to_float, promote_bools, identity,
-                 int_only, allow_complex, complex_to_float):
+                 int_only, allow_bool, allow_complex, complex_to_float):
         self.name = name
         self.promote_to_float = promote_to_float
         self.promote_bools = promote_bools
+        self.identity = identity
+        self.int_only = int_only
+        self.allow_bool = allow_bool
         self.allow_complex = allow_complex
         self.complex_to_float = complex_to_float
 
-        self.identity = identity
-        self.int_only = int_only
-
     def descr_repr(self, space):
         return space.wrap("<ufunc '%s'>" % self.name)
 
 
     def __init__(self, func, name, promote_to_float=False, promote_bools=False,
         identity=None, bool_result=False, int_only=False,
-        allow_complex=True, complex_to_float=False):
+        allow_bool=True, allow_complex=True, complex_to_float=False):
 
         W_Ufunc.__init__(self, name, promote_to_float, promote_bools, identity,
-                         int_only, allow_complex, complex_to_float)
+                         int_only, allow_bool, allow_complex, complex_to_float)
         self.func = func
         self.bool_result = bool_result
 
             if space.is_w(out, space.w_None):
                 out = None
         w_obj = convert_to_array(space, w_obj)
-        if w_obj.get_dtype().is_flexible_type():
+        dtype = w_obj.get_dtype()
+        if dtype.is_flexible_type():
             raise OperationError(space.w_TypeError,
                       space.wrap('Not implemented for this type'))
-        if self.int_only and not w_obj.get_dtype().is_int_type():
+        if (self.int_only and not dtype.is_int_type() or
+                not self.allow_bool and dtype.is_bool_type() or
+                not self.allow_complex and dtype.is_complex_type()):
             raise OperationError(space.w_TypeError, space.wrap(
                 "ufunc %s not supported for the input type" % self.name))
         calc_dtype = find_unaryop_result_dtype(space,
                                   w_obj.get_dtype(),
                                   promote_to_float=self.promote_to_float,
-                                  promote_bools=self.promote_bools,
-                                  allow_complex=self.allow_complex)
+                                  promote_bools=self.promote_bools)
         if out is not None:
             if not isinstance(out, W_NDimArray):
                 raise OperationError(space.w_TypeError, space.wrap(
 
     def __init__(self, func, name, promote_to_float=False, promote_bools=False,
         identity=None, comparison_func=False, int_only=False,
-        allow_complex=True, complex_to_float=False):
+        allow_bool=True, allow_complex=True, complex_to_float=False):
 
         W_Ufunc.__init__(self, name, promote_to_float, promote_bools, identity,
-                         int_only, allow_complex, complex_to_float)
+                         int_only, allow_bool, allow_complex, complex_to_float)
         self.func = func
         self.comparison_func = comparison_func
         if name == 'logical_and':
                 w_rdtype = w_ldtype
             elif w_lhs.is_scalar() and not w_rhs.is_scalar():
                 w_ldtype = w_rdtype
+        if (self.int_only and (not w_ldtype.is_int_type() or not w_rdtype.is_int_type()) or
+                not self.allow_bool and (w_ldtype.is_bool_type() or w_rdtype.is_bool_type()) or
+                not self.allow_complex and (w_ldtype.is_complex_type() or w_rdtype.is_complex_type())):
+            raise OperationError(space.w_TypeError, space.wrap("Unsupported types"))
         calc_dtype = find_binop_result_dtype(space,
             w_ldtype, w_rdtype,
-            int_only=self.int_only,
             promote_to_float=self.promote_to_float,
-            promote_bools=self.promote_bools,
-            allow_complex=self.allow_complex,
-            )
-        if self.int_only and not calc_dtype.is_int_type():
-            raise OperationError(space.w_TypeError, space.wrap(
-                "ufunc '%s' not supported for the input types" % self.name))
+            promote_bools=self.promote_bools)
         if space.is_none(w_out):
             out = None
         elif not isinstance(w_out, W_NDimArray):
 
 
 def find_binop_result_dtype(space, dt1, dt2, promote_to_float=False,
-    promote_bools=False, int_only=False, allow_complex=True):
+        promote_bools=False):
     # dt1.num should be <= dt2.num
     if dt1.num > dt2.num:
         dt1, dt2 = dt2, dt1
-    if int_only and (not dt1.is_int_type() or not dt2.is_int_type()):
-        raise OperationError(space.w_TypeError, space.wrap("Unsupported types"))
-    if not allow_complex and (dt1.is_complex_type() or dt2.is_complex_type()):
-        raise OperationError(space.w_TypeError, space.wrap("Unsupported types"))
     # Some operations promote op(bool, bool) to return int8, rather than bool
     if promote_bools and (dt1.kind == dt2.kind == interp_dtype.BOOLLTR):
         return interp_dtype.get_dtype_cache(space).w_int8dtype
             return interp_dtype.get_dtype_cache(space).w_complex64dtype
         elif dt2.num == 15:
             return interp_dtype.get_dtype_cache(space).w_complex128dtype
-        elif interp_boxes.ENABLED_LONG_DOUBLE and dt2.num == 16:
-            return interp_dtype.get_dtype_cache(space).w_clongdouble
+        elif dt2.num == 16:
+            return interp_dtype.get_dtype_cache(space).w_complexlongdtype
         else:
             raise OperationError(space.w_TypeError, space.wrap("Unsupported types"))
 
         dtypenum += 2
         return interp_dtype.get_dtype_cache(space).dtypes_by_num[dtypenum]
 
-
 @jit.unroll_safe
 def find_unaryop_result_dtype(space, dt, promote_to_float=False,
-    promote_bools=False, promote_to_largest=False, allow_complex=True):
+        promote_bools=False, promote_to_largest=False):
     if promote_bools and (dt.kind == interp_dtype.BOOLLTR):
         return interp_dtype.get_dtype_cache(space).w_int8dtype
-    if not allow_complex and (dt.is_complex_type()):
-        raise OperationError(space.w_TypeError, space.wrap("Unsupported types"))
     if promote_to_float:
         if dt.kind == interp_dtype.FLOATINGLTR or dt.kind==interp_dtype.COMPLEXLTR:
             return dt
             assert False
     return dt
 
-
 def find_dtype_for_scalar(space, w_obj, current_guess=None):
     bool_dtype = interp_dtype.get_dtype_cache(space).w_booldtype
     long_dtype = interp_dtype.get_dtype_cache(space).w_longdtype
         'unable to create dtype from objects, ' '"%T" instance not supported',
         w_obj)
 
-
 def ufunc_dtype_caller(space, ufunc_name, op_name, argcount, comparison_func,
                        bool_result):
     dtype_cache = interp_dtype.get_dtype_cache(space)
             return res
     return func_with_new_name(impl, ufunc_name)
 
+
 class UfuncState(object):
     def __init__(self, space):
         "NOT_RPYTHON"
             ("greater_equal", "ge", 2, {"comparison_func": True}),
             ("isnan", "isnan", 1, {"bool_result": True}),
             ("isinf", "isinf", 1, {"bool_result": True}),
-            ("isneginf", "isneginf", 1, {"bool_result": True,
-                                         "allow_complex": False}),
-            ("isposinf", "isposinf", 1, {"bool_result": True,
-                                         "allow_complex": False}),
             ("isfinite", "isfinite", 1, {"bool_result": True}),
 
             ('logical_and', 'logical_and', 2, {'comparison_func': True,
             ("negative", "neg", 1),
             ("absolute", "abs", 1, {"complex_to_float": True}),
             ("rint", "rint", 1),
-            ("sign", "sign", 1, {"promote_bools": True}),
+            ("sign", "sign", 1, {"allow_bool": False}),
             ("signbit", "signbit", 1, {"bool_result": True,
                                        "allow_complex": False}),
             ("reciprocal", "reciprocal", 1),
                                        "allow_complex": False}),
             ("logaddexp2", "logaddexp2", 2, {"promote_to_float": True,
                                        "allow_complex": False}),
+
             ("ones_like", "ones_like", 1),
             ("zeros_like", "zeros_like", 1),
         ]:

File pypy/module/micronumpy/test/test_arrayops.py

         a = arange(5)
         a.put(22, -5, mode='wrap')
         assert (a == array([0, 1, -5, 3, 4])).all()
-        raises(ValueError, "arange(5).put(22, -5, mode='raise')")
-        raises(ValueError, "arange(5).put(22, -5, mode='wrongmode')")
+        raises(IndexError, "arange(5).put(22, -5, mode='raise')")
+        raises(IndexError, "arange(5).put(22, -5, mode=2)")  # raise
+        a.put(22, -10, mode='wrongmode_starts_with_w_so_wrap')
+        assert (a == array([0, 1, -10, 3, 4])).all()
+        a.put(22, -15, mode='cccccccc')
+        assert (a == array([0, 1, -10, 3, -15])).all()
+        a.put(23, -1, mode=1)  # wrap
+        assert (a == array([0, 1, -10, -1, -15])).all()
+        raises(TypeError, "arange(5).put(22, -5, mode='zzzz')")  # unrecognized mode

File pypy/module/micronumpy/test/test_complex.py

         raises(TypeError, signbit, complex(1,1))
 
     def test_reciprocal(self):
-        from numpypy import array, reciprocal, complex64, complex128
-        c_and_relerr = [(complex64, 2e-7), (complex128, 2e-15)]
-        try:
-            from numpypy import clongdouble
-            c_and_relerr.append((clongdouble, 2e-30))
-        except:
-            pass # no longdouble yet
+        from numpypy import array, reciprocal, complex64, complex128, clongdouble
         inf = float('inf')
         nan = float('nan')
         #complex
                     complex(-r, i),
                     -0j, 0j, cnan,
                     cnan, cnan, cnan]
-        for c, rel_err in c_and_relerr:
+        for c, rel_err in ((complex64, 2e-7), (complex128, 2e-15), (clongdouble, 2e-15)):
             actual = reciprocal(array([orig], dtype=c))
             for b, a, e in zip(orig, actual, expected):
                 assert (a[0].real - e.real) < rel_err
         raises(TypeError, copysign, a, b)
 
     def test_exp2(self):
-        from numpypy import array, exp2, complex128, complex64
-        c_and_relerr = [(complex64, 2e-7), (complex128, 2e-15)]
-        try:
-            from numpypy import clongdouble
-            c_and_relerr.append((clongdouble, 2e-30))
-        except:
-            pass # no longdouble yet
+        from numpypy import array, exp2, complex128, complex64, clongdouble
         inf = float('inf')
         ninf = -float('inf')
         nan = float('nan')
         cmpl = complex
-        for c,rel_err in c_and_relerr:
+        for c, rel_err in ((complex64, 2e-7), (complex128, 2e-15), (clongdouble, 2e-15)):
             a = [cmpl(-5., 0), cmpl(-5., -5.), cmpl(-5., 5.),
                        cmpl(0., -5.), cmpl(0., 0.), cmpl(0., 5.),
                        cmpl(-0., -5.), cmpl(-0., 0.), cmpl(-0., 5.),
 
     def test_expm1(self):
         import math, cmath
-        from numpypy import array, expm1, complex128, complex64
+        from numpypy import array, expm1, complex128, complex64, clongdouble
         inf = float('inf')
         ninf = -float('inf')
         nan = float('nan')
         cmpl = complex
-        for c,rel_err in ((complex128, 2e-15), (complex64, 1e-7)):
+        for c, rel_err in ((complex64, 2e-7), (complex128, 2e-15), (clongdouble, 2e-15)):
             a = [cmpl(-5., 0), cmpl(-5., -5.), cmpl(-5., 5.),
                        cmpl(0., -5.), cmpl(0., 0.), cmpl(0., 5.),
                        cmpl(-0., -5.), cmpl(-0., 0.), cmpl(-0., 5.),
     def test_basic(self):
         from numpypy import (complex128, complex64, add, array, dtype,
             subtract as sub, multiply, divide, negative, absolute as abs,
-            floor_divide, real, imag, sign)
+            floor_divide, real, imag, sign, clongdouble)
         from numpypy import (equal, not_equal, greater, greater_equal, less,
                 less_equal, isnan)
-        complex_dtypes = [complex64, complex128]
-        try:
-            from numpypy import clongfloat
-            complex_dtypes.append(clongfloat)
-        except:
-            pass
         assert real(4.0) == 4.0
         assert imag(0.0) == 0.0
         a = array([complex(3.0, 4.0)])
         assert str(a.real) == 'abc'
         # numpy imag for flexible types returns self
         assert str(a.imag) == 'abc'
-        for complex_ in complex_dtypes:
-
+        for complex_ in complex64, complex128, clongdouble:
             O = complex(0, 0)
             c0 = complex_(complex(2.5, 0))
             c1 = complex_(complex(1, 2))
             assert negative(complex(1,1)) == complex(-1, -1)
             assert negative(complex(0, 0)) == 0
 
-
             assert multiply(1, c1) == c1
             assert multiply(2, c2) == complex(6, 8)
             assert multiply(c1, c2) == complex(-5, 10)

File pypy/module/micronumpy/test/test_dtypes.py

         raises(TypeError, lambda: dtype("int8") == 3)
         assert dtype(bool) == bool
 
+    def test_dtype_aliases(self):
+        from numpypy import dtype
+        assert dtype('longfloat').num in (12, 13)
+        assert dtype('longdouble').num in (12, 13)
+        assert dtype('clongfloat').num in (15, 16)
+        assert dtype('clongdouble').num in (15, 16)
+
     def test_dtype_with_types(self):
         from numpypy import dtype
 
             '?', 'b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', 'q', 'Q', 'f', 'd',
             'e'
         ]
+        if array([0], dtype='longdouble').itemsize > 8:
+            types += ['g', 'G']
         a = array([True], '?')
         for t in types:
             assert (a + array([0], t)).dtype is dtype(t)
             (numpy.float16, 10.),
             (numpy.float32, 2.0),
             (numpy.float64, 4.32),
+            (numpy.longdouble, 4.32),
         ]:
             assert hash(tp(value)) == hash(value)
 
         from math import isnan
         assert isnan(numpy.float32(None))
         assert isnan(numpy.float64(None))
+        assert isnan(numpy.longdouble(None))
+
+    def test_longfloat(self):
+        import numpypy as numpy
+        # it can be float96 or float128
+        if numpy.longfloat != numpy.float64:
+            assert numpy.longfloat.mro()[1:] == [numpy.floating,
+                                       numpy.inexact, numpy.number,
+                                       numpy.generic, object]
+        a = numpy.array([1, 2, 3], numpy.longdouble)
+        assert type(a[1]) is numpy.longdouble
+        assert numpy.float64(12) == numpy.longdouble(12)
+        assert numpy.float64(12) == numpy.longfloat(12)
+        raises(ValueError, numpy.longfloat, '23.2df')
 
     def test_complex_floating(self):
         import numpypy as numpy
         assert dtype('i4').isnative == True
         assert dtype('>i8').isnative == False
 
-    def test_any_all(self):
+    def test_any_all_nonzero(self):
         import numpypy as numpy
         x = numpy.bool_(True)
         assert x.any()
         assert x.all()
+        assert x.__nonzero__()
+        assert isinstance(x.any(), numpy.bool_)
+        assert isinstance(x.__nonzero__(), bool)
         x = numpy.bool_(False)
         assert not x.any()
         assert not x.all()
-        #
+        assert not x.__nonzero__()
+        assert isinstance(x.any(), numpy.bool_)
+        assert isinstance(x.__nonzero__(), bool)
         x = numpy.float64(0)
         assert not x.any()
         assert not x.all()
-        assert isinstance(x.any(), numpy.bool_)
+        assert not x.__nonzero__()
+        assert isinstance(x.any(), numpy.float64)
+        assert isinstance(x.__nonzero__(), bool)
+        x = numpy.complex128(0)
+        assert not x.any()
+        assert not x.all()
+        assert not x.__nonzero__()
+        assert isinstance(x.any(), numpy.complex128)
+        assert isinstance(x.__nonzero__(), bool)
+        x = numpy.complex128(0+1j)
+        assert x.any()
+        assert x.all()
+        assert x.__nonzero__()
+        assert isinstance(x.any(), numpy.complex128)
+        assert isinstance(x.__nonzero__(), bool)
 
     def test_ravel(self):
         from numpypy import float64, int8, array
         assert (x == array(42)).all()
 
 
-
 class AppTestStrUnicodeDtypes(BaseNumpyAppTest):
     def test_str_unicode(self):
         skip('numpypy differs from numpy')
         from cPickle import loads, dumps
 
         d = dtype([("x", "int32"), ("y", "int32"), ("z", "int32"), ("value", float)])
-        assert d.__reduce__() == (dtype, ('V20', 0, 1), (3, '<', None, ('x', 'y', 'z', 'value'), {'y': (dtype('int32'), 4), 'x': (dtype('int32'), 0), 'z': (dtype('int32'), 8), 'value': (dtype('float64'), 12)}, 20, 1, 0))
+        assert d.__reduce__() == (dtype, ('V20', 0, 1), (3, '|', None, ('x', 'y', 'z', 'value'), {'y': (dtype('int32'), 4), 'x': (dtype('int32'), 0), 'z': (dtype('int32'), 8), 'value': (dtype('float64'), 12)}, 20, 1, 0))
 
         new_d = loads(dumps(d))
 
         a = array([1, 2, 3], dtype=self.non_native_prefix + 'f2')
         assert a[0] == 1
         assert (a + a)[1] == 4
+        a = array([1, 2, 3], dtype=self.non_native_prefix + 'g') # longdouble
+        assert a[0] == 1
+        assert (a + a)[1] == 4
+        a = array([1, 2, 3], dtype=self.non_native_prefix + 'G') # clongdouble
+        assert a[0] == 1
+        assert (a + a)[1] == 4
 
 class AppTestPyPyOnly(BaseNumpyAppTest):
     def setup_class(cls):
         assert typeinfo['CDOUBLE'] == ('D', 15, 128, 8, complex128)
         assert typeinfo['HALF'] == ('e', 23, 16, 2, float16)
 
-class AppTestNoLongDoubleDtypes(BaseNumpyAppTest):
-    def setup_class(cls):
-        from pypy.module.micronumpy import Module
-        if Module.interpleveldefs.get('longfloat', None):
-            py.test.skip('longdouble exists, skip these tests')
-        if option.runappdirect and '__pypy__' not in sys.builtin_module_names:
-            py.test.skip("pypy only test for no longdouble support")
-        BaseNumpyAppTest.setup_class.im_func(cls)
-
-    def test_nolongfloat(self):
-        import numpypy
-        from numpypy import dtype
-        assert not getattr(numpypy, 'longdouble', False)
-        assert not getattr(numpypy, 'float128', False)
-        assert not getattr(numpypy, 'float96', False)
-        raises(TypeError, dtype, 'longdouble')
-        raises(TypeError, dtype, 'clongdouble')
-        raises(TypeError, dtype, 'longfloat')
-        raises(TypeError, dtype, 'clongfloat')
-        raises(TypeError, dtype, 'float128')
-        raises(TypeError, dtype, 'float96')
-
-class AppTestLongDoubleDtypes(BaseNumpyAppTest):
-    def setup_class(cls):
-        from pypy.module.micronumpy import Module
-        print dir(Module.interpleveldefs)
-        if not Module.interpleveldefs.get('longfloat', None):
-            py.test.skip('no longdouble types yet')
-        BaseNumpyAppTest.setup_class.im_func(cls)
-
-    def test_longfloat(self):
-        import numpypy as numpy
-        # it can be float96 or float128
-        if numpy.longfloat != numpy.float64:
-            assert numpy.longfloat.mro()[1:] == [numpy.floating,
-                                       numpy.inexact, numpy.number,
-                                       numpy.generic, object]
-        a = numpy.array([1, 2, 3], numpy.longdouble)
-        assert type(a[1]) is numpy.longdouble
-        assert numpy.float64(12) == numpy.longdouble(12)
-        assert numpy.float64(12) == numpy.longfloat(12)
-        raises(ValueError, numpy.longfloat, '23.2df')
-
-    def test_dtype_aliases(self):
-        from numpypy import dtype
-        assert dtype('longfloat').num in (12, 13)
-        assert dtype('longdouble').num in (12, 13)
-        assert dtype('clongfloat').num in (15, 16)
-        assert dtype('clongdouble').num in (15, 16)
-
-    def test_bool_binop_types(self):
-        from numpypy import array, dtype
-        types = ['g', 'G']
-        a = array([True], '?')
-        for t in types:
-            assert (a + array([0], t)).dtype is dtype(t)
-
-    def test_hash(self):
-        import numpypy as numpy
-        for tp, value in [
-            (numpy.longdouble, 4.32),
-        ]:
-            assert hash(tp(value)) == hash(value)
-
-    def test_float_None(self):
-        import numpypy as numpy
-        from math import isnan
-        assert isnan(numpy.longdouble(None))
-
-    def test_non_native(self):
-        from numpypy import array
-        a = array([1, 2, 3], dtype=self.non_native_prefix + 'g') # longdouble
-        assert a[0] == 1
-        assert (a + a)[1] == 4
-        a = array([1, 2, 3], dtype=self.non_native_prefix + 'G') # clongdouble
-        assert a[0] == 1
-        assert (a + a)[1] == 4
-
 class AppTestObjectDtypes(BaseNumpyAppTest):
     def test_scalar_from_object(self):
         from numpypy import array

File pypy/module/micronumpy/test/test_numarray.py

         assert b[0] == 1+0j
         assert b.dtype is dtype(complex)
 
+    def test_arange(self):
+        from numpypy import arange, dtype
+        a = arange(3)
+        assert (a == [0, 1, 2]).all()
+        assert a.dtype is dtype(int)
+        a = arange(3.0)
+        assert (a == [0., 1., 2.]).all()
+        assert a.dtype is dtype(float)
+        a = arange(3, 7)
+        assert (a == [3, 4, 5, 6]).all()
+        assert a.dtype is dtype(int)
+        a = arange(3, 7, 2)
+        assert (a == [3, 5]).all()
+        a = arange(3, dtype=float)
+        assert (a == [0., 1., 2.]).all()
+        assert a.dtype is dtype(float)
+        a = arange(0, 0.8, 0.1)
+        assert len(a) == 8
+        assert arange(False, True, True).dtype is dtype(int)
+
     def test_copy(self):
         from numpypy import arange, array
         a = arange(5)
 
     def test_getitem_obj_index(self):
         from numpypy import arange
-
         a = arange(10)
-
         assert a[self.CustomIndexObject(1)] == 1
 
     def test_getitem_obj_prefer_index_to_int(self):
         from numpypy import arange
-
         a = arange(10)
-
-
         assert a[self.CustomIndexIntObject(0, 1)] == 0
 
     def test_getitem_obj_int(self):
         from numpypy import arange
-
         a = arange(10)
-
         assert a[self.CustomIntObject(1)] == 1
 
     def test_setitem(self):
         assert a[1] == -0.005
         assert a[2] == -0.005
 
-
     def test_setitem_tuple(self):
         from numpypy import array
         a = array(range(5))
 
     def test_setitem_obj_index(self):
         from numpypy import arange
-
         a = arange(10)
-
         a[self.CustomIndexObject(1)] = 100
         assert a[1] == 100
 
     def test_setitem_obj_prefer_index_to_int(self):
         from numpypy import arange
-
         a = arange(10)
-
         a[self.CustomIndexIntObject(0, 1)] = 100
         assert a[0] == 100
 
     def test_setitem_obj_int(self):
         from numpypy import arange
-
         a = arange(10)
-
         a[self.CustomIntObject(1)] = 100
-
         assert a[1] == 100
 
     def test_access_swallow_exception(self):
         assert a[5] == 50
         b = a.imag
         assert b[7] == 0
-        raises(RuntimeError, 'b[7] = -2')
+        raises(ValueError, 'b[7] = -2')
         raises(TypeError, 'a.imag = -2')
         a = array(['abc','def'],dtype='S3')
         b = a.real
         assert a[1] == b[1]
         b[1] = 'xyz'
         assert a[1] == 'xyz'
-        assert a.imag[0] == 'abc'
+        assert a.imag[0] == ''
         raises(TypeError, 'a.imag = "qop"')
         a=array([[1+1j, 2-3j, 4+5j],[-6+7j, 8-9j, -2-1j]])
         assert a.real[0,1] == 2
         assert a[3].imag == -10
         assert a[2].imag == -5
 
+    def test_trace(self):
+        import numpypy as np
+        assert np.trace(np.eye(3)) == 3.0
+        a = np.arange(8).reshape((2,2,2))
+        assert np.array_equal(np.trace(a), [6, 8])
+        a = np.arange(24).reshape((2,2,2,3))
+        assert np.trace(a).shape == (2, 3)
+
     def test_view(self):
         from numpypy import array, int8, int16, dtype
         x = array((1, 2), dtype=int8)
             i2 = (i+1) * a.dtype.itemsize
             assert list(reversed(s1[i1:i2])) == s2[i1:i2]
 
+        a = array([1, -1, 10000], dtype='longfloat')
+        s1 = map(ord, a.tostring())
+        s2 = map(ord, a.byteswap().tostring())
+        assert a.dtype.itemsize >= 8
+        for i in range(a.size):
+            i1 = i * a.dtype.itemsize
+            i2 = (i+1) * a.dtype.itemsize
+            assert list(reversed(s1[i1:i2])) == s2[i1:i2]
+
     def test_clip(self):
         from numpypy import array
         a = array([1, 2, 17, -3, 12])
         c = b + b
         assert c.sum() == (6 + 8 + 10 + 12) * 2
         assert isinstance(c.sum(dtype='f8'), float)
+        assert isinstance(c.sum(None, 'f8'), float)
 
     def test_transpose(self):
         from numpypy import array
         assert type(array(True).item()) is bool
         assert type(array(3.5).item()) is float
         raises(IndexError, "array(3).item(15)")
-        raises(IndexError, "array([1, 2, 3]).item()")
+        raises(ValueError, "array([1, 2, 3]).item()")
         assert array([3]).item(0) == 3
         assert type(array([3]).item(0)) is int
         assert array([1, 2, 3]).item(-1) == 3
 
     def test_fromstring_types(self):
         from numpypy import (fromstring, int8, int16, int32, int64, uint8,
-            uint16, uint32, float16, float32, float64, array)
+            uint16, uint32, float16, float32, float64, longfloat, array)
         a = fromstring('\xFF', dtype=int8)
         assert a[0] == -1
         b = fromstring('\xFF', dtype=uint8)
         assert j[0] == 12
         k = fromstring(self.float16val, dtype=float16)
         assert k[0] == float16(5.)
+        dt =  array([5],dtype=longfloat).dtype
+        if dt.itemsize == 12:
+            from numpypy import float96
+            m = fromstring('\x00\x00\x00\x00\x00\x00\x00\xa0\x01@\x00\x00', dtype=float96)
+        elif dt.itemsize == 16:
+            from numpypy import float128
+            m = fromstring('\x00\x00\x00\x00\x00\x00\x00\xa0\x01@\x00\x00\x00\x00\x00\x00', dtype=float128)
+        elif dt.itemsize == 8:
+            skip('longfloat is float64')
+        else:
+            skip('unknown itemsize for longfloat')
+        assert m[0] == longfloat(5.)
 
     def test_fromstring_invalid(self):
         from numpypy import fromstring, uint16, uint8
         assert array(0, dtype='i2').tostring() == '\x00\x00'
 
 
-class AppTestRanges(BaseNumpyAppTest):
-    def test_arange(self):
-        from numpypy import arange, dtype
-        a = arange(3)
-        assert (a == [0, 1, 2]).all()
-        assert a.dtype is dtype(int)
-        a = arange(3.0)
-        assert (a == [0., 1., 2.]).all()
-        assert a.dtype is dtype(float)
-        a = arange(3, 7)
-        assert (a == [3, 4, 5, 6]).all()
-        assert a.dtype is dtype(int)
-        a = arange(3, 7, 2)
-        assert (a == [3, 5]).all()
-        a = arange(3, dtype=float)
-        assert (a == [0., 1., 2.]).all()
-        assert a.dtype is dtype(float)
-        a = arange(0, 0.8, 0.1)
-        assert len(a) == 8
-        assert arange(False, True, True).dtype is dtype(int)
-
-
 class AppTestRepr(BaseNumpyAppTest):
     def setup_class(cls):
         if option.runappdirect:
         assert (a[0, 0, 0] == 500).all()
         assert a[0, 0, 0].shape == (10,)
 
+    def test_subarray_multiple_rows(self):
+        import numpypy as np
+        descr = [
+            ('x', 'i4', (2,)),
+            ('y', 'f8', (2, 2)),
+            ('z', 'u1')]
+        buf = [
+            # x     y                  z
+            ([3,2], [[6.,4.],[6.,4.]], 8),
+            ([4,3], [[7.,5.],[7.,5.]], 9),
+            ]
+        h = np.array(buf, dtype=descr)
+        assert len(h) == 2
+        skip('broken')  # XXX
+        assert np.array_equal(h['x'], np.array([buf[0][0],
+                                                buf[1][0]], dtype='i4'))
+        assert np.array_equal(h['y'], np.array([buf[0][1],
+                                                buf[1][1]], dtype='f8'))
+        assert np.array_equal(h['z'], np.array([buf[0][2],
+                                                buf[1][2]], dtype='u1'))
+
     def test_multidim_subarray(self):
         from numpypy import dtype, array
 
         assert x.__pypy_data__ is obj
         del x.__pypy_data__
         assert x.__pypy_data__ is None
-
-class AppTestLongDoubleDtypes(BaseNumpyAppTest):
-    def setup_class(cls):
-        from pypy.module.micronumpy import Module
-        #print dir(Module.interpleveldefs)
-        if not Module.interpleveldefs.get('longfloat', None):
-            py.test.skip('no longdouble types yet')
-        BaseNumpyAppTest.setup_class.im_func(cls)
-
-    def test_byteswap(self):
-        from numpypy import array
-
-        a = array([1, -1, 10000], dtype='longfloat')
-        s1 = map(ord, a.tostring())
-        s2 = map(ord, a.byteswap().tostring())
-        assert a.dtype.itemsize >= 8
-        for i in range(a.size):
-            i1 = i * a.dtype.itemsize
-            i2 = (i+1) * a.dtype.itemsize
-            assert list(reversed(s1[i1:i2])) == s2[i1:i2]
-
-    def test_fromstring_types(self):
-        from numpypy import (fromstring, longfloat, array)
-        dt =  array([5],dtype=longfloat).dtype
-        if dt.itemsize == 12:
-            from numpypy import float96
-            m = fromstring('\x00\x00\x00\x00\x00\x00\x00\xa0\x01@\x00\x00', dtype=float96)
-        elif dt.itemsize==16:
-            from numpypy import float128
-            m = fromstring('\x00\x00\x00\x00\x00\x00\x00\xa0\x01@\x00\x00\x00\x00\x00\x00', dtype=float128)
-        elif dt.itemsize == 8:
-            skip('longfloat is float64')
-        else:
-            skip('unknown itemsize for longfloat')
-        assert m[0] == longfloat(5.)
-
-

File pypy/module/micronumpy/test/test_ufuncs.py

                         uncallable.add(s)
             return uncallable
         assert find_uncallable_ufuncs('int') == set()
-        assert find_uncallable_ufuncs('bool') == set()
+        assert find_uncallable_ufuncs('bool') == set(['sign'])
         assert find_uncallable_ufuncs('float') == set(
                 ['bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor',
                  'left_shift', 'right_shift', 'invert'])
         assert find_uncallable_ufuncs('complex') == set(
                 ['bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor',
                  'arctan2', 'deg2rad', 'degrees', 'rad2deg', 'radians',
-                 'fabs', 'fmod', 'invert', 'isneginf', 'isposinf',
+                 'fabs', 'fmod', 'invert', 'mod',
                  'logaddexp', 'logaddexp2', 'left_shift', 'right_shift',
                  'copysign', 'signbit', 'ceil', 'floor', 'trunc'])
 
         assert fabs(float('-inf')) == float('inf')
         assert isnan(fabs(float('nan')))
 
-
     def test_fmax(self):
         from numpypy import fmax, array
         import math
         # on Microsoft win32
         assert math.copysign(1., fmax(nnan, nan)) == math.copysign(1., nnan)
 
-
     def test_fmin(self):
         from numpypy import fmin, array
         import math
         # on Microsoft win32
         assert math.copysign(1., fmin(nnan, nan)) == math.copysign(1., nnan)
 
-
     def test_fmod(self):
         from numpypy import fmod
         import math
             reference = [0, -1, 0, 1, 0]
             if dtype[0] == 'u':
                 reference[1] = 0
-            # XXX need to fix specialization issue in types.py first
-            #elif dtype == 'int32':
-            #        reference[2] = -2147483648
-            #elif dtype == 'int64':
-            #        reference[2] = -9223372036854775808
+            elif dtype == 'int32':
+                    reference[2] = -2147483648
+            elif dtype == 'int64':
+                    reference[2] = -9223372036854775808
             a = array([-2, -1, 0, 1, 2], dtype)
             b = reciprocal(a)
             assert (b == reference).all()
         c = array([10.5+11.5j, -15.2-100.3456j, 0.2343+11.123456j])
         assert (c.round(0) == [10.+12.j, -15-100j, 0+11j]).all()
 
-
     def test_copysign(self):
         from numpypy import array, copysign
 
 
         assert expm1(1e-50) == 1e-50
 
-
     def test_sin(self):
         import math
         from numpypy import array, sin
         assert (~a == [-2, -3, -4, -5]).all()
         assert (bitwise_not(a) == ~a).all()
         assert (invert(a) == ~a).all()
+        assert invert(True) == False
+        assert invert(False) == True
 
     def test_shift(self):
         from numpypy import left_shift, right_shift, bool

File pypy/module/micronumpy/types.py

 from rpython.rlib.rawstorage import (alloc_raw_storage, raw_storage_setitem,
                                   raw_storage_getitem)
 from rpython.rlib.objectmodel import specialize
-from rpython.rlib.rarithmetic import widen, byteswap, r_ulonglong
+from rpython.rlib.rarithmetic import widen, byteswap, r_ulonglong, most_neg_value_of
 from rpython.rtyper.lltypesystem import lltype, rffi
 from rpython.rlib.rstruct.runpack import runpack
 from rpython.rlib.rstruct.nativefmttable import native_is_bigendian
     def isinf(self, v):
         return False
 
-    @raw_unary_op
-    def isneginf(self, v):
-        return False
-
-    @raw_unary_op
-    def isposinf(self, v):
-        return False
-
     @raw_binary_op
     def eq(self, v1, v2):
         return v1 == v2
 
     @simple_unary_op
     def invert(self, v):
-        return ~v
+        return not v
 
     @raw_unary_op
     def isfinite(self, v):
     def isinf(self, v):
         return False
 
-    @raw_unary_op
-    def isposinf(self, v):
-        return False
-
-    @raw_unary_op
-    def isneginf(self, v):
-        return False
-
     @simple_binary_op
     def bitwise_and(self, v1, v2):
         return v1 & v2
     def invert(self, v):
         return ~v
 
-    @simple_unary_op
+    @specialize.argtype(1)
     def reciprocal(self, v):
-        if v == 0:
+        raw = self.for_computation(self.unbox(v))
+        ans = 0
+        if raw == 0:
             # XXX good place to warn
-            # XXX can't do the following, func is specialized only on argtype(v)
-            # (which is the same for all int classes)
-            #if self.T in (rffi.INT, rffi.LONG):
-            #    return most_neg_value_of(self.T)
-            return 0
-        if abs(v) == 1:
-            return v
-        return 0
+            if self.T is rffi.INT or self.T is rffi.LONG:
+                ans = most_neg_value_of(self.T)
+        elif abs(raw) == 1:
+            ans = raw
+        return self.box(ans)
 
     @specialize.argtype(1)
     def round(self, v, decimals=0):
         return rfloat.isinf(v)
 
     @raw_unary_op
-    def isneginf(self, v):
-        return rfloat.isinf(v) and v < 0
-
-    @raw_unary_op
-    def isposinf(self, v):
-        return rfloat.isinf(v) and v > 0
-
-    @raw_unary_op
     def isfinite(self, v):
         return not (rfloat.isinf(v) or rfloat.isnan(v))
 
         return v
 
     def to_builtin_type(self, space, box):
-        real,imag = self.for_computation(self.unbox(box))
+        real, imag = self.for_computation(self.unbox(box))
         return space.newcomplex(real, imag)
 
+    def bool(self, v):
+        real, imag = self.for_computation(self.unbox(v))
+        return bool(real) or bool(imag)
+
     def read_bool(self, arr, i, offset):
         v = self.for_computation(self._read(arr.storage, i, offset))
         return bool(v[0]) or bool(v[1])
 
 NonNativeComplex128 = Complex128
 
-if interp_boxes.ENABLED_LONG_DOUBLE and interp_boxes.long_double_size == 12:
-    class Float96(BaseType, Float):
+if interp_boxes.long_double_size == 8:
+    FloatLong = Float64
+    NonNativeFloatLong = NonNativeFloat64
+    ComplexLong = Complex128
+    NonNativeComplexLong = NonNativeComplex128
+
+elif interp_boxes.long_double_size in (12, 16):
+    class FloatLong(BaseType, Float):
         _attrs_ = ()
 
         T = rffi.LONGDOUBLE
-        BoxType = interp_boxes.W_Float96Box
-        format_code = "q"
+        BoxType = interp_boxes.W_FloatLongBox
 
         def runpack_str(self, s):
-            assert len(s) == 12
+            assert len(s) == interp_boxes.long_double_size
             fval = unpack_float80(s, native_is_bigendian)
             return self.box(fval)
 
             pack_float80(result, value, 10, not native_is_bigendian)
             return self.box(unpack_float80(result.build(), native_is_bigendian))
 
-    NonNativeFloat96 = Float96
+    NonNativeFloatLong = FloatLong
 
-    class Complex192(ComplexFloating, BaseType):
+    class ComplexLong(ComplexFloating, BaseType):
         _attrs_ = ()
 
         T = rffi.LONGDOUBLE
-        BoxType = interp_boxes.W_Complex192Box
-        ComponentBoxType = interp_boxes.W_Float96Box
+        BoxType = interp_boxes.W_ComplexLongBox
+        ComponentBoxType = interp_boxes.W_FloatLongBox