[Numpy-svn] r5936 - in branches/1.2.x/numpy/ma: . tests

numpy-svn at scipy.org numpy-svn at scipy.org
Mon Oct 6 17:05:09 EDT 2008


Author: pierregm
Date: 2008-10-06 16:05:03 -0500 (Mon, 06 Oct 2008)
New Revision: 5936

Modified:
   branches/1.2.x/numpy/ma/core.py
   branches/1.2.x/numpy/ma/extras.py
   branches/1.2.x/numpy/ma/mrecords.py
   branches/1.2.x/numpy/ma/tests/test_core.py
   branches/1.2.x/numpy/ma/tests/test_extras.py
   branches/1.2.x/numpy/ma/tests/test_mrecords.py
   branches/1.2.x/numpy/ma/tests/test_subclassing.py
   branches/1.2.x/numpy/ma/testutils.py
   branches/1.2.x/numpy/ma/timer_comparison.py
Log:
Backporting bug fixes:

core:
MaskedArray
* __new__            : make sure that hard_mask is not overwritten by default [r5824]
* __array_finalize__ : force flexible-type masked arrays to have a full mask of False by default
* view               : add support for optional parameters
* __getitem__        : fixed for flexible-type
* __str__            : fixed for flexible-type [r5835]
* repr               : fixed for flexible-type [r5835]
* __deepcopy__       : introduced [r5791]
* concatenate        : fixed for flexible-type [r5869]
* count              : simplified to call the method on masked arrays instead of recreating an array
* minimum/maximum    : ensure that a masked array is returned [r5800]

extras
* fixed median on nD arrays (w/ n!=1) [r5831]

mrecords
* fixed fromrecords
* fixed __str__ and repr for MaskedRecords [r5835]

testutils
* prevent the use of plain assert in tests [r5879]

Modified: branches/1.2.x/numpy/ma/core.py
===================================================================
--- branches/1.2.x/numpy/ma/core.py	2008-10-06 02:55:14 UTC (rev 5935)
+++ branches/1.2.x/numpy/ma/core.py	2008-10-06 21:05:03 UTC (rev 5936)
@@ -57,17 +57,14 @@
            'var', 'where',
            'zeros']
 
-import sys
-import types
 import cPickle
 import operator
 
 import numpy as np
-from numpy import ndarray, typecodes, amax, amin, iscomplexobj,\
-    bool_, complex_, float_, int_, object_, str_
+from numpy import ndarray, amax, amin, iscomplexobj, bool_, complex_, float_,\
+                  int_, object_
 from numpy import array as narray
 
-
 import numpy.core.umath as umath
 import numpy.core.numerictypes as ntypes
 from numpy import expand_dims as n_expand_dims
@@ -1237,7 +1234,7 @@
 
     def __new__(cls, data=None, mask=nomask, dtype=None, copy=False,
                 subok=True, ndmin=0, fill_value=None,
-                keep_mask=True, hard_mask=False, flag=None, shrink=True,
+                keep_mask=True, hard_mask=None, flag=None, shrink=True,
                 **options):
         """Create a new masked array from scratch.
 
@@ -1257,9 +1254,9 @@
             copy = True
         # Careful, cls might not always be MaskedArray...
         if not isinstance(data, cls) or not subok:
-            _data = _data.view(cls)
+            _data = ndarray.view(_data, cls)
         else:
-            _data = _data.view(type(data))
+            _data = ndarray.view(_data, type(data))
         # Backwards compatibility w/ numpy.core.ma .......
         if hasattr(data,'_mask') and not isinstance(data, ndarray):
             _data._mask = data._mask
@@ -1341,7 +1338,10 @@
         if fill_value is not None:
             _data._fill_value = _check_fill_value(fill_value, _data.dtype)
         # Process extra options ..
-        _data._hardmask = hard_mask
+        if hard_mask is None:
+            _data._hardmask = getattr(data, '_hardmask', False)
+        else:
+            _data._hardmask = hard_mask
         _data._baseclass = _baseclass
         return _data
     #
@@ -1374,7 +1374,15 @@
         """
         # Get main attributes .........
         self._update_from(obj)
-        self._mask = getattr(obj, '_mask', nomask)
+        if isinstance(obj, ndarray):
+            odtype = obj.dtype
+            if odtype.names:
+                _mask = getattr(obj, '_mask', make_mask_none(obj.shape, odtype))
+            else:
+                _mask = getattr(obj, '_mask', nomask)
+        else:
+            _mask = nomask
+        self._mask = _mask
         # Finalize the mask ...........
         if self._mask is not nomask:
             self._mask.shape = self.shape
@@ -1425,6 +1433,24 @@
         #....
         return result
     #.............................................
+    def view(self, dtype=None, type=None):
+        if dtype is not None:
+            if type is None:
+                args = (dtype,)
+            else:
+                args = (dtype, type)
+        elif type is None:
+            args = ()
+        else:
+            args = (type,)
+        output = ndarray.view(self, *args)
+        if (getattr(output,'_mask', nomask) is not nomask):
+            mdtype = make_mask_descr(output.dtype)
+            output._mask = self._mask.view(mdtype, ndarray)
+            output._mask.shape = output.shape
+        return output
+    view.__doc__ = ndarray.view.__doc__
+    #.............................................
     def astype(self, newtype):
         """Returns a copy of the array cast to newtype."""
         newtype = np.dtype(newtype)
@@ -1453,15 +1479,22 @@
 #        if getmask(indx) is not nomask:
 #            msg = "Masked arrays must be filled before they can be used as indices!"
 #            raise IndexError, msg
-        dout = ndarray.__getitem__(self.view(ndarray), indx)
+        dout = ndarray.__getitem__(ndarray.view(self,ndarray), indx)
         # We could directly use ndarray.__getitem__ on self...
         # But then we would have to modify __array_finalize__ to prevent the
         # mask of being reshaped if it hasn't been set up properly yet...
         # So it's easier to stick to the current version
         _mask = self._mask
         if not getattr(dout,'ndim', False):
+            # A record ................
+            if isinstance(dout, np.void):
+                mask = _mask[indx]
+                if mask.view((bool,len(mask.dtype))).any():
+                    dout = masked_array(dout, mask=mask)
+                else:
+                    return dout
             # Just a scalar............
-            if _mask is not nomask and _mask[indx]:
+            elif _mask is not nomask and _mask[indx]:
                 return masked
         else:
             # Force dout to MA ........
@@ -1701,7 +1734,7 @@
         underlying data.
 
         """
-        return self.view(self._baseclass)
+        return ndarray.view(self, self._baseclass)
     _data = property(fget=_get_data)
     data = property(fget=_get_data)
 
@@ -1817,18 +1850,33 @@
 
 
     def compress(self, condition, axis=None, out=None):
-        """Return a where condition is True.
-        If condition is a MaskedArray, missing values are considered as False.
+        """
+    Return `a` where condition is ``True``.
+    If condition is a `MaskedArray`, missing values are considered as ``False``.
 
-        Returns
-        -------
-        A MaskedArray object.
+    Parameters
+    ----------
+    condition : var
+        Boolean 1-d array selecting which entries to return. If len(condition)
+        is less than the size of a along the axis, then output is truncated
+        to length of condition array.
+    axis : {None, int}, optional
+        Axis along which the operation must be performed.
+    out : {None, ndarray}, optional
+        Alternative output array in which to place the result. It must have
+        the same shape as the expected output but the type will be cast if
+        necessary.
 
-        Notes
-        -----
-        Please note the difference with compressed() !
-        The output of compress has a mask, the output of compressed does not.
+    Returns
+    -------
+    result : MaskedArray
+        A :class:`MaskedArray` object.
 
+    Warnings
+    --------
+    Please note the difference with :meth:`compressed` !
+    The output of :meth:`compress` has a mask, the output of :meth:`compressed` does not.
+
         """
         # Get the basic components
         (_data, _mask) = (self._data, self._mask)
@@ -1855,7 +1903,15 @@
                 res = self._data
             else:
                 if m.shape == ():
-                    if m:
+                    if m.dtype.names:
+                        m = m.view((bool, len(m.dtype)))
+                        if m.any():
+                            r = np.array(self._data.tolist(), dtype=object)
+                            np.putmask(r, m, f)
+                            return str(tuple(r))
+                        else:
+                            return str(self._data)
+                    elif m:
                         return str(f)
                     else:
                         return str(self._data)
@@ -1892,34 +1948,56 @@
       mask = %(mask)s,
       fill_value=%(fill)s)
 """
+        with_mask_flx = """\
+masked_%(name)s(data =
+ %(data)s,
+      mask =
+ %(mask)s,
+      fill_value=%(fill)s,
+      dtype=%(dtype)s)
+"""
+        with_mask1_flx = """\
+masked_%(name)s(data = %(data)s,
+      mask = %(mask)s,
+      fill_value=%(fill)s
+      dtype=%(dtype)s)
+"""
         n = len(self.shape)
         name = repr(self._data).split('(')[0]
-        if n <= 1:
-            return with_mask1 % {
-                'name': name,
-                'data': str(self),
-                'mask': str(self._mask),
-                'fill': str(self.fill_value),
-                }
-        return with_mask % {
-            'name': name,
-            'data': str(self),
-            'mask': str(self._mask),
-            'fill': str(self.fill_value),
-            }
+        parameters =  dict(name=name, data=str(self), mask=str(self._mask),
+                           fill=str(self.fill_value), dtype=str(self.dtype))
+        if self.dtype.names:
+            if n<= 1:
+                return with_mask1_flx % parameters
+            return  with_mask_flx % parameters
+        elif n <= 1:
+            return with_mask1 % parameters
+        return with_mask % parameters
     #............................................
     def __add__(self, other):
         "Add other to self, and return a new masked array."
         return add(self, other)
     #
+    def __radd__(self, other):
+        "Add other to self, and return a new masked array."
+        return add(self, other)
+    #
     def __sub__(self, other):
         "Subtract other to self, and return a new masked array."
         return subtract(self, other)
     #
+    def __rsub__(self, other):
+        "Subtract other to self, and return a new masked array."
+        return subtract(other, self)
+    #
     def __mul__(self, other):
         "Multiply other by self, and return a new masked array."
         return multiply(self, other)
     #
+    def __rmul__(self, other):
+        "Multiply other by self, and return a new masked array."
+        return multiply(self, other)
+    #
     def __div__(self, other):
         "Divide other into self, and return a new masked array."
         return divide(self, other)
@@ -2038,9 +2116,10 @@
 
         Returns
         -------
-        A masked array where the mask is True where all data are
-        masked.  If axis is None, returns either a scalar ot the
-        masked singleton if all values are masked.
+        result : MaskedArray
+            A masked array where the mask is True where all data are
+            masked.  If axis is None, returns either a scalar ot the
+            masked singleton if all values are masked.
 
         """
         m = self._mask
@@ -2182,7 +2261,7 @@
 
     Check if all of the elements of `a` are true.
 
