[Numpy-svn] r4771 - branches/maskedarray/numpy/ma

numpy-svn at scipy.org numpy-svn at scipy.org
Thu Feb 7 12:00:05 EST 2008


Author: pierregm
Date: 2008-02-07 11:00:02 -0600 (Thu, 07 Feb 2008)
New Revision: 4771

Modified:
   branches/maskedarray/numpy/ma/core.py
   branches/maskedarray/numpy/ma/extras.py
Log:
comments cleaning and docstring updates.

Modified: branches/maskedarray/numpy/ma/core.py
===================================================================
--- branches/maskedarray/numpy/ma/core.py	2008-02-07 11:42:03 UTC (rev 4770)
+++ branches/maskedarray/numpy/ma/core.py	2008-02-07 17:00:02 UTC (rev 4771)
@@ -258,7 +258,8 @@
     """
     if hasattr(a, 'filled'):
         return a.filled(value)
-    elif isinstance(a, ndarray): # and a.flags['CONTIGUOUS']:
+    elif isinstance(a, ndarray): 
+        # Should we check for contiguity ? and a.flags['CONTIGUOUS']:
         return a
     elif isinstance(a, dict):
         return narray(a, 'O')
@@ -441,7 +442,8 @@
             m = numpy.logical_or(m, dm)
             # The following two lines control the domain filling methods.
             d1 = d1.copy()
-#            d1[dm] = self.fill
+            # We could use smart indexing : d1[dm] = self.fill ...
+            # ... but numpy.putmask looks more efficient, despite the copy.
             numpy.putmask(d1, dm, self.fill)
         # Take care of the masked singletong first ...
         if not m.ndim and m:
@@ -549,7 +551,8 @@
         if (not m.ndim) and m:
             return masked
         rcls = get_masked_subclass(a,b)
-#        d = self.f.outer(filled(a, self.fillx), filled(b, self.filly)).view(rcls)
+        # We could fill the arguments first, butis it useful ?
+        # d = self.f.outer(filled(a, self.fillx), filled(b, self.filly)).view(rcls)
         d = self.f.outer(getdata(a), getdata(b)).view(rcls)
         if d.ndim > 0:
             d._mask = m
@@ -864,11 +867,12 @@
     floating point, consider `masked_values(x, value)` instead.
 
     """
+    # An alternative implementation relies on filling first: probably not needed.
+    # d = filled(x, 0)
+    # c = umath.equal(d, value)
+    # m = mask_or(c, getmask(x))
+    # return array(d, mask=m, copy=copy)
     return masked_where((x == value), x, copy=copy)
-#    d = filled(x, 0)
-#    c = umath.equal(d, value)
-#    m = mask_or(c, getmask(x))
-#    return array(d, mask=m, copy=copy)
 
 def masked_inside(x, v1, v2, copy=True):
     """Shortcut to masked_where, where condition is True for x inside
@@ -970,7 +974,7 @@
     else:
         cls = MaskedArray
     result = a.view(cls)
-    result._mask = cond
+    result._mask = condition
     return result
 
 
@@ -1336,6 +1340,7 @@
         """
         if self is masked:
             raise MAError, 'Cannot alter the masked element.'
+        # This test is useful, but we should keep things light...
 #        if getmask(indx) is not nomask:
 #            msg = "Masked arrays must be filled before they can be used as indices!"
 #            raise IndexError, msg
