~jtaylor/ubuntu/precise/python-numpy/multiarch-fix-818867

« back to all changes in this revision

Viewing changes to numpy/ma/core.py

  • Committer: Bazaar Package Importer
  • Author(s): Sandro Tosi
  • Date: 2010-10-07 10:19:13 UTC
  • mfrom: (7.1.5 sid)
  • Revision ID: james.westby@ubuntu.com-20101007101913-8b1kmt8ho4upcl9s
Tags: 1:1.4.1-5
* debian/patches/10_use_local_python.org_object.inv_sphinx.diff
  - fixed small typo in description
* debian/patches/changeset_r8364.diff
  - fix memory corruption (double free); thanks to Joseph Barillari for the
    report and to Michael Gilbert for pushing resolution; Closes: #581058

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
"""
 
2
numpy.ma : a package to handle missing or invalid values.
 
3
 
 
4
This package was initially written for numarray by Paul F. Dubois
 
5
at Lawrence Livermore National Laboratory.
 
6
In 2006, the package was completely rewritten by Pierre Gerard-Marchant
 
7
(University of Georgia) to make the MaskedArray class a subclass of ndarray,
 
8
and to improve support of structured arrays.
 
9
 
 
10
 
 
11
Copyright 1999, 2000, 2001 Regents of the University of California.
 
12
Released for unlimited redistribution.
 
13
 
 
14
* Adapted for numpy_core 2005 by Travis Oliphant and (mainly) Paul Dubois.
 
15
* Subclassing of the base `ndarray` 2006 by Pierre Gerard-Marchant
 
16
  (pgmdevlist_AT_gmail_DOT_com)
 
17
* Improvements suggested by Reggie Dugard (reggie_AT_merfinllc_DOT_com)
 
18
 
 
19
.. moduleauthor:: Pierre Gerard-Marchant
 
20
 
 
21
"""
1
22
# pylint: disable-msg=E1002
2
23
"""
3
24
numpy.ma : a package to handle missing or invalid values.
4
25
 
5
26
This package was initially written for numarray by Paul F. Dubois
6
 
at Lawrence Livermore National Laboratory. 
 
27
at Lawrence Livermore National Laboratory.
7
28
In 2006, the package was completely rewritten by Pierre Gerard-Marchant
8
29
(University of Georgia) to make the MaskedArray class a subclass of ndarray,
9
30
and to improve support of structured arrays.
12
33
Copyright 1999, 2000, 2001 Regents of the University of California.
13
34
Released for unlimited redistribution.
14
35
* Adapted for numpy_core 2005 by Travis Oliphant and (mainly) Paul Dubois.
15
 
* Subclassing of the base ndarray 2006 by Pierre Gerard-Marchant 
 
36
* Subclassing of the base ndarray 2006 by Pierre Gerard-Marchant
16
37
  (pgmdevlist_AT_gmail_DOT_com)
17
38
* Improvements suggested by Reggie Dugard (reggie_AT_merfinllc_DOT_com)
18
39
 
29
50
           'amax', 'amin', 'anom', 'anomalies', 'any', 'arange',
30
51
           'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan', 'arctan2',
31
52
           'arctanh', 'argmax', 'argmin', 'argsort', 'around',
32
 
           'array', 'asarray','asanyarray',
 
53
           'array', 'asarray', 'asanyarray',
33
54
           'bitwise_and', 'bitwise_or', 'bitwise_xor',
34
55
           'ceil', 'choose', 'clip', 'common_fill_value', 'compress',
35
56
           'compressed', 'concatenate', 'conjugate', 'copy', 'cos', 'cosh',
36
57
           'count', 'cumprod', 'cumsum',
37
 
           'default_fill_value', 'diag', 'diagonal', 'divide', 'dump', 'dumps',
 
58
           'default_fill_value', 'diag', 'diagonal', 'diff', 'divide', 'dump',
 
59
           'dumps',
38
60
           'empty', 'empty_like', 'equal', 'exp', 'expand_dims',
39
61
           'fabs', 'flatten_mask', 'fmod', 'filled', 'floor', 'floor_divide',
40
62
           'fix_invalid', 'flatten_structured_array', 'frombuffer', 'fromflex',
41
63
           'fromfunction',
42
 
           'getdata','getmask', 'getmaskarray', 'greater', 'greater_equal',
 
64
           'getdata', 'getmask', 'getmaskarray', 'greater', 'greater_equal',
43
65
           'harden_mask', 'hypot',
44
66
           'identity', 'ids', 'indices', 'inner', 'innerproduct',
45
67
           'isMA', 'isMaskedArray', 'is_mask', 'is_masked', 'isarray',
48
70
           'make_mask', 'make_mask_descr', 'make_mask_none', 'mask_or',
49
71
           'masked', 'masked_array', 'masked_equal', 'masked_greater',
50
72
           'masked_greater_equal', 'masked_inside', 'masked_invalid',
51
 
           'masked_less','masked_less_equal', 'masked_not_equal',
52
 
           'masked_object','masked_outside', 'masked_print_option',
53
 
           'masked_singleton','masked_values', 'masked_where', 'max', 'maximum',
 
73
           'masked_less', 'masked_less_equal', 'masked_not_equal',
 
74
           'masked_object', 'masked_outside', 'masked_print_option',
 
75
           'masked_singleton', 'masked_values', 'masked_where', 'max', 'maximum',
54
76
           'maximum_fill_value', 'mean', 'min', 'minimum', 'minimum_fill_value',
55
77
           'mod', 'multiply',
56
78
           'negative', 'nomask', 'nonzero', 'not_equal',
74
96
 
75
97
import numpy.core.umath as umath
76
98
import numpy.core.numerictypes as ntypes
 
99
from numpy.compat import getargspec, formatargspec
77
100
from numpy import expand_dims as n_expand_dims
78
101
import warnings
79
102
 
106
129
    """
107
130
    Get the signature from obj
108
131
    """
109
 
    import inspect
110
132
    try:
111
 
        sig = inspect.formatargspec(*inspect.getargspec(obj))
 
133
        sig = formatargspec(*getargspec(obj))
112
134
    except TypeError, errmsg:
113
135
        msg = "Unable to retrieve the signature of %s '%s'\n"\
114
136
              "(Initial error message: %s)"
122
144
#---- --- Exceptions ---
123
145
#####--------------------------------------------------------------------------
124
146
class MAError(Exception):
125
 
    "Class for MA related errors."
 
147
    """Class for masked array related errors."""
126
148
    pass
127
149
class MaskError(MAError):
128
150
    "Class for mask related errors."
141
163
                  'S' : 'N/A',
142
164
                  'u' : 999999,
143
165
                  'V' : '???',
 
166
                  'U' : 'N/A',
144
167
                  }
145
168
max_filler = ntypes._minvals
146
169
max_filler.update([(k, -np.inf) for k in [np.float32, np.float64]])
153
176
 
154
177
def default_fill_value(obj):
155
178
    """
156
 
    Calculate the default fill value for the argument object.
 
179
    Return the default fill value for the argument object.
 
180
 
 
181
    The default filling value depends on the datatype of the input
 
182
    array or the type of the input scalar:
 
183
 
 
184
       ========  ========
 
185
       datatype  default
 
186
       ========  ========
 
187
       bool      True
 
188
       int       999999
 
189
       float     1.e20
 
190
       complex   1.e20+0j
 
191
       object    '?'
 
192
       string    'N/A'
 
193
       ========  ========
 
194
 
 
195
 
 
196
    Parameters
 
197
    ----------
 
198
    obj : ndarray, dtype or scalar
 
199
        The array data-type or scalar for which the default fill value
 
200
        is returned.
 
201
 
 
202
    Returns
 
203
    -------
 
204
    fill_value : scalar
 
205
        The default fill value.
 
206
 
 
207
    Examples
 
208
    --------
 
209
    >>> np.ma.default_fill_value(1)
 
210
    999999
 
211
    >>> np.ma.default_fill_value(np.array([1.1, 2., np.pi]))
 
212
    1e+20
 
213
    >>>  np.ma.default_fill_value(np.dtype(complex))
 
214
    (1e+20+0j)
157
215
 
158
216
    """
159
 
    if hasattr(obj,'dtype'):
 
217
    if hasattr(obj, 'dtype'):
160
218
        defval = _check_fill_value(None, obj.dtype)
161
219
    elif isinstance(obj, np.dtype):
162
220
        if obj.subdtype:
163
 
            defval = default_filler[obj.subdtype[0].kind]
 
221
            defval = default_filler.get(obj.subdtype[0].kind, '?')
164
222
        else:
165
 
            defval = default_filler[obj.kind]
 
223
            defval = default_filler.get(obj.kind, '?')
166
224
    elif isinstance(obj, float):
167
225
        defval = default_filler['f']
168
226
    elif isinstance(obj, int) or isinstance(obj, long):
169
227
        defval = default_filler['i']
170
228
    elif isinstance(obj, str):
171
229
        defval = default_filler['S']
 
230
    elif isinstance(obj, unicode):
 
231
        defval = default_filler['U']
172
232
    elif isinstance(obj, complex):
173
233
        defval = default_filler['c']
174
234
    else:
189
249
 
190
250
def minimum_fill_value(obj):
191
251
    """
192
 
    Calculate the default fill value suitable for taking the minimum of ``obj``.
 
252
    Return the maximum value that can be represented by the dtype of an object.
 
253
 
 
254
    This function is useful for calculating a fill value suitable for
 
255
    taking the minimum of an array with a given dtype.
 
256
 
 
257
    Parameters
 
258
    ----------
 
259
    obj : ndarray or dtype
 
260
        An object that can be queried for it's numeric type.
 
261
 
 
262
    Returns
 
263
    -------
 
264
    val : scalar
 
265
        The maximum representable value.
 
266
 
 
267
    Raises
 
268
    ------
 
269
    TypeError
 
270
        If `obj` isn't a suitable numeric type.
 
271
 
 
272
    See Also
 
273
    --------
 
274
    maximum_fill_value : The inverse function.
 
275
    set_fill_value : Set the filling value of a masked array.
 
276
    MaskedArray.fill_value : Return current fill value.
 
277
 
 
278
    Examples
 
279
    --------
 
280
    >>> import numpy.ma as ma
 
281
    >>> a = np.int8()
 
282
    >>> ma.minimum_fill_value(a)
 
283
    127
 
284
    >>> a = np.int32()
 
285
    >>> ma.minimum_fill_value(a)
 
286
    2147483647
 
287
 
 
288
    An array of numeric data can also be passed.
 
289
 
 
290
    >>> a = np.array([1, 2, 3], dtype=np.int8)
 
291
    >>> ma.minimum_fill_value(a)
 
292
    127
 
293
    >>> a = np.array([1, 2, 3], dtype=np.float32)
 
294
    >>> ma.minimum_fill_value(a)
 
295
    inf
193
296
 
194
297
    """
195
298
    errmsg = "Unsuitable type for calculating minimum."
209
312
 
210
313
def maximum_fill_value(obj):
211
314
    """
212
 
    Calculate the default fill value suitable for taking the maximum of ``obj``.
 
315
    Return the minimum value that can be represented by the dtype of an object.
 
316
 
 
317
    This function is useful for calculating a fill value suitable for
 
318
    taking the maximum of an array with a given dtype.
 
319
 
 
320
    Parameters
 
321
    ----------
 
322
    obj : {ndarray, dtype}
 
323
        An object that can be queried for it's numeric type.
 
324
 
 
325
    Returns
 
326
    -------
 
327
    val : scalar
 
328
        The minimum representable value.
 
329
 
 
330
    Raises
 
331
    ------
 
332
    TypeError
 
333
        If `obj` isn't a suitable numeric type.
 
334
 
 
335
    See Also
 
336
    --------
 
337
    minimum_fill_value : The inverse function.
 
338
    set_fill_value : Set the filling value of a masked array.
 
339
    MaskedArray.fill_value : Return current fill value.
 
340
 
 
341
    Examples
 
342
    --------
 
343
    >>> import numpy.ma as ma
 
344
    >>> a = np.int8()
 
345
    >>> ma.maximum_fill_value(a)
 
346
    -128
 
347
    >>> a = np.int32()
 
348
    >>> ma.maximum_fill_value(a)
 
349
    -2147483648
 
350
 
 
351
    An array of numeric data can also be passed.
 
352
 
 
353
    >>> a = np.array([1, 2, 3], dtype=np.int8)
 
354
    >>> ma.maximum_fill_value(a)
 
355
    -128
 
356
    >>> a = np.array([1, 2, 3], dtype=np.float32)
 
357
    >>> ma.maximum_fill_value(a)
 
358
    -inf
213
359
 
214
360
    """
215
361
    errmsg = "Unsuitable type for calculating maximum."
319
465
    --------
320
466
    maximum_fill_value : Return the default fill value for a dtype.
321
467
    MaskedArray.fill_value : Return current fill value.
 
468
    MaskedArray.set_fill_value : Equivalent method.
322
469
 
323
470
    Examples
324
471
    --------
371
518
 
372
519
def common_fill_value(a, b):
373
520
    """
374
 
    Return the common filling value of a and b, if any.
375
 
    If a and b have different filling values, returns None.
 
521
    Return the common filling value of two masked arrays, if any.
 
522
 
 
523
    If ``a.fill_value == b.fill_value``, return the fill value,
 
524
    otherwise return None.
 
525
 
 
526
    Parameters
 
527
    ----------
 
528
    a, b : MaskedArray
 
529
        The masked arrays for which to compare fill values.
 
530
 
 
531
    Returns
 
532
    -------
 
533
    fill_value : scalar or None
 
534
        The common fill value, or None.
 
535
 
 
536
    Examples
 
537
    --------
 
538
    >>> x = np.ma.array([0, 1.], fill_value=3)
 
539
    >>> y = np.ma.array([0, 1.], fill_value=3)
 
540
    >>> np.ma.common_fill_value(x, y)
 
541
    3.0
376
542
 
377
543
    """
378
544
    t1 = get_fill_value(a)
383
549
 
384
550
 
385
551
#####--------------------------------------------------------------------------
386
 
def filled(a, fill_value = None):
 
552
def filled(a, fill_value=None):
387
553
    """
388
 
    Return `a` as an array where masked data have been replaced by `value`.
 
554
    Return input as an array with masked data replaced by a fill value.
389
555
 
390
 
    If `a` is not a MaskedArray, `a` itself is returned.
391
 
    If `a` is a MaskedArray and `fill_value` is None, `fill_value` is set to
392
 
    `a.fill_value`.
 
556
    If `a` is not a `MaskedArray`, `a` itself is returned.
 
557
    If `a` is a `MaskedArray` and `fill_value` is None, `fill_value` is set to
 
558
    ``a.fill_value``.
393
559
 
394
560
    Parameters
395
561
    ----------
396
 
    a : maskedarray or array_like
 
562
    a : MaskedArray or array_like
397
563
        An input object.
398
 
    fill_value : {var}, optional
399
 
        Filling value. If None, the output of :func:`get_fill_value(a)` is used
400
 
        instead.
 
564
    fill_value : scalar, optional
 
565
        Filling value. Default is None.
401
566
 
402
567
    Returns
403
568
    -------
404
 
    a : array_like
 
569
    a : ndarray
 
570
        The filled array.
 
571
 
 
572
    Examples
 
573
    --------
 
574
    >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[[1, 0, 0],
 
575
    ...                                                   [1, 0, 0],
 
576
    ...                                                   [0, 0, 0]])
 
577
    >>> x.filled()
 
578
    array([[999999,      1,      2],
 
579
           [999999,      4,      5],
 
580
           [     6,      7,      8]])
405
581
 
406
582
    """
407
583
    if hasattr(a, 'filled'):
451
627
        Input ``MaskedArray``, alternatively a ndarray or a subclass thereof.
452
628
    subok : bool
453
629
        Whether to force the output to be a `pure` ndarray (False) or to
454
 
        return a subclass of ndarray if approriate (True - default).
 
630
        return a subclass of ndarray if appropriate (True, default).
455
631
 
456
632
    See Also
457
633
    --------
482
658
           [3, 4]])
483
659
 
484
660
    """
485
 
    data = getattr(a, '_data', np.array(a, subok=subok))
 
661
    try:
 
662
        data = a._data
 
663
    except AttributeError:
 
664
        data = np.array(a, copy=False, subok=subok)
486
665
    if not subok:
487
666
        return data.view(ndarray)
488
667
    return data
491
670
 
492
671
def fix_invalid(a, mask=nomask, copy=True, fill_value=None):
493
672
    """
494
 
    Return (a copy of) `a` where invalid data (nan/inf) are masked
495
 
    and replaced by `fill_value`.
 
673
    Return input with invalid data masked and replaced by a fill value.
496
674
 
497
 
    Note that a copy is performed by default (just in case...).
 
675
    Invalid data means values of `nan`, `inf`, etc.
498
676
 
499
677
    Parameters
500
678
    ----------
501
679
    a : array_like
502
 
        A (subclass of) ndarray.
503
 
    copy : bool
 
680
        Input array, a (subclass of) ndarray.
 
681
    copy : bool, optional
504
682
        Whether to use a copy of `a` (True) or to fix `a` in place (False).
505
 
    fill_value : {var}, optional
506
 
        Value used for fixing invalid data.  If not given, the output
507
 
        of get_fill_value(a) is used instead.
 
683
        Default is True.
 
684
    fill_value : scalar, optional
 
685
        Value used for fixing invalid data. Default is None, in which case
 
686
        the ``a.fill_value`` is used.
508
687
 
509
688
    Returns
510
689
    -------
511
690
    b : MaskedArray
 
691
        The input array with invalid entries fixed.
 
692
 
 
693
    Notes
 
694
    -----
 
695
    A copy is performed by default.
 
696
 
 
697
    Examples
 
698
    --------
 
699
    >>> x = np.ma.array([1., -1, np.nan, np.inf], mask=[1] + [0]*3)
 
700
    >>> x
 
701
    masked_array(data = [-- -1.0 nan inf],
 
702
                 mask = [ True False False False],
 
703
           fill_value = 1e+20)
 
704
    >>> np.ma.fix_invalid(x)
 
705
    masked_array(data = [-- -1.0 -- --],
 
706
                 mask = [ True False  True  True],
 
707
           fill_value = 1e+20)
 
708
 
 
709
    >>> fixed = np.ma.fix_invalid(x)
 
710
    >>> fixed.data
 
711
    array([  1.00000000e+00,  -1.00000000e+00,   1.00000000e+20,
 
712
             1.00000000e+20])
 
713
    >>> x.data
 
714
    array([  1.,  -1.,  NaN,  Inf])
512
715
 
513
716
    """
514
717
    a = masked_array(a, copy=copy, mask=mask, subok=True)
531
734
ufunc_fills = {}
532
735
 
533
736
class _DomainCheckInterval:
534
 
    """Define a valid interval, so that :
 
737
    """
 
738
    Define a valid interval, so that :
535
739
 
536
 
    ``domain_check_interval(a,b)(x) = true`` where
 
740
    ``domain_check_interval(a,b)(x) == True`` where
537
741
    ``x < a`` or ``x > b``.
538
742
 
539
743
    """
548
752
        "Execute the call behavior."
549
753
        return umath.logical_or(umath.greater (x, self.b),
550
754
                                umath.less(x, self.a))
551
 
#............................
 
755
 
 
756
 
 
757
 
552
758
class _DomainTan:
553
759
    """Define a valid interval for the `tan` function, so that:
554
760
 
558
764
    def __init__(self, eps):
559
765
        "domain_tan(eps) = true where abs(cos(x)) < eps)"
560
766
        self.eps = eps
 
767
 