-    Performs a logical_and over the given axis and returns the result.
+    Performs a :func:`logical_and` over the given axis and returns the result.
     Masked values are considered as True during computation.
     For convenience, the output array is masked where ALL the values along the
     current axis are masked: if the output would have been a scalar and that
@@ -2344,10 +2423,8 @@
 
 
     def cumsum(self, axis=None, dtype=None, out=None):
-        """a.cumsum(axis=None, dtype=None, out=None)
-
+        """
     Return the cumulative sum of the elements along the given axis.
-
     The cumulative sum is calculated over the flattened array by
     default, otherwise over the specified axis.
 
@@ -2358,20 +2435,24 @@
     Parameters
     ----------
     axis : {None, -1, int}, optional
-        Axis along which the sum is computed. The default
-        (`axis` = None) is to compute over the flattened array.
+        Axis along which the sum is computed. The default (`axis` = None) is to
+        compute over the flattened array. `axis` may be negative, in which case
+        it counts from the   last to the first axis.
     dtype : {None, dtype}, optional
-        Determines the type of the returned array and of the accumulator
-        where the elements are summed. If dtype has the value None and
-        the type of a is an integer type of precision less than the default
-        platform integer, then the default platform integer precision is
-        used.  Otherwise, the dtype is the same as that of a.
+        Type of the returned array and of the accumulator in which the
+        elements are summed.  If `dtype` is not specified, it defaults
+        to the dtype of `a`, unless `a` has an integer dtype with a
+        precision less than that of the default platform integer.  In
+        that case, the default platform integer is used.
     out : ndarray, optional
         Alternative output array in which to place the result. It must
         have the same shape and buffer length as the expected output
         but the type will be cast if necessary.
-        WARNING : The mask is lost if out is not a valid MaskedArray !
 
+    Warning
+    -------
+        The mask is lost if out is not a valid :class:`MaskedArray` !
+
     Returns
     -------
     cumsum : ndarray.
@@ -2380,7 +2461,8 @@
 
     Example
     -------
-    >>> print np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0]).cumsum()
+    >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0])
+    >>> print marr.cumsum()
     [0 1 3 -- -- -- 9 16 24 33]
 
 
@@ -2401,8 +2483,7 @@
 
 
     def prod(self, axis=None, dtype=None, out=None):
-        """a.prod(axis=None, dtype=None, out=None)
-
+        """
     Return the product of the array elements over the given axis.
     Masked elements are set to 1 internally for computation.
 
@@ -2413,8 +2494,8 @@
         product is over all the array elements.
     dtype : {None, dtype}, optional
         Determines the type of the returned array and of the accumulator
-        where the elements are multiplied. If dtype has the value None and
-        the type of a is an integer type of precision less than the default
+        where the elements are multiplied. If ``dtype`` has the value ``None``
+        and the type of a is an integer type of precision less than the default
         platform integer, then the default platform integer precision is
         used.  Otherwise, the dtype is the same as that of a.
     out : {None, array}, optional
@@ -2473,10 +2554,7 @@
 
     def cumprod(self, axis=None, dtype=None, out=None):
         """
-    a.cumprod(axis=None, dtype=None, out=None)
-
     Return the cumulative product of the elements along the given axis.
-
     The cumulative product is taken over the flattened array by
     default, otherwise over the specified axis.
 
@@ -2491,21 +2569,24 @@
         (`axis` = None) is to compute over the flattened array.
     dtype : {None, dtype}, optional
         Determines the type of the returned array and of the accumulator
-        where the elements are multiplied. If dtype has the value None and
-        the type of a is an integer type of precision less than the default
+        where the elements are multiplied. If ``dtype`` has the value ``None`` and
+        the type of ``a`` is an integer type of precision less than the default
         platform integer, then the default platform integer precision is
-        used.  Otherwise, the dtype is the same as that of a.
+        used.  Otherwise, the dtype is the same as that of ``a``.
     out : ndarray, optional
         Alternative output array in which to place the result. It must
         have the same shape and buffer length as the expected output
         but the type will be cast if necessary.
-        WARNING : The mask is lost if out is not a valid MaskedArray !
 
+    Warning
+    -------
+        The mask is lost if out is not a valid MaskedArray !
+
     Returns
     -------
-    cumprod : ndarray.
-        A new array holding the result is returned unless out is
-        specified, in which case a reference to out is returned.
+    cumprod : ndarray
+        A new array holding the result is returned unless out is specified,
+        in which case a reference to out is returned.
 
     Notes
     -----
@@ -2524,43 +2605,7 @@
 
 
     def mean(self, axis=None, dtype=None, out=None):
-        """a.mean(axis=None, dtype=None, out=None) -> mean
-
-    Returns the average of the array elements.  The average is taken over the
-    flattened array by default, otherwise over the specified axis.
-
-    Parameters
-    ----------
-    axis : integer
-        Axis along which the means are computed. The default is
-        to compute the mean of the flattened array.
-    dtype : type
-        Type to use in computing the means. For arrays of
-        integer type the default is float32, for arrays of float types it
-        is the same as the array type.
-    out : ndarray
-        Alternative output array in which to place the result. It must have
-        the same shape as the expected output but the type will be cast if
-        necessary.
-
-    Returns
-    -------
-    mean : The return type varies, see above.
-        A new array holding the result is returned unless out is specified,
-        in which case a reference to out is returned.
-
-    See Also
-    --------
-    var : variance
-    std : standard deviation
-
-    Notes
-    -----
-    The mean is the sum of the elements along the axis divided by the
-    number of elements.
-
-
-        """
+        ""
         if self._mask is nomask:
             result = super(MaskedArray, self).mean(axis=axis, dtype=dtype)
         else:
@@ -2576,21 +2621,22 @@
                 outmask.flat = getattr(result, '_mask', nomask)
             return out
         return result
+    mean.__doc__ = ndarray.mean.__doc__
 
     def anom(self, axis=None, dtype=None):
-        """Return the anomalies (deviations from the average) along
-        the given axis.
+        """
+    Return the anomalies (deviations from the average) along the given axis.
 
-        Parameters
-        ----------
-        axis : int, optional
-            Axis along which to perform the operation.
-            If None, applies to a flattened version of the array.
-        dtype : {dtype}, optional
-            Datatype for the intermediary computation. If not
-            given, the current dtype is used instead.
+    Parameters
+    ----------
+    axis : int, optional
+        Axis along which to perform the operation.
+        If None, applies to a flattened version of the array.
+    dtype : {dtype}, optional
+        Datatype for the intermediary computation.
+        If not given, the current dtype is used instead.
 
-        """
+    """
         m = self.mean(axis, dtype)
         if not axis:
             return (self - m)
@@ -2598,50 +2644,7 @@
             return (self - expand_dims(m,axis))
 
     def var(self, axis=None, dtype=None, out=None, ddof=0):
-        """a.var(axis=None, dtype=None, out=None, ddof=0) -> variance
-
-    Returns the variance of the array elements, a measure of the spread of a
-    distribution.  The variance is computed for the flattened array by default,
-    otherwise over the specified axis.
-
-    Parameters
-    ----------
-    axis : integer
-        Axis along which the variance is computed. The default is to
-        compute the variance of the flattened array.
-    dtype : data-type
-        Type to use in computing the variance. For arrays of integer type
-        the default is float32, for arrays of float types it is the same as
-        the array type.
-    out : ndarray
-        Alternative output array in which to place the result. It must have
-        the same shape as the expected output but the type will be cast if
-        necessary.
-    ddof : {0, integer},
-        Means Delta Degrees of Freedom.  The divisor used in calculation is
-        N - ddof.
-
-    Returns
-    -------
-    variance : The return type varies, see above.
-        A new array holding the result is returned unless out is specified,
-        in which case a reference to out is returned.
-
-    See Also
-    --------
-    std : standard deviation
-    mean: average
-
-    Notes
-    -----
-    The variance is the average of the squared deviations from the mean,
-    i.e.  var = mean(abs(x - x.mean())**2).  The mean is computed by
-    dividing by N-ddof, where N is the number of elements. The argument
-    ddof defaults to zero; for an unbiased estimate supply ddof=1. Note
-    that for complex numbers the absolute value is taken before squaring,
-    so that the result is always real and nonnegative.
-
-        """
+        ""
         # Easy case: nomask, business as usual
         if self._mask is nomask:
             return self._data.var(axis=axis, dtype=dtype, out=out, ddof=ddof)
@@ -2675,52 +2678,11 @@
                 out.__setmask__(dvar.mask)
             return out
         return dvar
+    var.__doc__ = np.var.__doc__
 
-    def std(self, axis=None, dtype=None, out=None, ddof=0):
-        """a.std(axis=None, dtype=None, out=None, ddof=0)
 
-    Returns the standard deviation of the array elements, a measure of the
-    spread of a distribution. The standard deviation is computed for the
-    flattened array by default, otherwise over the specified axis.
-
-    Parameters
-    ----------
-    axis : integer
-        Axis along which the standard deviation is computed. The default is
-        to compute the standard deviation of the flattened array.
-    dtype : type
-        Type to use in computing the standard deviation. For arrays of
-        integer type the default is float32, for arrays of float types it
-        is the same as the array type.
-    out : ndarray
-        Alternative output array in which to place the result. It must have
-        the same shape as the expected output but the type will be cast if
-        necessary.
-    ddof : {0, integer}
-        Means Delta Degrees of Freedom.  The divisor used in calculations
-        is N-ddof.
-
-    Returns
-    -------
-    standard deviation : The return type varies, see above.
-        A new array holding the result is returned unless out is specified,
-        in which case a reference to out is returned.
-
-    See Also
-    --------
-    var : variance
-    mean : average
-
-    Notes
-    -----
-    The standard deviation is the square root of the average of the squared
-    deviations from the mean, i.e. var = sqrt(mean(abs(x - x.mean())**2)).  The
-    computed standard deviation is computed by dividing by the number of
-    elements, N-ddof. The option ddof defaults to zero, that is, a biased
-    estimate. Note that for complex numbers std takes the absolute value before
-    squaring, so that the result is always real and nonnegative.
-
-    """
+    def std(self, axis=None, dtype=None, out=None, ddof=0):
+        ""
         dvar = self.var(axis=axis,dtype=dtype,out=out, ddof=ddof)
         if dvar is not masked:
             dvar = sqrt(dvar)
@@ -2728,6 +2690,7 @@
                 out **= 0.5
                 return out
         return dvar
+    std.__doc__ = np.std.__doc__
 
     #............................................
     def round(self, decimals=0, out=None):
@@ -2928,8 +2891,7 @@
 
     #............................................
     def min(self, axis=None, out=None, fill_value=None):
-        """a.min(axis=None, out=None, fill_value=None)
-
+        """
     Return the minimum along a given axis.
 
     Parameters
@@ -2938,11 +2900,11 @@
         Axis along which to operate.  By default, ``axis`` is None and the
         flattened input is used.
     out : array_like, optional
-        Alternative output array in which to place the result.  Must
-        be of the same shape and buffer length as the expected output.
+        Alternative output array in which to place the result.  Must be of
+        the same shape and buffer length as the expected output.
     fill_value : {var}, optional
         Value used to fill in the masked values.
-        If None, use the output of minimum_fill_value().
+        If None, use the output of `minimum_fill_value`.
 
     Returns
     -------
@@ -2950,6 +2912,11 @@
         New array holding the result.
         If ``out`` was specified, ``out`` is returned.
 
+    See Also
+    --------
+    minimum_fill_value
+        Returns the minimum filling value for a given datatype.
+
         """
         _mask = ndarray.__getattribute__(self, '_mask')
         newmask = _mask.all(axis=axis)
