Repository navigation
Expand file tree
/
Copy pathmetadecorators.py
More file actions
2268 lines (1727 loc) · 78.5 KB
/
Copy pathmetadecorators.py
File metadata and controls
2268 lines (1727 loc) · 78.5 KB
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
from __future__ import (absolute_import, division, print_function)
import warnings
import wrapt
from collections import OrderedDict
import numpy as np
import numpy.ma as ma
from .extension import _interpline
from .util import (extract_vars, either, from_args, arg_location,
is_coordvar, latlon_coordvars, to_np,
from_var, iter_left_indexes, is_mapping,
is_moving_domain, is_latlon_pair)
from .coordpair import CoordPair
from .py3compat import viewkeys, viewitems, py3range
from .interputils import get_xy_z_params, get_xy, to_xy_coords
from .config import xarray_enabled
if xarray_enabled():
from xarray import DataArray
def copy_and_set_metadata(copy_varname=None, delete_attrs=None, name=None,
remove_dims=None, dimnames=None,
coords=None, **fixed_attrs):
"""A decorator that sets the metadata for a wrapped function's output.
Generally, the metadata is copied from the variable specified by
*copy_varname*, with other fixed fields set by the other decorator
arguments.
The *cache* argument used by most diagnostic routines is supplied by
this decorator when the *copy_varname* variable is extracted, in order
to prevent the variable from being extracted again by the wrapped function.
If the wrapped function's *meta* argument is False, then this decorator
returns the wrapped function output without applying the metadata.
Args:
copy_varname (:obj:`str`, optional): The NetCDF variable name to copy.
Default is None.
delete_attrs (sequence of :obj:`str`, optional): A sequence of key
names to remove from the :attr:`xarray.DataArray.attrs` attribute
in the wrapped function output (after being copied from
*copy_varname*). Default is None.
name (:obj:`str`): The name to use for the
:attr:`xarray.DataArray.name` attribute.
remove_dims (sequence of :obj:`int`, optional): A sequence of dimension
indexes to be removed from the wrapped function output (after being
copied from *copy_varname*). This is useful when the copy
variable is three dimensional but the wrapped function output
is two dimensional, and you still want to keep the names of
the rightmost two dimensions. Default is None.
dimnames (sequence of :obj:`str`, optional): A sequence of dimension
names in order to manually set the
:attr:`xarray.DataArray.dims` attribute. Default is None.
coords (:obj:`dict`): A mapping of coordinate name to coordinate
value to manually specify the :attr:`xarray.DataArray.coords`
attribute. Default is None.
**fixed_attrs: These keyword arguments are added to the
:attr:`xarray.DataArray.attrs` attribute.
Returns:
:class:`xarray.DataArray` or :class:`numpy.ndarray`: The wrapped
function output with or without metadata. If xarray is
enabled and the *meta* parameter is True, then the result will be a
:class:`xarray.DataArray` object. Otherwise, the result will be a
:class:`numpy.ndarray` object with no metadata.
"""
@wrapt.decorator
def func_wrapper(wrapped, instance, args, kwargs):
do_meta = from_args(wrapped, ("meta",), *args, **kwargs)["meta"]
if do_meta is None:
do_meta = True
if not xarray_enabled() or not do_meta:
return wrapped(*args, **kwargs)
argvars = from_args(wrapped, ("wrfin", "timeidx", "method",
"squeeze", "cache", "units", "meta",
"_key"),
*args, **kwargs)
wrfin = argvars["wrfin"]
timeidx = argvars["timeidx"]
units = argvars["units"]
method = argvars["method"]
squeeze = argvars["squeeze"]
cache = argvars["cache"]
_key = argvars["_key"]
if cache is None:
cache = {}
# Note: can't modify nonlocal var
if (callable(copy_varname)):
_copy_varname = copy_varname(wrfin)
else:
_copy_varname = copy_varname
# Extract the copy_from argument
var_to_copy = None if cache is None else cache.get(_copy_varname,
None)
if var_to_copy is None:
var_to_copy = extract_vars(wrfin, timeidx, (_copy_varname,),
method, squeeze, cache,
meta=True, _key=_key)[_copy_varname]
# Make a copy so we don't modify a user supplied cache
new_cache = dict(cache)
new_cache[_copy_varname] = var_to_copy
# Don't modify the original args/kargs. The args need to be a list
# so it can be modified.
new_args, cache_argloc = arg_location(wrapped, "cache", args, kwargs)
new_args[cache_argloc] = new_cache
result = wrapped(*new_args)
outname = ""
outdimnames = list()
outcoords = OrderedDict()
outattrs = OrderedDict()
if copy_varname is not None:
outname = var_to_copy.name
if dimnames is not None:
outdimnames = dimnames
outcoords = coords
else:
outdimnames += var_to_copy.dims
outcoords.update(var_to_copy.coords)
outattrs.update(var_to_copy.attrs)
if remove_dims is not None:
for dimname in remove_dims:
outdimnames.remove(dimname)
try:
del outcoords[dimname]
except KeyError:
pass
if name is not None:
outname = name
if units is not None:
outattrs["units"] = units
for argname, val in viewitems(fixed_attrs):
outattrs[argname] = val
if delete_attrs is not None:
for attr in delete_attrs:
try:
del outattrs[attr]
except KeyError:
pass
if isinstance(result, ma.MaskedArray):
outattrs["_FillValue"] = result.fill_value
outattrs["missing_value"] = result.fill_value
return DataArray(result, name=outname, coords=outcoords,
dims=outdimnames, attrs=outattrs)
return func_wrapper
def set_wind_metadata(copy_varname, name, description,
wind_ncvar=False,
two_d=False, wspd_wdir=False):
"""A decorator that sets the metadata for a wrapped wind function's output.
This is a special metadata decorator for working with wind functions, which
include wind extraction routines, uvmet routines, and
wind speed / wind direction routines.
If the wrapped function's *meta* argument is False, then this decorator
returns the wrapped function output without applying the metadata.
Args:
copy_varname (:obj:`str`, optional): The NetCDF variable name to copy.
Default is None.
name (:obj:`str`): The name to use for the
:attr:`xarray.DataArray.name` attribute.
description (:obj:`str`): The description to use for the 'description'
key in the :attr:`xarray.DataArray.attrs` attribute.
wind_ncvar (:obj:`bool`, optional): Set to True when the wrapped
function is simply extracting a wind variable (U, V, W) from the
NetCDF file. Set to False for other types of wind algorithms
(uvmet, wspd_wdir, etc). Default is False.
two_d (:obj:`bool`, optional): Set to True if the wind field is
two-dimensional. Set to False for a three-dimensional wind field.
Default is False.
wspd_wdir (:obj:`bool`): Set to True if the wrapped function is a
wind speed / wind direction algorithm. Otherwise, set to False.
Default is False.
Returns:
:class:`xarray.DataArray` or :class:`numpy.ndarray`: The wrapped
wind function output with or without metadata. If xarray is
enabled and the *meta* parameter is True, then the result will be a
:class:`xarray.DataArray` object. Otherwise, the result will be a
:class:`numpy.ndarray` object with no metadata.
"""
@wrapt.decorator
def func_wrapper(wrapped, instance, args, kwargs):
do_meta = from_args(wrapped, ("meta",), *args, **kwargs)["meta"]
if do_meta is None:
do_meta = True
if not xarray_enabled() or not do_meta:
return wrapped(*args, **kwargs)
argvars = from_args(wrapped, ("wrfin", "timeidx", "units",
"method", "squeeze", "ten_m", "cache",
"_key"),
*args, **kwargs)
wrfin = argvars["wrfin"]
timeidx = argvars["timeidx"]
units = argvars["units"]
method = argvars["method"]
squeeze = argvars["squeeze"]
ten_m = argvars["ten_m"]
cache = argvars["cache"]
_key = argvars["_key"]
if cache is None:
cache = {}
if isinstance(copy_varname, either):
_copy_varname = copy_varname(wrfin)
else:
_copy_varname = copy_varname
copy_var = extract_vars(wrfin, timeidx, _copy_varname,
method, squeeze, cache,
meta=True, _key=_key)[_copy_varname]
# Make a copy so we don't modify a user supplied cache
new_cache = dict(cache)
new_cache[_copy_varname] = copy_var
# Don't modify the original args/kargs. The args need to be a list
# so it can be modified.
new_args, cache_argloc = arg_location(wrapped, "cache", args, kwargs)
new_args[cache_argloc] = new_cache
result = wrapped(*new_args)
outcoords = OrderedDict()
outattrs = OrderedDict()
outdimnames = list(copy_var.dims)
outattrs.update(copy_var.attrs)
if wind_ncvar:
outcoords.update(copy_var.coords)
elif not wspd_wdir:
if not two_d:
outdimnames.insert(0, "u_v")
else:
outdimnames.insert(0, "u_v")
outattrs["MemoryOrder"] = "XY"
outcoords["u_v"] = ["u", "v"]
else:
if not two_d:
outdimnames.insert(0, "wspd_wdir")
else:
outdimnames.insert(0, "wspd_wdir")
outattrs["MemoryOrder"] = "XY"
outcoords["wspd_wdir"] = ["wspd", "wdir"]
if units is not None:
outattrs["units"] = units
# xarray doesn't line up coordinate dimensions based on
# names, it just remembers the index it originally mapped to.
# So, need to rebuild the XLAT, XLONG, coordinates again since the
# leftmost index changed.
if not wind_ncvar:
for key, dataarray in viewitems(copy_var.coords):
if is_coordvar(key):
outcoords[key] = dataarray.dims, to_np(dataarray)
elif key == "XTIME":
outcoords[key] = dataarray.dims, to_np(dataarray)
elif key == "Time":
outcoords[key] = to_np(dataarray)
outname = name
outattrs["description"] = description
return DataArray(result, name=outname, coords=outcoords,
dims=outdimnames, attrs=outattrs)
return func_wrapper
def set_cape_metadata(is2d):
"""A decorator that sets the metadata for a wrapped CAPE function's output.
This is a special metadata decorator for working with CAPE functions.
If the wrapped function's *meta* argument is False, then this decorator
returns the wrapped function output without applying the metadata.
Args:
is2d (:obj:`bool`): Set to True if the wrapped function is for a
two-dimensional CAPE routine. Set to False for a
three-dimensional CAPE routine.
Returns:
:class:`xarray.DataArray` or :class:`numpy.ndarray`: The wrapped
CAPE function output with or without metadata. If xarray is
enabled and the *meta* parameter is True, then the result will be a
:class:`xarray.DataArray` object. Otherwise, the result will be a
:class:`numpy.ndarray` object with no metadata.
"""
@wrapt.decorator
def func_wrapper(wrapped, instance, args, kwargs):
do_meta = from_args(wrapped, ("meta",), *args, **kwargs)["meta"]
if do_meta is None:
do_meta = True
if not xarray_enabled() or not do_meta:
return wrapped(*args, **kwargs)
argvars = from_args(wrapped, ("wrfin", "timeidx", "method", "squeeze",
"cache", "_key", "missing"),
*args, **kwargs)
wrfin = argvars["wrfin"]
timeidx = argvars["timeidx"]
method = argvars["method"]
squeeze = argvars["squeeze"]
cache = argvars["cache"]
missing = argvars["missing"]
_key = argvars["_key"]
if cache is None:
cache = {}
_copy_varname = "P"
copy_var = extract_vars(wrfin, timeidx, _copy_varname, method, squeeze,
cache, meta=True, _key=_key)[_copy_varname]
# Make a copy so we don't modify a user supplied cache
new_cache = dict(cache)
new_cache[_copy_varname] = copy_var
# Don't modify the original args/kargs. The args need to be a list
# so it can be modified.
new_args, cache_argloc = arg_location(wrapped, "cache", args, kwargs)
new_args[cache_argloc] = new_cache
result = wrapped(*new_args)
outcoords = OrderedDict()
outattrs = OrderedDict()
outattrs.update(copy_var.attrs)
outdimnames = [None] * result.ndim
if is2d:
# Right dims
outdimnames[-2:] = copy_var.dims[-2:]
# Left dims
outdimnames[1:-2] = copy_var.dims[0:-3]
outdimnames[0] = "mcape_mcin_lcl_lfc"
outattrs["description"] = "mcape ; mcin ; lcl ; lfc"
outattrs["MemoryOrder"] = "XY"
outattrs["units"] = "J kg-1 ; J kg-1 ; m ; m"
outname = "cape_2d"
else:
# Right dims
outdimnames[-3:] = copy_var.dims[-3:]
# Left dims
outdimnames[1:-3] = copy_var.dims[0:-3]
outdimnames[0] = "cape_cin"
outattrs["description"] = "cape; cin"
outattrs["units"] = "J kg-1 ; J kg-1"
outattrs["MemoryOrder"] = "XYZ"
outname = "cape_3d"
outattrs["_FillValue"] = missing
outattrs["missing_value"] = missing
# xarray doesn't line up coordinate dimensions based on
# names, it just remembers the index it originally mapped to.
# So, need to rebuild the XLAT, XLONG, coordinates again since the
# leftmost index changed.
for key, dataarray in viewitems(copy_var.coords):
if is_coordvar(key):
outcoords[key] = dataarray.dims, to_np(dataarray)
elif key == "XTIME":
outcoords[key] = dataarray.dims, to_np(dataarray)
elif key == "Time":
outcoords[key] = to_np(dataarray)
if is2d:
outcoords["mcape_mcin_lcl_lfc"] = ["mcape", "mcin", "lcl", "lfc"]
else:
outcoords["cape_cin"] = ["cape", "cin"]
return DataArray(result, name=outname, coords=outcoords,
dims=outdimnames, attrs=outattrs)
return func_wrapper
def set_cloudfrac_metadata():
"""A decorator that sets the metadata for a wrapped cloud fraction
function's output.
This is a special metadata decorator for working with cloud fraction
functions.
If the wrapped function's *meta* argument is False, then this decorator
returns the wrapped function output without applying the metadata.
Returns:
:class:`xarray.DataArray` or :class:`numpy.ndarray`: The wrapped
cloud fraction function output with or without metadata. If xarray is
enabled and the *meta* parameter is True, then the result will be a
:class:`xarray.DataArray` object. Otherwise, the result will be a
:class:`numpy.ndarray` object with no metadata.
"""
@wrapt.decorator
def func_wrapper(wrapped, instance, args, kwargs):
do_meta = from_args(wrapped, ("meta",), *args, **kwargs)["meta"]
if do_meta is None:
do_meta = True
if not xarray_enabled() or not do_meta:
return wrapped(*args, **kwargs)
argvars = from_args(wrapped, ("wrfin", "timeidx", "method", "squeeze",
"cache", "_key", "vert_type",
"low_thresh", "mid_thresh",
"high_thresh", "missing"),
*args, **kwargs)
wrfin = argvars["wrfin"]
timeidx = argvars["timeidx"]
method = argvars["method"]
squeeze = argvars["squeeze"]
cache = argvars["cache"]
_key = argvars["_key"]
vert_type = argvars["vert_type"]
low_thresh = argvars["low_thresh"]
mid_thresh = argvars["mid_thresh"]
high_thresh = argvars["high_thresh"]
missing = argvars["missing"]
if cache is None:
cache = {}
_copy_varname = "P"
copy_var = extract_vars(wrfin, timeidx, _copy_varname, method, squeeze,
cache, meta=True, _key=_key)[_copy_varname]
# Make a copy so we don't modify a user supplied cache
new_cache = dict(cache)
new_cache[_copy_varname] = copy_var
# Don't modify the original args/kargs. The args need to be a list
# so it can be modified.
new_args, cache_argloc = arg_location(wrapped, "cache", args, kwargs)
new_args[cache_argloc] = new_cache
result = wrapped(*new_args)
outcoords = OrderedDict()
outattrs = OrderedDict()
outattrs.update(copy_var.attrs)
outdimnames = [None] * result.ndim
# For printing units
unitstr = ("Pa" if vert_type.lower() == "pres"
or vert_type.lower() == "pressure" else "m")
# For setting the threholds in metdata
if vert_type.lower() == "pres" or vert_type.lower() == "pressure":
_low_thresh = 97000. if low_thresh is None else low_thresh
_mid_thresh = 80000. if mid_thresh is None else mid_thresh
_high_thresh = 45000. if high_thresh is None else high_thresh
elif vert_type.lower() == "height_msl" or "height_agl":
_low_thresh = 300. if low_thresh is None else low_thresh
_mid_thresh = 2000. if mid_thresh is None else mid_thresh
_high_thresh = 6000. if high_thresh is None else high_thresh
# Right dims
outdimnames[-2:] = copy_var.dims[-2:]
# Left dims
outdimnames[1:-2] = copy_var.dims[0:-3]
outdimnames[0] = "low_mid_high"
outattrs["description"] = "low, mid, high clouds"
outattrs["MemoryOrder"] = "XY"
outattrs["units"] = "%"
outattrs["low_thresh"] = "{} {}".format(_low_thresh, unitstr)
outattrs["mid_thresh"] = "{} {}".format(_mid_thresh, unitstr)
outattrs["high_thresh"] = "{} {}".format(_high_thresh, unitstr)
outattrs["_FillValue"] = missing
outattrs["missing_value"] = missing
outname = "cloudfrac"
# xarray doesn't line up coordinate dimensions based on
# names, it just remembers the index it originally mapped to.
# So, need to rebuild the XLAT, XLONG, coordinates again since the
# leftmost index changed.
for key, dataarray in viewitems(copy_var.coords):
if is_coordvar(key):
outcoords[key] = dataarray.dims, to_np(dataarray)
elif key == "XTIME":
outcoords[key] = dataarray.dims, to_np(dataarray)
elif key == "Time":
outcoords[key] = to_np(dataarray)
outcoords["low_mid_high"] = ["low", "mid", "high"]
return DataArray(result, name=outname, coords=outcoords,
dims=outdimnames, attrs=outattrs)
return func_wrapper
def set_latlon_metadata(xy=False):
"""A decorator that sets the metadata for a wrapped latlon function's
output.
This is a special metadata decorator for working with latlon functions.
If the wrapped function's *meta* argument is False, then this decorator
returns the wrapped function output without applying the metadata.
Args:
xy (:obj:`bool`, optional): Set to True if the wrapped function returns
xy values (ll_to_xy). Set to False if the wrapped function returns
latlon values (xy_to_ll). Default is False.
Returns:
:class:`xarray.DataArray` or :class:`numpy.ndarray`: The wrapped
latlon function output with or without metadata. If xarray is
enabled and the *meta* parameter is True, then the result will be a
:class:`xarray.DataArray` object. Otherwise, the result will be a
:class:`numpy.ndarray` object with no metadata.
"""
@wrapt.decorator
def func_wrapper(wrapped, instance, args, kwargs):
argvars = from_args(wrapped, ("wrfin", "meta"), *args, **kwargs)
# If it's a mapping, then this is handled as a special case in g_latlon
do_meta = (not is_mapping(argvars["wrfin"]) and argvars["meta"])
if do_meta is None:
do_meta = True
if not xarray_enabled() or not do_meta:
return wrapped(*args, **kwargs)
# Set squeeze to False. Squeeze will be handled in here
new_args, squeeze_argloc = arg_location(wrapped, "squeeze", args,
kwargs)
new_args[squeeze_argloc] = False
result = wrapped(*new_args)
# Want to preserve the input coordinate pair in metadata
if result.ndim == 1:
result = result[:, np.newaxis]
argnames = ["x", "y"] if not xy else ["latitude", "longitude"]
argnames.append("squeeze")
outname = "latlon" if not xy else "xy"
if result.ndim == 2:
dimnames = (["lat_lon", "idx"] if not xy else ["x_y", "idx"])
else:
dimnames = (["lat_lon", "domain_idx", "idx"] if not xy
else ["x_y", "domain_idx", "idx"])
argvars = from_args(wrapped, argnames, *args, **kwargs)
var1 = argvars[argnames[0]]
var2 = argvars[argnames[1]]
squeeze = argvars["squeeze"]
arr1 = np.asarray(var1).ravel()
arr2 = np.asarray(var2).ravel()
coords = {}
if not xy:
coords["xy_coord"] = (dimnames[-1], [CoordPair(x=x[0], y=x[1])
for x in zip(arr1, arr2)])
coords[dimnames[0]] = ["lat", "lon"]
else:
coords["latlon_coord"] = (dimnames[-1],
[CoordPair(lat=x[0], lon=x[1])
for x in zip(arr1, arr2)])
coords[dimnames[0]] = ["x", "y"]
da = DataArray(result, name=outname, dims=dimnames, coords=coords)
if squeeze:
da = da.squeeze()
return da
return func_wrapper
def set_height_metadata(geopt=False, stag=False):
"""A decorator that sets the metadata for a wrapped height function's
output.
This is a special metadata decorator for working with height functions.
If the wrapped function's *meta* argument is False, then this decorator
returns the wrapped function output without applying the metadata.
Args:
geopt (:obj:`bool`, optional): Set to True if the wrapped function
returns geopotential. Set to True if the wrapped function
returns geopotential height. Default is False.
stag (:obj:`bool`, optional): Set to True to use the vertical
staggered grid, rather than the mass grid. Default is False.
Returns:
:class:`xarray.DataArray` or :class:`numpy.ndarray`: The wrapped
height function output with or without metadata. If xarray is
enabled and the *meta* parameter is True, then the result will be a
:class:`xarray.DataArray` object. Otherwise, the result will be a
:class:`numpy.ndarray` object with no metadata.
"""
@wrapt.decorator
def func_wrapper(wrapped, instance, args, kwargs):
do_meta = from_args(wrapped, ("meta",), *args, **kwargs)["meta"]
if do_meta is None:
do_meta = True
if not xarray_enabled() or not do_meta:
return wrapped(*args, **kwargs)
argvars = from_args(wrapped, ("wrfin", "timeidx", "method",
"squeeze", "units", "msl", "cache",
"_key"),
*args, **kwargs)
wrfin = argvars["wrfin"]
timeidx = argvars["timeidx"]
units = argvars["units"]
method = argvars["method"]
squeeze = argvars["squeeze"]
msl = argvars["msl"]
cache = argvars["cache"]
_key = argvars["_key"]
if cache is None:
cache = {}
is_met_em = False
# For height, either copy the met_em GHT variable or copy and modify
# pressure (which has the same dims as destaggered height)
if not stag:
ht_metadata_varname = either("P", "GHT")(wrfin)
else:
ht_metadata_varname = either("PH", "GHT")(wrfin)
if ht_metadata_varname == "GHT":
is_met_em = True
ht_var = extract_vars(wrfin, timeidx, ht_metadata_varname,
method, squeeze, cache, meta=True,
_key=_key)
ht_metadata_var = ht_var[ht_metadata_varname]
# Make a copy so we don't modify a user supplied cache
new_cache = dict(cache)
new_cache[ht_metadata_varname] = ht_metadata_var
# Don't modify the original args/kargs. The args need to be a list
# so it can be modified.
new_args, cache_argloc = arg_location(wrapped, "cache", args, kwargs)
new_args[cache_argloc] = new_cache
result = wrapped(*new_args)
outcoords = OrderedDict()
outattrs = OrderedDict()
outdimnames = list(ht_metadata_var.dims)
outcoords.update(ht_metadata_var.coords)
outattrs.update(ht_metadata_var.attrs)
if geopt:
outname = "geopt"
outattrs["units"] = "m2 s-2"
if not stag or is_met_em:
outattrs["description"] = "geopotential (mass grid)"
else:
outattrs["description"] = ("geopotential (vertically "
"staggered grid)")
else:
outname = "height" if msl else "height_agl"
outattrs["units"] = units
height_type = "MSL" if msl else "AGL"
if not stag or is_met_em:
outattrs["description"] = ("model height - [{}] "
"(mass grid)".format(height_type))
else:
outattrs["description"] = ("model height - [{}] (vertically "
"staggered grid)".format(
height_type))
return DataArray(result, name=outname, dims=outdimnames,
coords=outcoords, attrs=outattrs)
return func_wrapper
def _set_horiz_meta(wrapped, instance, args, kwargs):
"""A decorator implementation that sets the metadata for a wrapped
horizontal interpolation function.
If the wrapped function's *meta* argument is False, then this decorator
returns the wrapped function output without applying the metadata.
Args:
wrapped: The wrapped function which in turns needs to be called by your
wrapper function.
instance: The object to which the wrapped function was bound when it
was called.
args: The list of positional arguments supplied when the decorated
function was called.
kwargs: The dictionary of keyword arguments supplied when the decorated
function was called.
Returns:
:class:`xarray.DataArray` or :class:`numpy.ndarray`: The wrapped
horiztontal interpolation function output with or without metadata.
If xarray is enabled and the *meta* parameter is True, then the result
will be a :class:`xarray.DataArray` object. Otherwise, the result will
be a :class:`numpy.ndarray` object with no metadata.
See Also:
:mod:`wrapt`
"""
argvars = from_args(wrapped, ("field3d", "vert", "desiredlev",
"missing", "squeeze"),
*args, **kwargs)
field3d = argvars["field3d"]
z = argvars["vert"]
desiredlev = argvars["desiredlev"]
_desiredlev = np.asarray(desiredlev)
missingval = argvars["missing"]
squeeze = argvars["squeeze"]
result = wrapped(*args, **kwargs)
levsare2d = _desiredlev.ndim >= 2
multiproduct = field3d.ndim - z.ndim == 1
# Defaults, in case the data isn't a DataArray
outname = None
outdimnames = None
outcoords = None
outattrs = OrderedDict()
# Get the vertical level units
vert_units = None
if isinstance(z, DataArray):
vert_units = z.attrs.get("units", None)
if isinstance(field3d, DataArray):
outcoords = OrderedDict()
outdimnames = list(field3d.dims)
outcoords.update(field3d.coords)
del outdimnames[-3]
try:
del outcoords[field3d.dims[-3]]
except KeyError:
pass # xarray 0.9
if not levsare2d:
outdimnames.insert(-2, "level")
if _desiredlev.ndim == 0:
outcoords["level"] = [desiredlev]
else:
outcoords["level"] = _desiredlev
else:
if (_desiredlev.ndim == 2):
outcoords["level"] = field3d.dims[-2:], _desiredlev[:]
else:
if multiproduct:
d = field3d.dims[1:-3] + field3d.dims[-2:]
else:
d = field3d.dims[0:-3] + field3d.dims[-2:]
outcoords["level"] = d, _desiredlev[:]
outattrs.update(field3d.attrs)
outname = "{0}_interp".format(field3d.name)
else:
outname = "field3d_interp"
outattrs["missing_value"] = missingval
outattrs["_FillValue"] = missingval
outattrs["vert_units"] = vert_units
for key in ("MemoryOrder", "description"):
try:
del outattrs[key]
except KeyError:
pass
da = DataArray(result, name=outname, dims=outdimnames,
coords=outcoords, attrs=outattrs)
return da.squeeze() if squeeze else da
def _set_cross_meta(wrapped, instance, args, kwargs):
"""A decorator implementation that sets the metadata for a wrapped cross \
section interpolation function.
If the wrapped function's *meta* argument is False, then this decorator
returns the wrapped function output without applying the metadata.
Args:
wrapped: The wrapped function which in turns needs to be called by your
wrapper function.
instance: The object to which the wrapped function was bound when it
was called.
args: The list of positional arguments supplied when the decorated
function was called.
kwargs: The dictionary of keyword arguments supplied when the decorated
function was called.
Returns:
:class:`xarray.DataArray` or :class:`numpy.ndarray`: The wrapped
cross section interpolation function output with or without metadata.
If xarray is enabled and the *meta* parameter is True, then the result
will be a :class:`xarray.DataArray` object. Otherwise, the result will
be a :class:`numpy.ndarray` object with no metadata.
See Also:
:mod:`wrapt`
"""
argvars = from_args(wrapped, ("field3d", "vert", "levels",
"latlon", "missing",
"wrfin", "timeidx", "stagger", "projection",
"ll_point", "pivot_point", "angle",
"start_point", "end_point", "autolevels",
"cache"),
*args, **kwargs)
field3d = argvars["field3d"]
z = argvars["vert"]
levels = argvars["levels"]
inc_latlon = argvars["latlon"]
missingval = argvars["missing"]
wrfin = argvars["wrfin"]
timeidx = argvars["timeidx"]
stagger = argvars["stagger"]
projection = argvars["projection"]
ll_point = argvars["ll_point"]
pivot_point = argvars["pivot_point"]
angle = argvars["angle"]
start_point = argvars["start_point"]
end_point = argvars["end_point"]
autolevels = argvars["autolevels"]
cache = argvars["cache"]
start_point_xy = None
end_point_xy = None
pivot_point_xy = None
if (inc_latlon is True or is_latlon_pair(start_point) or
is_latlon_pair(pivot_point)):
if wrfin is not None:
is_moving = is_moving_domain(wrfin)
else:
is_moving = False
if timeidx is None:
if wrfin is not None:
# Moving nests aren't supported with ALL_TIMES because the
# domain could move outside of the line, which causes
# crashes or different line lengths.
if is_moving:
raise ValueError("Requesting all times with a moving nest "
"is not supported when using lat/lon "
"cross sections because the domain could "
"move outside of the cross section. "
"You must request each time "
"individually.")
else:
# Domain not moving, just use 0
_timeidx = 0
# If using grid coordinates, then don't care about lat/lon
# coordinates. Just use 0.
else:
_timeidx = 0
else:
if is_moving:
_timeidx = timeidx
else:
# When using non-moving nests, set the time to 0
# to avoid problems downstream
_timeidx = 0
if pivot_point is not None:
if pivot_point.lat is not None and pivot_point.lon is not None:
xy_coords = to_xy_coords(pivot_point, wrfin, _timeidx,
stagger, projection, ll_point)
pivot_point_xy = (xy_coords.x, xy_coords.y)
else:
pivot_point_xy = (pivot_point.x, pivot_point.y)
if start_point is not None and end_point is not None:
if start_point.lat is not None and start_point.lon is not None:
xy_coords = to_xy_coords(start_point, wrfin, _timeidx,
stagger, projection, ll_point)
start_point_xy = (xy_coords.x, xy_coords.y)
else:
start_point_xy = (start_point.x, start_point.y)
if end_point.lat is not None and end_point.lon is not None:
xy_coords = to_xy_coords(end_point, wrfin, _timeidx,
stagger, projection, ll_point)
end_point_xy = (xy_coords.x, xy_coords.y)
else:
end_point_xy = (end_point.x, end_point.y)
xy, var2dz, z_var2d = get_xy_z_params(to_np(z), pivot_point_xy, angle,
start_point_xy, end_point_xy,
levels, autolevels)
# Make a copy so we don't modify a user supplied cache
if cache is not None:
new_cache = dict(cache)
else:
new_cache = {}
new_cache["xy"] = xy
new_cache["var2dz"] = var2dz
new_cache["z_var2d"] = z_var2d