def average(a, axis=None, weights=None, returned=False):

a = asarray(a)<EOL>mask = a.mask<EOL>ash = a.shape<EOL>if ash == ():<EOL><INDENT>ash = (<NUM_LIT:1>,)<EOL><DEDENT>if axis is None:<EOL><INDENT>if mask is nomask:<EOL><INDENT>if weights is None:<EOL><INDENT>n = a.sum(axis=None)<EOL>d = float(a.size)<EOL><DEDENT>else:<EOL><INDENT>w = filled(weights, <NUM_LIT:0.0>).ravel()<EOL>n = umath.add.reduce(a._data.ravel() * w)<EOL>d = umath.add.reduce(w)<EOL>del w<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if weights is None:<EOL><INDENT>n = a.filled(<NUM_LIT:0>).sum(axis=None)<EOL>d = float(umath.add.reduce((~mask).ravel()))<EOL><DEDENT>else:<EOL><INDENT>w = array(filled(weights, <NUM_LIT:0.0>), float, mask=mask).ravel()<EOL>n = add.reduce(a.ravel() * w)<EOL>d = add.reduce(w)<EOL>del w<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if mask is nomask:<EOL><INDENT>if weights is None:<EOL><INDENT>d = ash[axis] * <NUM_LIT:1.0><EOL>n = add.reduce(a._data, axis)<EOL><DEDENT>else:<EOL><INDENT>w = filled(weights, <NUM_LIT:0.0>)<EOL>wsh = w.shape<EOL>if wsh == ():<EOL><INDENT>wsh = (<NUM_LIT:1>,)<EOL><DEDENT>if wsh == ash:<EOL><INDENT>w = np.array(w, float, copy=<NUM_LIT:0>)<EOL>n = add.reduce(a * w, axis)<EOL>d = add.reduce(w, axis)<EOL>del w<EOL><DEDENT>elif wsh == (ash[axis],):<EOL><INDENT>ni = ash[axis]<EOL>r = [None] * len(ash)<EOL>r[axis] = slice(None, None, <NUM_LIT:1>)<EOL>w = eval ("<STR_LIT>" + repr(tuple(r)) + "<STR_LIT>")<EOL>n = add.reduce(a * w, axis)<EOL>d = add.reduce(w, axis, dtype=float)<EOL>del w, r<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>if weights is None:<EOL><INDENT>n = add.reduce(a, axis)<EOL>d = umath.add.reduce((~mask), axis=axis, dtype=float)<EOL><DEDENT>else:<EOL><INDENT>w = filled(weights, <NUM_LIT:0.0>)<EOL>wsh = w.shape<EOL>if wsh == ():<EOL><INDENT>wsh = (<NUM_LIT:1>,)<EOL><DEDENT>if wsh == ash:<EOL><INDENT>w = array(w, dtype=float, mask=mask, copy=<NUM_LIT:0>)<EOL>n = add.reduce(a * w, axis)<EOL>d = add.reduce(w, axis, dtype=float)<EOL><DEDENT>elif wsh == (ash[axis],):<EOL><INDENT>ni = ash[axis]<EOL>r = [None] * len(ash)<EOL>r[axis] = slice(None, None, <NUM_LIT:1>)<EOL>w = eval ("<STR_LIT>" + repr(tuple(r)) +"<STR_LIT>")<EOL>n = add.reduce(a * w, axis)<EOL>d = add.reduce(w, axis, dtype=float)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>del w<EOL><DEDENT><DEDENT><DEDENT>if n is masked or d is masked:<EOL><INDENT>return masked<EOL><DEDENT>result = n / d<EOL>del n<EOL>if isinstance(result, MaskedArray):<EOL><INDENT>if ((axis is None) or (axis == <NUM_LIT:0> and a.ndim == <NUM_LIT:1>)) and(result.mask is nomask):<EOL><INDENT>result = result._data<EOL><DEDENT>if returned:<EOL><INDENT>if not isinstance(d, MaskedArray):<EOL><INDENT>d = masked_array(d)<EOL><DEDENT>if isinstance(d, ndarray) and (not d.shape == result.shape):<EOL><INDENT>d = ones(result.shape, dtype=float) * d<EOL><DEDENT><DEDENT><DEDENT>if returned:<EOL><INDENT>return result, d<EOL><DEDENT>else:<EOL><INDENT>return result<EOL><DEDENT>

Return the weighted average of array over the given axis.

Parameters
----------
a : array_like
    Data to be averaged.
    Masked entries are not taken into account in the computation.
axis : int, optional
    Axis along which the average is computed. The default is to compute
    the average of the flattened array.
weights : array_like, optional
    The importance that each element has in the computation of the average.
    The weights array can either be 1-D (in which case its length must be
    the size of `a` along the given axis) or of the same shape as `a`.
    If ``weights=None``, then all data in `a` are assumed to have a
    weight equal to one.   If `weights` is complex, the imaginary parts
    are ignored.
returned : bool, optional
    Flag indicating whether a tuple ``(result, sum of weights)``
    should be returned as output (True), or just the result (False).
    Default is False.

Returns
-------
average, [sum_of_weights] : (tuple of) scalar or MaskedArray
    The average along the specified axis. When returned is `True`,
    return a tuple with the average as the first element and the sum
    of the weights as the second element. The return type is `np.float64`
    if `a` is of integer type, otherwise it is of the same type as `a`.
    If returned, `sum_of_weights` is of the same type as `average`.

Examples
--------
>>> a = np.ma.array([1., 2., 3., 4.], mask=[False, False, True, True])
>>> np.ma.average(a, weights=[3, 1, 0, 0])
1.25

>>> x = np.ma.arange(6.).reshape(3, 2)
>>> print x
[[ 0.  1.]
 [ 2.  3.]
 [ 4.  5.]]
>>> avg, sumweights = np.ma.average(x, axis=0, weights=[1, 2, 3],
...                                 returned=True)
>>> print avg
[2.66666666667 3.66666666667]


a = np.empty_like(arr).view(MaskedArray)<EOL>a._mask = np.ones(a.shape, dtype=make_mask_descr(a.dtype))<EOL>return a<EOL>

Empty masked array with the properties of an existing array.

Return an empty masked array of the same shape and dtype as
the array `arr`, where all the data are masked.

Parameters
----------
arr : ndarray
    An array describing the shape and dtype of the required MaskedArray.

Returns
-------
a : MaskedArray
    A masked array with all data masked.

Raises
------
AttributeError
    If `arr` doesn't have a shape attribute (i.e. not an ndarray)

See Also
--------
masked_all : Empty masked array with all elements masked.

Examples
--------
>>> import numpy.ma as ma
>>> arr = np.zeros((2, 3), dtype=np.float32)
>>> arr
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.]], dtype=float32)
>>> ma.masked_all_like(arr)
masked_array(data =
 [[-- -- --]
 [-- -- --]],
      mask =
 [[ True  True  True]
 [ True  True  True]],
      fill_value=1e+20)

The dtype of the masked array matches the dtype of `arr`.

>>> arr.dtype
dtype('float32')
>>> ma.masked_all_like(arr).dtype
dtype('float32')


def setxor1d(ar1, ar2, assume_unique=False):

if not assume_unique:<EOL><INDENT>ar1 = unique(ar1)<EOL>ar2 = unique(ar2)<EOL><DEDENT>aux = ma.concatenate((ar1, ar2))<EOL>if aux.size == <NUM_LIT:0>:<EOL><INDENT>return aux<EOL><DEDENT>aux.sort()<EOL>auxf = aux.filled()<EOL><INDENT>flag = ediff1d( aux, to_end = <NUM_LIT:1>, to_begin = <NUM_LIT:1> ) == <NUM_LIT:0><EOL><DEDENT>flag = ma.concatenate(([True], (auxf[<NUM_LIT:1>:] != auxf[:-<NUM_LIT:1>]), [True]))<EOL><INDENT>flag2 = ediff1d( flag ) == <NUM_LIT:0><EOL><DEDENT>flag2 = (flag[<NUM_LIT:1>:] == flag[:-<NUM_LIT:1>])<EOL>return aux[flag2]<EOL>

Set exclusive-or of 1-D arrays with unique elements.

The output is always a masked array. See `numpy.setxor1d` for more details.

See Also
--------
numpy.setxor1d : Equivalent function for ndarrays.


return compress_rowcols(a, <NUM_LIT:1>)<EOL>

Suppress whole columns of a 2-D array that contain masked values.

This is equivalent to ``np.ma.extras.compress_rowcols(a, 1)``, see
`extras.compress_rowcols` for details.

See Also
--------
extras.compress_rowcols


npfunc = getattr(np, self.__name__, None)<EOL>doc = getattr(npfunc, '<STR_LIT>', None)<EOL>if doc:<EOL><INDENT>sig = self.__name__ + ma.get_object_signature(npfunc)<EOL>locdoc = "<STR_LIT>""<STR_LIT>"<EOL>return '<STR_LIT:\n>'.join((sig, doc, locdoc))<EOL><DEDENT>return<EOL>

Retrieve the docstring and signature from the function.

The ``__doc__`` attribute of the function is used as the docstring for
the new masked array version of the function. A note on application
of the function to the mask is appended.

.. warning::
  If the function docstring already contained a Notes section, the
  new docstring will have two Notes sections instead of appending a note
  to the existing section.

Parameters
----------
None


return mask_rowcols(a, <NUM_LIT:1>)<EOL>

Mask columns of a 2D array that contain masked values.

This function is a shortcut to ``mask_rowcols`` with `axis` equal to 1.

See Also
--------
mask_rowcols : Mask rows and/or columns of a 2D array.
masked_where : Mask where a condition is met.

Examples
--------
>>> import numpy.ma as ma
>>> a = np.zeros((3, 3), dtype=np.int)
>>> a[1, 1] = 1
>>> a
array([[0, 0, 0],
       [0, 1, 0],
       [0, 0, 0]])
>>> a = ma.masked_equal(a, 1)
>>> a
masked_array(data =
 [[0 0 0]
 [0 -- 0]
 [0 0 0]],
      mask =
 [[False False False]
 [False  True False]
 [False False False]],
      fill_value=999999)
>>> ma.mask_cols(a)
masked_array(data =
 [[0 -- 0]
 [0 -- 0]
 [0 -- 0]],
      mask =
 [[False  True False]
 [False  True False]
 [False  True False]],
      fill_value=999999)


a = masked_array(np.empty(shape, dtype),<EOL>mask=np.ones(shape, make_mask_descr(dtype)))<EOL>return a<EOL>

Empty masked array with all elements masked.

Return an empty masked array of the given shape and dtype, where all the
data are masked.

Parameters
----------
shape : tuple
    Shape of the required MaskedArray.
dtype : dtype, optional
    Data type of the output.

Returns
-------
a : MaskedArray
    A masked array with all data masked.

See Also
--------
masked_all_like : Empty masked array modelled on an existing array.

Examples
--------
>>> import numpy.ma as ma
>>> ma.masked_all((3, 3))
masked_array(data =
 [[-- -- --]
 [-- -- --]
 [-- -- --]],
      mask =
 [[ True  True  True]
 [ True  True  True]
 [ True  True  True]],
      fill_value=1e+20)

The `dtype` parameter defines the underlying data type.

>>> a = ma.masked_all((3, 3))
>>> a.dtype
dtype('float64')
>>> a = ma.masked_all((3, 3), dtype=np.int32)
>>> a.dtype
dtype('int32')


ndescr = len(descr)<EOL>default_names = ['<STR_LIT>' % i for i in range(ndescr)]<EOL>if names is None:<EOL><INDENT>new_names = default_names<EOL><DEDENT>else:<EOL><INDENT>if isinstance(names, (tuple, list)):<EOL><INDENT>new_names = names<EOL><DEDENT>elif isinstance(names, str):<EOL><INDENT>new_names = names.split('<STR_LIT:U+002C>')<EOL><DEDENT>else:<EOL><INDENT>raise NameError("<STR_LIT>" % repr(names))<EOL><DEDENT>nnames = len(new_names)<EOL>if nnames < ndescr:<EOL><INDENT>new_names += default_names[nnames:]<EOL><DEDENT><DEDENT>ndescr = []<EOL>for (n, d, t) in zip(new_names, default_names, descr.descr):<EOL><INDENT>if n in reserved_fields:<EOL><INDENT>if t[<NUM_LIT:0>] in reserved_fields:<EOL><INDENT>ndescr.append((d, t[<NUM_LIT:1>]))<EOL><DEDENT>else:<EOL><INDENT>ndescr.append(t)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>ndescr.append((n, t[<NUM_LIT:1>]))<EOL><DEDENT><DEDENT>return np.dtype(ndescr)<EOL>

Checks that the field names of the descriptor ``descr`` are not some
reserved keywords. If this is the case, a default 'f%i' is substituted.
If the argument `names` is not None, updates the field names to valid names.


self._hardmask = True<EOL>


def fromrecords(reclist, dtype=None, shape=None, formats=None, names=None,<EOL>titles=None, aligned=False, byteorder=None,<EOL>fill_value=None, mask=nomask):

<EOL>_mask = getattr(reclist, '<STR_LIT>', None)<EOL>try:<EOL><INDENT>nfields = len(reclist[<NUM_LIT:0>])<EOL><DEDENT>except TypeError:<EOL><INDENT>nfields = len(reclist[<NUM_LIT:0>].dtype)<EOL><DEDENT>if isinstance(reclist, ndarray):<EOL><INDENT>if isinstance(reclist, MaskedArray):<EOL><INDENT>reclist = reclist.filled().view(ndarray)<EOL><DEDENT>if dtype is None:<EOL><INDENT>dtype = reclist.dtype<EOL><DEDENT>reclist = reclist.tolist()<EOL><DEDENT>mrec = recfromrecords(reclist, dtype=dtype, shape=shape, formats=formats,<EOL>names=names, titles=titles,<EOL>aligned=aligned, byteorder=byteorder).view(mrecarray)<EOL>if fill_value is not None:<EOL><INDENT>mrec.fill_value = fill_value<EOL><DEDENT>if mask is not nomask:<EOL><INDENT>mask = np.array(mask, copy=False)<EOL>maskrecordlength = len(mask.dtype)<EOL>if maskrecordlength:<EOL><INDENT>mrec._mask.flat = mask<EOL><DEDENT>elif len(mask.shape) == <NUM_LIT:2>:<EOL><INDENT>mrec._mask.flat = [tuple(m) for m in mask]<EOL><DEDENT>else:<EOL><INDENT>mrec.__setmask__(mask)<EOL><DEDENT><DEDENT>if _mask is not None:<EOL><INDENT>mrec._mask[:] = _mask<EOL><DEDENT>return mrec<EOL>