@@ -1401,6 +1406,8 @@
         """
         if mask is not nomask:
             mask = narray(mask, copy=copy, dtype=MaskType)
+            # We could try to check whether shrinking is needed..
+            # ... but we would waste some precious time
 #            if self._shrinkmask and not mask.any():
 #                mask = nomask
         if self._mask is nomask:
@@ -1425,8 +1432,9 @@
         """Return the current mask.
 
         """
-        return self._mask
+        # We could try to force a reshape, but that wouldn't work in some cases.
 #        return self._mask.reshape(self.shape)
+        return self._mask
     mask = property(fget=_get_mask, fset=__setmask__, doc="Mask")
     #............................................
     def harden_mask(self):
@@ -1566,8 +1574,6 @@
         data._update_from(self)
         if self._mask is not nomask:
             data = data[numpy.logical_not(ndarray.ravel(self._mask))]
-#        if not self._shrinkmask:
-#            data._mask = numpy.zeros(data.shape, dtype=MaskType)
         return data
     
     
@@ -1730,7 +1736,6 @@
         if self._mask is not nomask:
             warnings.warn("Warning: converting a masked element to nan.")
             return numpy.nan
-            #raise MAError, 'Cannot convert masked element to a Python float.'
         return float(self.item())
 
     def __int__(self):
@@ -1793,7 +1798,7 @@
             return masked_array(n1 - n2)
     #............................................
     flatten = _arraymethod('flatten')
-#    ravel = _arraymethod('ravel')
+    #
     def ravel(self):
         """Returns a 1D version of self, as a view."""
         r = ndarray.ravel(self._data).view(type(self))
@@ -1803,6 +1808,7 @@
         else:
             r._mask = nomask
         return r
+    #
     repeat = _arraymethod('repeat')
     #
     def reshape (self, *s):
@@ -1958,7 +1964,8 @@
                 d.__setmask__(self._mask.all(axis))
             return d
         elif type(out) is not type(self):
-            raise TypeError("The external array should have a type %s (got %s instead)" %\
+            raise TypeError("The external array should have a type %s "\
+                            "(got %s instead)" %\
                             (type(self), type(out)))
         self.filled(False).any(axis=axis, out=out)
         if out.ndim:
@@ -2011,7 +2018,7 @@
         axis : int, optional
             Axis along which to perform the operation.
             If None, applies to a flattened version of the array.
-        dtype : {dtype}, optional
+        dtype : dtype, optional
             Datatype for the intermediary computation. If not given,
             the current dtype is used instead.
 
@@ -2464,13 +2471,10 @@
         """
         return self.max(axis, fill_value) - self.min(axis, fill_value)
 
-
     # Array methods ---------------------------------------
-#    conj = conjugate = _arraymethod('conjugate')
     copy = _arraymethod('copy')
     diagonal = _arraymethod('diagonal')
     take = _arraymethod('take')
-#    ravel = _arraymethod('ravel')
     transpose = _arraymethod('transpose')
     T = property(fget=lambda self:self.transpose())
     swapaxes = _arraymethod('swapaxes')
@@ -2583,11 +2587,8 @@
     _data = ndarray.__new__(baseclass, baseshape, basetype)
     _mask = ndarray.__new__(ndarray, baseshape, 'b1')
     return subtype.__new__(subtype, _data, mask=_mask, dtype=basetype,)
-#MaskedArray.__dump__ = dump
-#MaskedArray.__dumps__ = dumps
 
 
-
 #####--------------------------------------------------------------------------
 #---- --- Shortcuts ---
 #####---------------------------------------------------------------------------
@@ -2597,6 +2598,7 @@
 isarray = isMaskedArray
 isMA = isMaskedArray  #backward compatibility
 # We define the masked singleton as a float for higher precedence...
+# Note that it can be tricky sometimes w/ type comparison
 masked_singleton = MaskedArray(0, dtype=float_, mask=True)
 masked = masked_singleton
 
@@ -2885,6 +2887,8 @@
         return data
     # OK, so we have to concatenate the masks
     dm = numpy.concatenate([getmaskarray(a) for a in arrays], axis)
+    # If we decide to keep a '_shrinkmask' option, we want to check that ...
+    # ... 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():
@@ -2958,10 +2962,6 @@
 
     """
     # We can't use 'frommethod', the order of arguments is different
-#    try:
-#        return a.putmask(values, mask)
-#    except AttributeError:
-#        return numpy.putmask(narray(a, copy=False), mask, values)
     if not isinstance(a, MaskedArray):
         a = a.view(MaskedArray)
     (valdata, valmask) = (getdata(values), getmask(values))
@@ -2970,9 +2970,6 @@
             a._sharedmask = True
             a.mask = numpy.zeros(a.shape, dtype=bool_)
             numpy.putmask(a._mask, mask, valmask)
-#            m = numpy.zeros(a.shape, dtype=bool_)
-#            numpy.putmask(m, mask, valmask)
-#            a = masked_array(a, copy=False, subok=True, mask=m)
     elif a._hardmask:
         if valmask is not nomask:
             m = a._mask.copy()
@@ -3094,22 +3091,6 @@
     if not d._mask.any():
         d._mask = nomask
     return d
-#    # Get the data as a (subclass of) MaskedArray
-#    xv = getdata(x)
-#    yv = getdata(y)
-#    d = numpy.choose(fc, (yv, xv)).view(MaskedArray)
-#    # Get the mask ....................
-#    xm = getmask(x)
-#    ym = getmask(y)
-#    d.mask = numpy.choose(fc, (ym, xm)) | getmask(condition)
-#    # Fix the dtype if one of the values was masked, to prevent an upload to float
-#    if y is masked:
-#        ndtype = xv.dtype
-#    elif x is masked:
-#        ndtype = yv.dtype
-#    else:
-#        ndtype = d.dtype
-#    return d.astype(ndtype)
 
 def choose (indices, t, out=None, mode='raise'):
     "Return array shaped like indices with elements chosen from t"
@@ -3322,3 +3303,5 @@
 def loads(strg):
     "Load a pickle from the current string."""
     return cPickle.loads(strg)
