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

Last change on this file since 4999 was 4696, checked in by musat, 10 months ago

Creation png si pas existants
IonelaMusat?

File size: 18.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
14dir_default='/thredds/ipsl/fabric/lmdz/SE/ORIG'
15
16# Gestion des options et arguments d'appel
17from optparse import OptionParser
18parser = OptionParser(desc) ; parser.set_usage("%%prog [-h]\n%s" % desc)
19#parser.add_option("-i", "--input", help="repertoire des donnes d'entree(defaut : %s)"%dir_default,
20#                  action="store",default=dir_default)
21parser.add_option("-i", "--input", help="repertoire des donnes d'entree(defaut : %s)",
22                  action="store",default=None)
23#parser.add_option("-g", "--grid", help="nom de grille (default: VLR)", action="store",default='VLR')
24parser.add_option("-g", "--grid", help="nom de grille (default: VLR)", action="store",default='')
25
26parser.add_option("-r", "--region", help="nom de zone (GLOB, ATLTN, etc; default: GLOB)", action="store",default='GLOB')
27parser.add_option("-p", "--season", help="saison a traiter " "(eg : JJA, DJF, YEAR, defaut=%YEAR)", 
28#parser.add_option("--season", help="saison a traiter " "(eg : JJA, DJF, YEAR, defaut=%YEAR)",
29#parser.add_option("-r", "--region", help="région a traiter " "(eg : GLOB, ATLTN, defaut=%GLOB)",
30                  action="store", default='YEAR')
31parser.add_option("-s", "--simulation", help="simulation+annees a traiter (sim_YYY1_YYY2) - laisser vide pour lister",
32                  action="store",default=None)
33parser.add_option("-t", "--reference", help="simulation de reference (sim_YYY1_YYY2, default=OBS) ",
34                  action="store",default='OBS')
35parser.add_option("-v", "--variables", help="liste des variables (separees par des virgules)", action="store",default=None)
36#parser.add_option("--root", help="Path to the root directory", action="store",default=None)
37parser.add_option("--root", help="Path to the root directory", action="store",default=None)
38parser.add_option("-f", "--force", help="force le recalcul de champs existants", 
39                  action="store_true",default=None)
40parser.add_option("--dirpng",help="Path of the simulation directory", action="store",default=None)
41parser.add_option("-o", "--pdf", help="nom du pdf de sortie (default: atlas_<SIMU>_<SAISON>.pdf)", action="store")
42parser.add_option("--lonmin", help="longitude minimale",action="store",default='0')
43parser.add_option("--lonmax", help="longitude maximale",action="store",default='360')
44parser.add_option("--latmin", help="latitude minimale",action="store",default='-90')
45parser.add_option("--latmax", help="latitude maximale",action="store",default='90')
46parser.add_option("--pmin", help="pression minimale",action="store",default='1')
47(opts, args) = parser.parse_args()
48
49print('pmin = ',opts.pmin)
50centerlon=float(opts.lonmax)-180
51print('centerlon = ',centerlon)
52
53#---------------------------------------------------------------------------------
54import math
55from climaf.api import *
56from climaf.html import * 
57# La description de l'organisation des données SE et des alias et rescalings
58# est partagée dans une micro-librairie :
59from lmdz_SE import * # svsg, all_SE_simulations
60from plot_params import plot_params
61#---------------------------------------------------------------------------------
62#
63#clog('debug')
64clog('critical')
65#crm(pattern='pme')
66#crm(pattern='hflsevap')
67#crm(pattern='tasmax')
68#crm(pattern='tasmin')
69def apply_scale_offset(dat,scale,offset):
70    return ccdo(ccdo(dat,operator='mulc,'+str(float(scale))),operator='addc,'+str(float(offset)))
71#
72#craz()
73if opts.simulation is None:
74    print("Available simulations at %s are : "%opts.input,)
75    for s in all_SE_simulations() : print(s,)
76    exit(0)
77#
78lvars=opts.variables
79if lvars is not None : lvars=lvars.split(',')
80else : lvars=variables_list
81#
82# Preparons une commande pour assembler les sorties Pdf
83if opts.pdf : pdffile=opts.pdf
84else: pdffile="atlas_"+opts.simulation+"_"+opts.season+".pdf"
85pdfargs=["pdfjam","--landscape","-o ",pdffile]
86#
87# Initialisation de l'index html
88index= header("LMDZ Atlas for "+opts.simulation+ " versus "+opts.reference+" ("+opts.season+")") 
89index += cell('PDF',pdffile)
90index += section("2d vars", level=4)
91index += open_table()
92#
93# Titres de colonnes
94ref=opts.reference ; 
95if (ref == 'OBS' ) : text_diff='bias'
96else:                text_diff='diff'
97index+=open_line('VARIABLE')+cell('bias')+cell('rmse')+cell('mean')+cell(ref)+cell(text_diff)+\
98        cell('zonal')+cell('all')+cell('pdf')+close_line()
99#
100# -- Declare the script ml2pl for vertical interpolation
101cscript("ml2pl", "/home/fabric/LMDZ/atlas/ml2pl.sh -p ${var_2} -m ${var_1} ${in_1} ${out} ${in_2}",
102    commuteWithTimeConcatenation=True, commuteWithSpaceConcatenation=True)
103# -- Vertical levels for the vertical interpolation
104fixed_fields("ml2pl",("press_levels.txt","/home/fabric/LMDZ/atlas/press_levels.txt"))
105#
106for variable  in lvars :
107    # Get the model and the reference
108    if opts.root:
109       simu=svsg(opts.simulation,variable,opts.season,opts.grid, root=opts.root)
110    else:
111       simu=svsg(opts.simulation,variable,opts.season,opts.grid)
112    print('variable = ',variable)
113    reff=svsg(opts.reference,variable,opts.season,opts.grid)
114    #
115    # If the variable is a 3D field:
116    #  - interpolate the variable on the standard pressure levels with ml2pl (L. Guez)
117    #  - Compute the difference model-ref with diff_zonmean (computes the zonal mean lat/pressure fields,
118    #    interpolates the model on the ref, both vertically and horizontally, and returns the difference)
119    if is3d(variable) :
120#cas1 sim2 != sim1 ; sim1 != OBS ; sim2 != OBS
121       if (opts.simulation != 'OBS' and opts.reference != 'OBS' and opts.simulation != opts.reference ) : 
122           print('simu = ',opts.simulation)
123           print('reff = ',opts.reference)
124           simu_pres = svsg(opts.simulation,'pres',opts.season,opts.grid)
125           simu = ml2pl(simu,simu_pres)
126           simu = zonmean(simu)
127           print('simu = ',simu)
128           reff_pres = svsg(opts.reference,'pres',opts.season,opts.grid)
129           reff = ml2pl(reff,reff_pres)
130           reff = zonmean(reff)
131           print('reff = ',reff)
132### IM250821 : projection grille horizontale
133#          reff=regrid(reff,simu)
134           simu=regrid(simu,reff)
135           diff=minus(simu,reff)
136           print('diff_zonmean simu = ',diff)
137           print(' cas1 sim ref on pressure levels w/ zonmean ')
138#cas2 sim !=$ OBS ; ref = OBS
139       elif (opts.simulation != 'OBS' and opts.reference == 'OBS' ) : 
140           print('cas2')
141### interpolation sur des niveaux de pression
142           simu_pres = svsg(opts.simulation,'pres',opts.season,opts.grid)
143           simu = ml2pl(simu,simu_pres)
144### moyenne zonale
145           simu = zonmean(simu)
146### moyenne zonale
147           reff = zonmean(reff)
148### projection grille simu
149           reff=regrid(reff,simu)
150### differences moyennes zonales
151           diff=minus(simu,reff)
152           print(' cas2 sim ref on pressure levels w/ zonmean ')
153#cas3 sim1 = sim2
154       elif ( opts.simulation == opts.reference and opts.simulation != 'OBS') : 
155           simu_pres = svsg(opts.simulation,'pres',opts.season,opts.grid)
156           simu = ml2pl(simu,simu_pres)
157           simu = zonmean(simu)
158           reff = simu
159           diff=minus(simu,reff)
160           print(' cas3 sim ref on pressure levels w/ zonmean ')
161       else :
162           print(' Cas non prevu !! ')
163           print(' Modifier l appel de atlas_none.py et relancer ')
164           exit(0)
165    else:
166#27.11.21 if (opts.grid == '' ) : reff=regrid(reff,simu)
167       if ( opts.simulation != opts.reference ) : reff=regrid(reff,simu)
168    diff=minus(simu,reff)
169
170    pparams = plot_params(variable,'full_field')
171    vertical_interval = 'trYMaxF=1000|trYMinF=1'
172    #vertical_interval = 'trYMaxF=1000|trYMinF=100'
173    #vertical_interval = 'trYMaxF=1000|trYMinF='+opts.pmin
174    vertical_interval = 'trYMaxF=1000|trYMinF=1'
175    stringFontHeight=0.018
176    if is3d(variable):
177        #pparams.update({'options':vertical_interval, 'y':'lin'})
178        pparams.update({'options':vertical_interval+'|gsnYAxisIrregular2Linear=True'})
179        stringFontHeight=0.03
180    # Map for simulation
181    simu_fig=plot(llbox(simu,lonmin=opts.lonmin,lonmax=opts.lonmax,latmin=opts.latmin,latmax=opts.latmax),
182                  title="",
183                  gsnLeftString=variable,
184                  gsnCenterString=opts.simulation,
185                  gsnRightString=opts.season,
186                  gsnStringFontHeightF=stringFontHeight,
187                  mpCenterLonF=centerlon,
188                  **pparams)
189#                 mpCenterLonF=0,
190    # Single figures
191    page=cpage([[simu_fig]],orientation='landscape', page_trim=True, fig_trim=True)
192    pdf_page=cpage([[simu_fig]],orientation='landscape',
193    page_trim=True, fig_trim=True, format='pdf', title=variable+" "+opts.simulation)
194    print('PB = ',opts.dirpng,opts.season,opts.simulation,'MAP',opts.region,variable)
195    print('DIRpng/im.pdf=',opts.dirpng+"/"+opts.season+"/"+opts.simulation+"/MAP/"+opts.region+"/"+variable+".pdf")
196    pdfargs.append(cfile(pdf_page,target=opts.dirpng+"/"+opts.season+"/"+opts.simulation+"/MAP/"+opts.region+"/"+variable+".pdf"))
197    simu_avg=cvalue(space_average(simu))
198    #
199    # Map for reference
200    ref_fig=plot(llbox(reff,lonmin=opts.lonmin,lonmax=opts.lonmax,latmin=opts.latmin,latmax=opts.latmax),
201                 title="",
202                 gsnLeftString=variable,
203                 gsnCenterString=ref,
204                 gsnRightString=opts.season,
205                 gsnStringFontHeightF=stringFontHeight,
206                 mpCenterLonF=centerlon,
207                 **pparams)
208#                mpCenterLonF=0,
209    #    # Single figures ref_fig
210    page=cpage([[ref_fig]],orientation='landscape', page_trim=True, fig_trim=True)
211    pdf_page=cpage([[ref_fig]],orientation='landscape',
212        page_trim=True, fig_trim=True, format='pdf', title=variable+" "+opts.simulation)
213    pdfargs.append(cfile(pdf_page,target=opts.dirpng+"/"+opts.season+"/"+opts.reference+"/MAP/"+opts.region+"/"+variable+".pdf"))
214    ref_avg=cvalue(space_average(reff))
215    #
216    # Bias (or difference between simulations) map
217    if (ref == 'OBS' ) : p=plot_params(variable,'bias')
218    else:                p=plot_params(variable,'model_model')
219    tmp_aux_params = plot_params(variable,'full_field')
220    scale = 1.0 ; offset = 0.0
221    if 'offset' in tmp_aux_params or 'scale' in tmp_aux_params:
222       if 'offset' in tmp_aux_params:
223          offset = tmp_aux_params['offset']
224       else:
225          offset=0.0
226       if 'scale' in tmp_aux_params:
227          scale = tmp_aux_params['scale']
228       else:
229          scale=1.0
230       wreff = apply_scale_offset(reff,scale,offset)
231       wsimu = apply_scale_offset(simu,scale,offset)
232    else:
233       wreff = reff
234       wsimu = simu
235    #
236    if is3d(variable):
237        #p.update({'options':vertical_interval, 'y':'lin'})
238        p.update({'options':vertical_interval+'|gsnYAxisIrregular2Linear=True'})
239    if variable in ['ua','va','ta','hus','hur']:
240        tmp_levs = tmp_aux_params['colors']
241        p.update({'contours':tmp_levs})
242        diff_fig=plot(llbox(diff,lonmin=opts.lonmin,lonmax=opts.lonmax,latmin=opts.latmin,latmax=opts.latmax),
243                  llbox(wreff,lonmin=opts.lonmin,lonmax=opts.lonmax,latmin=opts.latmin,latmax=opts.latmax),
244                  title="", format='png',
245                  gsnLeftString=variable,
246                  gsnCenterString=opts.simulation+' - '+ref,
247                  gsnRightString=opts.season,
248                  gsnStringFontHeightF=stringFontHeight,
249                  aux_options='cnLineThicknessF=2|cnLineLabelsOn=True', **p)
250    #    # Single figures diff_fig
251        page=cpage([[diff_fig]],orientation='landscape', page_trim=True, fig_trim=True)
252        pdf_page=cpage([[diff_fig]],orientation='landscape',
253                page_trim=True, fig_trim=True, format='pdf', title=variable+" "+opts.simulation)
254        pdfargs.append(cfile(pdf_page,target=opts.dirpng+"/"+opts.season+"/"+opts.simulation+"/DMAP_"+opts.reference+"/"+opts.region+"/"+variable+".pdf"))
255    else:
256        p.update({'contours':1})
257        diff_fig=plot(llbox(diff,lonmin=opts.lonmin,lonmax=opts.lonmax,latmin=opts.latmin,latmax=opts.latmax),
258                  title="", format='png',
259                  gsnLeftString=variable,
260                  gsnCenterString=opts.simulation+' - '+ref,
261                  gsnRightString=opts.season,
262                  gsnStringFontHeightF=stringFontHeight,
263                  mpCenterLonF=centerlon,
264                  **p)
265#                 mpCenterLonF=0,
266
267    #
268    # Bias mean value, and RMSD/RMSE
269    diff_avg=cvalue(space_average(diff))
270    rmsd=math.sqrt(cvalue(space_average(ccdo(diff,operator='b F64 sqr'))))
271    #
272    # Zonal means
273    if not is3d(variable):
274        # -- apply a mask corresponding to the reference
275        #IMorig mask = div(reff,reff)
276        #IMorig msimu = mul(wsimu,mask)
277        # -- Compute the zonal mean
278        #IMorig zmean=ccdo(msimu, operator='zonmean')
279        #IMorig ref_zmean=ccdo(wreff, operator='zonmean')
280        #
281        #IMorig sim=opts.simulation
282        #if variable in ['zg500']:
283        #   ref_zmean = ccdo(ref_zmean,operator='-b F32 mulc,1')
284        #   zmean = ccdo(zmean,operator='-b F32 mulc,1')
285        #IMorig zmean_fig=curves(cens([sim,ref],zmean,ref_zmean),
286        #IMorig                  title="",
287        #IMorig                  lgcols=3,
288               #IMorig           options=#'tiYAxisString=""|'+\
289                #IMorig                  #'+\'+\
290                #IMorig                  'tmYROn=True|'+\
291        #IMorig                          'tmYRBorderOn=True|'+\
292        #IMorig                          'tmYLOn=False|'+\
293        #IMorig                          'tmYUseRight=True|'+\
294        #IMorig                          'vpXF=0|'+\
295        #IMorig                          'vpWidthF=0.66|'+\
296        #IMorig                          'vpHeightF=0.33|'+\
297        #IMorig                          'tmYRLabelsOn=True|'+\
298        #IMorig                          'tmXBLabelFontHeightF=0.018|'+\
299        #IMorig                          'tmYLLabelFontHeightF=0.016|'+\
300        #IMorig                          'lgLabelFontHeightF=0.018|'+\
301        #IMorig                          #'pmLegendSide=Bottom|'+\
302        #IMorig                          'pmLegendOrthogonalPosF=-0.32|'+\
303        #IMorig                          'pmLegendParallelPosF=1.0|'+\
304        #IMorig                          'tmXMajorGrid=True|'+\
305        #IMorig                          'tmYMajorGrid=True|'+\
306        #IMorig                          'tmXMajorGridLineDashPattern=2|'+\
307        #IMorig                          'tmYMajorGridLineDashPattern=2|'+\
308        #IMorig                          'xyLineThicknessF=8|'+\
309        #IMorig                          'gsnLeftString='+variable+'|'+\
310        #IMorig                          'gsnCenterString='+opts.simulation+' vs '+ref+'|'+\
311        #IMorig                          'gsnRightString='+opts.season+'|'+\
312        #IMorig                          'gsnStringFontHeightF='+str(stringFontHeight))
313    #    # Single figures
314        page=cpage([[simu_fig]],orientation='landscape', page_trim=True, fig_trim=True)
315        pdf_page=cpage([[simu_fig]],orientation='landscape', 
316                page_trim=True, fig_trim=True, format='pdf', title=variable+" "+opts.simulation)
317        pdfargs.append(cfile(pdf_page,target=opts.dirpng+"/"+opts.season+"/"+opts.simulation+"/MAP/"+opts.region+"/"+variable+".pdf"))
318    #    # Single figures ref_fig
319        page=cpage([[ref_fig]],orientation='landscape', page_trim=True, fig_trim=True)
320        pdf_page=cpage([[ref_fig]],orientation='landscape', 
321                page_trim=True, fig_trim=True, format='pdf', title=variable+" "+opts.simulation)
322        pdfargs.append(cfile(pdf_page,target=opts.dirpng+"/"+opts.season+"/"+opts.reference+"/MAP/"+opts.region+"/"+variable+".pdf"))
323    #    # Single figures diff_fig
324        page=cpage([[diff_fig]],orientation='landscape', page_trim=True, fig_trim=True)
325        pdf_page=cpage([[diff_fig]],orientation='landscape', 
326                page_trim=True, fig_trim=True, format='pdf', title=variable+" "+opts.simulation)
327        pdfargs.append(cfile(pdf_page,target=opts.dirpng+"/"+opts.season+"/"+opts.simulation+"/DMAP_"+opts.reference+"/"+opts.region+"/"+variable+".pdf"))
328# Creation du Pdf multi-pages
329        comm=subprocess.Popen(pdfargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
330    #    # Composite figure
331    if is3d(variable):
332        page=cpage([[simu_fig,ref_fig],[diff_fig,None]],orientation='landscape', page_trim=True, fig_trim=True)
333        pdf_page=cpage([[simu_fig,ref_fig],[diff_fig,None]],orientation='landscape',
334                   page_trim=True, fig_trim=True, format='pdf', title=variable+" "+opts.simulation)
335    else:
336        #IMorig page=cpage([[simu_fig,ref_fig],[diff_fig,zmean_fig]],orientation='landscape', page_trim=True, fig_trim=True)
337        page=cpage([[simu_fig,ref_fig],[diff_fig,diff_fig]],orientation='landscape', page_trim=True, fig_trim=True)
338        #IMorig pdf_page=cpage([[simu_fig,ref_fig],[diff_fig,zmean_fig]],orientation='landscape',
339        pdf_page=cpage([[simu_fig,ref_fig],[diff_fig,diff_fig]],orientation='landscape', 
340                   page_trim=True, fig_trim=True, format='pdf', title=variable+" "+opts.simulation)
341    pdfargs.append(cfile(pdf_page))
342    #
343    thumbnail_size = 200
344    if is3d(variable):
345            index+=open_line(varlongname(variable)+' ('+variable+')')+\
346                    cell("%.2g"%diff_avg,cfile(diff_fig))+\
347                    cell("%.2g"%rmsd,cfile(diff_fig))+\
348                    cell(simu,cfile(simu_fig),thumbnail=thumbnail_size,hover=False)+\
349                    cell(ref,cfile(ref_fig),thumbnail=thumbnail_size,hover=False)+\
350                    cell(text_diff,cfile(diff_fig),thumbnail=thumbnail_size,hover=False)+\
351                    ' '+\
352                    cell('page',cfile(page),thumbnail=thumbnail_size,hover=False)+\
353                    cell('Pdf',cfile(pdf_page))
354            close_line()
355    else:
356            index+=open_line(varlongname(variable)+' ('+variable+')')+\
357                    cell("%.2g"%diff_avg,cfile(diff_fig))+\
358                    cell("%.2g"%rmsd,cfile(diff_fig))+\
359                    cell(simu,cfile(simu_fig),thumbnail=thumbnail_size,hover=False)+\
360                    cell(ref,cfile(ref_fig),thumbnail=thumbnail_size,hover=False)+\
361                    cell(text_diff,cfile(diff_fig),thumbnail=thumbnail_size,hover=False)+\
362                    cell('zonal mean',cfile(diff_fig),thumbnail=thumbnail_size,hover=False)+\
363                    cell('page',cfile(page),thumbnail=thumbnail_size,hover=False)+\
364                    cell('Pdf',cfile(pdf_page))
365            close_line()
366#IMorig: au-dessus cell('zonal mean',cfile(zmean_fig),thumbnail=thumbnail_size,hover=False)+\
367
368# Finalisons l'index html
369index += close_table()
370index += trailer()
371out="index_"+opts.region+"_"+opts.season+"_"+opts.simulation+".html"
372with open(out,"w") as filout : filout.write(index)
373#
374# Creation du Pdf multi-pages
375comm=subprocess.Popen(pdfargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
376#
377import os,os.path ; 
378# print("Attendez un bon peu : lancemement de firefox sur Ciclad....")
379# os.system("firefox file://"+os.path.abspath(os.path.curdir)+"/"+out+"&")
Note: See TracBrowser for help on using the repository browser.