Creates a MaskedRecords from a list of records.

    Parameters
    ----------
    reclist : sequence
        A list of records. Each element of the sequence is first converted
        to a masked array if needed. If a 2D array is passed as argument, it is
        processed line by line
    dtype : {None, dtype}, optional
        Data type descriptor.
    shape : {None,int}, optional
        Number of records. If None, ``shape`` is defined from the shape of the
        first array in the list.
    formats : {None, sequence}, optional
        Sequence of formats for each individual field. If None, the formats will
        be autodetected by inspecting the fields and selecting the highest dtype
        possible.
    names : {None, sequence}, optional
        Sequence of the names of each field.
    fill_value : {None, sequence}, optional
        Sequence of data to be used as filling values.
    mask : {nomask, sequence}, optional.
        External mask to apply on the data.

    Notes
    -----
    Lists of tuples should be preferred over lists of lists for faster processing.


if self.size > <NUM_LIT:1>:<EOL><INDENT>mstr = ["<STR_LIT>" % "<STR_LIT:U+002C>".join([str(i) for i in s])<EOL>for s in zip(*[getattr(self, f) for f in self.dtype.names])]<EOL>return "<STR_LIT>" % "<STR_LIT:U+002CU+0020>".join(mstr)<EOL><DEDENT>else:<EOL><INDENT>mstr = ["<STR_LIT:%s>" % "<STR_LIT:U+002C>".join([str(i) for i in s])<EOL>for s in zip([getattr(self, f) for f in self.dtype.names])]<EOL>return "<STR_LIT>" % "<STR_LIT:U+002CU+0020>".join(mstr)<EOL><DEDENT>


if fill_value is not None:<EOL><INDENT>return self.filled(fill_value).tolist()<EOL><DEDENT>result = narray(self.filled().tolist(), dtype=object)<EOL>mask = narray(self._mask.tolist())<EOL>result[mask] = None<EOL>return result.tolist()<EOL>

Copy the data portion of the array to a hierarchical python
        list and returns that list.

        Data items are converted to the nearest compatible Python
        type.  Masked values are converted to fill_value. If
        fill_value is None, the corresponding entries in the output
        list will be ``None``.


def addfield(mrecord, newfield, newfieldname=None):

_data = mrecord._data<EOL>_mask = mrecord._mask<EOL>if newfieldname is None or newfieldname in reserved_fields:<EOL><INDENT>newfieldname = '<STR_LIT>' % len(_data.dtype)<EOL><DEDENT>newfield = ma.array(newfield)<EOL>newdtype = np.dtype(_data.dtype.descr + [(newfieldname, newfield.dtype)])<EOL>newdata = recarray(_data.shape, newdtype)<EOL>[newdata.setfield(_data.getfield(*f), *f)<EOL>for f in _data.dtype.fields.values()]<EOL>newdata.setfield(newfield._data, *newdata.dtype.fields[newfieldname])<EOL>newdata = newdata.view(MaskedRecords)<EOL>newmdtype = np.dtype([(n, bool_) for n in newdtype.names])<EOL>newmask = recarray(_data.shape, newmdtype)<EOL>[newmask.setfield(_mask.getfield(*f), *f)<EOL>for f in _mask.dtype.fields.values()]<EOL>newmask.setfield(getmaskarray(newfield),<EOL>*newmask.dtype.fields[newfieldname])<EOL>newdata._mask = newmask<EOL>return newdata<EOL>

Adds a new field to the masked record array, using `newfield` as data
and `newfieldname` as name. If `newfieldname` is None, the new field name is
set to 'fi', where `i` is the number of existing fields.


return umath.logical_or(umath.greater (x, self.b),<EOL>umath.less(x, self.a))<EOL>


m = getmask(a)<EOL>if m is nomask:<EOL><INDENT>d = umath.right_shift(filled(a), n)<EOL>return masked_array(d)<EOL><DEDENT>else:<EOL><INDENT>d = umath.right_shift(filled(a, <NUM_LIT:0>), n)<EOL>return masked_array(d, mask=m)<EOL><DEDENT>

Shift the bits of an integer to the right.

This is the masked array version of `numpy.right_shift`, for details
see that function.

See Also
--------
numpy.right_shift


self._hardmask = False<EOL>return self<EOL>

Force the mask to soft.

Whether the mask of a masked array is hard or soft is determined by
its `hardmask` property. `soften_mask` sets `hardmask` to False.

See Also
--------
hardmask


m = getmask(x)<EOL>if m is nomask:<EOL><INDENT>return False<EOL><DEDENT>elif m.any():<EOL><INDENT>return True<EOL><DEDENT>return False<EOL>

Determine whether input has masked values.

Accepts any object as input, but always returns False unless the
input is a MaskedArray containing masked values.

Parameters
----------
x : array_like
    Array to check for masked values.

Returns
-------
result : bool
    True if `x` is a MaskedArray with masked values, False otherwise.

Examples
--------
>>> import numpy.ma as ma
>>> x = ma.masked_equal([0, 1, 0, 2, 3], 0)
>>> x
masked_array(data = [-- 1 -- 2 3],
      mask = [ True False  True False False],
      fill_value=999999)
>>> ma.is_masked(x)
True
>>> x = ma.masked_equal([0, 1, 0, 2, 3], 42)
>>> x
masked_array(data = [0 1 0 2 3],
      mask = False,
      fill_value=999999)
>>> ma.is_masked(x)
False

Always returns False if `x` isn't a MaskedArray.

>>> x = [False, True, False]
>>> ma.is_masked(x)
False
>>> x = 'a string'
>>> ma.is_masked(x)
False


return getattr(a, '<STR_LIT>', nomask)<EOL>

Return the mask of a masked array, or nomask.

Return the mask of `a` as an ndarray if `a` is a `MaskedArray` and the
mask is not `nomask`, else return `nomask`. To guarantee a full array
of booleans of the same shape as a, use `getmaskarray`.

Parameters
----------
a : array_like
    Input `MaskedArray` for which the mask is required.

See Also
--------
getdata : Return the data of a masked array as an ndarray.
getmaskarray : Return the mask of a masked array, or full array of False.

Examples
--------
>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(data =
 [[1 --]
 [3 4]],
      mask =
 [[False  True]
 [False False]],
      fill_value=999999)
>>> ma.getmask(a)
array([[False,  True],
       [False, False]], dtype=bool)

Equivalently use the `MaskedArray` `mask` attribute.

>>> a.mask
array([[False,  True],
       [False, False]], dtype=bool)

Result when mask == `nomask`

>>> b = ma.masked_array([[1,2],[3,4]])
>>> b
masked_array(data =
 [[1 2]
 [3 4]],
      mask =
 False,
      fill_value=999999)
>>> ma.nomask
False
>>> ma.getmask(b) == ma.nomask
True
>>> b.mask == ma.nomask
True


return self._enabled<EOL>

Is the use of the display value enabled?


if isinstance(a, MaskedArray):<EOL><INDENT>a.set_fill_value(fill_value)<EOL><DEDENT>return<EOL>

Set the filling value of a, if a is a masked array.

This function changes the fill value of the masked array `a` in place.
If `a` is not a masked array, the function returns silently, without
doing anything.

Parameters
----------
a : array_like
    Input array.
fill_value : dtype
    Filling value. A consistency test is performed to make sure
    the value is compatible with the dtype of `a`.

Returns
-------
None
    Nothing returned by this function.

See Also
--------
maximum_fill_value : Return the default fill value for a dtype.
MaskedArray.fill_value : Return current fill value.
MaskedArray.set_fill_value : Equivalent method.

Examples
--------
>>> import numpy.ma as ma
>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> a = ma.masked_where(a < 3, a)
>>> a
masked_array(data = [-- -- -- 3 4],
      mask = [ True  True  True False False],
      fill_value=999999)
>>> ma.set_fill_value(a, -999)
>>> a
masked_array(data = [-- -- -- 3 4],
      mask = [ True  True  True False False],
      fill_value=-999)

Nothing happens if `a` is not a masked array.

>>> a = range(5)
>>> a
[0, 1, 2, 3, 4]
>>> ma.set_fill_value(a, 100)
>>> a
[0, 1, 2, 3, 4]
>>> a = np.arange(5)
>>> a
array([0, 1, 2, 3, 4])
>>> ma.set_fill_value(a, 100)
>>> a
array([0, 1, 2, 3, 4])


target = _check_fill_value(value, self.dtype)<EOL>_fill_value = self._fill_value<EOL>if _fill_value is None:<EOL><INDENT>self._fill_value = target<EOL><DEDENT>else:<EOL><INDENT>_fill_value[()] = target<EOL><DEDENT>

Set the filling value of the masked array.

Parameters
----------
value : scalar, optional
    The new filling value. Default is None, in which case a default
    based on the data type is used.

See Also
--------
ma.set_fill_value : Equivalent function.

Examples
--------
>>> x = np.ma.array([0, 1.], fill_value=-np.inf)
>>> x.fill_value
-inf
>>> x.set_fill_value(np.pi)
>>> x.fill_value
3.1415926535897931

Reset to default:

>>> x.set_fill_value()
>>> x.fill_value
1e+20


def allclose (a, b, masked_equal=True, rtol=<NUM_LIT>, atol=<NUM_LIT>):

x = masked_array(a, copy=False)<EOL>y = masked_array(b, copy=False)<EOL>dtype = np.result_type(y, <NUM_LIT:1.>)<EOL>if y.dtype != dtype:<EOL><INDENT>y = masked_array(y, dtype=dtype, copy=False)<EOL><DEDENT>m = mask_or(getmask(x), getmask(y))<EOL>xinf = np.isinf(masked_array(x, copy=False, mask=m)).filled(False)<EOL>if not np.all(xinf == filled(np.isinf(y), False)):<EOL><INDENT>return False<EOL><DEDENT>if not np.any(xinf):<EOL><INDENT>d = filled(umath.less_equal(umath.absolute(x - y),<EOL>atol + rtol * umath.absolute(y)),<EOL>masked_equal)<EOL>return np.all(d)<EOL><DEDENT>if not np.all(filled(x[xinf] == y[xinf], masked_equal)):<EOL><INDENT>return False<EOL><DEDENT>x = x[~xinf]<EOL>y = y[~xinf]<EOL>d = filled(umath.less_equal(umath.absolute(x - y),<EOL>atol + rtol * umath.absolute(y)),<EOL>masked_equal)<EOL>return np.all(d)<EOL>

Returns True if two arrays are element-wise equal within a tolerance.

This function is equivalent to `allclose` except that masked values
are treated as equal (default) or unequal, depending on the `masked_equal`
argument.

Parameters
----------
a, b : array_like
    Input arrays to compare.
masked_equal : bool, optional
    Whether masked values in `a` and `b` are considered equal (True) or not
    (False). They are considered equal by default.
rtol : float, optional
    Relative tolerance. The relative difference is equal to ``rtol * b``.
    Default is 1e-5.
atol : float, optional
    Absolute tolerance. The absolute difference is equal to `atol`.
    Default is 1e-8.

Returns
-------
y : bool
    Returns True if the two arrays are equal within the given
    tolerance, False otherwise. If either array contains NaN, then
    False is returned.

See Also
--------
all, any
numpy.allclose : the non-masked `allclose`.

Notes
-----
If the following equation is element-wise True, then `allclose` returns
True::

  absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))

Return True if all elements of `a` and `b` are equal subject to
given tolerances.

Examples
--------
>>> a = ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1])
>>> a
masked_array(data = [10000000000.0 1e-07 --],
             mask = [False False  True],
       fill_value = 1e+20)
>>> b = ma.array([1e10, 1e-8, -42.0], mask=[0, 0, 1])
>>> ma.allclose(a, b)
False

>>> a = ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
>>> b = ma.array([1.00001e10, 1e-9, -42.0], mask=[0, 0, 1])
>>> ma.allclose(a, b)
True
>>> ma.allclose(a, b, masked_equal=False)
False

Masked values are not compared directly.

>>> a = ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
>>> b = ma.array([1.00001e10, 1e-9, 42.0], mask=[0, 0, 1])
>>> ma.allclose(a, b)
True
>>> ma.allclose(a, b, masked_equal=False)
False


return isinstance(x, MaskedArray)<EOL>

Test whether input is an instance of MaskedArray.

This function returns True if `x` is an instance of MaskedArray
and returns False otherwise.  Any object is accepted as input.

Parameters
----------
x : object
    Object to test.

Returns
-------
result : bool
    True if `x` is a MaskedArray.

See Also
--------
isMA : Alias to isMaskedArray.
isarray : Alias to isMaskedArray.

Examples
--------
>>> import numpy.ma as ma
>>> a = np.eye(3, 3)
>>> a
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])
>>> m = ma.masked_values(a, 0)
>>> m
masked_array(data =
 [[1.0 -- --]
 [-- 1.0 --]
 [-- -- 1.0]],
      mask =
 [[False  True  True]
 [ True False  True]
 [ True  True False]],
      fill_value=0.0)
>>> ma.isMaskedArray(a)
False
>>> ma.isMaskedArray(m)
True
>>> ma.isMaskedArray([0, 1, 2])
False


m = self._mask<EOL>if m.ndim and not m.any():<EOL><INDENT>self._mask = nomask<EOL><DEDENT>return self<EOL>

Reduce a mask to nomask when possible.

Parameters
----------
None

Returns
-------
None

Examples
--------
>>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4)
>>> x.mask
array([[False, False],
       [False, False]], dtype=bool)
