/
core.py
1860 lines (1525 loc) · 58.9 KB
/
core.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
""" Core utilities for handling GEOS-Chem data """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import yaml
import shutil
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np
import xarray as xr
import xbpch
import cartopy.crs as ccrs
import gcpy.constants as gcon
from .plot import WhGrYlRd
from .grid.horiz import make_grid_LL, make_grid_CS
from .grid.gc_vertical import GEOS_72L_grid, GEOS_47L_grid
from cartopy.mpl.geoaxes import GeoAxes
# YAML files to read
lumped_spc = "lumped_species.yml"
bpch_to_nc_names = "bpch_to_nc_names.yml"
def open_dataset(filename, **kwargs):
"""
Load and decode a dataset from an output file generated by GEOS-Chem.
This method inspects a GEOS-Chem output file and chooses a way to
load it into memory as an xarray Dataset. Because two different
libraries to support BPCH and netCDF outputs, you may need to pass
additional keyword arguments to the function.
Args:
-----
filename : str
Path to a GEOS-Chem output file (netCDF or BPCH format)
which can be loaded through either xarray or xbpch.
Note that xarray conventions for netCDF files apply.
Keyword Args (optional):
------------------------
Additional keyword arguments to be passed directly to
`xarray.open_dataset` or `xbpch.open_bpchdataset`.
Returns
-------
dataset : xarray.Dataset
The dataset loaded from the referenced filename.
See Also
--------
xarray.open_dataset
xbpch.open_bpchdataset
open_mfdataset
"""
basename, file_extension = os.path.splitext(filename)
# Modify the search so that we account for file names
# such as ".nc4.Ref", ".nc4.Dev", etc. (bmy, 10/1/19)
if file_extension == ".bpch":
_opener = xbpch.open_bpchdataset
elif ".nc" in file_extension:
_opener = xr.open_dataset
elif ".nc" in basename:
_opener = xr.open_dataset
else:
raise ValueError(
"Found unknown file extension ({}); please "
"pass a BPCH or netCDF file with extension "
'"bpch" or "nc"!'.format(file_extension)
)
return _opener(filename, **kwargs, drop_variables=gcon.skip_these_vars)
def open_mfdataset(
filenames,
concat_dim="time",
compat="no_conflicts",
preprocess=None,
lock=None,
**kwargs
):
"""
Load and decode multiple GEOS-Chem output files as a single Dataset.
Parameters
----------
filenames : list of str
Paths to GEOS-Chem output files to load. Must have the same
extension and be able to be concatenated along some common axis.
concat_dim : str, default='time'
Dimension to concatenate Datasets over. We default to "time"
since this is how GEOS-Chem splits output files.
compat : {'identical', 'equals', 'broadcast_equals',
'no_conflicts'}, optional
String indicating how to compare variables of the same name for
potential conflicts when merging:
- 'broadcast_equals': all values must be equal when
variables are broadcast against each other to ensure
common dimensions.
- 'equals': all values and dimensions must be the same.
- 'identical': all values, dimensions and attributes
must be the same.
- 'no_conflicts': only values which are not null in
both datasets must be equal. The returned dataset
then contains the combination of all non-null values.
Keyword Arguments (optional):
-----------------------------
preprocess : callable (optional)
A pre-processing function to apply to each Dataset prior to
concatenation
lock : False, True, or threading.Lock (optional)
Passed to :py:func:`dask.array.from_array`. By default,
xarray employs a per-variable lock when reading data from
NetCDF files, but this model has not yet been extended or
implemented for bpch files and so this is not actually used.
However, it is likely necessary before dask's multi-threaded
backend can be used.
**kwargs
Additional keyword arguments to be passed directly to
`xbpch.open_mfbpchdataset` or `xarray.open_mfdataset`.
Returns
-------
dataset : xarray.Dataset
A dataset containing the data in the specified input filenames.
See Also
--------
xarray.open_mfdataset
xbpch.open_mfbpchdataset
open_dataset
"""
# If filenames is a single string, then make it a list of length 1
if isinstance(filenames, str):
filenames = [filenames]
# Make sure that filenames is a list before proceeding
if not isinstance(filenames, list):
raise ValueError("The filenames argument must be a list of str!")
# Get the file name and file extension
test_fn = filenames[0]
basename, file_extension = os.path.splitext(test_fn)
# Modify the search so that we account for file names
# such as ".nc4.Ref", ".nc4.Dev", etc. (bmy, 10/1/19)
if file_extension == ".bpch":
_opener = xbpch.open_mfbpchdataset
elif ".nc" in file_extension:
_opener = xr.open_mfdataset
elif ".nc" in basename:
_opener = xr.open_mfdataset
else:
raise ValueError(
"Found unknown file extension ({}); please ".format(file_extension)
+ "pass a BPCH or netCDF file with extension "
+ '"bpch" or "nc" or "nc4"'
)
return _opener(
filenames,
concat_dim=concat_dim,
compat=compat,
preprocess=preprocess,
lock=lock,
drop_variables=gcon.skip_these_vars,
**kwargs
)
def check_paths(refpath, devpath):
"""
Checks to see if paths to data files exist.
Args:
-----
refpath : str
Path to the "Reference" data.
devpath : str
Path to the "Development" data.
"""
if not os.path.exists(refpath):
print("ERROR! Path 1 does not exist: {}".format(refpath))
else:
print("Path 1 exists: {}".format(refpath))
if not os.path.exists(devpath):
print("ERROR! Path 2 does not exist: {}".format(devpath))
else:
print("Path 2 exists: {}".format(devpath))
def compare_varnames(refdata, devdata, refonly=[], devonly=[], quiet=False):
"""
Finds variables that are common to two xarray Dataset objects.
Args:
-----
refdata : xarray Dataset
The first Dataset to be compared.
(This is often referred to as the "Reference" Dataset.)
devdata : xarray Dataset
The second Dataset to be compared.
(This is often referred to as the "Development" Dataset.)
Keyword Args (optional):
------------------------
quiet : boolean
Set this flag to True if you wish to suppress printing
informational output to stdout.
Default value: False
Returns:
--------
vardict : dict of lists of str
Dictionary containing several lists of variable names:
Key Value
----- -----
commonvars List of variables that are common to
both refdata and devdata
commonvarsOther List of variables that are common
to both refdata and devdata, but do
not have lat, lon, and/or level
dimensions (e.g. index variables).
commonvars2D List of variables that are common to
common to refdata and devdata, and that
have lat and lon dimensions, but not level.
commonvars3D List of variables that are common to
refdata and devdata, and that have lat,
lon, and level dimensions.
refonly List of 2D or 3D variables that are only
present in refdata.
devonly List of 2D or 3D variables that are only
present in devdata
"""
refvars = [k for k in refdata.data_vars.keys()]
devvars = [k for k in devdata.data_vars.keys()]
commonvars = sorted(list(set(refvars).intersection(set(devvars))))
refonly = [v for v in refvars if v not in devvars]
devonly = [v for v in devvars if v not in refvars]
dimmismatch = [v for v in commonvars if refdata[v].ndim != devdata[v].ndim]
commonvarsOther = [
v
for v in commonvars
if (
("lat" not in refdata[v].dims or "Xdim" not in refdata[v].dims)
and ("lon" not in refdata[v].dims or "Ydim" not in refdata[v].dims)
and ("lev" not in refdata[v].dims)
)
]
commonvars2D = [
v
for v in commonvars
if (
("lat" in refdata[v].dims or "Xdim" in refdata[v].dims)
and ("lon" in refdata[v].dims or "Ydim" in refdata[v].dims)
and ("lev" not in refdata[v].dims)
)
]
commonvars3D = [
v
for v in commonvars
if (
("lat" in refdata[v].dims or "Xdim" in refdata[v].dims)
and ("lon" in refdata[v].dims or "Ydim" in refdata[v].dims)
and ("lev" in refdata[v].dims)
)
]
# Print information on common and mismatching variables,
# as well as dimensions
if quiet == False:
print("\nComparing variable names in compare_varnames")
print("{} common variables".format(len(commonvars)))
if len(refonly) > 0:
print("{} variables in ref only (skip)".format(len(refonly)))
print(" Variable names: {}".format(refonly))
else:
print("0 variables in ref only")
if len(devonly) > 0:
print("{} variables in dev only (skip)".format(len(devonly)))
print(" Variable names: {}".format(devonly))
else:
print("0 variables in dev only")
if len(dimmismatch) > 0:
print(
"{} common variables have different dimensions".format(
len(dimmismatch)
)
)
print(" Variable names: {}".format(dimmismatch))
else:
print("All variables have same dimensions in ref and dev")
# For safety's sake, remove the 0-D and 1-D variables from
# refonly and devonly. This will ensure that refonly and
# devonly will only contain variables that can be plotted.
refonly = [v for v in refonly if v not in commonvarsOther]
devonly = [v for v in devonly if v not in commonvarsOther]
return {
"commonvars": commonvars,
"commonvarsOther": commonvarsOther,
"commonvars2D": commonvars2D,
"commonvars3D": commonvars3D,
"refonly": refonly,
"devonly": devonly,
}
def compare_stats(refdata, refstr, devdata, devstr, varname):
"""
Prints out global statistics (array sizes, mean, min, max, sum)
from two xarray Dataset objects.
Args:
----
refdata : xarray Dataset
The first Dataset to be compared.
(This is often referred to as the "Reference" Dataset.)
refstr : str
Label for refdata to be used in the printout
devdata : xarray Dataset
The second Dataset to be compared.
(This is often referred to as the "Development" Dataset.)
devstr : str
Label for devdata to be used in the printout
varname : str
Variable name for which global statistics will be printed out.
"""
refvar = refdata[varname]
devvar = devdata[varname]
units = refdata[varname].units
print("Data units:")
print(" {}: {}".format(refstr, units))
print(" {}: {}".format(devstr, units))
print("Array sizes:")
print(" {}: {}".format(refstr, refvar.shape))
print(" {}: {}".format(devstr, devvar.shape))
print("Global stats:")
print(" Mean:")
print(" {}: {}".format(refstr, np.round(refvar.values.mean(), 20)))
print(" {}: {}".format(devstr, np.round(devvar.values.mean(), 20)))
print(" Min:")
print(" {}: {}".format(refstr, np.round(refvar.values.min(), 20)))
print(" {}: {}".format(devstr, np.round(devvar.values.min(), 20)))
print(" Max:")
print(" {}: {}".format(refstr, np.round(refvar.values.max(), 20)))
print(" {}: {}".format(devstr, np.round(devvar.values.max(), 20)))
print(" Sum:")
print(" {}: {}".format(refstr, np.round(refvar.values.sum(), 20)))
print(" {}: {}".format(devstr, np.round(devvar.values.sum(), 20)))
def get_collection_data(datadir, collection, day, time):
datafile = get_gcc_filepath(datadir, collection, day, time)
if not os.path.exists(datafile):
print("ERROR! File does not exist: {}".format(datafile))
data_ds = xr.open_dataset(datafile)
return data_ds
def get_gchp_collection_data(datadir, collection, day, time):
datafile = get_gchp_filepath(datadir, collection, day, time)
data_ds = xr.open_dataset(datafile)
return data_ds
def convert_bpch_names_to_netcdf_names(ds, verbose=False):
"""
Function to convert the non-standard bpch diagnostic names
to names used in the GEOS-Chem netCDF diagnostic outputs.
Args:
-----
ds : xarray Dataset
The xarray Dataset object whose names are to be replaced.
Keyword Args (optional):
------------------------
verbose : boolean
Set this flag to True to print informational output.
Default value: False
Returns:
--------
ds_new : xarray Dataset
A new xarray Dataset object all of the bpch-style
diagnostic names replaced by GEOS-Chem netCDF names.
Remarks:
--------
To add more diagnostic names, edit the dictionary contained
in the bpch_to_nc_names.yml.
"""
# Names dictionary (key = bpch id, value[0] = netcdf id,
# value[1] = action to create full name using id)
# Now read from YAML file (bmy, 4/5/19)
yamlfile = os.path.join(os.path.dirname(__file__), bpch_to_nc_names)
names = yaml.load(open(yamlfile))
# define some special variable to overwrite above
special_vars = {
"Met_AIRNUMDE": "Met_AIRNUMDEN",
"Met_UWND": "Met_U",
"Met_VWND": "Met_V",
"Met_CLDTOP": "Met_CLDTOPS",
"Met_GWET": "Met_GWETTOP",
"Met_PRECON": "Met_PRECCON",
"Met_PREACC": "Met_PRECTOT",
"Met_PBL": "Met_PBLH",
}
# Tags for the UVFlux* diagnostics
uvflux_tags = [
"187nm",
"191nm",
"193nm",
"196nm",
"202nm",
"208nm",
"211nm",
"214nm",
"261nm",
"267nm",
"277nm",
"295nm",
"303nm",
"310nm",
"316nm",
"333nm",
"380nm",
"574nm",
]
# Python dictionary for variable name replacement
old_to_new = {}
# Loop over all variable names in the data set
for variable_name in ds.data_vars.keys():
# Save the original variable name, since this is the name
# that we actually need to replace in the dataset.
original_variable_name = variable_name
# Replace "__" with "_", in variable name (which will get tested
# against the name sin the YAML file. This will allow us to
# replace variable names in files created with BPCH2COARDS.
if "__" in variable_name:
variable_name = variable_name.replace("__", "_")
# Check if name matches anything in dictionary. Give warning if not.
oldid = ""
newid = ""
idaction = ""
for key in names:
if key in variable_name:
if names[key][1] == "skip":
# Verbose output
if verbose:
print("WARNING: skipping {}".format(key))
else:
oldid = key
newid = names[key][0]
idaction = names[key][1]
break
# Go to the next line if no definition was found
if oldid == "" or newid == "" or idaction == "":
continue
# If fullname replacement:
if idaction == "replace":
oldvar = oldid
newvar = newid
# Update the dictionary of names with this pair
# Use the original variable name.
old_to_new.update({original_variable_name: newvar})
# For all the rest:
else:
linearr = variable_name.split("_")
varstr = linearr[-1]
oldvar = oldid + varstr
# These categories use append
if oldid in [
"IJ_AVG_S_",
"RN_DECAY_",
"WETDCV_S_",
"WETDLS_S_",
"BXHGHT_S_",
"DAO_3D_S_",
"PL_SUL_",
"CV_FLX_S_",
"EW_FLX_S_",
"NS_FLX_S_",
"UP_FLX_S_",
"MC_FRC_S_",
]:
newvar = newid + "_" + varstr
# DAO_FLDS
# Skip certain fields that will cause conflicts w/ netCDF
elif oldid in "DAO_FLDS_":
if oldid in ["DAO_FLDS_PS_PBL", "DAO_FLDS_TROPPRAW"]:
# Verbose output
if verbose:
print("Skipping: {}".format(oldid))
else:
newvar = newid + "_" + varstr
# Special handling for J-values: The bpch variable names all
# begin with "J" (e.g. JNO, JACET), so we need to strip the first
# character of the variable name manually (bmy, 4/8/19)
elif oldid == "JV_MAP_S_":
newvar = newid + "_" + varstr[1:]
# IJ_SOA_S_
elif oldid == "IJ_SOA_S_":
newvar = newid + varstr
# DRYD_FLX_, DRYD_VEL_
elif "DRYD_" in oldid:
newvar = newid + "_" + varstr[:-2]
# BIOBSRCE_, BIOFSRCE_, BIOGSRCE_. ANTHSRCE_
elif oldid in ["BIOBSRCE_", "BIOFSRCE_", "BIOGSRCE_", "ANTHSRCE_"]:
newvar = "Emis" + varstr + "_" + newid
# Special handling for UV radiative flux diagnostics:
# We need to append the bin descriptor to the new name.
elif "FJX_FLXS" in oldid:
uvind = int(original_variable_name[-2:]) - 1
newvar = newid + "_" + uvflux_tags[uvind]
# If nothing found...
else:
# Verbose output
if verbose:
print("WARNING: Nothing defined for: {}".format(variable_name))
continue
# Overwrite certain variable names
if newvar in special_vars:
newvar = special_vars[newvar]
# Update the dictionary of names with this pair
old_to_new.update({original_variable_name: newvar})
# Verbose output
if verbose:
print("\nList of bpch names and netCDF names")
for key in old_to_new:
print("{} ==> {}".format(key.ljust(25), old_to_new[key].ljust(40)))
# Rename the variables in the dataset
if verbose:
print("\nRenaming variables in the data...")
with xr.set_options(keep_attrs=True):
ds = ds.rename(name_dict=old_to_new)
# Return the dataset
return ds
def get_lumped_species_definitions():
yamlfile = os.path.join(os.path.dirname(__file__), lumped_spc)
with open(yamlfile, "r") as f:
lumped_spc_dict = yaml.load(f.read())
return lumped_spc_dict
def archive_lumped_species_definitions(dst):
src = os.path.join(os.path.dirname(__file__), lumped_spc)
print("Archiving {} in {}".format(lumped_spc, dst))
shutil.copyfile(src, os.path.join(dst, lumped_spc))
def add_lumped_species_to_dataset(
ds,
lspc_dict={},
lspc_yaml="",
verbose=True,
overwrite=False,
prefix="SpeciesConc_",
):
"""
Function to calculate lumped species concentrations and add
them to an xarray Dataset. Lumped species definitions may be passed
as a dictionary or a path to a yaml file. If neither is passed then
the lumped species yaml file stored in gcpy is used. This file is
customized for use with benchmark simuation SpeciesConc diagnostic
collection output.
Args:
-----
ds : xarray Dataset
An xarray Dataset object prior to adding lumped species.
Keyword Args (optional):
------------------------
lspc_dict : dictionary
Dictionary containing list of constituent species and their
integer scale factors per lumped species.
Default value: False
lspc_yaml : str
Set this flag to True to print informational output.
Default value: False
verbose : boolean
Whether to print informational output.
Default value: True
overwrite : boolean
Whether to overwrite an existing species dataarray in a dataset
if it has the same name as a new lumped species. If False and
overlapping names are found then the function will raise an error.
Default value: False
prefix : str
Prefix to prepend to new lumped species names. This argument is
also used to extract an existing dataarray in the dataset with
the correct size and dimensions to use during initialization of
new lumped species dataarrays.
Default value: SpeciesConc_
Returns:
--------
ds_new : xarray Dataset
A new xarray Dataset object containing all of the original
species plus new lumped species.
"""
# Default is to add all benchmark lumped species.
# Can overwrite by passing a dictionary
# or a yaml file path containing one
assert not (
lspc_dict != {} and lspc_yaml != ""
), "Cannot pass both lspc_dict and lspc_yaml. Choose one only."
if lspc_dict == {} and lspc_yaml == "":
lspc_dict = get_lumped_species_definitions()
elif lspc_dict == {} and lspc_yaml != "":
with open(lspc_yaml, "r") as f:
lspc_dict = yaml.load(f.read())
# Get a dummy array to use for initialization
for var in ds.data_vars:
if prefix in var:
dummy_darr = ds[var]
break
# Create a new dataset equivalent to the old
ds_new = ds
for lspc in lspc_dict:
# Assemble lumped species variable name
varname_new = prefix + lspc
# Check if overlap with existing species
if varname_new in ds_new.data_vars and overwrite:
ds_new.drop(varname_new)
else:
assert(varname_new not in ds_new.data_vars), \
"{} already in dataset. To overwrite pass overwrite=True.".\
format(varname_new)
# Verbose prints
if verbose:
print("Creating {}".format(varname_new))
# Initialize new dataarray
darr = dummy_darr
darr.name = varname_new
darr.values = np.full(darr.shape, 0.0)
# Loop over and sum constituent species values
num_spc = 0
for i, spc in enumerate(lspc_dict[lspc]):
varname = prefix + spc
if varname not in ds_new.data_vars:
print("Warning: {} needed for {} not in dataset.".\
format(spc, lspc))
continue
if verbose:
print(" -> adding {} with scale {}".\
format(spc, lspc_dict[lspc][spc]))
darr.values = darr.values + \
ds_new[varname].values * lspc_dict[lspc][spc]
num_spc = num_spc + 1
# Replace values with NaN is no species found in dataset
if num_spc == 0:
print('No constituent species found in file. Setting to NaN.')
darr.values = np.full(darr.shape, np.nan)
# Merge new variable into dataset
ds_new = xr.merge([ds_new, darr])
return ds_new
def filter_names(names, text=""):
"""
Returns elements in a list that match a given substring.
Can be used in conjnction with compare_varnames to return a subset
of variable names pertaining to a given diagnostic type or species.
Args:
-----
names: list of str
Input list of names.
text: str
Target text string for restricting the search.
Returns:
--------
filtered_names: list of str
Returns all elements of names that contains the substring
specified by the "text" argument. If "text" is omitted,
then the original contents of names will be returned.
"""
if text != "":
filtered_names = [k for k in names if text in k]
else:
filtered_names = [k for k in names if k]
return filtered_names
def divide_dataset_by_dataarray(ds, dr, varlist=None):
"""
Divides variables in an xarray Dataset object by a single DataArray
object. Will also make sure that the Dataset variable attributes
are preserved.
This method can be useful for certain types of model diagnostics
that have to be divided by a counter array. For example, local
noontime J-value variables in a Dataset can be divided by the
fraction of time it was local noon in each grid box, etc.
Args:
-----
ds: xarray Dataset
The Dataset object containing variables to be divided.
dr: xarray DataArray
The DataArray object that will be used to divide the
variables of ds.
Keyword Args (optional):
------------------------
varlist: list of str
If passed, then only those variables of ds that are listed
in varlist will be divided by dr. Otherwise, all variables
of ds will be divided by dr.
Returns:
--------
ds_new : xarray Dataset
A new xarray Dataset object with its variables divided by dr.
"""
# -----------------------------
# Check arguments
# -----------------------------
if not isinstance(ds, xr.Dataset):
raise TypeError("The ds argument must be of type xarray.Dataset!")
if not isinstance(dr, xr.DataArray):
raise TypeError("The dr argument must be of type xarray.DataArray!")
if varlist is None:
varlist = ds.data_vars.keys()
# -----------------------------
# Do the division
# -----------------------------
# Keep all Dataset attributes
with xr.set_options(keep_attrs=True):
# Loop over variables
for v in varlist:
# Divide each variable of ds by dr
ds[v] = ds[v] / dr
return ds
def get_shape_of_data(data, vertical_dim="lev", return_dims=False):
"""
Convenience routine to return a the shape (and dimensions, if
requested) of an xarray Dataset, or xarray DataArray. Can also
also take as input a dictionary of sizes (i.e. {'time': 1,
'lev': 72, ...} from an xarray Dataset or xarray Datarray object.
Args:
-----
data : xarray Dataset, xarray DataArray, or dict
The data for which the size is requested.
Keyword Args (optional):
-------------------------
vertical_dim : str
Specify the vertical dimension that you wish to
return: lev or ilev.
Default value: 'lev'
return_dims : bool
Set this switch to True if you also wish to return a list of
dimensions in the same order as the tuple of dimension sizes.
Default value: False
Returns:
--------
shape : tuple of int
Tuple containing the sizes of each dimension of dr in order:
(time, lev|ilev, nf, lat|YDim, lon|XDim).
dims : list of str
If return_dims is True, then dims will contain a list of
dimension names in the same order as shape
(['time', 'lev', 'lat', 'lon'] for GEOS-Chem "Classic",
or ['time', 'lev', 'nf', 'Ydim', 'Xdim'] for GCHP.
"""
# Validate the data argument
if isinstance(data, xr.Dataset) or isinstance(data, xr.DataArray):
sizelist = data.sizes
elif isinstance(data, dict):
sizelist = data
else:
msg = (
'The "dataset" argument must be either an xarray Dataset, '
+ " xarray DataArray, or a dictionary!"
)
raise ValueError(msg)
# Initialize
dimlist = ["time", vertical_dim, "lat", "nf", "Ydim", "lon", "Xdim"]
shape = ()
dims = []
# Return a tuple with the shape of each dimension (and also a
# list of each dimension if return_dims is True).
for d in dimlist:
if d in sizelist:
shape += (sizelist[d],)
dims.append(d)
if return_dims:
return shape, dims
else:
return shape
def get_area_from_dataset(ds):
"""
Convenience routine to return the area variable (which is
usually called "AREA" for GEOS-Chem "Classic" or "Met_AREAM2"
for GCHP) from an xarray Dataset object.
Args:
-----
ds : xarray Dataset
The input dataset.
Returns:
--------
area_m2 : xarray DataArray
The surface area in m2, as found in ds.
"""
if "Met_AREAM2" in ds.data_vars.keys():
return ds["Met_AREAM2"]
elif "AREA" in ds.data_vars.keys():
return ds["AREA"]
else:
msg = (
'An area variable ("AREA" or "Met_AREAM2" is missing'
+ " from this dataset!"
)
raise ValueError(msg)
def get_variables_from_dataset(ds, varlist):
"""
Convenience routine to return multiple selected DataArray
variables from an xarray Dataset. All variables must be
found in the Dataset, or else an error will be raised.
Args:
-----
ds : xarray Dataset
The input dataset.
varlist : list of str
List of DataArray variables to extract from ds.
Returns:
--------
ds_subset : xarray Dataset
A new data set containing only the variables
that were requested.
Remarks:
-------
Use this routine if you absolutely need all of the requested
variables to be returned. Otherwise
"""
ds_subset = xr.Dataset()
for v in varlist:
if v in ds.data_vars.keys():
ds_subset = xr.merge([ds_subset, ds[v]])
else:
msg = "{} was not found in this dataset!".format(v)
raise ValueError(msg)
return ds_subset
def create_dataarray_of_nan(name, sizes, coords, attrs, vertical_dim="lev"):
"""
Given an xarray DataArray dr, returns a DataArray object with
the same dimensions, coordinates, attributes, and name, but
with its data set to missing values (NaN) everywhere.
This is useful if you need to plot or compare two DataArray
variables, and need to represent one as missing or undefined.
Args:
-----
name : str
The name for the DataArray object that will contain NaNs.
sizes : dict of int
Dictionary of the dimension names and their sizes (e.g.
{'time' : 1 ', 'lev': 72, ...} that will be used to create
the DataArray of NaNs. This can be obtained from an
xarray Dataset as ds.sizes.
coords : dict of lists of float
Dictionary containing the coordinate variables that will
be used to create the DataArray of NaNs. This can be obtained
from an xarray Dataset with ds.coords.
attrs : dict of str
Dictionary containing the DataArray variable attributes
(such as "units", "long_name", etc.). This can be obtained
from an xarray Dataset with dr.attrs.
Returns:
--------
dr : xarray DataArray
The output DataArray object, which will contain NaN values
everywhere. This will denote missing data.