-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathma.py
2267 lines (1995 loc) · 73.9 KB
/
ma.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""MA: a facility for dealing with missing observations
MA is generally used as a numpy.array look-alike.
by Paul F. Dubois.
Copyright 1999, 2000, 2001 Regents of the University of California.
Released for unlimited redistribution.
Adapted for numpy_core 2005 by Travis Oliphant and
(mainly) Paul Dubois.
"""
import types, sys
import numpy.core.umath as umath
import numpy.core.fromnumeric as fromnumeric
from numpy.core.numeric import newaxis, ndarray, inf
from numpy.core.fromnumeric import amax, amin
from numpy.core.numerictypes import bool_, typecodes
import numpy.core.numeric as numeric
import warnings
# Ufunc domain lookup for __array_wrap__
ufunc_domain = {}
# Ufunc fills lookup for __array__
ufunc_fills = {}
MaskType = bool_
nomask = MaskType(0)
divide_tolerance = 1.e-35
class MAError (Exception):
def __init__ (self, args=None):
"Create an exception"
# The .args attribute must be a tuple.
if not isinstance(args, tuple):
args = (args,)
self.args = args
def __str__(self):
"Calculate the string representation"
return str(self.args[0])
__repr__ = __str__
class _MaskedPrintOption:
"One instance of this class, masked_print_option, is created."
def __init__ (self, display):
"Create the masked print option object."
self.set_display(display)
self._enabled = 1
def display (self):
"Show what prints for masked values."
return self._display
def set_display (self, s):
"set_display(s) sets what prints for masked values."
self._display = s
def enabled (self):
"Is the use of the display value enabled?"
return self._enabled
def enable(self, flag=1):
"Set the enabling flag to flag."
self._enabled = flag
def __str__ (self):
return str(self._display)
__repr__ = __str__
#if you single index into a masked location you get this object.
masked_print_option = _MaskedPrintOption('--')
# Use single element arrays or scalars.
default_real_fill_value = 1.e20
default_complex_fill_value = 1.e20 + 0.0j
default_character_fill_value = '-'
default_integer_fill_value = 999999
default_object_fill_value = '?'
def default_fill_value (obj):
"Function to calculate default fill value for an object."
if isinstance(obj, types.FloatType):
return default_real_fill_value
elif isinstance(obj, types.IntType) or isinstance(obj, types.LongType):
return default_integer_fill_value
elif isinstance(obj, types.StringType):
return default_character_fill_value
elif isinstance(obj, types.ComplexType):
return default_complex_fill_value
elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray):
x = obj.dtype.char
if x in typecodes['Float']:
return default_real_fill_value
if x in typecodes['Integer']:
return default_integer_fill_value
if x in typecodes['Complex']:
return default_complex_fill_value
if x in typecodes['Character']:
return default_character_fill_value
if x in typecodes['UnsignedInteger']:
return umath.absolute(default_integer_fill_value)
return default_object_fill_value
else:
return default_object_fill_value
def minimum_fill_value (obj):
"Function to calculate default fill value suitable for taking minima."
if isinstance(obj, types.FloatType):
return numeric.inf
elif isinstance(obj, types.IntType) or isinstance(obj, types.LongType):
return sys.maxint
elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray):
x = obj.dtype.char
if x in typecodes['Float']:
return numeric.inf
if x in typecodes['Integer']:
return sys.maxint
if x in typecodes['UnsignedInteger']:
return sys.maxint
else:
raise TypeError, 'Unsuitable type for calculating minimum.'
def maximum_fill_value (obj):
"Function to calculate default fill value suitable for taking maxima."
if isinstance(obj, types.FloatType):
return -inf
elif isinstance(obj, types.IntType) or isinstance(obj, types.LongType):
return -sys.maxint
elif isinstance(obj, MaskedArray) or isinstance(obj, ndarray):
x = obj.dtype.char
if x in typecodes['Float']:
return -inf
if x in typecodes['Integer']:
return -sys.maxint
if x in typecodes['UnsignedInteger']:
return 0
else:
raise TypeError, 'Unsuitable type for calculating maximum.'
def set_fill_value (a, fill_value):
"Set fill value of a if it is a masked array."
if isMaskedArray(a):
a.set_fill_value (fill_value)
def getmask (a):
"""Mask of values in a; could be nomask.
Returns nomask if a is not a masked array.
To get an array for sure use getmaskarray."""
if isinstance(a, MaskedArray):
return a.raw_mask()
else:
return nomask
def getmaskarray (a):
"""Mask of values in a; an array of zeros if mask is nomask
or not a masked array, and is a byte-sized integer.
Do not try to add up entries, for example.
"""
m = getmask(a)
if m is nomask:
return make_mask_none(shape(a))
else:
return m
def is_mask (m):
"""Is m a legal mask? Does not check contents, only type.
"""
try:
return m.dtype.type is MaskType
except AttributeError:
return False
def make_mask (m, copy=0, flag=0):
"""make_mask(m, copy=0, flag=0)
return m as a mask, creating a copy if necessary or requested.
Can accept any sequence of integers or nomask. Does not check
that contents must be 0s and 1s.
if flag, return nomask if m contains no true elements.
"""
if m is nomask:
return nomask
elif isinstance(m, ndarray):
if m.dtype.type is MaskType:
if copy:
result = numeric.array(m, dtype=MaskType, copy=copy)
else:
result = m
else:
result = m.astype(MaskType)
else:
result = filled(m, True).astype(MaskType)
if flag and not fromnumeric.sometrue(fromnumeric.ravel(result)):
return nomask
else:
return result
def make_mask_none (s):
"Return a mask of all zeros of shape s."
result = numeric.zeros(s, dtype=MaskType)
result.shape = s
return result
def mask_or (m1, m2):
"""Logical or of the mask candidates m1 and m2, treating nomask as false.
Result may equal m1 or m2 if the other is nomask.
"""
if m1 is nomask: return make_mask(m2)
if m2 is nomask: return make_mask(m1)
if m1 is m2 and is_mask(m1): return m1
return make_mask(umath.logical_or(m1, m2))
def filled (a, value = None):
"""a as a contiguous numeric array with any masked areas replaced by value
if value is None or the special element "masked", get_fill_value(a)
is used instead.
If a is already a contiguous numeric array, a itself is returned.
filled(a) can be used to be sure that the result is numeric when
passing an object a to other software ignorant of MA, in particular to
numeric itself.
"""
if isinstance(a, MaskedArray):
return a.filled(value)
elif isinstance(a, ndarray) and a.flags['CONTIGUOUS']:
return a
elif isinstance(a, types.DictType):
return numeric.array(a, 'O')
else:
return numeric.array(a)
def get_fill_value (a):
"""
The fill value of a, if it has one; otherwise, the default fill value
for that type.
"""
if isMaskedArray(a):
result = a.fill_value()
else:
result = default_fill_value(a)
return result
def common_fill_value (a, b):
"The common fill_value of a and b, if there is one, or None"
t1 = get_fill_value(a)
t2 = get_fill_value(b)
if t1 == t2: return t1
return None
# Domain functions return 1 where the argument(s) are not in the domain.
class domain_check_interval:
"domain_check_interval(a,b)(x) = true where x < a or y > b"
def __init__(self, y1, y2):
"domain_check_interval(a,b)(x) = true where x < a or y > b"
self.y1 = y1
self.y2 = y2
def __call__ (self, x):
"Execute the call behavior."
return umath.logical_or(umath.greater (x, self.y2),
umath.less(x, self.y1)
)
class domain_tan:
"domain_tan(eps) = true where abs(cos(x)) < eps)"
def __init__(self, eps):
"domain_tan(eps) = true where abs(cos(x)) < eps)"
self.eps = eps
def __call__ (self, x):
"Execute the call behavior."
return umath.less(umath.absolute(umath.cos(x)), self.eps)
class domain_greater:
"domain_greater(v)(x) = true where x <= v"
def __init__(self, critical_value):
"domain_greater(v)(x) = true where x <= v"
self.critical_value = critical_value
def __call__ (self, x):
"Execute the call behavior."
return umath.less_equal (x, self.critical_value)
class domain_greater_equal:
"domain_greater_equal(v)(x) = true where x < v"
def __init__(self, critical_value):
"domain_greater_equal(v)(x) = true where x < v"
self.critical_value = critical_value
def __call__ (self, x):
"Execute the call behavior."
return umath.less (x, self.critical_value)
class masked_unary_operation:
def __init__ (self, aufunc, fill=0, domain=None):
""" masked_unary_operation(aufunc, fill=0, domain=None)
aufunc(fill) must be defined
self(x) returns aufunc(x)
with masked values where domain(x) is true or getmask(x) is true.
"""
self.f = aufunc
self.fill = fill
self.domain = domain
self.__doc__ = getattr(aufunc, "__doc__", str(aufunc))
self.__name__ = getattr(aufunc, "__name__", str(aufunc))
ufunc_domain[aufunc] = domain
ufunc_fills[aufunc] = fill,
def __call__ (self, a, *args, **kwargs):
"Execute the call behavior."
# numeric tries to return scalars rather than arrays when given scalars.
m = getmask(a)
d1 = filled(a, self.fill)
if self.domain is not None:
m = mask_or(m, self.domain(d1))
result = self.f(d1, *args, **kwargs)
return masked_array(result, m)
def __str__ (self):
return "Masked version of " + str(self.f)
class domain_safe_divide:
def __init__ (self, tolerance=divide_tolerance):
self.tolerance = tolerance
def __call__ (self, a, b):
return umath.absolute(a) * self.tolerance >= umath.absolute(b)
class domained_binary_operation:
"""Binary operations that have a domain, like divide. These are complicated
so they are a separate class. They have no reduce, outer or accumulate.
"""
def __init__ (self, abfunc, domain, fillx=0, filly=0):
"""abfunc(fillx, filly) must be defined.
abfunc(x, filly) = x for all x to enable reduce.
"""
self.f = abfunc
self.domain = domain
self.fillx = fillx
self.filly = filly
self.__doc__ = getattr(abfunc, "__doc__", str(abfunc))
self.__name__ = getattr(abfunc, "__name__", str(abfunc))
ufunc_domain[abfunc] = domain
ufunc_fills[abfunc] = fillx, filly
def __call__(self, a, b):
"Execute the call behavior."
ma = getmask(a)
mb = getmask(b)
d1 = filled(a, self.fillx)
d2 = filled(b, self.filly)
t = self.domain(d1, d2)
if fromnumeric.sometrue(t, None):
d2 = where(t, self.filly, d2)
mb = mask_or(mb, t)
m = mask_or(ma, mb)
result = self.f(d1, d2)
return masked_array(result, m)
def __str__ (self):
return "Masked version of " + str(self.f)
class masked_binary_operation:
def __init__ (self, abfunc, fillx=0, filly=0):
"""abfunc(fillx, filly) must be defined.
abfunc(x, filly) = x for all x to enable reduce.
"""
self.f = abfunc
self.fillx = fillx
self.filly = filly
self.__doc__ = getattr(abfunc, "__doc__", str(abfunc))
ufunc_domain[abfunc] = None
ufunc_fills[abfunc] = fillx, filly
def __call__ (self, a, b, *args, **kwargs):
"Execute the call behavior."
m = mask_or(getmask(a), getmask(b))
d1 = filled(a, self.fillx)
d2 = filled(b, self.filly)
result = self.f(d1, d2, *args, **kwargs)
if isinstance(result, ndarray) \
and m.ndim != 0 \
and m.shape != result.shape:
m = mask_or(getmaskarray(a), getmaskarray(b))
return masked_array(result, m)
def reduce (self, target, axis=0, dtype=None):
"""Reduce target along the given axis with this function."""
m = getmask(target)
t = filled(target, self.filly)
if t.shape == ():
t = t.reshape(1)
if m is not nomask:
m = make_mask(m, copy=1)
m.shape = (1,)
if m is nomask:
t = self.f.reduce(t, axis)
else:
t = masked_array (t, m)
# XXX: "or t.dtype" below is a workaround for what appears
# XXX: to be a bug in reduce.
t = self.f.reduce(filled(t, self.filly), axis,
dtype=dtype or t.dtype)
m = umath.logical_and.reduce(m, axis)
if isinstance(t, ndarray):
return masked_array(t, m, get_fill_value(target))
elif m:
return masked
else:
return t
def outer (self, a, b):
"Return the function applied to the outer product of a and b."
ma = getmask(a)
mb = getmask(b)
if ma is nomask and mb is nomask:
m = nomask
else:
ma = getmaskarray(a)
mb = getmaskarray(b)
m = logical_or.outer(ma, mb)
d = self.f.outer(filled(a, self.fillx), filled(b, self.filly))
return masked_array(d, m)
def accumulate (self, target, axis=0):
"""Accumulate target along axis after filling with y fill value."""
t = filled(target, self.filly)
return masked_array (self.f.accumulate (t, axis))
def __str__ (self):
return "Masked version of " + str(self.f)
sqrt = masked_unary_operation(umath.sqrt, 0.0, domain_greater_equal(0.0))
log = masked_unary_operation(umath.log, 1.0, domain_greater(0.0))
log10 = masked_unary_operation(umath.log10, 1.0, domain_greater(0.0))
exp = masked_unary_operation(umath.exp)
conjugate = masked_unary_operation(umath.conjugate)
sin = masked_unary_operation(umath.sin)
cos = masked_unary_operation(umath.cos)
tan = masked_unary_operation(umath.tan, 0.0, domain_tan(1.e-35))
arcsin = masked_unary_operation(umath.arcsin, 0.0, domain_check_interval(-1.0, 1.0))
arccos = masked_unary_operation(umath.arccos, 0.0, domain_check_interval(-1.0, 1.0))
arctan = masked_unary_operation(umath.arctan)
# Missing from numeric
arcsinh = masked_unary_operation(umath.arcsinh)
arccosh = masked_unary_operation(umath.arccosh, 1.0, domain_greater_equal(1.0))
arctanh = masked_unary_operation(umath.arctanh, 0.0, domain_check_interval(-1.0+1e-15, 1.0-1e-15))
sinh = masked_unary_operation(umath.sinh)
cosh = masked_unary_operation(umath.cosh)
tanh = masked_unary_operation(umath.tanh)
absolute = masked_unary_operation(umath.absolute)
fabs = masked_unary_operation(umath.fabs)
negative = masked_unary_operation(umath.negative)
def nonzero(a):
"""returns the indices of the elements of a which are not zero
and not masked
"""
return numeric.asarray(filled(a, 0).nonzero())
around = masked_unary_operation(fromnumeric.round_)
floor = masked_unary_operation(umath.floor)
ceil = masked_unary_operation(umath.ceil)
logical_not = masked_unary_operation(umath.logical_not)
add = masked_binary_operation(umath.add)
subtract = masked_binary_operation(umath.subtract)
subtract.reduce = None
multiply = masked_binary_operation(umath.multiply, 1, 1)
divide = domained_binary_operation(umath.divide, domain_safe_divide(), 0, 1)
true_divide = domained_binary_operation(umath.true_divide, domain_safe_divide(), 0, 1)
floor_divide = domained_binary_operation(umath.floor_divide, domain_safe_divide(), 0, 1)
remainder = domained_binary_operation(umath.remainder, domain_safe_divide(), 0, 1)
fmod = domained_binary_operation(umath.fmod, domain_safe_divide(), 0, 1)
hypot = masked_binary_operation(umath.hypot)
arctan2 = masked_binary_operation(umath.arctan2, 0.0, 1.0)
arctan2.reduce = None
equal = masked_binary_operation(umath.equal)
equal.reduce = None
not_equal = masked_binary_operation(umath.not_equal)
not_equal.reduce = None
less_equal = masked_binary_operation(umath.less_equal)
less_equal.reduce = None
greater_equal = masked_binary_operation(umath.greater_equal)
greater_equal.reduce = None
less = masked_binary_operation(umath.less)
less.reduce = None
greater = masked_binary_operation(umath.greater)
greater.reduce = None
logical_and = masked_binary_operation(umath.logical_and)
alltrue = masked_binary_operation(umath.logical_and, 1, 1).reduce
logical_or = masked_binary_operation(umath.logical_or)
sometrue = logical_or.reduce
logical_xor = masked_binary_operation(umath.logical_xor)
bitwise_and = masked_binary_operation(umath.bitwise_and)
bitwise_or = masked_binary_operation(umath.bitwise_or)
bitwise_xor = masked_binary_operation(umath.bitwise_xor)
def rank (object):
return fromnumeric.rank(filled(object))
def shape (object):
return fromnumeric.shape(filled(object))
def size (object, axis=None):
return fromnumeric.size(filled(object), axis)
class MaskedArray (object):
"""Arrays with possibly masked values.
Masked values of 1 exclude the corresponding element from
any computation.
Construction:
x = array(data, dtype=None, copy=True, order=False,
mask = nomask, fill_value=None)
If copy=False, every effort is made not to copy the data:
If data is a MaskedArray, and argument mask=nomask,
then the candidate data is data.data and the
mask used is data.mask. If data is a numeric array,
it is used as the candidate raw data.
If dtype is not None and
is != data.dtype.char then a data copy is required.
Otherwise, the candidate is used.
If a data copy is required, raw data stored is the result of:
numeric.array(data, dtype=dtype.char, copy=copy)
If mask is nomask there are no masked values. Otherwise mask must
be convertible to an array of booleans with the same shape as x.
fill_value is used to fill in masked values when necessary,
such as when printing and in method/function filled().
The fill_value is not used for computation within this module.
"""
__array_priority__ = 10.1
def __init__(self, data, dtype=None, copy=True, order=False,
mask=nomask, fill_value=None):
"""array(data, dtype=None, copy=True, order=False, mask=nomask, fill_value=None)
If data already a numeric array, its dtype becomes the default value of dtype.
"""
if dtype is None:
tc = None
else:
tc = numeric.dtype(dtype)
need_data_copied = copy
if isinstance(data, MaskedArray):
c = data.data
if tc is None:
tc = c.dtype
elif tc != c.dtype:
need_data_copied = True
if mask is nomask:
mask = data.mask
elif mask is not nomask: #attempting to change the mask
need_data_copied = True
elif isinstance(data, ndarray):
c = data
if tc is None:
tc = c.dtype
elif tc != c.dtype:
need_data_copied = True
else:
need_data_copied = False #because I'll do it now
c = numeric.array(data, dtype=tc, copy=True, order=order)
tc = c.dtype
if need_data_copied:
if tc == c.dtype:
self._data = numeric.array(c, dtype=tc, copy=True, order=order)
else:
self._data = c.astype(tc)
else:
self._data = c
if mask is nomask:
self._mask = nomask
self._shared_mask = 0
else:
self._mask = make_mask (mask)
if self._mask is nomask:
self._shared_mask = 0
else:
self._shared_mask = (self._mask is mask)
nm = size(self._mask)
nd = size(self._data)
if nm != nd:
if nm == 1:
self._mask = fromnumeric.resize(self._mask, self._data.shape)
self._shared_mask = 0
elif nd == 1:
self._data = fromnumeric.resize(self._data, self._mask.shape)
self._data.shape = self._mask.shape
else:
raise MAError, "Mask and data not compatible."
elif nm == 1 and shape(self._mask) != shape(self._data):
self.unshare_mask()
self._mask.shape = self._data.shape
self.set_fill_value(fill_value)
def __array__ (self, t=None, context=None):
"Special hook for numeric. Converts to numeric if possible."
if self._mask is not nomask:
if fromnumeric.ravel(self._mask).any():
if context is None:
warnings.warn("Cannot automatically convert masked array to "\
"numeric because data\n is masked in one or "\
"more locations.");
return self._data
#raise MAError, \
# """Cannot automatically convert masked array to numeric because data
# is masked in one or more locations.
# """
else:
func, args, i = context
fills = ufunc_fills.get(func)
if fills is None:
raise MAError, "%s not known to ma" % func
return self.filled(fills[i])
else: # Mask is all false
# Optimize to avoid future invocations of this section.
self._mask = nomask
self._shared_mask = 0
if t:
return self._data.astype(t)
else:
return self._data
def __array_wrap__ (self, array, context=None):
"""Special hook for ufuncs.
Wraps the numpy array and sets the mask according to
context.
"""
if context is None:
return MaskedArray(array, copy=False, mask=nomask)
func, args = context[:2]
domain = ufunc_domain[func]
m = reduce(mask_or, [getmask(a) for a in args])
if domain is not None:
m = mask_or(m, domain(*[getattr(a, '_data', a)
for a in args]))
if m is not nomask:
try:
shape = array.shape
except AttributeError:
pass
else:
if m.shape != shape:
m = reduce(mask_or, [getmaskarray(a) for a in args])
return MaskedArray(array, copy=False, mask=m)
def _get_shape(self):
"Return the current shape."
return self._data.shape
def _set_shape (self, newshape):
"Set the array's shape."
self._data.shape = newshape
if self._mask is not nomask:
self._mask = self._mask.copy()
self._mask.shape = newshape
def _get_flat(self):
"""Calculate the flat value.
"""
if self._mask is nomask:
return masked_array(self._data.ravel(), mask=nomask,
fill_value = self.fill_value())
else:
return masked_array(self._data.ravel(),
mask=self._mask.ravel(),
fill_value = self.fill_value())
def _set_flat (self, value):
"x.flat = value"
y = self.ravel()
y[:] = value
def _get_real(self):
"Get the real part of a complex array."
if self._mask is nomask:
return masked_array(self._data.real, mask=nomask,
fill_value = self.fill_value())
else:
return masked_array(self._data.real, mask=self._mask,
fill_value = self.fill_value())
def _set_real (self, value):
"x.real = value"
y = self.real
y[...] = value
def _get_imaginary(self):
"Get the imaginary part of a complex array."
if self._mask is nomask:
return masked_array(self._data.imag, mask=nomask,
fill_value = self.fill_value())
else:
return masked_array(self._data.imag, mask=self._mask,
fill_value = self.fill_value())
def _set_imaginary (self, value):
"x.imaginary = value"
y = self.imaginary
y[...] = value
def __str__(self):
"""Calculate the str representation, using masked for fill if
it is enabled. Otherwise fill with fill value.
"""
if masked_print_option.enabled():
f = masked_print_option
# XXX: Without the following special case masked
# XXX: would print as "[--]", not "--". Can we avoid
# XXX: checks for masked by choosing a different value
# XXX: for the masked singleton? 2005-01-05 -- sasha
if self is masked:
return str(f)
m = self._mask
if m is not nomask and m.shape == () and m:
return str(f)
# convert to object array to make filled work
self = self.astype(object)
else:
f = self.fill_value()
res = self.filled(f)
return str(res)
def __repr__(self):
"""Calculate the repr representation, using masked for fill if
it is enabled. Otherwise fill with fill value.
"""
with_mask = """\
array(data =
%(data)s,
mask =
%(mask)s,
fill_value=%(fill)s)
"""
with_mask1 = """\
array(data = %(data)s,
mask = %(mask)s,
fill_value=%(fill)s)
"""
without_mask = """array(
%(data)s)"""
without_mask1 = """array(%(data)s)"""
n = len(self.shape)
if self._mask is nomask:
if n <= 1:
return without_mask1 % {'data':str(self.filled())}
return without_mask % {'data':str(self.filled())}
else:
if n <= 1:
return with_mask % {
'data': str(self.filled()),
'mask': str(self._mask),
'fill': str(self.fill_value())
}
return with_mask % {
'data': str(self.filled()),
'mask': str(self._mask),
'fill': str(self.fill_value())
}
without_mask1 = """array(%(data)s)"""
if self._mask is nomask:
return without_mask % {'data':str(self.filled())}
else:
return with_mask % {
'data': str(self.filled()),
'mask': str(self._mask),
'fill': str(self.fill_value())
}
def __float__(self):
"Convert self to float."
self.unmask()
if self._mask is not nomask:
raise MAError, 'Cannot convert masked element to a Python float.'
return float(self.data.item())
def __int__(self):
"Convert self to int."
self.unmask()
if self._mask is not nomask:
raise MAError, 'Cannot convert masked element to a Python int.'
return int(self.data.item())
def __getitem__(self, i):
"Get item described by i. Not a copy as in previous versions."
self.unshare_mask()
m = self._mask
dout = self._data[i]
if m is nomask:
try:
if dout.size == 1:
return dout
else:
return masked_array(dout, fill_value=self._fill_value)
except AttributeError:
return dout
mi = m[i]
if mi.size == 1:
if mi:
return masked
else:
return dout
else:
return masked_array(dout, mi, fill_value=self._fill_value)
# --------
# setitem and setslice notes
# note that if value is masked, it means to mask those locations.
# setting a value changes the mask to match the value in those locations.
def __setitem__(self, index, value):
"Set item described by index. If value is masked, mask those locations."
d = self._data
if self is masked:
raise MAError, 'Cannot alter masked elements.'
if value is masked:
if self._mask is nomask:
self._mask = make_mask_none(d.shape)
self._shared_mask = False
else:
self.unshare_mask()
self._mask[index] = True
return
m = getmask(value)
value = filled(value).astype(d.dtype)
d[index] = value
if m is nomask:
if self._mask is not nomask:
self.unshare_mask()
self._mask[index] = False
else:
if self._mask is nomask:
self._mask = make_mask_none(d.shape)
self._shared_mask = True
else:
self.unshare_mask()
self._mask[index] = m
def __nonzero__(self):
"""returns true if any element is non-zero or masked
"""
# XXX: This changes bool conversion logic from MA.
# XXX: In MA bool(a) == len(a) != 0, but in numpy
# XXX: scalars do not have len
m = self._mask
d = self._data
return bool(m is not nomask and m.any()
or d is not nomask and d.any())
def __len__ (self):
"""Return length of first dimension. This is weird but Python's
slicing behavior depends on it."""
return len(self._data)
def __and__(self, other):
"Return bitwise_and"
return bitwise_and(self, other)
def __or__(self, other):
"Return bitwise_or"
return bitwise_or(self, other)
def __xor__(self, other):
"Return bitwise_xor"
return bitwise_xor(self, other)
__rand__ = __and__
__ror__ = __or__
__rxor__ = __xor__
def __abs__(self):
"Return absolute(self)"
return absolute(self)
def __neg__(self):
"Return negative(self)"
return negative(self)
def __pos__(self):
"Return array(self)"
return array(self)
def __add__(self, other):
"Return add(self, other)"
return add(self, other)
__radd__ = __add__
def __mod__ (self, other):
"Return remainder(self, other)"
return remainder(self, other)
def __rmod__ (self, other):
"Return remainder(other, self)"
return remainder(other, self)
def __lshift__ (self, n):
return left_shift(self, n)
def __rshift__ (self, n):
return right_shift(self, n)
def __sub__(self, other):
"Return subtract(self, other)"
return subtract(self, other)
def __rsub__(self, other):
"Return subtract(other, self)"
return subtract(other, self)
def __mul__(self, other):
"Return multiply(self, other)"
return multiply(self, other)
__rmul__ = __mul__
def __div__(self, other):
"Return divide(self, other)"
return divide(self, other)
def __rdiv__(self, other):
"Return divide(other, self)"
return divide(other, self)
def __truediv__(self, other):
"Return divide(self, other)"
return true_divide(self, other)
def __rtruediv__(self, other):
"Return divide(other, self)"
return true_divide(other, self)
def __floordiv__(self, other):
"Return divide(self, other)"
return floor_divide(self, other)
def __rfloordiv__(self, other):
"Return divide(other, self)"
return floor_divide(other, self)
def __pow__(self, other, third=None):
"Return power(self, other, third)"
return power(self, other, third)
def __sqrt__(self):
"Return sqrt(self)"
return sqrt(self)
def __iadd__(self, other):
"Add other to self in place."
t = self._data.dtype.char
f = filled(other, 0)
t1 = f.dtype.char
if t == t1:
pass
elif t in typecodes['Integer']:
if t1 in typecodes['Integer']:
f = f.astype(t)
else:
raise TypeError, 'Incorrect type for in-place operation.'
elif t in typecodes['Float']:
if t1 in typecodes['Integer']:
f = f.astype(t)
elif t1 in typecodes['Float']:
f = f.astype(t)
else:
raise TypeError, 'Incorrect type for in-place operation.'
elif t in typecodes['Complex']:
if t1 in typecodes['Integer']:
f = f.astype(t)
elif t1 in typecodes['Float']:
f = f.astype(t)
elif t1 in typecodes['Complex']:
f = f.astype(t)
else:
raise TypeError, 'Incorrect type for in-place operation.'
else:
raise TypeError, 'Incorrect type for in-place operation.'
if self._mask is nomask:
self._data += f
m = getmask(other)
self._mask = m
self._shared_mask = m is not nomask
else:
result = add(self, masked_array(f, mask=getmask(other)))
self._data = result.data