>>> x.shrink_mask()
>>> x.mask
False


if dtype is None:<EOL><INDENT>result = np.zeros(newshape, dtype=MaskType)<EOL><DEDENT>else:<EOL><INDENT>result = np.zeros(newshape, dtype=make_mask_descr(dtype))<EOL><DEDENT>return result<EOL>

Return a boolean mask of the given shape, filled with False.

This function returns a boolean ndarray with all entries False, that can
be used in common mask manipulations. If a complex dtype is specified, the
type of each field is converted to a boolean type.

Parameters
----------
newshape : tuple
    A tuple indicating the shape of the mask.
dtype : {None, dtype}, optional
    If None, use a MaskType instance. Otherwise, use a new datatype with
    the same fields as `dtype`, converted to boolean types.

Returns
-------
result : ndarray
    An ndarray of appropriate shape and dtype, filled with False.

See Also
--------
make_mask : Create a boolean mask from an array.
make_mask_descr : Construct a dtype description list from a given dtype.

Examples
--------
>>> import numpy.ma as ma
>>> ma.make_mask_none((3,))
array([False, False, False], dtype=bool)

Defining a more complex dtype.

>>> dtype = np.dtype({'names':['foo', 'bar'],
                      'formats':[np.float32, np.int]})
>>> dtype
dtype([('foo', '<f4'), ('bar', '<i4')])
>>> ma.make_mask_none((3,), dtype=dtype)
array([(False, False), (False, False), (False, False)],
      dtype=[('foo', '|b1'), ('bar', '|b1')])


m = getmask(a)<EOL>if m is nomask:<EOL><INDENT>d = umath.left_shift(filled(a), n)<EOL>return masked_array(d)<EOL><DEDENT>else:<EOL><INDENT>d = umath.left_shift(filled(a, <NUM_LIT:0>), n)<EOL>return masked_array(d, mask=m)<EOL><DEDENT>

Shift the bits of an integer to the left.

This is the masked array version of `numpy.left_shift`, for details
see that function.

See Also
--------
numpy.left_shift


fa = filled(a, <NUM_LIT:0>).ravel()<EOL>fb = filled(b, <NUM_LIT:0>).ravel()<EOL>d = np.outer(fa, fb)<EOL>ma = getmask(a)<EOL>mb = getmask(b)<EOL>if ma is nomask and mb is nomask:<EOL><INDENT>return masked_array(d)<EOL><DEDENT>ma = getmaskarray(a)<EOL>mb = getmaskarray(b)<EOL>m = make_mask(<NUM_LIT:1> - np.outer(<NUM_LIT:1> - ma, <NUM_LIT:1> - mb), copy=<NUM_LIT:0>)<EOL>return masked_array(d, mask=m)<EOL>

maskedarray version of the numpy function.


try:<EOL><INDENT>data = a._data<EOL><DEDENT>except AttributeError:<EOL><INDENT>data = np.array(a, copy=False, subok=subok)<EOL><DEDENT>if not subok:<EOL><INDENT>return data.view(ndarray)<EOL><DEDENT>return data<EOL>

Return the data of a masked array as an ndarray.

Return the data of `a` (if any) as an ndarray if `a` is a ``MaskedArray``,
else return `a` as a ndarray or subclass (depending on `subok`) if not.

Parameters
----------
a : array_like
    Input ``MaskedArray``, alternatively a ndarray or a subclass thereof.
subok : bool
    Whether to force the output to be a `pure` ndarray (False) or to
    return a subclass of ndarray if appropriate (True, default).

See Also
--------
getmask : Return the mask of a masked array, or nomask.
getmaskarray : Return the mask of a masked array, or full array of False.

Examples
--------
>>> import numpy.ma as ma
>>> a = ma.masked_equal([[1,2],[3,4]], 2)
>>> a
masked_array(data =
 [[1 --]
 [3 4]],
      mask =
 [[False  True]
 [False False]],
      fill_value=999999)
>>> ma.getdata(a)
array([[1, 2],
       [3, 4]])

Equivalently use the ``MaskedArray`` `data` attribute.

>>> a.data
array([[1, 2],
       [3, 4]])


m = getmask(other)<EOL>if self._mask is nomask:<EOL><INDENT>if m is not nomask and m.any():<EOL><INDENT>self._mask = make_mask_none(self.shape, self.dtype)<EOL>self._mask += m<EOL><DEDENT><DEDENT>elif m is not nomask:<EOL><INDENT>self._mask += m<EOL><DEDENT>ndarray.__isub__(self._data, np.where(self._mask, <NUM_LIT:0>, getdata(other)))<EOL>return self<EOL>


def argmin(a, axis=None, fill_value=None):

if fill_value is None:<EOL><INDENT>fill_value = default_fill_value(a)<EOL><DEDENT>d = filled(a, fill_value)<EOL>return d.argmin(axis=axis)<EOL>

Function version of the eponymous method.


m = getmask(other)<EOL>if self._mask is nomask:<EOL><INDENT>if m is not nomask and m.any():<EOL><INDENT>self._mask = make_mask_none(self.shape, self.dtype)<EOL>self._mask += m<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if m is not nomask:<EOL><INDENT>self._mask += m<EOL><DEDENT><DEDENT>ndarray.__iadd__(self._data, np.where(self._mask, <NUM_LIT:0>, getdata(other)))<EOL>return self<EOL>


target = narray(target, copy=False, subok=True)<EOL>m = getmask(target)<EOL>if axis is not None:<EOL><INDENT>kargs = { '<STR_LIT>' : axis }<EOL><DEDENT>else:<EOL><INDENT>kargs = {}<EOL>target = target.ravel()<EOL>if not (m is nomask):<EOL><INDENT>m = m.ravel()<EOL><DEDENT><DEDENT>if m is nomask:<EOL><INDENT>t = self.ufunc.reduce(target, **kargs)<EOL><DEDENT>else:<EOL><INDENT>target = target.filled(self.fill_value_func(target)).view(type(target))<EOL>t = self.ufunc.reduce(target, **kargs)<EOL>m = umath.logical_and.reduce(m, **kargs)<EOL>if hasattr(t, '<STR_LIT>'):<EOL><INDENT>t._mask = m<EOL><DEDENT>elif m:<EOL><INDENT>t = masked<EOL><DEDENT><DEDENT>return t<EOL>


if masked_print_option.enabled():<EOL><INDENT>f = masked_print_option<EOL>if self is masked:<EOL><INDENT>return str(f)<EOL><DEDENT>m = self._mask<EOL>if m is nomask:<EOL><INDENT>res = self._data<EOL><DEDENT>else:<EOL><INDENT>if m.shape == ():<EOL><INDENT>if m.dtype.names:<EOL><INDENT>m = m.view((bool, len(m.dtype)))<EOL>if m.any():<EOL><INDENT>return str(tuple((f if _m else _d) for _d, _m in<EOL>zip(self._data.tolist(), m)))<EOL><DEDENT>else:<EOL><INDENT>return str(self._data)<EOL><DEDENT><DEDENT>elif m:<EOL><INDENT>return str(f)<EOL><DEDENT>else:<EOL><INDENT>return str(self._data)<EOL><DEDENT><DEDENT>names = self.dtype.names<EOL>if names is None:<EOL><INDENT>res = self._data.astype("<STR_LIT:O>")<EOL>res.view(ndarray)[m] = f<EOL><DEDENT>else:<EOL><INDENT>rdtype = _recursive_make_descr(self.dtype, "<STR_LIT:O>")<EOL>res = self._data.astype(rdtype)<EOL>_recursive_printoption(res, m, f)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>res = self.filled(self.fill_value)<EOL><DEDENT>return str(res)<EOL>


def prod(self, axis=None, dtype=None, out=None):

_mask = ndarray.__getattribute__(self, '<STR_LIT>')<EOL>newmask = _check_mask_axis(_mask, axis)<EOL>if out is None:<EOL><INDENT>result = self.filled(<NUM_LIT:1>).prod(axis, dtype=dtype)<EOL>rndim = getattr(result, '<STR_LIT>', <NUM_LIT:0>)<EOL>if rndim:<EOL><INDENT>result = result.view(type(self))<EOL>result.__setmask__(newmask)<EOL><DEDENT>elif newmask:<EOL><INDENT>result = masked<EOL><DEDENT>return result<EOL><DEDENT>result = self.filled(<NUM_LIT:1>).prod(axis, dtype=dtype, out=out)<EOL>if isinstance(out, MaskedArray):<EOL><INDENT>outmask = getattr(out, '<STR_LIT>', nomask)<EOL>if (outmask is nomask):<EOL><INDENT>outmask = out._mask = make_mask_none(out.shape)<EOL><DEDENT>outmask.flat = newmask<EOL><DEDENT>return out<EOL>

Return the product of the array elements over the given axis.
Masked elements are set to 1 internally for computation.

Parameters
----------
axis : {None, int}, optional
    Axis over which the product is taken. If None is used, then the
    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
    platform integer, then the default platform integer precision is
    used.  Otherwise, the dtype is the same as that of a.
out : {None, array}, 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.

Returns
-------
product_along_axis : {array, scalar}, see dtype parameter above.
    Returns an array whose shape is the same as a with the specified
    axis removed. Returns a 0d array when a is 1d or axis=None.
    Returns a reference to the specified output array if specified.

See Also
--------
prod : equivalent function

Notes
-----
Arithmetic is modular when using integer types, and no error is raised
on overflow.

Examples
--------
>>> np.prod([1.,2.])
2.0
>>> np.prod([1.,2.], dtype=np.int32)
2
>>> np.prod([[1.,2.],[3.,4.]])
24.0
>>> np.prod([[1.,2.],[3.,4.]], axis=1)
array([  2.,  12.])


def __setmask__(self, mask, copy=False):

idtype = ndarray.__getattribute__(self, '<STR_LIT>')<EOL>current_mask = ndarray.__getattribute__(self, '<STR_LIT>')<EOL>if mask is masked:<EOL><INDENT>mask = True<EOL><DEDENT>if (current_mask is nomask):<EOL><INDENT>if mask is nomask:<EOL><INDENT>return<EOL><DEDENT>current_mask = self._mask = make_mask_none(self.shape, idtype)<EOL><DEDENT>if idtype.names is None:<EOL><INDENT>if self._hardmask:<EOL><INDENT>current_mask |= mask<EOL><DEDENT>elif isinstance(mask, (int, float, np.bool_, np.number)):<EOL><INDENT>current_mask[...] = mask<EOL><DEDENT>else:<EOL><INDENT>current_mask.flat = mask<EOL><DEDENT><DEDENT>else:<EOL><INDENT>mdtype = current_mask.dtype<EOL>mask = np.array(mask, copy=False)<EOL>if not mask.ndim:<EOL><INDENT>if mask.dtype.kind == '<STR_LIT:b>':<EOL><INDENT>mask = np.array(tuple([mask.item()]*len(mdtype)),<EOL>dtype=mdtype)<EOL><DEDENT>else:<EOL><INDENT>mask = mask.astype(mdtype)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>mask = np.array(mask, copy=copy, dtype=mdtype)<EOL><DEDENT>except TypeError:<EOL><INDENT>mask = np.array([tuple([m] * len(mdtype)) for m in mask],<EOL>dtype=mdtype)<EOL><DEDENT><DEDENT>if self._hardmask:<EOL><INDENT>for n in idtype.names:<EOL><INDENT>current_mask[n] |= mask[n]<EOL><DEDENT><DEDENT>elif isinstance(mask, (int, float, np.bool_, np.number)):<EOL><INDENT>current_mask[...] = mask<EOL><DEDENT>else:<EOL><INDENT>current_mask.flat = mask<EOL><DEDENT><DEDENT>if current_mask.shape:<EOL><INDENT>current_mask.shape = self.shape<EOL><DEDENT>return<EOL>


cf = '<STR_LIT>'[self.flags.fnc]<EOL>state = (<NUM_LIT:1>,<EOL>self.shape,<EOL>self.dtype,<EOL>self.flags.fnc,<EOL>self._data.tobytes(cf),<EOL>getmaskarray(self).tobytes(cf),<EOL>self._fill_value,<EOL>)<EOL>return state<EOL>

Return the internal state of the masked array, for pickling
        purposes.


def compress(self, condition, axis=None, out=None):

<EOL>(_data, _mask) = (self._data, self._mask)<EOL>condition = np.array(condition, copy=False, subok=False)<EOL>_new = _data.compress(condition, axis=axis, out=out).view(type(self))<EOL>_new._update_from(self)<EOL>if _mask is not nomask:<EOL><INDENT>_new._mask = _mask.compress(condition, axis=axis)<EOL><DEDENT>return _new<EOL>

Return `a` where condition is ``True``.

If condition is a `MaskedArray`, missing values are considered
as ``False``.

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.

Returns
-------
result : MaskedArray
    A :class:`MaskedArray` object.

Notes
-----
Please note the difference with :meth:`compressed` !
The output of :meth:`compress` has a mask, the output of
:meth:`compressed` does not.

Examples
--------
>>> x = np.ma.array([[1,2,3],[4,5,6],[7,8,9]], mask=[0] + [1,0]*4)
>>> print x
[[1 -- 3]
 [-- 5 --]
 [7 -- 9]]
>>> x.compress([1, 0, 1])
masked_array(data = [1 3],
      mask = [False False],
      fill_value=999999)

>>> x.compress([1, 0, 1], axis=1)
masked_array(data =
 [[1 3]
 [-- --]
 [7 9]],
      mask =
 [[False False]
 [ True  True]
 [False False]],
      fill_value=999999)


def min(self, axis=None, out=None, fill_value=None):

