/
data.py
2671 lines (1991 loc) · 74.8 KB
/
data.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
import itertools
import logging
import numpy
import netCDF4
from .. import core
from ..mixin.container import Container
from ..mixin.netcdf import NetCDFHDF5
from ..constants import masked as cfdm_masked
from ..functions import abspath
from ..decorators import (
_inplace_enabled,
_inplace_enabled_define_and_cleanup,
_manage_log_level_via_verbosity,
)
from . import abstract
from . import NumpyArray
logger = logging.getLogger(__name__)
class Data(Container, NetCDFHDF5, core.Data):
"""An orthogonal multidimensional array with masking and units.
.. versionadded:: (cfdm) 1.7.0
"""
def __init__(
self,
array=None,
units=None,
calendar=None,
fill_value=None,
source=None,
copy=True,
dtype=None,
mask=None,
_use_array=True,
**kwargs,
):
"""**Initialisation**
:Parameters:
array: data_like, optional
The array of values.
{{data_like}}
Ignored if the *source* parameter is set.
*Parameter example:*
``array=[34.6]``
*Parameter example:*
``array=[[1, 2], [3, 4]]``
*Parameter example:*
``array=numpy.ma.arange(10).reshape(2, 1, 5)``
units: `str`, optional
The physical units of the data. Ignored if the *source*
parameter is set.
The units may also be set after initialisation with the
`set_units` method.
*Parameter example:*
``units='km hr-1'``
*Parameter example:*
``units='days since 2018-12-01'``
calendar: `str`, optional
The calendar for reference time units. Ignored if the
*source* parameter is set.
The calendar may also be set after initialisation with the
`set_calendar` method.
*Parameter example:*
``calendar='360_day'``
fill_value: optional
The fill value of the data. By default, or if set to
`None`, the `numpy` fill value appropriate to the array's
data type will be used (see
`numpy.ma.default_fill_value`). Ignored if the *source*
parameter is set.
The fill value may also be set after initialisation with
the `set_fill_value` method.
*Parameter example:*
``fill_value=-999.``
dtype: data-type, optional
The desired data-type for the data. By default the
data-type will be inferred form the *array* parameter.
The data-type may also be set after initialisation
with the `dtype` attribute.
*Parameter example:*
``dtype=float``
*Parameter example:*
``dtype='float32'``
*Parameter example:*
``dtype=numpy.dtype('i2')``
mask: data_like, optional
Apply this mask to the data given by the *array*
parameter. By default, or if *mask* is `None`, no mask
is applied. May be any data_like object that
broadcasts to *array*. Masking will be carried out
where mask elements evaluate to `True`.
{{data_like}}
This mask will applied in addition to any mask already
defined by the *array* parameter.
source: optional
Initialise the array, units, calendar and fill value
from those of *source*.
{{init source}}
copy: `bool`, optional
If False then do not deep copy input parameters prior
to initialisation. By default arguments are deep
copied.
kwargs: ignored
Not used. Present to facilitate subclassing.
"""
if dtype is not None:
if isinstance(array, abstract.Array):
array = array.array
elif not isinstance(array, numpy.ndarray):
array = numpy.asanyarray(array)
array = array.astype(dtype)
array = NumpyArray(array)
if mask is not None:
if isinstance(array, abstract.Array):
array = array.array
elif not isinstance(array, numpy.ndarray):
array = numpy.asanyarray(array)
array = numpy.ma.array(array, mask=mask)
array = NumpyArray(array)
super().__init__(
array=array,
units=units,
calendar=calendar,
fill_value=fill_value,
source=source,
copy=copy,
_use_array=_use_array,
)
self._initialise_netcdf(source)
def __array__(self, *dtype):
"""The numpy array interface.
.. versionadded:: (cfdm) 1.7.0
:Parameters:
dtype: optional
Typecode or data-type to which the array is cast.
:Returns:
`numpy.ndarray`
An independent numpy array of the data.
**Examples:**
>>> d = {{package}}.{{class}}([1, 2, 3])
>>> a = numpy.array(d)
>>> print(type(a))
<class 'numpy.ndarray'>
>>> a[0] = -99
>>> d
<{{repr}}{{class}}(3): [1, 2, 3]>
>>> b = numpy.array(d, float)
>>> print(b)
[1. 2. 3.]
"""
array = self.array
if not dtype:
return array
else:
return array.astype(dtype[0], copy=False)
def __repr__(self):
"""Called by the `repr` built-in function.
x.__repr__() <==> repr(x)
"""
try:
shape = self.shape
except AttributeError:
shape = ""
else:
shape = str(shape)
shape = shape.replace(",)", ")")
return f"<{ self.__class__.__name__}{shape}: {self}>"
def __getitem__(self, indices):
"""Return a subspace of the data defined by indices.
d.__getitem__(indices) <==> d[indices]
Indexing follows rules that are very similar to the numpy indexing
rules, the only differences being:
* An integer index i takes the i-th element but does not reduce
the rank by one.
* When two or more dimensions' indices are sequences of integers
then these indices work independently along each dimension
(similar to the way vector subscripts work in Fortran). This is
the same behaviour as indexing on a Variable object of the
netCDF4 package.
.. versionadded:: (cfdm) 1.7.0
.. seealso:: `__setitem__`, `_parse_indices`
:Returns:
`{{class}}`
The subspace of the data.
**Examples:**
>>> d = {{package}}.{{class}}(numpy.arange(100, 190).reshape(1, 10, 9))
>>> d.shape
(1, 10, 9)
>>> d[:, :, 1].shape
(1, 10, 1)
>>> d[:, 0].shape
(1, 1, 9)
>>> d[..., 6:3:-1, 3:6].shape
(1, 3, 3)
>>> d[0, [2, 9], [4, 8]].shape
(1, 2, 2)
>>> d[0, :, -2].shape
(1, 10, 1)
"""
indices = self._parse_indices(indices)
array = self._get_Array(None)
if array is None:
raise ValueError("No array!!")
array = array[tuple(indices)]
out = self.copy(array=False)
out._set_Array(array, copy=False)
if out.shape != self.shape:
# Delete hdf5 chunksizes
out.nc_clear_hdf5_chunksizes()
return out
def __int__(self):
"""Called by the `int` built-in function.
x.__int__() <==> int(x)
"""
if self.size != 1:
raise TypeError(
"only length-1 arrays can be converted to "
f"Python scalars. Got {self}"
)
return int(self.array)
def __iter__(self):
"""Called when an iterator is required.
x.__iter__() <==> iter(x)
**Examples:**
>>> d = {{package}}.{{class}}([1, 2, 3], 'metres')
>>> for e in d:
... print(repr(e))
...
1
2
3
>>> d = {{package}}.{{class}}([[1, 2], [4, 5]], 'metres')
>>> for e in d:
... print(repr(e))
...
<{{repr}}Data(2): [1, 2] metres>
<{{repr}}Data(2): [4, 5] metres>
>>> d = {{package}}.{{class}}(34, 'metres')
>>> for e in d:
... print(repr(e))
Traceback (most recent call last):
...
TypeError: Iteration over 0-d Data
"""
ndim = self.ndim
if not ndim:
raise TypeError(f"Iteration over 0-d {self.__class__.__name__}")
if ndim == 1:
i = iter(self.array)
while 1:
try:
yield next(i)
except StopIteration:
return
else:
# ndim > 1
for n in range(self.shape[0]):
out = self[n, ...]
out.squeeze(0, inplace=True)
yield out
def __setitem__(self, indices, value):
"""Assign to data elements defined by indices.
d.__setitem__(indices, x) <==> d[indices]=x
Indexing follows rules that are very similar to the numpy indexing
rules, the only differences being:
* An integer index i takes the i-th element but does not reduce
the rank by one.
* When two or more dimensions' indices are sequences of integers
then these indices work independently along each dimension
(similar to the way vector subscripts work in Fortran). This is
the same behaviour as indexing on a Variable object of the
netCDF4 package.
**Broadcasting**
The value, or values, being assigned must be broadcastable to the
shape defined by the indices, using the numpy broadcasting rules.
**Missing data**
Data array elements may be set to missing values by assigning them
to `masked`. Missing values may be unmasked by assigning them to
any other value.
.. versionadded:: (cfdm) 1.7.0
.. seealso:: `__getitem__`, `_parse_indices`
:Returns:
`None`
**Examples:**
>>> d = {{package}}.{{class}}(numpy.arange(100, 190).reshape(1, 10, 9))
>>> d.shape
(1, 10, 9)
>>> d[:, :, 1] = -10
>>> d[:, 0] = range(9)
>>> d[..., 6:3:-1, 3:6] = numpy.arange(-18, -9).reshape(3, 3)
>>> d[0, [2, 9], [4, 8]] = {{package}}.{{class}}([[-2, -3]])
>>> d[0, :, -2] = {{package}}.masked
"""
indices = self._parse_indices(indices)
array = self.array
if value is cfdm_masked or numpy.ma.isMA(value):
# The data is not masked but the assignment is masking
# elements, so turn the non-masked array into a masked
# one.
array = array.view(numpy.ma.MaskedArray)
self._set_subspace(array, indices, numpy.asanyarray(value))
self._set_Array(array, copy=False)
def __str__(self):
"""Called by the `str` built-in function.
x.__str__() <==> str(x)
"""
units = self.get_units(None)
calendar = self.get_calendar(None)
isreftime = False
if units is not None:
if isinstance(units, str):
isreftime = "since" in units
else:
units = "??"
try:
first = self.first_element()
except Exception:
out = ""
if units and not isreftime:
out += f" {units}"
if calendar:
out += f" {calendar}"
return out
size = self.size
shape = self.shape
ndim = self.ndim
open_brackets = "[" * ndim
close_brackets = "]" * ndim
mask = [False, False, False]
if size == 1:
if isreftime:
# Convert reference time to date-time
if first is numpy.ma.masked:
first = 0
mask[0] = True
try:
first = type(self)(
numpy.ma.array(first, mask=mask[0]), units, calendar
).datetime_array
except (ValueError, OverflowError):
first = "??"
out = f"{open_brackets}{first}{close_brackets}"
else:
last = self.last_element()
if isreftime:
if last is numpy.ma.masked:
last = 0
mask[-1] = True
# Convert reference times to date-times
try:
first, last = type(self)(
numpy.ma.array(
[first, last], mask=(mask[0], mask[-1])
),
units,
calendar,
).datetime_array
except (ValueError, OverflowError):
first, last = ("??", "??")
if size > 3:
out = f"{open_brackets}{first}, ..., {last}{close_brackets}"
elif shape[-1:] == (3,):
middle = self.second_element()
if isreftime:
# Convert reference time to date-time
if middle is numpy.ma.masked:
middle = 0
mask[1] = True
try:
middle = type(self)(
numpy.ma.array(middle, mask=mask[1]),
units,
calendar,
).datetime_array
except (ValueError, OverflowError):
middle = "??"
out = (
f"{open_brackets}{first}, {middle}, {last}{close_brackets}"
)
elif size == 3:
out = f"{open_brackets}{first}, ..., {last}{close_brackets}"
else:
out = f"{open_brackets}{first}, {last}{close_brackets}"
if isreftime:
if calendar:
out += f" {calendar}"
elif units:
out += f" {units}"
return out
# ----------------------------------------------------------------
# Private methods
# ----------------------------------------------------------------
def _item(self, index):
"""Return an element of the data as a scalar.
It is assumed, but not checked, that the given index selects
exactly one element.
:Parameters:
index:
:Returns:
The selected element of the data.
**Examples:**
>>> d = {{package}}.{{class}}([[1, 2, 3]], 'km')
>>> x = d._item((0, -1))
>>> print(x, type(x))
3 <class 'int'>
>>> x = d._item((0, 1))
>>> print(x, type(x))
2 <class 'int'>
>>> d[0, 1] = {{package}}.masked
>>> d._item((slice(None), slice(1, 2)))
masked
"""
array = self[index].array
if not numpy.ma.isMA(array):
return array.item()
mask = array.mask
if mask is numpy.ma.nomask or not mask.item():
return array.item()
return numpy.ma.masked
def _parse_axes(self, axes):
"""Parses the data axes and returns valid non-duplicate axes.
:Parameters:
axes: (sequence of) `int`
The axes of the data.
{{axes int examples}}
:Returns:
`tuple`
**Examples:**
>>> d._parse_axes(1)
(1,)
>>> e._parse_axes([0, 2])
(0, 2)
"""
if axes is None:
return axes
ndim = self.ndim
if isinstance(axes, int):
axes = (axes,)
axes2 = []
for axis in axes:
if 0 <= axis < ndim:
axes2.append(axis)
elif -ndim <= axis < 0:
axes2.append(axis + ndim)
else:
raise ValueError(f"Invalid axis: {axis!r}")
# Check for duplicate axes
n = len(axes2)
if n > len(set(axes2)) >= 1:
raise ValueError(f"Duplicate axis: {axes2}")
return tuple(axes2)
def _set_Array(self, array, copy=True):
"""Set the array.
.. seealso:: `_set_CompressedArray`
:Parameters:
array: `numpy` array_like or `Array`, optional
The array to be inserted.
:Returns:
`None`
**Examples:**
>>> d._set_Array(a)
"""
if not isinstance(array, abstract.Array):
if not isinstance(array, numpy.ndarray):
array = numpy.asanyarray(array)
array = NumpyArray(array)
super()._set_Array(array, copy=copy)
def _set_CompressedArray(self, array, copy=True):
"""Set the compressed array.
.. versionadded:: (cfdm) 1.7.11
.. seealso:: `_set_Array`
:Parameters:
array: subclass of `CompressedArray`
The compressed array to be inserted.
:Returns:
`None`
**Examples:**
>>> d._set_CompressedArray(a)
"""
self._set_Array(array, copy=copy)
@classmethod
def _set_subspace(cls, array, indices, value):
"""Set a subspace of the data array defined by indices."""
axes_with_list_indices = [
i for i, x in enumerate(indices) if not isinstance(x, slice)
]
if len(axes_with_list_indices) < 2:
# --------------------------------------------------------
# At most one axis has a list-of-integers index so we can
# do a normal numpy assignment
# --------------------------------------------------------
array[tuple(indices)] = value
else:
# --------------------------------------------------------
# At least two axes have list-of-integers indices so we
# can't do a normal numpy assignment
# --------------------------------------------------------
indices1 = indices[:]
for i, x in enumerate(indices):
if i in axes_with_list_indices:
# This index is a list of integers
y = []
args = [iter(x)] * 2
for start, stop in itertools.zip_longest(*args):
if not stop:
y.append(slice(start, start + 1))
else:
step = stop - start
stop += 1
y.append(slice(start, stop, step))
indices1[i] = y
else:
indices1[i] = (x,)
if numpy.size(value) == 1:
for i in itertools.product(*indices1):
array[i] = value
else:
indices2 = []
ndim_difference = array.ndim - numpy.ndim(value)
for i, n in enumerate(numpy.shape(value)):
if n == 1:
indices2.append((slice(None),))
elif i + ndim_difference in axes_with_list_indices:
y = []
start = 0
while start < n:
stop = start + 2
y.append(slice(start, stop))
start = stop
indices2.append(y)
else:
indices2.append((slice(None),))
for i, j in zip(
itertools.product(*indices1), itertools.product(*indices2)
):
array[i] = value[j]
# ----------------------------------------------------------------
# Attributes
# ----------------------------------------------------------------
@property
def compressed_array(self):
"""Returns an independent numpy array of the compressed data.
.. versionadded:: (cfdm) 1.7.0
.. seealso:: `get_compressed_axes`, `get_compressed_dimension`,
`get_compression_type`
:Returns:
`numpy.ndarray`
An independent numpy array of the compressed data.
**Examples:**
>>> a = d.compressed_array
"""
ca = self._get_Array(None)
if not ca.get_compression_type():
raise ValueError("not compressed: can't get compressed array")
return ca.compressed_array
@property
def datetime_array(self):
"""Returns an independent numpy array of datetimes.
Specifically, returns an independent numpy array containing
the date-time objects corresponding to times since a reference
date.
Only applicable for reference time units.
If the calendar has not been set then the CF default calendar of
'standard' (i.e. the mixed Gregorian/Julian calendar as defined by
Udunits) will be used.
Conversions are carried out with the `netCDF4.num2date` function.
.. versionadded:: (cfdm) 1.7.0
.. seealso:: `array`, `datetime_as_string`
:Returns:
`numpy.ndarray`
An independent numpy array of the date-time objects.
**Examples:**
>>> d = {{package}}.{{class}}([31, 62, 90], units='days since 2018-12-01')
>>> a = d.datetime_array
>>> print(a)
[cftime.DatetimeGregorian(2019, 1, 1, 0, 0, 0, 0)
cftime.DatetimeGregorian(2019, 2, 1, 0, 0, 0, 0)
cftime.DatetimeGregorian(2019, 3, 1, 0, 0, 0, 0)]
>>> print(a[1])
2019-02-01 00:00:00
>>> d = {{package}}.{{class}}(
... [31, 62, 90], units='days since 2018-12-01', calendar='360_day')
>>> a = d.datetime_array
>>> print(a)
[cftime.Datetime360Day(2019, 1, 2, 0, 0, 0, 0)
cftime.Datetime360Day(2019, 2, 3, 0, 0, 0, 0)
cftime.Datetime360Day(2019, 3, 1, 0, 0, 0, 0)]
>>> print(a[1])
2019-02-03 00:00:00
"""
array = self.array
mask = None
if numpy.ma.isMA(array):
# num2date has issues if the mask is nomask
mask = array.mask
if mask is numpy.ma.nomask or not numpy.ma.is_masked(array):
mask = None
array = array.view(numpy.ndarray)
if mask is not None and not array.ndim:
# Fix until num2date copes with scalar aarrays containing
# missing data
return array
array = netCDF4.num2date(
array,
units=self.get_units(None),
calendar=self.get_calendar("standard"),
only_use_cftime_datetimes=True,
)
if mask is None:
# There is no missing data
array = numpy.array(array, dtype=object)
else:
# There is missing data
array = numpy.ma.masked_where(mask, array)
if not numpy.ndim(array):
array = numpy.ma.masked_all((), dtype=object)
return array
@property
def datetime_as_string(self):
"""Returns an independent numpy array with datetimes as strings.
Specifically, returns an independent numpy array containing
string representations of times since a reference date.
Only applicable for reference time units.
If the calendar has not been set then the CF default calendar of
"standard" (i.e. the mixed Gregorian/Julian calendar as defined by
Udunits) will be used.
Conversions are carried out with the `netCDF4.num2date` function.
.. versionadded:: (cfdm) 1.8.0
.. seealso:: `array`, `datetime_array`
:Returns:
`numpy.ndarray`
An independent numpy array of the date-time strings.
**Examples:**
>>> d = {{package}}.{{class}}([31, 62, 90], units='days since 2018-12-01')
>>> print(d.datetime_as_string)
['2019-01-01 00:00:00' '2019-02-01 00:00:00' '2019-03-01 00:00:00']
>>> d = {{package}}.{{class}}(
... [31, 62, 90], units='days since 2018-12-01', calendar='360_day')
>>> print(d.datetime_as_string)
['2019-01-02 00:00:00' '2019-02-03 00:00:00' '2019-03-01 00:00:00']
"""
return self.datetime_array.astype(str)
@property
def mask(self):
"""The Boolean missing data mask of the data array.
The Boolean mask has True where the data array has missing data
and False otherwise.
:Returns:
`{{class}}`
The Boolean mask as data.
**Examples:**
>>> d = {{package}}.{{class}}(numpy.ma.array(
... [[280.0, -99, -99, -99],
... [281.0, 279.0, 278.0, 279.5]],
... mask=[[0, 1, 1, 1], [0, 0, 0, 0]]
... ))
>>> d
<{{repr}}Data(2, 4): [[280.0, ..., 279.5]]>
>>> print(d.array)
[[280.0 -- -- --]
[281.0 279.0 278.0 279.5]]
>>> d.mask
<{{repr}}Data(2, 4): [[False, ..., False]]>
>>> print(d.mask.array)
[[False True True True]
[False False False False]]
"""
return type(self)(numpy.ma.getmaskarray(self.array))
# ----------------------------------------------------------------
# Methods
# ----------------------------------------------------------------
def any(self):
"""Test whether any data array elements evaluate to True.
Performs a logical or over the data array and returns the
result. Masked values are considered as False during computation.
:Returns:
`bool`
`True` if any data array elements evaluate to True,
otherwise `False`.
**Examples:**
>>> d = {{package}}.{{class}}([[0, 0, 0]])
>>> d.any()
False
>>> d[0, 0] = {{package}}.masked
>>> print(d.array)
[[-- 0 0]]
>>> d.any()
False
>>> d[0, 1] = 3
>>> print(d.array)
[[-- 3 0]]
>>> d.any()
True
>>> d[...] = {{package}}.masked
>>> print(d.array)
[[-- -- --]]
>>> d.any()
False
"""
masked = self.array.any()
if masked is numpy.ma.masked:
masked = False
return masked
@_inplace_enabled(default=False)
def apply_masking(
self,
fill_values=None,
valid_min=None,
valid_max=None,
valid_range=None,
inplace=False,
):
"""Apply masking.
Masking is applied according to the values of the keyword
parameters.
Elements that are already masked remain so.
.. versionadded:: (cfdm) 1.8.2
.. seealso:: `get_fill_value`, `mask`
:Parameters:
fill_values: `bool` or sequence of scalars, optional
Specify values that will be set to missing data. Data
elements exactly equal to any of the values are set to
missing data.
If True then the value returned by the `get_fill_value`
method, if such a value exists, is used.
Zero or more values may be provided in a sequence of
scalars.
*Parameter example:*
Specify a fill value of 999: ``fill_values=[999]``
*Parameter example:*
Specify fill values of 999 and -1.0e30:
``fill_values=[999, -1.0e30]``
*Parameter example:*
Use the fill value already set for the data:
``fill_values=True``
*Parameter example:*
Use no fill values: ``fill_values=False`` or
``fill_value=[]``
valid_min: number, optional
A scalar specifying the minimum valid value. Data elements
strictly less than this number will be set to missing
data.
valid_max: number, optional
A scalar specifying the maximum valid value. Data elements
strictly greater than this number will be set to missing