561
768
    def __call__ (self, x):
562
769
        "Executes the call behavior."
563
770
        return umath.less(umath.absolute(umath.cos(x)), self.eps)
564
 
#............................
 
771
 
 
772
 
 
773
 
565
774
class _DomainSafeDivide:
566
775
    """Define a domain for safe division."""
567
776
    def __init__ (self, tolerance=None):
568
777
        self.tolerance = tolerance
 
778
 
569
779
    def __call__ (self, a, b):
570
780
        # Delay the selection of the tolerance to here in order to reduce numpy
571
781
        # import times. The calculation of these parameters is a substantial
573
783
        if self.tolerance is None:
574
784
            self.tolerance = np.finfo(float).tiny
575
785
        return umath.absolute(a) * self.tolerance >= umath.absolute(b)
576
 
#............................
 
786
 
 
787
 
 
788
 
577
789
class _DomainGreater:
578
 
    "DomainGreater(v)(x) = true where x <= v"
 
790
    """DomainGreater(v)(x) is True where x <= v."""
579
791
    def __init__(self, critical_value):
580
792
        "DomainGreater(v)(x) = true where x <= v"
581
793
        self.critical_value = critical_value
583
795
    def __call__ (self, x):
584
796
        "Executes the call behavior."
585
797
        return umath.less_equal(x, self.critical_value)
586
 
#............................
 
798
 
 
799
 
 
800
 
587
801
class _DomainGreaterEqual:
588
 
    "DomainGreaterEqual(v)(x) = true where x < v"
 
802
    """DomainGreaterEqual(v)(x) is True where x < v."""
589
803
    def __init__(self, critical_value):
590
804
        "DomainGreaterEqual(v)(x) = true where x < v"
591
805
        self.critical_value = critical_value
596
810
 
597
811
#..............................................................................
598
812
class _MaskedUnaryOperation:
599
 
    """Defines masked version of unary operations, where invalid
600
 
    values are pre-masked.
 
813
    """
 
814
    Defines masked version of unary operations, where invalid values are
 
815
    pre-masked.
601
816
 
602
817
    Parameters
603
818
    ----------
604
 
    f : callable
605
 
    fill :
606
 
        Default filling value (0).
607
 
    domain :
608
 
        Default domain (None).
 
819
    mufunc : callable
 
820
        The function for which to define a masked version. Made available
 
821
        as ``_MaskedUnaryOperation.f``.
 
822
    fill : scalar, optional
 
823
        Filling value, default is 0.
 
824
    domain : class instance
 
825
        Domain for the function. Should be one of the ``_Domain*``
 
826
        classes. Default is None.
609
827
 
610
828
    """
611
829
    def __init__ (self, mufunc, fill=0, domain=None):
624
842
    #
625
843
    def __call__ (self, a, *args, **kwargs):
626
844
        "Execute the call behavior."
627
 
        #
628
 
        m = getmask(a)
629
 
        d1 = getdata(a)
630
 
        #
 
845
        d = getdata(a)
 
846
        # Case 1.1. : Domained function
631
847
        if self.domain is not None:
632
 
            dm = np.array(self.domain(d1), copy=False)
633
 
            m = np.logical_or(m, dm)
634
 
            # The following two lines control the domain filling methods.
635
 
            d1 = d1.copy()
636
 
            # We could use smart indexing : d1[dm] = self.fill ...
637
 
            # ... but np.putmask looks more efficient, despite the copy.
638
 
            np.putmask(d1, dm, self.fill)
639
 
        # Take care of the masked singletong first ...
640
 
        if (not m.ndim) and m:
641
 
            return masked
642
 
        elif m is nomask:
643
 
            result = self.f(d1, *args, **kwargs)
644
 
        else:
645
 
            result = np.where(m, d1, self.f(d1, *args, **kwargs))
646
 
        # If result is not a scalar
647
 
        if result.ndim:
648
 
            # Get the result subclass:
649
 
            if isinstance(a, MaskedArray):
650
 
                subtype = type(a)
651
 
            else:
652
 
                subtype = MaskedArray
653
 
            result = result.view(subtype)
654
 
            result._mask = m
655
 
            result._update_from(a)
 
848
            # Save the error status
 
849
            err_status_ini = np.geterr()
 
850
            np.seterr(divide='ignore', invalid='ignore')
 
851
            # Get the result
 
852
            result = self.f(d, *args, **kwargs)
 
853
            # Reset the error status
 
854
            np.seterr(**err_status_ini)
 
855
            # Make a mask
 
856
            m = ~umath.isfinite(result)
 
857
            m |= self.domain(d)
 
858
            m |= getmask(a)
 
859
        # Case 1.2. : Function without a domain
 
860
        else:
 
861
            # Get the result and the mask
 
862
            result = self.f(d, *args, **kwargs)
 
863
            m = getmask(a)
 
864
        # Case 2.1. : The result is scalarscalar
 
865
        if not result.ndim:
 
866
            if m:
 
867
                return masked
 
868
            return result
 
869
        # Case 2.2. The result is an array
 
870
        # We need to fill the invalid data back w/ the input
 
871
        # Now, that's plain silly: in C, we would just skip the element and keep
 
872
        # the original, but we do have to do it that way in Python
 
873
        if m is not nomask:
 
874
            # In case result has a lower dtype than the inputs (as in equal)
 
875
            try:
 
876
                np.putmask(result, m, d)
 
877
            except TypeError:
 
878
                pass
 
879
        # Transform to
 
880
        if isinstance(a, MaskedArray):
 
881
            subtype = type(a)
 
882
        else:
 
883
            subtype = MaskedArray
 
884
        result = result.view(subtype)
 
885
        result._mask = m
 
886
        result._update_from(a)
656
887
        return result
657
888
    #
658
889
    def __str__ (self):
659
890
        return "Masked version of %s. [Invalid values are masked]" % str(self.f)
660
891
 
661
 
#..............................................................................
 
892
 
 
893
 
662
894
class _MaskedBinaryOperation:
663
 
    """Define masked version of binary operations, where invalid
 
895
    """
 
896
    Define masked version of binary operations, where invalid
664
897
    values are pre-masked.
665
898
 
666
899
    Parameters
667
900
    ----------
668
 
    f : callable
669
 
    fillx :
670
 
        Default filling value for the first argument (0).
671
 
    filly :
672
 
        Default filling value for the second argument (0).
673
 
    domain :
674
 
        Default domain (None).
 
901
    mbfunc : function
 
902
        The function for which to define a masked version. Made available
 
903
        as ``_MaskedBinaryOperation.f``.
 
904
    domain : class instance
 
905
        Default domain for the function. Should be one of the ``_Domain*``
 
906
        classes. Default is None.
 
907
    fillx : scalar, optional
 
908
        Filling value for the first argument, default is 0.
 
909
    filly : scalar, optional
 
910
        Filling value for the second argument, default is 0.
675
911
 
676
912
    """
677
913
    def __init__ (self, mbfunc, fillx=0, filly=0):
688
924
 
689
925
    def __call__ (self, a, b, *args, **kwargs):
690
926
        "Execute the call behavior."
691
 
        m = mask_or(getmask(a), getmask(b), shrink=False)
692
 
        (da, db) = (getdata(a), getdata(b))
693
 
        # Easy case: there's no mask...
694
 
        if m is nomask:
695
 
            result = self.f(da, db, *args, **kwargs)
696
 
        # There are some masked elements: run only on the unmasked
 
927
        # Get the data, as ndarray
 
928
        (da, db) = (getdata(a, subok=False), getdata(b, subok=False))
 
929
        # Get the mask
 
930
        (ma, mb) = (getmask(a), getmask(b))
 
931
        if ma is nomask:
 
932
            if mb is nomask:
 
933
                m = nomask
 
934
            else:
 
935
                m = umath.logical_or(getmaskarray(a), mb)
 
936
        elif mb is nomask:
 
937
            m = umath.logical_or(ma, getmaskarray(b))
697
938
        else:
698
 
            result = np.where(m, da, self.f(da, db, *args, **kwargs))
699
 
        # Transforms to a (subclass of) MaskedArray if we don't have a scalar
700
 
        if result.shape:
701
 
            result = result.view(get_masked_subclass(a, b))
702
 
            # If we have a mask, make sure it's broadcasted properly
703
 
            if m.any():
704
 
                result._mask = mask_or(getmaskarray(a), getmaskarray(b))
705
 
            # If some initial masks where not shrunk, don't shrink the result
706
 
            elif m.shape:
707
 
                result._mask = make_mask_none(result.shape, result.dtype)
 
939
            m = umath.logical_or(ma, mb)
 
940
        # Get the result
 
941
        result = self.f(da, db, *args, **kwargs)
 
942
        # Case 1. : scalar
 
943
        if not result.ndim:
 
944
            if m:
 
945
                return masked
 
946
            return result
 
947
        # Case 2. : array
 
948
        # Revert result to da where masked
 
949
        if m.any():
 
950
            np.putmask(result, m, 0)
 
951
            result += m * da
 
952
        # Transforms to a (subclass of) MaskedArray
 
953
        result = result.view(get_masked_subclass(a, b))
 
954
        result._mask = m
 
955
        # Update the optional info from the inputs
 
956
        if isinstance(b, MaskedArray):
708
957
            if isinstance(a, MaskedArray):
709
958
                result._update_from(a)
710
 
            if isinstance(b, MaskedArray):
 
959
            else:
711
960
                result._update_from(b)
712
 
        # ... or return masked if we have a scalar and the common mask is True
713
 
        elif m:
714
 
            return masked
 
961
        elif isinstance(a, MaskedArray):
 
962
            result._update_from(a)
715
963
        return result
716
 
#
717
 
#        result = self.f(d1, d2, *args, **kwargs).view(get_masked_subclass(a, b))
718
 
#        if len(result.shape):
719
 
#            if m is not nomask:
720
 
#                result._mask = make_mask_none(result.shape)
721
 
#                result._mask.flat = m
722
 
#                #!!!!!
723
 
#                # Force m to be at least 1D
724
 
#                m.shape = m.shape or (1,)
725
 
#                print "Resetting data"
726
 
#                result.data[m].flat = d1.flat
727
 
#                #!!!!!
728
 
#            if isinstance(a, MaskedArray):
729
 
#                result._update_from(a)
730
 
#            if isinstance(b, MaskedArray):
731
 
#                result._update_from(b)
732
 
#        elif m:
733
 
#            return masked
734
 
#        return result
 
964
 
735
965
 
736
966
    def reduce(self, target, axis=0, dtype=None):
737
967
        """Reduce `target` along the given `axis`."""
775
1005
        if (not m.ndim) and m:
776
1006
            return masked
777
1007
        (da, db) = (getdata(a), getdata(b))
778
 
        if m is nomask:
779
 
            d = self.f.outer(da, db)
780
 
        else:
781
 
            d = np.where(m, da, self.f.outer(da, db))
 
1008
        d = self.f.outer(da, db)
 
1009
        if m is not nomask:
 
1010
            np.putmask(d, m, da)
782
1011
        if d.shape:
783
1012
            d = d.view(get_masked_subclass(a, b))
784
1013
            d._mask = m
799
1028
    def __str__ (self):
800
1029
        return "Masked version of " + str(self.f)
801
1030
 
802
 
#..............................................................................
 
1031
 
 
1032
 
803
1033
class _DomainedBinaryOperation:
804
1034
    """
805
1035
    Define binary operations that have a domain, like divide.
808
1038
 
809
1039
    Parameters
810
1040
    ----------
811
 
    f : function.
812
 
    domain : Default domain.
813
 
    fillx : Default filling value for the first argument (0).
814
 
    filly : Default filling value for the second argument (0).
 
1041
    mbfunc : function
 
1042
        The function for which to define a masked version. Made available
 
1043
        as ``_DomainedBinaryOperation.f``.
 
1044
    domain : class instance
 
1045
        Default domain for the function. Should be one of the ``_Domain*``
 
1046
        classes.
 
1047
    fillx : scalar, optional
 
1048
        Filling value for the first argument, default is 0.
 
1049
    filly : scalar, optional
 
1050
        Filling value for the second argument, default is 0.
815
1051
 
816
1052
    """
817
1053
    def __init__ (self, dbfunc, domain, fillx=0, filly=0):
829
1065
 
830
1066
    def __call__(self, a, b, *args, **kwargs):
831
1067
        "Execute the call behavior."
832
 
        ma = getmask(a)
833
 
        mb = getmaskarray(b)
834
 
        da = getdata(a)
835
 
        db = getdata(b)
836
 
        t = narray(self.domain(da, db), copy=False)
837
 
        if t.any(None):
838
 
            mb = mask_or(mb, t, shrink=False)
839
 
            # The following line controls the domain filling
840
 
            if t.size == db.size:
841
 
                db = np.where(t, self.filly, db)
 
1068
        # Get the data and the mask
 
1069
        (da, db) = (getdata(a, subok=False), getdata(b, subok=False))
 
1070
        (ma, mb) = (getmask(a), getmask(b))
 
1071
        # Save the current error status
 
1072
        err_status_ini = np.geterr()
 
1073
        np.seterr(divide='ignore', invalid='ignore')
 
1074
        # Get the result
 
1075
        result = self.f(da, db, *args, **kwargs)
 
1076
        # Reset the error status
 
1077
        np.seterr(**err_status_ini)
 
1078
        # Get the mask as a combination of ma, mb and invalid
 
1079
        m = ~umath.isfinite(result)
 
1080
        m |= ma
 
1081
        m |= mb
 
1082
        # Take care of the scalar case first
 
1083
        if (not m.ndim):
 
1084
            if m:
 
1085
                return masked
842
1086
            else:
843
 
                db = np.where(np.resize(t, db.shape), self.filly, db)
844
 
        # Shrink m if a.mask was nomask, otherwise don't.
845
 
        m = mask_or(ma, mb, shrink=(getattr(a, '_mask', nomask) is nomask))
846
 
        if (not m.ndim) and m:
847
 
            return masked
848
 
        elif (m is nomask):
849
 
            result = self.f(da, db, *args, **kwargs)
850
 
        else:
851
 
            result = np.where(m, da, self.f(da, db, *args, **kwargs))
852
 
        if result.shape:
853
 
            result = result.view(get_masked_subclass(a, b))
854
 
            # If we have a mask, make sure it's broadcasted properly
855
 
            if m.any():
856
 
                result._mask = mask_or(getmaskarray(a), mb)
857
 
            # If some initial masks where not shrunk, don't shrink the result
858
 
            elif m.shape:
859
 
                result._mask = make_mask_none(result.shape, result.dtype)
 
1087
                return result
 
1088
        # When the mask is True, put back da
 
1089
        np.putmask(result, m, 0)
 
1090
        result += m * da
 
1091
        result = result.view(get_masked_subclass(a, b))
 
1092
        result._mask = m
 
1093
        if isinstance(b, MaskedArray):
860
1094
            if isinstance(a, MaskedArray):
861
1095
                result._update_from(a)
862
 
            if isinstance(b, MaskedArray):
 
1096
            else:
863
1097
                result._update_from(b)
 
1098
        elif isinstance(a, MaskedArray):
 
1099
            result._update_from(a)
864
1100
        return result
865
1101
 
866
1102
    def __str__ (self):
893
1129
log10 = _MaskedUnaryOperation(umath.log10, 1.0,
894
1130
                              _DomainGreater(0.0))
895
1131
tan = _MaskedUnaryOperation(umath.tan, 0.0,
896
 
                            _DomainTan(1.e-35))
 
1132
                            _DomainTan(1e-35))
897
1133
arcsin = _MaskedUnaryOperation(umath.arcsin, 0.0,
898
1134
                               _DomainCheckInterval(-1.0, 1.0))
899
1135
arccos = _MaskedUnaryOperation(umath.arccos, 0.0,
901
1137
arccosh = _MaskedUnaryOperation(umath.arccosh, 1.0,
902
1138
                                _DomainGreaterEqual(1.0))
903
1139
arctanh = _MaskedUnaryOperation(umath.arctanh, 0.0,
904
 
                                _DomainCheckInterval(-1.0+1e-15, 1.0-1e-15))
 
1140
                                _DomainCheckInterval(-1.0 + 1e-15, 1.0 - 1e-15))
905
1141
# Binary ufuncs ...............................................................
906
1142
add = _MaskedBinaryOperation(umath.add)
907
1143
subtract = _MaskedBinaryOperation(umath.subtract)
1196
1432
    ----------
1197
1433
    m : array_like
1198
1434
        Potential mask.
1199
 
    copy : bool
 
1435
    copy : bool, optional
1200
1436
        Whether to return a copy of `m` (True) or `m` itself (False).
1201
 
    shrink : bool
 
1437
    shrink : bool, optional
1202
1438
        Whether to shrink `m` to ``nomask`` if all its values are False.
1203
 
    flag : bool
 
1439
    flag : bool, optional
1204
1440
        Deprecated equivalent of `shrink`.
1205
 
    dtype : dtype
 
1441
    dtype : dtype, optional
1206
1442
        Data-type of the output mask. By default, the output mask has
1207
1443
        a dtype of MaskType (bool). If the dtype is flexible, each field
1208
1444
        has a boolean dtype.
1334
1570
 
1335
1571
def mask_or (m1, m2, copy=False, shrink=True):
1336
1572
    """
1337
 
    Return the combination of two masks m1 and m2.
 
1573
    Combine two masks with the ``logical_or`` operator.
1338
1574
 
1339
 
    The masks are combined with the *logical_or* operator, treating
1340
 
    nomask as False.  The result may equal m1 or m2 if the other is
1341
 
    nomask.
 
1575
    The result may be a view on `m1` or `m2` if the other is `nomask`
 
1576
    (i.e. False).
1342
1577
 
1343
1578
    Parameters
1344
1579
    ----------
1345
 
    m1 : array_like
1346
 
        First mask.
1347
 
    m2 : array_like
1348
 
        Second mask
1349
 
    copy : {False, True}, optional
1350
 
        Whether to return a copy.
1351
 
    shrink : {True, False}, optional
1352
 
        Whether to shrink m to nomask if all its values are False.
 
1580
    m1, m2 : array_like
 
1581
        Input masks.
 
1582
    copy : bool, optional
 
1583
        If copy is False and one of the inputs is `nomask`, return a view
 
1584
        of the other input mask. Defaults to False.
 
1585
    shrink : bool, optional
 
1586
        Whether to shrink the output to `nomask` if all its values are
 
1587
        False. Defaults to True.
 
1588
 
 
1589
    Returns
 
1590
    -------
 
1591
    mask : output mask
 
1592
        The result masks values that are masked in either `m1` or `m2`.
1353
1593
 
1354
1594
    Raises
1355
1595
    ------
1356
1596
    ValueError
1357
 
        If m1 and m2 have different flexible dtypes.
 
1597
        If `m1` and `m2` have different flexible dtypes.
 
1598
 
 
1599
    Examples
 
1600
    --------
 
1601
    >>> m1 = np.ma.make_mask([0, 1, 1, 0])
 
1602
    >>> m2 = np.ma.make_mask([1, 0, 0, 0])
 
1603
    >>> np.ma.mask_or(m1, m2)
 
1604
    array([ True,  True,  True, False], dtype=bool)
1358
1605
 
1359
1606
    """
1360
1607
    def _recursive_mask_or(m1, m2, newmask):
1393
1640
    Parameters
1394
1641
    ----------
1395
1642
    mask : array_like
1396
 
        Array of booleans
 
1643
        Input array, which will be interpreted as booleans.
1397
1644
 
1398
1645
    Returns
1399
1646
    -------
1400
 
    flattened_mask : ndarray
1401
 
        Boolean array.
 