_mask = ndarray.__getattribute__(self, '<STR_LIT>')<EOL>newmask = _check_mask_axis(_mask, axis)<EOL>if fill_value is None:<EOL><INDENT>fill_value = minimum_fill_value(self)<EOL><DEDENT>if out is None:<EOL><INDENT>result = self.filled(fill_value).min(axis=axis, out=out).view(type(self))<EOL>if result.ndim:<EOL><INDENT>result.__setmask__(newmask)<EOL>if newmask.ndim:<EOL><INDENT>np.copyto(result, result.fill_value, where=newmask)<EOL><DEDENT><DEDENT>elif newmask:<EOL><INDENT>result = masked<EOL><DEDENT>return result<EOL><DEDENT>result = self.filled(fill_value).min(axis=axis, out=out)<EOL>if isinstance(out, MaskedArray):<EOL><INDENT>outmask = getattr(out, '<STR_LIT>', nomask)<EOL>if (outmask is nomask):<EOL><INDENT>outmask = out._mask = make_mask_none(out.shape)<EOL><DEDENT>outmask.flat = newmask<EOL><DEDENT>else:<EOL><INDENT>if out.dtype.kind in '<STR_LIT>':<EOL><INDENT>errmsg = "<STR_LIT>""<STR_LIT>"<EOL>raise MaskError(errmsg)<EOL><DEDENT>np.copyto(out, np.nan, where=newmask)<EOL><DEDENT>return out<EOL>

Return the minimum along a given axis.

Parameters
----------
axis : {None, int}, optional
    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.
fill_value : {var}, optional
    Value used to fill in the masked values.
    If None, use the output of `minimum_fill_value`.

Returns
-------
amin : array_like
    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.


<EOL>if not isinstance(ndtype, np.dtype):<EOL><INDENT>ndtype = np.dtype(ndtype)<EOL><DEDENT>return np.dtype(_recursive_make_descr(ndtype, np.bool))<EOL>

Construct a dtype description list from a given dtype.

Returns a new dtype object, with the type of all fields in `ndtype` to a
boolean type. Field names are not altered.

Parameters
----------
ndtype : dtype
    The dtype to convert.

Returns
-------
result : dtype
    A dtype that looks like `ndtype`, the type of all fields is boolean.

Examples
--------
>>> import numpy.ma as ma
>>> dtype = np.dtype({'names':['foo', 'bar'],
                      'formats':[np.float32, np.int]})
>>> dtype
dtype([('foo', '<f4'), ('bar', '<i4')])
>>> ma.make_mask_descr(dtype)
dtype([('foo', '|b1'), ('bar', '|b1')])
>>> ma.make_mask_descr(np.float32)
<type 'numpy.bool_'>


def argmax(a, axis=None, fill_value=None):

if fill_value is None:<EOL><INDENT>fill_value = default_fill_value(a)<EOL>try:<EOL><INDENT>fill_value = -fill_value<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>d = filled(a, fill_value)<EOL>return d.argmax(axis=axis)<EOL>


return np.size(getdata(obj), axis)<EOL>


ndtype = np.dtype(ndtype)<EOL>fields = ndtype.fields<EOL>if fill_value is None:<EOL><INDENT>if fields:<EOL><INDENT>descr = ndtype.descr<EOL>fill_value = np.array(_recursive_set_default_fill_value(descr),<EOL>dtype=ndtype,)<EOL><DEDENT>else:<EOL><INDENT>fill_value = default_fill_value(ndtype)<EOL><DEDENT><DEDENT>elif fields:<EOL><INDENT>fdtype = [(_[<NUM_LIT:0>], _[<NUM_LIT:1>]) for _ in ndtype.descr]<EOL>if isinstance(fill_value, (ndarray, np.void)):<EOL><INDENT>try:<EOL><INDENT>fill_value = np.array(fill_value, copy=False, dtype=fdtype)<EOL><DEDENT>except ValueError:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>raise ValueError(err_msg % (fill_value, fdtype))<EOL><DEDENT><DEDENT>else:<EOL><INDENT>descr = ndtype.descr<EOL>fill_value = np.asarray(fill_value, dtype=object)<EOL>fill_value = np.array(_recursive_set_fill_value(fill_value, descr),<EOL>dtype=ndtype)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if isinstance(fill_value, basestring) and (ndtype.char not in '<STR_LIT>'):<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>raise TypeError(err_msg % ndtype)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>fill_value = np.array(fill_value, copy=False, dtype=ndtype)<EOL><DEDENT>except OverflowError:<EOL><INDENT>err_msg = "<STR_LIT>"<EOL>raise TypeError(err_msg % (fill_value, ndtype))<EOL><DEDENT><DEDENT><DEDENT>return np.array(fill_value)<EOL>

Private function validating the given `fill_value` for the given dtype.

If fill_value is None, it is set to the default corresponding to the dtype
if this latter is standard (no fields). If the datatype is flexible (named
fields), fill_value is set to a tuple whose elements are the default fill
values corresponding to each field.

If fill_value is not None, its value is forced to the given dtype.


if self is masked:<EOL><INDENT>raise MaskError('<STR_LIT>')<EOL>

x.__setitem__(i, y) <==> x[i]=y

        Set item described by index. If value is masked, masks those
        locations.


def view(self, dtype=None, type=None, fill_value=None):