@@ -3008,6 +2975,11 @@
         New array holding the result.
         If ``out`` was specified, ``out`` is returned.
 
+    See Also
+    --------
+    maximum_fill_value
+        Returns the maximum filling value for a given datatype.
+
         """
         _mask = ndarray.__getattribute__(self, '_mask')
         newmask = _mask.all(axis=axis)
@@ -3214,6 +3186,14 @@
         return (_mareconstruct,
                 (self.__class__, self._baseclass, (0,), 'b', ),
                 self.__getstate__())
+    #
+    def __deepcopy__(self, memo={}):
+        from copy import deepcopy
+        copied = MaskedArray.__new__(type(self), self, copy=True)
+        memo[id(self)] = copied
+        for (k,v) in self.__dict__.iteritems():
+            copied.__dict__[k] = deepcopy(v, memo)
+        return copied
 
 
 def _mareconstruct(subtype, baseclass, baseshape, basetype,):
@@ -3314,6 +3294,8 @@
             mb = getmaskarray(b)
             m = logical_or.outer(ma, mb)
         result = self.ufunc.outer(filled(a), filled(b))
+        if not isinstance(result, MaskedArray):
+            result = result.view(MaskedArray)
         result._mask = m
         return result
 
@@ -3557,13 +3539,15 @@
     # ... all of them are True, and then check for dm.any()
 #    shrink = numpy.logical_or.reduce([getattr(a,'_shrinkmask',True) for a in arrays])
 #    if shrink and not dm.any():
-    if not dm.any():
+    if not dm.dtype.fields and not dm.any():
         data._mask = nomask
     else:
         data._mask = dm.reshape(d.shape)
     return data
 
 def count(a, axis = None):
+    if isinstance(a, MaskedArray):
+        return a.count(axis)
     return masked_array(a, copy=False).count(axis)
 count.__doc__ = MaskedArray.count.__doc__
 
@@ -3649,7 +3633,8 @@
     return
 
 def transpose(a, axes=None):
-    """Return a view of the array with dimensions permuted according to axes,
+    """
+    Return a view of the array with dimensions permuted according to axes,
     as a masked array.
 
     If ``axes`` is None (default), the output view has reversed
@@ -3953,7 +3938,8 @@
 #---- --- Pickling ---
 #####--------------------------------------------------------------------------
 def dump(a,F):
-    """Pickle the MaskedArray `a` to the file `F`.  `F` can either be
+    """
+    Pickle the MaskedArray `a` to the file `F`.  `F` can either be
     the handle of an exiting file, or a string representing a file
     name.
 
@@ -3963,15 +3949,16 @@
     return cPickle.dump(a,F)
 
 def dumps(a):
-    """Return a string corresponding to the pickling of the
-    MaskedArray.
+    """
+    Return a string corresponding to the pickling of the MaskedArray.
 
     """
     return cPickle.dumps(a)
 
 def load(F):
-    """Wrapper around ``cPickle.load`` which accepts either a
-    file-like object or a filename.
+    """
+    Wrapper around ``cPickle.load`` which accepts either a file-like object
+    or a filename.
 
     """
     if not hasattr(F, 'readline'):

Modified: branches/1.2.x/numpy/ma/extras.py
===================================================================
--- branches/1.2.x/numpy/ma/extras.py	2008-10-06 02:55:14 UTC (rev 5935)
+++ branches/1.2.x/numpy/ma/extras.py	2008-10-06 21:05:03 UTC (rev 5936)
@@ -415,7 +415,7 @@
 
     """
     def _median1D(data):
-        counts = filled(count(data, axis),0)
+        counts = filled(count(data),0)
         (idx, rmd) = divmod(counts, 2)
         if rmd:
             choice = slice(idx, idx+1)

Modified: branches/1.2.x/numpy/ma/mrecords.py
===================================================================
--- branches/1.2.x/numpy/ma/mrecords.py	2008-10-06 02:55:14 UTC (rev 5935)
+++ branches/1.2.x/numpy/ma/mrecords.py	2008-10-06 21:05:03 UTC (rev 5936)
@@ -16,23 +16,21 @@
 __author__ = "Pierre GF Gerard-Marchant"
 
 import sys
-import types
 
 import numpy as np
-from numpy import bool_, complex_, float_, int_, str_, object_, dtype, \
-    chararray, ndarray, recarray, record, array as narray
+from numpy import bool_, dtype, \
+    ndarray, recarray, array as narray
 import numpy.core.numerictypes as ntypes
-from numpy.core.records import find_duplicate, format_parser
 from numpy.core.records import fromarrays as recfromarrays, \
-    fromrecords as recfromrecords
+                               fromrecords as recfromrecords
 
 _byteorderconv = np.core.records._byteorderconv
 _typestr = ntypes._typestr
 
 import numpy.ma as ma
 from numpy.ma import MAError, MaskedArray, masked, nomask, masked_array,\
-    make_mask, mask_or, getdata, getmask, getmaskarray, filled, \
-    default_fill_value, masked_print_option
+                     getdata, getmaskarray, filled
+
 _check_fill_value = ma.core._check_fill_value
 
 import warnings
@@ -153,10 +151,9 @@
         return self
     #......................................................
     def __array_finalize__(self,obj):
-        MaskedArray._update_from(self,obj)
         # Make sure we have a _fieldmask by default ..
-        _fieldmask = getattr(obj, '_fieldmask', None)
-        if _fieldmask is None:
+        _mask = getattr(obj, '_mask', None)
+        if _mask is None:
             objmask = getattr(obj, '_mask', nomask)
             _dtype = ndarray.__getattribute__(self,'dtype')
             if objmask is nomask:
@@ -165,15 +162,15 @@
                 mdescr = ma.make_mask_descr(_dtype)
                 _mask = narray([tuple([m]*len(mdescr)) for m in objmask],
                                dtype=mdescr).view(recarray)
-        else:
-            _mask = _fieldmask
         # Update some of the attributes
-        _locdict = self.__dict__
-        if _locdict['_baseclass'] == ndarray:
-            _locdict['_baseclass'] = recarray
-        _locdict.update(_mask=_mask, _fieldmask=_mask)
+        _dict = self.__dict__
+        _dict.update(_mask=_mask, _fieldmask=_mask)
+        self._update_from(obj)
+        if _dict['_baseclass'] == ndarray:
+            _dict['_baseclass'] = recarray
         return
 
+
     def _getdata(self):
         "Returns the data as a recarray."
         return ndarray.view(self,recarray)
@@ -250,7 +247,6 @@
             # Get the list of names ......
             fielddict = ndarray.__getattribute__(self,'dtype').fields or {}
             # Check the attribute
-#####            _localdict = self.__dict__
             if attr not in fielddict:
                 return ret
             if newattr:         # We just added this one
@@ -284,8 +280,8 @@
         """Returns all the fields sharing the same fieldname base.
 The fieldname base is either `_data` or `_mask`."""
         _localdict = self.__dict__
-        _mask = _localdict['_fieldmask']
-        _data = self._data
+        _mask = ndarray.__getattribute__(self,'_mask')
+        _data = ndarray.view(self, _localdict['_baseclass'])
         # We want a field ........
         if isinstance(indx, basestring):
             #!!!: Make sure _sharedmask is True to propagate back to _fieldmask
@@ -473,7 +469,7 @@
                            dtype=dtype, shape=shape, formats=formats,
                            names=names, titles=titles, aligned=aligned,
                            byteorder=byteorder).view(mrecarray)
-    _array._fieldmask.flat = zip(*masklist)
+    _array._mask.flat = zip(*masklist)
     if fill_value is not None:
         _array.fill_value = fill_value
     return _array
@@ -507,13 +503,17 @@
     mask : {nomask, sequence}, optional.
         External mask to apply on the data.
 
-*Notes*:
+    Notes
+    -----
     Lists of tuples should be preferred over lists of lists for faster processing.
     """
     # Grab the initial _fieldmask, if needed:
     _fieldmask = getattr(reclist, '_fieldmask', None)
     # Get the list of records.....
-    nfields = len(reclist[0])
+    try:
+        nfields = len(reclist[0])
+    except TypeError:
+        nfields = len(reclist[0].dtype)
     if isinstance(reclist, ndarray):
         # Make sure we don't have some hidden mask
         if isinstance(reclist,MaskedArray):
@@ -656,7 +656,7 @@
 set to 'fi', where `i` is the number of existing fields.
     """
     _data = mrecord._data
-    _mask = mrecord._fieldmask
+    _mask = mrecord._mask
     if newfieldname is None or newfieldname in reserved_fields:
         newfieldname = 'f%i' % len(_data.dtype)
     newfield = ma.array(newfield)

Modified: branches/1.2.x/numpy/ma/tests/test_core.py
===================================================================
--- branches/1.2.x/numpy/ma/tests/test_core.py	2008-10-06 02:55:14 UTC (rev 5935)
+++ branches/1.2.x/numpy/ma/tests/test_core.py	2008-10-06 21:05:03 UTC (rev 5936)
@@ -60,15 +60,15 @@
         x = masked_array(0, mask=False)
         assert_equal(str(x), '0')
         x = array(0, mask=1)
