forked from jservonnat/C-ESM-EP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_C-ESM-EP.py
executable file
·3490 lines (3151 loc) · 176 KB
/
main_C-ESM-EP.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
# ----------------------------------------------------------------------------------- #
# -- Header of the atlas.py ; import the useful python modules (CliMAF, NEMO_atlas, -- #
# -- and potentially your own stuff stored in my_plot_functions.py in the current -- #
# -- working directory. -- #
# ------------------------------------------------------------------------------------ #
from climaf.api import *
from climaf.html import *
from climaf import cachedir
from CM_atlas import *
from climaf.site_settings import onCiclad, atTGCC, atCNRM
from getpass import getuser
from climaf import __path__ as cpath
import json
import os, copy, subprocess, shlex
# -----------------------------------------------------------------------------------
# -- PART 1: Get the instructions from:
# -- - the default values
# -- - the parameter file (priority 2)
# -- - the command line (priority 1)
# -----------------------------------------------------------------------------------
# -- Description of the atlas
# -----------------------------------------------------------------------------------
desc="\n\nAtlas Comparaisons de simulations (par rapport a une simulation de ref)"
# -- Get the parameters that the atlas takes as arguments
# -----------------------------------------------------------------------------------
from optparse import OptionParser
parser = OptionParser(desc) ; parser.set_usage("%%prog [-h]\n%s" % desc)
parser.add_option("-p", "--params",
help="Parameter file for the Coupled Model atlas (.py)",
action="store",default="params_couple.py")
parser.add_option("-s", "--season",
help="Season for the atlas",
action="store",default=None)
parser.add_option("--proj",
help="Projection: choose among GLOB, NH30, SH30",
action="store",default=None)
parser.add_option("--index_name",
help="Name of the html file (atlas)",
action="store",default=None)
parser.add_option("--clean_cache",
help="Set to 'True' or 'False' to clean the CliMAF cache (default: 'False')",
action="store",default=None)
parser.add_option("--datasets_setup",
help="Name of the file containing the list of dictionaries describing the datasets",
action="store",default=None)
parser.add_option("--comparison",
help="Name of the comparison",
action="store",default=None)
(opts, args) = parser.parse_args()
print 'opts.comparison = ', opts.comparison
# -- Get the default parameters from default_atlas_settings.py -> Priority = default
# -----------------------------------------------------------------------------------
default_file = '/share/default/default_atlas_settings.py'
while not os.path.isfile(os.getcwd()+default_file):
default_file = '/..'+default_file
execfile(os.getcwd()+default_file)
# -- If we specify a datasets_setup from the command line, we use 'models' from this file
# -----------------------------------------------------------------------------------
if opts.datasets_setup:
datasets_setup_available_period_set_file = str.replace(opts.datasets_setup,'.py','_available_period_set.py')
if os.path.isfile(datasets_setup_available_period_set_file):
use_available_period_set = True
execfile(datasets_setup_available_period_set_file)
# Create Wmodels_ts and Wmodels_clim from Wmodels
Wmodels_clim = copy.deepcopy(Wmodels)
for item in Wmodels_clim:
clim_period_args = copy.deepcopy(item['clim_period'])
item.pop('clim_period')
item.pop('ts_period')
item.update(clim_period_args)
#
Wmodels_ts = copy.deepcopy(Wmodels)
for item in Wmodels_ts:
ts_period_args = copy.deepcopy(item['ts_period'])
item.pop('ts_period')
item.pop('clim_period')
item.update(ts_period_args)
else:
execfile(opts.datasets_setup)
use_available_period_set = False
# -- Get the parameters from the param file -> Priority = 2
# -----------------------------------------------------------------------------------
execfile(opts.params)
# -- Get the command line arguments -> Priority = 1
# -----------------------------------------------------------------------------------
if opts.season:
season = opts.season
if opts.proj:
proj = opts.proj
if opts.index_name:
index_name = opts.index_name
if opts.clean_cache:
clean_cache = opts.clean_cache
# -- Add the season to the html file name
# -----------------------------------------------------------------------------------
if not index_name:
tmp_param_filename = str.split(opts.params,'/')
index_name = str.replace(tmp_param_filename[len(tmp_param_filename)-1],'params_','')
if opts.comparison:
index_name = str.replace(index_name,'.py', '_'+opts.comparison+'.html')
# Add the season
#index_name = str.replace(index_name,'.py','_'+season+'.html')
index_name = str.replace(index_name,'.py','.html')
# -- Add the user to the html file name
# -----------------------------------------------------------------------------------
user_login = ( str.split(getcwd(),'/')[4] if getuser()=='fabric' else getuser() )
index_name = 'atlas_'+index_name
# -> Clean the cache if specified by the user
# -----------------------------------------------------------------------------------
print 'clean_cache = ',clean_cache
if clean_cache=='True':
print '!!! Full clean of the cache !!!'
craz()
print '!!! Cache cleaned !!!'
# -> Specific Ciclad (fabric): set the url of the web server and the paths where the
# -> images are stored
# -----------------------------------------------------------------------------------
if onCiclad:
# Create a directory: /prodigfs/ipslfs/dods/user/CESMEP/comparison
# The atlas will be available in a self-consistent directory, containing the html and the figures.
# This way it is possible to clean the cache without removing the figures.
# It is also possible to copy the directory somewhere else (makes it transportable)
# subdir = '/prodigfs/ipslfs/dods/user/CESMEP/comparison'
component = str.replace( str.replace( str.replace( index_name, '_'+opts.comparison, '' ), '.html',''), 'atlas_', '')
subdir = '/prodigfs/ipslfs/dods/'+getuser()+'/C-ESM-EP/'+opts.comparison+'_'+user_login+'/'+component
if not os.path.isdir(subdir):
os.makedirs(subdir)
else:
os.system('rm -f '+subdir+'/*.png')
alt_dir_name = "/thredds/fileServer/IPSLFS"+str.split(subdir,'dods')[1]
root_url = "https://vesg.ipsl.upmc.fr"
if atCNRM:
# Import locations and create a sub-directory for the comparison
# The atlas will be available in this self-consistent directory, containing the html and the figures.
# This way it is possible to clean the cache without removing the figures.
# It is also possible to copy the directory somewhere else (makes it transportable)
# We enforce the username in subdir name, thus allowing to share a root dir
component = str.replace( str.replace( str.replace( index_name, '_'+opts.comparison, '' ), '.html',''), 'atlas_', '')
from locations import workspace,pathwebspace as alt_dir_name,username, root_url
subdir = workspace +'/C-ESM-EP/' +"/"+ opts.comparison+'_'+username+'/'+component
if not os.path.isdir(subdir): os.makedirs(subdir)
else : os.system('rm -f '+subdir+'/*.png')
# -> Specif TGCC: Creation du repertoire de l'atlas, ou nettoyage de celui-ci si il existe deja
# -----------------------------------------------------------------------------------
if atTGCC:
component_season = str.replace( str.replace( str.replace(index_name,'.html',''), 'atlas_', ''), '_'+opts.comparison, '' )
CWD = os.getcwd()
if '/drf/' in CWD: wspace='drf'
if '/gencmip6/' in CWD: wspace='gencmip6'
scratch_alt_dir_name = '/ccc/scratch/cont003/'+wspace+'/'+user_login+'/C-ESM-EP/'+opts.comparison+'_'+user_login+'/'+component_season+'/'
work_alt_dir_name = scratch_alt_dir_name.replace('scratch', 'work')
root_url = "https://vesg.ipsl.upmc.fr"
alt_dir_name = scratch_alt_dir_name
if not os.path.isdir(scratch_alt_dir_name):
os.makedirs(scratch_alt_dir_name)
else:
os.system('rm -f '+scratch_alt_dir_name+'/*.png')
# -> Specif TGCC and CNRM: Copy the empty.png image in the cache
# -----------------------------------------------------------------------------------
if atTGCC or atCNRM :
if not os.path.isdir(cachedir):
os.makedirs(cachedir)
if not os.path.isfile(cachedir+'/Empty.png'):
cmd = 'cp '+cpath+'/plot/Empty.png '+cachedir
print cmd
os.system(cmd)
# -> Differentiate between Ciclad and TGCC -> the first one allows working
# -> directly on the dods server ; the second one needs to go through a dods_cp
# -> That's why we set a 'dirname' on TGCC (copied with dods_cp afterwards)
# -> and an 'altdir' on Ciclad
# -----------------------------------------------------------------------------------
if atTGCC: alternative_dir = {'dirname': scratch_alt_dir_name}
if onCiclad or atCNRM : alternative_dir = {'dirname' : subdir}
# -- Set the verbosity of CliMAF (minimum is 'critical', maximum is 'debug',
# -- intermediate -> 'warning')
# -----------------------------------------------------------------------------------
clog(verbose)
# -- Control the 'force' option (by default set to None)
# -----------------------------------------------------------------------------------
for model in models:
if 'force' not in model:
model.update({'force': None})
# -- Print the models
# -----------------------------------------------------------------------------------
print '==> ----------------------------------- #'
print '==> Working on models:'
print '==> ----------------------------------- #'
print ' '
for model in models:
for key in model:
print ' '+key+' = ',model[key]
print ' --'
print ' --'
# -- Define the path to the main C-ESM-EP directory:
# -----------------------------------------------------------------------------------
rootmainpath = str.split(os.getcwd(),'C-ESM-EP')[0] + 'C-ESM-EP/'
if os.path.isfile(rootmainpath+'main_C-ESM-EP.py'):
main_cesmep_path = rootmainpath
if os.path.isfile(rootmainpath+str.split(str.split(os.getcwd(),'C-ESM-EP')[1],'/')[1]+'/main_C-ESM-EP.py'):
main_cesmep_path = rootmainpath+str.split(str.split(os.getcwd(),'C-ESM-EP')[1],'/')[1]+'/'
# -----------------------------------------------------------------------------------
# -- End PART 1
# --
# -----------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------
# -- PART 2: Build the html
# -- - the header
# -- - and the sections of diagnostics:
# -- * Atlas Explorer
# -- * Atmosphere
# -- * Blue Ocean - physics
# -- * White Ocean - Sea Ice
# -- * Green Ocean - Biogeochemistry
# -- * Land Surfaces
# -----------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------
# - Init html index
# -----------------------------------------------------------------------------------
index = header(atlas_head_title, style_file=style_file)
# ----------------------------------------------
# -- \
# -- Model Tuning: SST 50S/50N average \
# -- /
# -- /
# -- /
# ---------------------------------------------
# ---------------------------------------------------------------------------------------- #
# -- Compute the SST biases over 50S/50N for the reference models and the test datasets -- #
if do_SST_for_tuning:
# -- Start an html section to receive the plots
# ----------------------------------------------------------------------------------------------
index += section('Spatial averages = metrics for tuning', level=4)
index+=start_line('SST 50S/50N')
if not use_available_period_set:
Wmodels = period_for_diag_manager(models, diag='clim')
else:
Wmodels = copy.deepcopy(Wmodels_clim)
tuning_colors = colors_manager(Wmodels,cesmep_python_colors)
print 'tuning_colors = ',tuning_colors
for model in Wmodels:
model.update(dict(color=tuning_colors[Wmodels.index(model)]))
# ------------------------------------------------
# -- Start computing the spatial averages
# ------------------------------------------------
if not reference_models: reference_models = []
reference_datasets = [
dict(project='ref_ts', product='HadISST', period='1990-2010', dataset_type='obs_reference', frequency='monthly'),
dict(project='ref_ts', product='HadISST', period='1875-1899', dataset_type='obs_reference', frequency='monthly'),
]
ref_for_rmsc = dict(project='ref_ts', product='HadISST', period='1990-2010', dataset_type='obs_reference', frequency='monthly', variable='tos')
all_dataset_dicts= Wmodels + reference_models + reference_datasets
#
results = dict()
variable='tos'
#outjson = main_cesmep_path+'/'+opts.comparison+'/TuningMetrics/'+variable+'_'+opts.comparison+'_metrics_over_regions_for_tuning.json'
for dataset_dict in all_dataset_dicts:
#
# -- We already applied time manager, no need to re-do it (loosing time searching for the available periods)
wdataset_dict = dataset_dict.copy()
wdataset_dict.update(dict(variable='tos'))
#
# -- Use the project specs:
if wdataset_dict['project'] in tos_project_specs:
wdataset_dict.update(tos_project_specs[wdataset_dict['project']])
#
#
if not use_available_period_set:
frequency_manager_for_diag(wdataset_dict, diag='clim')
get_period_manager(wdataset_dict)
# -- Build customname and update dictionnary => we need customname anyway, for references too
if 'customname' in wdataset_dict:
customname = wdataset_dict['customname']
else:
customname = str.replace(build_plot_title(wdataset_dict, None),' ','_')
wperiod = ''
if 'clim_period' in wdataset_dict: wperiod=wdataset_dict['clim_period']
if 'period' in wdataset_dict:
if wdataset_dict['period'] not in 'fx': wperiod=wdataset_dict['period']
if wperiod not in customname: customname = customname+'_'+wperiod
customname = str.replace(customname,' ','_')
wdataset_dict.update(dict(customname = customname))
#
# -- We tag the datasets to identify if they are: test_dataset, reference_dataset or obs_reference
# -- This information is used by the plotting R script.
if dataset_dict in Wmodels:
wdataset_dict.update(dict(dataset_type='test_dataset'))
if dataset_dict in reference_models:
wdataset_dict.update(dict(dataset_type='reference_dataset'))
dataset_name = customname
results[dataset_name] = dict(results=dict(), dataset_dict=wdataset_dict)
#
# -- Loop on the regions; build the results dictionary and save it in the json file variable_comparison_spatial_averages_over_regions.json
regions_for_spatial_averages = [ dict(region_name='50S_50N', domain=[-50,50,0,360]) ]
season='ANM'
for region in regions_for_spatial_averages:
dat = llbox(regridn(clim_average(ds(**wdataset_dict), season), cdogrid='r360x180', option='remapdis'),
lonmin=region['domain'][2], lonmax=region['domain'][3],
latmin=region['domain'][0], latmax=region['domain'][1])
if safe_mode:
try:
rawvalue = cMA(space_average(dat))[0][0][0]
except:
rawvalue = 'NA'
print '!! => Computing rawvalue failed for ',wdataset_dict
print '--> Return NA'
else:
rawvalue = cMA(space_average(dat))[0][0][0]
#
if 'product' in wdataset_dict:
if wdataset_dict['product']=='WOA13-v2': rawvalue = rawvalue[0]
# -- Add offset to convert in Celsius
#print 'wdataset_dict in tuning_metrics : ',wdataset_dict
#print 'rawvalue = ',rawvalue
rawvalue = rawvalue - 273.15
# -- Compute bias
results[dataset_name]['results'].update( {region['region_name']: {'rawvalue': str(rawvalue)} } )
#
# -- Compute the centered RMSE rmsc
if wdataset_dict['dataset_type']!='obs_reference':
scyc_dat = llbox(regridn(annual_cycle(ds(**wdataset_dict)), cdogrid='r360x180', option='remapdis'),
lonmin=region['domain'][2], lonmax=region['domain'][3],
latmin=region['domain'][0], latmax=region['domain'][1])
anom_dat = fsub(scyc_dat, str(cMA(space_average(dat))[0][0][0]) )
scyc_ref = llbox(regridn(annual_cycle(ds(**ref_for_rmsc)), cdogrid='r360x180', option='remapdis'),
lonmin=region['domain'][2], lonmax=region['domain'][3],
latmin=region['domain'][0], latmax=region['domain'][1])
anom_ref = fsub(scyc_ref, str(cscalar(time_average(space_average(scyc_ref)))) )
if safe_mode:
try:
rmsc = cMA( ccdo( time_average(space_average( ccdo( minus(anom_dat, anom_ref), operator='sqr' ) )), operator='sqrt') )[0][0][0]
rms = cMA( ccdo( time_average(space_average( ccdo( minus(scyc_dat, scyc_ref), operator='sqr' ) )), operator='sqrt') )[0][0][0]
except:
print '!! => Computing RMSC and RMS failed for ',wdataset_dict
print '--> Return NA'
rmsc = 'NA'
rms = 'NA'
else:
rmsc = cMA( ccdo( time_average(space_average( ccdo( minus(anom_dat, anom_ref), operator='sqr' ) )), operator='sqrt') )[0][0][0]
rms = cMA( ccdo( time_average(space_average( ccdo( minus(scyc_dat, scyc_ref), operator='sqr' ) )), operator='sqrt') )[0][0][0]
#
results[dataset_name]['results'][region['region_name']].update( dict(rmsc = str(rmsc), rms=str(rms) ))
outjson = main_cesmep_path+'/'+opts.comparison+'/TuningMetrics/'+variable+'_'+opts.comparison+'_metrics_over_regions_for_tuning.json'
with open(outjson, 'w') as outfile:
json.dump(results, outfile, sort_keys = True, indent = 4)
#
# -- Eventually, do the plots
for region in regions_for_spatial_averages:
# -- plot the raw values
figname = subdir+ '/'+ opts.comparison+'_'+variable+'_'+region['region_name']+'_rawvalues_over_regions_for_tuning.png'
cmd = 'Rscript --vanilla '+main_cesmep_path+'share/scientific_packages/TuningMetrics/plot_rawvalue.R --metrics_json_file '+outjson+' --region '+region['region_name']+' --figname '+figname
print(cmd)
os.system(cmd)
index+=cell("", os.path.basename(figname), thumbnail="700*600", hover=False)
#
# -- plot the rmsc
figname = subdir+ '/'+ opts.comparison+'_'+variable+'_'+region['region_name']+'_rmsc_over_regions_for_tuning.png'
cmd = 'Rscript --vanilla '+main_cesmep_path+'share/scientific_packages/TuningMetrics/plot_rmsc.R --metrics_json_file '+outjson+' --region '+region['region_name']+' --figname '+figname
print(cmd)
os.system(cmd)
index+=cell("", os.path.basename(figname), thumbnail="700*600", hover=False)
#
# -- plot the rms
figname = subdir+ '/'+ opts.comparison+'_'+variable+'_'+region['region_name']+'_rms_over_regions_for_tuning.png'
cmd = 'Rscript --vanilla '+main_cesmep_path+'share/scientific_packages/TuningMetrics/plot_rmsc.R --metrics_json_file '+outjson+' --region '+region['region_name']+' --figname '+figname+' --statistic rms'
print(cmd)
os.system(cmd)
index+=cell("", os.path.basename(figname), thumbnail="700*600", hover=False)
# -- Close the line and the section
index += close_line() + close_table()
# ----------------------------------------------
# -- \
# -- Atlas Explorer \
# -- /
# -- /
# -- /
# ---------------------------------------------
# ---------------------------------------------------------------------------------------- #
# -- Plotting the maps of the Atlas Explorer -- #
if do_atlas_explorer:
print '---------------------------------'
print '-- Processing Atlas Explorer --'
print '-- do_atlas_explorer = True --'
print '-- atlas_explorer_variables = --'
print '-> ',atlas_explorer_variables
print '-- --'
# -- Period Manager
if not use_available_period_set:
Wmodels = period_for_diag_manager(models, diag='atlas_explorer')
apply_period_manager = True
else:
Wmodels = copy.deepcopy(Wmodels_clim)
apply_period_manager = False
if thumbnail_size:
thumbN_size = thumbnail_size
else:
thumbN_size = None
#thumbN_size = thumbnail_size_global
#craz()
from datetime import datetime
start = datetime.utcnow()
index += section_2D_maps(Wmodels, reference, proj, season, atlas_explorer_variables,
'Atlas Explorer', domain=domain, custom_plot_params=custom_plot_params,
add_product_in_title=add_product_in_title, safe_mode=safe_mode,
add_line_of_climato_plots=add_line_of_climato_plots,
alternative_dir=alternative_dir, custom_obs_dict=custom_obs_dict,
apply_period_manager=apply_period_manager, thumbnail_size=thumbN_size)
if atlas_explorer_climato_variables:
index += section_climato_2D_maps(Wmodels, reference, proj, season, atlas_explorer_climato_variables,
'Atlas Explorer Climatologies', domain=domain, custom_plot_params=custom_plot_params,
add_product_in_title=add_product_in_title, safe_mode=safe_mode,
alternative_dir=alternative_dir, custom_obs_dict=custom_obs_dict,
apply_period_manager=apply_period_manager, thumbnail_size=thumbN_size)
end = datetime.utcnow()
duration = end - start
print 'Total Atlas Explorer done in :',duration.seconds,'seconds'
# ---------------------------------------------------------------------------------------- #
# -- Plotting the maps of the Atlas Explorer -- #
if do_parallel_atlas_explorer:
print '---------------------------------'
print '-- Processing Atlas Explorer --'
print '-- do_parallel_atlas_explorer = True --'
print '-- atlas_explorer_variables = --'
print '-> ',atlas_explorer_variables
print '-- --'
# -- Period Manager
if not use_available_period_set:
Wmodels = period_for_diag_manager(models, diag='atlas_explorer')
apply_period_manager = True
else:
Wmodels = copy.deepcopy(Wmodels_clim)
apply_period_manager = False
if thumbnail_size:
thumbN_size = thumbnail_size
else:
thumbN_size = None
#thumbN_size = thumbnail_size_global
#craz()
from datetime import datetime
start = datetime.utcnow()
index += parallel_section_2D_maps(Wmodels, reference, proj, season, atlas_explorer_variables,
'Parallel Atlas Explorer', domain=domain, custom_plot_params=custom_plot_params,
add_product_in_title=add_product_in_title, safe_mode=safe_mode,
add_line_of_climato_plots=add_line_of_climato_plots,
alternative_dir=alternative_dir, custom_obs_dict=custom_obs_dict,
apply_period_manager=apply_period_manager, thumbnail_size=thumbN_size)
end = datetime.utcnow()
duration = end - start
print 'Total Parallel Atlas Explorer done in :',duration.seconds,'seconds'
# ---------------------------------------------------------------------------------------- #
# -- Plotting the maps of the Atlas Explorer -- #
if do_zonal_profiles_explorer:
print '---------------------------------'
print '-- Processing Zonal profiles --'
print '-- do_zonal_profiles = True --'
print '-- zonal_profiles_variables = --'
print '-> ',zonal_profiles_variables
print '-- --'
# -- Period Manager
if not use_available_period_set:
Wmodels = period_for_diag_manager(models, diag='clim')
apply_period_manager = True
else:
Wmodels = copy.deepcopy(Wmodels_clim)
apply_period_manager = False
index += section_zonal_profiles(Wmodels, reference, season, zonal_profiles_variables,
'Zonal Profiles Explorer', domain=domain,
safe_mode=safe_mode, alternative_dir=alternative_dir,
apply_period_manager=apply_period_manager)
# ----------------------------------------------
# -- \
# -- Main Time series \
# -- /
# -- /
# -- /
# ---------------------------------------------
def convert_list_to_string(dum,separator1=',', separator2='|'):
string = ''
if isinstance(dum,list):
for elt in dum:
concat_elt = elt
if isinstance(elt, list):
substring = ''
for elt2 in elt:
if substring=='':
substring = str(elt2)
else:
substring += separator1+str(elt2)
concat_elt = substring
if string=='':
string = concat_elt
else:
string += separator2+concat_elt
else:
if string=='':
string = str(concat_elt)
else:
string += separator1+str(concat_elt)
return string
else:
return dum
def ts_plot(ens_ts, **kwargs):
w_kwargs = kwargs.copy()
for kwarg in w_kwargs:
w_kwargs[kwarg] = convert_list_to_string(w_kwargs[kwarg])
return ensemble_ts_plot(ens_ts, **w_kwargs)
# ---------------------------------------------------------------------------------------- #
# -- Plotting the time series for the IGCMG meetings -- #
if do_main_time_series:
print '---------------------------------'
print '-- Processing Main Time Series --'
print '-- do_main_time_series = True --'
print '-- time_series_specs = --'
print '-> ',time_series_specs
print '-- --'
#
# ==> -- Open the section and an html table
# -----------------------------------------------------------------------------------------
index += section("Main Time Series", level=4)
#
# ==> -- Control the size of the thumbnail -> thumbN_size
# -----------------------------------------------------------------------------------------
thumbN_size = thumbnail_size
#
# -- Period Manager
if not use_available_period_set:
WWmodels_ts = period_for_diag_manager(models, diag='TS')
WWmodels_clim = period_for_diag_manager(models, diag='clim')
apply_period_manager = True
else:
WWmodels_ts = copy.deepcopy(Wmodels_ts)
WWmodels_clim = copy.deepcopy(Wmodels_clim)
apply_period_manager = False
#
# -- Remove CMIP5 models
WTSmodels = copy.deepcopy(WWmodels_ts)
#for model in WTSmodels:
# if model['project'] in 'CMIP5':
# WWmodels_ts.remove(model)
WCLIMmodels = copy.deepcopy(WWmodels_clim)
#for model in WCLIMmodels:
# if model['project'] in 'CMIP5':
# WWmodels_clim.remove(model)
#
# -- Loop on the time series specified in the params file
# -----------------------------------------------------------------------------------------
for time_series in time_series_specs:
# ==> -- Open the html line with the title
# -----------------------------------------------------------------------------------------
index += open_table()
line_title = ''
index+=start_line(line_title)
#
ens_ts_dict = dict()
names_ens = []
#
highlight_period = []
#
# -- Project specs: pass project-specific arguments
if 'project_specs' in time_series:
for dataset_dict in WWmodels_clim:
if dataset_dict['project'] in time_series['project_specs']:
dataset_dict.update(time_series['project_specs'][dataset_dict['project']])
for dataset_dict in WWmodels_ts:
if dataset_dict['project'] in time_series['project_specs']:
dataset_dict.update(time_series['project_specs'][dataset_dict['project']])
time_series.pop('project_specs')
#
if 'highlight_period' in time_series:
if time_series['highlight_period']=='clim_period':
for dataset_dict in WWmodels_clim:
# -- project_specs
#if 'project_specs' in time_series:
# if dataset_dict['project'] in time_series['project_specs']:
# dataset_dict.update(time_series['project_specs'][dataset_dict['project']])
print 'dataset_dict in time_series = ', dataset_dict
# -- Apply period manager if needed
if not use_available_period_set:
dataset_dict.update(dict(variable=time_series['variable']))
frequency_manager_for_diag(dataset_dict, diag='clim')
get_period_manager(dataset_dict)
highlight_period.append( build_period_str(dataset_dict) )
for dataset_dict in WWmodels_ts:
#
wdataset_dict = dataset_dict.copy()
wdataset_dict.update(dict(variable=time_series['variable']))
# -- project_specs
#if 'project_specs' in time_series:
# if dataset_dict['project'] in time_series['project_specs']:
# dataset_dict.update(time_series['project_specs'][dataset_dict['project']])
# -- Apply period manager if needed
if not use_available_period_set:
frequency_manager_for_diag(wdataset_dict, diag='TS')
get_period_manager(wdataset_dict)
#
# -- Get the dataset
dat = ds(**wdataset_dict)
#
# -- select a domain if the user provided one
if 'domain' in time_series:
lonmin = str(time_series['domain']['lonmin'])
lonmax = str(time_series['domain']['lonmax'])
latmin = str(time_series['domain']['latmin'])
latmax = str(time_series['domain']['latmax'])
# -- We regrid the dataset if
if time_series['variable'] in ocean_variables:
dat = regridn(dat, cdogrid='r360x180')
#
dat = llbox(dat,lonmin=lonmin,lonmax=lonmax,latmin=latmin,latmax=latmax)
#
#
# -- Apply the operation
if 'operation_kwargs' in time_series:
ts_dat = time_series['operation'](dat, **time_series['operation_kwargs'])
else:
ts_dat = time_series['operation'](dat)
#
# -- Get the name
mem_name = build_plot_title(wdataset_dict)
names_ens.append(mem_name)
#
# -- Add to the ensemble for plot
ens_ts_dict.update({mem_name:ts_dat})
#
#
# -- Finalize the CliMAF ensemble
ens_ts = cens(ens_ts_dict, order=names_ens)
#
# -- Do the plot
p = time_series.copy()
p.pop('variable')
if 'operation' in p: p.pop('operation')
if 'operation_kwargs' in p: p.pop('operation_kwargs')
if 'domain' in p: p.pop('domain')
if highlight_period:
p.update(dict(highlight_period = highlight_period))
else:
print '==> No highlight period provided => ', highlight_period
# -- Colors
p.update(dict(colors=colors_manager(WWmodels_ts,cesmep_python_colors)))
print 'ens_ts = ', ens_ts
print 'p = ', p
myplot = ts_plot(ens_ts, **p)
#cdrop(myplot)
#
# ==> -- Add the plot to the line
# -----------------------------------------------------------------------------------------
if 'fig_size' in time_series:
fig_size = time_series['fig_size']
else:
fig_size = '15*5'
thumbnail_main_ts = str(int(str.split(fig_size,'*')[0])*75)+'*'+str(int(str.split(fig_size,'*')[1])*75)
index += cell("",safe_mode_cfile_plot(myplot, safe_mode=safe_mode),
thumbnail=thumbnail_main_ts, hover=hover, **alternative_dir)
#
# ==> -- Close the line and the table for this section
# -----------------------------------------------------------------------------------------
index+=close_line() + close_table()
# ----------------------------------------------
# -- \
# -- Atmosphere \
# -- /
# -- /
# -- /
# ---------------------------------------------
# ---------------------------------------------------------------------------------------- #
# -- Plotting the Atmosphere maps -- #
if do_atmos_maps:
print '--------------------------------------'
print '-- Processing Atmospheric variables --'
print '-- do_atmos_maps = True --'
print '-- atmos_variables = --'
print '-> ',atmos_variables
print '-- --'
# -- Period Manager
if not use_available_period_set:
Wmodels = period_for_diag_manager(models, diag='atm_2D_maps')
apply_period_manager = True
else:
Wmodels = copy.deepcopy(Wmodels_clim)
apply_period_manager = False
for model in Wmodels: model.update(dict(table='Amon'))
index += section_2D_maps(Wmodels, reference, proj, season, atmos_variables,
'Atmosphere', domain=domain, custom_plot_params=custom_plot_params,
add_product_in_title=add_product_in_title, safe_mode=safe_mode,
add_line_of_climato_plots=add_line_of_climato_plots,
alternative_dir=alternative_dir, custom_obs_dict=custom_obs_dict,
apply_period_manager=apply_period_manager)
# ----------------------------------------------
# -- \
# -- Blue Ocean \
# -- /
# -- /
# -- /
# ---------------------------------------------
# ---------------------------------------------------------------------------------------- #
# Useful observations for the NEMO atlas
if reference=='default':
# (1) Annual Cycles (12 years, 2D fields)
levitus_ac=dict(project="ref_climatos",product='NODC-Levitus')
woa13_ac=dict(project="ref_climatos",product='WOA13-v2')
rapid_ac=dict(project="ref_climatos",variable='moc', product='RAPID')
# (2) Time Series (N months, 2D fields)
hadisst_ts=dict(project="ref_ts",product='HadISST', period='1870-2010')#,period=opts.period)
aviso_ts=dict(project="ref_ts",product='AVISO-L4', period='1993-2010')#,period=opts.period)
oras4_ts=dict(project="ref_ts",product='ORAS4', period='1958-2014')#,period=opts.period)
# ---------------------------------------------------------------------------------------- #
# -- Plotting the Ocean 2D maps -- #
if do_ocean_2D_maps:
print '----------------------------------'
print '-- Processing Oceanic variables --'
print '-- do_ocean_2D_maps = True --'
print '-- ocean_variables = --'
print '-> ',ocean_2D_variables
print '-- --'
# -- Period Manager
if not use_available_period_set:
Wmodels = period_for_diag_manager(models, diag='ocean_2D_maps')
apply_period_manager = True
else:
Wmodels = copy.deepcopy(Wmodels_clim)
apply_period_manager = False
for model in Wmodels: model.update(dict(table='Omon'))
if thumbnail_size:
thumbN_size = thumbnail_size
else:
thumbN_size = thumbnail_size_global
#
if do_parallel:
index += parallel_section_2D_maps(Wmodels, reference, proj, season, ocean_2D_variables,
'Ocean 2D maps', domain=domain, custom_plot_params=custom_plot_params,
add_product_in_title=add_product_in_title, safe_mode=safe_mode,
add_line_of_climato_plots=add_line_of_climato_plots,
alternative_dir=alternative_dir, custom_obs_dict=custom_obs_dict,
apply_period_manager=apply_period_manager, thumbnail_size=thumbN_size)
else:
index += section_2D_maps(Wmodels, reference, proj, season, ocean_2D_variables,
'Ocean 2D maps', domain=domain, custom_plot_params=custom_plot_params,
add_product_in_title=add_product_in_title, safe_mode=safe_mode,
add_line_of_climato_plots=add_line_of_climato_plots,
alternative_dir=alternative_dir, custom_obs_dict=custom_obs_dict,
thumbnail_size=thumbN_size,
ocean_variables=ocean_variables,
apply_period_manager=apply_period_manager)
# ---------------------------------------------------------------------------------------- #
# -- MLD maps: global, polar stereographic and North Atlantic -- #
# -- Winter and annual max -- #
if do_MLD_maps:
# -- Open the section and an html table
index += section("Mixed Layer Depth", level=4)
#
# -- MLD
variable = 'mlotst'
#
# -- Check which reference will be used:
# -> 'default' = the observations that we get from variable2reference()
# -> or a dictionary pointing to a CliMAF dataset (without the variable)
if reference=='default':
ref = variable2reference(variable, my_obs=custom_obs_dict)
else:
ref = reference
#
# -- MLD Diags -> Season and proj
if not MLD_diags: MLD_diags=[('ANM','GLOB'),('JFM','GLOB'),('JAS','GLOB'),('JFM','NH40'),('Annual Max','NH40'),('JAS','SH30'),('Annual Max','SH30')]
#
# -- Period Manager
if not use_available_period_set:
Wmodels = period_for_diag_manager(models, diag='MLD_maps')
apply_period_manager = True
else:
Wmodels = copy.deepcopy(Wmodels_clim)
apply_period_manager = False
#
# -- Loop on the MLD diags
for MLD_diag in MLD_diags:
season = MLD_diag[0]
proj = MLD_diag[1]
#
# -- Control the size of the thumbnail -> thumbN_size
thumbN_size = (thumbnail_polar_size if 'SH' in proj or 'NH' in proj else thumbnail_size_global)
#
# -- Open the html line with the title
index += open_table()
line_title = season+' '+proj+' climato '+varlongname(variable)+' ('+variable+')'
index+=open_line(line_title) + close_line()+ close_table()
#
# -- Open the html line for the plots
index += open_table() + open_line('')
#
# --> Plot the climatology vs the reference
# -- This is a trick if the model outputs for the atmosphere and the ocean are yearly
# -- then we need to set another frequency for the diagnostics needing monthly or seasonal outputs
wref = ref.copy()
if 'frequency_for_annual_cycle' in wref: wref.update( dict(frequency = wref['frequency_for_annual_cycle']) )
ref_MLD_climato = plot_climato(variable, wref, season, proj, custom_plot_params=custom_plot_params,
safe_mode=safe_mode, regrid_option='remapdis', apply_period_manager=apply_period_manager)
#
# -- Add the climatology to the line
index += cell("", ref_MLD_climato, thumbnail=thumbN_size, hover=hover, **alternative_dir)
#
for model in Wmodels:
# -- This is a trick if the model outputs for the atmosphere and the ocean are yearly
# -- then we need to set another frequency for the diagnostics needing monthly or seasonal outputs
wmodel = model.copy()
wmodel.update(dict(table='Omon', grid='gn'))
if 'frequency_for_annual_cycle' in wmodel: wmodel.update( dict(frequency = wmodel['frequency_for_annual_cycle']) )
print 'wmodel = '
MLD_climato = plot_climato(variable, wmodel, season, proj, custom_plot_params=custom_plot_params,
safe_mode=safe_mode, regrid_option='remapdis', apply_period_manager=apply_period_manager)
index += cell("",MLD_climato, thumbnail=thumbN_size, hover=hover, **alternative_dir)
#
# -- Close the line and the table of the climatos
close_line()
#
# -- Close the table
index += close_table()
# ---------------------------------------------------------------------------------------- #
# -- Wind stress curl maps: global, Pacific and North Atlantic -- #
# -- Winter and annual max -- #
if do_curl_maps:
# -- Open the section and an html table
index += section("Wind stress Curl", level=4)
#
# -- Zonal and meridional components of the wind stress
tauu_variable = 'tauuo'
tauv_variable = 'tauvo'
curl_variable = 'socurl'
#
# -- Wind stress curl Diags -> Season and proj
if not curl_diags:
curl_diags= [ dict(name='Global, annual mean', season='ANM',proj='GLOB', thumbNsize='400*300'),
dict(name='NH, annual mean', season='ANM',proj='NH40', thumbNsize='400*400'),
dict(name='North Atlantic, annual mean', season='ANM', domain=dict(lonmin=-80,lonmax=0,latmin=30,latmax=90), thumbNsize='400*300'),
dict(name='Tropical Atlantic, annual mean', season='ANM', domain=dict(lonmin=-90,lonmax=0,latmin=-10,latmax=45), thumbNsize='400*300'),
dict(name='North Pacific, annual mean', season='ANM', domain=dict(lonmin=120,lonmax=240,latmin=30,latmax=75), thumbNsize='500*250'),
dict(name='North Atlantic, JFM', season='JFM', domain=dict(lonmin=-80,lonmax=0,latmin=30,latmax=90), thumbNsize='400*300'),
]
domains = dict( ATL=dict(lonmin=-80,lonmax=0,latmin=20,latmax=90),
PAC=dict(lonmin=-80,lonmax=0,latmin=20,latmax=90),
)
#
# -- Period Manager
if not use_available_period_set:
Wmodels = period_for_diag_manager(models, diag='2D_maps')
apply_period_manager = True
else:
Wmodels = copy.deepcopy(Wmodels_clim)
apply_period_manager = False
#
# -- Loop on the wind stress curl diags
for curl_diag in curl_diags:
season = curl_diag['season']
proj = 'GLOB'
if 'proj' in curl_diag:
proj = curl_diag['proj']
domain = {}
if 'domain' in curl_diag:
domain = curl_diag['domain']
#
# -- Control the size of the thumbnail -> thumbN_size
thumbN_size = curl_diag['thumbNsize']
#
# -- Open the html line with the title
index += open_table()
line_title = 'Wind stress Curl climato '+curl_diag['name']
index+=start_line(line_title)
#
# -- Loop on the models (add the results to the html line)
if not use_available_period_set:
Wmodels = period_for_diag_manager(models, diag='2D_maps')