if dtype is None:<EOL><INDENT>if type is None:<EOL><INDENT>output = ndarray.view(self)<EOL><DEDENT>else:<EOL><INDENT>output = ndarray.view(self, type)<EOL><DEDENT><DEDENT>elif type is None:<EOL><INDENT>try:<EOL><INDENT>if issubclass(dtype, ndarray):<EOL><INDENT>output = ndarray.view(self, dtype)<EOL>dtype = None<EOL><DEDENT>else:<EOL><INDENT>output = ndarray.view(self, dtype)<EOL><DEDENT><DEDENT>except TypeError:<EOL><INDENT>output = ndarray.view(self, dtype)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>output = ndarray.view(self, dtype, type)<EOL><DEDENT>if (getattr(output, '<STR_LIT>', nomask) is not nomask):<EOL><INDENT>if dtype is None:<EOL><INDENT>dtype = output.dtype<EOL><DEDENT>mdtype = make_mask_descr(dtype)<EOL>output._mask = self._mask.view(mdtype, ndarray)<EOL>try:<EOL><INDENT>output._mask.shape = output.shape<EOL><DEDENT>except (AttributeError, TypeError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>if getattr(output, '<STR_LIT>', None) is not None:<EOL><INDENT>if fill_value is None:<EOL><INDENT>if dtype is None:<EOL><INDENT>pass <EOL><DEDENT>else:<EOL><INDENT>output._fill_value = None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>output.fill_value = fill_value<EOL><DEDENT><DEDENT>return output<EOL>

Return a view of the MaskedArray data

Parameters
----------
dtype : data-type or ndarray sub-class, optional
    Data-type descriptor of the returned view, e.g., float32 or int16.
    The default, None, results in the view having the same data-type
    as `a`. As with ``ndarray.view``, dtype can also be specified as
    an ndarray sub-class, which then specifies the type of the
    returned object (this is equivalent to setting the ``type``
    parameter).
type : Python type, optional
    Type of the returned view, e.g., ndarray or matrix.  Again, the
    default None results in type preservation.

Notes
-----

``a.view()`` is used two different ways:

``a.view(some_dtype)`` or ``a.view(dtype=some_dtype)`` constructs a view
of the array's memory with a different data-type.  This can cause a
reinterpretation of the bytes of memory.

``a.view(ndarray_subclass)`` or ``a.view(type=ndarray_subclass)`` just
returns an instance of `ndarray_subclass` that looks at the same array
(same shape, dtype, etc.)  This does not cause a reinterpretation of the
memory.

If `fill_value` is not specified, but `dtype` is specified (and is not
an ndarray sub-class), the `fill_value` of the MaskedArray will be
reset. If neither `fill_value` nor `dtype` are specified (or if
`dtype` is an ndarray sub-class), then the fill value is preserved.
Finally, if `fill_value` is specified, but `dtype` is not, the fill
value is set to the specified value.

For ``a.view(some_dtype)``, if ``some_dtype`` has a different number of
bytes per entry than the previous dtype (for example, converting a
regular array to a structured array), then the behavior of the view
cannot be predicted just from the superficial appearance of ``a`` (shown
by ``print(a)``). It also depends on exactly how ``a`` is stored in
memory. Therefore if ``a`` is C-ordered versus fortran-ordered, versus
defined as a slice or transpose, etc., the view may give different
results.


ma = getmask(a)<EOL>mb = getmask(b)<EOL>if ma is nomask and mb is nomask:<EOL><INDENT>m = nomask<EOL><DEDENT>else:<EOL><INDENT>ma = getmaskarray(a)<EOL>mb = getmaskarray(b)<EOL>m = logical_or.outer(ma, mb)<EOL><DEDENT>result = self.ufunc.outer(filled(a), filled(b))<EOL>if not isinstance(result, MaskedArray):<EOL><INDENT>result = result.view(MaskedArray)<EOL><DEDENT>result._mask = m<EOL>return result<EOL>

Return the function applied to the outer product of a and b.


return divide(self, other)<EOL>

Divide other into self, and return a new masked array.


return floor_divide(other, self)<EOL>


def array(data, dtype=None, copy=False, order=False,<EOL>mask=nomask, fill_value=None,<EOL>keep_mask=True, hard_mask=False, shrink=True, subok=True, ndmin=<NUM_LIT:0>,<EOL>):

<EOL>return MaskedArray(data, mask=mask, dtype=dtype, copy=copy, subok=subok,<EOL>keep_mask=keep_mask, hard_mask=hard_mask,<EOL>fill_value=fill_value, ndmin=ndmin, shrink=shrink)<EOL>

array(data, dtype=None, copy=False, order=False, mask=nomask,
             fill_value=None, keep_mask=True, hard_mask=False, shrink=True,
             subok=True, ndmin=0)

    Acts as shortcut to MaskedArray, with options in a different order
    for convenience.  And backwards compatibility...


def masked_less_equal(x, value, copy=True):

return masked_where(less_equal(x, value), x, copy=copy)<EOL>

Mask an array where less than or equal to a given value.

This function is a shortcut to ``masked_where``, with
`condition` = (x <= value).

See Also
--------
masked_where : Mask where a condition is met.

Examples
--------
>>> import numpy.ma as ma
>>> a = np.arange(4)
>>> a
array([0, 1, 2, 3])
>>> ma.masked_less_equal(a, 2)
masked_array(data = [-- -- -- 3],
      mask = [ True  True  True False],
      fill_value=999999)


d = np.concatenate([getdata(a) for a in arrays], axis)<EOL>rcls = get_masked_subclass(*arrays)<EOL>data = d.view(rcls)<EOL>for x in arrays:<EOL><INDENT>if getmask(x) is not nomask:<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return data<EOL><DEDENT>dm = np.concatenate([getmaskarray(a) for a in arrays], axis)<EOL><INDENT>shrink = numpy.logical_or.reduce([getattr(a,'<STR_LIT>',True) for a in arrays])<EOL>if shrink and not dm.any():<EOL><DEDENT>if not dm.dtype.fields and not dm.any():<EOL><INDENT>data._mask = nomask<EOL><DEDENT>else:<EOL><INDENT>data._mask = dm.reshape(d.shape)<EOL><DEDENT>return data<EOL>

Concatenate a sequence of arrays along the given axis.

Parameters
----------
arrays : sequence of array_like
    The arrays must have the same shape, except in the dimension
    corresponding to `axis` (the first, by default).
axis : int, optional
    The axis along which the arrays will be joined. Default is 0.

Returns
-------
result : MaskedArray
    The concatenated array with any masked entries preserved.

See Also
--------
numpy.concatenate : Equivalent function in the top-level NumPy module.

Examples
--------
>>> import numpy.ma as ma
>>> a = ma.arange(3)
>>> a[1] = ma.masked
>>> b = ma.arange(2, 5)
>>> a
masked_array(data = [0 -- 2],
             mask = [False  True False],
       fill_value = 999999)
>>> b
masked_array(data = [2 3 4],
             mask = False,
       fill_value = 999999)
>>> ma.concatenate([a, b])
masked_array(data = [0 -- 2 2 3 4],
             mask = [False  True False False False False],
       fill_value = 999999)


m = self._mask<EOL>if m is nomask:<EOL><INDENT>return self._data<EOL><DEDENT>if fill_value is None:<EOL><INDENT>fill_value = self.fill_value<EOL><DEDENT>else:<EOL><INDENT>fill_value = _check_fill_value(fill_value, self.dtype)<EOL><DEDENT>if self is masked_singleton:<EOL><INDENT>return np.asanyarray(fill_value)<EOL><DEDENT>if m.dtype.names:<EOL><INDENT>result = self._data.copy('<STR_LIT>')<EOL>_recursive_filled(result, self._mask, fill_value)<EOL><DEDENT>elif not m.any():<EOL><INDENT>return self._data<EOL><DEDENT>else:<EOL><INDENT>result = self._data.copy('<STR_LIT>')<EOL>try:<EOL><INDENT>np.copyto(result, fill_value, where=m)<EOL><DEDENT>except (TypeError, AttributeError):<EOL><INDENT>fill_value = narray(fill_value, dtype=object)<EOL>d = result.astype(object)<EOL>result = np.choose(m, (d, fill_value))<EOL><DEDENT>except IndexError:<EOL><INDENT>if self._data.shape:<EOL><INDENT>raise<EOL><DEDENT>elif m:<EOL><INDENT>result = np.array(fill_value, dtype=self.dtype)<EOL><DEDENT>else:<EOL><INDENT>result = self._data<EOL><DEDENT><DEDENT><DEDENT>return result<EOL>

Return a copy of self, with masked values filled with a given value.

Parameters
----------
fill_value : scalar, optional
    The value to use for invalid entries (None by default).
    If None, the `fill_value` attribute of the array is used instead.

Returns
-------
filled_array : ndarray
    A copy of ``self`` with invalid entries replaced by *fill_value*
    (be it the function argument or the attribute of ``self``.

Notes
-----
The result is **not** a MaskedArray!

Examples
--------
>>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999)
>>> x.filled()
array([1, 2, -999, 4, -999])
>>> type(x.filled())
<type 'numpy.ndarray'>

Subclassing is preserved. This means that if the data part of the masked
array is a matrix, `filled` returns a matrix:

>>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
>>> x.filled()
matrix([[     1, 999999],
        [999999,      4]])


if axis is None:<EOL><INDENT>return minimum(self)<EOL><DEDENT>else:<EOL><INDENT>return minimum.reduce(self, axis)<EOL><DEDENT>

Return the array minimum along the specified axis.

Parameters
----------
axis : int, optional
    The axis along which to find the minima. Default is None, in which case
    the minimum value in the whole array is returned.

Returns
-------
min : scalar or MaskedArray
    If `axis` is None, the result is a scalar. Otherwise, if `axis` is
    given and the array is at least 2-D, the result is a masked array with
    dimension one smaller than the array on which `mini` is called.

Examples
--------
>>> x = np.ma.array(np.arange(6), mask=[0 ,1, 0, 0, 0 ,1]).reshape(3, 2)
>>> print x
[[0 --]
 [2 3]
 [4 --]]
>>> x.mini()
0
>>> x.mini(axis=0)
masked_array(data = [0 3],
             mask = [False False],
       fill_value = 999999)
>>> print x.mini(axis=1)
[0 2 4]


if hasattr(obj, '<STR_LIT>'):<EOL><INDENT>defval = _check_fill_value(None, obj.dtype)<EOL><DEDENT>elif isinstance(obj, np.dtype):<EOL><INDENT>if obj.subdtype:<EOL><INDENT>defval = default_filler.get(obj.subdtype[<NUM_LIT:0>].kind, '<STR_LIT:?>')<EOL><DEDENT>elif obj.kind in '<STR_LIT>':<EOL><INDENT>defval = default_filler.get(obj.str[<NUM_LIT:1>:], '<STR_LIT:?>')<EOL><DEDENT>else:<EOL><INDENT>defval = default_filler.get(obj.kind, '<STR_LIT:?>')<EOL><DEDENT><DEDENT>elif isinstance(obj, float):<EOL><INDENT>defval = default_filler['<STR_LIT:f>']<EOL><DEDENT>elif isinstance(obj, int) or isinstance(obj, long):<EOL><INDENT>defval = default_filler['<STR_LIT:i>']<EOL><DEDENT>elif isinstance(obj, str):<EOL><INDENT>defval = default_filler['<STR_LIT:S>']<EOL><DEDENT>elif isinstance(obj, unicode):<EOL><INDENT>defval = default_filler['<STR_LIT>']<EOL><DEDENT>elif isinstance(obj, complex):<EOL><INDENT>defval = default_filler['<STR_LIT:c>']<EOL><DEDENT>else:<EOL><INDENT>defval = default_filler['<STR_LIT:O>']<EOL><DEDENT>return defval<EOL>

Return the default fill value for the argument object.

The default filling value depends on the datatype of the input
array or the type of the input scalar:

   ========  ========
   datatype  default
   ========  ========
   bool      True
   int       999999
   float     1.e20
   complex   1.e20+0j
   object    '?'
   string    'N/A'
   ========  ========

Parameters
----------
obj : ndarray, dtype or scalar
    The array data-type or scalar for which the default fill value
    is returned.

Returns
-------
fill_value : scalar
    The default fill value.

Examples
--------
>>> np.ma.default_fill_value(1)
999999
>>> np.ma.default_fill_value(np.array([1.1, 2., np.pi]))
1e+20
>>> np.ma.default_fill_value(np.dtype(complex))
(1e+20+0j)


def make_mask(m, copy=False, shrink=True, dtype=MaskType):

if m is nomask:<EOL><INDENT>return nomask<EOL><DEDENT>elif isinstance(m, ndarray):<EOL><INDENT>m = filled(m, True)<EOL>dtype = make_mask_descr(dtype)<EOL>if m.dtype == dtype:<EOL><INDENT>if copy:<EOL><INDENT>result = m.copy()<EOL><DEDENT>else:<EOL><INDENT>result = m<EOL><DEDENT><DEDENT>else:<EOL><INDENT>result = np.array(m, dtype=dtype, copy=copy)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>result = np.array(filled(m, True), dtype=MaskType)<EOL><DEDENT>if shrink and (not result.dtype.names) and (not result.any()):<EOL><INDENT>return nomask<EOL><DEDENT>else:<EOL><INDENT>return result<EOL><DEDENT>

Create a boolean mask from an array.

Return `m` as a boolean mask, creating a copy if necessary or requested.
The function can accept any sequence that is convertible to integers,
or ``nomask``.  Does not require that contents must be 0s and 1s, values
of 0 are interepreted as False, everything else as True.

Parameters
----------
m : array_like
    Potential mask.
copy : bool, optional
    Whether to return a copy of `m` (True) or `m` itself (False).
shrink : bool, optional
    Whether to shrink `m` to ``nomask`` if all its values are False.
dtype : dtype, optional
    Data-type of the output mask. By default, the output mask has
    a dtype of MaskType (bool). If the dtype is flexible, each field
    has a boolean dtype.

Returns
-------
result : ndarray
    A boolean mask derived from `m`.

Examples
--------
>>> import numpy.ma as ma
>>> m = [True, False, True, True]
>>> ma.make_mask(m)
array([ True, False,  True,  True], dtype=bool)
>>> m = [1, 0, 1, 1]
>>> ma.make_mask(m)
array([ True, False,  True,  True], dtype=bool)
>>> m = [1, 0, 2, -3]
>>> ma.make_mask(m)
array([ True, False,  True,  True], dtype=bool)

Effect of the `shrink` parameter.

>>> m = np.zeros(4)
>>> m
array([ 0.,  0.,  0.,  0.])
>>> ma.make_mask(m)
False
>>> ma.make_mask(m, shrink=False)
array([False, False, False, False], dtype=bool)

Using a flexible `dtype`.

>>> m = [1, 0, 1, 1]
>>> n = [0, 1, 0, 0]
>>> arr = []
>>> for man, mouse in zip(m, n):
...     arr.append((man, mouse))
>>> arr
[(1, 0), (0, 1), (1, 0), (1, 0)]
>>> dtype = np.dtype({'names':['man', 'mouse'],
                      'formats':[np.int, np.int]})
>>> arr = np.array(arr, dtype=dtype)
>>> arr
array([(1, 0), (0, 1), (1, 0), (1, 0)],
      dtype=[('man', '<i4'), ('mouse', '<i4')])
>>> ma.make_mask(arr, dtype=dtype)
array([(True, False), (False, True), (True, False), (True, False)],
      dtype=[('man', '|b1'), ('mouse', '|b1')])


return pickle.loads(strg)<EOL>

Load a pickle from the current string.

The result of ``cPickle.loads(strg)`` is returned.

Parameters
----------
strg : str
    The string to load.

See Also
--------
dumps : Return a string corresponding to the pickling of a masked array.


result = n_expand_dims(x, axis)<EOL>if isinstance(x, MaskedArray):<EOL><INDENT>new_shape = result.shape<EOL>result = x.view()<EOL>result.shape = new_shape<EOL>if result._mask is not nomask:<EOL><INDENT>result._mask.shape = new_shape<EOL><DEDENT><DEDENT>return result<EOL>

Expand the shape of an array.

Expands the shape of the array by including a new axis before the one
specified by the `axis` parameter. This function behaves the same as
`numpy.expand_dims` but preserves masked elements.

See Also
--------
numpy.expand_dims : Equivalent function in top-level NumPy module.

Examples
--------
>>> import numpy.ma as ma
>>> x = ma.array([1, 2, 4])
>>> x[1] = ma.masked
>>> x
masked_array(data = [1 -- 4],
             mask = [False  True False],
       fill_value = 999999)
>>> np.expand_dims(x, axis=0)
array([[1, 2, 4]])
>>> ma.expand_dims(x, axis=0)
masked_array(data =
 [[1 -- 4]],
             mask =
 [[False  True False]],
       fill_value = 999999)

The same result can be achieved using slicing syntax with `np.newaxis`.

>>> x[np.newaxis, :]
masked_array(data =
 [[1 -- 4]],
             mask =
 [[False  True False]],
       fill_value = 999999)


y = self.ravel()<EOL>y[:] = value<EOL>

Set a flattened version of self to value.


return add(self, other)<EOL>

Add other to self, and return a new masked array.


def put(a, indices, values, mode='<STR_LIT>'):

<EOL>try:<EOL><INDENT>return a.put(indices, values, mode=mode)<EOL><DEDENT>except AttributeError:<EOL><INDENT>return narray(a, copy=False).put(indices, values, mode=mode)<EOL><DEDENT>

Set storage-indexed locations to corresponding values.

This function is equivalent to `MaskedArray.put`, see that method
for details.

See Also
--------
MaskedArray.put


def resize(self, newshape, refcheck=True, order=False):

<EOL><INDENT>try:<EOL><INDENT>ndarray.resize(self, newshape, refcheck=refcheck)<EOL>if self.mask is not nomask:<EOL><INDENT>self._mask.resize(newshape, refcheck=refcheck)<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return None<EOL><DEDENT>errmsg = "<STR_LIT>""<STR_LIT>""<STR_LIT>"<EOL>raise ValueError(errmsg)<EOL>

.. warning::

    This method does nothing, except raise a ValueError exception. A
    masked array does not own its data and therefore cannot safely be
    resized in place. Use the `numpy.ma.resize` function instead.

This method is difficult to implement safely and may be deprecated in
future releases of NumPy.


<EOL>try:<EOL><INDENT>return a.transpose(axes)<EOL><DEDENT>except AttributeError:<EOL><INDENT>return narray(a, copy=False).transpose(axes).view(MaskedArray)<EOL><DEDENT>

Permute the dimensions of an array.

This function is exactly equivalent to `numpy.transpose`.

See Also
--------
numpy.transpose : Equivalent function in top-level NumPy module.

Examples
--------
>>> import numpy.ma as ma
>>> x = ma.arange(4).reshape((2,2))
>>> x[1, 1] = ma.masked
>>>> x
masked_array(data =
 [[0 1]
 [2 --]],
             mask =
 [[False False]
 [False  True]],
       fill_value = 999999)
>>> ma.transpose(x)
masked_array(data =
 [[0 2]
 [1 --]],
             mask =
 [[False False]
 [False  True]],
       fill_value = 999999)


if x is None and y is None:<EOL><INDENT>return filled(condition, <NUM_LIT:0>).nonzero()<EOL><DEDENT>elif x is None or y is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>fc = filled(condition, <NUM_LIT:0>).astype(MaskType)<EOL>notfc = np.logical_not(fc)<EOL>xv = getdata(x)<EOL>yv = getdata(y)<EOL>if x is masked:<EOL><INDENT>ndtype = yv.dtype<EOL><DEDENT>elif y is masked:<EOL><INDENT>ndtype = xv.dtype<EOL><DEDENT>else:<EOL><INDENT>ndtype = np.find_common_type([xv.dtype, yv.dtype], [])<EOL><DEDENT>d = np.empty(fc.shape, dtype=ndtype).view(MaskedArray)<EOL>_data = d._data<EOL>np.copyto(_data, xv.astype(ndtype), where=fc)<EOL>np.copyto(_data, yv.astype(ndtype), where=notfc)<EOL>_mask = d._mask = np.zeros(fc.shape, dtype=MaskType)<EOL>np.copyto(_mask, getmask(x), where=fc)<EOL>np.copyto(_mask, getmask(y), where=notfc)<EOL>_mask |= getmaskarray(condition)<EOL>if not _mask.any():<EOL><INDENT>d._mask = nomask<EOL><DEDENT>return d<EOL>

Return a masked array with elements from x or y, depending on condition.

Returns a masked array, shaped like condition, where the elements
are from `x` when `condition` is True, and from `y` otherwise.
If neither `x` nor `y` are given, the function returns a tuple of
indices where `condition` is True (the result of
``condition.nonzero()``).

Parameters
----------
condition : array_like, bool
    The condition to meet. For each True element, yield the corresponding
    element from `x`, otherwise from `y`.
x, y : array_like, optional
    Values from which to choose. `x` and `y` need to have the same shape
    as condition, or be broadcast-able to that shape.

Returns
-------
out : MaskedArray or tuple of ndarrays
    The resulting masked array if `x` and `y` were given, otherwise
    the result of ``condition.nonzero()``.

See Also
--------
numpy.where : Equivalent function in the top-level NumPy module.

Examples
--------
>>> x = np.ma.array(np.arange(9.).reshape(3, 3), mask=[[0, 1, 0],
...                                                    [1, 0, 1],
...                                                    [0, 1, 0]])
>>> print x
[[0.0 -- 2.0]
 [-- 4.0 --]
 [6.0 -- 8.0]]
>>> np.ma.where(x > 5)    # return the indices where x > 5
(array([2, 2]), array([0, 2]))

>>> print np.ma.where(x > 5, x, -3.1416)
[[-3.1416 -- -3.1416]
 [-- -3.1416 --]
 [6.0 -- 8.0]]


self._display = s<EOL>

Set the string to print for masked values.


def argmax(self, axis=None, fill_value=None, out=None):

if fill_value is None:<EOL><INDENT>fill_value = maximum_fill_value(self._data)<EOL><DEDENT>d = self.filled(fill_value).view(ndarray)<EOL>return d.argmax(axis, out=out)<EOL>

Returns array of indices of the maximum values along the given axis.
Masked values are treated as if they had the value fill_value.

Parameters
----------
axis : {None, integer}
    If None, the index is into the flattened array, otherwise along
    the specified axis
fill_value : {var}, optional
    Value used to fill in the masked values.  If None, the output of
    maximum_fill_value(self._data) is used instead.
out : {None, array}, optional
    Array into which the result can be placed. Its type is preserved
    and it must be of the right shape to hold the output.

Returns
-------
index_array : {integer_array}

Examples
--------
>>> a = np.arange(6).reshape(2,3)
>>> a.argmax()
5
>>> a.argmax(0)
array([1, 1, 1])
>>> a.argmax(1)
array([2, 2])


return true_divide(other, self)<EOL>

Divide other into self, and return a new masked array.


m = mask_or(getmask(a), getmask(b))<EOL>if m is nomask:<EOL><INDENT>x = getdata(a)<EOL>y = getdata(b)<EOL>d = umath.equal(x, y)<EOL>return d.all()<EOL><DEDENT>elif fill_value:<EOL><INDENT>x = getdata(a)<EOL>y = getdata(b)<EOL>d = umath.equal(x, y)<EOL>dm = array(d, mask=m, copy=False)<EOL>return dm.filled(True).all(None)<EOL><DEDENT>else:<EOL><INDENT>return False<EOL><DEDENT>

Return True if all entries of a and b are equal, using
fill_value as a truth value where either or both are masked.

Parameters
----------
a, b : array_like
    Input arrays to compare.
fill_value : bool, optional
    Whether masked values in a or b are considered equal (True) or not
    (False).

Returns
-------
y : bool
    Returns True if the two arrays are equal within the given
    tolerance, False otherwise. If either array contains NaN,
    then False is returned.

See Also
--------
all, any
numpy.ma.allclose

Examples
--------
>>> a = ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1])
>>> a
masked_array(data = [10000000000.0 1e-07 --],
      mask = [False False  True],
      fill_value=1e+20)

