-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathaccessor.py
1491 lines (1247 loc) · 49.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 warnings
from collections import ChainMap
from typing import (
Any,
Callable,
Dict,
Hashable,
Iterable,
List,
Mapping,
MutableMapping,
Set,
Tuple,
Union,
)
import xarray as xr
from xarray import DataArray, Dataset
from .helpers import bounds_to_vertices
from .utils import parse_cell_methods_attr
#: 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")
# Define the criteria for coordinate matches
# Copied from metpy
# Internally we only use X, Y, Z, T
coordinate_criteria: MutableMapping[str, MutableMapping[str, Tuple]] = {
"standard_name": {
"X": ("projection_x_coordinate",),
"Y": ("projection_y_coordinate",),
"T": ("time",),
"time": ("time",),
"vertical": (
"air_pressure",
"height",
"depth",
"geopotential_height",
# computed dimensional coordinate name
"altitude",
"height_above_geopotential_datum",
"height_above_reference_ellipsoid",
"height_above_mean_sea_level",
),
"Z": (
"model_level_number",
"atmosphere_ln_pressure_coordinate",
"atmosphere_sigma_coordinate",
"atmosphere_hybrid_sigma_pressure_coordinate",
"atmosphere_hybrid_height_coordinate",
"atmosphere_sleve_coordinate",
"ocean_sigma_coordinate",
"ocean_s_coordinate",
"ocean_s_coordinate_g1",
"ocean_s_coordinate_g2",
"ocean_sigma_z_coordinate",
"ocean_double_sigma_coordinate",
),
"latitude": ("latitude",),
"longitude": ("longitude",),
},
"_CoordinateAxisType": {
"T": ("Time",),
"Z": ("GeoZ", "Height", "Pressure"),
"Y": ("GeoY",),
"latitude": ("Lat",),
"X": ("GeoX",),
"longitude": ("Lon",),
},
"axis": {"T": ("T",), "Z": ("Z",), "Y": ("Y",), "X": ("X",)},
"cartesian_axis": {"T": ("T",), "Z": ("Z",), "Y": ("Y",), "X": ("X",)},
"positive": {"vertical": ("up", "down")},
"units": {
"latitude": (
"degree_north",
"degree_N",
"degreeN",
"degrees_north",
"degrees_N",
"degreesN",
),
"longitude": (
"degree_east",
"degree_E",
"degreeE",
"degrees_east",
"degrees_E",
"degreesE",
),
},
}
# "long_name" and "standard_name" criteria are the same. For convenience.
coordinate_criteria["long_name"] = coordinate_criteria["standard_name"]
#: regular expressions for guess_coord_axis
regex = {
"time": "time[0-9]*|min|hour|day|week|month|year",
"vertical": (
"(lv_|bottom_top|sigma|h(ei)?ght|altitude|depth|isobaric|pres|"
"isotherm)[a-z_]*[0-9]*"
),
"Y": "y",
"latitude": "y?lat[a-z0-9]*",
"X": "x",
"longitude": "x?lon[a-z0-9]*",
}
regex["Z"] = regex["vertical"]
regex["T"] = regex["time"]
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"]
def _is_datetime_like(da: DataArray) -> bool:
import numpy as np
if np.issubdtype(da.dtype, np.datetime64) or np.issubdtype(
da.dtype, np.timedelta64
):
return True
try:
import cftime
if isinstance(da.data[0], cftime.datetime):
return True
except ImportError:
pass
return False
# Type for Mapper functions
Mapper = Callable[[Union[DataArray, Dataset], str], List[str]]
def apply_mapper(
mappers: Union[Mapper, Tuple[Mapper, ...]],
obj: Union[DataArray, Dataset],
key: str,
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 default is None:
default = []
def _apply_single_mapper(mapper):
try:
results = mapper(obj, key)
except Exception as e:
if error:
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))
nresults = sum([bool(v) for v in results])
if nresults > 1:
raise KeyError(
f"Multiple mappers succeeded with key {key!r}.\nI was using mappers: {mappers!r}."
f"I received results: {results!r}.\nPlease open an issue."
)
if nresults == 0:
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 list(itertools.chain(*results))
def _get_axis_coord_single(var: Union[DataArray, Dataset], key: str) -> List[str]:
""" Helper method for when we really want only one result per key. """
results = _get_axis_coord(var, 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
def _get_axis_coord_time_accessor(
var: Union[DataArray, Dataset], key: str
) -> List[str]:
"""
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 = _get_axis_coord_single(var, key)
return [v + "." + ext for v in results]
else:
return []
def _get_axis_coord(var: Union[DataArray, Dataset], key: str) -> List[str]:
"""
Translate from axis or coord name to variable name
Parameters
----------
var: 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 var.encoding:
search_in.update(var.encoding["coordinates"].split(" "))
if "coordinates" in var.attrs:
search_in.update(var.attrs["coordinates"].split(" "))
if not search_in:
search_in = set(var.coords)
# maybe only do this for key in _AXIS_NAMES?
search_in.update(var.indexes)
results: Set = set()
for coord in search_in:
for criterion, valid_values in coordinate_criteria.items():
if key in valid_values:
expected = valid_values[key]
if (
coord in var.coords
and var.coords[coord].attrs.get(criterion, None) in expected
):
results.update((coord,))
return list(results)
def _get_measure_variable(
da: DataArray, key: str, error: bool = True, default: str = None
) -> List[DataArray]:
""" tiny wrapper since xarray does not support providing str for weights."""
varnames = apply_mapper(_get_measure, da, key, error, default)
if len(varnames) > 1:
raise ValueError(f"Multiple measures found for key {key!r}: {varnames!r}.")
return [da[varnames[0]]]
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)
#: Default mappers for common keys.
_DEFAULT_KEY_MAPPERS: Mapping[str, Tuple[Mapper, ...]] = {
"dim": (_get_axis_coord,),
"dims": (_get_axis_coord,), # transpose
"dimensions": (_get_axis_coord,), # stack
"dims_dict": (_get_axis_coord,), # swap_dims, rename_dims
"shifts": (_get_axis_coord,), # shift, roll
"pad_width": (_get_axis_coord,), # shift, roll
# "names": something_with_all_valid_keys? # set_coords, reset_coords
"coords": (_get_axis_coord,), # interp
"indexers": (_get_axis_coord,), # sel, isel, reindex
# "indexes": (_get_axis_coord,), # set_index
"dims_or_levels": (_get_axis_coord,), # reset_index
"window": (_get_axis_coord,), # rolling_exp
"coord": (_get_axis_coord_single,), # differentiate, integrate
"group": (_get_axis_coord_single, _get_axis_coord_time_accessor),
"indexer": (_get_axis_coord_single,), # resample
"variables": (_get_axis_coord,), # sortby
"weights": (_get_measure_variable,), # type: ignore
}
def _get_with_standard_name(ds: Dataset, name: Union[str, List[str]]) -> List[str]:
""" returns a list of variable names with standard name == name. """
varnames = []
for vname, var in ds.variables.items():
stdname = var.attrs.get("standard_name", None)
if stdname == name:
varnames.append(str(vname))
return varnames
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.
"""
# this list will need to be updated any time a new mapper is added
mapper_docstrings = {
_get_axis_coord: f"One or more of {(_AXIS_NAMES + _COORD_NAMES)!r}",
_get_axis_coord_single: f"One of {(_AXIS_NAMES + _COORD_NAMES)!r}",
# _get_measure_variable: f"One of {_CELL_MEASURES!r}",
}
sig = inspect.signature(func)
string = ""
for k in set(sig.parameters.keys()) & set(_DEFAULT_KEY_MAPPERS):
mappers = _DEFAULT_KEY_MAPPERS.get(k, [])
docstring = "; ".join(
mapper_docstrings.get(mapper, "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}: {mapper_docstrings[_get_axis_coord]} \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:
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)
# attributes like chunks / sizes
newmap = dict()
unused_keys = set(attribute.keys())
for key in _AXIS_NAMES + _COORD_NAMES:
value = set(apply_mapper(_get_axis_coord, obj, key, error=False))
unused_keys -= value
if value:
good_values = value & set(obj.dims)
if not good_values:
continue
if len(good_values) > 1:
raise AttributeError(
f"cf_xarray can't wrap attribute {attr!r} because there are multiple values for {key!r} viz. {good_values!r}. "
f"There is no unique mapping from {key!r} to a value in {attr!r}."
)
newmap.update({key: attribute[good_values.pop()]})
newmap.update({key: attribute[key] for key in unused_keys})
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
class _CFWrappedClass:
"""
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,
)
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 is setting ``xincrease`` and ``yincrease``. It could set
other arguments in the future.
"""
valid_keys = self.accessor.keys()
@functools.wraps(func)
def _plot_wrapper(*args, **kwargs):
if "x" in kwargs:
if kwargs["x"] in valid_keys:
xvar = self.accessor[kwargs["x"]]
else:
xvar = self._obj[kwargs["x"]]
if "positive" in xvar.attrs:
if xvar.attrs["positive"] == "down":
kwargs.setdefault("xincrease", False)
else:
kwargs.setdefault("xincrease", True)
if "y" in kwargs:
if kwargs["y"] in valid_keys:
yvar = self.accessor[kwargs["y"]]
else:
yvar = self._obj[kwargs["y"]]
if "positive" in yvar.attrs:
if yvar.attrs["positive"] == "down":
kwargs.setdefault("yincrease", False)
else:
kwargs.setdefault("yincrease", True)
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, (_get_axis_coord_single,)),
)
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, (_get_axis_coord_single,)),
# 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,
)
class CFAccessor:
"""
Common Dataset and DataArray accessor functionality.
"""
def __init__(self, da):
self._obj = da
self._all_cell_measures = None
def _get_all_cell_measures(self):
"""
Get all cell measures defined in the object, adding CF pre-defined measures.
"""
# get all_cell_measures only once
if not self._all_cell_measures:
self._all_cell_measures = set(_CELL_MEASURES + tuple(self.cell_measures))
return self._all_cell_measures
def _process_signature(
self,
func: Callable,
args,
kwargs,
key_mappers: MutableMapping[str, Tuple[Mapper, ...]],
):
"""
Processes a function's signature, args, kwargs:
1. Binds *args so that everthing is a Mapping from kwarg name to values
2. Calls _rewrite_values to rewrite any special CF names to normal xarray names.
This uses key_mappers
3. Unpacks arguments if necessary before returning them.
"""
sig = inspect.signature(func, follow_wrapped=False)
# Catch things like .isel(T=5).
# This assigns indexers_kwargs=dict(T=5).
# and indexers_kwargs is of kind VAR_KEYWORD
var_kws: List = []
# capture *args, e.g. transpose
var_args: List = []
for param in sig.parameters:
if sig.parameters[param].kind is inspect.Parameter.VAR_KEYWORD:
var_kws.append(param)
elif sig.parameters[param].kind is inspect.Parameter.VAR_POSITIONAL:
var_args.append(param)
posargs = []
if args or kwargs:
bound = sig.bind(*args, **kwargs)
arguments = self._rewrite_values(
bound.arguments, key_mappers, tuple(var_kws)
)
# unwrap the *args type arguments
for arg in var_args:
value = arguments.pop(arg, None)
if value:
# value should always be Iterable
posargs.extend(value)
# now unwrap the **kwargs type arguments
for kw in var_kws:
value = arguments.pop(kw, None)
if value:
arguments.update(**value)
else:
arguments = {}
return posargs, arguments
def _rewrite_values(
self,
kwargs,
key_mappers: Mapping[str, Tuple[Mapper, ...]],
var_kws: Tuple[str, ...],
):
"""
Rewrites the values in a Mapping from kwarg to value.
Parameters
----------
kwargs: Mapping
Mapping from kwarg name to value
key_mappers: Mapping
Mapping from kwarg name to a Mapper function that will convert a
given CF "special" name to an xarray name.
var_kws: List[str]
List of variable kwargs that need special treatment.
e.g. **indexers_kwargs in isel
Returns
-------
dict of kwargs with fully rewritten values.
"""
updates: dict = {}
# allow multiple return values here.
# these are valid for .sel, .isel, .coarsen
all_mappers = ChainMap(key_mappers, dict.fromkeys(var_kws, (_get_axis_coord,)))
for key in set(all_mappers) & set(kwargs):
value = kwargs[key]
mappers = all_mappers[key]
if isinstance(value, str):
value = [value]
if isinstance(value, dict):
# this for things like isel where **kwargs captures things like T=5
# .sel, .isel, .rolling
# Account for multiple names matching the key.
# e.g. .isel(X=5) → .isel(xi_rho=5, xi_u=5, xi_v=5, xi_psi=5)
# where xi_* have attrs["axis"] = "X"
updates[key] = ChainMap(
*[
dict.fromkeys(
apply_mapper(mappers, self._obj, k, False, [k]), v
)
for k, v in value.items()
]
)
elif value is Ellipsis:
pass
else:
# things like sum which have dim
newvalue = [
apply_mapper(mappers, self._obj, v, error=False, default=[v])
for v in value
]
# Mappers return list by default
# for input dim=["lat", "X"], newvalue=[["lat"], ["lon"]],
# so we deal with that here.
unpacked = list(itertools.chain(*newvalue))
if len(unpacked) == 1:
# handle 'group'
updates[key] = unpacked[0]
else:
updates[key] = unpacked
kwargs.update(updates)
# TODO: is there a way to merge this with above?
# maybe the keys we are looking for are in kwargs.
# For example, this happens with DataArray.plot(),
# where the signature is obscured and kwargs is
# kwargs = {"x": "X", "col": "T"}
for vkw in var_kws:
if vkw in kwargs:
maybe_update = {
# TODO: this is assuming key_mappers[k] is always
# _get_axis_coord_single
k: apply_mapper(
key_mappers[k], self._obj, v, error=False, default=[v]
)[0]
for k, v in kwargs[vkw].items()
if k in key_mappers
}
kwargs[vkw].update(maybe_update)
return kwargs
def __getattr__(self, attr):
return _getattr(
obj=self._obj,
attr=attr,
accessor=self,
key_mappers=_DEFAULT_KEY_MAPPERS,
wrap_classes=True,
)
def __contains__(self, item: str) -> bool:
"""
Check whether item is a valid key for indexing with .cf
"""
return item in self.keys()
@property
def plot(self):
return _CFWrappedPlotMethods(self._obj, self)
def describe(self):
"""
Print a string repr to screen.
"""
text = "Axes:\n"
axes = self.axes
for key in _AXIS_NAMES:
text += f"\t{key}: {axes[key] if key in axes else []}\n"
text += "\nCoordinates:\n"
coords = self.coordinates
for key in _COORD_NAMES:
text += f"\t{key}: {coords[key] if key in coords else []}\n"
text += "\nCell Measures:\n"
measures = self.cell_measures
for key in sorted(self._get_all_cell_measures()):
text += f"\t{key}: {measures[key] if key in measures else []}\n"
text += "\nStandard Names:\n"
if isinstance(self._obj, DataArray):
text += "\tunsupported\n"
else:
for key, value in sorted(self.standard_names.items()):
if key not in _COORD_NAMES:
text += f"\t{key}: {value}\n"
print(text)
def get_valid_keys(self) -> Set[str]:
warnings.warn(
"Now called `keys` and `get_valid_keys` will be removed in a future version.",
DeprecationWarning,
)
return self.keys()
def keys(self) -> Set[str]:
"""
Utility function that returns valid keys for .cf[].
This is useful for checking whether a key is valid for indexing, i.e.
that the attributes necessary to allow indexing by that key exist.
Returns
-------
Set of valid key names that can be used with __getitem__ or .cf[key].
"""
varnames = list(self.axes) + list(self.coordinates)
varnames.extend(list(self.cell_measures))
varnames.extend(list(self.standard_names))
return set(varnames)
@property
def axes(self) -> Dict[str, List[str]]:
"""
Property that returns a dictionary mapping valid Axis standard names for ``.cf[]``
to variable names.
This is useful for checking whether a key is valid for indexing, i.e.
that the attributes necessary to allow indexing by that key exist.
However, it will only return the Axis names, not Coordinate names.
Returns
-------
Dictionary of valid Axis names that can be used with ``__getitem__`` or ``.cf[key]``.
Will be ("X", "Y", "Z", "T") or a subset thereof.
"""
vardict = {
key: apply_mapper(_get_axis_coord, self._obj, key, error=False)
for key in _AXIS_NAMES
}
return {k: sorted(v) for k, v in vardict.items() if v}
@property
def coordinates(self) -> Dict[str, List[str]]:
"""
Property that returns a dictionary mapping valid Coordinate standard names for ``.cf[]``
to variable names.
This is useful for checking whether a key is valid for indexing, i.e.
that the attributes necessary to allow indexing by that key exist.
However, it will only return the Coordinate names, not Axis names.
Returns
-------
Dictionary of valid Coordinate names that can be used with ``__getitem__`` or ``.cf[key]``.
Will be ("longitude", "latitude", "vertical", "time") or a subset thereof.
"""
vardict = {
key: apply_mapper(_get_axis_coord, self._obj, key, error=False)
for key in _COORD_NAMES
}
return {k: sorted(v) for k, v in vardict.items() if v}
@property
def cell_measures(self) -> Dict[str, List[str]]:
"""
Property that returns a dictionary mapping valid cell measure standard names for ``.cf[]``
to variable names.
This is useful for checking whether a key is valid for indexing, i.e.
that the attributes necessary to allow indexing by that key exist.
Returns
-------
Dictionary of valid cell measure names that can be used with __getitem__ or .cf[key].
"""
obj = self._obj
all_attrs = [da.attrs.get("cell_measures", "") for da in obj.coords.values()]
if isinstance(obj, DataArray):
all_attrs += [obj.attrs.get("cell_measures", "")]
elif isinstance(obj, Dataset):
all_attrs += [
da.attrs.get("cell_measures", "") for da in obj.data_vars.values()
]
measures: Dict[str, List[str]] = dict()
for attr in all_attrs:
for key, value in parse_cell_methods_attr(attr).items():
measures[key] = measures.setdefault(key, []) + [value]
return {k: sorted(set(v)) for k, v in measures.items() if v}
def get_standard_names(self) -> List[str]:
warnings.warn(
"`get_standard_names` will be removed in a future version in favor of `standard_names`.",
DeprecationWarning,
)
return list(self.standard_names.keys())
@property
def standard_names(self) -> Dict[str, List[str]]:
"""
Returns a sorted list of standard names in Dataset.
Parameters
----------
obj: DataArray, Dataset
Xarray object to process
Returns
-------
Dictionary of standard names in dataset
"""
if isinstance(self._obj, Dataset):
variables = self._obj.variables
elif isinstance(self._obj, DataArray):
variables = self._obj.coords
vardict: Dict[str, List[str]] = dict()
for k, v in variables.items():
if "standard_name" in v.attrs:
std_name = v.attrs["standard_name"]
vardict[std_name] = vardict.setdefault(std_name, []) + [k]
return {k: sorted(v) for k, v in vardict.items()}
def get_associated_variable_names(self, name: Hashable) -> Dict[str, List[str]]:
"""
Returns a dict mapping
1. "ancillary_variables"
2. "bounds"
3. "cell_measures"
4. "coordinates"
to a list of variable names referred to in the appropriate attribute