+
+################################################################################

Modified: branches/maskedarray/numpy/ma/extras.py
===================================================================
--- branches/maskedarray/numpy/ma/extras.py	2008-02-07 11:42:03 UTC (rev 4770)
+++ branches/maskedarray/numpy/ma/extras.py	2008-02-07 17:00:02 UTC (rev 4771)
@@ -52,8 +52,9 @@
 def count_masked(arr, axis=None):
     """Count the number of masked elements along the given axis.
 
-    *Parameters*:
-        axis : {integer}, optional
+    Parameters
+    ----------
+        axis : int, optional
             Axis along which to count.
             If None (default), a flattened version of the array is used.
 
@@ -65,8 +66,9 @@
     """Return an empty masked array of the given shape and dtype,
     where all the data are masked.
 
-    *Parameters*:
-        dtype : {dtype}, optional
+    Parameters
+    ----------
+        dtype : dtype, optional
             Data type of the output.
 
     """
@@ -90,15 +92,17 @@
     """Return an unbiased estimate of the variance.
     i.e. var = sum((x - x.mean())**2)/(size(x,axis)-1)
 
-    *Parameters*:
-        axis : {integer}, optional
+    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.
 
-    *Notes*:
+    Notes
+    -----
         The value returned is an unbiased estimate of the true variance.
         For the (less standard) biased estimate, use var.
 
@@ -121,15 +125,17 @@
     standard deviation is the square root of the average of the
     squared deviations from the mean, i.e. stdu = sqrt(varu(x)).
 
-    *Parameters*:
-        axis : {integer}, optional
+    Parameters
+    ----------
+        axis : int, optional
             Axis along which to perform the operation.
             If None, applies to a flattened version of the array.
-        dtype : {dtype}, optional
+        dtype : dtype, optional
             Datatype for the intermediary computation.
             If not given, the current dtype is used instead.
 
-    *Notes*:
+    Notes
+    -----
         The value returned is an unbiased estimate of the true
         standard deviation.  For the biased estimate,
         use std.
@@ -144,9 +150,8 @@
             # Should we use umath.sqrt instead ?
             return sqrt(dvar)
     return sqrt(dvar)
-#    return a.__class__(sqrt(dvar._data), mask=dvar._mask,
-#                          fill_value=a._fill_value)
 
+
 MaskedArray.stdu = stdu
 MaskedArray.varu = varu
 
@@ -300,19 +305,19 @@
 def average(a, axis=None, weights=None, returned=False):
     """Average the array over the given axis.
 
-    *Parameters*:
-        axis : {integer}, optional
+    Parameters
+    ----------
+        axis : int, optional
             Axis along which to perform the operation.
             If None, applies to a flattened version of the array.
-        weights : {sequence}, optional
+        weights : sequence, optional
             Sequence of weights.
             The weights must have the shape of a, or be 1D with length
             the size of a along the given axis.
             If no weights are given, weights are assumed to be 1.
-        returned : {boolean}
-            Flag indicating whether a tuple (result, sum of
-            weights/counts) should be returned as output (True), or
-            just the result (False).
+        returned : bool
+            Flag indicating whether a tuple (result, sum of weights/counts) 
+            should be returned as output (True), or just the result (False).
 
     """
     a = asarray(a)