>>> b = array([1e10, 1e-7, -42.0])
>>> b
array([  1.00000000e+10,   1.00000000e-07,  -4.20000000e+01])
>>> ma.allequal(a, b, fill_value=False)
False
>>> ma.allequal(a, b)
True


return pickle.dumps(a)<EOL>

Return a string corresponding to the pickling of a masked array.

This is a wrapper around ``cPickle.dumps``.

Parameters
----------
a : MaskedArray
    The array for which the string representation of the pickle is
    returned.


_mask = self._mask<EOL>if _mask is nomask:<EOL><INDENT>return self._data.tolist()<EOL><DEDENT>result = []<EOL>for (d, m) in zip(self._data, self._mask):<EOL><INDENT>if m:<EOL><INDENT>result.append(None)<EOL><DEDENT>else:<EOL><INDENT>result.append(d.item())<EOL><DEDENT><DEDENT>return tuple(result)<EOL>

Transforms the mvoid object into a tuple.

Masked fields are replaced by None.

Returns
-------
returned_tuple
    Tuple of fields


doc = getattr(self._func, '<STR_LIT>', None)<EOL>sig = get_object_signature(self._func)<EOL>if doc:<EOL><INDENT>if sig:<EOL><INDENT>sig = "<STR_LIT>" % (self._func.__name__, sig)<EOL><DEDENT>doc = sig + doc<EOL><DEDENT>return doc<EOL>

Return the doc of the function (from the doc of the method).


m = self.mean(axis, dtype)<EOL>if not axis:<EOL><INDENT>return (self - m)<EOL><DEDENT>else:<EOL><INDENT>return (self - expand_dims(m, axis))<EOL><DEDENT>

Compute the anomalies (deviations from the arithmetic mean)
along the given axis.

Returns an array of anomalies, with the same shape as the input and
where the arithmetic mean is computed along the given axis.

Parameters
----------
axis : int, optional
    Axis over which the anomalies are taken.
    The default is to use the mean of the flattened array as reference.
dtype : dtype, optional
    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.

See Also
--------
mean : Compute the mean of the array.

Examples
--------
>>> a = np.ma.array([1,2,3])
>>> a.anom()
masked_array(data = [-1.  0.  1.],
             mask = False,
       fill_value = 1e+20)


def masked_values(x, value, rtol=<NUM_LIT>, atol=<NUM_LIT>, copy=True, shrink=True):

mabs = umath.absolute<EOL>xnew = filled(x, value)<EOL>if issubclass(xnew.dtype.type, np.floating):<EOL><INDENT>condition = umath.less_equal(mabs(xnew - value), atol + rtol * mabs(value))<EOL>mask = getattr(x, '<STR_LIT>', nomask)<EOL><DEDENT>else:<EOL><INDENT>condition = umath.equal(xnew, value)<EOL>mask = nomask<EOL><DEDENT>mask = mask_or(mask, make_mask(condition, shrink=shrink))<EOL>return masked_array(xnew, mask=mask, copy=copy, fill_value=value)<EOL>

Mask using floating point equality.

Return a MaskedArray, masked where the data in array `x` are approximately
equal to `value`, i.e. where the following condition is True

(abs(x - value) <= atol+rtol*abs(value))

The fill_value is set to `value` and the mask is set to ``nomask`` if
possible.  For integers, consider using ``masked_equal``.

Parameters
----------
x : array_like
    Array to mask.
value : float
    Masking value.
rtol : float, optional
    Tolerance parameter.
atol : float, optional
    Tolerance parameter (1e-8).
copy : bool, optional
    Whether to return a copy of `x`.
shrink : bool, optional
    Whether to collapse a mask full of False to ``nomask``.

Returns
-------
result : MaskedArray
    The result of masking `x` where approximately equal to `value`.

See Also
--------
masked_where : Mask where a condition is met.
masked_equal : Mask where equal to a given value (integers).

Examples
--------
>>> import numpy.ma as ma
>>> x = np.array([1, 1.1, 2, 1.1, 3])
>>> ma.masked_values(x, 1.1)
masked_array(data = [1.0 -- 2.0 -- 3.0],
      mask = [False  True False  True False],
      fill_value=1.1)

Note that `mask` is set to ``nomask`` if possible.

>>> ma.masked_values(x, 1.5)
masked_array(data = [ 1.   1.1  2.   1.1  3. ],
      mask = False,
      fill_value=1.5)

For integers, the fill value will be different in general to the
result of ``masked_equal``.

>>> x = np.arange(5)
>>> x
array([0, 1, 2, 3, 4])
>>> ma.masked_values(x, 2)
masked_array(data = [0 1 -- 3 4],
      mask = [False False  True False False],
      fill_value=2)
>>> ma.masked_equal(x, 2)
masked_array(data = [0 1 -- 3 4],
      mask = [False False  True False False],
      fill_value=999999)


self.eps = eps<EOL>

domain_tan(eps) = true where abs(cos(x)) < eps)


other_data = getdata(other)<EOL>dom_mask = _DomainSafeDivide().__call__(self._data, other_data)<EOL>other_mask = getmask(other)<EOL>new_mask = mask_or(other_mask, dom_mask)<EOL>if dom_mask.any():<EOL><INDENT>(_, fval) = ufunc_fills[np.true_divide]<EOL>other_data = np.where(dom_mask, fval, other_data)<EOL>


if third is not None:<EOL><INDENT>raise MaskError("<STR_LIT>")<EOL><DEDENT>ma = getmask(a)<EOL>mb = getmask(b)<EOL>m = mask_or(ma, mb)<EOL>fa = getdata(a)<EOL>fb = getdata(b)<EOL>if isinstance(a, MaskedArray):<EOL><INDENT>basetype = type(a)<EOL><DEDENT>else:<EOL><INDENT>basetype = MaskedArray<EOL><DEDENT>with np.errstate(divide='<STR_LIT:ignore>', invalid='<STR_LIT:ignore>'):<EOL><INDENT>result = np.where(m, fa, umath.power(fa, fb)).view(basetype)<EOL><DEDENT>result._update_from(a)<EOL>invalid = np.logical_not(np.isfinite(result.view(ndarray)))<EOL>if m is not nomask:<EOL><INDENT>if not (result.ndim):<EOL><INDENT>return masked<EOL><DEDENT>result._mask = np.logical_or(m, invalid)<EOL><DEDENT>if invalid.any():<EOL><INDENT>if not result.ndim:<EOL><INDENT>return masked<EOL><DEDENT>elif result._mask is nomask:<EOL><INDENT>result._mask = invalid<EOL><DEDENT>result._data[invalid] = result.fill_value<EOL><DEDENT>return result<EOL>

Returns element-wise base array raised to power from second array.

This is the masked array version of `numpy.power`. For details see
`numpy.power`.

See Also
--------
numpy.power

Notes
-----
The *out* argument to `numpy.power` is not supported, `third` has to be
None.


def masked_object(x, value, copy=True, shrink=True):

if isMaskedArray(x):<EOL><INDENT>condition = umath.equal(x._data, value)<EOL>mask = x._mask<EOL><DEDENT>else:<EOL><INDENT>condition = umath.equal(np.asarray(x), value)<EOL>mask = nomask<EOL><DEDENT>mask = mask_or(mask, make_mask(condition, shrink=shrink))<EOL>return masked_array(x, mask=mask, copy=copy, fill_value=value)<EOL>

Mask the array `x` where the data are exactly equal to value.

This function is similar to `masked_values`, but only suitable
for object arrays: for floating point, use `masked_values` instead.

Parameters
----------
x : array_like
    Array to mask
value : object
    Comparison value
copy : {True, False}, optional
    Whether to return a copy of `x`.
shrink : {True, False}, optional
    Whether to collapse a mask full of False to nomask

Returns
-------
result : MaskedArray
    The result of masking `x` where equal to `value`.

See Also
--------
masked_where : Mask where a condition is met.
masked_equal : Mask where equal to a given value (integers).
masked_values : Mask using floating point equality.

Examples
--------
>>> import numpy.ma as ma
>>> food = np.array(['green_eggs', 'ham'], dtype=object)
>>> # don't eat spoiled food
>>> eat = ma.masked_object(food, 'green_eggs')
>>> print eat
[-- ham]
>>> # plain ol` ham is boring
>>> fresh_food = np.array(['cheese', 'ham', 'pineapple'], dtype=object)
>>> eat = ma.masked_object(fresh_food, 'green_eggs')
>>> print eat
[cheese ham pineapple]

Note that `mask` is set to ``nomask`` if possible.

>>> eat
masked_array(data = [cheese ham pineapple],
      mask = False,
      fill_value=?)


if self._sharedmask:<EOL><INDENT>self._mask = self._mask.copy()<EOL>self._sharedmask = False<EOL><DEDENT>return self<EOL>

Copy the mask and set the sharedmask flag to False.

Whether the mask is shared between masked arrays can be seen from
the `sharedmask` property. `unshare_mask` ensures the mask is not shared.
A copy of the mask is only made if it was shared.

See Also
--------
sharedmask


return multiply(self, other)<EOL>

Multiply other by self, and return a new masked array.


<EOL>def _flatmask(mask):<EOL><INDENT>"<STR_LIT>"<EOL>mnames = mask.dtype.names<EOL>if mnames:<EOL><INDENT>return [flatten_mask(mask[name]) for name in mnames]<EOL><DEDENT>else:<EOL><INDENT>return mask<EOL><DEDENT><DEDENT>def _flatsequence(sequence):<EOL><INDENT>"<STR_LIT>"<EOL>try:<EOL><INDENT>for element in sequence:<EOL><INDENT>if hasattr(element, '<STR_LIT>'):<EOL><INDENT>for f in _flatsequence(element):<EOL><INDENT>yield f<EOL><DEDENT><DEDENT>else:<EOL><INDENT>yield element<EOL><DEDENT><DEDENT><DEDENT>except TypeError:<EOL><INDENT>yield sequence<EOL><DEDENT><DEDENT>mask = np.asarray(mask)<EOL>flattened = _flatsequence(_flatmask(mask))<EOL>return np.array([_ for _ in flattened], dtype=bool)<EOL>

Returns a completely flattened version of the mask, where nested fields
are collapsed.

Parameters
----------
mask : array_like
    Input array, which will be interpreted as booleans.

Returns
-------
flattened_mask : ndarray of bools
    The flattened input.

Examples
--------
>>> mask = np.array([0, 0, 1], dtype=np.bool)
>>> flatten_mask(mask)
array([False, False,  True], dtype=bool)

>>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)])
>>> flatten_mask(mask)
array([False, False, False,  True], dtype=bool)

>>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
>>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype)
>>> flatten_mask(mask)
array([False, False, False, False, False,  True], dtype=bool)


if obj is not None and isinstance(obj, ndarray):<EOL><INDENT>_baseclass = type(obj)<EOL><DEDENT>else:<EOL><INDENT>_baseclass = ndarray<EOL><DEDENT>_optinfo = {}<EOL>_optinfo.update(getattr(obj, '<STR_LIT>', {}))<EOL>_optinfo.update(getattr(obj, '<STR_LIT>', {}))<EOL>if not isinstance(obj, MaskedArray):<EOL><INDENT>_optinfo.update(getattr(obj, '<STR_LIT>', {}))<EOL><DEDENT>_dict = dict(_fill_value=getattr(obj, '<STR_LIT>', None),<EOL>_hardmask=getattr(obj, '<STR_LIT>', False),<EOL>_sharedmask=getattr(obj, '<STR_LIT>', False),<EOL>_isfield=getattr(obj, '<STR_LIT>', False),<EOL>_baseclass=getattr(obj, '<STR_LIT>', _baseclass),<EOL>_optinfo=_optinfo,<EOL>_basedict=_optinfo)<EOL>self.__dict__.update(_dict)<EOL>self.__dict__.update(_optinfo)<EOL>return<EOL>


m = getmask(other)<EOL>if self._mask is nomask:<EOL><INDENT>if m is not nomask and m.any():<EOL><INDENT>self._mask = make_mask_none(self.shape, self.dtype)<EOL>self._mask += m<EOL><DEDENT><DEDENT>elif m is not nomask:<EOL><INDENT>self._mask += m<EOL><DEDENT>ndarray.__imul__(self._data, np.where(self._mask, <NUM_LIT:1>, getdata(other)))<EOL>return self<EOL>


def ptp(obj, axis=None, out=None, fill_value=None):

try:<EOL><INDENT>return obj.ptp(axis, out=out, fill_value=fill_value)<EOL><DEDENT>except (AttributeError, TypeError):<EOL><INDENT>return asanyarray(obj).ptp(axis=axis, fill_value=fill_value, out=out)<EOL><DEDENT>

a.ptp(axis=None) =  a.max(axis)-a.min(axis)


def assert_almost_equal(actual, desired, decimal=<NUM_LIT:7>, err_msg='<STR_LIT>', verbose=True):

