/
data.py
12520 lines (9638 loc) · 363 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 logging
import math
import operator
from functools import partial, reduce
from itertools import product
from numbers import Integral
from operator import mul
import cfdm
import cftime
import dask.array as da
import numpy as np
from dask import compute, delayed # noqa: F401
from dask.array import Array
from dask.array.core import normalize_chunks
from dask.base import is_dask_collection, tokenize
from dask.highlevelgraph import HighLevelGraph
from dask.optimization import cull
from ..cfdatetime import dt as cf_dt
from ..constants import masked as cf_masked
from ..decorators import (
_deprecated_kwarg_check,
_display_or_return,
_inplace_enabled,
_inplace_enabled_define_and_cleanup,
_manage_log_level_via_verbosity,
)
from ..functions import (
_DEPRECATION_ERROR_KWARGS,
_section,
atol,
default_netCDF_fillvals,
free_memory,
parse_indices,
rtol,
)
from ..mixin_container import Container
from ..units import Units
from .collapse import Collapse
from .creation import generate_axis_identifiers, to_dask
from .dask_utils import (
_da_ma_allclose,
cf_contains,
cf_dt2rt,
cf_harden_mask,
cf_percentile,
cf_rt2dt,
cf_soften_mask,
cf_units,
cf_where,
)
from .mixin import DataClassDeprecationsMixin
from .utils import (
YMDhms,
collapse,
conform_units,
convert_to_datetime,
convert_to_reftime,
first_non_missing_value,
is_numeric_dtype,
new_axis_identifier,
scalar_masked_array,
)
logger = logging.getLogger(__name__)
# --------------------------------------------------------------------
# Constants
# --------------------------------------------------------------------
_year_length = 365.242198781
_month_length = _year_length / 12
_empty_set = set()
_units_None = Units()
_units_1 = Units("1")
_units_radians = Units("radians")
_month_units = ("month", "months")
_year_units = ("year", "years", "yr")
_dtype_float32 = np.dtype("float32")
_dtype_float = np.dtype(float)
_dtype_bool = np.dtype(bool)
_DEFAULT_CHUNKS = "auto"
_DEFAULT_HARDMASK = True
# Contstants used to specify which `Data` components should be cleared
# when a new dask array is set. See `Data._clear_after_dask_update`
# for details.
_NONE = 0 # = 0b0000
_ARRAY = 1 # = 0b0001
_CACHE = 2 # = 0b0010
_ALL = 15 # = 0b1111
class Data(DataClassDeprecationsMixin, Container, cfdm.Data):
"""An N-dimensional data array with units and masked values.
* Contains an N-dimensional, indexable and broadcastable array with
many similarities to a `numpy` array.
* Contains the units of the array elements.
* Supports masked arrays, regardless of whether or not it was
initialised with a masked array.
* Stores and operates on data arrays which are larger than the
available memory.
**Indexing**
A data array is indexable in a similar way to numpy array:
>>> d.shape
(12, 19, 73, 96)
>>> d[...].shape
(12, 19, 73, 96)
>>> d[slice(0, 9), 10:0:-2, :, :].shape
(9, 5, 73, 96)
There are three extensions to the numpy indexing functionality:
* Size 1 dimensions are never removed by indexing.
An integer index i takes the i-th element but does not reduce the
rank of the output array by one:
>>> d.shape
(12, 19, 73, 96)
>>> d[0, ...].shape
(1, 19, 73, 96)
>>> d[:, 3, slice(10, 0, -2), 95].shape
(12, 1, 5, 1)
Size 1 dimensions may be removed with the `squeeze` method.
* The indices for each axis work independently.
When more than one dimension's slice is a 1-d boolean sequence or
1-d sequence of integers, then these indices work independently
along each dimension (similar to the way vector subscripts work in
Fortran), rather than by their elements:
>>> d.shape
(12, 19, 73, 96)
>>> d[0, :, [0, 1], [0, 13, 27]].shape
(1, 19, 2, 3)
* Boolean indices may be any object which exposes the numpy array
interface.
>>> d.shape
(12, 19, 73, 96)
>>> d[..., d[0, 0, 0]>d[0, 0, 0].min()]
**Cyclic axes**
"""
def __init__(
self,
array=None,
units=None,
calendar=None,
fill_value=None,
hardmask=_DEFAULT_HARDMASK,
chunks=_DEFAULT_CHUNKS,
dt=False,
source=None,
copy=True,
dtype=None,
mask=None,
to_memory=False,
init_options=None,
_use_array=True,
):
"""**Initialisation**
:Parameters:
array: optional
The array of values. May be any scalar or array-like
object, including another `Data` instance.
*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` or `Units`, optional
The physical units of the data. if a `Units` object is
provided then this an also set the calendar.
The units (without the calendar) 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.
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`).
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')``
.. versionadded:: 3.0.4
mask: 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 scalar or array-like object
(such as a `list`, `numpy` array or `Data` instance)
that is broadcastable to the shape of *array*. Masking
will be carried out where the mask elements evaluate
to `True`.
This mask will applied in addition to any mask already
defined by the *array* parameter.
.. versionadded:: 3.0.5
{{init source: optional}}
hardmask: `bool`, optional
If False then the mask is soft. By default the mask is
hard.
dt: `bool`, optional
If True then strings (such as ``'1990-12-01 12:00'``)
given by the *array* parameter are re-interpreted as
date-time objects. By default they are not.
{{init copy: `bool`, optional}}
{{chunks: `int`, `tuple`, `dict` or `str`, optional}}
.. versionadded:: 3.14.0
to_memory: `bool`, optional
If True then ensure that the original data are in
memory, rather than on disk.
If the original data are on disk, then reading data
into memory during initialisation will slow down the
initialisation process, but can considerably improve
downstream performance by avoiding the need for
independent reads for every dask chunk, each time the
data are computed.
In general, setting *to_memory* to True is not the same
as calling the `persist` of the newly created `Data`
object, which also decompresses data compressed by
convention and computes any data type, mask and
date-time modifications.
If the input *array* is a `dask.array.Array` object
then *to_memory* is ignored.
.. versionadded:: 3.14.0
init_options: `dict`, optional
Provide optional keyword arguments to methods and
functions called during the initialisation process. A
dictionary key identifies a method or function. The
corresponding value is another dictionary whose
key/value pairs are the keyword parameter names and
values to be applied.
Supported keys are:
* ``'from_array'``: Provide keyword arguments to
the `dask.array.from_array` function. This is used
when initialising data that is not already a dask
array and is not compressed by convention.
* ``'first_non_missing_value'``: Provide keyword
arguments to the
`cf.data.utils.first_non_missing_value`
function. This is used when the input array contains
date-time strings or objects, and may affect
performance.
*Parameter example:*
``{'from_array': {'inline_array': True}}``
chunk: deprecated at version 3.14.0
Use the *chunks* parameter instead.
**Examples**
>>> d = cf.Data(5)
>>> d = cf.Data([1,2,3], units='K')
>>> import numpy
>>> d = cf.Data(numpy.arange(10).reshape(2,5),
... units=Units('m/s'), fill_value=-999)
>>> d = cf.Data('fly')
>>> d = cf.Data(tuple('fly'))
"""
if source is None and isinstance(array, self.__class__):
source = array
if init_options is None:
init_options = {}
if source is not None:
try:
array = source._get_Array(None)
except AttributeError:
array = None
super().__init__(
source=source, _use_array=_use_array and array is not None
)
if _use_array:
try:
array = source.to_dask_array()
except (AttributeError, TypeError):
pass
else:
self._set_dask(array, copy=copy, clear=_NONE)
else:
self._del_dask(None)
# Set the mask hardness
self.hardmask = getattr(source, "hardmask", _DEFAULT_HARDMASK)
return
super().__init__(
array=array,
fill_value=fill_value,
_use_array=False,
)
# Set the units
units = Units(units, calendar=calendar)
self._Units = units
# Set the mask hardness
self.hardmask = hardmask
if array is None:
# No data has been set
return
try:
ndim = array.ndim
except AttributeError:
ndim = np.ndim(array)
# Create the _cyclic attribute: identifies which axes are
# cyclic (and therefore allow cyclic slicing). It must be a
# subset of the axes given by the _axes attribute. If an axis
# is removed from _axes then it must also be removed from
# _cyclic.
#
# Never change the value of the _cyclic attribute in-place.
self._cyclic = _empty_set
# Create the _axes attribute: an ordered sequence of unique
# (within this `Data` instance) names for each array axis.
self._axes = generate_axis_identifiers(ndim)
if not _use_array:
return
# Still here? Then create a dask array and store it.
# Find out if the input data is compressed by convention
try:
compressed = array.get_compression_type()
except AttributeError:
compressed = ""
if compressed:
if init_options.get("from_array"):
raise ValueError(
"Can't define 'from_array' initialisation options "
"for compressed input arrays"
)
# Bring the compressed data into memory without
# decompressing it
if to_memory:
try:
array = array.to_memory()
except AttributeError:
pass
if self._is_abstract_Array_subclass(array):
# Save the input array in case it's useful later. For
# compressed input arrays this will contain extra information,
# such as a count or index variable.
self._set_Array(array)
# Cast the input data as a dask array
kwargs = init_options.get("from_array", {})
if "chunks" in kwargs:
raise TypeError(
"Can't define 'chunks' in the 'from_array' initialisation "
"options. Use the 'chunks' parameter instead."
)
array = to_dask(array, chunks, **kwargs)
# Find out if we have an array of date-time objects
if units.isreftime:
dt = True
first_value = None
if not dt and array.dtype.kind == "O":
kwargs = init_options.get("first_non_missing_value", {})
first_value = first_non_missing_value(array, **kwargs)
if first_value is not None:
dt = hasattr(first_value, "timetuple")
# Convert string or object date-times to floating point
# reference times
if dt and array.dtype.kind in "USO":
array, units = convert_to_reftime(array, units, first_value)
# Reset the units
self._Units = units
# Store the dask array
self._set_dask(array, clear=_NONE)
# Override the data type
if dtype is not None:
self.dtype = dtype
# Apply a mask
if mask is not None:
self.where(mask, cf_masked, inplace=True)
@property
def dask_compressed_array(self):
"""Returns a dask array of the compressed data.
.. versionadded:: 3.14.0
:Returns:
`dask.array.Array`
The compressed data.
**Examples**
>>> a = d.dask_compressed_array
"""
ca = self.source(None)
if ca is None or not ca.get_compression_type():
raise ValueError("not compressed: can't get compressed dask array")
return ca.to_dask_array()
def __contains__(self, value):
"""Membership test operator ``in``
x.__contains__(y) <==> y in x
Returns True if the scalar *value* is contained anywhere in
the data. If *value* is not scalar then an exception is
raised.
**Performance**
`__contains__` causes all delayed operations to be computed
unless *value* is a `Data` object with incompatible units, in
which case `False` is always returned.
**Examples**
>>> d = cf.Data([[0, 1, 2], [3, 4, 5]], 'm')
>>> 4 in d
True
>>> 4.0 in d
True
>>> cf.Data(5) in d
True
>>> cf.Data(5, 'm') in d
True
>>> cf.Data(0.005, 'km') in d
True
>>> 99 in d
False
>>> cf.Data(2, 'seconds') in d
False
>>> [1] in d
Traceback (most recent call last):
...
TypeError: elementwise comparison failed; must test against a scalar, not [1]
>>> [1, 2] in d
Traceback (most recent call last):
...
TypeError: elementwise comparison failed; must test against a scalar, not [1, 2]
>>> d = cf.Data(["foo", "bar"])
>>> 'foo' in d
True
>>> 'xyz' in d
False
"""
# Check that value is scalar by seeing if its shape is ()
shape = getattr(value, "shape", None)
if shape is None:
if isinstance(value, str):
# Strings are scalars, even though they have a len().
shape = ()
else:
try:
len(value)
except TypeError:
# value has no len() so assume that it is a scalar
shape = ()
else:
# value has a len() so assume that it is not a scalar
shape = True
elif is_dask_collection(value) and math.isnan(value.size):
# value is a dask array with unknown size, so calculate
# the size. This is acceptable, as we're going to compute
# it anyway at the end of this method.
value.compute_chunk_sizes()
shape = value.shape
if shape:
raise TypeError(
"elementwise comparison failed; must test against a scalar, "
f"not {value!r}"
)
# If value is a scalar Data object then conform its units
if isinstance(value, self.__class__):
self_units = self.Units
value_units = value.Units
if value_units.equivalent(self_units):
if not value_units.equals(self_units):
value = value.copy()
value.Units = self_units
elif value_units:
# No need to check the dask array if the value units
# are incompatible
return False
value = value.to_dask_array()
dx = self.to_dask_array()
out_ind = tuple(range(dx.ndim))
dx_ind = out_ind
dx = da.blockwise(
cf_contains,
out_ind,
dx,
dx_ind,
value,
(),
adjust_chunks={i: 1 for i in out_ind},
dtype=bool,
)
return bool(dx.any())
@property
def _atol(self):
"""Return the current value of the `cf.atol` function."""
return atol().value
@property
def _rtol(self):
"""Return the current value of the `cf.rtol` function."""
return rtol().value
def _is_abstract_Array_subclass(self, array):
"""Whether or not an array is a type of abstract Array.
:Parameters:
array:
:Returns:
`bool`
"""
return isinstance(array, cfdm.Array)
def __data__(self):
"""Returns a new reference to self."""
return self
def __float__(self):
"""Called to implement the built-in function `float`
x.__float__() <==> float(x)
**Performance**
`__float__` causes all delayed operations to be executed,
unless the dask array size is already known to be greater than
1.
"""
return float(self.to_dask_array())
def __int__(self):
"""Called to implement the built-in function `int`
x.__int__() <==> int(x)
**Performance**
`__int__` causes all delayed operations to be executed, unless
the dask array size is already known to be greater than 1.
"""
return int(self.to_dask_array())
def __iter__(self):
"""Called when an iterator is required.
x.__iter__() <==> iter(x)
**Performance**
If the shape of the data is unknown then it is calculated
immediately by executing all delayed operations.
**Examples**
>>> d = cf.Data([1, 2, 3], 'metres')
>>> for e in d:
... print(repr(e))
...
<CF Data(1): [1] metres>
<CF Data(1): [2] metres>
<CF Data(1): [3] metres>
>>> d = cf.Data([[1, 2], [3, 4]], 'metres')
>>> for e in d:
... print(repr(e))
...
<CF Data: [1, 2] metres>
<CF Data: [3, 4] metres>
>>> d = cf.Data(99, 'metres')
>>> for e in d:
... print(repr(e))
...
Traceback (most recent call last):
...
TypeError: iteration over a 0-d Data
"""
try:
n = len(self)
except TypeError:
raise TypeError(f"iteration over a 0-d {self.__class__.__name__}")
if self.__keepdims_indexing__:
for i in range(n):
out = self[i]
out.reshape(out.shape[1:], inplace=True)
yield out
else:
for i in range(n):
yield self[i]
def __len__(self):
"""Called to implement the built-in function `len`.
x.__len__() <==> len(x)
**Performance**
If the shape of the data is unknown then it is calculated
immediately by executing all delayed operations.
**Examples**
>>> len(cf.Data([1, 2, 3]))
3
>>> len(cf.Data([[1, 2, 3]]))
1
>>> len(cf.Data([[1, 2, 3], [4, 5, 6]]))
2
>>> len(cf.Data(1))
Traceback (most recent call last):
...
TypeError: len() of unsized object
"""
dx = self.to_dask_array()
if math.isnan(dx.size):
logger.debug("Computing data len: Performance may be degraded")
dx.compute_chunk_sizes()
return len(dx)
def __bool__(self):
"""Truth value testing and the built-in operation `bool`
x.__bool__() <==> bool(x)
**Performance**
`__bool__` causes all delayed operations to be computed.
**Examples**
>>> bool(cf.Data(1.5))
True
>>> bool(cf.Data([[False]]))
False
"""
size = self.size
if size != 1:
raise ValueError(
f"The truth value of a {self.__class__.__name__} with {size} "
"elements is ambiguous. Use d.any() or d.all()"
)
return bool(self.to_dask_array())
def __repr__(self):
"""Called by the `repr` built-in function.
x.__repr__() <==> repr(x)
"""
return super().__repr__().replace("<", "<CF ", 1)
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 `netCDF4.Variable` object.
**Performance**
If the shape of the data is unknown then it is calculated
immediately by executing all delayed operations.
. seealso:: `__setitem__`, `__keepdims_indexing__`,
`__orthogonal_indexing__`
:Returns:
`Data`
The subspace of the data.
**Examples**
>>> import numpy
>>> d = Data(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)
"""
if indices is Ellipsis:
return self.copy()
ancillary_mask = ()
try:
arg = indices[0]
except (IndexError, TypeError):
pass
else:
if isinstance(arg, str) and arg == "mask":
ancillary_mask = indices[1]
indices = indices[2:]
shape = self.shape
keepdims = self.__keepdims_indexing__
indices, roll = parse_indices(
shape, indices, cyclic=True, keepdims=keepdims
)
axes = self._axes
cyclic_axes = self._cyclic
# ------------------------------------------------------------
# Roll axes with cyclic slices
# ------------------------------------------------------------
if roll:
# For example, if slice(-2, 3) has been requested on a
# cyclic axis, then we roll that axis by two points and
# apply the slice(0, 5) instead.
if not cyclic_axes.issuperset([axes[i] for i in roll]):
raise IndexError(
"Can't take a cyclic slice of a non-cyclic axis"
)
new = self.roll(
axis=tuple(roll.keys()), shift=tuple(roll.values())
)
dx = new.to_dask_array()
else:
new = self.copy(array=False)
dx = self.to_dask_array()
# ------------------------------------------------------------
# Subspace the dask array
# ------------------------------------------------------------
if self.__orthogonal_indexing__:
# Apply 'orthogonal indexing': indices that are 1-d arrays
# or lists subspace along each dimension
# independently. This behaviour is similar to Fortran, but
# different to dask.
axes_with_list_indices = [
i
for i, x in enumerate(indices)
if isinstance(x, list) or getattr(x, "shape", False)
]
n_axes_with_list_indices = len(axes_with_list_indices)
if n_axes_with_list_indices < 2:
# At most one axis has a list/1-d array index so do a
# normal dask subspace
dx = dx[tuple(indices)]
else:
# At least two axes have list/1-d array indices so we
# can't do a normal dask subspace
# Subspace axes which have list/1-d array indices
for axis in axes_with_list_indices:
dx = da.take(dx, indices[axis], axis=axis)
if n_axes_with_list_indices < len(indices):
# Subspace axes which don't have list/1-d array
# indices. (Do this after subspacing axes which do
# have list/1-d array indices, in case
# __keepdims_indexing__ is False.)
slice_indices = [
slice(None) if i in axes_with_list_indices else x
for i, x in enumerate(indices)
]
dx = dx[tuple(slice_indices)]
else:
raise NotImplementedError(
"Non-orthogonal indexing has not yet been implemented"
)
# ------------------------------------------------------------
# Set the subspaced dask array
# ------------------------------------------------------------
new._set_dask(dx)
# ------------------------------------------------------------
# Get the axis identifiers for the subspace
# ------------------------------------------------------------
shape0 = shape
if keepdims:
new_axes = axes
else:
new_axes = [
axis
for axis, x in zip(axes, indices)
if not isinstance(x, Integral) and getattr(x, "shape", True)
]
if new_axes != axes:
new._axes = new_axes
cyclic_axes = new._cyclic
if cyclic_axes:
shape0 = [
n for n, axis in zip(shape, axes) if axis in new_axes
]
# ------------------------------------------------------------
# Cyclic axes that have been reduced in size are no longer
# considered to be cyclic
# ------------------------------------------------------------
if cyclic_axes:
x = [
axis
for axis, n0, n1 in zip(new_axes, shape0, new.shape)
if axis in cyclic_axes and n0 != n1
]
if x:
# Never change the value of the _cyclic attribute
# in-place
new._cyclic = cyclic_axes.difference(x)
# ------------------------------------------------------------
# Apply ancillary masks
# ------------------------------------------------------------
for mask in ancillary_mask:
new.where(mask, cf_masked, None, inplace=True)
if new.shape != self.shape:
# Delete hdf5 chunksizes when the shape has changed.
new.nc_clear_hdf5_chunksizes()
return new
def __setitem__(self, indices, value):
"""Implement indexed assignment.
x.__setitem__(indices, y) <==> x[indices]=y
Assignment to data array elements defined by indices.
Elements of a data array may be changed by assigning values to
a subspace. See `__getitem__` for details on how to define
subspace of the data array.
.. note:: Currently at most one dimension's assignment index
may be a 1-d array of integers or booleans. This is
is different to `__getitem__`, which by default
applies 'orthogonal indexing' when multiple indices
of 1-d array of integers or booleans are present.
**Missing data**
The treatment of missing data elements during assignment to a
subspace depends on the value of the `hardmask` attribute. If
it is True then masked elements will not be unmasked,
otherwise masked elements may be set to any value.
In either case, unmasked elements may be set, (including
missing data).
Unmasked elements may be set to missing data by assignment to
the `cf.masked` constant or by assignment to a value which
contains masked elements.
**Performance**