-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathaccessor.py
2209 lines (1852 loc) · 74.1 KB
/
accessor.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 functools
import inspect
import itertools
import re
import warnings
from collections import ChainMap
from datetime import datetime
from typing import (
Any,
Callable,
Dict,
Hashable,
Iterable,
List,
Mapping,
MutableMapping,
Set,
Tuple,
TypeVar,
Union,
cast,
)
import xarray as xr
from xarray import DataArray, Dataset
from xarray.core.arithmetic import SupportsArithmetic
from .criteria import cf_role_criteria, coordinate_criteria, regex
from .helpers import bounds_to_vertices
from .options import OPTIONS
from .utils import (
_get_version,
_is_datetime_like,
always_iterable,
invert_mappings,
parse_cell_methods_attr,
parse_cf_standard_name_table,
)
#: Classes wrapped by cf_xarray.
_WRAPPED_CLASSES = (
xr.core.resample.Resample,
xr.core.groupby.GroupBy,
xr.core.rolling.Rolling,
xr.core.rolling.Coarsen,
xr.core.weighted.Weighted,
)
#: `axis` names understood by cf_xarray
_AXIS_NAMES = ("X", "Y", "Z", "T")
#: `coordinate` types understood by cf_xarray.
_COORD_NAMES = ("longitude", "latitude", "vertical", "time")
#: Cell measures understood by cf_xarray.
_CELL_MEASURES = ("area", "volume")
ATTRS = {
"X": {"axis": "X"},
"T": {"axis": "T", "standard_name": "time"},
"Y": {"axis": "Y"},
"Z": {"axis": "Z"},
"latitude": {"units": "degrees_north", "standard_name": "latitude"},
"longitude": {"units": "degrees_east", "standard_name": "longitude"},
}
ATTRS["time"] = ATTRS["T"]
ATTRS["vertical"] = ATTRS["Z"]
# Type for Mapper functions
Mapper = Callable[[Union[DataArray, Dataset], str], List[str]]
# Type for decorators
F = TypeVar("F", bound=Callable[..., Any])
def apply_mapper(
mappers: Union[Mapper, Tuple[Mapper, ...]],
obj: Union[DataArray, Dataset],
key: Any,
error: bool = True,
default: Any = None,
) -> List[Any]:
"""
Applies a mapping function; does error handling / returning defaults.
Expects the mapper function to raise an error if passed a bad key.
It should return a list in all other cases including when there are no
results for a good key.
"""
if not isinstance(key, str):
if default is None:
raise ValueError("`default` must be provided when `key` is not a string.")
return list(always_iterable(default))
default = [] if default is None else list(always_iterable(default))
def _apply_single_mapper(mapper):
try:
results = mapper(obj, key)
except KeyError as e:
if error or "I expected only one." in repr(e):
raise e
else:
results = []
return results
if not isinstance(mappers, Iterable):
mappers = (mappers,)
# apply a sequence of mappers
# if the mapper fails, it *should* return an empty list
# if the mapper raises an error, that is processed based on `error`
results = []
for mapper in mappers:
results.append(_apply_single_mapper(mapper))
flat = list(itertools.chain(*results))
# de-duplicate
if all(not isinstance(r, DataArray) for r in flat):
results = list(set(flat))
else:
results = flat
nresults = any(bool(v) for v in [results])
if not nresults:
if error:
raise KeyError(
f"cf-xarray cannot interpret key {key!r}. Perhaps some needed attributes are missing."
)
else:
# none of the mappers worked. Return the default
return default
return results
def _get_groupby_time_accessor(var: Union[DataArray, Dataset], key: str) -> List[str]:
"""
Time variable accessor e.g. 'T.month'
"""
"""
Helper method for when our key name is of the nature "T.month" and we want to
isolate the "T" for coordinate mapping
Parameters
----------
var : DataArray, Dataset
DataArray belonging to the coordinate to be checked
key : str, [e.g. "T.month"]
key to check for.
Returns
-------
List[str], Variable name(s) in parent xarray object that matches axis or coordinate `key` appended by the frequency extension (e.g. ".month")
Notes
-----
Returns an empty list if there is no frequency extension specified.
"""
if "." in key:
key, ext = key.split(".", 1)
results = apply_mapper((_get_all,), var, key, error=False)
if len(results) > 1:
raise KeyError(f"Multiple results received for {key}.")
return [v + "." + ext for v in results]
else:
return []
def _get_custom_criteria(
obj: Union[DataArray, Dataset], key: str, criteria=None
) -> List[str]:
"""
Translate from axis, coord, or custom name to variable name optionally
using ``custom_criteria``
Parameters
----------
obj : DataArray, Dataset
key : str
key to check for.
criteria : dict, optional
Criteria to use to map from variable to attributes describing the
variable. An example is coordinate_criteria which maps coordinates to
their attributes and attribute values. If user has defined
custom_criteria, this will be used by default.
Returns
-------
List[str], Variable name(s) in parent xarray object that matches axis, coordinate, or custom `key`
"""
if isinstance(obj, DataArray):
obj = obj._to_temp_dataset()
if criteria is None:
if not OPTIONS["custom_criteria"]:
return []
criteria = OPTIONS["custom_criteria"]
if criteria is not None:
criteria = always_iterable(criteria, allowed=(tuple, list, set))
criteria = ChainMap(*criteria)
results: Set = set()
if key in criteria:
for criterion, patterns in criteria[key].items():
for var in obj.variables:
if re.match(patterns, obj[var].attrs.get(criterion, "")):
results.update((var,))
# also check name specifically since not in attributes
elif criterion == "name" and re.match(patterns, var):
results.update((var,))
return list(results)
def _get_axis_coord(obj: Union[DataArray, Dataset], key: str) -> List[str]:
"""
Translate from axis or coord name to variable name
Parameters
----------
obj : DataArray, Dataset
DataArray belonging to the coordinate to be checked
key : str, ["X", "Y", "Z", "T", "longitude", "latitude", "vertical", "time"]
key to check for.
error : bool
raise errors when key is not found or interpretable. Use False and provide default
to replicate dict.get(k, None).
default : Any
default value to return when error is False.
Returns
-------
List[str], Variable name(s) in parent xarray object that matches axis or coordinate `key`
Notes
-----
This functions checks for the following attributes in order
- `standard_name` (CF option)
- `_CoordinateAxisType` (from THREDDS)
- `axis` (CF option)
- `positive` (CF standard for non-pressure vertical coordinate)
References
----------
MetPy's parse_cf
"""
valid_keys = _COORD_NAMES + _AXIS_NAMES
if key not in valid_keys:
raise KeyError(
f"cf_xarray did not understand key {key!r}. Expected one of {valid_keys!r}"
)
search_in = set()
if "coordinates" in obj.encoding:
search_in.update(obj.encoding["coordinates"].split(" "))
if "coordinates" in obj.attrs:
search_in.update(obj.attrs["coordinates"].split(" "))
if not search_in:
search_in = set(obj.coords)
# maybe only do this for key in _AXIS_NAMES?
search_in.update(obj.indexes)
search_in = search_in & set(obj.coords)
results: Set = set()
for coord in search_in:
var = obj.coords[coord]
if key in coordinate_criteria:
for criterion, expected in coordinate_criteria[key].items():
if var.attrs.get(criterion, None) in expected:
results.update((coord,))
if criterion == "units":
# deal with pint-backed objects
units = getattr(var.data, "units", None)
if units in expected:
results.update((coord,))
return list(results)
def _get_measure(obj: Union[DataArray, Dataset], key: str) -> List[str]:
"""
Translate from cell measures to appropriate variable name.
This function interprets the ``cell_measures`` attribute on DataArrays.
Parameters
----------
obj : DataArray, Dataset
DataArray belonging to the coordinate to be checked
key : str
key to check for.
Returns
-------
List[str], Variable name(s) in parent xarray object that matches axis or coordinate `key`
"""
if isinstance(obj, DataArray):
obj = obj._to_temp_dataset()
results = set()
for var in obj.variables:
da = obj[var]
if "cell_measures" in da.attrs:
attr = da.attrs["cell_measures"]
measures = parse_cell_methods_attr(attr)
if key in measures:
results.update([measures[key]])
if isinstance(results, str):
return [results]
return list(results)
def _get_bounds(obj: Union[DataArray, Dataset], key: str) -> List[str]:
"""
Translate from key (either CF key or variable name) to its bounds' variable names.
This function interprets the ``bounds`` attribute on DataArrays.
Parameters
----------
obj : DataArray, Dataset
DataArray belonging to the coordinate to be checked
key : str
key to check for.
Returns
-------
List[str], Variable name(s) in parent xarray object that are bounds of `key`
"""
results = set()
for var in apply_mapper(_get_all, obj, key, error=False, default=[key]):
if "bounds" in obj[var].attrs:
results |= {obj[var].attrs["bounds"]}
return list(results)
def _get_with_standard_name(
obj: Union[DataArray, Dataset], name: Union[str, List[str]]
) -> List[str]:
"""returns a list of variable names with standard name == name."""
if name is None:
return []
varnames = []
if isinstance(obj, DataArray):
obj = obj.coords.to_dataset()
for vname, var in obj.variables.items():
stdname = var.attrs.get("standard_name", None)
if stdname == name:
varnames.append(str(vname))
return varnames
def _get_all(obj: Union[DataArray, Dataset], key: str) -> List[str]:
"""
One or more of ('X', 'Y', 'Z', 'T', 'longitude', 'latitude', 'vertical', 'time',
'area', 'volume'), or arbitrary measures, or standard names
"""
all_mappers = (
_get_custom_criteria,
functools.partial(_get_custom_criteria, criteria=cf_role_criteria),
_get_axis_coord,
_get_measure,
_get_with_standard_name,
)
results = apply_mapper(all_mappers, obj, key, error=False, default=None)
return results
def _get_dims(obj: Union[DataArray, Dataset], key: str) -> List[str]:
"""
One or more of ('X', 'Y', 'Z', 'T', 'longitude', 'latitude', 'vertical', 'time',
'area', 'volume'), or arbitrary measures, or standard names present in .dims
"""
return [k for k in _get_all(obj, key) if k in obj.dims]
def _get_indexes(obj: Union[DataArray, Dataset], key: str) -> List[str]:
"""
One or more of ('X', 'Y', 'Z', 'T', 'longitude', 'latitude', 'vertical', 'time',
'area', 'volume'), or arbitrary measures, or standard names present in .indexes
"""
return [k for k in _get_all(obj, key) if k in obj.indexes]
def _get_coords(obj: Union[DataArray, Dataset], key: str) -> List[str]:
"""
One or more of ('X', 'Y', 'Z', 'T', 'longitude', 'latitude', 'vertical', 'time',
'area', 'volume'), or arbitrary measures, or standard names present in .coords
"""
return [k for k in _get_all(obj, key) if k in obj.coords]
def _variables(func: F) -> F:
@functools.wraps(func)
def wrapper(obj: Union[DataArray, Dataset], key: str) -> List[DataArray]:
return [obj[k] for k in func(obj, key)]
return cast(F, wrapper)
def _single(func: F) -> F:
@functools.wraps(func)
def wrapper(obj: Union[DataArray, Dataset], key: str):
results = func(obj, key)
if len(results) > 1:
raise KeyError(
f"Multiple results for {key!r} found: {results!r}. I expected only one."
)
elif len(results) == 0:
raise KeyError(f"No results found for {key!r}.")
return results
wrapper.__doc__ = (
func.__doc__.replace("One or more of", "One of")
if func.__doc__
else func.__doc__
)
return cast(F, wrapper)
#: Default mappers for common keys.
_DEFAULT_KEY_MAPPERS: Mapping[str, Tuple[Mapper, ...]] = {
"dim": (_get_dims,),
"dims": (_get_dims,), # transpose
"drop_dims": (_get_dims,), # drop_dims
"dims_dict": (_get_dims,), # swap_dims, rename_dims
"shifts": (_get_dims,), # shift, roll
"pad_width": (_get_dims,), # shift, roll
"names": (_get_all,), # set_coords, reset_coords, drop_vars
"name_dict": (_get_all,), # rename, rename_vars
"new_name_or_name_dict": (_get_all,), # rename
"labels": (_get_indexes,), # drop_sel
"coords": (_get_dims,), # interp
"indexers": (_get_dims,), # sel, isel, reindex
# "indexes": (_single(_get_dims),), # set_index this decodes keys but not values
"dims_or_levels": (_get_dims,), # reset_index
"window": (_get_dims,), # rolling_exp
"coord": (_single(_get_coords),), # differentiate, integrate
"group": (_single(_get_all), _get_groupby_time_accessor), # groupby
"indexer": (_single(_get_indexes),), # resample
"variables": (_get_all,), # sortby
"weights": (_variables(_single(_get_all)),), # type: ignore
"chunks": (_get_dims,), # chunk
}
def _guess_bounds_dim(da):
"""
Guess bounds values given a 1D coordinate variable.
Assumes equal spacing on either side of the coordinate label.
"""
assert da.ndim == 1
dim = da.dims[0]
diff = da.diff(dim)
lower = da - diff / 2
upper = da + diff / 2
bounds = xr.concat([lower, upper], dim="bounds")
first = (bounds.isel({dim: 0}) - diff[0]).assign_coords({dim: da[dim][0]})
result = xr.concat([first, bounds], dim=dim)
return result
def _build_docstring(func):
"""
Builds a nice docstring for wrapped functions, stating what key words
can be used for arguments.
"""
sig = inspect.signature(func)
string = ""
for k in set(sig.parameters.keys()) & set(_DEFAULT_KEY_MAPPERS):
mappers = _DEFAULT_KEY_MAPPERS.get(k, [])
docstring = ";\n\t\t\t".join(
mapper.__doc__ if mapper.__doc__ else "unknown. please open an issue."
for mapper in mappers
)
string += f"\t\t{k}: {docstring} \n"
for param in sig.parameters:
if sig.parameters[param].kind is inspect.Parameter.VAR_KEYWORD:
string += f"\t\t{param}: {_get_all.__doc__} \n\n"
return (
f"\n\tThe following arguments will be processed by cf_xarray: \n{string}"
"\n\t----\n\t"
)
def _getattr(
obj: Union[DataArray, Dataset],
attr: str,
accessor: "CFAccessor",
key_mappers: Mapping[str, Mapper],
wrap_classes: bool = False,
extra_decorator: Callable = None,
):
"""
Common getattr functionality.
Parameters
----------
obj : DataArray, Dataset
attr : Name of attribute in obj that will be shadowed.
accessor : High level accessor object: CFAccessor
key_mappers : dict
dict(key_name: mapper)
wrap_classes : bool
Should we wrap the return value with _CFWrappedClass?
Only True for the high level CFAccessor.
Facilitates code reuse for _CFWrappedClass and _CFWrapppedPlotMethods
For both of those, wrap_classes is False.
extra_decorator : Callable (optional)
An extra decorator, if necessary. This is used by _CFPlotMethods to set default
kwargs based on CF attributes.
"""
try:
attribute: Union[Mapping, Callable] = getattr(obj, attr)
except AttributeError:
if getattr(
CFDatasetAccessor if isinstance(obj, DataArray) else CFDataArrayAccessor,
attr,
None,
):
raise AttributeError(
f"{obj.__class__.__name__+'.cf'!r} object has no attribute {attr!r}"
)
raise AttributeError(
f"{attr!r} is not a valid attribute on the underlying xarray object."
)
if isinstance(attribute, Mapping):
if not attribute:
return dict(attribute)
newmap = {}
inverted = invert_mappings(
accessor.axes,
accessor.coordinates,
accessor.cell_measures,
accessor.standard_names,
)
unused_keys = set(attribute.keys()) - set(inverted)
for key, value in attribute.items():
for name in inverted[key]:
if name in newmap:
raise AttributeError(
f"cf_xarray can't wrap attribute {attr!r} because there are multiple values for {name!r}. "
f"There is no unique mapping from {name!r} to a value in {attr!r}."
)
newmap.update(dict.fromkeys(inverted[key], value))
newmap.update({key: attribute[key] for key in unused_keys})
skip = {"data_vars": ["coords"], "coords": None}
if attr in ["coords", "data_vars"]:
for key in newmap:
newmap[key] = _getitem(accessor, key, skip=skip[attr])
return newmap
elif isinstance(attribute, Callable): # type: ignore
func: Callable = attribute
else:
raise AttributeError(
f"cf_xarray does not know how to wrap attribute '{type(obj).__name__}.{attr}'. "
"Please file an issue if you have a solution."
)
@functools.wraps(func)
def wrapper(*args, **kwargs):
posargs, arguments = accessor._process_signature(
func, args, kwargs, key_mappers
)
final_func = extra_decorator(func) if extra_decorator else func
result = final_func(*posargs, **arguments)
if wrap_classes and isinstance(result, _WRAPPED_CLASSES):
result = _CFWrappedClass(result, accessor)
return result
wrapper.__doc__ = _build_docstring(func) + wrapper.__doc__
return wrapper
def _getitem(
accessor: "CFAccessor", key: Union[str, List[str]], skip: List[str] = None
) -> Union[DataArray, Dataset]:
"""
Index into obj using key. Attaches CF associated variables.
Parameters
----------
accessor : CFAccessor
key : str, List[str]
skip : str, optional
One of ["coords", "measures"], avoid clashes with special coord names
"""
obj = accessor._obj
kind = str(type(obj).__name__)
scalar_key = isinstance(key, str)
if scalar_key:
key = (key,) # type: ignore
if skip is None:
skip = []
def drop_bounds(names):
# sometimes bounds variables have the same standard_name as the
# actual variable. It seems practical to ignore them when indexing
# with a scalar key. Hopefully these will soon get decoded to IntervalIndex
# and we can move on...
if scalar_key:
bounds = set([obj[k].attrs.get("bounds", None) for k in names])
names = set(names) - bounds
return names
def check_results(names, key):
if scalar_key and len(names) > 1:
raise KeyError(
f"Receive multiple variables for key {key!r}: {names}. "
f"Expected only one. Please pass a list [{key!r}] "
f"instead to get all variables matching {key!r}."
)
try:
measures = accessor._get_all_cell_measures()
except ValueError:
measures = []
warnings.warn("Ignoring bad cell_measures attribute.", UserWarning)
custom_criteria = ChainMap(*OPTIONS["custom_criteria"])
varnames: List[Hashable] = []
coords: List[Hashable] = []
successful = dict.fromkeys(key, False)
for k in key:
if "coords" not in skip and k in _AXIS_NAMES + _COORD_NAMES:
names = _get_all(obj, k)
names = drop_bounds(names)
check_results(names, k)
successful[k] = bool(names)
coords.extend(names)
elif "measures" not in skip and k in measures:
measure = _get_all(obj, k)
check_results(measure, k)
successful[k] = bool(measure)
if measure:
varnames.extend(measure)
elif k in custom_criteria or k in cf_role_criteria:
names = _get_all(obj, k)
check_results(names, k)
successful[k] = bool(names)
varnames.extend(names)
else:
stdnames = set(_get_with_standard_name(obj, k))
objcoords = set(obj.coords)
stdnames = drop_bounds(stdnames)
if "coords" in skip:
stdnames -= objcoords
check_results(stdnames, k)
successful[k] = bool(stdnames)
varnames.extend(stdnames - objcoords)
coords.extend(stdnames & objcoords)
# these are not special names but could be variable names in underlying object
# we allow this so that we can return variables with appropriate CF auxiliary variables
varnames.extend([k for k, v in successful.items() if not v])
allnames = varnames + coords
try:
for name in allnames:
extravars = accessor.get_associated_variable_names(
name, skip_bounds=scalar_key, error=False
)
coords.extend(itertools.chain(*extravars.values()))
if isinstance(obj, DataArray):
ds = obj._to_temp_dataset()
else:
ds = obj
if scalar_key:
if len(allnames) == 1:
da: DataArray = ds.reset_coords()[allnames[0]] # type: ignore
if allnames[0] in coords:
coords.remove(allnames[0])
for k1 in coords:
da.coords[k1] = ds.variables[k1]
return da
else:
raise KeyError(
f"Received scalar key {key[0]!r} but multiple results: {allnames!r}. "
f"Please pass a list instead (['{key[0]}']) to get back a Dataset "
f"with {allnames!r}."
)
ds = ds.reset_coords()[varnames + coords]
if isinstance(obj, DataArray):
if scalar_key and len(ds.variables) == 1:
# single dimension coordinates
assert coords
assert not varnames
return ds[coords[0]]
elif scalar_key and len(ds.variables) > 1:
raise NotImplementedError(
"Not sure what to return when given scalar key for DataArray and it has multiple values. "
"Please open an issue."
)
return ds.set_coords(coords)
except KeyError:
raise KeyError(
f"{kind}.cf does not understand the key {k!r}. "
f"Use 'repr({kind}.cf)' (or '{kind}.cf' in a Jupyter environment) to see a list of key names that can be interpreted."
)
def _possible_x_y_plot(obj, key, skip=None):
"""Guesses a name for an x/y variable if possible."""
# in priority order
x_criteria = [
("coordinates", "longitude"),
("axes", "X"),
("coordinates", "time"),
("axes", "T"),
]
y_criteria = [
("coordinates", "vertical"),
("axes", "Z"),
("coordinates", "latitude"),
("axes", "Y"),
]
def _get_possible(accessor, criteria):
# is_scalar depends on NON_NUMPY_SUPPORTED_TYPES
# importing a private function seems better than
# maintaining that variable!
from xarray.core.utils import is_scalar
for attr, key in criteria:
values = getattr(accessor, attr).get(key)
ax_coord_name = getattr(accessor, attr).get(key)
if not values:
continue
elif ax_coord_name:
values = [v for v in values if v in ax_coord_name]
values = [v for v in values if v != skip]
if len(values) == 1 and not is_scalar(accessor._obj[values[0]]):
return values[0]
else:
for v in values:
if not is_scalar(accessor._obj[v]):
return v
return None
if key == "x":
return _get_possible(obj.cf, x_criteria)
elif key == "y":
return _get_possible(obj.cf, y_criteria)
class _CFWrappedClass(SupportsArithmetic):
"""
This class is used to wrap any class in _WRAPPED_CLASSES.
"""
def __init__(self, towrap, accessor: "CFAccessor"):
"""
Parameters
----------
towrap : Resample, GroupBy, Coarsen, Rolling, Weighted
Instance of xarray class that is being wrapped.
accessor : CFAccessor
Parent accessor object
"""
self.wrapped = towrap
self.accessor = accessor
def __repr__(self):
return "--- CF-xarray wrapped \n" + repr(self.wrapped)
def __getattr__(self, attr):
return _getattr(
obj=self.wrapped,
attr=attr,
accessor=self.accessor,
key_mappers=_DEFAULT_KEY_MAPPERS,
)
def __iter__(self):
return iter(self.wrapped)
class _CFWrappedPlotMethods:
"""
This class wraps DataArray.plot
"""
def __init__(self, obj, accessor):
self._obj = obj
self.accessor = accessor
self._keys = ("x", "y", "hue", "col", "row")
def _plot_decorator(self, func):
"""
This decorator is used to set default kwargs on plotting functions.
For now, this can
1. set ``xincrease`` and ``yincrease``.
2. automatically set ``x`` or ``y``.
"""
valid_keys = self.accessor.keys()
@functools.wraps(func)
def _plot_wrapper(*args, **kwargs):
def _process_x_or_y(kwargs, key, skip=None):
if key not in kwargs:
kwargs[key] = _possible_x_y_plot(self._obj, key, skip)
value = kwargs.get(key)
if value:
if value in valid_keys:
var = self.accessor[value]
else:
var = self._obj[value]
if "positive" in var.attrs:
if var.attrs["positive"] == "down":
kwargs.setdefault(f"{key}increase", False)
else:
kwargs.setdefault(f"{key}increase", True)
return kwargs
is_line_plot = (func.__name__ == "line") or (
func.__name__ == "wrapper"
and (kwargs.get("hue") or self._obj.ndim == 1)
)
if is_line_plot:
hue = kwargs.get("hue")
if "x" not in kwargs and "y" not in kwargs:
kwargs = _process_x_or_y(kwargs, "x", skip=hue)
if not kwargs.get("x"):
kwargs = _process_x_or_y(kwargs, "y", skip=hue)
else:
kwargs = _process_x_or_y(kwargs, "x", skip=kwargs.get("y"))
kwargs = _process_x_or_y(kwargs, "y", skip=kwargs.get("x"))
return func(*args, **kwargs)
return _plot_wrapper
def __call__(self, *args, **kwargs):
"""
Allows .plot()
"""
plot = _getattr(
obj=self._obj,
attr="plot",
accessor=self.accessor,
key_mappers=dict.fromkeys(self._keys, (_single(_get_all),)),
)
return self._plot_decorator(plot)(*args, **kwargs)
def __getattr__(self, attr):
"""
Wraps .plot.contour() for example.
"""
return _getattr(
obj=self._obj.plot,
attr=attr,
accessor=self.accessor,
key_mappers=dict.fromkeys(self._keys, (_single(_get_all),)),
# TODO: "extra_decorator" is more complex than I would like it to be.
# Not sure if there is a better way though
extra_decorator=self._plot_decorator,
)
def create_flag_dict(da):
if not da.cf.is_flag_variable:
raise ValueError(
"Comparisons are only supported for DataArrays that represent CF flag variables."
".attrs must contain 'flag_values' and 'flag_meanings'"
)
flag_meanings = da.attrs["flag_meanings"].split(" ")
flag_values = da.attrs["flag_values"]
# TODO: assert flag_values is iterable
assert len(flag_values) == len(flag_meanings)
return dict(zip(flag_meanings, flag_values))
class CFAccessor:
"""
Common Dataset and DataArray accessor functionality.
"""
def __init__(self, obj):
self._obj = obj
self._all_cell_measures = None
def _assert_valid_other_comparison(self, other):
flag_dict = create_flag_dict(self._obj)
if other not in flag_dict:
raise ValueError(
f"Did not find flag value meaning [{other}] in known flag meanings: [{flag_dict.keys()!r}]"
)
return flag_dict
def __eq__(self, other):
"""
Compare flag values against `other`.
`other` must be in the 'flag_meanings' attribute.
`other` is mapped to the corresponding value in the 'flag_values' attribute, and then
compared.
"""
flag_dict = self._assert_valid_other_comparison(other)
return self._obj == flag_dict[other]
def __ne__(self, other):
"""
Compare flag values against `other`.
`other` must be in the 'flag_meanings' attribute.
`other` is mapped to the corresponding value in the 'flag_values' attribute, and then
compared.
"""
flag_dict = self._assert_valid_other_comparison(other)
return self._obj != flag_dict[other]
def __lt__(self, other):
"""
Compare flag values against `other`.
`other` must be in the 'flag_meanings' attribute.
`other` is mapped to the corresponding value in the 'flag_values' attribute, and then
compared.
"""
flag_dict = self._assert_valid_other_comparison(other)
return self._obj < flag_dict[other]
def __le__(self, other):
"""
Compare flag values against `other`.
`other` must be in the 'flag_meanings' attribute.
`other` is mapped to the corresponding value in the 'flag_values' attribute, and then
compared.
"""
flag_dict = self._assert_valid_other_comparison(other)
return self._obj <= flag_dict[other]
def __gt__(self, other):
"""
Compare flag values against `other`.
`other` must be in the 'flag_meanings' attribute.
`other` is mapped to the corresponding value in the 'flag_values' attribute, and then
compared.
"""
flag_dict = self._assert_valid_other_comparison(other)
return self._obj > flag_dict[other]
def __ge__(self, other):
"""
Compare flag values against `other`.
`other` must be in the 'flag_meanings' attribute.
`other` is mapped to the corresponding value in the 'flag_values' attribute, and then
compared.
"""
flag_dict = self._assert_valid_other_comparison(other)
return self._obj >= flag_dict[other]
def isin(self, test_elements):
"""Test each value in the array for whether it is in test_elements.
Parameters