if isinstance(actual, np.ndarray) or isinstance(desired, np.ndarray):<EOL><INDENT>return assert_array_almost_equal(actual, desired, decimal=decimal,<EOL>err_msg=err_msg, verbose=verbose)<EOL><DEDENT>msg = build_err_msg([actual, desired],<EOL>err_msg=err_msg, verbose=verbose)<EOL>if not round(abs(desired - actual), decimal) == <NUM_LIT:0>:<EOL><INDENT>raise AssertionError(msg)<EOL><DEDENT>

Asserts that two items are almost equal.
    The test is equivalent to abs(desired-actual) < 0.5 * 10**(-decimal)


def assert_array_less(x, y, err_msg='<STR_LIT>', verbose=True):

assert_array_compare(operator.__lt__, x, y,<EOL>err_msg=err_msg, verbose=verbose,<EOL>header='<STR_LIT>')<EOL>

Checks that x is smaller than y elementwise.


def fail_if_array_equal(x, y, err_msg='<STR_LIT>', verbose=True):

def compare(x, y):<EOL><INDENT>return (not np.alltrue(approx(x, y)))<EOL><DEDENT>assert_array_compare(compare, x, y, err_msg=err_msg, verbose=verbose,<EOL>header='<STR_LIT>')<EOL>

Raises an assertion error if two masked arrays are not equal (elementwise).


def _assert_equal_on_sequences(actual, desired, err_msg='<STR_LIT>'):

assert_equal(len(actual), len(desired), err_msg)<EOL>for k in range(len(desired)):<EOL><INDENT>assert_equal(actual[k], desired[k], '<STR_LIT>' % (k, err_msg))<EOL><DEDENT>return<EOL>

Asserts the equality of two non-array sequences.


>>> 2+2
<BadExample object at 0x084D05AC>  #random: may vary on your system


fullpath = filepath[:]<EOL>pkg_name = []<EOL>while '<STR_LIT>' in filepath or '<STR_LIT>' in filepath:<EOL><INDENT>filepath, p2 = os.path.split(filepath)<EOL>if p2 in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>break<EOL><DEDENT>pkg_name.append(p2)<EOL><DEDENT>if not pkg_name:<EOL><INDENT>if '<STR_LIT>' in fullpath:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT><DEDENT>pkg_name.reverse()<EOL>if pkg_name[<NUM_LIT:0>].endswith('<STR_LIT>'):<EOL><INDENT>pkg_name.pop(<NUM_LIT:0>)<EOL><DEDENT>return '<STR_LIT:.>'.join(pkg_name)<EOL>

Given a path where a package is installed, determine its name.

Parameters
----------
filepath : str
    Path to a file. If the determination fails, "numpy" is returned.

Examples
--------
>>> np.testing.nosetester.get_package_name('nonsense')
'numpy'


fine_nose = True<EOL>minimum_nose_version = (<NUM_LIT:0>, <NUM_LIT:10>, <NUM_LIT:0>)<EOL>try:<EOL><INDENT>import nose<EOL><DEDENT>except ImportError:<EOL><INDENT>fine_nose = False<EOL><DEDENT>else:<EOL><INDENT>if nose.__versioninfo__ < minimum_nose_version:<EOL><INDENT>fine_nose = False<EOL><DEDENT><DEDENT>if not fine_nose:<EOL><INDENT>msg = '<STR_LIT>''<STR_LIT>' %minimum_nose_version<EOL>raise ImportError(msg)<EOL><DEDENT>return nose<EOL>


def bench(self, label='<STR_LIT>', verbose=<NUM_LIT:1>, extra_argv=None):

print("<STR_LIT>" % self.package_name)<EOL>self._show_system_info()<EOL>argv = self._test_argv(label, verbose, extra_argv)<EOL>argv += ['<STR_LIT>', r'<STR_LIT>' % os.sep]<EOL>nose = import_nose()<EOL>from .noseclasses import Unplugger<EOL>add_plugins = [Unplugger('<STR_LIT>')]<EOL>return nose.run(argv=argv, addplugins=add_plugins)<EOL>

Run benchmarks for module using nose.

Parameters
----------
label : {'fast', 'full', '', attribute identifier}, optional
    Identifies the benchmarks to run. This can be a string to pass to
    the nosetests executable with the '-A' option, or one of several
    special values.  Special values are:
    * 'fast' - the default - which corresponds to the ``nosetests -A``
      option of 'not slow'.
    * 'full' - fast (as above) and slow benchmarks as in the
      'no -A' option to nosetests - this is the same as ''.
    * None or '' - run all tests.
    attribute_identifier - string passed directly to nosetests as '-A'.
verbose : int, optional
    Verbosity value for benchmark outputs, in the range 1-10. Default is 1.
extra_argv : list, optional
    List with any extra arguments to pass to nosetests.

Returns
-------
success : bool
    Returns True if running the benchmarks works, False if an error
    occurred.

Notes
-----
Benchmarks are like tests, but have names starting with "bench" instead
of "test", and can be found under the "benchmarks" sub-directory of the
module.

Each NumPy module exposes `bench` in its namespace to run all benchmarks
for it.

Examples
--------
>>> success = np.lib.bench() #doctest: +SKIP
Running benchmarks for numpy.lib
...
using 562341 items:
unique:
0.11
unique1d:
0.11
ratio: 1.0
nUnique: 56230 == 56230
...
OK

>>> success #doctest: +SKIP
True


if module is None:<EOL><INDENT>return True<EOL><DEDENT>elif inspect.isfunction(object):<EOL><INDENT>return module.__dict__ is object.__globals__<EOL><DEDENT>elif inspect.isbuiltin(object):<EOL><INDENT>return module.__name__ == object.__module__<EOL><DEDENT>elif inspect.isclass(object):<EOL><INDENT>return module.__name__ == object.__module__<EOL><DEDENT>elif inspect.ismethod(object):<EOL><INDENT>return module.__name__ == object.__self__.__class__.__module__<EOL><DEDENT>elif inspect.getmodule(object) is not None:<EOL><INDENT>return module is inspect.getmodule(object)<EOL><DEDENT>elif hasattr(object, '<STR_LIT>'):<EOL><INDENT>return module.__name__ == object.__module__<EOL><DEDENT>elif isinstance(object, property):<EOL><INDENT>return True <EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>

Return true if the given object is defined in the given
module.


import numpy as np<EOL>if x.dtype == np.float32:<EOL><INDENT>return _integer_repr(x, np.int32, np.int32(-<NUM_LIT:2>**<NUM_LIT>))<EOL><DEDENT>elif x.dtype == np.float64:<EOL><INDENT>return _integer_repr(x, np.int64, np.int64(-<NUM_LIT:2>**<NUM_LIT>))<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>" % x.dtype)<EOL><DEDENT>

Return the signed-magnitude interpretation of the binary representation of
    x.


def assert_array_equal(x, y, err_msg='<STR_LIT>', verbose=True):

assert_array_compare(operator.__eq__, x, y, err_msg=err_msg,<EOL>verbose=verbose, header='<STR_LIT>')<EOL>

Raises an AssertionError if two array_like objects are not equal.

Given two array_like objects, check that the shape is equal and all
elements of these objects are equal. An exception is raised at
shape mismatch or conflicting values. In contrast to the standard usage
in numpy, NaNs are compared like numbers, no assertion is raised if
both objects have NaNs in the same positions.

The usual caution for verifying equality with floating point numbers is
advised.

Parameters
----------
x : array_like
    The actual object to check.
y : array_like
    The desired, expected object.
err_msg : str, optional
    The error message to be printed in case of failure.
verbose : bool, optional
    If True, the conflicting values are appended to the error message.

Raises
------
AssertionError
    If actual and desired objects are not equal.

See Also
--------
assert_allclose: Compare two array_like objects for equality with desired
                 relative and/or absolute precision.
assert_array_almost_equal_nulp, assert_array_max_ulp, assert_equal

Examples
--------
The first assert does not raise an exception:

>>> np.testing.assert_array_equal([1.0,2.33333,np.nan],
...                               [np.exp(0),2.33333, np.nan])

Assert fails with numerical inprecision with floats:

>>> np.testing.assert_array_equal([1.0,np.pi,np.nan],
...                               [1, np.sqrt(np.pi)**2, np.nan])
...
<type 'exceptions.ValueError'>:
AssertionError:
Arrays are not equal
<BLANKLINE>
(mismatch 50.0%)
 x: array([ 1.        ,  3.14159265,         NaN])
 y: array([ 1.        ,  3.14159265,         NaN])

Use `assert_allclose` or one of the nulp (number of floating point values)
functions for these cases instead:

>>> np.testing.assert_allclose([1.0,np.pi,np.nan],
...                            [1, np.sqrt(np.pi)**2, np.nan],
...                            rtol=1e-10, atol=0)


frame = sys._getframe(<NUM_LIT:1>)<EOL>locs, globs = frame.f_locals, frame.f_globals<EOL>code = compile(code_str,<EOL>'<STR_LIT>' % label,<EOL>'<STR_LIT>')<EOL>i = <NUM_LIT:0><EOL>elapsed = jiffies()<EOL>while i < times:<EOL><INDENT>i += <NUM_LIT:1><EOL>exec(code, globs, locs)<EOL><DEDENT>elapsed = jiffies() - elapsed<EOL>return <NUM_LIT>*elapsed<EOL>

Return elapsed time for executing code in the namespace of the caller.

The supplied code string is compiled with the Python builtin ``compile``.
The precision of the timing is 10 milli-seconds. If the code will execute
fast on this timescale, it can be executed many times to get reasonable
timing accuracy.

Parameters
----------
code_str : str
    The code to be timed.
times : int, optional
    The number of times the code is executed. Default is 1. The code is
    only compiled once.
label : str, optional
    A label to identify `code_str` with. This is passed into ``compile``
    as the second argument (for run-time error messages).

Returns
-------
elapsed : float
    Total elapsed time in seconds for executing `code_str` `times` times.

Examples
--------
>>> etime = np.testing.measure('for i in range(1000): np.sqrt(i**2)',
...                            times=times)
>>> print "Time for a single execution : ", etime / times, "s"
Time for a single execution :  0.005 s


from numpy.core import isfinite, errstate<EOL>with errstate(invalid='<STR_LIT:ignore>'):<EOL><INDENT>st = isfinite(x)<EOL>if isinstance(st, type(NotImplemented)):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT><DEDENT>return st<EOL>

like isfinite, but always raise an error if type not supported instead of
    returning a TypeError object.

    Notes
    -----
    isfinite and other ufunc sometimes return a NotImplementedType object instead
    of raising any exception. This function is a wrapper to make sure an
    exception is always raised.

    This should be removed once this problem is solved at the Ufunc level.


import random<EOL>from numpy.core import zeros, float64<EOL>results = zeros(args, float64)<EOL>f = results.flat<EOL>for i in range(len(f)):<EOL><INDENT>f[i] = random.random()<EOL><DEDENT>return results<EOL>

Returns an array of random numbers with the given shape.

    This only uses the standard library, so it is useful for testing purposes.


import numpy as np<EOL>if dtype:<EOL><INDENT>x = np.array(x, dtype=dtype)<EOL>y = np.array(y, dtype=dtype)<EOL><DEDENT>else:<EOL><INDENT>x = np.array(x)<EOL>y = np.array(y)<EOL><DEDENT>t = np.common_type(x, y)<EOL>if np.iscomplexobj(x) or np.iscomplexobj(y):<EOL><INDENT>raise NotImplementedError("<STR_LIT>")<EOL><DEDENT>x = np.array(x, dtype=t)<EOL>y = np.array(y, dtype=t)<EOL>if not x.shape == y.shape:<EOL><INDENT>raise ValueError("<STR_LIT>" %(x.shape, y.shape))<EOL><DEDENT>def _diff(rx, ry, vdt):<EOL><INDENT>diff = np.array(rx-ry, dtype=vdt)<EOL>return np.abs(diff)<EOL><DEDENT>rx = integer_repr(x)<EOL>ry = integer_repr(y)<EOL>return _diff(rx, ry, t)<EOL>

For each item in x and y, return the number of representable floating
    points between them.

    Parameters
    ----------
    x : array_like
        first input array
    y : array_like
        second input array

    Returns
    -------
    nulp : array_like
        number of representable floating point numbers between each item in x
        and y.

    Examples
    --------
    # By definition, epsilon is the smallest number such as 1 + eps != 1, so
    # there should be exactly one ULP between 1 and 1 + eps
    >>> nulp_diff(1, 1 + np.finfo(x.dtype).eps)
    1.0


nose = import_nose()<EOL>return nose.tools.assert_raises(*args,**kwargs)<EOL>

assert_raises(exception_class, callable, *args, **kwargs)

Fail unless an exception of class exception_class is thrown
by callable when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
thrown, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.


