-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_ccam.py
More file actions
3249 lines (2702 loc) · 129 KB
/
run_ccam.py
File metadata and controls
3249 lines (2702 loc) · 129 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import argparse
import sys
import subprocess
from calendar import monthrange
import json
# CCAM simulation python code
def main(inargs):
"Main CCAM simulation script"
global d
print("Reading arguments")
d = vars(inargs)
convert_old_settings()
check_inargs()
print("Verify directories")
create_directories()
if d['preprocess_test'] is True:
print("Define preprocess settings")
set_preprocess_options()
if d['simulation_test'] is True:
print("Define simulation settings")
set_simulation_options()
print("Loop over simulation months")
for mth in range(0, d['ncountmax']):
print("----------------------------------------")
if d['timeloop_test'] is True:
# Find date for downscaling
get_datetime()
print("Reading date ",d['iyr'],d['imth_2digit'])
d['ofile'] = dict2str('{name}.{iyr}{imth_2digit}')
if d['preprocess_test'] is True:
# Create surface files if needed
check_surface_files()
if d['simulation_test'] is True:
# Define input and output files
print("Define input and output filenames")
prep_iofiles()
locate_tracer_emissions()
# Determine model parameters
print("Set model parameters")
set_mlev_params()
config_initconds()
set_nudging()
set_downscaling()
set_gwdrag()
set_convection()
set_cloud()
set_radiation()
set_land_carbon_aerosol()
set_ocean()
set_pblmix()
# special modes
set_aquaplanet()
# Create CCAM namelist and system checks
print("Create CCAM namelist and perform system checks")
set_surf_output()
prepare_ccam_infiles()
create_input_file()
check_correct_host()
# Run CCAM simulation
print("Run CCAM")
run_model()
if d['postprocess_test'] is True:
print("Post-process CCAM output")
post_process_output()
if d['timeloop_test'] is True:
print("Update simulation date and time")
update_monthyear()
update_yearqm()
print("----------------------------------------")
print("Simulation loop completed")
# Check if restart is required
print("Update simulation restart status")
restart_flag()
print("Script completed sucessfully")
#===============================================================================
# Initialisation and finalisation
#===============================================================================
def convert_old_settings():
"Convert dmode for new format"
# replace number options with text versions. This makes the code more readable.
dmode_dict = { 0:"nudging_gcm", 1:"sst_only", 2:"nudging_ccam", 3:"sst_6hour",
4:"generate_veg", 5:"postprocess", 6:"nudging_gcm_with_sst",
7:"aquaplanet1", 8:"aquaplanet2", 9:"aquaplanet3",
10:"aquaplanet4", 11:"aquaplanet5", 12:"aquaplanet6",
13:"aquaplanet7", 14:"aquaplanet8" }
d['dmode'] = find_mode(d['dmode'],dmode_dict,"dmode")
# determine what simulation modes should be active
d['preprocess_test'] = False
if d['dmode'] != "postprocess":
d['preprocess_test'] = True
d['simulation_test'] = False
if not d['dmode'] in ["generate_veg", "postprocess"]:
d['simulation_test'] = True
d['postprocess_test'] = False
if d['dmode'] != "generate_veg":
d['postprocess_test'] = True
d['timeloop_test'] = False
if (d['preprocess_test'] is True) or (d['simulation_test'] is True):
d['timeloop_test'] = True
if d['simulation_test'] is True:
if d['preprocess_test'] is False:
print('Internal error - simulation_test=T requires preprocess_test=T')
sys.exit(1)
machinetype_dict = { 0:"mpirun", 1:"srun" }
d['machinetype'] = find_mode(d['machinetype'],machinetype_dict,"machinetype")
if d['preprocess_test'] is True:
leap_dict = { 0:"noleap", 1:"leap", 2:"360", 3:"auto" }
d['leap'] = find_mode(d['leap'],leap_dict,"leap")
sib_dict = { 1:"cable_vary", 3:"cable_sli", 4:"cable_const",
5:"cable_modis2020", 6:"cable_sli_modis2020",
7:"cable_modis2020_const"}
d['sib'] = find_mode(d['sib'],sib_dict,"sib")
aero_dict = { 0:"off", 1:"prognostic" }
d['aero'] = find_mode(d['aero'],aero_dict,"aero")
mlo_dict = { 0:"prescribed", 1:"dynamical" }
d['mlo'] = find_mode(d['mlo'],mlo_dict,"mlo")
casa_dict = { 0:"off", 1:"casa_cnp", 2:"casa_cnp_pop" }
d['casa'] = find_mode(d['casa'],casa_dict,"casa")
if d['simulation_test'] is True:
conv_dict = { 0:"2014", 1:"2015a", 2:"2015b", 3:"2017", 4:"Mod2015a", 5:"2021", 6:"grell" }
d['conv'] = find_mode(d['conv'],conv_dict,"conv")
cldfrac_dict = { 0:"smith", 1:"mcgregor", 2:"tiedtke" }
d['cldfrac'] = find_mode(d['cldfrac'],cldfrac_dict,"cldfrac")
cloud_dict = { 0:"liq_ice", 1:"liq_ice_rain", 2:"liq_ice_rain_snow_graupel", 3:"lin" }
d['cloud'] = find_mode(d['cloud'],cloud_dict,"cloud")
rad_dict = { 0:"SE3", 1:"SE4", 2:"SE4lin" }
d['rad'] = find_mode(d['rad'],rad_dict,"rad")
bmix_dict = { 0:"ri", 1:"tke_eps", 2:"hbg" }
d['bmix'] = find_mode(d['bmix'],bmix_dict,"bmix")
bcsoil_dict = { 0:"constant", 1:"climatology", 2:"recycle" }
d['bcsoil'] = find_mode(d['bcsoil'],bcsoil_dict,"bcsoil")
if d['postprocess_test'] is True:
ncout_dict = { 0:"off", 1:"all", 5:"ctm", 7:"basic", 8:"tracer", 9:"all_s", 10:"basic_s" }
d['ncout'] = find_mode(d['ncout'],ncout_dict,"ncout")
ncsurf_dict = { 0:"off", 3:"cordex", 4:"cordex_s" }
d['ncsurf'] = find_mode(d['ncsurf'],ncsurf_dict,"ncsurf")
nchigh_dict = { 0:"off", 1:"latlon", 2:"latlon_s", 3:"shep", 4:"shep_s" }
d['nchigh'] = find_mode(d['nchigh'],nchigh_dict,"nchigh")
nctar_dict = { 0:"off", 1:"tar", 2:"delete" }
d['nctar'] = find_mode(d['nctar'],nctar_dict,"nctar")
drsmode_dict = { 0:"off", 1:"on" }
d['drsmode'] = find_mode(d['drsmode'],drsmode_dict,"drsmode")
# backwards compatibility, but also allows for theta options
if d['outlevmode']==0:
d['outlevmode']="pressure"
if d['outlevmode']==1:
d['outlevmode']="height"
if d['outlevmode']==2:
d['outlevmode']="pressure_height"
# fix for historical
if d['rcp']=='historical':
d['rcp']='historic'
def find_mode(nt, nt_dict, nt_name):
"Correct and test arguments"
# search list and replace numerical option with text based on nt_dict
itest = False
for ct in nt_dict:
if nt == str(ct):
nt = nt_dict[ct]
if nt == nt_dict[ct]:
itest = True
if itest is False:
print("Invalid option for "+nt_name)
sys.exit(1)
return nt
def check_inargs():
"Check all inargs are specified and are internally consistent"
# split arguments needed for downscaling and arguments needed for post-processing
# args2common for all modes
# args2preprocess for preprocess_test
# args2simulation for simulation_test
# args2postprocess for postprocessing_test
# cmip and rcp to be moved to args2preprocess when possible
args2common = ['name', 'nproc', 'ncountmax', 'dmode', 'iys', 'ims', 'ids', 'iye', 'ime',
'ide', 'machinetype', 'cmip', 'rcp', 'insdir', 'hdir']
args2preprocess = ['midlon', 'midlat', 'gridres', 'gridsize', 'wdir', 'terread',
'igbpveg', 'ocnbath', 'casafield', 'uclemparm', 'cableparm',
'vegindex', 'soilparm', 'uservegfile', 'userlaifile', 'bcsoilfile',
'nnode', 'sib', 'aero', 'mlo', 'casa', 'leap', 'rad_year' ]
args2simulation = ['bcdom', 'bcsoil', 'sstfile', 'sstinit', 'bcdir', 'sstdir', 'stdat',
'aeroemiss', 'model', 'tracer', 'rad', 'ktc', 'ktc_surf', 'ktc_high',
'tke_timeave_length', 'mlev', 'cloud', 'cldfrac', 'conv', 'bmix' ]
args2postprocess = ['minlat', 'maxlat', 'minlon', 'maxlon', 'reqres', 'outlevmode',
'plevs', 'mlevs', 'tlevs', 'dlevs', 'drsmode', 'drsdomain', 'model_id',
'contact', 'rcm_version_id', "drsproject", 'pcc2hist', 'ncout',
'nctar', 'ncsurf', 'nchigh', 'drshost', 'drsensemble' ]
# check arguments
for i in args2common:
if not i in d.keys():
print('Missing input argument --'+i)
sys.exit(1)
if d['preprocess_test'] is True:
for i in args2preprocess:
if not i in d.keys():
print('Missing input argument --'+i)
sys.exit(1)
if d['simulation_test'] is True:
for i in args2simulation:
if not i in d.keys():
print('Missing input argument --'+i)
sys.exit(1)
if d['postprocess_test'] is True:
for i in args2postprocess:
if not i in d.keys():
print('Missing input argument --'+i)
sys.exit(1)
# process level data for later use
d['plevs'] = d['plevs'].replace(',', ', ')
d['mlevs'] = d['mlevs'].replace(',', ', ')
d['tlevs'] = d['tlevs'].replace(',', ', ')
d['dlevs'] = d['dlevs'].replace(',', ', ')
# default value for year
d['iyr'] = d['iys']
d['imth'] = d['ims']
def create_directories():
"Create output directories and go to working directory"
# verify ccam directories exist and create any missing directories
dirname = dict2str('{hdir}')
if not os.path.isdir(dirname):
print("-> Creating ",dirname)
os.mkdir(dirname)
os.chdir(dirname)
if d['preprocess_test'] is True:
dirname = dict2str('{wdir}')
if not os.path.isdir(dirname):
print("-> Creating ",dirname)
os.mkdir(dirname)
dirname = "vegdata"
if not os.path.isdir(dirname):
print("-> Creating ",dirname)
os.mkdir(dirname)
if d['simulation_test'] is True:
for dirname in ['OUTPUT', 'RESTART']:
if not os.path.isdir(dirname):
print("-> Creating ",dirname)
os.mkdir(dirname)
if d['postprocess_test'] is True:
# different ouitlevmode indicate different vertical levels in different directories
if d['outlevmode'].find("pressure") != -1:
dirname = 'daily'
if not os.path.isdir(dirname):
print("-> Creating ",dirname)
os.mkdir(dirname)
if d['outlevmode'].find("height") != -1:
dirname = 'daily_h'
if not os.path.isdir(dirname):
print("-> Creating ",dirname)
os.mkdir(dirname)
if d['outlevmode'].find("theta") != -1:
dirname = 'daily_t'
if not os.path.isdir(dirname):
print("-> Creating ",dirname)
os.mkdir(dirname)
# ncsurf decides if raw output is processed, but ktc_surf decides if raw output is created
if d['ncsurf'] != "off":
dirname = 'cordex'
if not os.path.isdir(dirname):
print("-> Creating ",dirname)
os.mkdir(dirname)
# nchigh decides if raw output is processed, but ktc_high decides if raw output is created
if d['nchigh'] != "off":
dirname = 'highfreq'
if not os.path.isdir(dirname):
print("-> Creating ",dirname)
os.mkdir(dirname)
if d['dmode'] == "postprocess":
run_cmdline('rm -f {hdir}/restart5.qm')
dirname = dict2str('{hdir}/OUTPUT')
if not os.path.isdir(dirname):
raise ValueError("dmode=postprocess requires existing data in OUTPUT directory")
else:
run_cmdline('rm -f {hdir}/restart.qm')
dirname = dict2str('{wdir}')
# change to working or OUTPUT directory, depending on dmode
os.chdir(dirname)
def restart_flag():
"Create restart.qm containing flag for restart. This flag signifies that CCAM completed previous month"
cdate = d['iyr']*100 + d['imth']
edate = d['iye']*100 + d['ime']
if d['dmode'] == "postprocess":
if cdate > edate:
print("Reached end of postprocessing time-period")
write2file(d['hdir']+'/restart5.qm', "Complete", mode='w+')
else:
write2file(d['hdir']+'/restart5.qm', "True", mode='w+')
else:
if cdate > edate:
print("Reached end of simulation time-period")
write2file(d['hdir']+'/restart.qm', "Complete", mode='w+')
sys.exit(0)
else:
write2file(d['hdir']+'/restart.qm', "True", mode='w+')
#===============================================================================
# Timeloop functions
#===============================================================================
def get_datetime():
"Determine relevant dates and timesteps for running model"
# Load year.qm with current simulation year:
fname = dict2str('{hdir}/year.qm')
if os.path.exists(fname):
yyyydd = open(fname).read()
if len(yyyydd) == 8:
d['iyr'] = int(yyyydd[0:4])
d['imth'] = int(yyyydd[4:6])
d['iday'] = int(yyyydd[6:8])
else:
d['iyr'] = int(yyyydd[0:4])
d['imth'] = int(yyyydd[4:6])
d['iday'] = 1
else:
d['iyr'] = d['iys']
d['imth'] = d['ims']
d['iday'] = d['ids']
# Abort run at finish year
sdate = d['iyr']*10000 + d['imth']*100 + d['iday']
edate = d['iye']*10000 + d['ime']*100 + d['ide']
if (sdate>edate) and (d['simulation_test'] is True):
print("CCAM simulation already completed. Delete year.qm to restart.")
write2file(d['hdir']+'/restart.qm', "Complete", mode='w+')
sys.exit(0)
# Calculate date of previous month
iyr = d['iyr']
imth = d['imth']
if imth == 1:
d['imthlst'] = 12
d['iyrlst'] = iyr-1
else:
d['imthlst'] = imth-1
d['iyrlst'] = iyr
d['rest_iyrlst'] = iyr-1
# two-digit versions of previous and current month
d['imthlst_2digit'] = mon_2digit(d['imthlst'])
d['imth_2digit'] = mon_2digit(d['imth'])
# update calendar for generate_veg which only requires monthly temporal resolution
if d['simulation_test'] is False:
if d['leap'] == "auto":
d['leap'] = "leap"
d['eday'] = monthrange(iyr, imth)[1]
# update radiation year and decade for aerosols
if d['rad_year_input'] == 0:
d['use_rad_year'] = '.false.'
d['rad_year'] = d['iyr']
else:
d['use_rad_year'] = '.true.'
d['rad_year'] = d['rad_year_input']
# Decade start and end:
d['ddyear'] = int(int(d['rad_year']/10)*10)
d['deyear'] = int(d['ddyear'] + 9)
def update_monthyear():
# update counter for next simulation month and remove old files
iyr = d['iyr']
imth = d['imth']
d['iday'] = d['eday'] + 1
if d['leap'] == "auto":
raise ValueError("ERROR: Unable to assign calendar with leap=auto")
elif d['leap'] == "noleap":
month_length = monthrange(iyr, imth)[1]
if imth == 2:
month_length = 28 #leap year turned off
elif d['leap'] == "leap":
month_length = monthrange(iyr, imth)[1]
elif d['leap'] == "360":
month_length = 30
else:
raise ValueError("ERROR: Unknown option for leap")
if d['iday'] > month_length:
d['iday'] = 1
d['imth'] = d['imth'] + 1
if d['imth'] < 12:
fname = dict2str('Rest{name}.{iyrlst}12.000000')
if os.path.exists(fname):
run_cmdline('rm Rest{name}.{iyrlst}12.??????')
if d['imth'] > 12:
fname = dict2str('Rest{name}.{iyr}12.000000')
if os.path.exists(fname):
run_cmdline('tar cvf {hdir}/RESTART/Rest{name}.{iyr}12.tar Rest{name}.{iyr}12.??????')
run_cmdline('rm Rest{name}.{iyr}0?.?????? Rest{name}.{iyr}10.?????? Rest{name}.{iyr}11.??????')
#run_cmdline('rm {name}*{iyr}??')
#run_cmdline('rm {name}*{iyr}??.nc')
d['imth'] = 1
d['iyr'] = d['iyr'] + 1
def update_yearqm():
"Update the year.qm file"
d['yyyymmdd'] = d['iyr'] * 10000 + d['imth'] * 100 + d['iday']
write2file(d['hdir']+'/year.qm', "{yyyymmdd}", mode='w+')
#===============================================================================
# Preprocess
#===============================================================================
def set_preprocess_options():
"Define settings for preprocess"
# This function is called when preprocess_test is True
# configure domain if undefined
if d['gridres'] == -999.:
d['gridres'] = 112.*90./d['gridsize']
print(dict2str('-> Update gridres to {gridres}'))
# define domain name and special variables
d['domain'] = dict2str('{gridsize}_{midlon}_{midlat}_{gridres}km')
d['inv_schmidt'] = float(d['gridres']) * float(d['gridsize']) / (112. * 90.)
d['gridres_m'] = d['gridres']*1000.
d['lowres'] = 112.*90./(float(d['inv_schmidt'])*float(d['gridsize']))
# define user input
if d['uclemparm'] == 'default':
d['uclemparm'] = ''
if d['cableparm'] == 'default':
d['cableparm'] = ''
if d['soilparm'] == 'default':
d['soilparm'] = ''
if d['vegindex'] == 'default':
d['vegindex'] = ''
if d['uservegfile'] == 'none':
d['uservegfile'] = ''
if d['userlaifile'] == 'none':
d['userlaifile'] = ''
# store input rad_year as rad_year_input
d['rad_year_input'] = d['rad_year']
def check_surface_files():
"Ensure surface datasets exist"
d['vegin'] = dict2str('{hdir}/vegdata')
# Define vegetation file
if (d['cmip']=="cmip5") or (d['sib']=="cable_const") or (d['sib']=="cable_modis2020_const"):
# Fixed land-use
d['vegfile'] = dict2str('veg{domain}.{imth_2digit}')
else:
# Use same year as LAI will not change. Only the area fraction
d['vegfile'] = dict2str('veg{domain}.{iyr}.{imth_2digit}')
# Define aerosol file
if d['aero'] == "off":
d['sulffile'] = 'none'
if d['aero'] == "prognostic":
d['sulffile'] = dict2str('aero{domain}.{iyr}.{imth_2digit}')
# Check custom option
cfname = dict2str('{vegin}/custom.qm')
if not os.path.exists(cfname):
cfname = dict2str('{hdir}/custom.qm')
if not os.path.exists(cfname):
cfname = dict2str('{wdir}/custom.qm')
testfail = False
if not os.path.exists(cfname):
print("WARN: Cannot locate custom.qm - Need to rebuild vegetation")
testfail = True
else:
filename = open(cfname, 'r')
if dict2str('{uclemparm}\n') != filename.readline():
print("WARN: uclemparm changed in custom.qm - Need to rebuild vegetation")
testfail = True
if dict2str('{cableparm}\n') != filename.readline():
print("WARN: uclemparm changed in custom.qm - Need to rebuild vegetation")
testfail = True
if dict2str('{soilparm}\n') != filename.readline():
print("WARN: soilparm changed in custom.qm - Need to rebuild vegetation")
testfail = True
if dict2str('{vegindex}\n') != filename.readline():
print("WARN: vegindex changed in custom.qm - Need to rebuild vegetation")
testfail = True
if dict2str('{uservegfile}\n') != filename.readline():
print("WARN: uservegfile changed in custom.qm - Need to rebuild vegetation")
testfail = True
if dict2str('{userlaifile}\n') != filename.readline():
print("WARN: userlaifile changed in custom.qm - Need to rebuild vegetation")
testfail = True
if dict2str('{cmip}\n') != filename.readline():
print("WARN: cmip changed in custom.qm - Need to rebuild vegetation")
testfail = True
if dict2str('{rcp}\n') != filename.readline():
print("WARN: rcp changed in custom.qm - Need to rebuild vegetation")
testfail = True
if dict2str('{sib}\n') != filename.readline():
print("WARN: sib changed in custom.qm - Need to rebuild vegetation")
testfail = True
filename.close()
if testfail is True:
print("Create surface data")
run_cable_all()
for fname in ['topout', 'bath', 'casa']:
filename = dict2str('{vegin}/'+fname+'{domain}')
if not os.path.exists(filename):
print("Create surface data")
run_cable_all()
testfail = False
for mon in range(1, 13):
if (d['cmip']=="cmip5") or (d['sib']=="cable_const") or (d['sib']=='cable_modis2020_const'):
fname = dict2str('{vegin}/veg{domain}.'+mon_2digit(mon))
else:
fname = dict2str('{vegin}/veg{domain}.{iyr}.'+mon_2digit(mon))
if not os.path.exists(fname):
testfail = True
if check_correct_landuse(fname):
#print("WARN: Cannot find valid CABLE data for ",fname)
testfail = True
if testfail is True:
print("Update land-surface data")
run_cable_land()
# check aerosols
if d['aero'] == "prognostic":
fname = dict2str('{vegin}/{sulffile}')
if not os.path.exists(fname):
print("Update aerosol data")
run_aerosol()
def run_cable_all():
"Generate topography and land-use files for CCAM"
# Update all topography, landtype, bathymetry and carbon input files
run_cmdline('rm -f {vegin}/topo*')
run_cmdline('rm -f {vegin}/veg*')
run_cmdline('rm -f {vegin}/bath*')
run_cmdline('rm -f {vegin}/casa*')
run_cmdline('rm -f {vegin}/aero*') # delete aerosols due to cmip/rcp change
run_topo()
run_land()
run_ocean()
run_carbon()
run_cmdline('mv -f topout{domain} {vegin}')
run_cmdline('mv -f veg{domain}* {vegin}')
run_cmdline('mv -f bath{domain} {vegin}')
run_cmdline('mv -f casa{domain} {vegin}')
update_custom_land()
def run_cable_land():
"Generate topography and land-use files for CCAM"
# update only landtype files
run_cmdline("ln -s {vegin}/topout{domain} .")
run_land()
run_cmdline('rm -f topout{domain}')
run_cmdline('mv -f veg{domain}* {vegin}')
update_custom_land()
def update_custom_land():
"Update custom.qm with current preprocess files"
# record surface file configurations
# this information is used to determine if surface files need to be recalculated
filename = open(dict2str('{vegin}/custom.qm'), 'w+')
filename.write(dict2str('{uclemparm}\n'))
filename.write(dict2str('{cableparm}\n'))
filename.write(dict2str('{soilparm}\n'))
filename.write(dict2str('{vegindex}\n'))
filename.write(dict2str('{uservegfile}\n'))
filename.write(dict2str('{userlaifile}\n'))
filename.write(dict2str('{cmip}\n'))
filename.write(dict2str('{rcp}\n'))
filename.write(dict2str('{sib}\n'))
filename.close()
def run_topo():
"Run terread for topography"
print("-> Generating topography file")
write2file('top.nml', top_template(), mode='w+')
if d['machinetype'] == "srun":
run_cmdline('srun -n 1 {terread} < top.nml > terread.log')
else:
run_cmdline('{terread} < top.nml > terread.log')
check_msg_in_log("terread","terread.log","terread completed successfully")
def run_land():
"Run landuse program"
#default will disable change_landuse
d['change_landuse'] = ""
# CABLE land-use
# determine if time-varying
if (d['sib']!="cable_const") and (d['sib']!="cable_modis2020_const"):
if d['cmip'] == "cmip6":
if d['iyr'] < 2015:
d['change_landuse'] = dict2str('{stdat}/{cmip}/cmip/multiple-states_input4MIPs_landState_ScenarioMIP_UofMD-landState-base-2-1-h_gn_0850-2015.nc')
else:
if d['rcp'] == "ssp126":
d['rcplabel'] = "IMAGE"
elif d['rcp'] == "ssp245":
d['rcplabel'] = "MESSAGE"
elif d['rcp'] == "ssp370":
d['rcplabel'] = "AIM"
elif d['rcp'] == "ssp460":
d['rcplabel'] = "GCAM"
elif d['rcp'] == "ssp585":
d['rcplabel'] = "MAGPIE"
else:
raise ValueError(dict2str("Invalid choice for rcp"))
d['change_landuse'] = dict2str('{stdat}/{cmip}/{rcp}/multiple-states_input4MIPs_landState_ScenarioMIP_UofMD-{rcplabel}-{rcp}-2-1-f_gn_2015-2100.nc')
if d['change_landuse'] == "":
print("-> Generating CABLE land-use data (constant)")
else:
print("-> Generating CABLE land-use data (varying)")
# use MODIS2020 dataset
if (d['sib']=="cable_modis2020") or (d['sib']=="cable_sli_modis2020") or (d['sib']=="cable_modis2020_const"):
write2file('igbpveg.nml', igbpveg_template2(), mode='w+')
else:
write2file('igbpveg.nml', igbpveg_template(), mode='w+')
# Run IGBPVEG
if d['machinetype'] == "srun":
run_cmdline('env OMP_NUM_THREADS={nnode} OMP_WAIT_POLICY="PASSIVE" OMP_STACKSIZE=1024m srun -n 1 -c {nnode} {igbpveg} -s 5000 < igbpveg.nml > igbpveg.log')
else:
run_cmdline('env OMP_NUM_THREADS={nnode} OMP_WAIT_POLICY="PASSIVE" OMP_STACKSIZE=1024m {igbpveg} -s 5000 < igbpveg.nml > igbpveg.log')
# Check for errors
check_msg_in_log("igbpveg","igbpveg.log","igbpveg completed successfully")
run_cmdline('mv -f topsib{domain} topout{domain}')
def run_ocean():
"Run ocnbath for ocean bathymetry and rivers"
print("-> Processing bathymetry data")
write2file('ocnbath.nml', ocnbath_template(), mode='w+')
if d['machinetype'] == "srun":
run_cmdline('env OMP_NUM_THREADS={nnode} OMP_WAIT_POLICY="PASSIVE" OMP_STACKSIZE=1024m srun -n 1 -c {nnode} {ocnbath} -s 5000 < ocnbath.nml > ocnbath.log')
else:
run_cmdline('env OMP_NUM_THREADS={nnode} OMP_WAIT_POLICY="PASSIVE" OMP_STACKSIZE=1024m {ocnbath} -s 5000 < ocnbath.nml > ocnbath.log')
check_msg_in_log("ocnbath","ocnbath.log","ocnbath completed successfully")
def run_carbon():
"Run casafield for carbon cycle emissions"
print("-> Processing CASA data")
if d['machinetype'] == "srun":
run_cmdline('srun -n 1 {casafield} -t topout{domain} -i {insdir}/vegin/casaNP_gridinfo_1dx1d.nc -o casa{domain} > casafield.log')
else:
run_cmdline('{casafield} -t topout{domain} -i {insdir}/vegin/casaNP_gridinfo_1dx1d.nc -o casa{domain} > casafield.log')
check_msg_in_log("casafield","casafield.log","casafield completed successfully")
def run_aerosol():
"Run aeroemiss for aerosol emissions"
# Update only aerosol files
create_aeroemiss_file()
if d['aero'] == "prognostic":
run_cmdline('mv -f {sulffile} {vegin}')
update_custom_land()
def create_aeroemiss_file():
"Prepare aerosol files"
if d['aero'] == "prognostic":
print("-> Create aerosol emissions")
if d['cmip'] == "cmip5":
if d['rcp'] == "historic" or d['iyr'] < 2010:
aero = {'so2_anth': get_fpath('{stdat}/{cmip}/historic/IPCC_emissions_SO2_anthropogenic_{ddyear}*.nc'),
'so2_ship': get_fpath('{stdat}/{cmip}/historic/IPCC_emissions_SO2_ships_{ddyear}*.nc'),
'so2_biom': get_fpath('{stdat}/{cmip}/historic/IPCC_GriddedBiomassBurningEmissions_SO2_decadalmonthlymean{ddyear}*.nc'),
'bc_anth': get_fpath('{stdat}/{cmip}/historic/IPCC_emissions_BC_anthropogenic_{ddyear}*.nc'),
'bc_ship': get_fpath('{stdat}/{cmip}/historic/IPCC_emissions_BC_ships_{ddyear}*.nc'),
'bc_biom': get_fpath('{stdat}/{cmip}/historic/IPCC_GriddedBiomassBurningEmissions_BC_decadalmonthlymean{ddyear}*.nc'),
'oc_anth': get_fpath('{stdat}/{cmip}/historic/IPCC_emissions_OC_anthropogenic_{ddyear}*.nc'),
'oc_ship': get_fpath('{stdat}/{cmip}/historic/IPCC_emissions_OC_ships_{ddyear}*.nc'),
'oc_biom': get_fpath('{stdat}/{cmip}/historic/IPCC_GriddedBiomassBurningEmissions_OC_decadalmonthlymean{ddyear}*.nc')}
elif d['iyr'] < 2100:
aero = {'so2_anth': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_SO2_anthropogenic_{ddyear}*.nc'),
'so2_ship': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_SO2_ships_{ddyear}*.nc'),
'so2_biom': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_SO2_biomassburning_{ddyear}*.nc'),
'bc_anth': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_BC_anthropogenic_{ddyear}*.nc'),
'bc_ship': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_BC_ships_{ddyear}*.nc'),
'bc_biom': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_BC_biomassburning_{ddyear}*.nc'),
'oc_anth': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_OC_anthropogenic_{ddyear}*.nc'),
'oc_ship': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_OC_ships_{ddyear}*.nc'),
'oc_biom': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_OC_biomassburning_{ddyear}*.nc')}
else:
aero = {'so2_anth': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_SO2_anthropogenic_2090*.nc'),
'so2_ship': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_SO2_ships_2090*.nc'),
'so2_biom': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_SO2_biomassburning_2090*.nc'),
'bc_anth': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_BC_anthropogenic_2090*.nc'),
'bc_ship': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_BC_ships_2090*.nc'),
'bc_biom': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_BC_biomassburning_2090*.nc'),
'oc_anth': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_OC_anthropogenic_2090*.nc'),
'oc_ship': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_OC_ships_2090*.nc'),
'oc_biom': get_fpath('{stdat}/{cmip}/{rcp}/IPCC_emissions_{rcp}_OC_biomassburning_2090*.nc')}
elif d['cmip'] == "cmip6":
if d['rcp'] == "historic" or d['iyr'] < 2015:
aero = {'so2_anth': get_fpath('{stdat}/{cmip}/cmip/SO2-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_{iyr}*.nc'),
'so2_ship': get_fpath('{stdat}/{cmip}/cmip/SO2-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_{iyr}*.nc'),
'so2_biom': get_fpath('{stdat}/{cmip}/cmip/SO2-em-openburning-share_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_{iyr}*.nc'),
'bc_anth': get_fpath('{stdat}/{cmip}/cmip/BC-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_{iyr}*.nc'),
'bc_ship': get_fpath('{stdat}/{cmip}/cmip/BC-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_{iyr}*.nc'),
'bc_biom': get_fpath('{stdat}/{cmip}/cmip/BC-em-openburning-share_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_{iyr}*.nc'),
'oc_anth': get_fpath('{stdat}/{cmip}/cmip/OC-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_{iyr}*.nc'),
'oc_ship': get_fpath('{stdat}/{cmip}/cmip/OC-em-anthro_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_{iyr}*.nc'),
'oc_biom': get_fpath('{stdat}/{cmip}/cmip/OC-em-openburning-share_input4MIPs_emissions_CMIP_CEDS-2017-05-18_gn_{iyr}*.nc')}
else:
if d['rcp'] == "ssp126":
d['rcplabel'] = "IMAGE"
elif d['rcp'] == "ssp245":
d['rcplabel'] = "MESSAGE-GLOBIOM"
elif d['rcp'] == "ssp370":
d['rcplabel'] = "AIM"
elif d['rcp'] == "ssp460":
d['rcplabel'] = "GCAM4"
elif d['rcp'] == "ssp585":
d['rcplabel'] = "REMIND-MAGPIE"
else:
raise ValueError(dict2str("Invalid choice for rcp"))
if d['iyr'] < 2020:
aero = {'so2_anth': get_fpath('{stdat}/{cmip}/{rcp}/SO2-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2015*.nc'),
'so2_ship': get_fpath('{stdat}/{cmip}/{rcp}/SO2-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2015*.nc'),
'so2_biom': get_fpath('{stdat}/{cmip}/{rcp}/SO2-em-openburning-share_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2015*.nc'),
'bc_anth': get_fpath('{stdat}/{cmip}/{rcp}/BC-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2015*.nc'),
'bc_ship': get_fpath('{stdat}/{cmip}/{rcp}/BC-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2015*.nc'),
'bc_biom': get_fpath('{stdat}/{cmip}/{rcp}/BC-em-openburning-share_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2015*.nc'),
'oc_anth': get_fpath('{stdat}/{cmip}/{rcp}/OC-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2015*.nc'),
'oc_ship': get_fpath('{stdat}/{cmip}/{rcp}/OC-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2015*.nc'),
'oc_biom': get_fpath('{stdat}/{cmip}/{rcp}/OC-em-openburning-share_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2015*.nc')}
elif d['iyr'] < 2100:
aero = {'so2_anth': get_fpath('{stdat}/{cmip}/{rcp}/SO2-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_{ddyear}*.nc'),
'so2_ship': get_fpath('{stdat}/{cmip}/{rcp}/SO2-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_{ddyear}*.nc'),
'so2_biom': get_fpath('{stdat}/{cmip}/{rcp}/SO2-em-openburning-share_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_{ddyear}*.nc'),
'bc_anth': get_fpath('{stdat}/{cmip}/{rcp}/BC-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_{ddyear}*.nc'),
'bc_ship': get_fpath('{stdat}/{cmip}/{rcp}/BC-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_{ddyear}*.nc'),
'bc_biom': get_fpath('{stdat}/{cmip}/{rcp}/BC-em-openburning-share_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_{ddyear}*.nc'),
'oc_anth': get_fpath('{stdat}/{cmip}/{rcp}/OC-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_{ddyear}*.nc'),
'oc_ship': get_fpath('{stdat}/{cmip}/{rcp}/OC-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_{ddyear}*.nc'),
'oc_biom': get_fpath('{stdat}/{cmip}/{rcp}/OC-em-openburning-share_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_{ddyear}*.nc')}
else:
aero = {'so2_anth': get_fpath('{stdat}/{cmip}/{rcp}/SO2-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2090*.nc'),
'so2_ship': get_fpath('{stdat}/{cmip}/{rcp}/SO2-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2090*.nc'),
'so2_biom': get_fpath('{stdat}/{cmip}/{rcp}/SO2-em-openburning-share_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2090*.nc'),
'bc_anth': get_fpath('{stdat}/{cmip}/{rcp}/BC-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2090*.nc'),
'bc_ship': get_fpath('{stdat}/{cmip}/{rcp}/BC-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2090*.nc'),
'bc_biom': get_fpath('{stdat}/{cmip}/{rcp}/BC-em-openburning-share_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2090*.nc'),
'oc_anth': get_fpath('{stdat}/{cmip}/{rcp}/OC-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2090*.nc'),
'oc_ship': get_fpath('{stdat}/{cmip}/{rcp}/OC-em-anthro_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2090*.nc'),
'oc_biom': get_fpath('{stdat}/{cmip}/{rcp}/OC-em-openburning-share_input4MIPs_emissions_ScenarioMIP_IAMC-{rcplabel}-{rcp}-1-1_gn_2090*.nc')}
else:
raise ValueError(dict2str("Invalid choice for cmip"))
aero['volcano'] = dict2str('{stdat}/contineous_volc.nc')
aero['dmsfile'] = dict2str('{stdat}/dmsemiss.nc')
aero['dustfile'] = dict2str('{stdat}/ginoux.nc')
for fpath in iter(aero.keys()):
check_file_exists(aero[fpath])
d.update(aero)
write2file('aeroemiss.nml', aeroemiss_template(), mode='w+')
# Create new sulffile
if d['machinetype'] == "srun":
run_cmdline('env OMP_NUM_THREADS={nnode} OMP_WAIT_POLICY="PASSIVE" OMP_STACKSIZE=1024m srun -n 1 -c {nnode} {aeroemiss} -o {sulffile} < aeroemiss.nml > aero.log')
else:
run_cmdline('env OMP_NUM_THREADS={nnode} OMP_WAIT_POLICY="PASSIVE" OMP_STACKSIZE=1024m {aeroemiss} -o {sulffile} < aeroemiss.nml > aero.log')
check_msg_in_log("aeroemiss","aero.log","aeroemiss completed successfully")
#===============================================================================
# Simulation
#===============================================================================
def set_simulation_options():
"Define simulation options"
# This function is called when simulation_test is True
# raw cc output frequency (mins)
if d['ktc'] > 360:
print("WARN: Output frequency ktc is greater than 360")
print("WARN: Output is unsuitable for further downscaling")
# need hourly output for CTM
# (may need to move this logic to run_ccam.sh)
if d['postprocess_test'] is True:
if d['ncout'] == "ctm":
if d['ktc'] > 60:
print("-> Adjusting ncout for CTM to 60 mins")
d['ktc'] = 60
# define dictionary of pre-defined dx (mtrs) : dt (sec) relationships
d_dxdt = {60000:1200, 45000:900, 36000:720,
30000:600, 22500:450, 20000:400, 18000:360,
15000:300, 12000:240, 11250:225, 10000:200, 9000:180,
7500:150, 7200:144, 6000:120, 5000:100, 4500:90, 4000:80,
3750:75, 3600:72, 3000:60, 2500:50, 2400:48, 2250:45,
2000:40, 1800:36, 1500:30, 1250:25, 1200:24,
1000:20, 900:18, 800:16, 750:15, 600:12,
500:10, 450:9, 400:8, 300:6,
250:5, 200:4, 150:3, 100:2, 50:1}
# Note - if simulation_test=T then preprocess_test=T
# determine dt based on dx, ktc, ktc_surf and ktc_high
test_gridres = d['gridres_m']
test_surf = d['ktc']
if d['ktc_surf']>0:
test_surf = d['ktc_surf']
test_high = d['ktc']
if d['ktc_high']>0:
test_high = d['ktc_high']
for dx in sorted(d_dxdt):
if (test_gridres>=dx) and (60*d['ktc']%d_dxdt[dx]==0) and (60*test_surf%d_dxdt[dx]==0) and (60*test_high%d_dxdt[dx]==0):
d['dt'] = d_dxdt[dx]
# resolution below 50m requires time step less than 1 second
if test_gridres < 50:
raise ValueError("Minimum grid resolution of 50m has been exceeded")
# check for errors with output frequency
if d['ktc_surf'] > 0:
if d['ktc']%d['ktc_surf'] != 0:
raise ValueError("ktc must be a multiple of ktc_surf")
if d['ktc_high'] > 0:
if d['ktc']%d['ktc_high'] != 0:
raise ValueError("ktc must be a multiple of ktc_high")
def prep_iofiles():
"Prepare input and output files"
# This function is called if simulation_test=T
# Define host model fields:
d['mesonest'] = dict2str('{bcdom}{iyr}{imth_2digit}.nc')
fpath = dict2str('{bcdir}/{mesonest}')
if not os.path.exists(fpath):
d['mesonest'] = dict2str('{bcdom}.{iyr}{imth_2digit}.nc')
fpath = dict2str('{bcdir}/{mesonest}')
if not os.path.exists(fpath):
d['mesonest'] = dict2str('{bcdom}_{iyr}{imth_2digit}.nc')
fpath = dict2str('{bcdir}/{mesonest}')
if not os.path.exists(fpath):
d['mesonest'] = dict2str('{bcdom}{iyr}{imth_2digit}')
fpath = dict2str('{bcdir}/{mesonest}.tar')
if not os.path.exists(fpath):
d['mesonest'] = dict2str('{bcdom}.{iyr}{imth_2digit}')
fpath = dict2str('{bcdir}/{mesonest}.tar')
if not os.path.exists(fpath):
d['mesonest'] = dict2str('{bcdom}_{iyr}{imth_2digit}')
fpath = dict2str('{bcdir}/{mesonest}.tar')
if not os.path.exists(fpath):
d['mesonest'] = dict2str('{bcdom}.{iyr}{imth_2digit}')
fpath = dict2str('{bcdir}/{mesonest}')
if not os.path.exists(fpath):
if not os.path.exists(fpath+'.000000'):
d['mesonest'] = dict2str('{bcdom}{iyr}{imth_2digit}')
# no mesonest file required for some dmode options
if d['dmode'] in ["sst_only", "aquaplanet1", "aquaplanet2", "aquaplanet3", "aquaplanet4", "aquaplanet5",
"aquaplanet6", "aquaplanet7", "aquaplanet8"]:
d['mesonest'] = 'error'
# Define restart file:
d['restfile'] = dict2str('Rest{name}.{iyr}{imth_2digit}')
# Check for user errors
if d['cmip'] == "cmip3":
print("ERROR: cmip=cmip3 is not supported")
sys.exit(1)
elif d['cmip'] == "cmip5":
if d['rcp'] == "historic":
if d['iyr'] >= 2005:
raise ValueError("Historical period finished at 2004. Consider selecting a future RCP.")
elif d['cmip'] == "cmip6":
if d['rcp'] == "historic":
if d['iyr'] >= 2015:
raise ValueError("Historical period finished at 2014. Consider selecting a future SSP.")
else:
print("ERROR: Unknown cmip option cmip = ",d['cmip'])
sys.exit(1)
# Define ozone infile:
d['amipo3'] = ".false."
if d['dmode'] in ["aquaplanet1", "aquaplanet2", "aquaplanet3",
"aquaplanet4", "aquaplanet5", "aquaplanet6",
"aquaplanet7", "aquaplanet8"]:
d['amipo3'] = ".true."
d['ozone'] = dict2str('{stdat}/APE-Ozone.T42-Lat-Alt')
elif d['cmip'] == "cmip5":
if (d['rcp']=="historic") or (d['iyr']<2005):