@@ -381,7 +386,8 @@
                     ni = ash[axis]
                     r = [None]*len(ash)
                     r[axis] = slice(None, None, 1)
-                    w = eval ("w["+ repr(tuple(r)) + "] * masked_array(ones(ash, float), mask)")
+                    w = eval ("w["+ repr(tuple(r)) + \
+                              "] * masked_array(ones(ash, float), mask)")
                     n = add.reduce(a*w, axis, dtype=float_)
                     d = add.reduce(w, axis, dtype=float_)
                 else:
@@ -415,8 +421,15 @@
         - If axis is None, rows and columns are suppressed.
         - If axis is 0, only rows are suppressed.
         - If axis is 1 or -1, only columns are suppressed.
+        
+    Parameters
+    ----------
+        axis : int, optional
+            Axis along which to perform the operation.
+            If None, applies to a flattened version of the array.
 
-    *Returns*:
+    Returns
+    -------
         compressed_array : an ndarray.
 
     """
@@ -462,7 +475,15 @@
         - If axis is 0, only rows are masked.
         - If axis is 1 or -1, only columns are masked.
 
-    Returns a *pure* ndarray.
+    Parameters
+    ----------
+        axis : int, optional
+            Axis along which to perform the operation.
+            If None, applies to a flattened version of the array.
+            
+    Returns
+    -------
+         a *pure* ndarray.
 
     """
     a = asarray(a)
@@ -483,12 +504,22 @@
 def mask_rows(a, axis=None):
     """Mask whole rows of a 2D array that contain masked values.
 
+    Parameters
+    ----------
+        axis : int, optional
+            Axis along which to perform the operation.
+            If None, applies to a flattened version of the array.
     """
     return mask_rowcols(a, 0)
 
 def mask_cols(a, axis=None):
     """Mask whole columns of a 2D array that contain masked values.
 
+    Parameters
+    ----------
+        axis : int, optional
+            Axis along which to perform the operation.
+            If None, applies to a flattened version of the array.
     """
     return mask_rowcols(a, 1)
 
@@ -502,12 +533,14 @@
     appears in a row or column, the whole row or column is considered
     masked.
 
-    *Parameters*:
+    Parameters
+    ----------
         strict : {boolean}
             Whether masked data are propagated (True) or set to 0 for
             the computation.
 
-    *Note*:
+    Notes
+    -----
         The first argument is not conjugated.
 
     """
@@ -528,7 +561,8 @@
     """Return the differences between consecutive elements of an
     array, possibly with prefixed and/or appended values.
 
-    *Parameters*:
+    Parameters
+    ----------
         array : {array}
             Input array,  will be flattened before the difference is taken.
         to_end : {number}, optional
@@ -538,7 +572,8 @@
             If provided, this number will be taked onto the beginning of the
             returned differences.
 
-    *Returns*:
+    Returns
+    -------
           ed : {array}
             The differences. Loosely, this will be (ary[1:] - ary[:-1]).
 
@@ -693,6 +728,11 @@
     of 2 tuples, corresponding to the indices of the first and last
     unmasked values respectively.
 
+    Parameters
+    ----------
+        axis : int, optional
+            Axis along which to perform the operation.
+            If None, applies to a flattened version of the array.
     """
     a = asarray(a)
     if axis is None or a.ndim == 1:
@@ -726,9 +766,19 @@
     """Find contiguous unmasked data in a masked array along the given
     axis.
 
-    Return a sorted sequence of slices (start index, end index).
+    Parameters
+    ----------
+        axis : int, optional
+            Axis along which to perform the operation.
+            If None, applies to a flattened version of the array.
+            
+    Returns
+    -------
+        a sorted sequence of slices (start index, end index).
 
-    Note: Only accepts 2D arrays at most.
+    Notes
+    -----
+        Only accepts 2D arrays at most.
 
     """
     a = asarray(a)
@@ -750,12 +800,3 @@
     return result
 
 ################################################################################
-if __name__ == '__main__':
-    #
-    import numpy as N
-    from numpy.ma.testutils import assert_equal
-    if 1:
-        b = ones(5)
-        m = [1,0,0,0,0]
-        d = masked_array(b,mask=m)
-        c = mr_[d,0,0,d]




More information about the Numpy-svn mailing list