if isinstance(desired, dict):<EOL><INDENT>if not isinstance(actual, dict) :<EOL><INDENT>raise AssertionError(repr(type(actual)))<EOL><DEDENT>assert_equal(len(actual), len(desired), err_msg, verbose)<EOL>for k, i in desired.items():<EOL><INDENT>if k not in actual :<EOL><INDENT>raise AssertionError(repr(k))<EOL><DEDENT>assert_equal(actual[k], desired[k], '<STR_LIT>' % (k, err_msg), verbose)<EOL><DEDENT>return<EOL><DEDENT>if isinstance(desired, (list, tuple)) and isinstance(actual, (list, tuple)):<EOL><INDENT>assert_equal(len(actual), len(desired), err_msg, verbose)<EOL>for k in range(len(desired)):<EOL><INDENT>assert_equal(actual[k], desired[k], '<STR_LIT>' % (k, err_msg), verbose)<EOL><DEDENT>return<EOL><DEDENT>from numpy.core import ndarray, isscalar, signbit<EOL>from numpy.lib import iscomplexobj, real, imag<EOL>if isinstance(actual, ndarray) or isinstance(desired, ndarray):<EOL><INDENT>return assert_array_equal(actual, desired, err_msg, verbose)<EOL><DEDENT>msg = build_err_msg([actual, desired], err_msg, verbose=verbose)<EOL>try:<EOL><INDENT>usecomplex = iscomplexobj(actual) or iscomplexobj(desired)<EOL><DEDENT>except ValueError:<EOL><INDENT>usecomplex = False<EOL><DEDENT>if usecomplex:<EOL><INDENT>if iscomplexobj(actual):<EOL><INDENT>actualr = real(actual)<EOL>actuali = imag(actual)<EOL><DEDENT>else:<EOL><INDENT>actualr = actual<EOL>actuali = <NUM_LIT:0><EOL><DEDENT>if iscomplexobj(desired):<EOL><INDENT>desiredr = real(desired)<EOL>desiredi = imag(desired)<EOL><DEDENT>else:<EOL><INDENT>desiredr = desired<EOL>desiredi = <NUM_LIT:0><EOL><DEDENT>try:<EOL><INDENT>assert_equal(actualr, desiredr)<EOL>assert_equal(actuali, desiredi)<EOL><DEDENT>except AssertionError:<EOL><INDENT>raise AssertionError(msg)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>if isscalar(desired) != isscalar(actual):<EOL><INDENT>raise AssertionError(msg)<EOL><DEDENT>if not (gisfinite(desired) and gisfinite(actual)):<EOL><INDENT>isdesnan = gisnan(desired)<EOL>isactnan = gisnan(actual)<EOL>if isdesnan or isactnan:<EOL><INDENT>if not (isdesnan and isactnan):<EOL><INDENT>raise AssertionError(msg)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if not desired == actual:<EOL><INDENT>raise AssertionError(msg)<EOL><DEDENT><DEDENT>return<EOL><DEDENT>elif desired == <NUM_LIT:0> and actual == <NUM_LIT:0>:<EOL><INDENT>if not signbit(desired) == signbit(actual):<EOL><INDENT>raise AssertionError(msg)<EOL><DEDENT><DEDENT><DEDENT>except (TypeError, ValueError, NotImplementedError):<EOL><INDENT>pass<EOL><DEDENT>if not (desired == actual):<EOL><INDENT>raise AssertionError(msg)<EOL><DEDENT>

Raises an AssertionError if two objects are not equal.

Given two objects (scalars, lists, tuples, dictionaries or numpy arrays),
check that all elements of these objects are equal. An exception is raised
at the first conflicting values.

Parameters
----------
actual : array_like
    The object to check.
desired : array_like
    The expected object.
err_msg : str, optional
    The error message to be printed in case of failure.
verbose : bool, optional
    If True, the conflicting values are appended to the error message.

Raises
------
AssertionError
    If actual and desired are not equal.

Examples
--------
>>> np.testing.assert_equal([4,5], [4,6])
...
<type 'exceptions.AssertionError'>:
Items are not equal:
item=1
 ACTUAL: 5
 DESIRED: 6


t.slow = True<EOL>return t<EOL>

Label a test as 'slow'.

The exact definition of a slow test is obviously both subjective and
hardware-dependent, but in general any individual test that requires more
than a second or two should be labeled as slow (the whole suite consits of
thousands of tests, so even a second is significant).

Parameters
----------
t : callable
    The test to label as slow.

Returns
-------
t : callable
    The decorated test `t`.

Examples
--------
The `numpy.testing` module includes ``import decorators as dec``.
A test can be decorated as slow like this::

  from numpy.testing import *

  @dec.slow
  def test_big(self):
      print 'Big, slow test'


if sys.platform == '<STR_LIT:win32>':<EOL><INDENT>locales = ['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>locales = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>def wrapper(*args, **kwargs):<EOL><INDENT>curloc = locale.getlocale(locale.LC_NUMERIC)<EOL>try:<EOL><INDENT>for loc in locales:<EOL><INDENT>try:<EOL><INDENT>locale.setlocale(locale.LC_NUMERIC, loc)<EOL>break<EOL><DEDENT>except locale.Error:<EOL><INDENT>pass<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise nose.SkipTest("<STR_LIT>"<EOL>"<STR_LIT>")<EOL><DEDENT>return func(*args, **kwargs)<EOL><DEDENT>finally:<EOL><INDENT>locale.setlocale(locale.LC_NUMERIC, locale=curloc)<EOL><DEDENT><DEDENT>return nose.tools.make_decorator(func)(wrapper)<EOL>

Swap LC_NUMERIC locale to one in which the decimal point is ',' and not '.'
If not possible, raise nose.SkipTest


def assert_deprecated(self, function, num=<NUM_LIT:1>, ignore_others=False,<EOL>function_fails=False,<EOL>exceptions=(DeprecationWarning,), args=(), kwargs={}):

<EOL>self.log[:] = []<EOL>try:<EOL><INDENT>function(*args, **kwargs)<EOL><DEDENT>except (Exception if function_fails else tuple()):<EOL><INDENT>pass<EOL><DEDENT>num_found = <NUM_LIT:0><EOL>for warning in self.log:<EOL><INDENT>if warning.category is DeprecationWarning:<EOL><INDENT>num_found += <NUM_LIT:1><EOL><DEDENT>elif not ignore_others:<EOL><INDENT>raise AssertionError("<STR_LIT>"<EOL>% warning.category)<EOL><DEDENT><DEDENT>if num is not None and num_found != num:<EOL><INDENT>raise AssertionError("<STR_LIT>"<EOL>% (len(self.log), num))<EOL><DEDENT>with warnings.catch_warnings():<EOL><INDENT>warnings.filterwarnings("<STR_LIT:error>", message=self.message,<EOL>category=DeprecationWarning)<EOL>try:<EOL><INDENT>function(*args, **kwargs)<EOL>if exceptions != tuple():<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT><DEDENT>except exceptions:<EOL><INDENT>if exceptions == tuple():<EOL><INDENT>raise AssertionError("<STR_LIT>")<EOL><DEDENT><DEDENT><DEDENT>

Test if DeprecationWarnings are given and raised.

        This first checks if the function when called gives `num`
        DeprecationWarnings, after that it tries to raise these
        DeprecationWarnings and compares them with `exceptions`.
        The exceptions can be different for cases where this code path
        is simply not anticipated and the exception is replaced.

        Parameters
        ----------
        f : callable
            The function to test
        num : int
            Number of DeprecationWarnings to expect. This should normally be 1.
        ignore_other : bool
            Whether warnings of the wrong type should be ignored (note that
            the message is not checked)
        function_fails : bool
            If the function would normally fail, setting this will check for
            warnings inside a try/except block.
        exceptions : Exception or tuple of Exceptions
            Exception to expect when turning the warnings into an error.
            The default checks for DeprecationWarnings. If exceptions is
            empty the function is expected to run successfull.
        args : tuple
            Arguments for `f`
        kwargs : dict
            Keyword arguments for `f`


if self.base is not None and hasattr(self.base, '<STR_LIT>'):<EOL><INDENT>self.base.flush()<EOL><DEDENT>

Write any changes in the array to the file on disk.

For further information, see `memmap`.

Parameters
----------
None

See Also
--------
memmap


Return the current print options.

Returns
-------
print_opts : dict
    Dictionary of current print options with keys

      - precision : int
      - threshold : int
      - edgeitems : int
      - linewidth : int
      - suppress : bool
      - nanstr : str
      - infstr : str
      - formatter : dict of callables

    For a full description of these options, see `set_printoptions`.

See Also
--------
set_printoptions, set_string_function


def _formatArray(a, format_function, rank, max_line_len,<EOL>next_line_prefix, separator, edge_items, summary_insert):

if rank == <NUM_LIT:0>:<EOL><INDENT>obj = a.item()<EOL>if isinstance(obj, tuple):<EOL><INDENT>obj = _convert_arrays(obj)<EOL><DEDENT>return str(obj)<EOL><DEDENT>if summary_insert and <NUM_LIT:2>*edge_items < len(a):<EOL><INDENT>leading_items, trailing_items, summary_insert1 =edge_items, edge_items, summary_insert<EOL><DEDENT>else:<EOL><INDENT>leading_items, trailing_items, summary_insert1 = <NUM_LIT:0>, len(a), "<STR_LIT>"<EOL><DEDENT>if rank == <NUM_LIT:1>:<EOL><INDENT>s = "<STR_LIT>"<EOL>line = next_line_prefix<EOL>for i in range(leading_items):<EOL><INDENT>word = format_function(a[i]) + separator<EOL>s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)<EOL><DEDENT>if summary_insert1:<EOL><INDENT>s, line = _extendLine(s, line, summary_insert1, max_line_len, next_line_prefix)<EOL><DEDENT>for i in range(trailing_items, <NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>word = format_function(a[-i]) + separator<EOL>s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)<EOL><DEDENT>word = format_function(a[-<NUM_LIT:1>])<EOL>s, line = _extendLine(s, line, word, max_line_len, next_line_prefix)<EOL>s += line + "<STR_LIT>"<EOL>s = '<STR_LIT:[>' + s[len(next_line_prefix):]<EOL><DEDENT>else:<EOL><INDENT>s = '<STR_LIT:[>'<EOL>sep = separator.rstrip()<EOL>for i in range(leading_items):<EOL><INDENT>if i > <NUM_LIT:0>:<EOL><INDENT>s += next_line_prefix<EOL><DEDENT>s += _formatArray(a[i], format_function, rank-<NUM_LIT:1>, max_line_len,<EOL>"<STR_LIT:U+0020>" + next_line_prefix, separator, edge_items,<EOL>summary_insert)<EOL>s = s.rstrip() + sep.rstrip() + '<STR_LIT:\n>'*max(rank-<NUM_LIT:1>, <NUM_LIT:1>)<EOL><DEDENT>if summary_insert1:<EOL><INDENT>s += next_line_prefix + summary_insert1 + "<STR_LIT:\n>"<EOL><DEDENT>for i in range(trailing_items, <NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>if leading_items or i != trailing_items:<EOL><INDENT>s += next_line_prefix<EOL><DEDENT>s += _formatArray(a[-i], format_function, rank-<NUM_LIT:1>, max_line_len,<EOL>"<STR_LIT:U+0020>" + next_line_prefix, separator, edge_items,<EOL>summary_insert)<EOL>s = s.rstrip() + sep.rstrip() + '<STR_LIT:\n>'*max(rank-<NUM_LIT:1>, <NUM_LIT:1>)<EOL><DEDENT>if leading_items or trailing_items > <NUM_LIT:1>:<EOL><INDENT>s += next_line_prefix<EOL><DEDENT>s += _formatArray(a[-<NUM_LIT:1>], format_function, rank-<NUM_LIT:1>, max_line_len,<EOL>"<STR_LIT:U+0020>" + next_line_prefix, separator, edge_items,<EOL>summary_insert).rstrip()+'<STR_LIT>'<EOL><DEDENT>return s<EOL>

formatArray is designed for two modes of operation:

    1. Full output

    2. Summarized output


try:<EOL><INDENT>result = a.shape<EOL><DEDENT>except AttributeError:<EOL><INDENT>result = asarray(a).shape<EOL><DEDENT>return result<EOL>

Return the shape of an array.

Parameters
----------
a : array_like
    Input array.

Returns
-------
shape : tuple of ints
    The elements of the shape tuple give the lengths of the
    corresponding array dimensions.

See Also
--------
alen
ndarray.shape : Equivalent array method.

Examples
--------
>>> np.shape(np.eye(3))
(3, 3)
>>> np.shape([[1, 2]])
(1, 2)
>>> np.shape([0])
(1,)
>>> np.shape(0)
()

>>> a = np.array([(1, 2), (3, 4)], dtype=[('x', 'i4'), ('y', 'i4')])
>>> np.shape(a)
(2,)
>>> a.shape
(2,)


try:<EOL><INDENT>argmin = a.argmin<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', axis)<EOL><DEDENT>return argmin(axis)<EOL>

Return the indices of the minimum values along an axis.

See Also
--------
argmax : Similar function.  Please refer to `numpy.argmax` for detailed
    documentation.


def around(a, decimals=<NUM_LIT:0>, out=None):

try:<EOL><INDENT>round = a.round<EOL><DEDENT>except AttributeError:<EOL><INDENT>return _wrapit(a, '<STR_LIT>', decimals, out)<EOL><DEDENT>return round(decimals, out)<EOL>

Evenly round to the given number of decimals.

Parameters
----------
a : array_like
    Input data.
decimals : int, optional
    Number of decimal places to round to (default: 0).  If
    decimals is negative, it specifies the number of positions to
    the left of the decimal point.
out : ndarray, optional
    Alternative output array in which to place the result. It must have
    the same shape as the expected output, but the type of the output
    values will be cast if necessary. See `doc.ufuncs` (Section
    "Output arguments") for details.

Returns
-------
rounded_array : ndarray
    An array of the same type as `a`, containing the rounded values.
    Unless `out` was specified, a new array is created.  A reference to
    the result is returned.

    The real and imaginary parts of complex numbers are rounded
    separately.  The result of rounding a float is a float.

See Also
--------
ndarray.round : equivalent method

ceil, fix, floor, rint, trunc

Notes
-----
For values exactly halfway between rounded decimal values, Numpy
rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0,
-0.5 and 0.5 round to 0.0, etc. Results may also be surprising due
to the inexact representation of decimal fractions in the IEEE
floating point standard [1]_ and errors introduced when scaling
by powers of ten.

References
----------
.. [1] "Lecture Notes on the Status of  IEEE 754", William Kahan,
       http://www.cs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF
.. [2] "How Futile are Mindless Assessments of
       Roundoff in Floating-Point Computation?", William Kahan,
       http://www.cs.berkeley.edu/~wkahan/Mindless.pdf

Examples
--------
>>> np.around([0.37, 1.64])
array([ 0.,  2.])
>>> np.around([0.37, 1.64], decimals=1)
array([ 0.4,  1.6])
>>> np.around([.5, 1.5, 2.5, 3.5, 4.5]) # rounds to nearest even value
array([ 0.,  2.,  2.,  4.,  4.])
>>> np.around([1,2,3,11], decimals=1) # ndarray of ints is returned
array([ 1,  2,  3, 11])
>>> np.around([1,2,3,11], decimals=-1)
array([ 0,  0,  0, 10])