-        assert(x.filled().dtype is x._data.dtype)
+        self.failUnless(x.filled().dtype is x._data.dtype)
 
 
     def test_basic1d(self):
         "Test of basic array creation and properties in 1 dimension."
         (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
-        assert(not isMaskedArray(x))
-        assert(isMaskedArray(xm))
-        assert((xm-ym).filled(0).any())
+        self.failUnless(not isMaskedArray(x))
+        self.failUnless(isMaskedArray(xm))
+        self.failUnless((xm-ym).filled(0).any())
         fail_if_equal(xm.mask.astype(int_), ym.mask.astype(int_))
         s = x.shape
         assert_equal(np.shape(xm), s)
@@ -92,8 +92,8 @@
             ym.shape = s
             xf.shape = s
             #
-            assert(not isMaskedArray(x))
-            assert(isMaskedArray(xm))
+            self.failUnless(not isMaskedArray(x))
+            self.failUnless(isMaskedArray(xm))
             assert_equal(shape(xm), s)
             assert_equal(xm.shape, s)
             assert_equal( xm.size , reduce(lambda x,y:x*y, s))
@@ -132,6 +132,15 @@
         assert_array_equal(z,[1,1,0,0])
         assert_array_equal(z.mask,[False,True,False,False])
 
+    def test_concatenate_flexible(self):
+        "Tests the concatenation on flexible arrays."
+        data = masked_array(zip(np.random.rand(10),
+                                np.arange(10)),
+                            dtype=[('a',float),('b',int)])
+        #
+        test = concatenate([data[:5], data[5:]])
+        assert_equal_records(test, data)
+
     def test_creation_ndmin(self):
         "Check the use of ndmin"
         x = array([1,2,3],mask=[1,0,0], ndmin=2)
@@ -168,15 +177,17 @@
         x.mask = nomask
         data = array((x,x[::-1]))
         assert_equal(data, [[0,1,2,3,4],[4,3,2,1,0]])
-        assert(data.mask is nomask)
+        self.failUnless(data.mask is nomask)
 
     def test_asarray(self):
         (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
         xm.fill_value = -9999
+        xm._hardmask = True
         xmm = asarray(xm)
         assert_equal(xmm._data, xm._data)
         assert_equal(xmm._mask, xm._mask)
         assert_equal(xmm.fill_value, xm.fill_value)
+        assert_equal(xmm._hardmask, xm._hardmask)
 
     def test_fix_invalid(self):
         "Checks fix_invalid."
@@ -189,8 +200,8 @@
         "Test of masked element"
         x = arange(6)
         x[1] = masked
-        assert(str(masked) ==  '--')
-        assert(x[1] is masked)
+        self.failUnless(str(masked) ==  '--')
+        self.failUnless(x[1] is masked)
         assert_equal(filled(x[1], 0), 0)
         # don't know why these should raise an exception...
         #self.failUnlessRaises(Exception, lambda x,y: x+y, masked, masked)
@@ -204,12 +215,12 @@
         x = (1,2,3,4,5)
         a[0] = x
         assert_equal(a[0], x)
-        assert(a[0] is x)
+        self.failUnless(a[0] is x)
         #
         import datetime
         dt = datetime.datetime.now()
         a[0] = dt
-        assert(a[0] is dt)
+        self.failUnless(a[0] is dt)
 
 
     def test_indexing(self):
@@ -268,39 +279,39 @@
         n = [0,0,1,0,0]
         m = make_mask(n)
         m2 = make_mask(m)
-        assert(m is m2)
+        self.failUnless(m is m2)
         m3 = make_mask(m, copy=1)
-        assert(m is not m3)
+        self.failUnless(m is not m3)
 
         warnings.simplefilter('ignore', DeprecationWarning)
         x1 = np.arange(5)
         y1 = array(x1, mask=m)
-        #assert( y1._data is x1)
+        #self.failUnless( y1._data is x1)
         assert_equal(y1._data.__array_interface__, x1.__array_interface__)
-        assert( allequal(x1,y1.raw_data()))
-        #assert( y1.mask is m)
+        self.failUnless( allequal(x1,y1.raw_data()))
+        #self.failUnless( y1.mask is m)
         assert_equal(y1._mask.__array_interface__, m.__array_interface__)
         warnings.simplefilter('default', DeprecationWarning)
 
         y1a = array(y1)
-        #assert( y1a.raw_data() is y1.raw_data())
-        assert( y1a._data.__array_interface__ == y1._data.__array_interface__)
-        assert( y1a.mask is y1.mask)
+        #self.failUnless( y1a.raw_data() is y1.raw_data())
+        self.failUnless( y1a._data.__array_interface__ == y1._data.__array_interface__)
+        self.failUnless( y1a.mask is y1.mask)
 
         y2 = array(x1, mask=m)
-        #assert( y2.raw_data() is x1)
-        assert (y2._data.__array_interface__ == x1.__array_interface__)
-        #assert( y2.mask is m)
-        assert (y2._mask.__array_interface__ == m.__array_interface__)
-        assert( y2[2] is masked)
+        #self.failUnless( y2.raw_data() is x1)
+        self.failUnless(y2._data.__array_interface__ == x1.__array_interface__)
+        #self.failUnless( y2.mask is m)
+        self.failUnless(y2._mask.__array_interface__ == m.__array_interface__)
+        self.failUnless( y2[2] is masked)
         y2[2] = 9
-        assert( y2[2] is not masked)
-        #assert( y2.mask is not m)
-        assert (y2._mask.__array_interface__ != m.__array_interface__)
-        assert( allequal(y2.mask, 0))
+        self.failUnless( y2[2] is not masked)
+        #self.failUnless( y2.mask is not m)
+        self.failUnless(y2._mask.__array_interface__ != m.__array_interface__)
+        self.failUnless( allequal(y2.mask, 0))
 
         y3 = array(x1*1.0, mask=m)
-        assert(filled(y3).dtype is (x1*1.0).dtype)
+        self.failUnless(filled(y3).dtype is (x1*1.0).dtype)
 
         x4 = arange(4)
         x4[2] = masked
@@ -330,6 +341,24 @@
         assert_not_equal(y._mask.ctypes.data, x._mask.ctypes.data)
 
 
+    def test_deepcopy(self):
+        from copy import deepcopy
+        a = array([0,1,2], mask=[False,True,False])
+        copied = deepcopy(a)
+        assert_equal(copied.mask, a.mask)
+        assert_not_equal(id(a._mask), id(copied._mask))
+        #
+        copied[1] = 1
+        assert_equal(copied.mask,[0,0,0])
+        assert_equal(a.mask, [0,1,0])
+        #
+        copied = deepcopy(a)
+        assert_equal(copied.mask, a.mask)
+        copied.mask[1] = False
+        assert_equal(copied.mask,[0,0,0])
+        assert_equal(a.mask, [0,1,0])
+
+
     def test_pickling(self):
         "Tests pickling"
         import cPickle
@@ -345,7 +374,7 @@
         a_pickled = cPickle.loads(a.dumps())
         assert_equal(a_pickled._mask, a._mask)
         assert_equal(a_pickled, a)
-        assert(isinstance(a_pickled._data,np.matrix))
+        self.failUnless(isinstance(a_pickled._data,np.matrix))
 
 
     def test_single_element_subscript(self):
@@ -372,7 +401,7 @@
         a = array([1,2,3],mask=[1,0,0])
         self.assertRaises(TypeError, lambda:float(a))
         assert_equal(float(a[-1]), 3.)
-        assert(np.isnan(float(a[0])))
+        self.failUnless(np.isnan(float(a[0])))
         self.assertRaises(TypeError, int, a)
         assert_equal(int(a[-1]), 3)
         self.assertRaises(MAError, lambda:int(a[0]))
@@ -546,11 +575,11 @@
         "Tests some scalar arithmetics on MaskedArrays."
         # Masked singleton should remain masked no matter what
         xm = array(0, mask=1)
-        assert((1/array(0)).mask)
-        assert((1 + xm).mask)
-        assert((-xm).mask)
-        assert(maximum(xm, xm).mask)
-        assert(minimum(xm, xm).mask)
+        self.failUnless((1/array(0)).mask)
+        self.failUnless((1 + xm).mask)
+        self.failUnless((-xm).mask)
+        self.failUnless(maximum(xm, xm).mask)
+        self.failUnless(minimum(xm, xm).mask)
 
     def test_arithmetic_with_masked_singleton(self):
         "Checks that there's no collapsing to masked"
@@ -604,7 +633,7 @@
     def test_count_func (self):
         "Tests count"
         ott = array([0.,1.,2.,3.], mask=[1,0,0,0])
-        assert( isinstance(count(ott), int))
+        self.failUnless( isinstance(count(ott), int))
         assert_equal(3, count(ott))
         assert_equal(1, count(1))
         assert_equal(0, array(1,mask=[1]))
@@ -638,6 +667,23 @@
         x[-1,-1] = masked
         assert_equal(maximum(x), 2)
 
+    def test_minimummaximum_func(self):
+        a = np.ones((2,2))
+        aminimum = minimum(a,a)
+        self.failUnless(isinstance(aminimum, MaskedArray))
+        assert_equal(aminimum, np.minimum(a,a))
+        #
+        aminimum = minimum.outer(a,a)
+        self.failUnless(isinstance(aminimum, MaskedArray))
+        assert_equal(aminimum, np.minimum.outer(a,a))
+        #
+        amaximum = maximum(a,a)
+        self.failUnless(isinstance(amaximum, MaskedArray))
+        assert_equal(amaximum, np.maximum(a,a))
+        #
+        amaximum = maximum.outer(a,a)
+        self.failUnless(isinstance(amaximum, MaskedArray))
+        assert_equal(amaximum, np.maximum.outer(a,a))
 
     def test_minmax_funcs_with_output(self):
         "Tests the min/max functions with explicit outputs"
@@ -651,11 +697,11 @@
             # Use the np version
             nout = np.empty((4,), dtype=int)
             result = npfunc(xm,axis=0,out=nout)
-            assert(result is nout)
+            self.failUnless(result is nout)
             # Use the ma version
             nout.fill(-999)
             result = mafunc(xm,axis=0,out=nout)
-            assert(result is nout)
+            self.failUnless(result is nout)
 
 
     def test_minmax_methods(self):
@@ -663,22 +709,22 @@
         (_, _, _, _, _, xm, _, _, _, _) = self.d
         xm.shape = (xm.size,)
         assert_equal(xm.max(), 10)
-        assert(xm[0].max() is masked)
-        assert(xm[0].max(0) is masked)
-        assert(xm[0].max(-1) is masked)
+        self.failUnless(xm[0].max() is masked)
+        self.failUnless(xm[0].max(0) is masked)
+        self.failUnless(xm[0].max(-1) is masked)
         assert_equal(xm.min(), -10.)
-        assert(xm[0].min() is masked)
-        assert(xm[0].min(0) is masked)
-        assert(xm[0].min(-1) is masked)
+        self.failUnless(xm[0].min() is masked)
+        self.failUnless(xm[0].min(0) is masked)
+        self.failUnless(xm[0].min(-1) is masked)
         assert_equal(xm.ptp(), 20.)
-        assert(xm[0].ptp() is masked)
-        assert(xm[0].ptp(0) is masked)
-        assert(xm[0].ptp(-1) is masked)
+        self.failUnless(xm[0].ptp() is masked)
+        self.failUnless(xm[0].ptp(0) is masked)
+        self.failUnless(xm[0].ptp(-1) is masked)
         #
         x = array([1,2,3], mask=True)
-        assert(x.min() is masked)
-        assert(x.max() is masked)
-        assert(x.ptp() is masked)
+        self.failUnless(x.min() is masked)
+        self.failUnless(x.max() is masked)
+        self.failUnless(x.ptp() is masked)
     #........................
     def test_addsumprod (self):
         "Tests add, sum, product."
@@ -751,13 +797,13 @@
             output.fill(-9999)
             result = npfunc(xm, axis=0,out=output)
             # ... the result should be the given output
-            assert(result is output)
+            self.failUnless(result is output)
             assert_equal(result, xmmeth(axis=0, out=output))
             #
             output = empty(4, dtype=int)
             result = xmmeth(axis=0, out=output)
-            assert(result is output)
-            assert(output[0] is masked)
+            self.failUnless(result is output)
+            self.failUnless(output[0] is masked)
 
 #------------------------------------------------------------------------------
 
@@ -791,8 +837,8 @@
         assert_equal(xs._data, [0,10,2,3,40])
         #assert_equal(xh.mask.ctypes._data, m.ctypes._data)
         assert_equal(xs.mask, [0,0,0,1,0])
-        assert(xh._hardmask)
-        assert(not xs._hardmask)
+        self.failUnless(xh._hardmask)
+        self.failUnless(not xs._hardmask)
         xh[1:4] = [10,20,30]
         xs[1:4] = [10,20,30]
         assert_equal(xh._data, [0,10,20,3,4])
@@ -885,39 +931,39 @@
         ndtype = [('a',int),('b',float),('c',"|S3")]
         # A check on a list should return a single record
         fval = _check_fill_value([-999,-999.9,"???"], ndtype)
-        assert(isinstance(fval,ndarray))
+        self.failUnless(isinstance(fval,ndarray))
         assert_equal(fval.item(), [-999,-999.9,"???"])
         # A check on Non should output the defaults
         fval = _check_fill_value(None, ndtype)
-        assert(isinstance(fval,ndarray))
+        self.failUnless(isinstance(fval,ndarray))
         assert_equal(fval.item(), [default_fill_value(0),
                                    default_fill_value(0.),
                                    default_fill_value("0")])
         #.....Using a flexible type as fill_value should work
         fill_val = np.array((-999,-999.9,"???"),dtype=ndtype)
         fval = _check_fill_value(fill_val, ndtype)
-        assert(isinstance(fval,ndarray))
+        self.failUnless(isinstance(fval,ndarray))
         assert_equal(fval.item(), [-999,-999.9,"???"])
         #.....Using a flexible type w/ a different type shouldn't matter
         fill_val = np.array((-999,-999.9,"???"),
                             dtype=[("A",int),("B",float),("C","|S3")])
         fval = _check_fill_value(fill_val, ndtype)
-        assert(isinstance(fval,ndarray))
+        self.failUnless(isinstance(fval,ndarray))
         assert_equal(fval.item(), [-999,-999.9,"???"])
         #.....Using an object-array shouldn't matter either
         fill_value =  np.array((-999,-999.9,"???"), dtype=object)
         fval = _check_fill_value(fill_val, ndtype)
-        assert(isinstance(fval,ndarray))
+        self.failUnless(isinstance(fval,ndarray))
         assert_equal(fval.item(), [-999,-999.9,"???"])
         #
         fill_value =  np.array((-999,-999.9,"???"))
         fval = _check_fill_value(fill_val, ndtype)
-        assert(isinstance(fval,ndarray))
+        self.failUnless(isinstance(fval,ndarray))
         assert_equal(fval.item(), [-999,-999.9,"???"])
         #.....One-field-only flexible type should work as well
         ndtype = [("a",int)]
         fval = _check_fill_value(-999, ndtype)
-        assert(isinstance(fval,ndarray))
+        self.failUnless(isinstance(fval,ndarray))
         assert_equal(fval.item(), (-999,))
 
 
@@ -1041,8 +1087,8 @@
     def test_reduce(self):
         "Tests reduce on MaskedArrays."
         a = self.d[0]
-        assert(not alltrue(a,axis=0))
-        assert(sometrue(a,axis=0))
+        self.failUnless(not alltrue(a,axis=0))
+        self.failUnless(sometrue(a,axis=0))
         assert_equal(sum(a[:3],axis=0), 0)
         assert_equal(product(a,axis=0), 0)
         assert_equal(add.reduce(a), pi)
@@ -1055,8 +1101,8 @@
         assert_equal(amask.min(), 5)
         assert_equal(amask.max(0), a.max(0))
         assert_equal(amask.min(0), [5,6,7,8])
-        assert(amask.max(1)[0].mask)
-        assert(amask.min(1)[0].mask)
+        self.failUnless(amask.max(1)[0].mask)
+        self.failUnless(amask.min(1)[0].mask)
 
 
 #------------------------------------------------------------------------------
@@ -1309,18 +1355,18 @@
         store = empty(1, dtype=bool)
         full = array([1,2,3], mask=True)
         #
-        assert(full.all() is masked)
+        self.failUnless(full.all() is masked)
         full.all(out=store)
-        assert(store)
-        assert(store._mask, True)
-        assert(store is not masked)
+        self.failUnless(store)
+        self.failUnless(store._mask, True)
+        self.failUnless(store is not masked)
         #
         store = empty(1, dtype=bool)
-        assert(full.any() is masked)
+        self.failUnless(full.any() is masked)
         full.any(out=store)
-        assert(not store)
-        assert(store._mask, True)
-        assert(store is not masked)
+        self.failUnless(not store)
+        self.failUnless(store._mask, True)
+        self.failUnless(store is not masked)
 
 
     def test_argmax_argmin(self):
@@ -1408,7 +1454,7 @@
         a = array(np.matrix([1,2,3,4]), mask=[0,0,0,0])
         b = a.compressed()
         assert_equal(b,a)
-        assert(isinstance(b,np.matrix))
+        self.failUnless(isinstance(b,np.matrix))
         a[0,0] = masked
         b = a.compressed()
         assert_equal(b, [[2,3,4]])
@@ -1436,12 +1482,12 @@
         n = [0,0,0,1,1]
         m = make_mask(n)
         x = array(d, mask = m)
-        assert( x[3] is masked)
-        assert( x[4] is masked)
+        self.failUnless( x[3] is masked)
+        self.failUnless( x[4] is masked)
         x[[1,4]] = [10,40]
-#        assert( x.mask is not m)
-        assert( x[3] is masked)
-        assert( x[4] is not masked)
+#        self.failUnless( x.mask is not m)
+        self.failUnless( x[3] is masked)
+        self.failUnless( x[4] is not masked)
         assert_equal(x, [0,10,2,-1,40])
         #
         x = masked_array(arange(10), mask=[1,0,0,0,0]*2)
@@ -1561,7 +1607,7 @@
         #
         x = [1,4,2,3]
         sortedx = sort(x)
-        assert(not isinstance(sorted, MaskedArray))
+        self.failUnless(not isinstance(sorted, MaskedArray))
         #
         x = array([0,1,-1,-2,2], mask=nomask, dtype=np.int8)
         sortedx = sort(x, endwith=False)
@@ -1621,7 +1667,7 @@
         assert_equal(data.squeeze(), [1,2,3])
         assert_equal(data.squeeze()._mask, [1,1,1])
         data = masked_array([[1]], mask=True)
-        assert(data.squeeze() is masked)
+        self.failUnless(data.squeeze() is masked)
 
 
     def test_swapaxes(self):
@@ -1668,8 +1714,8 @@
         x = array(np.arange(12))
         x[[1,-2]] = masked
         xlist = x.tolist()
-        assert(xlist[1] is None)
-        assert(xlist[-2] is None)
+        self.failUnless(xlist[1] is None)
+        self.failUnless(xlist[-2] is None)
         #
         x.shape = (3,4)
         xlist = x.tolist()
@@ -1784,12 +1830,12 @@
             output.fill(-9999)
             result = npfunc(xm, axis=0,out=output)
             # ... the result should be the given output
-            assert(result is output)
+            self.failUnless(result is output)
             assert_equal(result, xmmeth(axis=0, out=output))
             #
             output = empty((3,4), dtype=int)
             result = xmmeth(axis=0, out=output)
-            assert(result is output)
+            self.failUnless(result is output)
 
 
     def test_ptp(self):
@@ -1844,31 +1890,31 @@
         x = array(arange(10), mask=True)
         for methodname in ('var', 'std'):
             method = getattr(x,methodname)
-            assert(method() is masked)
-            assert(method(0) is masked)
-            assert(method(-1) is masked)
+            self.failUnless(method() is masked)
+            self.failUnless(method(0) is masked)
+            self.failUnless(method(-1) is masked)
             # Using a masked array as explicit output
             _ = method(out=mout)
-            assert(mout is not masked)
+            self.failUnless(mout is not masked)
             assert_equal(mout.mask, True)
             # Using a ndarray as explicit output
             _ = method(out=nout)
-            assert(np.isnan(nout))
+            self.failUnless(np.isnan(nout))
         #
         x = array(arange(10), mask=True)
         x[-1] = 9
         for methodname in ('var', 'std'):
             method = getattr(x,methodname)
-            assert(method(ddof=1) is masked)
-            assert(method(0, ddof=1) is masked)
-            assert(method(-1, ddof=1) is masked)
+            self.failUnless(method(ddof=1) is masked)
+            self.failUnless(method(0, ddof=1) is masked)
+            self.failUnless(method(-1, ddof=1) is masked)
             # Using a masked array as explicit output
             _ = method(out=mout, ddof=1)
-            assert(mout is not masked)
+            self.failUnless(mout is not masked)
             assert_equal(mout.mask, True)
             # Using a ndarray as explicit output
             _ = method(out=nout, ddof=1)
-            assert(np.isnan(nout))
+            self.failUnless(np.isnan(nout))
 
 #------------------------------------------------------------------------------
 
@@ -1986,7 +2032,7 @@
         else:
             raise AssertionError("Should have failed...")
         test = masked_equal(a,1)
-        assert(test.mask, [0,1,0,0,0,0,0,0,0,0])
+        assert_equal(test.mask, [0,1,0,0,0,0,0,0,0,0])
 
 
     def test_masked_otherfunctions(self):
@@ -2032,24 +2078,24 @@
         output.fill(-9999)
         result = np.round(xm, decimals=2,out=output)
         # ... the result should be the given output
-        assert(result is output)
+        self.failUnless(result is output)
         assert_equal(result, xm.round(decimals=2, out=output))
         #
         output = empty((3,4), dtype=float)
         result = xm.round(decimals=2, out=output)
-        assert(result is output)
+        self.failUnless(result is output)
 
 
     def test_identity(self):
         a = identity(5)
-        assert(isinstance(a, MaskedArray))
+        self.failUnless(isinstance(a, MaskedArray))
         assert_equal(a, np.identity(5))
 
 
     def test_power(self):
         x = -1.1
         assert_almost_equal(power(x,2.), 1.21)
-        assert(power(x,masked) is masked)
+        self.failUnless(power(x,masked) is masked)
         x = array([-1.1,-1.1,1.1,1.1,0.])
         b = array([0.5,2.,0.5,2.,-1.], mask=[0,0,0,0,1])
         y = power(x,b)
@@ -2182,7 +2228,7 @@
         store = empty(4, dtype=int)
         chosen = choose([2, 3, 1, 0], choices, out=store)
         assert_equal(store, array([20, 31, 12, 3]))
-        assert(store is chosen)
+        self.failUnless(store is chosen)
         # Check with some masked indices + out
         store = empty(4, dtype=int)
         indices_ = array([2, 3, 1, 0], mask=[1,0,0,1])
@@ -2204,25 +2250,25 @@
         # Try the default
         b = a.reshape((5,2))
         assert_equal(b.shape, (5,2))
-        assert(b.flags['C'])
+        self.failUnless(b.flags['C'])
         # Try w/ arguments as list instead of tuple
         b = a.reshape(5,2)
         assert_equal(b.shape, (5,2))
-        assert(b.flags['C'])
+        self.failUnless(b.flags['C'])
         # Try w/ order
         b = a.reshape((5,2), order='F')
         assert_equal(b.shape, (5,2))
-        assert(b.flags['F'])
+        self.failUnless(b.flags['F'])
         # Try w/ order
         b = a.reshape(5,2, order='F')
         assert_equal(b.shape, (5,2))
-        assert(b.flags['F'])
+        self.failUnless(b.flags['F'])
         #
         c = np.reshape(a, (2,5))
-        assert(isinstance(c, MaskedArray))
+        self.failUnless(isinstance(c, MaskedArray))
         assert_equal(c.shape, (2,5))
-        assert(c[0,0] is masked)
-        assert(c.flags['C'])
+        self.failUnless(c[0,0] is masked)
+        self.failUnless(c.flags['C'])
 
 #------------------------------------------------------------------------------
 
@@ -2307,8 +2353,52 @@
         assert_equal(getmaskarray(test),
                      np.array([(1, 1) , (1, 1), (1, 1)],
                               dtype=[('a', '|b1'), ('b', '|b1')]))
+    #
+    def test_view(self):
+        "Test view w/ flexible dtype"
+        iterator = zip(np.arange(10), np.random.rand(10))
+        data = np.array(iterator)
+        a = array(iterator, dtype=[('a',float),('b',float)])
+        a.mask[0] = (1,0)
+        controlmask = np.array([1]+19*[0], dtype=bool)
+        #
+        test = a.view(float)
+        assert_equal(test, data.ravel())
+        assert_equal(test.mask, controlmask)
+        #
+        test = a.view((float,2))
+        assert_equal(test, data)
+        assert_equal(test.mask, controlmask.reshape(-1,2))
+        #
+        test = a.view([('A',float),('B',float)])
+        assert_equal(test.mask.dtype.names, ('A', 'B'))
+        assert_equal(test['A'], a['a'])
+        assert_equal(test['B'], a['b'])
+        #
+        test = a.view(np.ndarray)
+        assert_equal(test, a._data)
+        #
+        test = a.view((float,2), np.matrix)
+        assert_equal(test, data)
+        self.failUnless(isinstance(test, np.matrix))
+    #
+    def test_getitem(self):
+        ndtype = [('a',float), ('b',float)]
+        a = array(zip(np.random.rand(10),np.arange(10)), dtype=ndtype)
+        a.mask = np.array(zip([0,0,0,0,0,0,0,0,1,1],
+                              [1,0,0,0,0,0,0,0,1,0]),
+                          dtype=[('a',bool),('b',bool)])
+        # No mask
+        self.failUnless(isinstance(a[1], np.void))
+        # One element masked
+        self.failUnless(isinstance(a[0], MaskedArray))
+        assert_equal_records(a[0]._data, a._data[0])
+        assert_equal_records(a[0]._mask, a._mask[0])
+        # All element masked
+        self.failUnless(isinstance(a[-2], MaskedArray))
+        assert_equal_records(a[-2]._data, a._data[-2])
+        assert_equal_records(a[-2]._mask, a._mask[-2])
 
-
 ###############################################################################
 #------------------------------------------------------------------------------
 if __name__ == "__main__":

Modified: branches/1.2.x/numpy/ma/tests/test_extras.py
===================================================================
--- branches/1.2.x/numpy/ma/tests/test_extras.py	2008-10-06 02:55:14 UTC (rev 5935)
+++ branches/1.2.x/numpy/ma/tests/test_extras.py	2008-10-06 21:05:03 UTC (rev 5936)
@@ -11,7 +11,7 @@
 __revision__ = "$Revision: 3473 $"
 __date__     = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $'
 
-import numpy
+import numpy as np
 from numpy.testing import TestCase, run_module_suite
 from numpy.ma.testutils import *
 from numpy.ma.core import *
@@ -26,7 +26,7 @@
         assert_equal(2.0, average(ott, weights=[1., 1., 2., 1.]))
         result, wts = average(ott, weights=[1.,1.,2.,1.], returned=1)
         assert_equal(2.0, result)
-        assert(wts == 4.0)
+        self.failUnless(wts == 4.0)
         ott[:] = masked
         assert_equal(average(ott,axis=0).mask, [True])
         ott = array([0.,1.,2.,3.], mask=[1,0,0,0])
@@ -104,7 +104,7 @@
         m = [1,0,0,0,0]
         d = masked_array(b,mask=m)
         c = mr_[d,0,0,d]
-        assert(isinstance(c,MaskedArray) or isinstance(c,core.MaskedArray))
+        self.failUnless(isinstance(c,MaskedArray) or isinstance(c,core.MaskedArray))
         assert_array_equal(c,[1,1,1,1,1,0,0,1,1,1,1,1])
         assert_array_equal(c.mask, mr_[m,0,0,m])
 
@@ -117,12 +117,12 @@
         b_1 = masked_array(a_1,mask=m_1)
         b_2 = masked_array(a_2,mask=m_2)
         d = mr_['1',b_1,b_2]  # append columns
-        assert(d.shape == (5,10))
+        self.failUnless(d.shape == (5,10))
         assert_array_equal(d[:,:5],b_1)
         assert_array_equal(d[:,5:],b_2)
         assert_array_equal(d.mask, np.r_['1',m_1,m_2])
         d = mr_[b_1,b_2]
-        assert(d.shape == (10,5))
+        self.failUnless(d.shape == (10,5))
         assert_array_equal(d[:5,:],b_1)
         assert_array_equal(d[5:,:],b_2)
         assert_array_equal(d.mask, np.r_[m_1,m_2])
@@ -158,14 +158,14 @@
         assert_equal(tmp[-3], slice(0,3,None))
         #
         tmp = notmasked_contiguous(a, 0)
-        assert(len(tmp[-1]) == 1)
-        assert(tmp[-2] is None)
+        self.failUnless(len(tmp[-1]) == 1)
+        self.failUnless(tmp[-2] is None)
         assert_equal(tmp[-3],tmp[-1])
-        assert(len(tmp[0]) == 2)
+        self.failUnless(len(tmp[0]) == 2)
         #
         tmp = notmasked_contiguous(a, 1)
         assert_equal(tmp[0][-1], slice(0,3,None))
-        assert(tmp[1] is None)
+        self.failUnless(tmp[1] is None)
         assert_equal(tmp[2][-1], slice(7,7,None))
         assert_equal(tmp[2][-2], slice(0,5,None))
 
@@ -205,12 +205,12 @@
         assert_equal(mask_rowcols(x,0).mask, [[1,1,1],[1,1,1],[0,0,0]] )
         assert_equal(mask_rowcols(x,1,).mask, [[1,1,0],[1,1,0],[1,1,0]] )
         x = array(x._data, mask=[[1,0,0],[0,1,0],[0,0,1]])
-        assert(mask_rowcols(x).all() is masked)
-        assert(mask_rowcols(x,0).all() is masked)
-        assert(mask_rowcols(x,1).all() is masked)
-        assert(mask_rowcols(x).mask.all())
-        assert(mask_rowcols(x,0).mask.all())
-        assert(mask_rowcols(x,1).mask.all())
+        self.failUnless(mask_rowcols(x).all() is masked)
+        self.failUnless(mask_rowcols(x,0).all() is masked)
+        self.failUnless(mask_rowcols(x,1).all() is masked)
+        self.failUnless(mask_rowcols(x).mask.all())
+        self.failUnless(mask_rowcols(x,0).mask.all())
+        self.failUnless(mask_rowcols(x,1).mask.all())
     #
     def test_dot(self):
         "Tests dot product"
@@ -332,25 +332,36 @@
     def test_2d(self):
         "Tests median w/ 2D"
         (n,p) = (101,30)
-        x = masked_array(numpy.linspace(-1.,1.,n),)
+        x = masked_array(np.linspace(-1.,1.,n),)
         x[:10] = x[-10:] = masked
-        z = masked_array(numpy.empty((n,p), dtype=numpy.float_))
+        z = masked_array(np.empty((n,p), dtype=float))
         z[:,0] = x[:]
-        idx = numpy.arange(len(x))
+        idx = np.arange(len(x))
         for i in range(1,p):
-            numpy.random.shuffle(idx)
+            np.random.shuffle(idx)
             z[:,i] = x[idx]
         assert_equal(median(z[:,0]), 0)
-        assert_equal(median(z), numpy.zeros((p,)))
+        assert_equal(median(z), 0)
+        assert_equal(median(z, axis=0), np.zeros(p))
+        assert_equal(median(z.T, axis=1), np.zeros(p))
     #
+    def test_2d_waxis(self):
+        "Tests median w/ 2D arrays and different axis."
+        x = masked_array(np.arange(30).reshape(10,3))
+        x[:3] = x[-3:] = masked
+        assert_equal(median(x), 14.5)
+        assert_equal(median(x, axis=0), [13.5,14.5,15.5])
+        assert_equal(median(x,axis=1), [0,0,0,10,13,16,19,0,0,0])
+        assert_equal(median(x,axis=1).mask, [1,1,1,0,0,0,0,1,1,1])
+    #
     def test_3d(self):
         "Tests median w/ 3D"
-        x = numpy.ma.arange(24).reshape(3,4,2)
+        x = np.ma.arange(24).reshape(3,4,2)
         x[x%3==0] = masked
         assert_equal(median(x,0), [[12,9],[6,15],[12,9],[18,15]])
         x.shape = (4,3,2)
         assert_equal(median(x,0),[[99,10],[11,99],[13,14]])
-        x = numpy.ma.arange(24).reshape(4,3,2)
+        x = np.ma.arange(24).reshape(4,3,2)
         x[x%5==0] = masked
         assert_equal(median(x,0), [[12,10],[8,9],[16,17]])
 
@@ -483,9 +494,9 @@
     def test_polyfit(self):
         "Tests polyfit"
         # On ndarrays
-        x = numpy.random.rand(10)
-        y = numpy.random.rand(20).reshape(-1,2)
-        assert_almost_equal(polyfit(x,y,3),numpy.polyfit(x,y,3))
+        x = np.random.rand(10)
+        y = np.random.rand(20).reshape(-1,2)
+        assert_almost_equal(polyfit(x,y,3),np.polyfit(x,y,3))
         # ON 1D maskedarrays
         x = x.view(MaskedArray)
         x[0] = masked
@@ -493,17 +504,17 @@
         y[0,0] = y[-1,-1] = masked
         #
         (C,R,K,S,D) = polyfit(x,y[:,0],3,full=True)
-        (c,r,k,s,d) = numpy.polyfit(x[1:], y[1:,0].compressed(), 3, full=True)
+        (c,r,k,s,d) = np.polyfit(x[1:], y[1:,0].compressed(), 3, full=True)
         for (a,a_) in zip((C,R,K,S,D),(c,r,k,s,d)):
             assert_almost_equal(a, a_)
         #
         (C,R,K,S,D) = polyfit(x,y[:,-1],3,full=True)
-        (c,r,k,s,d) = numpy.polyfit(x[1:-1], y[1:-1,-1], 3, full=True)
+        (c,r,k,s,d) = np.polyfit(x[1:-1], y[1:-1,-1], 3, full=True)
         for (a,a_) in zip((C,R,K,S,D),(c,r,k,s,d)):
             assert_almost_equal(a, a_)
         #
         (C,R,K,S,D) = polyfit(x,y,3,full=True)
-        (c,r,k,s,d) = numpy.polyfit(x[1:-1], y[1:-1,:], 3, full=True)
+        (c,r,k,s,d) = np.polyfit(x[1:-1], y[1:-1,:], 3, full=True)
         for (a,a_) in zip((C,R,K,S,D),(c,r,k,s,d)):
             assert_almost_equal(a, a_)
 

Modified: branches/1.2.x/numpy/ma/tests/test_mrecords.py
===================================================================
--- branches/1.2.x/numpy/ma/tests/test_mrecords.py	2008-10-06 02:55:14 UTC (rev 5935)
+++ branches/1.2.x/numpy/ma/tests/test_mrecords.py	2008-10-06 21:05:03 UTC (rev 5936)
@@ -8,23 +8,19 @@
 __revision__ = "$Revision: 3473 $"
 __date__     = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $'
 
-import types
-
 import numpy as np
 from numpy import recarray
 from numpy.core.records import fromrecords as recfromrecords, \
-    fromarrays as recfromarrays
+                               fromarrays as recfromarrays
 
 import numpy.ma.testutils
 from numpy.ma.testutils import *
 
 import numpy.ma as ma
-from numpy.ma import masked, nomask, getdata, getmaskarray
+from numpy.ma import masked, nomask
 
-import numpy.ma.mrecords
-reload(numpy.ma.mrecords)
-from numpy.ma.mrecords import MaskedRecords, mrecarray,\
-    fromarrays, fromtextfile, fromrecords, addfield
+from numpy.ma.mrecords import MaskedRecords, mrecarray, fromarrays, \
+                              fromtextfile, fromrecords, addfield
 
 #..............................................................................
 class TestMRecords(TestCase):
@@ -207,8 +203,8 @@
     #
     def test_set_elements(self):
         base = self.base.copy()
-        mbase = base.view(mrecarray)
         # Set an element to mask .....................
+        mbase = base.view(mrecarray).copy()
         mbase[-2] = masked
         assert_equal(mbase._fieldmask.tolist(),
                      np.array([(0,0,0),(1,1,1),(0,0,0),(1,1,1),(1,1,1)],
@@ -268,16 +264,16 @@
         base = self.base.copy()
         mbase = base.view(mrecarray)
         mbase.harden_mask()
-        assert(mbase._hardmask)
+        self.failUnless(mbase._hardmask)
         mbase._mask = nomask
         assert_equal_records(mbase._mask, base._mask)
         mbase.soften_mask()
-        assert(not mbase._hardmask)
+        self.failUnless(not mbase._hardmask)
         mbase._mask = nomask
         # So, the mask of a field is no longer set to nomask...
         assert_equal_records(mbase._mask,
                              ma.make_mask_none(base.shape,base.dtype))
-        assert(ma.make_mask(mbase['b']._mask) is nomask)
+        self.failUnless(ma.make_mask(mbase['b']._mask) is nomask)
         assert_equal(mbase['a']._mask,mbase['b']._mask)
     #
     def test_pickling(self):
@@ -432,7 +428,6 @@
 'strings',4,-1e-10,,,1
 """
         import os
-        from datetime import datetime
         import tempfile
         (tmp_fd,tmp_fl) = tempfile.mkstemp()
         os.write(tmp_fd, fcontent)
@@ -440,7 +435,7 @@
         mrectxt = fromtextfile(tmp_fl, delimitor=',',varnames='ABCDEFG')
         os.remove(tmp_fl)
         #
-        assert(isinstance(mrectxt, MaskedRecords))
+        self.failUnless(isinstance(mrectxt, MaskedRecords))
         assert_equal(mrectxt.F, [1,1,1,1])
         assert_equal(mrectxt.E._mask, [1,1,1,1])
         assert_equal(mrectxt.C, [1,2,3.e+5,-1e-10])

Modified: branches/1.2.x/numpy/ma/tests/test_subclassing.py
===================================================================
--- branches/1.2.x/numpy/ma/tests/test_subclassing.py	2008-10-06 02:55:14 UTC (rev 5935)
+++ branches/1.2.x/numpy/ma/tests/test_subclassing.py	2008-10-06 21:05:03 UTC (rev 5936)
@@ -11,8 +11,6 @@
 __date__     = '$Date: 2007-10-29 17:18:13 +0200 (Mon, 29 Oct 2007) $'
 
 import numpy as np
-import numpy.core.numeric as numeric
-
 from numpy.testing import *
 from numpy.ma.testutils import *
 from numpy.ma.core import *
@@ -78,24 +76,24 @@
         m = [0,0,1,0,0]
         xsub = SubArray(x)
         xmsub = masked_array(xsub, mask=m)
-        assert isinstance(xmsub, MaskedArray)
+        self.failUnless(isinstance(xmsub, MaskedArray))
         assert_equal(xmsub._data, xsub)
-        assert isinstance(xmsub._data, SubArray)
+        self.failUnless(isinstance(xmsub._data, SubArray))
 
     def test_maskedarray_subclassing(self):
         "Tests subclassing MaskedArray"
         x = np.arange(5)
         mx = mmatrix(x,mask=[0,1,0,0,0])
-        assert isinstance(mx._data, np.matrix)
+        self.failUnless(isinstance(mx._data, np.matrix))
         "Tests masked_unary_operation"
-        assert isinstance(add(mx,mx), mmatrix)
-        assert isinstance(add(mx,x), mmatrix)
+        self.failUnless(isinstance(add(mx,mx), mmatrix))
+        self.failUnless(isinstance(add(mx,x), mmatrix))
         assert_equal(add(mx,x), mx+x)
-        assert isinstance(add(mx,mx)._data, np.matrix)
-        assert isinstance(add.outer(mx,mx), mmatrix)
+        self.failUnless(isinstance(add(mx,mx)._data, np.matrix))
+        self.failUnless(isinstance(add.outer(mx,mx), mmatrix))
         "Tests masked_binary_operation"
-        assert isinstance(hypot(mx,mx), mmatrix)
-        assert isinstance(hypot(mx,x), mmatrix)
+        self.failUnless(isinstance(hypot(mx,mx), mmatrix))
+        self.failUnless(isinstance(hypot(mx,x), mmatrix))
 
     def test_attributepropagation(self):
         x = array(arange(5), mask=[0]+[1]*4)
@@ -103,16 +101,16 @@
         ym = msubarray(x)
         #
         z = (my+1)
-        assert isinstance(z,MaskedArray)
-        assert not isinstance(z, MSubArray)
-        assert isinstance(z._data, SubArray)
+        self.failUnless(isinstance(z,MaskedArray))
+        self.failUnless(not isinstance(z, MSubArray))
+        self.failUnless(isinstance(z._data, SubArray))
         assert_equal(z._data.info, {})
         #
         z = (ym+1)
-        assert isinstance(z, MaskedArray)
-        assert isinstance(z, MSubArray)
-        assert isinstance(z._data, SubArray)
-        assert z._data.info['added'] > 0
+        self.failUnless(isinstance(z, MaskedArray))
+        self.failUnless(isinstance(z, MSubArray))
+        self.failUnless(isinstance(z._data, SubArray))
+        self.failUnless(z._data.info['added'] > 0)
         #
         ym._set_mask([1,0,0,0,1])
         assert_equal(ym._mask, [1,0,0,0,1])
@@ -121,7 +119,7 @@
         #
         xsub = subarray(x, info={'name':'x'})
         mxsub = masked_array(xsub)
-        assert hasattr(mxsub, 'info')
+        self.failUnless(hasattr(mxsub, 'info'))
         assert_equal(mxsub.info, xsub.info)
 
     def test_subclasspreservation(self):
@@ -132,22 +130,22 @@
         xsub = MSubArray(x, mask=m, info={'xsub':xinfo})
         #
         mxsub = masked_array(xsub, subok=False)
-        assert not isinstance(mxsub, MSubArray)
-        assert isinstance(mxsub, MaskedArray)
+        self.failUnless(not isinstance(mxsub, MSubArray))
+        self.failUnless(isinstance(mxsub, MaskedArray))
         assert_equal(mxsub._mask, m)
         #
         mxsub = asarray(xsub)
-        assert not isinstance(mxsub, MSubArray)
-        assert isinstance(mxsub, MaskedArray)
+        self.failUnless(not isinstance(mxsub, MSubArray))
+        self.failUnless(isinstance(mxsub, MaskedArray))
         assert_equal(mxsub._mask, m)
         #
         mxsub = masked_array(xsub, subok=True)
-        assert isinstance(mxsub, MSubArray)
+        self.failUnless(isinstance(mxsub, MSubArray))
         assert_equal(mxsub.info, xsub.info)
         assert_equal(mxsub._mask, xsub._mask)
         #
         mxsub = asanyarray(xsub)
-        assert isinstance(mxsub, MSubArray)
+        self.failUnless(isinstance(mxsub, MSubArray))
         assert_equal(mxsub.info, xsub.info)
         assert_equal(mxsub._mask, m)
 
@@ -156,24 +154,4 @@
 if __name__ == '__main__':
     run_module_suite()
 
-    if 0:
-        x = array(arange(5), mask=[0]+[1]*4)
-        my = masked_array(subarray(x))
-        ym = msubarray(x)
-        #
-        z = (my+1)
-        assert isinstance(z,MaskedArray)
-        assert not isinstance(z, MSubArray)
-        assert isinstance(z._data, SubArray)
-        assert_equal(z._data.info, {})
-        #
-        z = (ym+1)
-        assert isinstance(z, MaskedArray)
-        assert isinstance(z, MSubArray)
-        assert isinstance(z._data, SubArray)
-        assert z._data.info['added'] > 0
-        #
-        ym._set_mask([1,0,0,0,1])
-        assert_equal(ym._mask, [1,0,0,0,1])
-        ym._series._set_mask([0,0,0,0,1])
-        assert_equal(ym._mask, [0,0,0,0,1])
+

Modified: branches/1.2.x/numpy/ma/testutils.py
===================================================================
--- branches/1.2.x/numpy/ma/testutils.py	2008-10-06 02:55:14 UTC (rev 5935)
+++ branches/1.2.x/numpy/ma/testutils.py	2008-10-06 21:05:03 UTC (rev 5936)
@@ -16,12 +16,10 @@
 from numpy import ndarray, float_
 import numpy.core.umath as umath
 from numpy.testing import *
-from numpy.testing.utils import build_err_msg, rand
 import numpy.testing.utils as utils
 
-import core
-from core import mask_or, getmask, getmaskarray, masked_array, nomask, masked
-from core import fix_invalid, filled, equal, less
+from core import mask_or, getmask, masked_array, nomask, masked, filled, \
+                 equal, less
 
 #------------------------------------------------------------------------------
 def approx (a, b, fill_value=True, rtol=1.e-5, atol=1.e-8):
@@ -83,10 +81,12 @@
     """
     # Case #1: dictionary .....
     if isinstance(desired, dict):
-        assert isinstance(actual, dict), repr(type(actual))
+        if not isinstance(actual, dict):
+            raise AssertionError(repr(type(actual)))
         assert_equal(len(actual),len(desired),err_msg)
         for k,i in desired.items():
-            assert k in actual, repr(k)
+            if not k in actual:
+                raise AssertionError("%s not in %s" % (k,actual))
             assert_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg))
         return
     # Case #2: lists .....
@@ -94,7 +94,8 @@
         return _assert_equal_on_sequences(actual, desired, err_msg='')
     if not (isinstance(actual, ndarray) or isinstance(desired, ndarray)):
         msg = build_err_msg([actual, desired], err_msg,)
-        assert desired == actual, msg
+        if not desired == actual:
+            raise AssertionError(msg)
         return
     # Case #4. arrays or equivalent
     if ((actual is masked) and not (desired is masked)) or \
@@ -124,10 +125,12 @@
     """Raises an assertion error if two items are equal.
     """
     if isinstance(desired, dict):
-        assert isinstance(actual, dict), repr(type(actual))
+        if not isinstance(actual, dict):
+            raise AssertionError(repr(type(actual)))
         fail_if_equal(len(actual),len(desired),err_msg)
         for k,i in desired.items():
-            assert k in actual, repr(k)
+            if not k in actual:
+                raise AssertionError(repr(k))
             fail_if_equal(actual[k], desired[k], 'key=%r\n%s' % (k,err_msg))
         return
     if isinstance(desired, (list,tuple)) and isinstance(actual, (list,tuple)):
@@ -138,7 +141,8 @@
     if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray):
         return fail_if_array_equal(actual, desired, err_msg)
     msg = build_err_msg([actual, desired], err_msg)
-    assert desired != actual, msg
+    if not desired != actual:
+        raise AssertionError(msg)
 assert_not_equal = fail_if_equal
 
 
@@ -151,7 +155,8 @@
                                          err_msg=err_msg, verbose=verbose)
     msg = build_err_msg([actual, desired],
                         err_msg=err_msg, verbose=verbose)
