-
Notifications
You must be signed in to change notification settings - Fork 0
/
func_sdh_oe_midc.py
1426 lines (1185 loc) · 54.6 KB
/
func_sdh_oe_midc.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
### Same as func_sdh but for cmorized data (here mpiesm and ecearth)
from __future__ import print_function
import sys
import os
from getpass import getuser
import string
import subprocess
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import netCDF4 as netcdf4
import xarray as xr
import pandas
#import regionmask
#import cartopy.crs as ccrs
from IPython.display import display, Math, Latex
import warnings
from datetime import datetime
from datetime import timedelta
import datetime
import calendar
import pandas as pd
import pickle
outdir= '/dodrio/scratch/projects/2022_200/project_output/bclimate/sdeherto/postprocessing/'
procdir=outdir
ddir= '/dodrio/scratch/projects/2022_200/project_output/bclimate/sdeherto/postprocessing/'
model = {'lnd' : 'clm2', 'atm' : 'cam', 'rof' : 'mosart'}
#read in different files
def open_ds(var,case,esm='cesm',stream='h0',model='cam'):
if esm=='cesm':
if case[:4]=='hist':
comp='BHIST'
tseriesdir = ddir + 'b.e213.'+comp+'_BPRP.f09_g17.esm-hist-'+case.split('-')[1]+'/'
else:
comp='BSSP126'
tseriesdir = ddir + 'b.e213.'+comp+'_BPRP.f09_g17.esm-'+case+'/'
# define filename
fn = var+'_b.e213.'+comp+'_BPRP.f09_g17.esm-'+case+'.'+ model + '.' + stream + '.nc'
else:
ens='i'+case.split('-')[1][-1]
case=case.split('-')[0]
if case=='hist':
case='histctl'
tspan='1980-2014'
else:
tspan='2015-2099'
tseriesdir = ddir + esm+'/'+case+'/'
# define filename
if stream=='h0':
fn = var+'_monthly_'+esm+'_'+case+'_'+ens+'_no-dynveg_'+tspan+ '.nc'
elif stream=='h2':
fn = var+'_3hr_'+esm+'_'+case+'_'+ens+'_no-dynveg_'+tspan+ '.nc'
elif stream=='h1':
fn = var+'_'+esm+'_'+case+'_'+ens+'_no-dynveg_'+tspan+ '.nc'
# check if variable timeseries exists and open variable as data array
if not os.path.isfile(tseriesdir + fn):
print(fn + ' does not exists in ')
print(tseriesdir)
return
else:
if esm=='cesm':
ds = xr.open_dataset(tseriesdir+fn)
ds['time']=ds['time'].astype("datetime64[ns]")
elif esm=='mpiesm':
# ds = xr.open_dataset(savedir+fn)
#print(ds.time.attrs['units'])
ds = xr.open_dataset(tseriesdir+fn)
ds['time']=pd.to_datetime(ds['time'], format='%Y%m%d')
elif esm=='ecearth':
ds = xr.open_dataset(tseriesdir+fn)
return ds
def open_ds_mean(var,case,esm='cesm',model='cam'):
# define filename
if esm=='cesm':
if case[:4]=='hist':
comp='BHIST'
savedir = ddir + 'b.e213.'+comp+'_BPRP.f09_g17.esm-hist-'+case.split('-')[1] + '/mean/'
fn = case.split('-')[0][:4]+'.'+model+'.mean_'+var + '.'+case[-3:] + '.nc'
else:
comp='BSSP126'
savedir = ddir + 'b.e213.'+comp+'_BPRP.f09_g17.esm-'+case + '/mean/'
fn = case.split('-')[0]+'.'+model+'.mean_'+var + '.'+case[-3:] + '.nc'
else:
print(case.split('-'))
ens='i'+case.split('-')[1][-1]
case=case.split('-')[0]
if case=='hist':
case='histctl'
tspan='1980-2014'
else:
tspan='2015-2099'
tseriesdir = ddir + esm+'/'+case+'/'
# define filename
if stream=='h0':
fn = var+'_monthly_'+esm+'_'+case+'_'+ens+'_no-dynveg_'+tspan+ '.nc'
elif stream=='h2':
fn = var+'_3hr_'+esm+'_'+case+'_'+ens+'_no-dynveg_'+tspan+ '.nc'
elif stream=='h1':
fn = var+'_'+esm+'_'+case+'_'+ens+'_no-dynveg_'+tspan+ '.nc'
# check if variable timeseries exists and open variable as data array
if not os.path.isfile(savedir + fn):
print(fn + ' does not exists in ')
print(savedir)
return
else:
if esm=='cesm':
ds = xr.open_dataset(tseriesdir+fn)
ds['time']=ds['time'].astype("datetime64[ns]")
elif esm=='mpiesm':
# ds = xr.open_dataset(savedir+fn)
#print(ds.time.attrs['units'])
ds = xr.open_dataset(tseriesdir+fn)
ds['time']=pd.to_datetime(ds['time'], format='%Y%m%d')
elif esm=='ecearth':
ds = xr.open_dataset(tseriesdir+fn)
return ds
def open_da_mean(var, case, esm='cesm',model='cam'):
ds = open_ds_mean(var, case, esm, model)
da = ds[var]
return da
def open_da(var, case, esm='cesm', stream='h0', model='cam',isxtrm=False):
if isxtrm:
ds = open_ds_xtrm(var, case, esm, stream, model)
else:
ds = open_ds(var, case, esm, stream, model)
da = ds[var]
#shift time by one (to fix index error in preprocessing)
# if stream=='h0':
# t=xr.CFTimeIndex(da.time.get_index('time') - timedelta(days=31))
# elif stream=='h1':
# t=xr.CFTimeIndex(da.time.get_index('time') - timedelta(days=1))
# elif stream=='h2':
# t=xr.CFTimeIndex(da.time.get_index('time') - timedelta(hours=3))
# print(t)
#da['time']=t
return da
def open_da_delta(var, case, case_ref,esm, stream, model, ens=True, mode='mean',isxtrm=False):
""" open and caluclate the difference between the ensemble means of two members """
# Load the two datasets
if ens == True:
da_res = open_da_ens(var,case=case, esm=esm, n_ens=3, stream=stream, model=model, mode = mode,isxtrm=isxtrm)
da_ctl = open_da_ens(var,case=case_ref, esm=esm, n_ens=3, stream=stream, model=model, mode = mode,isxtrm=isxtrm)
else: # open single simulation
da_res = open_da(var,case=case,esm=esm, model=model,isxtrm=isxtrm)
da_ctl = open_da(var,case=case_ref,esm=esm, model=model,isxtrm=isxtrm)
# calculate difference and update attributes
print(da_ctl.time)
print(da_res.time)
da1=da_res
da2=da_ctl
#da1=extract_anaperiod(da_res, esm,stream,isxtrm=isxtrm)
#if case_ref=='hist':
# da2=extract_anaperiod_hist(da_ctl, esm,stream,isxtrm=isxtrm)
#else:
# da2=extract_anaperiod(da_ctl, esm,stream,isxtrm=isxtrm)
#print(da1.time)
#print(da2.time)
if isxtrm:
da2['year']=da1.year
else:
da2['time']=da1.time
da_delta = da1-da2
#da_delta.attrs['long_name'] = '$\Delta$ '+ da_ctl.long_name
#da_delta.name = '$\Delta$ '+ da_ctl.name
return da_delta
def open_da_delta_mean(var, case, case_ref, esm, model, ens=True, mode='mean'):
""" open and caluclate the difference between the ensemble means of two members """
# Load the two datasets
if ens == True:
da_res = open_da_ens_mean(var,case=case, esm=esm, n_ens=3, model=model, mode = mode)
da_ctl = open_da_ens_mean(var,case=case_ref, esm=esm, n_ens=3, model=model, mode = mode)
else: # open single simulation
da_res = open_da_mean(var,case=case,esm=esm, model=model)
da_ctl = open_da_mean(var,case=case_ref,esm=esm, model=model)
# calculate difference and update attributes
da_delta = da_res - da_ctl
return da_delta
def open_da_ens(var, case, esm, n_ens, stream='h0', model='cam', mode='mean',isxtrm=False):
# loop over ensemble members
print(case)
for i in range(1,n_ens+1):
case_name = case+'-i308.00'+str(i)
da = open_da(var, case=case_name, esm=esm, stream=stream, model=model,isxtrm=isxtrm)
print(da)
if case=='hist':
da=extract_anaperiod_hist(da, esm,stream=stream,isxtrm=isxtrm)
else:
da=extract_anaperiod(da, esm,stream=stream,isxtrm=isxtrm)
if i==1:
da_concat = da
else:
if isxtrm:
da['year']=da_concat.year
else:
da['time']=da_concat.time
da_concat = xr.concat((da_concat, da), dim='ens_member')
# different output options
# return ensemble mean
if mode == 'mean':
return da_concat.mean(dim='ens_member', keep_attrs='True')
# standard deviation
if mode == 'std':
return da_concat.std(dim='ens_member', keep_attrs='True')
# the full ensemble with dim (ens_member)
if mode == 'all':
return da_concat
def open_da_ens_mean(var, case, esm, n_ens, model='cam', mode='mean'):
ens_list=['000','001','002','003']
# loop over ensemble members
for i in range(1,n_ens+1):
case_name = case+'-i308.00'+str(i)
da = open_da_mean(var, case=case_name, esm=esm, model=model)
if i==1:
da_concat = da
else:
da_concat = xr.concat((da_concat, da), dim='ens_member')
# different output options
# return ensemble mean
if mode == 'mean':
return da_concat.mean(dim='ens_member', keep_attrs='True')
# standard deviation
if mode == 'std':
return da_concat.std(dim='ens_member', keep_attrs='True')
# the full ensemble with dim (ens_member)
if mode == 'all':
return da_concat
# save dataset as nc in postprocessing dir for extremes
def save_da_xtrm(da,var,case, esm, block,comp,ens):
if esm=='cesm':
savedir = procdir + 'b.e213.'+comp+'_BPRP.f09_g17.esm-'+case+'-i308.'+ens + '/tseries/'
# define filename
fn = case + '.'+ model[block] + '.' + var + '.' + ens +'.nc'
else:
case=case.split('_')[0]
if case=='hist':
case='histctl'
savedir = ddir + esm+'/'+case+'/tseries/'
# define filename
fn = case + '.'+ model[block] + '.' + var + '.' + ens +'.nc'
# check if variable timeseries exists and open variable as data array
if os.path.isfile(savedir + fn):
print(fn + ' already exists')
else:
da.to_dataset().to_netcdf(savedir+fn)
return
def extract_anaperiod_hist(da,esm,stream,isxtrm=False):
"""Extract analysis period out of data-array (last 30 years)"""
# number of spin up years
if esm=='cesm': ##cesm contains 1 timestep in the next year which should not be taken into account
if isxtrm:
if da.name in ['TREFHTdaymax']:
if len(da.shape)>3:
da = da[:,-30*365-1:-1,:,:]
else:
# spin up with monthly timestep
da = da[-30*365-1:-1,:,:]
else:
if len(da.shape)>3:
da = da[:,-30-1:-1,:,:]
else:
# spin up with monthly timestep
da = da[-30-1:-1,:,:]
else:
if len(da.shape)>3:
if stream == 'h2' : # this option still to test
# 3 hourly timesteps
da = da[:,-30*365*8-1:-1,:,:]
else:
# spin up with monthly timestep
da = da[:,-20*12-1:-1,:,:]
else:
if stream == 'h2' : # this option still to test
# 3 hourly timesteps
da = da[-20*365*8-1:-1,:,:]
else:
# spin up with monthly timestep
da = da[-20*12-1:-1,:,:]
else:
if len(da.shape)>3:
if stream == 'h2' : # this option still to test
# 3 hourly timesteps
da = da[:,-30*365*8:,:,:]
else:
# spin up with monthly timestep
da = da[:,-20*12:,:,:]
else:
if stream == 'h2' : # this option still to test
# 3 hourly timesteps
da = da[-30*365*8:,:,:]
else:
# spin up with monthly timestep
da = da[-20*12:,:,:]
return da
def extract_anaperiod(da, esm,stream,isxtrm=False):
"""Extract analysis period out of data-array (2040-2060)"""
# number of spin up years
if esm=='cesm': ##cesm contains 1 timestep in the next year which should not be taken into account
print(da.shape)
if isxtrm:
if da.name in ['TREFHTdaymax']:
if len(da.shape)>3:
da = da[:,-60*365-1:-40*365-1,:,:]
else:
# spin up with monthly timestep
da = da[-60*365-1:-40*365-1,:,:]
else:
if len(da.shape)>3:
da = da[:,-60*30-1:-40*30-1,:,:]
else:
# spin up with monthly timestep
da = da[-60*30-1:-40*30-1,:,:]
else:
if len(da.shape)>3:
if stream == 'h2' : # this option still to test
# 3 hourly timesteps
da = da[:,-60*365*8-1:-40*365*8-1,:,:]
else:
# spin up with monthly timestep
da = da[:,300:540,:,:]
else:
if stream == 'h2' : # this option still to test
# 3 hourly timesteps
da = da[-60*365*8-1:-40*365*8-1,:,:]
else:
# spin up with monthly timestep
da = da[300:540,:,:]
else:
if len(da.shape)>3:
if stream == 'h2' : # this option still to test
# 3 hourly timesteps
da = da[:,-60*365*8:-40*365*8,:,:]
else:
# spin up with monthly timestep
da = da[:,300:540,:,:]
else:
if stream == 'h2' : # this option still to test
# 3 hourly timesteps
da = da[8:-40*365*8,:,:]
else:
# spin up with monthly timestep
da = da[300:540,:,:]
return da
# open dataset of extremes
def open_ds_xtrm(var,case,esm,stream='h0',model='cam'):
if esm=='cesm':
if case[:4]=='hist':
comp='BHIST'
tseriesdir = ddir + 'b.e213.'+comp+'_BPRP.f09_g17.esm-hist-'+case.split('-')[1]+'/tseries/'
fn = case.split('-')[0][:4]+'.'+model+'.'+var + '.'+case[-3:] + '.nc'
else:
comp='BSSP126'
tseriesdir = ddir + 'b.e213.'+comp+'_BPRP.f09_g17.esm-'+case+'/tseries/'
fn = case.split('-')[0]+'.'+model+'.'+var + '.'+case[-3:] + '.nc'
else:
case=case.split('_')[0]
if case=='hist':
case='histctl'
savedir = ddir + esm+'/'+case+'/tseries/'
# define filename
fn = case + '.'+ model[block] + '.' + var + '.' + ens +'.nc'
if not os.path.isfile(tseriesdir + fn):
print(fn + ' does not exists in ')
print(tseriesdir)
return
else:
# open the dataset
ds = xr.open_dataset(tseriesdir+fn)
return ds
# check if dataset of extremes exists
def exist_da_xtrm(var,case, esm, block,comp,ens):
if esm=='cesm':
savedir = outdir + 'b.e213.'+comp+'_BPRP.f09_g17.esm-'+case+'-i308.'+ens + '/tseries/'
# define filename
fn = case + '.'+ model[block] + '.' + var + '.' + ens +'.nc'
else:
case=case.split('_')[0]
if case=='hist':
case='histctl'
savedir = ddir + esm+'/'+case+'/tseries/'
# define filename
fn = case + '.'+ model[block] + '.' + var + '.' + ens +'.nc'
# check if variable timeseries exists and open variable as data array
if not os.path.isfile(savedir + fn): exists = False
else: exists = True
return exists
def conv_m_s_to_mm_day(da_in):
if not da_in.attrs['units'] == 'mm/day':
da_out = da_in * 86400000
# update attributes and change units
da_out.attrs= da_in.attrs
da_out.attrs['units'] = 'mm/day'
else:
da_out = da_in
return da_out
#compute average of extremes
def mean_xtrm(var,case,esm,block,ens):
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# check if var is already existing
if exist_da_xtrm(var,case, esm,block,comp,ens):
# open da with daily data
case_name = case+'-i308.'+ens
da = open_da(var, case_name, esm,stream='h0', model=model[block],isxtrm=True)
da=extract_anaperiod(da, esm,stream='h0',isxtrm=True)
# calculate mean
da_mean= da.mean('year')
da_mean.name = var
da_mean.attrs['long_name'] = 'Mean '+da.long_name
if esm=='cesm':
savedir = procdir + 'b.e213.'+comp+'_BPRP.f09_g17.esm-'+case+'-i308.'+ens + '/mean/'
# define filename
fn = case + '.'+ model[block] + '.mean_' + var + '.' + ens +'.nc'
else:
case=case.split('_')[0]
if case=='hist':
case='histctl'
savedir = ddir + esm+'/'+case+'/mean/'
# define filename
fn = case + '.'+ model[block] + '.mean_' + var + '.' + ens +'.nc'
# check if variable timeseries exists and open variable as data array
if os.path.isfile(savedir + fn):
print(fn + ' already exists')
else:
da_mean.to_dataset().to_netcdf(savedir+fn)
else:
print('extreme does not exist')
return
#compute averages
def mean_var(var,case,esm,stream,block,ens):
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# check if var is already existing
# open da with daily data
case_name = case+'-i308.'+ens
da = open_da(var,case_name,esm,stream,model[block])
da=extract_anaperiod(da,esm, stream=stream)
# calculate mean
da_mean= da.mean('time')
da_mean.name = var
da_mean.attrs['long_name'] = 'Mean '+da.long_name
if esm=='cesm':
savedir = procdir + 'b.e213.'+comp+'_BPRP.f09_g17.esm-'+case+'-i308.'+ens + '/mean/'
# define filename
fn = case + '.'+ model[block] + '.mean_' + var + '.' + ens +'.nc'
else:
case=case.split('_')[0]
if case=='hist':
case='histctl'
savedir = ddir + esm+'/'+case+'/mean/'
# define filename
fn = case + '.'+ model[block] + '.mean_' + var + '.' + ens +'.nc'
# check if variable timeseries exists and open variable as data array
if os.path.isfile(savedir + fn):
print(fn + ' already exists')
else:
da_mean.to_dataset().to_netcdf(savedir+fn)
return
def comp_PRECT(case,esm='cesm', ens='001'):
if esm=='cesm':
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# check if var is already existing
# open da with daily data
case_name = case+'-i308.'+ens
da1 = open_da('PRECC',case_name, stream='h0',model=model['atm'])
da2 = open_da('PRECL',case_name, stream='h0',model=model['atm'])
da=da1+da2
else:
case_name = case+'-i308.'+ens
da = open_da('pr',case_name, esm=esm, stream='h0',model=model['atm'])
# calculate mean
da_e=extract_anaperiod(da, esm,stream='h0')
da_mean= da_e.mean('time')
da.name = 'PRECT'
da_mean.name = 'PRECT'
if esm=='cesm':
savedir = procdir + 'b.e213.'+comp+'_BPRP.f09_g17.esm-'+case+'-i308.'+ens +'/'
# define filename
block='atm'
fn_mean = case + '.'+ model[block] + '.mean_PRECT.' + ens +'.nc'
fn='PRECT_b.e213.'+comp+'_BPRP.f09_g17.esm-'+case + '-i308.'+ens+'.cam.h0.nc'
else:
return
###TO FILL IN
# check if variable timeseries exists and open variable as data array
if os.path.isfile(savedir +'/mean/'+ fn_mean):
print(fn_mean + ' already exists')
else:
da_mean.to_dataset().to_netcdf(savedir+'/mean/'+fn_mean)
if os.path.isfile(savedir + fn):
print(fn + ' already exists')
else:
da.to_dataset().to_netcdf(savedir+fn)
return
def comp_PRECT_day(case,ens):
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# check if var is already existing
# open da with daily data
case_name = case+'-i308.'+ens
model = {'lnd' : 'clm2', 'atm' : 'cam', 'rof' : 'mosart'}
da = open_da('PRECT',case_name, stream='h2',model=model['atm'])
# calculate mean
da_day=da.resample(time='D').sum(keep_attrs=True)
da_day.name = 'PRECT'
savedir = procdir + 'b.e213.'+comp+'_BPRP.f09_g17.esm-'+case+'-i308.'+ens +'/'
# define filename
block='atm'
fn='PRECT_b.e213.'+comp+'_BPRP.f09_g17.esm-'+case + '-i308.'+ens+'.cam.h1.nc'
# check if variable timeseries exists and open variable as data array
if os.path.isfile(savedir + fn):
print(fn + ' already exists')
else:
da_day.to_dataset().to_netcdf(savedir+fn)
return
# process TXx: calculate and save annual maximum of maxdaytime temperature
def proc_TXx(var_or, case, esm,block,ens):
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# define new variable name
if var_or=='TS' or var_or=='ts':
var = 'TXx'
elif var_or=='TREFHT' or var_or=='tas':
var='TRXx'
else:
print('incorrect variable')
return
# check if var is already existing
if exist_da_xtrm(var,case, esm,block,comp,ens):
print(var +' already exists')
else: # do calculations
case_name = case+'-i308.'+ens
# open da with daily data
da = open_da(var_or,case_name, esm, stream='h2', model=model[block])
# calculate maximum per year
da_xtrm= da.groupby('time.year').max(keep_attrs=True)
da_xtrm.name = var
da_xtrm.attrs['long_name'] = 'Annual maximum of '+da.long_name
# save variable into netcdf
save_da_xtrm(da_xtrm,var,case=case, esm=esm, block=block,comp=comp,ens=ens)
# process TXx: calculate and save annual maximum of maxdaytime temperature
def proc_Tdaymax(var_or, case, block,ens):
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# define new variable name
if var_or=='TS':
var = 'TSdaymax'
elif var_or=='TREFHT':
var='TREFHTdaymax'
else:
print('incorrect variable')
return
model = {'lnd' : 'clm2', 'atm' : 'cam', 'rof' : 'mosart'}
# check if var is already existing
if exist_da_xtrm(var,case, block,comp,ens):
print(var +' already exists')
else: # do calculations
case_name = case+'-i308.'+ens
# open da with daily data
da = open_da(var_or,case_name, stream='h2', model=model[block])
# calculate maximum per year
da_xtrm=da.resample(time='D').max(keep_attrs=True)
da_xtrm.name = var
da_xtrm.attrs['long_name'] = 'daily maximum of '+da.long_name
# save variable into netcdf
save_da_xtrm(da_xtrm,var,case=case, block=block,comp=comp,ens=ens)
# process TNn: calculate and save annual maximum of maxdaytime temperature
def proc_TNn(var_or, case, block,ens):
# define new variable name
if var_or=='TS':
var = 'TNn'
elif var_or=='TREFHT':
var='TRNn'
else:
print('incorrect variable')
return
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
model = {'lnd' : 'clm2', 'atm' : 'cam', 'rof' : 'mosart'}
# check if var is already existing
if exist_da_xtrm(var,case=case, block=block,comp=comp,ens=ens):
print(var +' already exists')
else: # do calculations
case_name = case+'-i308.'+ens
# open da with daily data
da = open_da(var_or,case_name, stream='h2', model=model[block])
# calculate minimum per year
da_xtrm = da.groupby('time.year').min(keep_attrs=True)
da_xtrm.name = var
da_xtrm.attrs['long_name'] = 'Annual minimum of '+da.long_name
# save variable into netcdf
save_da_xtrm(da_xtrm,var,case=case, block=block,comp=comp,ens=ens)
# calculate 99th percentile of max daytime temperatures
def proc_TX99(var_or, case, block,ens):
# define new variable name
if var_or=='TS':
var = 'TX99'
elif var_or=='TREFHT':
var='TRX99'
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# check if var is already existing
if exist_da_xtrm(var,case=case, block=block,comp=comp,ens=ens):
print(var +' already exists')
else: # do calculations
case_name = case+'-i308.'+ens
# open da with daily data
da = open_da(var_or,case_name, stream='h2', model=model[block])
da_day=da.resample(time='D').max(keep_attrs=True)
# calculate maximum per year
da_xtrm = da_day.quantile(0.99, dim=('time'))
da_xtrm.name = var
da_xtrm.attrs['long_name'] = '99th percentile of daily '+da.long_name
da_xtrm.attrs['units'] = 'K'
# save variable into netcdf
save_da_xtrm(da_xtrm,var,case=case, block=block,comp=comp,ens=ens)
# calculate 1st percentile of min nighttime temperatures
def proc_TN01(var_or, case, block,ens):
# define new variable name
if var_or=='TS':
var = 'TN01'
elif var_or=='TREFHT':
var='TRN01'
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# check if var is already existing
if exist_da_xtrm(var,case=case, block=block,comp=comp,ens=ens):
print(var +' already exists')
else: # do calculations
case_name = case+'-i308.'+ens
# open da with daily data
da = open_da(var_or,case_name, stream='h2', model=model[block])
da_day = da.resample(time='D').min(keep_attrs=True)
# calculate maximum per year
da_xtrm = da_day.quantile(0.01, dim=('time'))
da_xtrm.name = var
da_xtrm.attrs['long_name'] = '1st percentile of daily '+da.long_name
da_xtrm.attrs['units'] = 'K'
# save variable into netcdf
save_da_xtrm(da_xtrm,var,case=case, block=block,comp=comp,ens=ens)
def proc_TN10(var_or, case, block,ens):
"""calculcate and save cold days 10pctl of days within period """
# define new variable name
if var_or=='TS':
var = 'TN10'
elif var_or=='TREFHT':
var='TRN10'
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# check if var is already existing
if exist_da_xtrm(var,case=case, block=block,comp=comp,ens=ens):
print(var +' already exists')
else: # do calculations
case_name = case+'-i308.'+ens
# open da with daily data
da = open_da(var_or,case_name, stream='h2', model=model[block])
da_day = da.resample(time='D').min(keep_attrs=True)
# calculate maximum per year
da_xtrm = da_day.quantile(0.1, dim=('time'))
da_xtrm.name = var
da_xtrm.attrs['long_name'] = '10th percentile of daily'+da.long_name
da_xtrm.attrs['units'] = 'K'
# save variable into netcdf
save_da_xtrm(da_xtrm,var,case=case, block=block,comp=comp,ens=ens)
def proc_TX90(var_or, case, block,ens):
"""calculcate and save warm days 90th pctl of days within period """
# define new variable name
if var_or=='TS':
var = 'TX90'
elif var_or=='TREFHT':
var='TRX90'
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# check if var is already existing
if exist_da_xtrm(var,case=case, block=block,comp=comp,ens=ens):
print(var +' already exists')
else: # do calculations
case_name = case+'-i308.'+ens
# open da with daily data
da = open_da(var_or,case_name, stream='h2', model=model[block])
da_day = da.resample(time='D').max(keep_attrs=True)
# calculate maximum per year
da_xtrm = da_day.quantile(0.9, dim=('time'))
da_xtrm.name = var
da_xtrm.attrs['long_name'] = '90th percentile of daily'+da.long_name
da_xtrm.attrs['units'] = 'K'
# save variable into netcdf
save_da_xtrm(da_xtrm,var,case=case, block=block,comp=comp,ens=ens)
def proc_Rx1day(var_or, case, block,ens):
"""process Rx1day: calculate annual maximum 1 day precipitation"""
# define new variable name
var = 'Rx1day'
model = {'lnd' : 'clm2', 'atm' : 'cam', 'rof' : 'mosart'}
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# check if var is already existing
if exist_da_xtrm(var,case=case, block=block,comp=comp,ens=ens):
print(var +' already exists')
else: # do calculations
case_name = case+'-i308.'+ens
# open da with daily data
da = open_da(var_or,case_name, stream='h2', model=model[block])
da_day = da.resample(time='D').sum(keep_attrs=True)
da_day[:]=da_day.values*3
# calculate maximum per year
da_xtrm= da.groupby('time.year').max(keep_attrs=True)
da_xtrm.name = var
da_xtrm.attrs['long_name'] = 'Annual maximum of '+da.long_name
# save variable into netcdf
save_da_xtrm(da_xtrm,var,case=case, block=block,comp=comp,ens=ens)
def proc_R05(var_or, case, block,ens):
"""calculcate and save 5th pctl of monthly precip: drought months """
# define new variable name
var = 'R05'
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# check if var is already existing
if exist_da_xtrm(var,case=case, block=block,comp=comp,ens=ens):
print(var +' already exists')
else: # do calculations
# open da with daily data(var, case, n_ens, stream='h0', model='cam', mode='mean',isxtrm=False)
da = open_da_ens(var_or,case=case, n_ens=3, stream='h0', model='cam', mode='all')
da_lumped = da.stack(dim=("ens_member", "time"))
# calculate quantile over months
da_xtrm = da_lumped.quantile(0.05, dim=('dim'))
da_xtrm.name = var
# save variable into netcdf
save_da_xtrm(da_xtrm,var,case=case, block=block,comp=comp,ens=ens)
return
def proc_R95(var_or, case, block,ens):
"""calculcate and save 95th pctl of monthly precip: wet months """
# define new variable name
var = 'R95'
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# check if var is already existing
if exist_da_xtrm(var,case=case, block=block,comp=comp,ens=ens):
print(var +' already exists')
else: # do calculations
# open da with daily data
da = open_da_ens(var_or,case=case, n_ens=3, stream='h0', model='cam', mode='all')
da_lumped = da.stack(dim=("ens_member", "time"))
# calculate quantile over months
da_xtrm = da_lumped.quantile(0.95, dim=('dim'))
da_xtrm.name = var
# save variable into netcdf
save_da_xtrm(da_xtrm,var,case=case, block=block,comp=comp,ens=ens)
return
def proc_TXx_monthly(var_or, case, block,ens):
""" process TXx: calculate and save monthly maximum of daytime temperature and save in monthly folder"""
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# define new variable name
if var_or=='TS':
var = 'TXx_m'
elif var_or=='TREFHT':
var='TRXx_m'
else:
print('incorrect variable')
return
model = {'lnd' : 'clm2', 'atm' : 'cam', 'rof' : 'mosart'}
# check if var is already existing
case_name = case+'-i308.'+ens
# open da with daily data
da = open_da(var_or,case_name, stream='h2', model=model[block])
# calculate maximum per year
da_xtrm = da.resample(time='M').max(keep_attrs=True)
da_xtrm.name = var
da_xtrm.attrs['long_name'] = 'Monthly maximum of '+da.long_name
da_ex=extract_anaperiod(da_xtrm, esm,stream='h0')
da_mean= da_ex.mean('time')
da_mean.name = var
savedir = procdir + 'b.e213.'+comp+'_BPRP.f09_g17.esm-'+case+'-i308.'+ens +'/'
# define filename
fn_mean = case + '.'+ model[block] + '.mean_'+var+'.' + ens +'.nc'
fn=var+'_b.e213.'+comp+'_BPRP.f09_g17.esm-'+case + '-i308.'+ens+'.cam.h0.nc'
# check if variable timeseries exists and open variable as data array
if os.path.isfile(savedir +'/mean/'+ fn_mean):
print(fn_mean + ' already exists')
else:
da_mean.to_dataset().to_netcdf(savedir+'/mean/'+fn_mean)
if os.path.isfile(savedir + fn):
print(fn + ' already exists')
else:
da_xtrm.to_dataset().to_netcdf(savedir+fn)
return
# process TXx: calculate and save annual maximum of maxdaytime temperature
def proc_TNn_monthly(var_or, case, block,ens):
""" process TNn: calculate and save monthly minimum of nighttime temperature and save in monthly folder"""
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# define new variable name
if var_or=='TS':
var = 'TNn_m'
elif var_or=='TREFHT':
var='TRNn_m'
else:
print('incorrect variable')
return
model = {'lnd' : 'clm2', 'atm' : 'cam', 'rof' : 'mosart'}
# check if var is already existing
case_name = case+'-i308.'+ens
# open da with daily data
da = open_da(var_or,case_name, stream='h2', model=model[block])
# calculate maximum per year
da_xtrm = da.resample(time='M').max(keep_attrs=True)
da_xtrm.name = var
da_xtrm.attrs['long_name'] = 'Monthly minimum of '+da.long_name
da_ex=extract_anaperiod(da_xtrm, esm,stream='h0')
da_mean= da_ex.mean('time')
da_mean.name = var
savedir = procdir + 'b.e213.'+comp+'_BPRP.f09_g17.esm-'+case+'-i308.'+ens +'/'
# define filename
fn_mean = case + '.'+ model[block] + '.mean_'+var+'.' + ens +'.nc'
fn=var+'_b.e213.'+comp+'_BPRP.f09_g17.esm-'+case + '-i308.'+ens+'.cam.h0.nc'
# check if variable timeseries exists and open variable as data array
if os.path.isfile(savedir +'/mean/'+ fn_mean):
print(fn_mean + ' already exists')
else:
da_mean.to_dataset().to_netcdf(savedir+'/mean/'+fn_mean)
if os.path.isfile(savedir + fn):
print(fn + ' already exists')
else:
da_xtrm.to_dataset().to_netcdf(savedir+fn)
return
##
# get da of CDD: annual number of consecutive dry days
# because not possible to save as netcdf.
def get_CDD(var_or, case,ens):
if case=='hist':
comp='BHIST'
else:
comp='BSSP126'
# define new variable name
var = 'CDD'
block='atm'
model = {'lnd' : 'clm2', 'atm' : 'cam', 'rof' : 'mosart'}
case_name = case+'-i308.'+ens
# open da with daily data and convert to mm/day
da = open_da(var_or,case=case_name, stream='h1', model=model[block])
da = 1000*3600*24*da