source: BOL/Multi_atlas/atlas/atlas_none.py @ 3885

Last change on this file since 3885 was 3885, checked in by musat, 3 years ago

Mise a jour des scripts par rapport a la version fabric
IM

File size: 11.4 KB
Line 
1# -*- coding: iso-8859-1 -*-
2# Created : S.Sénési - nov 2015
3
4#
5desc="\nCreation d'un atlas pour une simu, une grille et une liste de variables et de saisons \n"+\
6"  Exemples : \n"+\
7"  >>> python ./atlas.py -v tas,hfls -s NPv3.1ada_1982_1991\n"+\
8""
9# Avec CliMAF, cette etape est loin d'etre necessaire; on la réalise pour 'exposer' ces fichiers
10# dans une arborescence à laquelle sont habitues certains utilisateurs
11
12
13# Répertoire de base pour les entrées et les résultats
14#dir_default='/data/hourdin/LMDZ6/SE/ORIG'
15#dir_default='/prodigfs/fabric/LMDZ6/SE/ORIG'
16#dir_default='/prodigfs/ipslfs/dods/fabric/lmdz/SE/ORIG'
17
18# Gestion des options et arguments d'appel
19from optparse import OptionParser
20parser = OptionParser(desc) ; parser.set_usage("%%prog [-h]\n%s" % desc)
21#parser.add_option("-i", "--input", help="repertoire des donnes d'entree(defaut : %s)"%dir_default,
22#                  action="store",default=dir_default)
23parser.add_option("-i", "--input", help="repertoire des donnes d'entree(defaut : %s)",
24                  action="store",default=None)
25parser.add_option("-g", "--grid", help="nom de grille (default: VLR)", action="store",default='VLR')
26parser.add_option("-r", "--region", help="nom de zone (default: GLOB)", action="store",default='GLOB')
27parser.add_option("-p", "--season", help="saison a traiter " "(eg : JJA, DJF, YEAR, defaut=%YEAR)", 
28                  action="store", default='YEAR')
29parser.add_option("-s", "--simulation", help="simulation+annees a traiter (sim_YYY1_YYY2) - laisser vide pour lister",
30                  action="store",default=None)
31parser.add_option("-t", "--reference", help="simulation de reference (sim_YYY1_YYY2, default=OBS) ",
32                  action="store",default='OBS')
33parser.add_option("-v", "--variables", help="liste des variables (separees par des virgules)", action="store",default=None)
34#parser.add_option("--root", help="Path to the root directory", action="store",default=None)
35parser.add_option("--root", help="Path to the root directory", action="store",default=None)
36parser.add_option("-f", "--force", help="force le recalcul de champs existants", 
37                  action="store_true",default=None)
38parser.add_option("-o", "--pdf", help="nom du pdf de sortie (default: atlas_<SIMU>_<SAISON>.pdf)", action="store")
39(opts, args) = parser.parse_args()
40
41#---------------------------------------------------------------------------------
42import math
43from climaf.api import *
44from climaf.html import * 
45# La description de l'organisation des données SE et des alias et rescalings
46# est partagée dans une micro-librairie :
47from lmdz_SE import * # svsg, all_SE_simulations
48from plot_params import plot_params
49#---------------------------------------------------------------------------------
50#
51clog('debug')
52crm(pattern='pme')
53crm(pattern='hflsevap')
54#crm(pattern='tasmax')
55#crm(pattern='tasmin')
56def apply_scale_offset(dat,scale,offset):
57    return ccdo(ccdo(dat,operator='mulc,'+str(float(scale))),operator='addc,'+str(float(offset)))
58#
59#craz()
60if opts.simulation is None:
61    print "Available simulations at %s are : "%opts.input,
62    for s in all_SE_simulations() : print s,
63    exit(0)
64#
65lvars=opts.variables
66if lvars is not None : lvars=lvars.split(',')
67else : lvars=variables_list
68#
69# Preparons une commande pour assembler les sorties Pdf
70if opts.pdf : pdffile=opts.pdf
71else: pdffile="atlas_"+opts.simulation+"_"+opts.season+".pdf"
72pdfargs=["pdfjam","--landscape","-o ",pdffile]
73#
74# Initialisation de l'index html
75index= header("LMDZ Atlas for "+opts.simulation+ " versus "+opts.reference+" ("+opts.season+")") 
76index += cell('PDF',pdffile)
77index += section("2d vars", level=4)
78index += open_table()
79#
80# Titres de colonnes
81ref=opts.reference ; 
82if (ref == 'OBS' ) : text_diff='bias'
83else:                text_diff='diff'
84index+=open_line('VARIABLE')+cell('bias')+cell('rmse')+cell('mean')+cell(ref)+cell(text_diff)+\
85        cell('zonal')+cell('all')+cell('pdf')+close_line()
86#
87# -- Declare the script ml2pl for vertical interpolation
88cscript("ml2pl", "/home/jservon/Evaluation/CliMAF/Atlas_LMDz/ml2pl.sh -p ${var_2} -m ${var_1} ${in_1} ${out} ${in_2}",
89    commuteWithTimeConcatenation=True, commuteWithSpaceConcatenation=True)
90# -- Vertical levels for the vertical interpolation
91fixed_fields("ml2pl",("press_levels.txt","/home/fabric/LMDZ/atlas/press_levels.txt"))
92#
93for variable  in lvars :
94    # Get the model and the reference
95    if opts.root:
96       simu=svsg(opts.simulation,variable,opts.season,opts.grid, root=opts.root)
97    else:
98       simu=svsg(opts.simulation,variable,opts.season,opts.grid)
99    print 'variable = ',variable
100    reff=svsg(opts.reference,variable,opts.season,opts.grid)
101    #
102    # If the variable is a 3D field:
103    #  - interpolate the variable on the standard pressure levels with ml2pl (L. Guez)
104    #  - Compute the difference model-ref with diff_zonmean (computes the zonal mean lat/pressure fields,
105    #    interpolates the model on the ref, both vertically and horizontally, and returns the difference)
106    if is3d(variable) :
107       simu_pres = svsg(opts.simulation,'pres',opts.season,opts.grid)
108       simu = ml2pl(simu,simu_pres)
109       if (ref != 'OBS' ) : 
110           reff_pres = svsg(opts.reference,'pres',opts.season,opts.grid)
111           reff = ml2pl(reff,reff_pres)
112       simu = zonmean(simu)
113       reff = zonmean(reff)
114       diff = diff_zonmean(simu,reff)
115    else:
116        if (opts.grid == '' ) : reff=regrid(reff,simu)
117        diff=minus(simu,reff)
118
119    pparams = plot_params(variable,'full_field')
120    vertical_interval = 'trYMaxF=1000|trYMinF=1'
121    stringFontHeight=0.018
122    if is3d(variable):
123        pparams.update({'options':vertical_interval})
124        stringFontHeight=0.03
125    # Map for simulation
126    simu_fig=plot(simu,title="",
127                  gsnLeftString=variable,
128                  gsnCenterString=opts.simulation,
129                  gsnRightString=opts.season,
130                  gsnStringFontHeightF=stringFontHeight,
131                  mpCenterLonF=0,
132                  **pparams)
133    simu_avg=cvalue(space_average(simu))
134    #
135    # Map for reference
136    ref_fig=plot(reff,title="",
137                 gsnLeftString=variable,
138                 gsnCenterString=ref,
139                 gsnRightString=opts.season,
140                 gsnStringFontHeightF=stringFontHeight,
141                 mpCenterLonF=0,
142                 **pparams)
143    ref_avg=cvalue(space_average(reff))
144    #
145    # Bias (or difference between simulations) map
146    if (ref == 'OBS' ) : p=plot_params(variable,'bias')
147    else:                p=plot_params(variable,'model_model')
148    tmp_aux_params = plot_params(variable,'full_field')
149    scale = 1.0 ; offset = 0.0
150    if 'offset' in tmp_aux_params or 'scale' in tmp_aux_params:
151       if 'offset' in tmp_aux_params:
152          offset = tmp_aux_params['offset']
153       else:
154          offset=0.0
155       if 'scale' in tmp_aux_params:
156          scale = tmp_aux_params['scale']
157       else:
158          scale=1.0
159       wreff = apply_scale_offset(reff,scale,offset)
160       wsimu = apply_scale_offset(simu,scale,offset)
161    else:
162       wreff = reff
163       wsimu = simu
164    #
165    if is3d(variable):
166        p.update({'options':vertical_interval})
167    if variable in ['ua','va','ta','hus','hur']:
168        tmp_levs = tmp_aux_params['colors']
169        p.update({'contours':tmp_levs})
170        diff_fig=plot(diff,wreff,title="", format='png', mpCenterLonF=0,
171                  gsnLeftString=variable,
172                  gsnCenterString=opts.simulation+' - '+ref,
173                  gsnRightString=opts.season,
174                  gsnStringFontHeightF=stringFontHeight,
175                  aux_options='cnLineThicknessF=2|cnLineLabelsOn=True', **p)
176    else:
177        p.update({'contours':1})
178        diff_fig=plot(diff,title="", format='png', mpCenterLonF=0,
179                  gsnLeftString=variable,
180                  gsnCenterString=opts.simulation+' - '+ref,
181                  gsnRightString=opts.season,
182                  gsnStringFontHeightF=stringFontHeight,
183                  **p)
184
185    #
186    # Bias mean value, and RMSD/RMSE
187    diff_avg=cvalue(space_average(diff))
188    rmsd=math.sqrt(cvalue(space_average(ccdo(diff,operator='-b F64 sqr'))))
189    #
190    # Zonal means
191    if not is3d(variable):
192        # -- apply a mask corresponding to the reference
193        mask = div(reff,reff)
194        msimu = mul(wsimu,mask)
195        # -- Compute the zonal mean
196        zmean=ccdo(msimu, operator='zonmean')
197        ref_zmean=ccdo(wreff, operator='zonmean')
198        #
199        sim=opts.simulation
200        #if variable in ['zg500']:
201        #   ref_zmean = ccdo(ref_zmean,operator='-b F32 mulc,1')
202        #   zmean = ccdo(zmean,operator='-b F32 mulc,1')
203        zmean_fig=curves(cens([sim,ref],zmean,ref_zmean),
204                         title="",
205                         lgcols=3,
206                         options=#'tiYAxisString=""|'+\
207                                 #'+\'+\
208                                 'tmYROn=True|'+\
209                                 'tmYRBorderOn=True|'+\
210                                 'tmYLOn=False|'+\
211                                 'tmYUseRight=True|'+\
212                                 'vpXF=0|'+\
213                                 'vpWidthF=0.66|'+\
214                                 'vpHeightF=0.33|'+\
215                                 'tmYRLabelsOn=True|'+\
216                                 'tmXBLabelFontHeightF=0.018|'+\
217                                 'tmYLLabelFontHeightF=0.016|'+\
218                                 'lgLabelFontHeightF=0.018|'+\
219                                 #'pmLegendSide=Bottom|'+\
220                                 'pmLegendOrthogonalPosF=-0.32|'+\
221                                 'pmLegendParallelPosF=1.0|'+\
222                                 'tmXMajorGrid=True|'+\
223                                 'tmYMajorGrid=True|'+\
224                                 'tmXMajorGridLineDashPattern=2|'+\
225                                 'tmYMajorGridLineDashPattern=2|'+\
226                                 'xyLineThicknessF=8|'+\
227                                 'gsnLeftString='+variable+'|'+\
228                                 'gsnCenterString='+opts.simulation+' vs '+ref+'|'+\
229                                 'gsnRightString='+opts.season+'|'+\
230                                 'gsnStringFontHeightF='+str(stringFontHeight))
231    #    # Composite figure
232    if is3d(variable):
233        page=cpage([[simu_fig,ref_fig],[diff_fig,None]],orientation='landscape', page_trim=True, fig_trim=True)
234        pdf_page=cpage([[simu_fig,ref_fig],[diff_fig,None]],orientation='landscape',
235                   page_trim=True, fig_trim=True, format='pdf', title=variable+" "+opts.simulation)
236    else:
237        page=cpage([[simu_fig,ref_fig],[diff_fig,zmean_fig]],orientation='landscape', page_trim=True, fig_trim=True)
238        pdf_page=cpage([[simu_fig,ref_fig],[diff_fig,zmean_fig]],orientation='landscape', 
239                   page_trim=True, fig_trim=True, format='pdf', title=variable+" "+opts.simulation)
240    pdfargs.append(cfile(pdf_page))
241    #
242    thumbnail_size = 200
243    if is3d(variable):
244            index+=open_line(varlongname(variable)+' ('+variable+')')+\
245                    cell("%.2g"%diff_avg,cfile(diff_fig))+\
246                    cell("%.2g"%rmsd,cfile(diff_fig))+\
247                    cell(simu,cfile(simu_fig),thumbnail=thumbnail_size,hover=False)+\
248                    cell(ref,cfile(ref_fig),thumbnail=thumbnail_size,hover=False)+\
249                    cell(text_diff,cfile(diff_fig),thumbnail=thumbnail_size,hover=False)+\
250                    ' '+\
251                    cell('page',cfile(page),thumbnail=thumbnail_size,hover=False)+\
252                    cell('Pdf',cfile(pdf_page))
253            close_line()
254    else:
255            index+=open_line(varlongname(variable)+' ('+variable+')')+\
256                    cell("%.2g"%diff_avg,cfile(diff_fig))+\
257                    cell("%.2g"%rmsd,cfile(diff_fig))+\
258                    cell(simu,cfile(simu_fig),thumbnail=thumbnail_size,hover=False)+\
259                   cell(ref,cfile(ref_fig),thumbnail=thumbnail_size,hover=False)+\
260                    cell(text_diff,cfile(diff_fig),thumbnail=thumbnail_size,hover=False)+\
261                    cell('zonal mean',cfile(zmean_fig),thumbnail=thumbnail_size,hover=False)+\
262                    cell('page',cfile(page),thumbnail=thumbnail_size,hover=False)+\
263                    cell('Pdf',cfile(pdf_page))
264            close_line()
265#
266# Finalisons l'index html
267index += close_table()
268index += trailer()
269#out="index_example.html"
270out="index_"+opts.region+"_"+opts.season+"_"+opts.simulation+".html"
271with open(out,"w") as filout : filout.write(index)
272#
273# Creation du Pdf multi-pages
274comm=subprocess.Popen(pdfargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
275#
276import os,os.path ; 
277# print("Attendez un bon peu : lancemement de firefox sur Ciclad....")
278# os.system("firefox file://"+os.path.abspath(os.path.curdir)+"/"+out+"&")
Note: See TracBrowser for help on using the repository browser.