-    assert round(abs(desired - actual),decimal) == 0, msg
+    if not round(abs(desired - actual),decimal) == 0:
+        raise AssertionError(msg)
 
 
 assert_close = assert_almost_equal

Modified: branches/1.2.x/numpy/ma/timer_comparison.py
===================================================================
--- branches/1.2.x/numpy/ma/timer_comparison.py	2008-10-06 02:55:14 UTC (rev 5935)
+++ branches/1.2.x/numpy/ma/timer_comparison.py	2008-10-06 21:05:03 UTC (rev 5936)
@@ -1,17 +1,15 @@
-
 import timeit
 
-import numpy
-from numpy import int_, float_, bool_
-import numpy.core.fromnumeric as fromnumeric
+import numpy as np
+from numpy import float_
+import np.core.fromnumeric as fromnumeric
 
-from numpy.testing.utils import build_err_msg, rand
+from np.testing.utils import build_err_msg
 
+np.seterr(all='ignore')
 
-numpy.seterr(all='ignore')
+pi = np.pi
 
-pi = numpy.pi
-
 class moduletester:
     #-----------------------------------
     def __init__(self, module):
@@ -61,15 +59,15 @@
         y = self.filled(self.masked_array(yf, mask=m), fill_value)
         if (x.dtype.char != "O"):
             x = x.astype(float_)