1647
    flattened_mask : ndarray of bools
 
1648
        The flattened input.
1402
1649
 
1403
1650
    Examples
1404
1651
    --------
1405
1652
    >>> mask = np.array([0, 0, 1], dtype=np.bool)
1406
1653
    >>> flatten_mask(mask)
1407
1654
    array([False, False,  True], dtype=bool)
 
1655
 
1408
1656
    >>> mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)])
1409
1657
    >>> flatten_mask(mask)
1410
1658
    array([False, False, False,  True], dtype=bool)
 
1659
 
1411
1660
    >>> mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
1412
1661
    >>> mask = np.array([(0, (0, 0)), (0, (0, 1))], dtype=mdtype)
1413
1662
    >>> flatten_mask(mask)
1440
1689
    return np.array([_ for _ in flattened], dtype=bool)
1441
1690
 
1442
1691
 
 
1692
def _check_mask_axis(mask, axis):
 
1693
    "Check whether there are masked values along the given axis"
 
1694
    if mask is not nomask:
 
1695
        return mask.all(axis=axis)
 
1696
    return nomask
 
1697
 
 
1698
 
1443
1699
#####--------------------------------------------------------------------------
1444
1700
#--- --- Masking functions ---
1445
1701
#####--------------------------------------------------------------------------
1720
1976
    # c = umath.equal(d, value)
1721
1977
    # m = mask_or(c, getmask(x))
1722
1978
    # return array(d, mask=m, copy=copy)
1723
 
    return masked_where(equal(x, value), x, copy=copy)
 
1979
    output = masked_where(equal(x, value), x, copy=copy)
 
1980
    output.fill_value = value
 
1981
    return output
1724
1982
 
1725
1983
 
1726
1984
def masked_inside(x, v1, v2, copy=True):
1864
2122
    return masked_array(x, mask=mask, copy=copy, fill_value=value)
1865
2123
 
1866
2124
 
1867
 
def masked_values(x, value, rtol=1.e-5, atol=1.e-8, copy=True, shrink=True):
 
2125
def masked_values(x, value, rtol=1e-5, atol=1e-8, copy=True, shrink=True):
1868
2126
    """
1869
2127
    Mask using floating point equality.
1870
2128
 
1886
2144
        Tolerance parameter.
1887
2145
    atol : float, optional
1888
2146
        Tolerance parameter (1e-8).
1889
 
    copy : {True, False}, optional
 
2147
    copy : bool, optional
1890
2148
        Whether to return a copy of `x`.
1891
 
    shrink : {True, False}, optional
1892
 
        Whether to collapse a mask full of False to ``nomask``
 
2149
    shrink : bool, optional
 
2150
        Whether to collapse a mask full of False to ``nomask``.
1893
2151
 
1894
2152
    Returns
1895
2153
    -------
1936
2194
    mabs = umath.absolute
1937
2195
    xnew = filled(x, value)
1938
2196
    if issubclass(xnew.dtype.type, np.floating):
1939
 
        condition = umath.less_equal(mabs(xnew-value), atol + rtol*mabs(value))
 
2197
        condition = umath.less_equal(mabs(xnew - value), atol + rtol * mabs(value))
1940
2198
        mask = getattr(x, '_mask', nomask)
1941
2199
    else:
1942
2200
        condition = umath.equal(xnew, value)
1973
2231
 
1974
2232
    """
1975
2233
    a = np.array(a, copy=copy, subok=True)
1976
 
    condition = ~(np.isfinite(a))
1977
 
    if hasattr(a, '_mask'):
1978
 
        condition = mask_or(condition, a._mask)
 
2234
    mask = getattr(a, '_mask', None)
 
2235
    if mask is not None:
 
2236
        condition = ~(np.isfinite(getdata(a)))
 
2237
        if mask is not nomask:
 
2238
            condition |= mask
1979
2239
        cls = type(a)
1980
2240
    else:
 
2241
        condition = ~(np.isfinite(a))
1981
2242
        cls = MaskedArray
1982
2243
    result = a.view(cls)
1983
2244
    result._mask = condition
2037
2298
            np.putmask(curdata, curmask, printopt)
2038
2299
    return
2039
2300
 
2040
 
