Changeset 468


Ignore:
Timestamp:
Dec 9, 2011, 8:33:29 PM (13 years ago)
Author:
aslmd
Message:

UTIL:PYTHON: added support for Ls and sol indexing through option --axtime (mesoscale model files). also a bit of cleaning, especially with info to user, now more compact.

Location:
trunk/UTIL/PYTHON
Files:
4 edited

Legend:

Unmodified
Added
Removed
  • trunk/UTIL/PYTHON/myplot.py

    r467 r468  
    2020
    2121## Author: AS
    22 def getname(var=False,winds=False,anomaly=False):
     22def getname(var=False,var2=False,winds=False,anomaly=False):
    2323    if var and winds:     basename = var + '_UV'
    2424    elif var:             basename = var
     
    2626    else:                 errormess("please set at least winds or var",printvar=nc.variables)
    2727    if anomaly:           basename = 'd' + basename
     28    if var2:              basename = basename + '_' + var2
    2829    return basename
    2930
     
    8485    shape = np.array(input).shape
    8586    #print 'd1,d2,d3,d4: ',d1,d2,d3,d4
    86     print 'IN  REDUCEFIELD dim,shape: ',dimension,shape
    8787    if anomaly: print 'ANOMALY ANOMALY'
    8888    output = input
     
    171171        elif d3 is not None:        output = reduce_zaxis(input[:,d3,:,:],ax=1,yint=yint,vert=alt,indice=d3)
    172172        elif d4 is not None:        output = mean(input[d4,:,:,:],axis=0)
    173     dimension = np.array(output).ndim
    174     shape = np.array(output).shape
    175     print 'OUT REDUCEFIELD dim,shape: ',dimension,shape
     173    dimension2 = np.array(output).ndim
     174    shape2 = np.array(output).shape
     175    print 'REDUCEFIELD dim,shape: ',dimension,shape,' >>> ',dimension2,shape2
    176176    return output, error
    177177
     
    264264
    265265## Author: AS
    266 def getlschar ( namefile ):
     266def getlschar ( namefile, getaxis=False ):
    267267    from netCDF4 import Dataset
    268268    from timestuff import sol2ls
     
    281281        #### strangely enough this does not work for api or ncrcat results!
    282282        zetimestart = getattr(nc, 'START_DATE')
    283         zeday = int(zetime[8]+zetime[9]) - int(zetimestart[8]+zetimestart[9])
    284         if zeday < 0:    lschar=""  ## might have crossed a month... fix soon
    285         else:            lschar="_Ls"+str( int( 10. * sol2ls ( getattr( nc, 'JULDAY' ) + zeday ) ) / 10. )
     283        zeday = int(zetime[8]+zetime[9]) - int(zetimestart[8]+zetimestart[9]) - 1 ###?
     284        if zeday < 0:    dals = -99    ## might have crossed a month... fix soon
     285        else:            dals = int( 10. * sol2ls ( getattr( nc, 'JULDAY' ) + zeday ) ) / 10.
     286        if not getaxis:  lschar = "_Ls"+str(dals)
    286287        ###
    287288        zetime2 = nc.variables['Times'][1]
     
    290291        zehour    = one
    291292        zehourin  = abs ( next - one )
     293        ### A CORRIGER POUR LES SOLS IL FAUT LIRE LE MONTH !!!!
     294        if getaxis:
     295            zelen = len(nc.variables['Times'][:])
     296            yeye = range(zelen) ; lsaxis = range(zelen) ; solaxis = range(zelen) ; ltaxis = range(zelen)
     297            for iii in yeye:
     298               zetime = nc.variables['Times'][iii] ; zetimestart = getattr(nc, 'START_DATE')
     299               zeday = int(zetime[8]+zetime[9]) - int(zetimestart[8]+zetimestart[9]) - 1
     300               ltaxis[iii] = int(zetime[11]+zetime[12]) + int(zetime[14]+zetime[15])/37.
     301               solaxis[iii] = getattr( nc, 'JULDAY' ) + zeday +  ltaxis[iii] / 24.
     302               lsaxis[iii] = sol2ls ( solaxis[iii] )
     303               if ltaxis[iii] < ltaxis[iii-1]: ltaxis[iii] = ltaxis[iii] + 24.
     304               #print ltaxis[iii], solaxis[iii], lsaxis[iii]
     305            lschar = lsaxis ; zehour = solaxis ; zehourin = ltaxis
    292306    else:
    293307        lschar=""
     
    649663    ###
    650664    if zevmin < 0. and min(fieldcalc) > 0.: zevmin = 0.
    651     print "BOUNDS field ", min(fieldcalc), max(fieldcalc)
    652     print "BOUNDS adopted ", zevmin, zevmax
     665    print "BOUNDS field ", min(fieldcalc), max(fieldcalc), " //// adopted", zevmin, zevmax
    653666    return zevmin, zevmax
    654667
     
    10211034   x = array(x)
    10221035   y = array(y)
    1023    print "CHECK: what_I_plot.shape", what_I_plot.shape
    1024    print "CHECK: x.shape, y.shape", x.shape, y.shape
     1036   print "CHECK SHAPE: what_I_plot, x, y", what_I_plot.shape, x.shape, y.shape
    10251037   if len(shape) == 1:
    10261038      if shape[0] != len(x):
  • trunk/UTIL/PYTHON/myscript.py

    r458 r468  
    5353    parser.add_option('--ymin',         action='store',dest='ymin',    type="float",   default=None, help='min value for y-axis in contour-plots [min(yaxis)]')
    5454    parser.add_option('--inverty',      action='store_true',dest='inverty',            default=False,help='force decreasing values along y-axis (e.g. p-levels)')
    55     parser.add_option('--logy',         action='store_true',dest='logy',               default=False,help='set y-axis to logarithmic.')   
     55    parser.add_option('--logy',         action='store_true',dest='logy',               default=False,help='set y-axis to logarithmic')   
     56    parser.add_option('--axtime',       action='store',dest='axtime',  type="string",  default=None, help='choose "ls" or "sol" for time reference')
    5657
    5758    ### OPERATIONS BETWEEN FILES
  • trunk/UTIL/PYTHON/planetoplot.py

    r464 r468  
    5757           mquality=False,\
    5858           trans=1,\
    59            zarea=None):
     59           zarea=None,\
     60           axtime=None):
    6061
    6162
     
    7273    from mymath import deg,max,min,mean,get_tsat,writeascii,fig2data,fig2img
    7374    import matplotlib as mpl
    74     from matplotlib.pyplot import contour,contourf, subplot, figure, rcParams, savefig, colorbar, pcolor, show, plot, clabel, title, close, legend
     75    from matplotlib.pyplot import contour,contourf, subplot, figure, rcParams, savefig, colorbar, pcolor, show, plot, clabel, title, close, legend, xlabel
    7576    from matplotlib.cm import get_cmap
    7677    import numpy as np
     
    113114    ### Loop over the files + vars initially separated by commas to be plotted on the same figure ###
    114115    #################################################################################################
    115     k = 0 ; firstfile = True
     116    k = 0 ; firstfile = True ; count = 0
    116117    for nnn in range(len(namefiles)):
    117118     for vvv in range(len(var)):
    118119
    119       print "********** LOOP..... THIS IS SUBPLOT NUMBER.....",k
    120 
    121120      ######################
    122121      ### Load NETCDF object
    123       namefile = namefiles[nnn] ; print "********** THE NAMEFILE IS....", namefile
     122      namefile = namefiles[nnn]
    124123      nc  = Dataset(namefile)
    125124
     
    134133      ### ... VAR
    135134      varname=var[vvv]
    136       print "********** THE VAR IS....",varname, var2
    137135      if varname not in nc.variables: varname = False
    138136      ### ... WINDS
     
    153151          else:                           errormess("no time axis found.")
    154152          vert = nc.variables["altitude"][:]
     153          if axtime in ["ls","sol"]:   errormess("not supported. should not be too difficult though.")
    155154      elif typefile in ['meso','mesoapi','geo','mesoideal']:
    156155          ### the following lines are kind of dirty... not possible to ask for several lats and lons
    157           if vlon is not None or vlat is not None:   indices = bidimfind(lon2d,lat2d,vlon,vlat) ; print '********** INDICES: ', indices
     156          if vlon is not None or vlat is not None:   indices = bidimfind(lon2d,lat2d,vlon,vlat)
    158157          if slon is not None: slon[0][0] = indices[0] ; slon[0][1] = indices[0]
    159158          if slat is not None: slat[0][0] = indices[1] ; slat[0][1] = indices[1]
     
    169168          else:                 londim='WEST-EAST_PATCH_END_UNSTAG'
    170169          lon = np.arange(0,getattr(nc,londim),1) ; lat = np.arange(0,getattr(nc,latdim),1)
    171           if "Times" in nc.variables:time = np.arange(0,len(nc.variables["Times"]),1)
    172           elif "Time" in nc.variables:time = np.arange(0,len(nc.variables["Time"]),1)
     170          ###
     171          if axtime in ["ls","sol"]:
     172              lstab, soltab, lttab = getlschar ( namefile, getaxis = True )
     173              if axtime == "ls":      time = lstab
     174              elif axtime == "sol":   time = soltab
     175          else:
     176              if "Times" in nc.variables:   time = count + np.arange(0,len(nc.variables["Times"]),1)
     177              elif "Time" in nc.variables:  time = count + np.arange(0,len(nc.variables["Time"]),1)
     178              count = time[-1] + 1  ## so that a cat is possible with simple subscripts
     179          ###
    173180          if typefile in ['geo']:   vert = [0.] ; stime = readslices(str(0))
    174181          else:
     
    209216      ##### GENERAL STUFF HERE
    210217          all_var[k] = getfield(nc,varname)
    211       print "********** all_var[k].shape", all_var[k].shape
    212       k += 1
    213       firstfile = False
     218     
     219      print "**** GOT SUBDATA:",k," NAMEFILE:",namefile," VAR:",varname, var2 ; k += 1 ; firstfile = False
    214220      #### End of for namefile in namefiles
    215221
     
    217223    ### Operation on files
    218224    if ope is not None:
    219         print ope
     225        print "********** OPERATION: ",ope
    220226        if "var" not in ope:
    221227             if len(var) > 1: errormess("for this operation... please set only one var !")
     
    228234                all_varname[k+1] = all_varname[k] ; all_time[k+1] = all_time[k] ; all_namefile[k+1] = all_namefile[k] ; numplot = numplot+2
    229235             elif ope in ["cat"]:
    230                 tab = all_var[0];k = 1
     236                tabtime = all_time[0];tab = all_var[0];k = 1
    231237                if var2: tab2 = all_var2[0]
    232238                while k != len(namefiles):
    233239                    if var2: tab2 = np.append(tab2,all_var2[k],axis=0)
    234                     tab = np.append(tab,all_var[k],axis=0) ; k += 1
    235                 all_time[0] = np.arange(0,len(tab),1) ### AS: time reference is too simplistic, should be better
    236                 all_var[0] = np.array(tab) ; numplot = 1
     240                    tabtime = np.append(tabtime,all_time[k]) ; tab = np.append(tab,all_var[k],axis=0) ; k += 1
     241                #all_time[0] = np.arange(0,len(tab),1) ### AS: time reference is too simplistic, should be better
     242                all_time[0] = np.array(tabtime) ; all_var[0] = np.array(tab) ; numplot = 1
    237243                if var2: all_var2[0] = np.array(tab2)
    238244             else: errormess(ope+" : non-implemented operation. Check pp.py --help")
     
    284290       ltst = None
    285291       if typefile in ['mesoapi','meso'] and indextime is not None:  ltst = localtime ( interv[0]+indextime*interv[1], 0.5*(wlon[0]+wlon[1]) ) 
    286        print "********** index lon, lat, vert, time ",indexlon,indexlat,indexvert,indextime
     292       print "********** INDEX LON:",indexlon," LAT:",indexlat," VERT:",indexvert," TIME:",indextime
    287293       ####################################################################
    288294       error = False
     
    380386                        if colorb != 'nobar':       
    381387                            if (fileref is not None) and (index_f is numplot-1):   daformat = "%.3f"
     388                            elif mult != 1:                                        daformat = "%.1f"
    382389                            else:                                                  daformat = fmtvar(fvar.upper())
    383390                            colorbar( fraction=0.05,pad=0.03,format=daformat,\
    384                                       ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,20])),extend='neither',spacing='proportional' )
     391                                      ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional' )
    385392                        if winds:
    386393                            if typefile in ['mesoapi','meso']:
     
    443450                 if indextime is not None: lbl = lbl + " it" + str(indextime)
    444451
    445                  if indexvert is not None:    plot(x,what_I_plot,label=lbl)  ## regular plot
    446                  else:                        plot(what_I_plot,x,label=lbl)  ## vertical profile
    447                  legend(loc='best')
     452                 if indexvert is not None or indextime is None:    plot(x,what_I_plot,label=lbl)  ## regular plot
     453                 else:                                             plot(what_I_plot,x,label=lbl)  ## vertical profile
     454                 if nplot > 1: legend(loc='best')
     455                 if indextime is None and axtime is not None:      xlabel(axtime.upper()) ## define the right label
    448456                 if save == 'txt':  writeascii(np.transpose(what_I_plot),'profile'+str(nplot)+'.txt')
    449457
     
    456464
    457465       ### Next subplot
    458        basename = getname(var=varname,winds=winds,anomaly=anomaly)
     466       basename = getname(var=varname,var2=var2,winds=winds,anomaly=anomaly)
    459467       if len(what_I_plot.shape) > 3:
    460468           basename = basename + getstralt(nc,level)
     
    464472            if slat is not None: basename = basename + "_lat_" + str(int(lat2d[indices[1],indices[0]]))
    465473            plottitle = basename
    466             if addchar:   [addchar,gogol,gogol2] = getlschar ( all_namefile[index_f] )  ;  plottitle = plottitle + addchar
     474            ### dans le nouveau systeme time=ls,sol,lt cette ligne pourrait ne servir a rien (ou deplacer au dessus)
     475            if addchar and indextime is not None:   [addchar,gogol,gogol2] = getlschar ( all_namefile[index_f] )  ;  plottitle = plottitle + addchar
    467476            if ltst is not None and ( (mapmode == 0) or (proj in ["lcc","laea","merc","nsper"]) ):  plottitle = plottitle + "_LT" + str(ltst)
    468477       else:
     
    472481                else:                        plottitle = basename+' '+namefiles[0]#index_f]
    473482            else:                            plottitle = basename+' '+namefiles[0]#index_f]
    474        if mult != 1:                         plottitle = str(mult) + "*" + plottitle
     483       if mult != 1:                         plottitle = '{:.0e}'.format(mult) + "*" + plottitle
    475484       if zetitle != "fill":                 
    476485          plottitle = zetitle
  • trunk/UTIL/PYTHON/pp.py

    r464 r468  
    141141                invert_y=opt.inverty,xaxis=zexaxis,yaxis=zeyaxis,ylog=opt.logy,yintegral=opt.column,\
    142142                blat=opt.blat,blon=opt.blon,tsat=opt.tsat,flagnolow=opt.nolow,\
    143                 mrate=opt.rate,mquality=opt.quality,trans=opt.trans,zarea=opt.area)
     143                mrate=opt.rate,mquality=opt.quality,trans=opt.trans,zarea=opt.area,axtime=opt.axtime)
    144144        print 'DONE: '+name
    145145        system("rm -f to_be_erased")
     
    156156    f.write(command)
    157157
    158     print "********** OPTIONS: ", opt
     158    #print "********** OPTIONS: ", opt
    159159    print "********************************************************** END"
Note: See TracChangeset for help on using the changeset viewer.