-            if isinstance(x, numpy.ndarray) and x.size > 1:
-                x[numpy.isnan(x)] = 0
-            elif numpy.isnan(x):
+            if isinstance(x, np.ndarray) and x.size > 1:
+                x[np.isnan(x)] = 0
+            elif np.isnan(x):
                 x = 0
         if (y.dtype.char != "O"):
             y = y.astype(float_)
-            if isinstance(y, numpy.ndarray) and y.size > 1:
-                y[numpy.isnan(y)] = 0
-            elif numpy.isnan(y):
+            if isinstance(y, np.ndarray) and y.size > 1:
+                y[np.isnan(y)] = 0
+            elif np.isnan(y):
                 y = 0
         try:
             cond = (x.shape==() or y.shape==()) or x.shape == y.shape
@@ -110,23 +108,23 @@
     #----------------------------------
     def test_0(self):
         "Tests creation"
-        x = numpy.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
+        x = np.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
         m = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
         xm = self.masked_array(x, mask=m)
         xm[0]
     #----------------------------------
     def test_1(self):
         "Tests creation"
-        x = numpy.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
-        y = numpy.array([5.,0.,3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
+        x = np.array([1.,1.,1.,-2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
+        y = np.array([5.,0.,3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
         a10 = 10.
         m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
         m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0 ,0, 1]
         xm = self.masked_array(x, mask=m1)
         ym = self.masked_array(y, mask=m2)
-        z = numpy.array([-.5, 0., .5, .8])
+        z = np.array([-.5, 0., .5, .8])
         zm = self.masked_array(z, mask=[0,1,0,0])
-        xf = numpy.where(m1, 1.e+20, x)
+        xf = np.where(m1, 1.e+20, x)
         xm.set_fill_value(1.e+20)
         #.....
         assert((xm-ym).filled(0).any())
@@ -146,13 +144,13 @@
     #----------------------------------
     def test_2(self):
         "Tests conversions and indexing"
-        x1 = numpy.array([1,2,4,3])
+        x1 = np.array([1,2,4,3])
         x2 = self.array(x1, mask=[1,0,0,0])
         x3 = self.array(x1, mask=[0,1,0,1])
         x4 = self.array(x1)
     # test conversion to strings
         junk, garbage = str(x2), repr(x2)
-#        assert_equal(numpy.sort(x1), self.sort(x2, fill_value=0))
+#        assert_equal(np.sort(x1), self.sort(x2, fill_value=0))
     # tests of indexing
         assert type(x2[1]) is type(x1[1])
         assert x1[1] == x2[1]
@@ -178,12 +176,12 @@
         x4[:] = self.masked_array([1,2,3,4],[0,1,1,0])
 #        assert self.allequal(self.getmask(x4), self.array([0,1,1,0]))
 #        assert self.allequal(x4, self.array([1,2,3,4]))
-        x1 = numpy.arange(5)*1.0
+        x1 = np.arange(5)*1.0
         x2 = self.masked_values(x1, 3.0)
 #        assert self.allequal(x1,x2)
 #        assert self.allequal(self.array([0,0,0,1,0], self.MaskType), x2.mask)
         x1 = self.array([1,'hello',2,3],object)
-        x2 = numpy.array([1,'hello',2,3],object)
+        x2 = np.array([1,'hello',2,3],object)
         s1 = x1[1]
         s2 = x2[1]
         assert x1[1:1].shape == (0,)
@@ -216,15 +214,15 @@
     def test_4(self):
         "Test of take, transpose, inner, outer products"
         x = self.arange(24)
-        y = numpy.arange(24)
+        y = np.arange(24)
         x[5:6] = self.masked
         x = x.reshape(2,3,4)
         y = y.reshape(2,3,4)
-        assert self.allequal(numpy.transpose(y,(2,0,1)), self.transpose(x,(2,0,1)))
-        assert self.allequal(numpy.take(y, (2,0,1), 1), self.take(x, (2,0,1), 1))
-        assert self.allequal(numpy.inner(self.filled(x,0), self.filled(y,0)),
+        assert self.allequal(np.transpose(y,(2,0,1)), self.transpose(x,(2,0,1)))
+        assert self.allequal(np.take(y, (2,0,1), 1), self.take(x, (2,0,1), 1))
+        assert self.allequal(np.inner(self.filled(x,0), self.filled(y,0)),
                             self.inner(x, y))
-        assert self.allequal(numpy.outer(self.filled(x,0), self.filled(y,0)),
+        assert self.allequal(np.outer(self.filled(x,0), self.filled(y,0)),
                             self.outer(x, y))
         y = self.array(['abc', 1, 'def', 2, 3], object)
         y[2] = self.masked
@@ -396,8 +394,8 @@
         self.assert_array_equal(self.average(x, axis=0), 2.5)
         self.assert_array_equal(self.average(x, axis=0, weights=w1), 2.5)
         y = self.array([self.arange(6), 2.0*self.arange(6)])
-        self.assert_array_equal(self.average(y, None), numpy.add.reduce(numpy.arange(6))*3./12.)
-        self.assert_array_equal(self.average(y, axis=0), numpy.arange(6) * 3./2.)
+        self.assert_array_equal(self.average(y, None), np.add.reduce(np.arange(6))*3./12.)
+        self.assert_array_equal(self.average(y, axis=0), np.arange(6) * 3./2.)
         self.assert_array_equal(self.average(y, axis=1), [self.average(x,axis=0), self.average(x,axis=0) * 2.0])
         self.assert_array_equal(self.average(y, None, weights=w2), 20./6.)
         self.assert_array_equal(self.average(y, axis=0, weights=w2), [0.,1.,2.,3.,4.,10.])
@@ -420,7 +418,7 @@
     #------------------------
     def test_A(self):
         x = self.arange(24)
-        y = numpy.arange(24)
+        y = np.arange(24)
         x[5:6] = self.masked
         x = x.reshape(2,3,4)
 
@@ -431,10 +429,10 @@
     setup_base = "from __main__ import moduletester \n"\
                  "import numpy\n" \
                  "tester = moduletester(module)\n"
-#    setup_new = "import numpy.ma.core_ini as module\n"+setup_base
-    setup_cur = "import numpy.ma.core as module\n"+setup_base
-#    setup_alt = "import numpy.ma.core_alt as module\n"+setup_base
-#    setup_tmp = "import numpy.ma.core_tmp as module\n"+setup_base
+#    setup_new = "import np.ma.core_ini as module\n"+setup_base
+    setup_cur = "import np.ma.core as module\n"+setup_base
+#    setup_alt = "import np.ma.core_alt as module\n"+setup_base
+#    setup_tmp = "import np.ma.core_tmp as module\n"+setup_base
 
     (nrepeat, nloop) = (10, 10)
 
@@ -445,10 +443,10 @@
             cur = timeit.Timer(func, setup_cur).repeat(nrepeat, nloop*10)
 #            alt = timeit.Timer(func, setup_alt).repeat(nrepeat, nloop*10)
 #            tmp = timeit.Timer(func, setup_tmp).repeat(nrepeat, nloop*10)
-#            new = numpy.sort(new)
-            cur = numpy.sort(cur)
-#            alt = numpy.sort(alt)
-#            tmp = numpy.sort(tmp)
+#            new = np.sort(new)
+            cur = np.sort(cur)
+#            alt = np.sort(alt)
+#            tmp = np.sort(tmp)
             print "#%i" % i +50*'.'
             print eval("moduletester.test_%i.__doc__" % i)
 #            print "core_ini     : %.3f - %.3f" % (new[0], new[1])




More information about the Numpy-svn mailing list