_print_templates = dict(long = """\
 
2301
_print_templates = dict(long="""\
2041
2302
masked_%(name)s(data =
2042
2303
 %(data)s,
2043
2304
       %(nlen)s mask =
2044
2305
 %(mask)s,
2045
2306
 %(nlen)s fill_value = %(fill)s)
2046
2307
""",
2047
 
                        short = """\
 
2308
                        short="""\
2048
2309
masked_%(name)s(data = %(data)s,
2049
2310
       %(nlen)s mask = %(mask)s,
2050
2311
%(nlen)s  fill_value = %(fill)s)
2051
2312
""",
2052
 
                        long_flx = """\
 
2313
                        long_flx="""\
2053
2314
masked_%(name)s(data =
2054
2315
 %(data)s,
2055
2316
       %(nlen)s mask =
2057
2318
%(nlen)s  fill_value = %(fill)s,
2058
2319
      %(nlen)s dtype = %(dtype)s)
2059
2320
""",
2060
 
                        short_flx = """\
 
2321
                        short_flx="""\
2061
2322
masked_%(name)s(data = %(data)s,
2062
2323
%(nlen)s        mask = %(mask)s,
2063
2324
%(nlen)s  fill_value = %(fill)s,
2086
2347
    """
2087
2348
    Define a wrapper for basic array methods.
2088
2349
 
2089
 
    Upon call, returns a masked array, where the new _data array is
 
2350
    Upon call, returns a masked array, where the new ``_data`` array is
2090
2351
    the output of the corresponding method called on the original
2091
 
    _data.
 
2352
    ``_data``.
2092
2353
 
2093
 
    If onmask is True, the new mask is the output of the method called
 
2354
    If `onmask` is True, the new mask is the output of the method called
2094
2355
    on the initial mask. Otherwise, the new mask is just a reference
2095
2356
    to the initial mask.
2096
2357
 
 
2358
    Attributes
 
2359
    ----------
 
2360
    _onmask : bool
 
2361
        Holds the `onmask` parameter.
 
2362
    obj : object
 
2363
        The object calling `_arraymethod`.
 
2364
 
2097
2365
    Parameters
2098
2366
    ----------
2099
 
    _name : String
 
2367
    funcname : str
2100
2368
        Name of the function to apply on data.
2101
 
    _onmask : bool
 
2369
    onmask : bool
2102
2370
        Whether the mask must be processed also (True) or left
2103
 
        alone (False). Default: True.
2104
 
    obj : Object
2105
 
        The object calling the arraymethod.
 
2371
        alone (False). Default is True. Make available as `_onmask`
 
2372
        attribute.
2106
2373
 
2107
2374
    """
2108
2375
    def __init__(self, funcname, onmask=True):
2124
2391
    #
2125
2392
    def __call__(self, *args, **params):
2126
2393
        methodname = self.__name__
2127
 
        data = self.obj._data
2128
 
        mask = self.obj._mask
2129
 
        cls = type(self.obj)
 
2394
        instance = self.obj
 
2395
        # Fallback : if the instance has not been initialized, use the first arg
 
2396
        if instance is None:
 
2397
            args = list(args)
 
2398
            instance = args.pop(0)
 
2399
        data = instance._data
 
2400
        mask = instance._mask
 
2401
        cls = type(instance)
2130
2402
        result = getattr(data, methodname)(*args, **params).view(cls)
2131
 
        result._update_from(self.obj)
 
2403
        result._update_from(instance)
2132
2404
        if result.ndim:
2133
2405
            if not self._onmask:
2134
2406
                result.__setmask__(mask)
2141
2413
#..........................................................
2142
2414
 
2143
2415
class MaskedIterator(object):
2144
 
    "Define an interator."
 
2416
    """
 
2417
    Flat iterator object to iterate over masked arrays.
 
2418
 
 
2419
    A `MaskedIterator` iterator is returned by ``x.flat`` for any masked array
 
2420
    `x`. It allows iterating over the array as if it were a 1-D array,
 
2421
    either in a for-loop or by calling its `next` method.
 
2422
 
 
2423
    Iteration is done in C-contiguous style, with the last index varying the
 
2424
    fastest. The iterator can also be indexed using basic slicing or
 
2425
    advanced indexing.
 
2426
 
 
2427
    See Also
 
2428
    --------
 
2429
    MaskedArray.flat : Return a flat iterator over an array.
 
2430
    MaskedArray.flatten : Returns a flattened copy of an array.
 
2431
 
 
2432
    Notes
 
2433
    -----
 
2434
    `MaskedIterator` is not exported by the `ma` module. Instead of
 
2435
    instantiating a `MaskedIterator` directly, use `MaskedArray.flat`.
 
2436
 
 
2437
    Examples
 
2438
    --------
 
2439
    >>> x = np.ma.array(arange(6).reshape(2, 3))
 
2440
    >>> fl = x.flat
 
2441
    >>> type(fl)
 
2442
    <class 'numpy.ma.core.MaskedIterator'>
 
2443
    >>> for item in fl:
 
2444
    ...     print item
 
2445
    ...
 
2446
    0
 
2447
    1
 
2448
    2
 
2449
    3
 
2450
    4
 
2451
    5
 
2452
 
 
2453
    Extracting more than a single element b indexing the `MaskedIterator`
 
2454
    returns a masked array:
 
2455
 
 
2456
    >>> fl[2:4]
 
2457
    masked_array(data = [2 3],
 
2458
                 mask = False,
 
2459
           fill_value = 999999)
 
2460
 
 
2461
    """
2145
2462
    def __init__(self, ma):
2146
2463
        self.ma = ma
2147
2464
        self.dataiter = ma._data.flat
2170
2487
#        self.ma1d[index] = value
2171
2488
 
2172
2489
    def next(self):
2173
 
        "Returns the next element of the iterator."
 
2490
        """
 
2491
        Return the next value, or raise StopIteration.
 
2492
 
 
2493
        Examples
 
2494
        --------
 
2495
        >>> x = np.ma.array([3, 2], mask=[0, 1])
 
2496
        >>> fl = x.flat
 
2497
        >>> fl.next()
 
2498
        3
 
2499
        >>> fl.next()
 
2500
        masked_array(data = --,
 
2501
                     mask = True,
 
2502
               fill_value = 1e+20)
 
2503
        >>> fl.next()
 
2504
        Traceback (most recent call last):
 
2505
          File "<stdin>", line 1, in <module>
 
2506
          File "/home/ralf/python/numpy/numpy/ma/core.py", line 2243, in next
 
2507
            d = self.dataiter.next()
 
2508
        StopIteration
 
2509
 
 
2510
        """
2174
2511
        d = self.dataiter.next()
2175
2512
        if self.maskiter is not None and self.maskiter.next():
2176
2513
            d = masked
2179
2516
 
2180
2517
def flatten_structured_array(a):
2181
2518
    """
2182
 
    Flatten a strutured array.
2183
 
 
2184
 
    The datatype of the output is the largest datatype of the (nested) fields.
 
2519
    Flatten a structured array.
 
2520
 
 
2521
    The data type of the output is chosen such that it can represent all of the
 
2522
    (nested) fields.
 
2523
 
 
2524
    Parameters
 
2525
    ----------
 
2526
    a : structured array
2185
2527
 
2186
2528
    Returns
2187
2529
    -------
2188
 
    output : var
2189
 
        Flatten MaskedArray if the input is a MaskedArray,
2190
 
        standard ndarray otherwise.
 
2530
    output : masked array or ndarray
 
2531
        A flattened masked array if the input is a masked array, otherwise a
 
2532
        standard ndarray.
2191
2533
 
2192
2534
    Examples
2193
2535
    --------
2202
2544
    def flatten_sequence(iterable):
2203
2545
        """Flattens a compound of nested iterables."""
2204
2546
        for elm in iter(iterable):
2205
 
            if hasattr(elm,'__iter__'):
 
2547
            if hasattr(elm, '__iter__'):
2206
2548
                for f in flatten_sequence(elm):
2207
2549
                    yield f
2208
2550
            else:
2229
2571
 
2230
2572
class MaskedArray(ndarray):
2231
2573
    """
2232
 
    Arrays with possibly masked values.  Masked values of True
2233
 
    exclude the corresponding element from any computation.
2234
 
 
2235
 
    Construction:
2236
 
        x = MaskedArray(data, mask=nomask, dtype=None, copy=True,
2237
 
        fill_value=None, keep_mask=True, hard_mask=False, shrink=True)
 
2574
    An array class with possibly masked values.
 
2575
 
 
2576
    Masked values of True exclude the corresponding element from any
 
2577
    computation.
 
2578
 
 
2579
    Construction::
 
2580
 
 
2581
      x = MaskedArray(data, mask=nomask, dtype=None, copy=True,
 
2582
                      fill_value=None, keep_mask=True, hard_mask=False,
 
2583
                      shrink=True)
2238
2584
 
2239
2585
    Parameters
2240
2586
    ----------
2241
 
    data : {var}
 
2587
    data : array_like
2242
2588
        Input data.
2243
 
    mask : {nomask, sequence}, optional
2244
 
        Mask.  Must be convertible to an array of booleans with
2245
 
        the same shape as data: True indicates a masked (eg.,
2246
 
        invalid) data.
2247
 
    dtype : {dtype}, optional
 
2589
    mask : sequence, optional
 
2590
        Mask. Must be convertible to an array of booleans with the same
 
2591
        shape as `data`. True indicates a masked (i.e. invalid) data.
 
2592
    dtype : dtype, optional
2248
2593
        Data type of the output.
2249
 
        If dtype is None, the type of the data argument (`data.dtype`) is used.
2250
 
        If dtype is not None and different from `data.dtype`, a copy is performed.
2251
 
    copy : {False, True}, optional
 
2594
        If `dtype` is None, the type of the data argument (``data.dtype``)
 
2595
        is used. If `dtype` is not None and different from ``data.dtype``,
 
2596
        a copy is performed.
 
2597
    copy : bool, optional
2252
2598
        Whether to copy the input data (True), or to use a reference instead.
2253
 
        Note: data are NOT copied by default.
2254
 
    subok : {True, False}, optional
2255
 
        Whether to return a subclass of MaskedArray (if possible)
2256
 
        or a plain MaskedArray.
2257
 
    ndmin : {0, int}, optional
2258
 
        Minimum number of dimensions
2259
 
    fill_value : {var}, optional
 
2599
        Default is False.
 
2600
    subok : bool, optional
 
2601
        Whether to return a subclass of `MaskedArray` if possible (True) or a
 
2602
        plain `MaskedArray`. Default is True.
 
2603
    ndmin : int, optional
 
2604
        Minimum number of dimensions. Default is 0.
 
2605
    fill_value : scalar, optional
2260
2606
        Value used to fill in the masked values when necessary.
2261
 
        If None, a default based on the datatype is used.
2262
 
    keep_mask : {True, boolean}, optional
2263
 
        Whether to combine mask with the mask of the input data,
2264
 
        if any (True), or to use only mask for the output (False).
2265
 
    hard_mask : {False, boolean}, optional
2266
 
        Whether to use a hard mask or not.
2267
 
        With a hard mask, masked values cannot be unmasked.
2268
 
    shrink : {True, boolean}, optional
2269
 
        Whether to force compression of an empty mask.
 
2607
        If None, a default based on the data-type is used.
 
2608
    keep_mask : bool, optional
 
2609
        Whether to combine `mask` with the mask of the input data, if any
 
2610
        (True), or to use only `mask` for the output (False). Default is True.
 
2611
    hard_mask : bool, optional
 
2612
        Whether to use a hard mask or not. With a hard mask, masked values
 
2613
        cannot be unmasked. Default is False.
 
2614
    shrink : bool, optional
 
2615
        Whether to force compression of an empty mask. Default is True.
2270
2616
 
2271
2617
    """
2272
2618
 
2303
2649
        else:
2304
2650
            _data = ndarray.view(_data, type(data))
2305
2651
        # Backwards compatibility w/ numpy.core.ma .......
2306
 
        if hasattr(data,'_mask') and not isinstance(data, ndarray):
 
2652
        if hasattr(data, '_mask') and not isinstance(data, ndarray):
2307
2653
            _data._mask = data._mask
2308
2654
            _sharedmask = True
2309
2655
        # Process mask ...............................
2325
2671
                else:
2326
2672
                    _data._mask = np.zeros(_data.shape, dtype=mdtype)
2327
2673
            # Check whether we missed something
2328
 
            elif isinstance(data, (tuple,list)):
 
2674
            elif isinstance(data, (tuple, list)):
2329
2675
                try:
2330
2676
                    # If data is a sequence of masked array
2331
2677
                    mask = np.array([getmaskarray(m) for m in data],
2353
2699
                mask = np.array(mask, copy=copy, dtype=mdtype)
2354
2700
            # Or assume it's a sequence of bool/int
2355
2701
            except TypeError:
2356
 
                mask = np.array([tuple([m]*len(mdtype)) for m in mask],
 
2702
                mask = np.array([tuple([m] * len(mdtype)) for m in mask],
2357
2703
                                 dtype=mdtype)
2358
2704
            # Make sure the mask and the data have the same shape
2359
2705
            if mask.shape != _data.shape:
2363
2709
                elif nm == nd:
2364
2710
                    mask = np.reshape(mask, _data.shape)
2365
2711
                else:
2366
 
                    msg = "Mask and data not compatible: data size is %i, "+\
 
2712
                    msg = "Mask and data not compatible: data size is %i, " + \
2367
2713
                          "mask size is %i."
2368
2714
                    raise MaskError, msg % (nd, nm)
2369
2715
                copy = True
2421
2767
                     _hardmask=getattr(obj, '_hardmask', False),
2422
2768
                     _sharedmask=getattr(obj, '_sharedmask', False),
2423
2769
                     _isfield=getattr(obj, '_isfield', False),
2424
 
                     _baseclass=getattr(obj,'_baseclass', _baseclass),
 
2770
                     _baseclass=getattr(obj, '_baseclass', _baseclass),
2425
2771
                     _optinfo=_optinfo,
2426
2772
                     _basedict=_optinfo)
2427
2773
        self.__dict__.update(_dict)
2444
2790
        self._mask = _mask
2445
2791
        # Finalize the mask ...........
2446
2792
        if self._mask is not nomask:
2447
 
            self._mask.shape = self.shape
 
2793
            try:
 
2794
                self._mask.shape = self.shape
 
2795
            except ValueError:
 
2796
                self._mask = nomask
2448
2797
        return
2449
2798
    #..................................
2450
2799
    def __array_wrap__(self, obj, context=None):
2631
2980
        #........................................
2632
2981
#        ndgetattr = ndarray.__getattribute__
2633
2982
        _data = self._data
2634
 
        _dtype = ndarray.__getattribute__(_data,'dtype')
2635
 
        _mask = ndarray.__getattribute__(self,'_mask')
 
2983
        _dtype = ndarray.__getattribute__(_data, 'dtype')
 
2984
        _mask = ndarray.__getattribute__(self, '_mask')
2636
2985
        nbfields = len(_dtype.names or ())
2637
2986
        #........................................
2638
2987
        if value is masked:
2664
3013
            # Unshare the mask if necessary to avoid propagation
2665
3014
            if not self._isfield:
2666
3015
                self.unshare_mask()
2667
 
                _mask = ndarray.__getattribute__(self,'_mask')
 
3016
                _mask = ndarray.__getattribute__(self, '_mask')
2668
3017
            # Set the data, then the mask
2669
3018
            ndarray.__setitem__(_data, indx, dval)
2670
3019
            ndarray.__setitem__(_mask, indx, mval)
2671
 
        elif hasattr(indx, 'dtype') and (indx.dtype==MaskType):
 
3020
        elif hasattr(indx, 'dtype') and (indx.dtype == MaskType):
2672
3021
            indx = indx * umath.logical_not(_mask)
2673
3022
            ndarray.__setitem__(_data, indx, dval)
2674
3023
        else:
2710
3059
        """Set the mask.
2711
3060
 
2712
3061
        """
2713
 
        idtype = ndarray.__getattribute__(self,'dtype')
2714
 
        current_mask = ndarray.__getattribute__(self,'_mask')
 
3062
        idtype = ndarray.__getattribute__(self, 'dtype')
 
3063
        current_mask = ndarray.__getattribute__(self, '_mask')
2715
3064
        if mask is masked:
2716
3065
            mask = True
2717
3066
        # Make sure the mask is set
2748
3097
                    mask = np.array(mask, copy=copy, dtype=mdtype)
2749
3098
                # Or assume it's a sequence of bool/int
2750
3099
                except TypeError:
2751
 
                    mask = np.array([tuple([m]*len(mdtype)) for m in mask],
 
3100
                    mask = np.array([tuple([m] * len(mdtype)) for m in mask],
2752
3101
                                    dtype=mdtype)
2753
3102
            # Hardmask: don't unmask the data
2754
3103
            if self._hardmask:
2782
3131
        _mask = ndarray.__getattribute__(self, '_mask').view(ndarray)
2783
3132
        if _mask.dtype.names is None:
2784
3133
            return _mask
2785
 
        return np.all(flatten_structured_array(_mask), axis=-1)
 
3134
        return np.all(flatten_structured_array(_mask), axis= -1)
2786
3135
 
2787
3136
 
2788
3137
    def _set_recordmask(self):
2795
3144
 
2796
3145
    #............................................
2797
3146
    def harden_mask(self):
2798
 
        """Force the mask to hard.
 
3147
        """
 
3148
        Force the mask to hard.
 
3149
 
 
3150
        Whether the mask of a masked array is hard or soft is determined by
 
3151
        its `hardmask` property. `harden_mask` sets `hardmask` to True.
 
3152
 
 
3153
        See Also
 
3154
        --------
 
3155
        hardmask
2799
3156
 
2800
3157
        """
2801
3158
        self._hardmask = True
 
3159
        return self
2802
3160
 
2803
3161
    def soften_mask(self):
2804
 
        """Force the mask to soft.
 
3162
        """
 
3163
        Force the mask to soft.
 
3164
 
 
3165
        Whether the mask of a masked array is hard or soft is determined by
 
3166
        its `hardmask` property. `soften_mask` sets `hardmask` to False.
 
3167
 
 
3168
        See Also
 
3169
        --------
 
3170
        hardmask
2805
3171
 
2806
3172
        """
2807
3173
        self._hardmask = False
 
3174
        return self
2808
3175
 
2809
3176
    hardmask = property(fget=lambda self: self._hardmask,
2810
3177
                        doc="Hardness of the mask")
2811
3178
 
2812
3179
 
2813
3180
    def unshare_mask(self):
2814
 
        """Copy the mask and set the sharedmask flag to False.
 
3181
        """
 
3182
        Copy the mask and set the sharedmask flag to False.
 
3183
 
 
3184
        Whether the mask is shared between masked arrays can be seen from
 
3185
        the `sharedmask` property. `unshare_mask` ensures the mask is not shared.
 
3186
        A copy of the mask is only made if it was shared.
 
3187
 
 
3188
        See Also
 
3189
        --------
 
3190
        sharedmask
2815
3191
 
2816
3192
        """
2817
3193
        if self._sharedmask:
2818
3194
            self._mask = self._mask.copy()
2819
3195
            self._sharedmask = False
 
3196
        return self
2820
3197
 
2821
3198
    sharedmask = property(fget=lambda self: self._sharedmask,
2822
3199
                          doc="Share status of the mask (read-only).")
2823
3200
 
2824
3201
    def shrink_mask(self):
2825
 
        """Reduce a mask to nomask when possible.
 
3202
        """
 
3203
        Reduce a mask to nomask when possible.
 
3204
 
 
3205
        Parameters
 
3206
        ----------
 
3207
        None
 
3208
 
 
3209
        Returns
 
3210
        -------
 
3211
        None
 
3212
 
 
3213
        Examples
 
3214
        --------
 
3215
        >>> x = np.ma.array([[1,2 ], [3, 4]], mask=[0]*4)
 
3216
        >>> x.mask
 
3217
        array([[False, False],
 
3218
               [False, False]], dtype=bool)
 
3219
        >>> x.shrink_mask()
 
3220
        >>> x.mask
 
3221
        False
2826
3222
 
2827
3223
        """
2828
3224
        m = self._mask
2829
3225
        if m.ndim and not m.any():
2830
3226
            self._mask = nomask
 
3227
        return self
2831
3228
 
2832
3229
    #............................................
2833
3230
 
2834
 
    baseclass = property(fget= lambda self:self._baseclass,
 
3231
    baseclass = property(fget=lambda self:self._baseclass,
2835
3232
                         doc="Class of the underlying data (read-only).")
2836
 
    
 
3233
 
2837
3234
    def _get_data(self):
2838
3235
        """Return the current data, as a view of the original
2839
3236
        underlying data.
2844
3241
    data = property(fget=_get_data)
2845
3242
 
2846
3243
    def raw_data(self):
2847
 
        """Return the _data part of the MaskedArray.
2848
 
 
2849
 
        DEPRECATED: You should really use ``.data`` instead...
 
3244
        """
 
3245
        Return the data part of the masked array.
 
3246
 
 
3247
        DEPRECATED: You should really use ``.data`` instead.
 
3248
 
 
3249
        Examples
 
3250
        --------
 
3251
        >>> x = np.ma.array([1, 2, 3], mask=[False, True, False])
 
3252
        >>> x
 
3253
        masked_array(data = [1 -- 3],
 
3254
                     mask = [False  True False],
 
3255
               fill_value = 999999)
 
3256
        >>> x.data
 
3257
        array([1, 2, 3])
2850
3258
 
2851
3259
        """
2852
3260
        warnings.warn('Use .data instead.', DeprecationWarning)
2869
3277
                    doc="Flat version of the array.")
2870
3278
    #............................................
2871
3279
    def get_fill_value(self):
2872
 
        """Return the filling value.
 
3280
        """
 
3281
        Return the filling value of the masked array.
 
3282
 
 
3283
        Returns
 
3284
        -------
 
3285
        fill_value : scalar
 
3286
            The filling value.
 
3287
 
 
3288
        Examples
 
3289
        --------
 
3290
        >>> for dt in [np.int32, np.int64, np.float64, np.complex128]:
 
3291
        ...     np.ma.array([0, 1], dtype=dt).get_fill_value()
 
3292
        ...
 
3293
        999999
 
3294
        999999
 
3295
        1e+20
 
3296
        (1e+20+0j)
 
3297
 
 
3298
        >>> x = np.ma.array([0, 1.], fill_value=-np.inf)
 
3299
        >>> x.get_fill_value()
 
3300
        -inf
2873
3301
 
2874
3302
        """
2875
3303
        if self._fill_value is None:
2877
3305
        return self._fill_value
2878
3306
 
2879
3307
    def set_fill_value(self, value=None):
2880
 
        """Set the filling value to value.
2881
 
 
2882
 
        If value is None, use a default based on the data type.
 
3308
        """
 
3309
        Set the filling value of the masked array.
 
3310
 
 
3311
        Parameters
 
3312
        ----------
 
3313
        value : scalar, optional
 
3314
            The new filling value. Default is None, in which case a default
 
3315
            based on the data type is used.
 
3316
 
 
3317
        See Also
 
3318
        --------
 
3319
        ma.set_fill_value : Equivalent function.
 
3320
 
 
3321
        Examples
 
3322
        --------
 
3323
        >>> x = np.ma.array([0, 1.], fill_value=-np.inf)
 
3324
        >>> x.fill_value
 
3325
        -inf
 
3326
        >>> x.set_fill_value(np.pi)
 
3327
        >>> x.fill_value
 
3328
        3.1415926535897931
 
3329
 
 
3330
        Reset to default:
 
3331
 
 
3332
        >>> x.set_fill_value()
 
3333
        >>> x.fill_value
 
3334
        1e+20
2883
3335
 
2884
3336
        """
2885
3337
        self._fill_value = _check_fill_value(value, self.dtype)
2890
3342
 
2891
3343
    def filled(self, fill_value=None):
2892
3344
        """
2893
 
    Return a copy of self, where masked values are filled with `fill_value`.
2894
 
 
2895
 
    If `fill_value` is None, `self.fill_value` is used instead.
2896
 
 
2897
 
    Notes
2898
 
    -----
2899
 
    + Subclassing is preserved
2900
 
    + The result is NOT a MaskedArray !
2901
 
 
2902
 
    Examples
2903
 
    --------
2904
 
    >>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999)
2905
 
    >>> x.filled()
2906
 
    array([1,2,-999,4,-999])
2907
 
    >>> type(x.filled())
2908
 
    <type 'numpy.ndarray'>
 
3345
        Return a copy of self, where masked values are filled with a fill value.
 
3346
 
 
3347
        If `fill_value` is None, `MaskedArray.fill_value` is used instead.
 
3348
 
 
3349
        Parameters
 
3350
        ----------
 
3351
        fill_value : scalar, optional
 
3352
            The value to use for invalid entries. Default is None.
 
3353
 
 
3354
        Notes
 
3355
        -----
 
3356
        The result is **not** a MaskedArray!
 
3357
 
 
3358
        Examples
 
3359
        --------
 
3360
        >>> x = np.ma.array([1,2,3,4,5], mask=[0,0,1,0,1], fill_value=-999)
 
3361
        >>> x.filled()
 
3362
        array([1, 2, -999, 4, -999])
 
3363
        >>> type(x.filled())
 
3364
        <type 'numpy.ndarray'>
 
3365
 
 
3366
        Subclassing is preserved. This means that if the data part of the masked
 
3367
        array is a matrix, `filled` returns a matrix:
 
3368
 
 
3369
        >>> x = np.ma.array(np.matrix([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
 
3370
        >>> x.filled()
 
3371
        matrix([[     1, 999999],
 
3372
                [999999,      4]])
2909
3373
 
2910
3374
        """
2911
3375
        m = self._mask
2945
3409
 
2946
3410
    def compressed(self):
2947
3411
        """
2948
 
        Return a 1-D array of all the non-masked data.
 
3412
        Return all the non-masked data as a 1-D array.
2949
3413
 
2950
3414
        Returns
2951
3415
        -------
2952
 
        data : ndarray.
2953
 
            A new ndarray holding the non-masked data is returned.
 
3416
        data : ndarray
 
3417
            A new `ndarray` holding the non-masked data is returned.
2954
3418
 
2955
3419
        Notes
2956
3420
        -----
2957
 
        + The result is NOT a MaskedArray !
 
3421
        The result is **not** a MaskedArray!
2958
3422
 
2959
3423
        Examples
2960
3424
        --------
2961
 
        >>> x = array(arange(5), mask=[0]+[1]*4)
2962
 
        >>> print x.compressed()
2963
 
        [0]
2964
 
        >>> print type(x.compressed())
 
3425
        >>> x = np.ma.array(np.arange(5), mask=[0]*2 + [1]*3)
 
3426
        >>> x.compressed()
 
3427
        array([0, 1])
 
3428
        >>> type(x.compressed())
2965
3429
        <type 'numpy.ndarray'>
2966
3430
 
2967
3431
        """
3082
3546
        """
3083
3547
        n = len(self.shape)
3084
3548
        name = repr(self._data).split('(')[0]
3085
 
        parameters =  dict(name=name, nlen=" "*len(name),
 
3549
        parameters = dict(name=name, nlen=" " * len(name),
3086
3550
                           data=str(self), mask=str(self._mask),
3087
3551
                           fill=str(self.fill_value), dtype=str(self.dtype))
3088
3552
        if self.dtype.names:
3095
3559
    #............................................
3096
3560
    def __eq__(self, other):
3097
3561
        "Check whether other equals self elementwise"
 
3562
        if self is masked:
 
3563
            return masked
3098
3564
        omask = getattr(other, '_mask', nomask)
3099
3565
        if omask is nomask:
3100
3566
            check = ndarray.__eq__(self.filled(0), other).view(type(self))
3114
3580
                    try:
3115
3581
                        mask = mask.view((bool_, len(self.dtype))).all(axis)
3116
3582
                    except ValueError:
3117
 
                        mask =  np.all([[f[n].all() for n in mask.dtype.names]
 
3583
                        mask = np.all([[f[n].all() for n in mask.dtype.names]
3118
3584
                                        for f in mask], axis=axis)
3119
3585
                check._mask = mask
3120
3586
        return check
3121
3587
    #
3122
3588
    def __ne__(self, other):
3123
3589
        "Check whether other doesn't equal self elementwise"
 
3590
        if self is masked:
 
3591
            return masked
3124
3592
        omask = getattr(other, '_mask', nomask)
3125
3593
        if omask is nomask:
3126
3594
            check = ndarray.__ne__(self.filled(0), other).view(type(self))
3140
3608
                    try:
3141
3609
                        mask = mask.view((bool_, len(self.dtype))).all(axis)
3142
3610
                    except ValueError:
3143
 
                        mask =  np.all([[f[n].all() for n in mask.dtype.names]
 
3611
                        mask = np.all([[f[n].all() for n in mask.dtype.names]
3144
3612
                                        for f in mask], axis=axis)
3145
3613
                check._mask = mask
3146
3614
        return check
3273
3741
        return int(self.item())
3274
3742
    #............................................
3275
3743
    def get_imag(self):
3276
 
        "Returns the imaginary part."
 
3744
        """
 
3745
        Return the imaginary part of the masked array.
 
3746
 
 
3747
        The returned array is a view on the imaginary part of the `MaskedArray`
 
3748
        whose `get_imag` method is called.
 
3749
 
 
3750
        Parameters
 
3751
        ----------
 
3752
        None
 
3753
 
 
3754
        Returns
 
3755
        -------
 
3756
        result : MaskedArray
 
3757
            The imaginary part of the masked array.
 
3758
 
 
3759
        See Also
 
3760
        --------
 
3761
        get_real, real, imag
 
3762
 
 
3763
        Examples
 
3764
        --------
 
3765
        >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
 
3766
        >>> x.get_imag()
 
3767
        masked_array(data = [1.0 -- 1.6],
 
3768
                     mask = [False  True False],
 
3769
               fill_value = 1e+20)
 
3770
 
 
3771
        """
3277
3772
        result = self._data.imag.view(type(self))
3278
3773
        result.__setmask__(self._mask)
3279
3774
        return result
3280
3775
    imag = property(fget=get_imag, doc="Imaginary part.")
3281
3776
 
3282
3777
    def get_real(self):
3283
 
        "Returns the real part."
 
3778
        """
 
3779
        Return the real part of the masked array.
 
3780
 
 
3781
        The returned array is a view on the real part of the `MaskedArray`
 
3782
        whose `get_real` method is called.
 
3783
 
 
3784
        Parameters
 
3785
        ----------
 
3786
        None
 
3787
 
 
3788
        Returns
 
3789
        -------
 
3790
        result : MaskedArray
 
3791
            The real part of the masked array.
 
3792
 
 
3793
        See Also
 
3794
        --------
 
3795
        get_imag, real, imag
 
3796
 
 
3797
        Examples
 
3798
        --------
 
3799
        >>> x = np.ma.array([1+1.j, -2j, 3.45+1.6j], mask=[False, True, False])
 
3800
        >>> x.get_real()
 
3801
        masked_array(data = [1.0 -- 3.45],
 
3802
                     mask = [False  True False],
 
3803
               fill_value = 1e+20)
 
3804
 
 
3805
        """
3284
3806
        result = self._data.real.view(type(self))
3285
3807
        result.__setmask__(self._mask)
3286
3808
        return result
3295
3817
        Parameters
3296
3818
        ----------
3297
3819
        axis : int, optional
3298
 
            Axis along which to count the non-masked elements. If axis is None,
3299
 
            all the non masked elements are counted.
 
3820
            Axis along which to count the non-masked elements. If `axis` is
 
3821
            `None`, all non-masked elements are counted.
3300
3822
 
3301
3823
        Returns
3302
3824
        -------
3303
 
        result : MaskedArray
3304
 
            A masked array where the mask is True where all data are
3305
 
            masked.  If axis is None, returns either a scalar ot the
3306
 
            masked singleton if all values are masked.
 
3825
        result : int or ndarray
 
3826
            If `axis` is `None`, an integer count is returned. When `axis` is
 
3827
            not `None`, an array with shape determined by the lengths of the
 
3828
            remaining axes, is returned.
 
3829
 
 
3830
        See Also
 
3831
        --------
 
3832
        count_masked : Count masked elements in array or along a given axis.
 
3833
 
 
3834
        Examples
 
3835
        --------
 
3836
        >>> import numpy.ma as ma
 
3837
        >>> a = ma.arange(6).reshape((2, 3))
 
3838
        >>> a[1, :] = ma.masked
 
3839
        >>> a
 
3840
        masked_array(data =
 
3841
         [[0 1 2]
 
3842
         [-- -- --]],
 
3843
                     mask =
 
3844
         [[False False False]
 
3845
         [ True  True  True]],
 
3846
               fill_value = 999999)
 
3847
        >>> a.count()
 
3848
        3
 
3849
 
 
3850
        When the `axis` keyword is specified an array of appropriate size is
 
3851
        returned.
 
3852
 
 
3853
        >>> a.count(axis=0)
 
3854
        array([1, 1, 1])
 
3855
        >>> a.count(axis=1)
 
3856
        array([3, 0])
3307
3857
 
3308
3858
        """
3309
3859
        m = self._mask
3324
3874
        n1 = np.size(m, axis)
3325
3875
        n2 = m.astype(int).sum(axis)
3326
3876
        if axis is None:
3327
 
            return (n1-n2)
 
3877
            return (n1 - n2)
3328
3878
        else:
3329
3879
            return narray(n1 - n2)
3330
3880
    #............................................
3363
3913
    #
3364
3914
    def reshape (self, *s, **kwargs):
3365
3915
        """
3366
 
        Returns a masked array containing the data of a, but with a new shape.
3367
 
        The result is a view to the original array; if this is not possible,
3368
 
        a ValueError is raised.
 
3916
        Give a new shape to the array without changing its data.
 
3917
 
 
3918
        Returns a masked array containing the same data, but with a new shape.
 
3919
        The result is a view on the original array; if this is not possible, a
 
3920
        ValueError is raised.
3369
3921
 
3370
3922
        Parameters
3371
3923
        ----------
3372
 
        shape : shape tuple or int
3373
 
           The new shape should be compatible with the original shape. If an
3374
 
           integer, then the result will be a 1D array of that length.
 
3924
        shape : int or tuple of ints
 
3925
            The new shape should be compatible with the original shape. If an
 
3926
            integer is supplied, then the result will be a 1-D array of that
 
3927
            length.
3375
3928
        order : {'C', 'F'}, optional
3376
3929
            Determines whether the array data should be viewed as in C
3377
 
            (row-major) order or FORTRAN (column-major) order.
 
3930
            (row-major) or FORTRAN (column-major) order.
3378
3931
 
3379
3932
        Returns
3380
3933
        -------
3381
3934
        reshaped_array : array
3382
 
            A new view to the array.
 
3935
            A new view on the array.
 
3936
 
 
3937
        See Also
 
3938
        --------
 
3939
        reshape : Equivalent function in the masked array module.
 
3940
        numpy.ndarray.reshape : Equivalent method on ndarray object.
 
3941
        numpy.reshape : Equivalent function in the NumPy module.
3383
3942
 
3384
3943
        Notes
3385
3944
        -----
3386
 
        If you want to modify the shape in place, please use ``a.shape = s``
 
3945
        The reshaping operation cannot guarantee that a copy will not be made,
 
3946
        to modify the shape in place, use ``a.shape = s``
3387
3947
 
3388
3948
        Examples
3389
3949
        --------
3399
3959
         [--]]
3400
3960
 
3401
3961
        """
3402
 
        kwargs.update(order=kwargs.get('order','C'))
 
3962
        kwargs.update(order=kwargs.get('order', 'C'))
3403
3963
        result = self._data.reshape(*s, **kwargs).view(type(self))
3404
3964
        result._update_from(self)
3405
3965
        mask = self._mask
3409
3969
    #
3410
3970
    def resize(self, newshape, refcheck=True, order=False):
3411
3971
        """
3412
 
    Change shape and size of array in-place.
 
3972
        .. warning::
 
3973
 
 
3974
            This method does nothing, except raise a ValueError exception. A
 
3975
            masked array does not own its data and therefore cannot safely be
 
3976
            resized in place. Use the `numpy.ma.resize` function instead.
 
3977
 
 
3978
        This method is difficult to implement safely and may be deprecated in
 
3979
        future releases of NumPy.
3413
3980
 
3414
3981
        """
3415
3982
        # Note : the 'order' keyword looks broken, let's just drop it
3496
4063
        self._mask = m
3497
4064
    #............................................
3498
4065
    def ids (self):
3499
 
        """Return the addresses of the data and mask areas."""
 
4066
        """
 
4067
        Return the addresses of the data and mask areas.
 
4068
 
 
4069
        Parameters
 
4070
        ----------
 
4071
        None
 
4072
 
 
4073
        Examples
 
4074
        --------
 
4075
        >>> x = np.ma.array([1, 2, 3], mask=[0, 1, 1])
 
4076
        >>> x.ids()
 
4077
        (166670640, 166659832)
 
4078
 
 
4079
        If the array has no mask, the address of `nomask` is returned. This address
 
4080
        is typically not close to the data in memory:
 
4081
 
 
4082
        >>> x = np.ma.array([1, 2, 3])
 
4083
        >>> x.ids()
 
4084
        (166691080, 3083169284L)
 
4085
 
 
4086
        """
3500
4087
        if self._mask is nomask:
3501
4088
            return (self.ctypes.data, id(nomask))
3502
4089
        return (self.ctypes.data, self._mask.ctypes.data)
3503
4090
 
3504
4091
    def iscontiguous(self):
3505
 
        "Is the data contiguous?"
 
4092
        """
 
4093
        Return a boolean indicating whether the data is contiguous.
 
4094
 
 
4095
        Parameters
 
4096
        ----------
 
4097
        None
 
4098
 
 
4099
        Examples
 
4100
        --------
 
4101
        >>> x = np.ma.array([1, 2, 3])
 
4102
        >>> x.iscontiguous()
 
4103
        True
 
4104
 
 
4105
        `iscontiguous` returns one of the flags of the masked array:
 
4106
 
 
4107
        >>> x.flags
 
4108
          C_CONTIGUOUS : True
 
4109
          F_CONTIGUOUS : True
 
4110
          OWNDATA : False
 
4111
          WRITEABLE : True
 
4112
          ALIGNED : True
 
4113
          UPDATEIFCOPY : False
 
4114
 
 
4115
        """
3506
4116
        return self.flags['CONTIGUOUS']
3507
4117
 
3508
4118
    #............................................
3538
4148
    True
3539
4149
 
3540
4150
        """
3541
 
        mask = self._mask.all(axis)
 
4151
        mask = _check_mask_axis(self._mask, axis)
3542
4152
        if out is None:
3543
4153
            d = self.filled(True).all(axis=axis).view(type(self))
3544
4154
            if d.ndim:
3574
4184
        any : equivalent function
3575
4185
 
3576
4186
        """
3577
 
        mask = self._mask.all(axis)
 
4187
        mask = _check_mask_axis(self._mask, axis)
3578
4188
        if out is None:
3579
4189
            d = self.filled(False).any(axis=axis).view(type(self))
3580
4190
            if d.ndim:
3591
4201
 
3592
4202
    def nonzero(self):
3593
4203
        """
3594
 
    Return the indices of the elements of a that are not zero
3595
 
    nor masked, as a tuple of arrays.
3596
 
 
3597
 
    There are as many tuples as dimensions of a, each tuple
3598
 
    contains the indices of the non-zero elements in that
3599
 
    dimension.  The corresponding non-zero values can be obtained
3600
 
    with ``a[a.nonzero()]``.
3601
 
 
3602
 
    To group the indices by element, rather than dimension, use
3603
 
    instead: ``transpose(a.nonzero())``.
3604
 
 
3605
 
    The result of this is always a 2d array, with a row for each
3606
 
    non-zero element.
 
4204
        Return the indices of unmasked elements that are not zero.
 
4205
 
 
4206
        Returns a tuple of arrays, one for each dimension, containing the
 
4207
        indices of the non-zero elements in that dimension. The corresponding
 
4208
        non-zero values can be obtained with::
 
4209
 
 
4210
            a[a.nonzero()]
 
4211
 
 
4212
        To group the indices by element, rather than dimension, use
 
4213
        instead::
 
4214
 
 
4215
            np.transpose(a.nonzero())
 
4216
 
 
4217
        The result of this is always a 2d array, with a row for each non-zero
 
4218
        element.
 
4219
 
 
4220
        Parameters
 
4221
        ----------
 
4222
        None
 
4223
 
 
4224
        Returns
 
4225
        -------
 
4226
        tuple_of_arrays : tuple
 
4227
            Indices of elements that are non-zero.
 
4228
 
 
4229
        See Also
 
4230
        --------
 
4231
        numpy.nonzero :
 
4232
            Function operating on ndarrays.
 
4233
        flatnonzero :
 
4234
            Return indices that are non-zero in the flattened version of the input
 
4235
            array.
 
4236
        ndarray.nonzero :
 
4237
            Equivalent ndarray method.
 
4238
 
 
4239
        Examples
 
4240
        --------
 
4241
        >>> import numpy.ma as ma
 
4242
        >>> x = ma.array(np.eye(3))
 
4243
        >>> x
 
4244
        masked_array(data =
 
4245
         [[ 1.  0.  0.]
 
4246
         [ 0.  1.  0.]
 
4247
         [ 0.  0.  1.]],
 
4248
              mask =
 
4249
         False,
 
4250
              fill_value=1e+20)
 
4251
        >>> x.nonzero()
 
4252
        (array([0, 1, 2]), array([0, 1, 2]))
 
4253
 
 
4254
        Masked elements are ignored.
 
4255
 
 
4256
        >>> x[1, 1] = ma.masked
 
4257
        >>> x
 
4258
        masked_array(data =
 
4259
         [[1.0 0.0 0.0]
 
4260
         [0.0 -- 0.0]
 
4261
         [0.0 0.0 1.0]],
 
4262
              mask =
 
4263
         [[False False False]
 
4264
         [False  True False]
 
4265
         [False False False]],
 
4266
              fill_value=1e+20)
 
4267
        >>> x.nonzero()
 
4268
        (array([0, 2]), array([0, 2]))
 
4269
 
 
4270
        Indices can also be grouped by element.
 
4271
 
 
4272
        >>> np.transpose(x.nonzero())
 
4273
        array([[0, 0],
 
4274
               [2, 2]])
 
4275
 
 
4276
        A common use for ``nonzero`` is to find the indices of an array, where
 
4277
        a condition is True.  Given an array `a`, the condition `a` > 3 is a
 
4278
        boolean array and since False is interpreted as 0, ma.nonzero(a > 3)
 
4279
        yields the indices of the `a` where the condition is true.
 
4280
 
 
4281
        >>> a = ma.array([[1,2,3],[4,5,6],[7,8,9]])
 
4282
        >>> a > 3
 
4283
        masked_array(data =
 
4284
         [[False False False]
 
4285
         [ True  True  True]
 
4286
         [ True  True  True]],
 
4287
              mask =
 
4288
         False,
 
4289
              fill_value=999999)
 
4290
        >>> ma.nonzero(a > 3)
 
4291
        (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
 
4292
 
 
4293
        The ``nonzero`` method of the condition array can also be called.
 
4294
 
 
4295
        >>> (a > 3).nonzero()
 
4296
        (array([1, 1, 1, 2, 2, 2]), array([0, 1, 2, 0, 1, 2]))
3607
4297
 
3608
4298
        """
3609
4299
        return narray(self.filled(0), copy=False).nonzero()
3671
4361
 
3672
4362
        """
3673
4363
        _mask = ndarray.__getattribute__(self, '_mask')
3674
 
        newmask = _mask.all(axis=axis)
 
4364
        newmask = _check_mask_axis(_mask, axis)
3675
4365
        # No explicit output
3676
4366
        if out is None:
3677
 
            result = self.filled(0).sum(axis, dtype=dtype).view(type(self))
3678
 
            if result.ndim:
 
4367
            result = self.filled(0).sum(axis, dtype=dtype)
 
4368
            rndim = getattr(result, 'ndim', 0)
 
4369
            if rndim:
 
4370
                result = result.view(type(self))
3679
4371
                result.__setmask__(newmask)
3680
4372
            elif newmask:
3681
4373
                result = masked
3692
4384
 
3693
4385
    def cumsum(self, axis=None, dtype=None, out=None):
3694
4386
        """
3695
 
    Return the cumulative sum of the elements along the given axis.
3696
 
    The cumulative sum is calculated over the flattened array by
3697
 
    default, otherwise over the specified axis.
3698
 
 
3699
 
    Masked values are set to 0 internally during the computation.
3700
 
    However, their position is saved, and the result will be masked at
3701
 
    the same locations.
3702
 
 
3703
 
    Parameters
3704
 
    ----------
3705
 
    axis : {None, -1, int}, optional
3706
 
        Axis along which the sum is computed. The default (`axis` = None) is to
3707
 
        compute over the flattened array. `axis` may be negative, in which case
3708
 
        it counts from the   last to the first axis.
3709
 
    dtype : {None, dtype}, optional
3710
 
        Type of the returned array and of the accumulator in which the
3711
 
        elements are summed.  If `dtype` is not specified, it defaults
3712
 
        to the dtype of `a`, unless `a` has an integer dtype with a
3713
 
        precision less than that of the default platform integer.  In
3714
 
        that case, the default platform integer is used.
3715
 
    out : ndarray, optional
3716
 
        Alternative output array in which to place the result. It must
3717
 
        have the same shape and buffer length as the expected output
3718
 
        but the type will be cast if necessary.
3719
 
 
3720
 
    Warnings
3721
 
    --------
3722
 
    The mask is lost if out is not a valid :class:`MaskedArray` !
3723
 
 
3724
 
    Returns
3725
 
    -------
3726
 
    cumsum : ndarray.
3727
 
        A new array holding the result is returned unless ``out`` is
3728
 
        specified, in which case a reference to ``out`` is returned.
3729
 
 
3730
 
    Examples
3731
 
    --------
3732
 
    >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0])
3733
 
    >>> print marr.cumsum()
3734
 
    [0 1 3 -- -- -- 9 16 24 33]
3735
 
 
3736
 
 
3737
 
    Notes
3738
 
    -----
3739
 
    Arithmetic is modular when using integer types, and no error is
3740
 
    raised on overflow.
 
4387
        Return the cumulative sum of the elements along the given axis.
 
4388
        The cumulative sum is calculated over the flattened array by
 
4389
        default, otherwise over the specified axis.
 
4390
 
 
4391
        Masked values are set to 0 internally during the computation.
 
4392
        However, their position is saved, and the result will be masked at
 
4393
        the same locations.
 
4394
 
 
4395
        Parameters
 
4396
        ----------
 
4397
        axis : {None, -1, int}, optional
 
4398
            Axis along which the sum is computed. The default (`axis` = None) is to
 
4399
            compute over the flattened array. `axis` may be negative, in which case
 
4400
            it counts from the   last to the first axis.
 
4401
        dtype : {None, dtype}, optional
 
4402
            Type of the returned array and of the accumulator in which the
 
4403
            elements are summed.  If `dtype` is not specified, it defaults
 
4404
            to the dtype of `a`, unless `a` has an integer dtype with a
 
4405
            precision less than that of the default platform integer.  In
 
4406
            that case, the default platform integer is used.
 
4407
        out : ndarray, optional
 
4408
            Alternative output array in which to place the result. It must
 
4409
            have the same shape and buffer length as the expected output
 
4410
            but the type will be cast if necessary.
 
4411
 
 
4412
        Returns
 
4413
        -------
 
4414
        cumsum : ndarray.
 
4415
            A new array holding the result is returned unless ``out`` is
 
4416
            specified, in which case a reference to ``out`` is returned.
 
4417
 
 
4418
        Notes
 
4419
        -----
 
4420
        The mask is lost if `out` is not a valid :class:`MaskedArray` !
 
4421
 
 
4422
        Arithmetic is modular when using integer types, and no error is
 
4423
        raised on overflow.
 
4424
 
 
4425
        Examples
 
4426
        --------
 
4427
        >>> marr = np.ma.array(np.arange(10), mask=[0,0,0,1,1,1,0,0,0,0])
 
4428
        >>> print marr.cumsum()
 
4429
        [0 1 3 -- -- -- 9 16 24 33]
3741
4430
 
3742
4431
        """
3743
4432
        result = self.filled(0).cumsum(axis=axis, dtype=dtype, out=out)
3800
4489
 
3801
4490
        """
3802
4491
        _mask = ndarray.__getattribute__(self, '_mask')
3803
 
        newmask = _mask.all(axis=axis)
 
4492
        newmask = _check_mask_axis(_mask, axis)
3804
4493
        # No explicit output
3805
4494
        if out is None:
3806
 
            result = self.filled(1).prod(axis, dtype=dtype).view(type(self))
3807
 
            if result.ndim:
 
4495
            result = self.filled(1).prod(axis, dtype=dtype)
 
4496
            rndim = getattr(result, 'ndim', 0)
 
4497
            if rndim:
 
4498
                result = result.view(type(self))
3808
4499
                result.__setmask__(newmask)
3809
4500
            elif newmask:
3810
4501
                result = masked
3822
4513
 
3823
4514
    def cumprod(self, axis=None, dtype=None, out=None):
3824
4515
        """
3825
 
    Return the cumulative product of the elements along the given axis.
3826
 
    The cumulative product is taken over the flattened array by
3827
 
    default, otherwise over the specified axis.
3828
 
 
3829
 
    Masked values are set to 1 internally during the computation.
3830
 
    However, their position is saved, and the result will be masked at
3831
 
    the same locations.
3832
 
 
3833
 
    Parameters
3834
 
    ----------
3835
 
    axis : {None, -1, int}, optional
3836
 
        Axis along which the product is computed. The default
3837
 
        (`axis` = None) is to compute over the flattened array.
3838
 
    dtype : {None, dtype}, optional
3839
 
        Determines the type of the returned array and of the accumulator
3840
 
        where the elements are multiplied. If ``dtype`` has the value ``None`` and
3841
 
        the type of ``a`` is an integer type of precision less than the default
3842
 
        platform integer, then the default platform integer precision is
3843
 
        used.  Otherwise, the dtype is the same as that of ``a``.
3844
 
    out : ndarray, optional
3845
 
        Alternative output array in which to place the result. It must
3846
 
        have the same shape and buffer length as the expected output
3847
 
        but the type will be cast if necessary.
3848
 
 
3849
 
    Warnings
3850
 
    --------
3851
 
    The mask is lost if out is not a valid MaskedArray !
3852
 
 
3853
 
    Returns
3854
 
    -------
3855
 
    cumprod : ndarray
3856
 
        A new array holding the result is returned unless out is specified,
3857
 
        in which case a reference to out is returned.
3858
 
 
3859
 
    Notes
3860
 
    -----
3861
 
    Arithmetic is modular when using integer types, and no error is
3862
 
    raised on overflow.
3863
 
 
3864
 
    """
 
4516
        Return the cumulative product of the elements along the given axis.
 
4517
        The cumulative product is taken over the flattened array by
 
4518
        default, otherwise over the specified axis.
 
4519
 
 
4520
        Masked values are set to 1 internally during the computation.
 
4521
        However, their position is saved, and the result will be masked at
 
4522
        the same locations.
 
4523
 
 
4524
        Parameters
 
4525
        ----------
 
4526
        axis : {None, -1, int}, optional
 
4527
            Axis along which the product is computed. The default
 
4528
            (`axis` = None) is to compute over the flattened array.
 
4529
        dtype : {None, dtype}, optional
 
4530
            Determines the type of the returned array and of the accumulator
 
4531
            where the elements are multiplied. If ``dtype`` has the value ``None``
 
4532
            and the type of ``a`` is an integer type of precision less than the
 
4533
            default platform integer, then the default platform integer precision
 
4534
            is used.  Otherwise, the dtype is the same as that of ``a``.
 
4535
        out : ndarray, optional
 
4536
            Alternative output array in which to place the result. It must
 
4537
            have the same shape and buffer length as the expected output
 
4538
            but the type will be cast if necessary.
 
4539
 
 
4540
        Returns
 
4541
        -------
 
4542
        cumprod : ndarray
 
4543
            A new array holding the result is returned unless out is specified,
 
4544
            in which case a reference to out is returned.
 
4545
 
 
4546
        Notes
 
4547
        -----
 
4548
        The mask is lost if `out` is not a valid MaskedArray !
 
4549
 
 
4550
        Arithmetic is modular when using integer types, and no error is
 
4551
        raised on overflow.
 
4552
 
 
4553
        """
3865
4554
        result = self.filled(1).cumprod(axis=axis, dtype=dtype, out=out)
3866
4555
        if out is not None:
3867
4556
            if isinstance(out, MaskedArray):
3874
4563
 
3875
4564
    def mean(self, axis=None, dtype=None, out=None):
3876
4565
        """
3877
 
    Returns the average of the array elements along given axis.
3878
 
    Refer to `numpy.mean` for full documentation.
3879
 
 
3880
 
    See Also
3881
 
    --------
3882
 
    numpy.mean : equivalent function'
 
4566
        Returns the average of the array elements.
 
4567
 
 
4568
        Masked entries are ignored.
 
4569
        The average is taken over the flattened array by default, otherwise over
 
4570
        the specified axis. Refer to `numpy.mean` for the full documentation.
 
4571
 
 
4572
        Parameters
 
4573
        ----------
 
4574
        a : array_like
 
4575
            Array containing numbers whose mean is desired. If `a` is not an
 
4576
            array, a conversion is attempted.
 
4577
        axis : int, optional
 
4578
            Axis along which the means are computed. The default is to compute
 
4579
            the mean of the flattened array.
 
4580
        dtype : dtype, optional
 
4581
            Type to use in computing the mean. For integer inputs, the default
 
4582
            is float64; for floating point, inputs it is the same as the input
 
4583
            dtype.
 
4584
        out : ndarray, optional
 
4585
            Alternative output array in which to place the result. It must have
 
4586
            the same shape as the expected output but the type will be cast if
 
4587
            necessary.
 
4588
 
 
4589
        Returns
 
4590
        -------
 
4591
        mean : ndarray, see dtype parameter above
 
4592
            If `out=None`, returns a new array containing the mean values,
 
4593
            otherwise a reference to the output array is returned.
 
4594
 
 
4595
        See Also
 
4596
        --------
 
4597
        numpy.ma.mean : Equivalent function.
 
4598
        numpy.mean : Equivalent function on non-masked arrays.
 
4599
        numpy.ma.average: Weighted average.
 
4600
 
 
4601
        Examples
 
4602
        --------
 
4603
        >>> a = np.ma.array([1,2,3], mask=[False, False, True])
 
4604
        >>> a
 
4605
        masked_array(data = [1 2 --],
 
4606
                     mask = [False False  True],
 
4607
               fill_value = 999999)
 
4608
        >>> a.mean()
 
4609
        1.5
 
4610
 
3883
4611
        """
3884
4612
        if self._mask is nomask:
3885
4613
            result = super(MaskedArray, self).mean(axis=axis, dtype=dtype)
3886
4614
        else:
3887
4615
            dsum = self.sum(axis=axis, dtype=dtype)
3888
4616
            cnt = self.count(axis=axis)
3889
 
            result = dsum*1./cnt
 
4617
            result = dsum * 1. / cnt
3890
4618
        if out is not None:
3891
4619
            out.flat = result
3892
4620
            if isinstance(out, MaskedArray):
3899
4627
 
3900
4628
    def anom(self, axis=None, dtype=None):
3901
4629
        """
3902
 
    Return the anomalies (deviations from the average) along the given axis.
3903
 
 
3904
 
    Parameters
3905
 
    ----------
3906
 
    axis : int, optional
3907
 
        Axis along which to perform the operation.
3908
 
        If None, applies to a flattened version of the array.
3909
 
    dtype : {dtype}, optional
3910
 
        Datatype for the intermediary computation.
3911
 
        If not given, the current dtype is used instead.
3912
 
 
3913
 
    """
 
4630
        Compute the anomalies (deviations from the arithmetic mean)
 
4631
        along the given axis.
 
4632
 
 
4633
        Returns an array of anomalies, with the same shape as the input and
 
4634
        where the arithmetic mean is computed along the given axis.
 
4635
 
 
4636
        Parameters
 
4637
        ----------
 
4638
        axis : int, optional
 
4639
            Axis over which the anomalies are taken.
 
4640
            The default is to use the mean of the flattened array as reference.
 
4641
        dtype : dtype, optional
 
4642
            Type to use in computing the variance. For arrays of integer type
 
4643
             the default is float32; for arrays of float types it is the same as
 
4644
             the array type.
 
4645
 
 
4646
        See Also
 
4647
        --------
 
4648
        mean : Compute the mean of the array.
 
4649
 
 
4650
        Examples
 
4651
        --------
 
4652
        >>> a = np.ma.array([1,2,3])
 
4653
        >>> a.anom()
 
4654
        masked_array(data = [-1.  0.  1.],
 
4655
                     mask = False,
 
4656
               fill_value = 1e+20)
 
4657
 
 
4658
        """
3914
4659
        m = self.mean(axis, dtype)
3915
4660
        if not axis:
3916
4661
            return (self - m)
3923
4668
        if self._mask is nomask:
3924
4669
            return self._data.var(axis=axis, dtype=dtype, out=out, ddof=ddof)
3925
4670
        # Some data are masked, yay!
3926
 
        cnt = self.count(axis=axis)-ddof
 
4671
        cnt = self.count(axis=axis) - ddof
3927
4672
        danom = self.anom(axis=axis, dtype=dtype)
3928
4673
        if iscomplexobj(self):
3929
 
            danom = umath.absolute(danom)**2
 
4674
            danom = umath.absolute(danom) ** 2
3930
4675
        else:
3931
4676
            danom *= danom
3932
4677
        dvar = divide(danom.sum(axis), cnt).view(type(self))
3933
4678
        # Apply the mask if it's not a scalar
3934
4679
        if dvar.ndim:
3935
 
            dvar._mask = mask_or(self._mask.all(axis), (cnt<=ddof))
 
4680
            dvar._mask = mask_or(self._mask.all(axis), (cnt <= ddof))
3936
4681
            dvar._update_from(self)
3937
 
        elif getattr(dvar,'_mask', False):
 
4682
        elif getattr(dvar, '_mask', False):
3938
4683
        # Make sure that masked is returned when the scalar is masked.
3939
4684
            dvar = masked
3940
4685
            if out is not None:
3997
4742
    def argsort(self, axis=None, fill_value=None, kind='quicksort',
3998
4743
                order=None):
3999
4744
        """
4000
 
    Return an ndarray of indices that sort the array along the
4001
 
    specified axis.  Masked values are filled beforehand to
4002
 
    fill_value.
4003
 
 
4004
 
    Parameters
4005
 
    ----------
4006
 
    axis : int, optional
4007
 
        Axis along which to sort.  If not given, the flattened array is used.
4008
 
    kind : {'quicksort', 'mergesort', 'heapsort'}, optional
4009
 
        Sorting algorithm.
4010
 
    order : list, optional
4011
 
        When `a` is an array with fields defined, this argument specifies
4012
 
        which fields to compare first, second, etc.  Not all fields need be
4013
 
        specified.
4014
 
    Returns
4015
 
    -------
4016
 
    index_array : ndarray, int
4017
 
        Array of indices that sort `a` along the specified axis.
4018
 
        In other words, ``a[index_array]`` yields a sorted `a`.
4019
 
 
4020
 
    See Also
4021
 
    --------
4022
 
    sort : Describes sorting algorithms used.
4023
 
    lexsort : Indirect stable sort with multiple keys.
4024
 
    ndarray.sort : Inplace sort.
4025
 
 
4026
 
    Notes
4027
 
    -----
4028
 
    See `sort` for notes on the different sorting algorithms.
 
4745
        Return an ndarray of indices that sort the array along the
 
4746
        specified axis.  Masked values are filled beforehand to
 
4747
        `fill_value`.
 
4748
 
 
4749
        Parameters
 
4750
        ----------
 
4751
        axis : int, optional
 
4752
            Axis along which to sort.  The default is -1 (last axis).
 
4753
            If None, the flattened array is used.
 
4754
        fill_value : var, optional
 
4755
            Value used to fill the array before sorting.
 
4756
            The default is the `fill_value` attribute of the input array.
 
4757
        kind : {'quicksort', 'mergesort', 'heapsort'}, optional
 
4758
            Sorting algorithm.
 
4759
        order : list, optional
 
4760
            When `a` is an array with fields defined, this argument specifies
 
4761
            which fields to compare first, second, etc.  Not all fields need be
 
4762
            specified.
 
4763
 
 
4764
        Returns
 
4765
        -------
 
4766
        index_array : ndarray, int
 
4767
            Array of indices that sort `a` along the specified axis.
 
4768
            In other words, ``a[index_array]`` yields a sorted `a`.
 
4769
 
 
4770
        See Also
 
4771
        --------
 
4772
        sort : Describes sorting algorithms used.
 
4773
        lexsort : Indirect stable sort with multiple keys.
 
4774
        ndarray.sort : Inplace sort.
 
4775
 
 
4776
        Notes
 
4777
        -----
 
4778
        See `sort` for notes on the different sorting algorithms.
 
4779
 
 
4780
        Examples
 
4781
        --------
 
4782
        >>> a = np.ma.array([3,2,1], mask=[False, False, True])
 
4783
        >>> a
 
4784
        masked_array(data = [3 2 --],
 
4785
                     mask = [False False  True],
 
4786
               fill_value = 999999)
 
4787
        >>> a.argsort()
 
4788
        array([1, 0, 2])
4029
4789
 
4030
4790
        """
4031
4791
        if fill_value is None:
4114
4874
        return d.argmax(axis, out=out)
4115
4875
 
4116
4876
 
4117
 
    def sort(self, axis=-1, kind='quicksort', order=None,
 
4877
    def sort(self, axis= -1, kind='quicksort', order=None,
4118
4878
             endwith=True, fill_value=None):
4119
4879
        """
4120
4880
    Return a sorted copy of an array.
4254
5014
 
4255
5015
        """
4256
5016
        _mask = ndarray.__getattribute__(self, '_mask')
4257
 
        newmask = _mask.all(axis=axis)
 
5017
        newmask = _check_mask_axis(_mask, axis)
4258
5018
        if fill_value is None:
4259
5019
            fill_value = minimum_fill_value(self)
4260
5020
        # No explicit output
4285
5045
        return out
4286
5046
 
4287
5047
    def mini(self, axis=None):
 
5048
        """
 
5049
        Return the array minimum along the specified axis.
 
5050
 
 
5051
        Parameters
 
5052
        ----------
 
5053
        axis : int, optional
 
5054
            The axis along which to find the minima. Default is None, in which case
 
5055
            the minimum value in the whole array is returned.
 
5056
 
 
5057
        Returns
 
5058
        -------
 
5059
        min : scalar or MaskedArray
 
5060
            If `axis` is None, the result is a scalar. Otherwise, if `axis` is
 
5061
            given and the array is at least 2-D, the result is a masked array with
 
5062
            dimension one smaller than the array on which `mini` is called.
 
5063
 
 
5064
        Examples
 
5065
        --------
 
5066
        >>> x = np.ma.array(np.arange(6), mask=[0 ,1, 0, 0, 0 ,1]).reshape(3, 2)
 
5067
        >>> print x
 
5068
        [[0 --]
 
5069
         [2 3]
 
5070
         [4 --]]
 
5071
        >>> x.mini()
 
5072
        0
 
5073
        >>> x.mini(axis=0)
 
5074
        masked_array(data = [0 3],
 
5075
                     mask = [False False],
 
5076
               fill_value = 999999)
 
5077
        >>> print x.mini(axis=1)
 
5078
        [0 2 4]
 
5079
 
 
5080
        """
4288
5081
        if axis is None:
4289
5082
            return minimum(self)
4290
5083
        else:
4320
5113
 
4321
5114
        """
4322
5115
        _mask = ndarray.__getattribute__(self, '_mask')
4323
 
        newmask = _mask.all(axis=axis)
 
5116
        newmask = _check_mask_axis(_mask, axis)
4324
5117
        if fill_value is None:
4325
5118
            fill_value = maximum_fill_value(self)
4326
5119
        # No explicit output
4397
5190
    #--------------------------------------------
4398
5191
    def tolist(self, fill_value=None):
4399
5192
        """
4400
 
    Copy the data portion of the array to a hierarchical python
4401
 
    list and returns that list.
4402
 
 
4403
 
    Data items are converted to the nearest compatible Python
4404
 
    type.  Masked values are converted to fill_value. If
4405
 
    fill_value is None, the corresponding entries in the output
4406
 
    list will be ``None``.
 
5193
        Return the data portion of the masked array as a hierarchical Python list.
 
5194
 
 
5195
        Data items are converted to the nearest compatible Python type.
 
5196
        Masked values are converted to `fill_value`. If `fill_value` is None,
 
5197
        the corresponding entries in the output list will be ``None``.
 
5198
 
 
5199
        Parameters
 
5200
        ----------
 
5201
        fill_value : scalar, optional
 
5202
            The value to use for invalid entries. Default is None.
 
5203
 
 
5204
        Returns
 
5205
        -------
 
5206
        result : list
 
5207
            The Python list representation of the masked array.
 
5208
 
 
5209
        Examples
 
5210
        --------
 
5211
        >>> x = np.ma.array([[1,2,3], [4,5,6], [7,8,9]], mask=[0] + [1,0]*4)
 
5212
        >>> x.tolist()
 
5213
        [[1, None, 3], [None, 5, None], [7, None, 9]]
 
5214
        >>> x.tolist(-999)
 
5215
        [[1, -999, 3], [-999, 5, -999], [7, -999, 9]]
4407
5216
 
4408
5217
        """
4409
5218
        if fill_value is not None:
4423
5232
                nodata = tuple([None] * dtypesize)
4424
5233
            else:
4425
5234
                nodata = None
4426
 
            [operator.setitem(result,i,nodata) for i in maskedidx]
 
5235
            [operator.setitem(result, i, nodata) for i in maskedidx]
4427
5236
        else:
4428
5237
            for idx in zip(*[i.tolist() for i in _mask.nonzero()]):
4429
5238
                tmp = result
4434
5243
    #........................
4435
5244
    def tostring(self, fill_value=None, order='C'):
4436
5245
        """
4437
 
        Return a copy of array data as a Python string containing the raw bytes
4438
 
        in the array.  The array is filled beforehand.
 
5246
        Return the array data as a string containing the raw bytes in the array.
 
5247
 
 
5248
        The array is filled with a fill value before the string conversion.
4439
5249
 
4440
5250
        Parameters
4441
5251
        ----------
4442
 
        fill_value : {var}, optional
4443
 
            Value used to fill in the masked values.
4444
 
            If None, uses self.fill_value instead.
4445
 
        order : {string}
4446
 
            Order of the data item in the copy {'C','F','A'}.
4447
 
            'C'       -- C order (row major)
4448
 
            'Fortran' -- Fortran order (column major)
4449
 
            'Any'     -- Current order of array.
4450
 
            None      -- Same as "Any"
 
5252
        fill_value : scalar, optional
 
5253
            Value used to fill in the masked values. Deafult is None, in which
 
5254
            case `MaskedArray.fill_value` is used.
 
5255
        order : {'C','F','A'}, optional
 
5256
            Order of the data item in the copy. Default is 'C'.
 
5257
 
 
5258
            - 'C'   -- C order (row major).
 
5259
            - 'F'   -- Fortran order (column major).
 
5260
            - 'A'   -- Any, current order of array.
 
5261
            - None  -- Same as 'A'.
 
5262
 
 
5263
        See Also
 
5264
        --------
 
5265
        ndarray.tostring
 
5266
        tolist, tofile
4451
5267
 
4452
5268
        Notes
4453
5269
        -----
4454
 
        As for method:`ndarray.tostring`, information about the shape, dtype...,
4455
 
        but also fill_value will be lost.
 
5270
        As for `ndarray.tostring`, information about the shape, dtype, etc.,
 
5271
        but also about `fill_value`, will be lost.
 
5272
 
 
5273
        Examples
 
5274
        --------
 
5275
        >>> x = np.ma.array(np.array([[1, 2], [3, 4]]), mask=[[0, 1], [1, 0]])
 
5276
        >>> x.tostring()
 
5277
        '\\x01\\x00\\x00\\x00?B\\x0f\\x00?B\\x0f\\x00\\x04\\x00\\x00\\x00'
4456
5278
 
4457
5279
        """
4458
5280
        return self.filled(fill_value).tostring(order=order)
4459
5281
    #........................
4460
5282
    def tofile(self, fid, sep="", format="%s"):
 
5283
        """
 
5284
        Save a masked array to a file in binary format.
 
5285
 
 
5286
        .. warning::
 
5287
          This function is not implemented yet.
 
5288
 
 
5289
        Raises
 
5290
        ------
 
5291
        NotImplementedError
 
5292
            When `tofile` is called.
 
5293
 
 
5294
        """
4461
5295
        raise NotImplementedError("Not implemented yet, sorry...")
4462
5296
 
4463
5297
    def toflex(self):
4464
5298
        """
4465
 
        Transforms a MaskedArray into a flexible-type array with two fields:
4466
 
 
4467
 
        * the ``_data`` field stores the ``_data`` part of the array;
4468
 
        * the ``_mask`` field stores the ``_mask`` part of the array;
 
5299
        Transforms a masked array into a flexible-type array.
 
5300
 
 
5301
        The flexible type array that is returned will have two fields:
 
5302
 
 
5303
        * the ``_data`` field stores the ``_data`` part of the array.
 
5304
        * the ``_mask`` field stores the ``_mask`` part of the array.
 
5305
 
 
5306
        Parameters
 
5307
        ----------
 
5308
        None
4469
5309
 
4470
5310
        Returns
4471
5311
        -------
4472
5312
        record : ndarray
4473
 
            A new flexible-type ndarray with two fields: the first element
 
5313
            A new flexible-type `ndarray` with two fields: the first element
4474
5314
            containing a value, the second element containing the corresponding
4475
 
            mask boolean.  The returned record shape matches self.shape.
 
5315
            mask boolean. The returned record shape matches self.shape.
4476
5316
 
4477
5317
        Notes
4478
5318
        -----
4479
 
        A side-effect of transforming a masked array into a flexible ndarray is
 
5319
        A side-effect of transforming a masked array into a flexible `ndarray` is
4480
5320
        that meta information (``fill_value``, ...) will be lost.
4481
5321
 
4482
5322
        Examples
4502
5342
        mdtype = self._mask.dtype
4503
5343
        #
4504
5344
        record = np.ndarray(shape=self.shape,
4505
 
                            dtype=[('_data',ddtype),('_mask',mdtype)])
 
5345
                            dtype=[('_data', ddtype), ('_mask', mdtype)])
4506
5346
        record['_data'] = self._data
4507
5347
        record['_mask'] = self._mask
4508
5348
        return record
4514
5354
        purposes.
4515
5355
 
4516
5356
        """
 
5357
        cf = 'CF'[self.flags.fnc]
4517
5358
        state = (1,
4518
5359
                 self.shape,
4519
5360
                 self.dtype,
4520
5361
                 self.flags.fnc,
4521
 
                 self._data.tostring(),
4522
 
                 getmaskarray(self).tostring(),
 
5362
                 self._data.tostring(cf),
 
5363
                 getmaskarray(self).tostring(cf),
4523
5364
                 self._fill_value,
4524
5365
                 )
4525
5366
        return state
4546
5387
 
4547
5388
        """
4548
5389
        return (_mareconstruct,
4549
 
                (self.__class__, self._baseclass, (0,), 'b', ),
 
5390
                (self.__class__, self._baseclass, (0,), 'b',),
4550
5391
                self.__getstate__())
4551
5392
    #
4552
5393
    def __deepcopy__(self, memo=None):
4555
5396
        if memo is None:
4556
5397
            memo = {}
4557
5398
        memo[id(self)] = copied
4558
 
        for (k,v) in self.__dict__.iteritems():
 
5399
        for (k, v) in self.__dict__.iteritems():
4559
5400
            copied.__dict__[k] = deepcopy(v, memo)
4560
5401
        return copied
4561
5402
 
4707
5548
#---- --- Extrema functions ---
4708
5549
#####---------------------------------------------------------------------------
4709
5550
class _extrema_operation(object):
4710
 
    "Generic class for maximum/minimum functions."
 
5551
    """
 
5552
    Generic class for maximum/minimum functions.
 
5553
 
 
5554
    .. note::
 
5555
      This is the base class for `_maximum_operation` and
 
5556
      `_minimum_operation`.
 
5557
 
 
5558
    """
4711
5559
    def __call__(self, a, b=None):
4712
5560
        "Executes the call behavior."
4713
5561
        if b is None:
4811
5659
#---- --- Definition of functions from the corresponding methods ---
4812
5660
#####---------------------------------------------------------------------------
4813
5661
class _frommethod:
4814
 
    """Define functions from existing MaskedArray methods.
 
5662
    """
 
5663
    Define functions from existing MaskedArray methods.
4815
5664
 
4816
5665
    Parameters
4817
5666
    ----------
4818
 
        _methodname : string
4819
 
            Name of the method to transform.
 
5667
    methodname : str
 
5668
        Name of the method to transform.
4820
5669
 
4821
5670
    """
4822
5671
    def __init__(self, methodname):
4833
5682
            return doc
4834
5683
    #
4835
5684
    def __call__(self, a, *args, **params):
4836
 
        if isinstance(a, MaskedArray):
4837
 
            return getattr(a, self.__name__).__call__(*args, **params)
4838
 
        #FIXME ----
4839
 
        #As x is not a MaskedArray, we transform it to a ndarray with asarray
4840
 
        #... and call the corresponding method.
4841
 
        #Except that sometimes it doesn't work (try reshape([1,2,3,4],(2,2)))
4842
 
        #we end up with a "SystemError: NULL result without error in PyObject_Call"
4843
 
        #A dirty trick is then to call the initial numpy function...
4844
 
        method = getattr(narray(a, copy=False), self.__name__)
4845
 
        try:
 
5685
        # Get the method from the array (if possible)
 
5686
        method_name = self.__name__
 
5687
        method = getattr(a, method_name, None)
 
5688
        if method is not None:
4846
5689
            return method(*args, **params)
4847
 
        except SystemError:
4848
 
            return getattr(np,self.__name__).__call__(a, *args, **params)
 
5690
        # Still here ? Then a is not a MaskedArray
 
5691
        method = getattr(MaskedArray, method_name, None)
 
5692
        if method is not None:
 
5693
            return method(MaskedArray(a), *args, **params)
 
5694
        # Still here ? OK, let's call the corresponding np function
 
5695
        method = getattr(np, method_name)
 
5696
        return method(a, *args, **params)
4849
5697
 
4850
5698
all = _frommethod('all')
4851
5699
anomalies = anom = _frommethod('anom')
4876
5724
 
4877
5725
#..............................................................................
4878
5726
def power(a, b, third=None):
4879
 
    """Computes a**b elementwise.
 
5727
    """
 
5728
    Returns element-wise base array raised to power from second array.
 
5729
 
 
5730
    This is the masked array version of `numpy.power`. For details see
 
5731
    `numpy.power`.
 
5732
 
 
5733
    See Also
 
5734
    --------
 
5735
    numpy.power
 
5736
 
 
5737
    Notes
 
5738
    -----
 
5739
    The *out* argument to `numpy.power` is not supported, `third` has to be
 
5740
    None.
4880
5741
 
4881
5742
    """
4882
5743
    if third is not None:
4950
5811
    if fill_value is None:
4951
5812
        fill_value = default_fill_value(a)
4952
5813
        try:
4953
 
            fill_value = - fill_value
 
5814
            fill_value = -fill_value
4954
5815
        except:
4955
5816
            pass
4956
5817
    d = filled(a, fill_value)
4957
5818
    return d.argmax(axis=axis)
4958
5819
argmin.__doc__ = MaskedArray.argmax.__doc__
4959
5820
 
4960
 
def sort(a, axis=-1, kind='quicksort', order=None, endwith=True, fill_value=None):
 
5821
def sort(a, axis= -1, kind='quicksort', order=None, endwith=True, fill_value=None):
4961
5822
    "Function version of the eponymous method."
4962
5823
    a = narray(a, copy=True, subok=True)
4963
5824
    if axis is None:
4979
5840
 
4980
5841
def compressed(x):
4981
5842
    """
4982
 
    Return a 1-D array of all the non-masked data.
 
5843
    Return all the non-masked data as a 1-D array.
 
5844
 
 
5845
    This function is equivalent to calling the "compressed" method of a
 
5846
    `MaskedArray`, see `MaskedArray.compressed` for details.
4983
5847
 
4984
5848
    See Also
4985
5849
    --------
4986
5850
    MaskedArray.compressed
4987
 
        equivalent method
 
5851
        Equivalent method.
4988
5852
 
4989
5853
    """
4990
5854
    if getmask(x) is nomask:
4993
5857
        return x.compressed()
4994
5858
 
4995
5859
def concatenate(arrays, axis=0):
4996
 
    "Concatenate the arrays along the given axis."
 
5860
    """
 
5861
    Concatenate a sequence of arrays along the given axis.
 
5862
 
 
5863
    Parameters
 
5864
    ----------
 
5865
    arrays : sequence of array_like
 
5866
        The arrays must have the same shape, except in the dimension
 
5867
        corresponding to `axis` (the first, by default).
 
5868
    axis : int, optional
 
5869
        The axis along which the arrays will be joined. Default is 0.
 
5870
 
 
5871
    Returns
 
5872
    -------
 
5873
    result : MaskedArray
 
5874
        The concatenated array with any masked entries preserved.
 
5875
 
 
5876
    See Also
 
5877
    --------
 
5878
    numpy.concatenate : Equivalent function in the top-level NumPy module.
 
5879
 
 
5880
    Examples
 
5881
    --------
 
5882
    >>> import numpy.ma as ma
 
5883
    >>> a = ma.arange(3)
 
5884
    >>> a[1] = ma.masked
 
5885
    >>> b = ma.arange(2, 5)
 
5886
    >>> a
 
5887
    masked_array(data = [0 -- 2],
 
5888
                 mask = [False  True False],
 
5889
           fill_value = 999999)
 
5890
    >>> b
 
5891
    masked_array(data = [2 3 4],
 
5892
                 mask = False,
 
5893
           fill_value = 999999)
 
5894
    >>> ma.concatenate([a, b])
 
5895
    masked_array(data = [0 -- 2 2 3 4],
 
5896
                 mask = [False  True False False False False],
 
5897
           fill_value = 999999)
 
5898
 
 
5899
    """
4997
5900
    d = np.concatenate([getdata(a) for a in arrays], axis)
4998
5901
    rcls = get_masked_subclass(*arrays)
4999
5902
    data = d.view(rcls)
5015
5918
        data._mask = dm.reshape(d.shape)
5016
5919
    return data
5017
5920
 
5018
 
def count(a, axis = None):
 
5921
def count(a, axis=None):
5019
5922
    if isinstance(a, MaskedArray):
5020
5923
        return a.count(axis)
5021
5924
    return masked_array(a, copy=False).count(axis)
5026
5929
    """
5027
5930
    Extract a diagonal or construct a diagonal array.
5028
5931
 
5029
 
    Parameters
5030
 
    ----------
5031
 
    v : array_like
5032
 
        If `v` is a 2-dimensional array, return a copy of
5033
 
        its `k`-th diagonal. If `v` is a 1-dimensional array,
5034
 
        return a 2-dimensional array with `v` on the `k`-th diagonal.
5035
 
    k : int, optional
5036
 
        Diagonal in question.  The defaults is 0.
 
5932
    This function is the equivalent of `numpy.diag` that takes masked
 
5933
    values into account, see `numpy.diag` for details.
5037
5934
 
5038
 
    Examples
 
5935
    See Also
5039
5936
    --------
5040
 
    >>> x = np.arange(9).reshape((3,3))
5041
 
    >>> x
5042
 
    array([[0, 1, 2],
5043
 
           [3, 4, 5],
5044
 
           [6, 7, 8]])
5045
 
    >>> np.diag(x)
5046
 
    array([0, 4, 8])
5047
 
    >>> np.diag(np.diag(x))
5048
 
    array([[0, 0, 0],
5049
 
           [0, 4, 0],
5050
 
           [0, 0, 8]])
 
5937
    numpy.diag : Equivalent function for ndarrays.
5051
5938
 
5052
5939
    """
5053
5940
    output = np.diag(v, k).view(MaskedArray)
5058
5945
 
5059
5946
def expand_dims(x, axis):
5060
5947
    """
5061
 
    Expand the shape of the array by including a new axis before
5062
 
    the given one.
 
5948
    Expand the shape of an array.
 
5949
 
 
5950
    Expands the shape of the array by including a new axis before the one
 
5951
    specified by the `axis` parameter. This function behaves the same as
 
5952
    `numpy.expand_dims` but preserves masked elements.
 
5953
 
 
5954
    See Also
 
5955
    --------
 
5956
    numpy.expand_dims : Equivalent function in top-level NumPy module.
 
5957
 
 
5958
    Examples
 
5959
    --------
 
5960
    >>> import numpy.ma as ma
 
5961
    >>> x = ma.array([1, 2, 4])
 
5962
    >>> x[1] = ma.masked
 
5963
    >>> x
 
5964
    masked_array(data = [1 -- 4],
 
5965
                 mask = [False  True False],
 
5966
           fill_value = 999999)
 
5967
    >>> np.expand_dims(x, axis=0)
 
5968
    array([[1, 2, 4]])
 
5969
    >>> ma.expand_dims(x, axis=0)
 
5970
    masked_array(data =
 
5971
     [[1 -- 4]],
 
5972
                 mask =
 
5973
     [[False  True False]],
 
5974
           fill_value = 999999)
 
5975
 
 
5976
    The same result can be achieved using slicing syntax with `np.newaxis`.
 
5977
 
 
5978
    >>> x[np.newaxis, :]
 
5979
    masked_array(data =
 
5980
     [[1 -- 4]],
 
5981
                 mask =
 
5982
     [[False  True False]],
 
5983
           fill_value = 999999)
5063
5984
 
5064
5985
    """
5065
5986
    result = n_expand_dims(x, axis)
5073
5994
 
5074
5995
#......................................
5075
5996
def left_shift (a, n):
5076
 
    "Left shift n bits."
 
5997
    """
 
5998
    Shift the bits of an integer to the left.
 
5999
 
 
6000
    This is the masked array version of `numpy.left_shift`, for details
 
6001
    see that function.
 
6002
 
 
6003
    See Also
 
6004
    --------
 
6005
    numpy.left_shift
 
6006
 
 
6007
    """
5077
6008
    m = getmask(a)
5078
6009
    if m is nomask:
5079
6010
        d = umath.left_shift(filled(a), n)
5083
6014
        return masked_array(d, mask=m)
5084
6015
 
5085
6016
def right_shift (a, n):
5086
 
    "Right shift n bits."
 
6017
    """
 
6018
    Shift the bits of an integer to the right.
 
6019
 
 
6020
    This is the masked array version of `numpy.right_shift`, for details
 
6021
    see that function.
 
6022
 
 
6023
    See Also
 
6024
    --------
 
6025
    numpy.right_shift
 
6026
 
 
6027
    """
5087
6028
    m = getmask(a)
5088
6029
    if m is nomask:
5089
6030
        d = umath.right_shift(filled(a), n)
5094
6035
 
5095
6036
#......................................
5096
6037
def put(a, indices, values, mode='raise'):
5097
 
    """Set storage-indexed locations to corresponding values.
5098
 
 
5099
 
    Values and indices are filled if necessary.
 
6038
    """
 
6039
    Set storage-indexed locations to corresponding values.
 
6040
 
 
6041
    This function is equivalent to `MaskedArray.put`, see that method
 
6042
    for details.
 
6043
 
 
6044
    See Also
 
6045
    --------
 
6046
    MaskedArray.put
5100
6047
 
5101
6048
    """
5102
6049
    # We can't use 'frommethod', the order of arguments is different
5106
6053
        return narray(a, copy=False).put(indices, values, mode=mode)
5107
6054
 
5108
6055
def putmask(a, mask, values): #, mode='raise'):
5109
 
    """Set a.flat[n] = values[n] for each n where mask.flat[n] is true.
5110
 
 
5111
 
    If values is not the same size of a and mask then it will repeat
5112
 
    as necessary.  This gives different behavior than
5113
 
    a[mask] = values.
5114
 
 
5115
 
    Note: Using a masked array as values will NOT transform a ndarray in
5116
 
          a maskedarray.
 
6056
    """
 
6057
    Changes elements of an array based on conditional and input values.
 
6058
 
 
6059
    This is the masked array version of `numpy.putmask`, for details see
 
6060
    `numpy.putmask`.
 
6061
 
 
6062
    See Also
 
6063
    --------
 
6064
    numpy.putmask
 
6065
 
 
6066
    Notes
 
6067
    -----
 
6068
    Using a masked array as `values` will **not** transform a `ndarray` into
 
6069
    a `MaskedArray`.
5117
6070
 
5118
6071
    """
5119
6072
    # We can't use 'frommethod', the order of arguments is different
5139
6092
 
5140
6093
def transpose(a, axes=None):
5141
6094
    """
5142
 
    Return a view of the array with dimensions permuted according to axes,
5143
 
    as a masked array.
5144
 
 
5145
 
    If ``axes`` is None (default), the output view has reversed
5146
 
    dimensions compared to the original.
 
6095
    Permute the dimensions of an array.
 
6096
 
 
6097
    This function is exactly equivalent to `numpy.transpose`.
 
6098
 
 
6099
    See Also
 
6100
    --------
 
6101
    numpy.transpose : Equivalent function in top-level NumPy module.
 
6102
 
 
6103
    Examples
 
6104
    --------
 
6105
    >>> import numpy.ma as ma
 
6106
    >>> x = ma.arange(4).reshape((2,2))
 
6107
    >>> x[1, 1] = ma.masked
 
6108
    >>>> x
 
6109
    masked_array(data =
 
6110
     [[0 1]
 
6111
     [2 --]],
 
6112
                 mask =
 
6113
     [[False False]
 
6114
     [False  True]],
 
6115
           fill_value = 999999)
 
6116
    >>> ma.transpose(x)
 
6117
    masked_array(data =
 
6118
     [[0 2]
 
6119
     [1 --]],
 
6120
                 mask =
 
6121
     [[False False]
 
6122
     [False  True]],
 
6123
           fill_value = 999999)
5147
6124
 
5148
6125
    """
5149
6126
    #We can't use 'frommethod', as 'transpose' doesn't take keywords
5153
6130
        return narray(a, copy=False).transpose(axes).view(MaskedArray)
5154
6131
 
5155
6132
def reshape(a, new_shape, order='C'):
5156
 
    """Change the shape of the array a to new_shape."""
 
6133
    """
 
6134
    Returns an array containing the same data with a new shape.
 
6135
 
 
6136
    Refer to `MaskedArray.reshape` for full documentation.
 
6137
 
 
6138
    See Also
 
6139
    --------
 
6140
    MaskedArray.reshape : equivalent function
 
6141
 
 
6142
    """
5157
6143
    #We can't use 'frommethod', it whine about some parameters. Dmmit.
5158
6144
    try:
5159
6145
        return a.reshape(new_shape, order=order)
5162
6148
        return _tmp.view(MaskedArray)
5163
6149
 
5164
6150
def resize(x, new_shape):
5165
 
    """Return a new array with the specified shape.
5166
 
 
5167
 
    The total size of the original array can be any size.  The new
5168
 
    array is filled with repeated copies of a. If a was masked, the
5169
 
    new array will be masked, and the new mask will be a repetition of
5170
 
    the old one.
 
6151
    """
 
6152
    Return a new masked array with the specified size and shape.
 
6153
 
 
6154
    This is the masked equivalent of the `numpy.resize` function. The new
 
6155
    array is filled with repeated copies of `x` (in the order that the
 
6156
    data are stored in memory). If `x` is masked, the new array will be
 
6157
    masked, and the new mask will be a repetition of the old one.
 
6158
 
 
6159
    See Also
 
6160
    --------
 
6161
    numpy.resize : Equivalent function in the top level NumPy module.
 
6162
 
 
6163
    Examples
 
6164
    --------
 
6165
    >>> import numpy.ma as ma
 
6166
    >>> a = ma.array([[1, 2] ,[3, 4]])
 
6167
    >>> a[0, 1] = ma.masked
 
6168
    >>> a
 
6169
    masked_array(data =
 
6170
     [[1 --]
 
6171
     [3 4]],
 
6172
                 mask =
 
6173
     [[False  True]
 
6174
     [False False]],
 
6175
           fill_value = 999999)
 
6176
    >>> np.resize(a, (3, 3))
 
6177
    array([[1, 2, 3],
 
6178
           [4, 1, 2],
 
6179
           [3, 4, 1]])
 
6180
    >>> ma.resize(a, (3, 3))
 
6181
    masked_array(data =
 
6182
     [[1 -- 3]
 
6183
     [4 1 --]
 
6184
     [3 4 1]],
 
6185
                 mask =
 
6186
     [[False  True False]
 
6187
     [False False  True]
 
6188
     [False False False]],
 
6189
           fill_value = 999999)
 
6190
 
 
6191
    A MaskedArray is always returned, regardless of the input type.
 
6192
 
 
6193
    >>> a = np.array([[1, 2] ,[3, 4]])
 
6194
    >>> ma.resize(a, (3, 3))
 
6195
    masked_array(data =
 
6196
     [[1 2 3]
 
6197
     [4 1 2]
 
6198
     [3 4 1]],
 
6199
                 mask =
 
6200
     False,
 
6201
           fill_value = 999999)
5171
6202
 
5172
6203
    """
5173
6204
    # We can't use _frommethods here, as N.resize is notoriously whiny.
5201
6232
#---- --- Extra functions ---
5202
6233
#####--------------------------------------------------------------------------
5203
6234
def where (condition, x=None, y=None):
5204
 
    """where(condition | x, y)
 
6235
    """
 
6236
    Return a masked array with elements from x or y, depending on condition.
5205
6237
 
5206
 
    Returns a (subclass of) masked array, shaped like condition, where
5207
 
    the elements are x when condition is True, and y otherwise.  If
5208
 
    neither x nor y are given, returns a tuple of indices where
5209
 
    condition is True (a la condition.nonzero()).
 
6238
    Returns a masked array, shaped like condition, where the elements
 
6239
    are from `x` when `condition` is True, and from `y` otherwise.
 
6240
    If neither `x` nor `y` are given, the function returns a tuple of
 
6241
    indices where `condition` is True (the result of
 
6242
    ``condition.nonzero()``).
5210
6243
 
5211
6244
    Parameters
5212
6245
    ----------
5213
 
    condition : {var}
5214
 
        The condition to meet. Must be convertible to an integer
5215
 
        array.
5216
 
    x : {var}, optional
5217
 
        Values of the output when the condition is met
5218
 
    y : {var}, optional
5219
 
        Values of the output when the condition is not met.
 
6246
    condition : array_like, bool
 
6247
        The condition to meet. For each True element, yield the corresponding
 
6248
        element from `x`, otherwise from `y`.
 
6249
    x, y : array_like, optional
 
6250
        Values from which to choose. `x` and `y` need to have the same shape
 
6251
        as condition, or be broadcast-able to that shape.
 
6252
 
 
6253
    Returns
 
6254
    -------
 
6255
    out : MaskedArray or tuple of ndarrays
 
6256
        The resulting masked array if `x` and `y` were given, otherwise
 
6257
        the result of ``condition.nonzero()``.
 
6258
 
 
6259
    See Also
 
6260
    --------
 
6261
    numpy.where : Equivalent function in the top-level NumPy module.
 
6262
 
 
6263
    Examples
 
6264
    --------
 
6265
    >>> x = np.ma.array(np.arange(9.).reshape(3, 3), mask=[[0, 1, 0],
 
6266
    ...                                                    [1, 0, 1],
 
6267
    ...                                                    [0, 1, 0]])
 
6268
    >>> print x
 
6269
    [[0.0 -- 2.0]
 
6270
     [-- 4.0 --]
 
6271
     [6.0 -- 8.0]]
 
6272
    >>> np.ma.where(x > 5)    # return the indices where x > 5
 
6273
    (array([2, 2]), array([0, 2]))
 
6274
 
 
6275
    >>> print np.ma.where(x > 5, x, -3.1416)
 
6276
    [[-3.1416 -- -3.1416]
 
6277
     [-- -3.1416 --]
 
6278
     [6.0 -- 8.0]]
5220
6279
 
5221
6280
    """
5222
6281
    if x is None and y is None:
5234
6293
    elif y is masked:
5235
6294
        ndtype = xv.dtype
5236
6295
    else:
5237
 
        ndtype = np.max([xv.dtype, yv.dtype])
 
6296
        ndtype = np.find_common_type([xv.dtype, yv.dtype], [])
5238
6297
    # Construct an empty array and fill it
5239
6298
    d = np.empty(fc.shape, dtype=ndtype).view(MaskedArray)
5240
6299
    _data = d._data
5251
6310
 
5252
6311
def choose (indices, choices, out=None, mode='raise'):
5253
6312
    """
5254
 
    choose(a, choices, out=None, mode='raise')
5255
 
 
5256
6313
    Use an index array to construct a new array from a set of choices.
5257
6314
 
5258
6315
    Given an array of integers and a set of n choice arrays, this method
5262
6319
 
5263
6320
    Parameters
5264
6321
    ----------
5265
 
    a : int array
5266
 
        This array must contain integers in [0, n-1], where n is the number
5267
 
        of choices.
 
6322
    a : ndarray of ints
 
6323
        This array must contain integers in ``[0, n-1]``, where n is the
 
6324
        number of choices.
5268
6325
    choices : sequence of arrays
5269
6326
        Choice arrays. The index array and all of the choices should be
5270
6327
        broadcastable to the same shape.
5271
6328
    out : array, optional
5272
6329
        If provided, the result will be inserted into this array. It should
5273
 
        be of the appropriate shape and dtype
 
6330
        be of the appropriate shape and `dtype`.
5274
6331
    mode : {'raise', 'wrap', 'clip'}, optional
5275
6332
        Specifies how out-of-bounds indices will behave.
5276
 
        'raise' : raise an error
5277
 
        'wrap' : wrap around
5278
 
        'clip' : clip to the range
 
6333
 
 
6334
        * 'raise' : raise an error
 
6335
        * 'wrap' : wrap around
 
6336
        * 'clip' : clip to the range
5279
6337
 
5280
6338
    Returns
5281
6339
    -------
5285
6343
    --------
5286
6344
    choose : equivalent function
5287
6345
 
 
6346
    Examples
 
6347
    --------
 
6348
    >>> choice = np.array([[1,1,1], [2,2,2], [3,3,3]])
 
6349
    >>> a = np.array([2, 1, 0])
 
6350
    >>> np.ma.choose(a, choice)
 
6351
    masked_array(data = [3 2 1],
 
6352
          mask = False,
 
6353
          fill_value=999999)
 
6354
 
5288
6355
    """
5289
6356
    def fmask (x):
5290
6357
        "Returns the filled array, or True if masked."
5382
6449
        return masked_array(d)
5383
6450
    ma = getmaskarray(a)
5384
6451
    mb = getmaskarray(b)
5385
 
    m = make_mask(1-np.outer(1-ma, 1-mb), copy=0)
 
6452
    m = make_mask(1 - np.outer(1 - ma, 1 - mb), copy=0)
5386
6453
    return masked_array(d, mask=m)
5387
6454
outer.__doc__ = doc_note(np.outer.__doc__,
5388
6455
                         "Masked values are replaced by 0.")
5393
6460
    Return True if all entries of a and b are equal, using
5394
6461
    fill_value as a truth value where either or both are masked.
5395
6462
 
 
6463
    Parameters
 
6464
    ----------
 
6465
    a, b : array_like
 
6466
        Input arrays to compare.
 
6467
    fill_value : bool, optional
 
6468
        Whether masked values in a or b are considered equal (True) or not
 
6469
        (False).
 
6470
 
 
6471
    Returns
 
6472
    -------
 
6473
    y : bool
 
6474
        Returns True if the two arrays are equal within the given
 
6475
        tolerance, False otherwise. If either array contains NaN,
 
6476
        then False is returned.
 
6477
 
 
6478
    See Also
 
6479
    --------
 
6480
    all, any
 
6481
    numpy.ma.allclose
 
6482
 
 
6483
    Examples
 
6484
    --------
 
6485
    >>> a = ma.array([1e10, 1e-7, 42.0], mask=[0, 0, 1])
 
6486
    >>> a
 
6487
    masked_array(data = [10000000000.0 1e-07 --],
 
6488
          mask = [False False  True],
 
6489
          fill_value=1e+20)
 
6490
 
 
6491
    >>> b = array([1e10, 1e-7, -42.0])
 
6492
    >>> b
 
6493
    array([  1.00000000e+10,   1.00000000e-07,  -4.20000000e+01])
 
6494
    >>> ma.allequal(a, b, fill_value=False)
 
6495
    False
 
6496
    >>> ma.allequal(a, b)
 
6497
    True
 
6498
 
5396
6499
    """
5397
6500
    m = mask_or(getmask(a), getmask(b))
5398
6501
    if m is nomask:
5409
6512
    else:
5410
6513
        return False
5411
6514
 
5412
 
def allclose (a, b, masked_equal=True, rtol=1.e-5, atol=1.e-8, fill_value=None):
 
6515
def allclose (a, b, masked_equal=True, rtol=1e-5, atol=1e-8, fill_value=None):
5413
6516
    """
5414
6517
    Returns True if two arrays are element-wise equal within a tolerance.
5415
6518
 
5421
6524
    ----------
5422
6525
    a, b : array_like
5423
6526
        Input arrays to compare.
5424
 
    masked_equal : boolean, optional
 
6527
    masked_equal : bool, optional
5425
6528
        Whether masked values in `a` and `b` are considered equal (True) or not
5426
6529
        (False). They are considered equal by default.
5427
 
    rtol : Relative tolerance
5428
 
        The relative difference is equal to `rtol` * `b`.
5429
 
    atol : Absolute tolerance
5430
 
        The absolute difference is equal to `atol`.
5431
 
    fill_value : boolean, optional
5432
 
        *Deprecated* - Whether masked values in a or b are considered equal
 
6530
    rtol : float, optional
 
6531
        Relative tolerance. The relative difference is equal to ``rtol * b``.
 
6532
        Default is 1e-5.
 
6533
    atol : float, optional
 
6534
        Absolute tolerance. The absolute difference is equal to `atol`.
 
6535
        Default is 1e-8.
 
6536
    fill_value : bool, optional
 
6537
        *Deprecated* - Whether masked values in `a` or `b` are considered equal
5433
6538
        (True) or not (False).
5434
6539
 
5435
6540
    Returns
5436
6541
    -------
5437
6542
    y : bool
5438
6543
        Returns True if the two arrays are equal within the given
5439
 
        tolerance; False otherwise. If either array contains NaN, then
 
6544
        tolerance, False otherwise. If either array contains NaN, then
5440
6545
        False is returned.
5441
6546
 
5442
6547
    See Also
5443
6548
    --------
5444
6549
    all, any
5445
 
    numpy.allclose : the non-masked allclose
 
6550
    numpy.allclose : the non-masked `allclose`.
5446
6551
 
5447
6552
    Notes
5448
6553
    -----
5449
 
    If the following equation is element-wise True, then allclose returns
5450
 
    True.
5451
 
 
5452
 
     absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
5453
 
 
5454
 
    Return True if all elements of a and b are equal subject to
 
6554
    If the following equation is element-wise True, then `allclose` returns
 
6555
    True::
 
6556
 
 
6557
      absolute(`a` - `b`) <= (`atol` + `rtol` * absolute(`b`))
 
6558
 
 
6559
    Return True if all elements of `a` and `b` are equal subject to
5455
6560
    given tolerances.
5456
6561
 
5457
6562
    Examples
5464
6569
    >>> b = ma.array([1e10, 1e-8, -42.0], mask=[0, 0, 1])
5465
6570
    >>> ma.allclose(a, b)
5466
6571
    False
 
6572
 
5467
6573
    >>> a = ma.array([1e10, 1e-8, 42.0], mask=[0, 0, 1])
5468
6574
    >>> b = ma.array([1.00001e10, 1e-9, -42.0], mask=[0, 0, 1])
5469
6575
    >>> ma.allclose(a, b)
5495
6601
        return False
5496
6602
    # No infs at all
5497
6603
    if not np.any(xinf):
5498
 
        d = filled(umath.less_equal(umath.absolute(x-y),
 
6604
        d = filled(umath.less_equal(umath.absolute(x - y),
5499
6605
                                    atol + rtol * umath.absolute(y)),
5500
6606
                   masked_equal)
5501
6607
        return np.all(d)
5503
6609
        return False
5504
6610
    x = x[~xinf]
5505
6611
    y = y[~xinf]
5506
 
    d = filled(umath.less_equal(umath.absolute(x-y),
 
6612
    d = filled(umath.less_equal(umath.absolute(x - y),
5507
6613
                                atol + rtol * umath.absolute(y)),
5508
6614
               masked_equal)
5509
6615
    return np.all(d)
5511
6617
#..............................................................................
5512
6618
def asarray(a, dtype=None, order=None):
5513
6619
    """
5514
 
    Convert the input `a` to a masked array of the given datatype.
 
6620
    Convert the input to a masked array of the given data-type.
 
6621
 
 
6622
    No copy is performed if the input is already an `ndarray`. If `a` is
 
6623
    a subclass of `MaskedArray`, a base class `MaskedArray` is returned.
5515
6624
 
5516
6625
    Parameters
5517
6626
    ----------
5518
6627
    a : array_like
5519
 
        Input data, in any form that can be converted to an array.  This
 
6628
        Input data, in any form that can be converted to a masked array. This
5520
6629
        includes lists, lists of tuples, tuples, tuples of tuples, tuples
5521
 
        of lists and ndarrays.
5522
 
    dtype : data-type, optional
 
6630
        of lists, ndarrays and masked arrays.
 
6631
    dtype : dtype, optional
5523
6632
        By default, the data-type is inferred from the input data.
5524
6633
    order : {'C', 'F'}, optional
5525
6634
        Whether to use row-major ('C') or column-major ('FORTRAN') memory
5526
 
        representation.  Defaults to 'C'.
 
6635
        representation.  Default is 'C'.
5527
6636
 
5528
6637
    Returns
5529
6638
    -------
5530
 
    out : ndarray
5531
 
        MaskedArray interpretation of `a`.  No copy is performed if the input
5532
 
        is already an ndarray.  If `a` is a subclass of MaskedArray, a base
5533
 
        class MaskedArray is returned.
 
6639
    out : MaskedArray
 
6640
        Masked array interpretation of `a`.
 
6641
 
 
6642
    See Also
 
6643
    --------
 
6644
    asanyarray : Similar to `asarray`, but conserves subclasses.
 
6645
 
 
6646
    Examples
 
6647
    --------
 
6648
    >>> x = np.arange(10.).reshape(2, 5)
 
6649
    >>> x
 
6650
    array([[ 0.,  1.,  2.,  3.,  4.],
 
6651
           [ 5.,  6.,  7.,  8.,  9.]])
 
6652
    >>> np.ma.asarray(x)
 
6653
    masked_array(data =
 
6654
     [[ 0.  1.  2.  3.  4.]
 
6655
     [ 5.  6.  7.  8.  9.]],
 
6656
                 mask =
 
6657
     False,
 
6658
           fill_value = 1e+20)
 
6659
    >>> type(np.ma.asarray(x))
 
6660
    <class 'numpy.ma.core.MaskedArray'>
5534
6661
 
5535
6662
    """
5536
6663
    return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=False)
5537
6664
 
5538
6665
def asanyarray(a, dtype=None):
5539
6666
    """
5540
 
    Convert the input `a` to a masked array of the given datatype.
5541
 
    If `a` is a subclass of MaskedArray, its class is conserved.
 
6667
    Convert the input to a masked array, conserving subclasses.
 
6668
 
 
6669
    If `a` is a subclass of `MaskedArray`, its class is conserved.
 
6670
    No copy is performed if the input is already an `ndarray`.
5542
6671
 
5543
6672
    Parameters
5544
6673
    ----------
5545
6674
    a : array_like
5546
 
        Input data, in any form that can be converted to an array.  This
5547
 
        includes lists, lists of tuples, tuples, tuples of tuples, tuples
5548
 
        of lists and ndarrays.
5549
 
    dtype : data-type, optional
 
6675
        Input data, in any form that can be converted to an array.
 
6676
    dtype : dtype, optional
5550
6677
        By default, the data-type is inferred from the input data.
5551
6678
    order : {'C', 'F'}, optional
5552
6679
        Whether to use row-major ('C') or column-major ('FORTRAN') memory
5553
 
        representation.  Defaults to 'C'.
 
6680
        representation.  Default is 'C'.
5554
6681
 
5555
6682
    Returns
5556
6683
    -------
5557
 
    out : ndarray
5558
 
        MaskedArray interpretation of `a`.  No copy is performed if the input
5559
 
        is already an ndarray.
 
6684
    out : MaskedArray
 
6685
        MaskedArray interpretation of `a`.
 
6686
 
 
6687
    See Also
 
6688
    --------
 
6689
    asarray : Similar to `asanyarray`, but does not conserve subclass.
 
6690
 
 
6691
    Examples
 
6692
    --------
 
6693
    >>> x = np.arange(10.).reshape(2, 5)
 
6694
    >>> x
 
6695
    array([[ 0.,  1.,  2.,  3.,  4.],
 
6696
           [ 5.,  6.,  7.,  8.,  9.]])
 
6697
    >>> np.ma.asanyarray(x)
 
6698
    masked_array(data =
 
6699
     [[ 0.  1.  2.  3.  4.]
 
6700
     [ 5.  6.  7.  8.  9.]],
 
6701
                 mask =
 
6702
     False,
 
6703
           fill_value = 1e+20)
 
6704
    >>> type(np.ma.asanyarray(x))
 
6705
    <class 'numpy.ma.core.MaskedArray'>
5560
6706
 
5561
6707
    """
5562
6708
    return masked_array(a, dtype=dtype, copy=False, keep_mask=True, subok=True)
5567
6713
#####--------------------------------------------------------------------------
5568
6714
def dump(a, F):
5569
6715
    """
5570
 
    Pickle the MaskedArray `a` to the file `F`.  `F` can either be
5571
 
    the handle of an exiting file, or a string representing a file
5572
 
    name.
 
6716
    Pickle a masked array to a file.
 
6717
 
 
6718
    This is a wrapper around ``cPickle.dump``.
 
6719
 
 
6720
    Parameters
 
6721
    ----------
 
6722
    a : MaskedArray
 
6723
        The array to be pickled.
 
6724
    F : str or file-like object
 
6725
        The file to pickle `a` to. If a string, the full path to the file.
5573
6726
 
5574
6727
    """
5575
 
    if not hasattr(F,'readline'):
 
6728
    if not hasattr(F, 'readline'):
5576
6729
        F = open(F, 'w')
5577
6730
    return cPickle.dump(a, F)
5578
6731
 
5579
6732
def dumps(a):
5580
6733
    """
5581
 
    Return a string corresponding to the pickling of the MaskedArray.
 
6734
    Return a string corresponding to the pickling of a masked array.
 
6735
 
 
6736
    This is a wrapper around ``cPickle.dumps``.
 
6737
 
 
6738
    Parameters
 
6739
    ----------
 
6740
    a : MaskedArray
 
6741
        The array for which the string representation of the pickle is
 
6742
        returned.
5582
6743
 
5583
6744
    """
5584
6745
    return cPickle.dumps(a)
5588
6749
    Wrapper around ``cPickle.load`` which accepts either a file-like object
5589
6750
    or a filename.
5590
6751
 
 
6752
    Parameters
 
6753
    ----------
 
6754
    F : str or file
 
6755
        The file or file name to load.
 
6756
 
 
6757
    See Also
 
6758
    --------
 
6759
    dump : Pickle an array
 
6760
 
 
6761
    Notes
 
6762
    -----
 
6763
    This is different from `numpy.load`, which does not use cPickle but loads
 
6764
    the NumPy binary .npy format.
 
6765
 
5591
6766
    """
5592
6767
    if not hasattr(F, 'readline'):
5593
 
        F = open(F,'r')
 
6768
        F = open(F, 'r')
5594
6769
    return cPickle.load(F)
5595
6770
 
5596
6771
def loads(strg):
5597
 
    "Load a pickle from the current string."""
 
6772
    """
 
6773
    Load a pickle from the current string.
 
6774
 
 
6775
    The result of ``cPickle.loads(strg)`` is returned.
 
6776
 
 
6777
    Parameters
 
6778
    ----------
 
6779
    strg : str
 
6780
        The string to load.
 
6781
 
 
6782
    See Also
 
6783
    --------
 
6784
    dumps : Return a string corresponding to the pickling of a masked array.
 
6785
 
 
6786
    """
5598
6787
    return cPickle.loads(strg)
5599
6788
 
5600
6789
################################################################################
5601
 
def fromfile(file, dtype=float, count=-1, sep=''):
 
6790
def fromfile(file, dtype=float, count= -1, sep=''):
5602
6791
    raise NotImplementedError("Not yet implemented. Sorry")
5603
6792
 
5604
6793
 
5605
6794
def fromflex(fxarray):
5606
6795
    """
5607
 
    Rebuilds a masked_array from a flexible-type array output by the '.torecord'
5608
 
    array
 
6796
    Build a masked array from a suitable flexible-type array.
 
6797
 
 
6798
    The input array has to have a data-type with ``_data`` and ``_mask``
 
6799
    fields. This type of array is output by `MaskedArray.toflex`.
 
6800
 
 
6801
    Parameters
 
6802
    ----------
 
6803
    fxarray : ndarray
 
6804
        The structured input array, containing ``_data`` and ``_mask``
 
6805
        fields. If present, other fields are discarded.
 
6806
 
 
6807
    Returns
 
6808
    -------
 
6809
    result : MaskedArray
 
6810
        The constructed masked array.
 
6811
 
 
6812
    See Also
 
6813
    --------
 
6814
    MaskedArray.toflex : Build a flexible-type array from a masked array.
 
6815
 
 
6816
    Examples
 
6817
    --------
 
6818
    >>> x = np.ma.array(np.arange(9).reshape(3, 3), mask=[0] + [1, 0] * 4)
 
6819
    >>> rec = x.toflex()
 
6820
    >>> rec
 
6821
    array([[(0, False), (1, True), (2, False)],
 
6822
           [(3, True), (4, False), (5, True)],
 
6823
           [(6, False), (7, True), (8, False)]],
 
6824
          dtype=[('_data', '<i4'), ('_mask', '|b1')])
 
6825
    >>> x2 = np.ma.fromflex(rec)
 
6826
    >>> x2
 
6827
    masked_array(data =
 
6828
     [[0 -- 2]
 
6829
     [-- 4 --]
 
6830
     [6 -- 8]],
 
6831
                 mask =
 
6832
     [[False  True False]
 
6833
     [ True False  True]
 
6834
     [False  True False]],
 
6835
           fill_value = 999999)
 
6836
 
 
6837
    Extra fields can be present in the structured array but are discarded:
 
6838
 
 
6839
    >>> dt = [('_data', '<i4'), ('_mask', '|b1'), ('field3', '<f4')]
 
6840
    >>> rec2 = np.zeros((2, 2), dtype=dt)
 
6841
    >>> rec2
 
6842
    array([[(0, False, 0.0), (0, False, 0.0)],
 
6843
           [(0, False, 0.0), (0, False, 0.0)]],
 
6844
          dtype=[('_data', '<i4'), ('_mask', '|b1'), ('field3', '<f4')])
 
6845
    >>> y = np.ma.fromflex(rec2)
 
6846
    >>> y
 
6847
    masked_array(data =
 
6848
     [[0 0]
 
6849
     [0 0]],
 
6850
                 mask =
 
6851
     [[False False]
 
6852
     [False False]],
 
6853
           fill_value = 999999)
 
6854
 
5609
6855
    """
5610
6856
    return masked_array(fxarray['_data'], mask=fxarray['_mask'])
5611
6857
 
5641
6887
 
5642
6888
arange = _convert2ma('arange')
5643
6889
clip = np.clip
 
6890
diff = np.diff
5644
6891
empty = _convert2ma('empty')
5645
6892
empty_like = _convert2ma('empty_like')
5646
6893
frombuffer = _convert2ma('frombuffer')