-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathload_gridded_data.py
3341 lines (2818 loc) · 143 KB
/
load_gridded_data.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Module: load_gridded_data.py
Purpose: Contains functions used in the uploading of the various gridded datasets
(calibration and prior) needed by the LMR.
Originator: Robert Tardif, U. of Washington, January 2015
Revisions:
- Added function for the upload of the GPCC historical precipitation dataset.
[R. Tardif, U of Washington, December 2015]
- Added function for uploading the ERA20CM *ensemble* to be used as prior.
[R. Tardif, U of Washington, February 2016]
- Added function for the upload of the Dai historical PDSI dataset.
[R. Tardif, U of Washington, May 2016]
- Added function to upload the data from the TraCE21ka climate simulation.
[R. Tardif, U of Washington, December 2016]
- Modified the read_gridded_data_CMIP5_model function to handle fields with
lats/lons defined using 2d arrays (on irregular grids), and added
possibility of returning multiyear averages.
[R. Tardif, U of Washington, March 2017]
- Modified the read_gridded_data_CMIP5_model function to handle fields with
dims as [time,lat] (latitudinally-averaged) and [time,lev,lat]
(latitude-depth cross-sections).
[R. Tardif, U of Washington, April 2017]
- Minor fix to detrending functionality to handle fields with masked values
[R. Tardif, U of Washington, April 2017]
- Added the function read_gridded_data_cGENIE_model to read data files
derived from output of the cGENIE EMIC.
[R. Tardif, U of Washington, Aug 2017]
- Modified the read_gridded_data_CMIP5_model function for greater flexibility
in handling names of geographical coordinates in input .nc files.
[R. Tardif, U of Washington, Aug 2017]
- Bug fix to calculation of anomalies to specific reference period in
read_gridded_data_GPCC, read_gridded_data_DaiPDSI and read_gridded_data_SPEI
[M. Erb, N. Arizona U. & R. Tardif, U of Washington, Feb 2018]
- Reference period w.r.t. which anomalies are computed are now passed as argument
to functions tasked with uploading instrumental-era calibration datasets.
[R. Tardif, U. of Washington, February 2018]
"""
from netCDF4 import Dataset, date2num, num2date
from datetime import datetime, timedelta
from calendar import monthrange
from scipy import stats
import numpy as np
import pylab as pl
import os.path
import string
import math
def read_gridded_data_GISTEMP(data_dir,data_file,data_vars,outfreq,ref_period):
#==========================================================================================
#
# Reads the monthly data of surface air temperature anomalies from the GISTEMP gridded
# product.
#
# Input:
# - data_dir : Full name of directory containing gridded
# data. (string)
# - data_file : Name of file containing gridded data. (string)
#
# - data_vars : List of variable names to read. (string list)
# Here should simply be ['Tsfc'], as only sfc temperature
# data (anomalies) are contained in the file.
#
# - outfreq : string indicating whether to return monthly or annual averages
#
# - ref_period : two-element list indicating the period w.r.t. which anomalies
# are to be referenced. Set to None if no processing required,
# otherwise expects [start,end] ex. [1951,1980]
#
# Output: (numpy arrays)
# - time_yrs : Array with years over which data is available.
# dims: [nb_years]
# - lat : Array containing the latitudes of gridded data.
# dims: [lat]
# - lon : Array containing the longitudes of gridded data.
# dims: [lon]
# - value : Array with the annually-averaged data calculated from monthly data
# dims: [time,lat,lon]
#
#==========================================================================================
nbmaxnan = 0 # max nb of nan's allowed in calculation of annual average
# Check if file exists
infile = data_dir+'/GISTEMP/'+data_file
if not os.path.isfile(infile):
raise SystemExit(('Error in specification of gridded dataset. '
'File {} does not exist. Exiting.').format(infile))
# Sanity check on number of variables to read
if len(data_vars) > 1:
raise SystemExit('Too many variables to read! This file only contains'
' surface air temperature (anomalies). Exiting.')
dateref = datetime(1800,1,1,0)
data = Dataset(infile,'r')
lat = data.variables['lat'][:]
lon = data.variables['lon'][:]
indneg = np.where(lon < 0)[0]
if len(indneg) > 0: # if non-empty
lon[indneg] = 360.0 + lon[indneg]
# ----------------------------------------------------------------------------------
# Convert time from "nb of days from dateref" to actual date/time as datetime object
# ----------------------------------------------------------------------------------
ntime = len(data.dimensions['time'])
daysfromdateref = data.variables['time'][:]
dates = np.array([dateref + timedelta(days=int(i)) for i in daysfromdateref])
fillval = np.power(2,15)-1
value = np.copy(data.variables['tempanomaly'])
value[value == fillval] = np.NAN
if ref_period:
climo_month = np.zeros([12, len(lat), len(lon)], dtype=float)
# loop over months
for i in range(12):
m = i+1
indsmref = [j for j,v in enumerate(dates) if v.year >= ref_period[0] and v.year <= ref_period[1] and v.month == m]
indsm = [j for j,v in enumerate(dates) if v.month == m]
climo_month[i] = np.nanmean(value[indsmref], axis=0)
value[indsm] = (value[indsm] - climo_month[i])
else:
print('Warning: using default reference period defining temperature anomalies for GISTEMP product.')
if outfreq == 'annual':
# List years available in dataset and sort
years = list(set([d.year for d in dates])) # 'set' is used to get unique values in list
years.sort # sort the list
dates_annual = np.array([datetime(y,1,1,0,0) for y in years])
value_annual = np.empty([len(years), len(lat), len(lon)], dtype=float)
value_annual[:] = np.nan # initialize with nan's
# Loop over years in dataset
for i in range(0,len(years)):
# find indices in time array where "years[i]" appear
ind = [j for j, k in enumerate(dates) if k.year == years[i]]
# ---------------------------------------
# Calculate annual mean from monthly data
# Note: data has dims [time,lat,lon]
# ---------------------------------------
tmp = np.nanmean(value[ind],axis=0)
# apply check of max nb of nan values allowed
nancount = np.isnan(value[ind]).sum(axis=0)
tmp[nancount > nbmaxnan] = np.nan # put nan back if nb of nan's in current year above threshold
value_annual[i,:,:] = tmp
dates_ret = dates_annual
value_ret = value_annual
else:
dates_ret = dates
value_ret = value
return dates_ret, lat, lon, value_ret
#==========================================================================================
def read_gridded_data_HadCRUT(data_dir,data_file,data_vars,outfreq,ref_period):
#==========================================================================================
#
# Reads the monthly data of surface air temperature anomalies from the HadCRUT gridded
# product.
#
# Input:
# - data_dir : Full name of directory containing gridded
# data. (string)
# - data_file : Name of file containing gridded data. (string)
#
# - data_vars : List of variable names to read. (string list)
# Here should simply be ['Tsfc'], as only sfc temperature
# data (anomalies) are contained in the file.
# - outfreq : string indicating whether to return monthly or annual averages
#
# - ref_period : two-element list indicating the period w.r.t. which anomalies
# are to be referenced. Set to None if no processing required,
# otherwise expects [start,end] ex. [1951,1980]
#
# Output: (numpy arrays)
# - time_yrs : Array with years over which data is available.
# dims: [nb_years]
# - lat : Array containing the latitudes of gridded data.
# dims: [lat]
# - lon : Array containing the longitudes of gridded data.
# dims: [lon]
# - value : Array with the annually-averaged data calculated from monthly data
# dims: [time,lat,lon]
#
#==========================================================================================
nbmaxnan = 0 # max nb of nan's allowed in calculation of annual average
# Check if file exists
infile = data_dir+'/HadCRUT/'+data_file
if not os.path.isfile(infile):
raise SystemExit(('Error in specification of gridded dataset. '
'File {} does not exist. Exiting.').format(infile))
# Sanity check on number of variables to read
if len(data_vars) > 1:
raise SystemExit('Too many variables to read! This file only contains'
' surface air temperature (anomalies). Exiting.')
dateref = datetime(1850,1,1,0)
data = Dataset(infile,'r')
lat = data.variables['latitude'][:]
lon = data.variables['longitude'][:]
indneg = np.where(lon < 0)[0]
if len(indneg) > 0: # if non-empty
lon[indneg] = 360.0 + lon[indneg]
# -------------------------------------------------------------
# Convert time from "nb of days from dateref" to absolute years
# -------------------------------------------------------------
ntime = len(data.dimensions['time'])
daysfromdateref = data.variables['time'][:]
dates = np.array([dateref + timedelta(days=int(i)) for i in daysfromdateref])
value = np.copy(data.variables['temperature_anomaly'])
value[value == -1e+30] = np.NAN
if ref_period:
climo_month = np.zeros([12, len(lat), len(lon)], dtype=float)
# loop over months
for i in range(12):
m = i+1
indsmref = [j for j,v in enumerate(dates) if v.year >= ref_period[0] and v.year <= ref_period[1] and v.month == m]
indsm = [j for j,v in enumerate(dates) if v.month == m]
climo_month[i] = np.nanmean(value[indsmref], axis=0)
value[indsm] = (value[indsm] - climo_month[i])
else:
print('Warning: using default reference period defining temperature anomalies for HadCRUT product.')
if outfreq == 'annual':
# List years available in dataset and sort
years = list(set([d.year for d in dates])) # 'set' is used to get unique values in list
years.sort # sort the list
dates_annual = np.array([datetime(y,1,1,0,0) for y in years])
value_annual = np.empty([len(years), len(lat), len(lon)], dtype=float)
value_annual[:] = np.nan # initialize with nan's
# Loop over years in dataset
for i in range(0,len(years)):
# find indices in time array where "years[i]" appear
ind = [j for j, k in enumerate(dates) if k.year == years[i]]
# ---------------------------------------
# Calculate annual mean from monthly data
# Note: data has dims [time,lat,lon]
# ---------------------------------------
tmp = np.nanmean(value[ind],axis=0)
# apply check of max nb of nan values allowed
nancount = np.isnan(value[ind]).sum(axis=0)
tmp[nancount > nbmaxnan] = np.nan # put nan back if nb of nan's in current year above threshold
value_annual[i,:,:] = tmp
dates_ret = dates_annual
value_ret = value_annual
else:
dates_ret = dates
value_ret = value
return dates_ret, lat, lon, value_ret
#==========================================================================================
def read_gridded_data_BerkeleyEarth(data_dir,data_file,data_vars,outfreq,ref_period):
#==========================================================================================
#
# Reads the monthly data of surface air temperature anomalies from the BerkeleyEarth gridded
# product.
#
# Input:
# - data_dir : Full name of directory containing gridded
# data. (string)
# - data_file : Name of file containing gridded data. (string)
#
# - data_vars : List of variable names to read. (string list)
# Here should simply be ['Tsfc'], as only sfc temperature
# data (anomalies) are contained in the file.
#
# - outfreq : string indicating whether to return monthly or annual averages
#
# - ref_period : two-element list indicating the period w.r.t. which anomalies
# are to be referenced. Set to None if no processing required,
# otherwise expects [start,end] ex. [1951,1980]
#
# Output: (numpy arrays)
# - time_yrs : Array with years over which data is available.
# dims: [nb_years]
# - lat : Array containing the latitudes of gridded data.
# dims: [lat]
# - lon : Array containing the longitudes of gridded data.
# dims: [lon]
# - value : Array with the annually-averaged data calculated from monthly data
# dims: [time,lat,lon]
#
#==========================================================================================
nbmaxnan = 0 # max nb of nan's allowed in calculation of annual average
# Check if file exists
infile = data_dir+'/BerkeleyEarth/'+data_file
if not os.path.isfile(infile):
raise SystemExit(('Error in specification of gridded dataset. '
'File {} does not exist. Exiting.').format(infile))
# Sanity check on number of variables to read
if len(data_vars) > 1:
raise SystemExit('Too many variables to read! This file only contains'
' surface air temperature (anomalies). Exiting.')
data = Dataset(infile,'r')
lat = data.variables['latitude'][:]
lon = data.variables['longitude'][:]
indneg = np.where(lon < 0)[0]
if len(indneg) > 0: # if non-empty
lon[indneg] = 360.0 + lon[indneg]
# -------------------------------------------------------------
# Time is in year A.D. (in decimal real number)
# -------------------------------------------------------------
ntime = len(data.dimensions['time'])
time_yrs = []
for i in range(0,len(data.variables['time'][:])):
yrAD = data.variables['time'][i]
year = int(yrAD)
rem = yrAD - year
base = datetime(year, 1, 1)
time_yrs.append(base + timedelta(seconds=(base.replace(year=base.year + 1) - base).total_seconds() * rem))
dates = np.array(time_yrs)
fillval = data.variables['temperature'].missing_value
value = np.copy(data.variables['temperature'])
value[value == fillval] = np.NAN
if ref_period:
climo_month = np.zeros([12, len(lat), len(lon)], dtype=float)
# loop over months
for i in range(12):
m = i+1
indsmref = [j for j,v in enumerate(dates) if v.year >= ref_period[0] and v.year <= ref_period[1] and v.month == m]
indsm = [j for j,v in enumerate(dates) if v.month == m]
climo_month[i] = np.nanmean(value[indsmref], axis=0)
value[indsm] = (value[indsm] - climo_month[i])
else:
print('Warning: using default reference period defining temperature anomalies for BEST product.')
if outfreq == 'annual':
# List years available in dataset and sort
years = list(set([d.year for d in dates])) # 'set' is used to get unique values in list
years.sort # sort the list
dates_annual = np.array([datetime(y,1,1,0,0) for y in years])
value_annual = np.empty([len(years), len(lat), len(lon)], dtype=float)
value_annual[:] = np.nan # initialize with nan's
# Loop over years in dataset
for i in range(0,len(years)):
# find indices in time array where "years[i]" appear
ind = [j for j, k in enumerate(dates) if k.year == years[i]]
# ---------------------------------------
# Calculate annual mean from monthly data
# Note: data has dims [time,lat,lon]
# ---------------------------------------
tmp = np.nanmean(value[ind],axis=0)
# apply check of max nb of nan values allowed
nancount = np.isnan(value[ind]).sum(axis=0)
tmp[nancount > nbmaxnan] = np.nan # put nan back if nb of nan's in current year above threshold
value_annual[i,:,:] = tmp
dates_ret = dates_annual
value_ret = value_annual
else:
dates_ret = dates
value_ret = value
return dates_ret, lat, lon, value_ret
#==========================================================================================
def read_gridded_data_MLOST(data_dir,data_file,data_vars,outfreq,ref_period):
#==========================================================================================
#
# Reads the monthly data of surface air temperature anomalies from the MLOST NOAA/NCDC
# gridded product.
#
# Input:
# - data_dir : Full name of directory containing gridded
# data. (string)
# - data_file : Name of file containing gridded data. (string)
#
# - data_vars : List of variable names to read. (string list)
# Here should simply be ['Tsfc'], as only sfc temperature
# data (anomalies) are contained in the file.
#
# - outfreq : string indicating whether to return monthly or annual averages
#
# - ref_period : two-element list indicating the period w.r.t. which anomalies
# are to be referenced. Set to None if no processing required,
# otherwise expects [start,end] ex. [1951,1980]
#
# Output: (numpy arrays)
# - time_yrs : Array with years over which data is available.
# dims: [nb_years]
# - lat : Array containing the latitudes of gridded data.
# dims: [lat]
# - lon : Array containing the longitudes of gridded data.
# dims: [lon]
# - value : Array with the annually-averaged data calculated from monthly data
# dims: [time,lat,lon]
#
#==========================================================================================
nbmaxnan = 0 # max nb of nan's allowed in calculation of annual average
# Check if file exists
if 'MLOST' in data_file:
infile = data_dir+'/MLOST/'+data_file
elif 'NOAAGlobalTemp' in data_file:
infile = data_dir+'/NOAAGlobalTemp/'+data_file
else:
print('In read_gridded_data_MLOST: error in specification of',
' datadirectory for this calibration dataset.')
raise SystemExit()
if not os.path.isfile(infile):
raise SystemExit(('Error in specification of gridded dataset. '
'File {} does not exist. Exiting.').format(infile))
# Sanity check on number of variables to read
if len(data_vars) > 1:
raise SystemExit('Too many variables to read! This file only contains'
' surface air temperature (anomalies). Exiting.')
data = Dataset(infile,'r')
lat = data.variables['lat'][:]
lon = data.variables['lon'][:]
indneg = np.where(lon < 0)[0]
if len(indneg) > 0: # if non-empty
lon[indneg] = 360.0 + lon[indneg]
# -----------------------------------------------------------------
# Time is in "days since 1800-1-1 0:0:0":convert to calendar years
# -----------------------------------------------------------------
dateref = datetime(1800,1,1,0)
ntime = len(data.dimensions['time'])
daysfromdateref = data.variables['time'][:]
dates = np.array([dateref + timedelta(days=int(i)) for i in daysfromdateref])
fillval = data.variables['air'].missing_value
value = np.copy(data.variables['air'])
value[value == fillval] = np.NAN
if ref_period:
climo_month = np.zeros([12, len(lat), len(lon)], dtype=float)
# loop over months
for i in range(12):
m = i+1
indsmref = [j for j,v in enumerate(dates) if v.year >= ref_period[0] and v.year <= ref_period[1] and v.month == m]
indsm = [j for j,v in enumerate(dates) if v.month == m]
climo_month[i] = np.nanmean(value[indsmref], axis=0)
value[indsm] = (value[indsm] - climo_month[i])
else:
print('Warning: using default reference period defining temperature anomalies for MLOST product.')
if outfreq == 'annual':
# List years available in dataset and sort
years = list(set([d.year for d in dates])) # 'set' is used to get unique values in list
years.sort # sort the list
dates_annual = np.array([datetime(y,1,1,0,0) for y in years])
value_annual = np.empty([len(years), len(lat), len(lon)], dtype=float)
value_annual[:] = np.nan # initialize with nan's
# Loop over years in dataset
for i in range(0,len(years)):
# find indices in time array where "years[i]" appear
ind = [j for j, k in enumerate(dates) if k.year == years[i]]
# ---------------------------------------
# Calculate annual mean from monthly data
# Note: data has dims [time,lat,lon]
# ---------------------------------------
tmp = np.nanmean(value[ind],axis=0)
# apply check of max nb of nan values allowed
nancount = np.isnan(value[ind]).sum(axis=0)
tmp[nancount > nbmaxnan] = np.nan # put nan back if nb of nan's in current year above threshold
value_annual[i,:,:] = tmp
dates_ret = dates_annual
value_ret = value_annual
else:
dates_ret = dates
value_ret = value
return dates_ret, lat, lon, value_ret
#==========================================================================================
def read_gridded_data_GPCC(data_dir,data_file,data_vars,out_anomalies,ref_period,outfreq):
#==========================================================================================
#
# Reads the monthly data of surface air temperature anomalies from the GPCC
# gridded product.
#
# Input:
# - data_dir : Full name of directory containing gridded
# data. (string)
# - data_file : Name of file containing gridded data. (string)
#
# - data_vars : List of variable names to read. (string list)
# Here should simply be ['precip'], as only precipitation
# data (anomalies) are contained in the file.
#
# - out_anomalies: Boolean indicating whether anomalies w.r.t. a referenced period
# are to be csalculated and provided as output
#
# - ref_period : two-element list indicating the period w.r.t. which anomalies
# are to be referenced. Use [start,end] ex. [1951,1980]
#
# - outfreq : string indicating whether to return monthly or annual averages
#
# Output: (numpy arrays)
# - time_yrs : Array with years over which data is available.
# dims: [nb_years]
# - lat : Array containing the latitudes of gridded data.
# dims: [lat]
# - lon : Array containing the longitudes of gridded data.
# dims: [lon]
# - value : Array with the annually-averaged data calculated from monthly data
# dims: [time,lat,lon]
#
#==========================================================================================
nbmaxnan = 0 # max nb of nan's allowed in calculation of annual average
# Check if file exists
infile = data_dir+'/GPCC/'+data_file
if not os.path.isfile(infile):
raise SystemExit(('Error in specification of gridded dataset. '
'File {} does not exist. Exiting.').format(infile))
# Sanity check on number of variables to read
if len(data_vars) > 1:
raise SystemExit('Too many variables to read! This file only contains'
' precipitation accumulation or flux data. Exiting.')
data = Dataset(infile,'r')
lat = data.variables['lat'][:]
lon = data.variables['lon'][:]
indneg = np.where(lon < 0)[0]
if len(indneg) > 0: # if non-empty
lon[indneg] = 360.0 + lon[indneg]
# -----------------------------------------------------------------
# Time is in "days since 1800-1-1 0:0:0":convert to calendar years
# -----------------------------------------------------------------
dateref = datetime(1800,1,1,0)
ntime = len(data.dimensions['time'])
daysfromdateref = data.variables['time'][:]
dates = np.array([dateref + timedelta(days=int(i)) for i in daysfromdateref])
fillval = data.variables['precip'].missing_value
value = np.copy(data.variables['precip'])
value[value == fillval] = np.NAN
# Calculate anomalies w.r.t. reference period, if out_anomalies is set to True in
# class calibration_precip_GPCC() in LMR_calibrate.py
if out_anomalies:
if ref_period and type(ref_period) in [list,tuple] and len(ref_period) == 2:
climo_month = np.zeros([12, len(lat), len(lon)], dtype=float)
# loop over months
for i in range(12):
m = i+1
indsmref = [j for j,v in enumerate(dates) if v.year >= ref_period[0] and v.year <= ref_period[1] and v.month == m]
indsm = [j for j,v in enumerate(dates) if v.month == m]
climo_month[i] = np.nanmean(value[indsmref], axis=0)
value[indsm] = (value[indsm] - climo_month[i])
else:
raise SystemExit('In read_gridded_data_GPCC: out_anomalies is set to True,'
' but a reference period is not properly defined. Exiting.')
if outfreq == 'annual':
# List years available in dataset and sort
years = list(set([d.year for d in dates])) # 'set' is used to get unique values in list
years.sort # sort the list
dates_annual = np.array([datetime(y,1,1,0,0) for y in years])
value_annual = np.empty([len(years), len(lat), len(lon)], dtype=float)
value_annual[:] = np.nan # initialize with nan's
# Loop over years in dataset
for i in range(0,len(years)):
# find indices in time array where "years[i]" appear
ind = [j for j, k in enumerate(dates) if k.year == years[i]]
# ---------------------------------------
# Calculate annual mean from monthly data
# Note: data has dims [time,lat,lon]
# ---------------------------------------
tmp = np.nanmean(value[ind],axis=0)
# apply check of max nb of nan values allowed
nancount = np.isnan(value[ind]).sum(axis=0)
tmp[nancount > nbmaxnan] = np.nan # put nan back if nb of nan's in current year above threshold
value_annual[i,:,:] = tmp
dates_ret = dates_annual
value_ret = value_annual
else:
dates_ret = dates
value_ret = value
return dates_ret, lat, lon, value_ret
#==========================================================================================
def read_gridded_data_DaiPDSI(data_dir,data_file,data_vars,out_anomalies,ref_period,outfreq):
#==========================================================================================
#
# Reads the monthly data of Palmer Drought Severity Index (PDSI) anomalies from the
# "Dai" PDSI gridded product obtained from NOAA/ESRL at:
# http://www.esrl.noaa.gov/psd/data/gridded/data.pdsi.html
#
# Input:
# - data_dir : Full name of directory containing gridded
# data. (string)
# - data_file : Name of file containing gridded data. (string)
#
# - data_vars : List of variable names to read. (string list)
# Here should simply be ['pdsi'], as only PDSI
# data are contained in the file.
#
# - out_anomalies: Boolean indicating whether anomalies w.r.t. a referenced period
# are to be calculated and provided as output
#
# - ref_period : two-element list indicating the period w.r.t. which anomalies
# are to be referenced. Use [start,end] ex. [1951,1980]
#
# - outfreq : string indicating whether to return monthly or annual averages
#
# Output: (numpy arrays)
# - time_yrs : Array with years over which data is available.
# dims: [nb_years]
# - lat : Array containing the latitudes of gridded data.
# dims: [lat]
# - lon : Array containing the longitudes of gridded data.
# dims: [lon]
# - value : Array with the annually-averaged data calculated from monthly data
# dims: [time,lat,lon]
#
#==========================================================================================
nbmaxnan = 0 # max nb of nan's allowed in calculation of annual average
# Check if file exists
infile = data_dir+'/DaiPDSI/'+data_file
if not os.path.isfile(infile):
raise SystemExit(('Error in specification of gridded dataset. '
'File {} does not exist. Exiting.').format(infile))
# Sanity check on number of variables to read
if len(data_vars) > 1:
raise SystemExit('Too many variables to read! This file only contains'
' Palmer Drought Severity Index (PDSI). Exiting.')
data = Dataset(infile,'r')
lat = data.variables['lat'][:]
lon = data.variables['lon'][:]
indneg = np.where(lon < 0)[0]
if len(indneg) > 0: # if non-empty
lon[indneg] = 360.0 + lon[indneg]
# -----------------------------------------------------------------
# Time is in "hours since 1800-1-1 0:0:0":convert to calendar years
# -----------------------------------------------------------------
dateref = datetime(1800,1,1,0)
ntime = len(data.dimensions['time'])
hoursfromdateref = data.variables['time'][:]
dates = np.array([dateref + timedelta(hours=int(i)) for i in hoursfromdateref])
fillval = data.variables['pdsi'].missing_value
value = np.copy(data.variables['pdsi'])
value[value == fillval] = np.NAN
# Calculate anomalies w.r.t. reference period, if out_anomalies is set to True in class calibration_precip_DaiPDSI()
# in LMR_calibrate.py
if out_anomalies:
if ref_period and type(ref_period) in [list,tuple] and len(ref_period) == 2:
climo_month = np.zeros([12, len(lat), len(lon)], dtype=float)
# loop over months
for i in range(12):
m = i+1
indsmref = [j for j,v in enumerate(dates) if v.year >= ref_period[0] and v.year <= ref_period[1] and v.month == m]
indsm = [j for j,v in enumerate(dates) if v.month == m]
climo_month[i] = np.nanmean(value[indsmref], axis=0)
value[indsm] = (value[indsm] - climo_month[i])
else:
raise SystemExit('In read_gridded_data_DaiPDSI: out_anomalies is set to True,'
' but a reference period is not properly defined. Exiting.')
if outfreq == 'annual':
# List years available in dataset and sort
years = list(set([d.year for d in dates])) # 'set' is used to get unique values in list
years.sort # sort the list
dates_annual = np.array([datetime(y,1,1,0,0) for y in years])
value_annual = np.empty([len(years), len(lat), len(lon)], dtype=float)
value_annual[:] = np.nan # initialize with nan's
# Loop over years in dataset
for i in range(0,len(years)):
# find indices in time array where "years[i]" appear
ind = [j for j, k in enumerate(dates) if k.year == years[i]]
# ---------------------------------------
# Calculate annual mean from monthly data
# Note: data has dims [time,lat,lon]
# ---------------------------------------
tmp = np.nanmean(value[ind],axis=0)
# apply check of max nb of nan values allowed
nancount = np.isnan(value[ind]).sum(axis=0)
tmp[nancount > nbmaxnan] = np.nan # put nan back if nb of nan's in current year above threshold
value_annual[i,:,:] = tmp
dates_ret = dates_annual
value_ret = value_annual
else:
dates_ret = dates
value_ret = value
return dates_ret, lat, lon, value_ret
#==========================================================================================
def read_gridded_data_SPEI(data_dir,data_file,data_vars,out_anomalies,ref_period,outfreq):
#==========================================================================================
#
# Reads the monthly data of Standardized Precipitation Evapotranspiration Index from
# Begueria S., Vicente-Serrano S., Reig F., Latorre B. (2014) Standardized precipitation
# evapotranspiration index (SPEI) revisited: Parameter fitting, evapotranspiration models,
# tools, datasets and drought monitoring. International Journal of Climatology 34, 3001-3023.
# SPEI gridded product obtained from the Consejo Superior de Investigaciones Cientificas
# (CSIC) at http://sac.csic.es/spei/index.html
#
# Input:
# - data_dir : Full name of directory containing gridded
# data. (string)
# - data_file : Name of file containing gridded data. (string)
#
# - data_vars : List of variable names to read. (string list)
# Here should simply be ['spei'], as only SPEI
# data are contained in the file.
#
# - out_anomalies: Boolean indicating whether anomalies w.r.t. a referenced period
# are to be calculated and provided as output
#
# - ref_period : two-element list indicating the period w.r.t. which anomalies
# are to be referenced. Use [start,end] ex. [1951,1980]
#
# - outfreq : string indicating whether to return monthly or annual averages
#
# Output: (numpy arrays)
# - time_yrs : Array with years over which data is available.
# dims: [nb_years]
# - lat : Array containing the latitudes of gridded data.
# dims: [lat]
# - lon : Array containing the longitudes of gridded data.
# dims: [lon]
# - value : Array with the annually-averaged data calculated from monthly data
# dims: [time,lat,lon]
#
#==========================================================================================
nbmaxnan = 0 # max nb of nan's allowed in calculation of annual average
# Check if file exists
infile = data_dir+'/SPEI/'+data_file
if not os.path.isfile(infile):
raise SystemExit(('Error in specification of gridded dataset. '
'File {} does not exist. Exiting.').format(infile))
# Sanity check on number of variables to read
if len(data_vars) > 1:
raise SystemExit('Too many variables to read! This file only contains'
' Standardized Precipitation Evapotranspiration Index (SPEI).'
' Exiting.')
data = Dataset(infile,'r')
lat = data.variables['lat'][:]
lon = data.variables['lon'][:]
indneg = np.where(lon < 0)[0]
if len(indneg) > 0: # if non-empty
lon[indneg] = 360.0 + lon[indneg]
# -----------------------------------------------------------------
# Time is in "days since 1900-1-1 0:0:0":convert to calendar years
# -----------------------------------------------------------------
dateref = datetime(1900,1,1,0)
ntime = len(data.dimensions['time'])
daysfromdateref = data.variables['time'][:]
dates = np.array([dateref + timedelta(days=int(i)) for i in daysfromdateref])
fillval = data.variables['spei']._FillValue
value = np.copy(data.variables['spei'])
value[value == fillval] = np.NAN
# Calculate anomalies w.r.t. reference period, if out_anomalies is set to True in class calibration_precip_DaiPDSI()
# in LMR_calibrate.py
if out_anomalies:
if ref_period and type(ref_period) in [list,tuple] and len(ref_period) == 2:
climo_month = np.zeros([12, len(lat), len(lon)], dtype=float)
# loop over months
for i in range(12):
m = i+1
indsmref = [j for j,v in enumerate(dates) if v.year >= ref_period[0] and v.year <= ref_period[1] and v.month == m]
indsm = [j for j,v in enumerate(dates) if v.month == m]
climo_month[i] = np.nanmean(value[indsmref], axis=0)
value[indsm] = (value[indsm] - climo_month[i])
else:
raise SystemExit('In read_gridded_data_SPEI: out_anomalies is set to True,'
' but a reference period is not properly defined. Exiting.')
if outfreq == 'annual':
# List years available in dataset and sort
years = list(set([d.year for d in dates])) # 'set' is used to get unique values in list
years.sort # sort the list
dates_annual = np.array([datetime(y,1,1,0,0) for y in years])
value_annual = np.empty([len(years), len(lat), len(lon)], dtype=float)
value_annual[:] = np.nan # initialize with nan's
# Loop over years in dataset
for i in range(0,len(years)):
# find indices in time array where "years[i]" appear
ind = [j for j, k in enumerate(dates) if k.year == years[i]]
# ---------------------------------------
# Calculate annual mean from monthly data
# Note: data has dims [time,lat,lon]
# ---------------------------------------
tmp = np.nanmean(value[ind],axis=0)
# apply check of max nb of nan values allowed
nancount = np.isnan(value[ind]).sum(axis=0)
tmp[nancount > nbmaxnan] = np.nan # put nan back if nb of nan's in current year above threshold
value_annual[i,:,:] = tmp
dates_ret = dates_annual
value_ret = value_annual
else:
dates_ret = dates
value_ret = value
return dates_ret, lat, lon, value_ret
anom_ref=None
#==========================================================================================
def read_gridded_data_CMIP5_model(data_dir,data_file,data_vars,outtimeavg,
detrend=None,anom_ref=None,var_info=None):
#==========================================================================================
#
# Reads the monthly data from a CMIP5 model and return yearly averaged values
#
# Input:
# - data_dir : Full name of directory containing gridded
# data. (string)
# - data_file : Name of file containing gridded data. (string)
#
# - data_vars : Variables names to be read, and info on whether each
# variable is to be returned as anomalies of as full field
# (dict)
#
# - outtimeavg : Dictionary indicating the type of averaging (key) and associated
# information on averaging period (integer list)
# if the type is "annual": list of integers indicating the months of
# the year over which to average the data.
# Requires availability of monthly data.
# if type is "multiyear" : list of single integer indicating the length
# of averaging period (in years).
# Requires availability of data with a
# resolution of at least the averaging
# interval.
#
# ex 1: outtimeavg = {'annual': [1,2,3,4,5,6,7,8,9,10,11,12]}
# ex 2: outtimeavg = {'multiyear': [100]} -> 100yr average
#
# *or*:
# Integer list or tuple of integer lists indicating the sequence of
# months over which to average the data.
#
# - detrend : Boolean to indicate if detrending is to be applied to the prior
#
# - anom_ref : Reference period (in years CE) used in calculating anomalies (tuple)
#
# - var_info : Dict. containing information about whether some state variables
# represent temperature or moisture (used to extract proper
# seasonally-avg. data to be used in calculation of proxy estimates)
#
# Output:
# - datadict : Master dictionary containing dictionaries, one for each state
# variable, themselves containing the following numpy arrays:
# - time_yrs : Array with years over which data is available.
# dims: [nb_years]
# - lat : Array containing the latitudes of gridded data.
# dims: [lat]
# - lon : Array containing the longitudes of gridded data.
# dims: [lon]
# - value : Array with the averaged data calculated from
# monthly data dims: [time,lat,lon]
#
# ex. data access : datadict['tas_sfc_Amon']['years'] => array containing years of the
# 'tas' data
# datadict['tas_sfc_Amon']['lat'] => array of lats for 'tas' data
# datadict['tas_sfc_Amon']['lon'] => array of lons for 'tas' data
# datadict['tas_sfc_Amon']['value'] => array of 'tas' data values
#
#==========================================================================================
datadict = {}
# Loop over state variables to load
for v in range(len(data_vars)):
vardef = list(data_vars.keys())[v]
data_file_read = data_file.replace('[vardef_template]', vardef)
# Check if file exists
infile = data_dir + '/' + data_file_read
if not os.path.isfile(infile):
print('Error in specification of gridded dataset')
print('File ', infile, ' does not exist! - Exiting ...')
raise SystemExit()
else:
print('Reading file: ', infile)
# Get file content
data = Dataset(infile,'r')
# Dimensions used to store the data
nc_dims = [dim for dim in data.dimensions]
dictdims = {}
for dim in nc_dims:
dictdims[dim] = len(data.dimensions[dim])
# Define the name of the variable to extract from the variable definition (from namelist)
var_to_extract = vardef.split('_')[0]
# Query its dimensions
vardims = data.variables[var_to_extract].dimensions
nbdims = len(vardims)
# names of variable dims
vardimnames = []
for d in vardims:
vardimnames.append(d)
# put everything in lower case for homogeneity
vardimnames = [item.lower() for item in vardimnames]
# One of the dims has to be time!
if 'time' not in vardimnames:
print('Variable does not have *time* as a dimension! Exiting!')
raise SystemExit()
else:
# read in the time netCDF4.Variable
time = data.variables['time']
# Transform into calendar dates using netCDF4 variable attributes (units & calendar)
# TODO: may not want to depend on netcdf4.num2date...
try:
if hasattr(time, 'calendar'):
# if time is defined as "months since":not handled by datetime functions
if 'months since' in time.units:
new_time = np.zeros(time.shape)