Changeset 876


Ignore:
Timestamp:
Feb 11, 2013, 2:22:32 PM (12 years ago)
Author:
aslmd
Message:

UTIL PYTHON. Added a speedy mode for large file ! Not all options are available for the moment. Also better access to planetoplot by not preloading all functions (this is better for lisibility too).

Location:
trunk/UTIL/PYTHON
Files:
4 edited

Legend:

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

    r874 r876  
     1
     2import numpy as np
     3import netCDF4
     4
    15## Author: AS
    26def errormess(text,printvar=None):
     
    812## Author: AS
    913def adjust_length (tab, zelen):
    10     from numpy import ones
    1114    if tab is None:
    12         outtab = ones(zelen) * -999999
     15        outtab = np.ones(zelen) * -999999
    1316    else:
    1417        if zelen != len(tab):
    1518            print "not enough or too much values... setting same values all variables"
    16             outtab = ones(zelen) * tab[0]
     19            outtab = np.ones(zelen) * tab[0]
    1720        else:
    1821            outtab = tab
     
    3134## Author: AS + AC
    3235def localtime(time,lon,namefile): # lon is the mean longitude of the plot, not of the domain. central lon of domain is taken from cen_lon
    33     import numpy as np
    34     from netCDF4 import Dataset
    3536    ## THIS IS FOR MESOSCALE
    36     nc = Dataset(namefile)
     37    nc = netCDF4.Dataset(namefile)
    3738    ## get start date and intervals
    3839    dt_hour=1. ; start=0.
     
    9394
    9495## Author: AS
     96def getfieldred (nc,var,indexlon,indexlat,indexvert,indextime):
     97    dimension = len(nc.variables[var].dimensions)
     98    ## this allows to get much faster and use much less memory esp. with large datasets
     99    if dimension == 2:    field = nc.variables[var][indextime,indexlon]
     100    elif dimension == 3:  field = nc.variables[var][indextime,indexlat,indexlon]
     101    elif dimension == 4:  field = nc.variables[var][indextime,indexvert,indexlat,indexlon]
     102    elif dimension == 1:  field = nc.variables[var][indextime]
     103    return field
     104
     105## Author: AS
    95106def getfield (nc,var):
     107    dimension = len(nc.variables[var].dimensions)
    96108    ## this allows to get much faster (than simply referring to nc.variables[var])
    97     import numpy as np
    98     dimension = len(nc.variables[var].dimensions)
    99     #print "   Opening variable with", dimension, "dimensions ..."
     109    print "   Opening variable",var," with", dimension, "dimensions ..."
    100110    if dimension == 2:    field = nc.variables[var][:,:]
    101111    elif dimension == 3:  field = nc.variables[var][:,:,:]
     
    142152# The corresponding variable to call is UV or uvmet (to use api)
    143153def windamplitude (nc,mode):
    144     import numpy as np
    145154    varinfile = nc.variables.keys()
    146155    if "U" in varinfile: zu=getfield(nc,'U')
     
    177186# this only requires co2col so that you can concat.nc at low cost
    178187def enrichment_factor(nc,lon,lat,time):
    179     import numpy as np
    180188    from myplot import reducefield
    181189    varinfile = nc.variables.keys()
     
    213221# The corresponding variable to call is SLOPEXY
    214222def slopeamplitude (nc):
    215     import numpy as np
    216223    varinfile = nc.variables.keys()
    217224    if "slopex" in varinfile: zu=getfield(nc,'slopex')
     
    233240# The corresponding variable to call is DELTAT
    234241def deltat0t1 (nc):
    235     import numpy as np
    236242    varinfile = nc.variables.keys()
    237243    if "tsurf" in varinfile: zu=getfield(nc,'tsurf')
     
    251257    ### it would be actually better to name d4 d3 d2 d1 as t z y x
    252258    ### ... note, anomaly is only computed over d1 and d2 for the moment
    253     import numpy as np
    254259    from mymath import max,mean,min,sum,getmask
    255260    csmooth = 12 ## a fair amount of grid points (too high results in high computation time)
     
    444449    from mymath import max,mean
    445450    from scipy import integrate
    446     import numpy as np
    447451    if yint and vert is not None and indice is not None:
    448452       if type(input).__name__=='MaskedArray':
     
    483487        rcParams['font.size'] = int( rcParams['font.size'] * 2. / 3. )
    484488    elif numplot <= 6:
    485         subv = 2
    486         subh = 3
    487         #fig.subplots_adjust(wspace = 0.4, hspace = 0.0)
    488         fig.subplots_adjust(wspace = 0.5, hspace = 0.3)
     489        subv = 3#2
     490        subh = 2#3
     491        ##fig.subplots_adjust(wspace = 0.4, hspace = 0.0)
     492        #fig.subplots_adjust(wspace = 0.5, hspace = 0.3)
     493        fig.subplots_adjust(wspace = 0.3, hspace = 0.5)
    489494        rcParams['font.size'] = int( rcParams['font.size'] * 1. / 2. )
    490495    elif numplot <= 8:
     
    531536## Author: AS
    532537def getlschar ( namefile, getaxis=False ):
    533     from netCDF4 import Dataset
    534538    from timestuff import sol2ls
    535     from numpy import array
    536539    from string import rstrip
    537540    import os as daos
     
    542545      namefile = namefiletest
    543546      #### we assume that wrfout is next to wrfout_z and wrfout_zabg
    544       nc  = Dataset(namefile)
     547      nc  = netCDF4.Dataset(namefile)
    545548      zetime = None
    546549      days_in_month = [61, 66, 66, 65, 60, 54, 50, 46, 47, 47, 51, 56]
     
    548551      if 'Times' in nc.variables:
    549552        zetime = nc.variables['Times'][0]
    550         shape = array(nc.variables['Times']).shape
     553        shape = np.array(nc.variables['Times']).shape
    551554        if shape[0] < 2: zetime = None
    552555    if zetime is not None \
     
    621624## Author: AS
    622625def polarinterv (lon2d,lat2d):
    623     import numpy as np
    624626    wlon = [np.min(lon2d),np.max(lon2d)]
    625627    ind = np.array(lat2d).shape[0] / 2  ## to get a good boundlat and to get the pole
     
    629631## Author: AS
    630632def simplinterv (lon2d,lat2d):
    631     import numpy as np
    632633    return [[np.min(lon2d),np.max(lon2d)],[np.min(lat2d),np.max(lat2d)]]
    633634
     
    679680## Author: AS + AC
    680681def getcoorddef ( nc ):   
    681     import numpy as np
    682682    ## getcoord2d for predefined types
    683683    typefile = whatkindfile(nc)
     
    712712## Author: AS
    713713def getcoord2d (nc,nlat='XLAT',nlon='XLONG',is1d=False):
    714     import numpy as np
    715714    if nlon == "nothing" or nlat == "nothing":
    716715        print "NO LAT LON FIELDS. I AM TRYING MY BEST. I ASSUME GLOBAL FIELD."
     
    740739## FROM COOKBOOK http://www.scipy.org/Cookbook/SignalSmooth
    741740def smooth1d(x,window_len=11,window='hanning'):
    742     import numpy
    743741    """smooth the data using a window with requested size.
    744742    This method is based on the convolution of a scaled window with the signal.
     
    762760    TODO: the window parameter could be the window itself if an array instead of a string   
    763761    """
    764     x = numpy.array(x)
     762    x = np.array(x)
    765763    if x.ndim != 1:
    766764        raise ValueError, "smooth only accepts 1 dimension arrays."
     
    771769    if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
    772770        raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'"
    773     s=numpy.r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]]
     771    s=np.r_[x[window_len-1:0:-1],x,x[-1:-window_len:-1]]
    774772    #print(len(s))
    775773    if window == 'flat': #moving average
    776         w=numpy.ones(window_len,'d')
     774        w=np.ones(window_len,'d')
    777775    else:
    778776        w=eval('numpy.'+window+'(window_len)')
    779     y=numpy.convolve(w/w.sum(),s,mode='valid')
     777    y=np.convolve(w/w.sum(),s,mode='valid')
    780778    return y
    781779
     
    789787## FROM COOKBOOK http://www.scipy.org/Cookbook/SignalSmooth
    790788def gauss_kern(size, sizey=None):
    791         import numpy as np
    792789        # Returns a normalized 2D gauss kernel array for convolutions
    793790        size = int(size)
     
    832829    ## factor regle toutes les longueurs (dont la reference). l'AUGMENTER pour raccourcir les vecteurs.
    833830    import  matplotlib.pyplot               as plt
    834     import  numpy                           as np
    835831    #posx = np.min(x) - np.std(x) / 10.
    836832    #posy = np.min(y) - np.std(y) / 10.
     
    874870def define_proj (char,wlon,wlat,back=None,blat=None,blon=None):
    875871    from    mpl_toolkits.basemap            import Basemap
    876     import  numpy                           as np
    877872    import  matplotlib                      as mpl
    878873    from mymath import max
     
    978973## Author: AS
    979974def calculate_bounds(field,vmin=None,vmax=None):
    980     import numpy as np
    981975    from mymath import max,min,mean
    982976    ind = np.where(field < 9e+35)
     
    10221016## Author : AC
    10231017def hole_bounds(what_I_plot,zevmin,zevmax):
    1024     import numpy as np
    10251018    zi=0
    10261019    for i in what_I_plot:
     
    12641257## Author: TN
    12651258def separatenames (name):
    1266   from numpy import concatenate
    12671259  # look for comas in the input name to separate different names (files, variables,etc ..)
    12681260  if name is None:
     
    12791271      else:
    12801272        name1 = currentname[0:indexvir]
    1281       names = concatenate((names,[name1]))
     1273      names = np.concatenate((names,[name1]))
    12821274      currentname = currentname[indexvir+1:len(currentname)]
    12831275  return names
     
    12861278## Author: TN
    12871279def readslices(saxis):
    1288   from numpy import empty
    12891280  if saxis == None:
    12901281     zesaxis = None
    12911282  else:
    1292      zesaxis = empty((len(saxis),2))
     1283     zesaxis = np.empty((len(saxis),2))
    12931284     for i in range(len(saxis)):
    12941285        a = separatenames(saxis[i])
     
    13041295def readdata(data,datatype,coord1,coord2):
    13051296## Read sparse data
    1306   from numpy import empty
    13071297  if datatype == 'txt':
    13081298     if len(data[coord1].shape) == 1:
     
    13201310## Author: AS
    13211311def bidimfind(lon2d,lat2d,vlon,vlat,file=None):
    1322    import numpy as np
    13231312   import matplotlib.pyplot as mpl
    13241313   if vlat is None:    array = (lon2d - vlon)**2
     
    13421331# input  : all the desired slices and the good index
    13431332# output : all indexes to be taken into account for reducing field
    1344   import numpy as np
    13451333  if ( np.array(axis).ndim == 2):
    13461334      axis = axis[:,0]
     
    13641352# x axis priority: 1/time 2/lon 3/lat 4/vertical
    13651353# To be improved !!!...
    1366    from numpy import array,swapaxes
    13671354   x = None
    13681355   y = None
    13691356   count = 0
    1370    what_I_plot = array(what_I_plot)
     1357   what_I_plot = np.array(what_I_plot)
    13711358   shape = what_I_plot.shape
    13721359   if indextime is None and len(time) > 1:
     
    13941381         else: y = vert
    13951382         count = count+1
    1396    x = array(x)
    1397    y = array(y)
     1383   x = np.array(x)
     1384   y = np.array(y)
    13981385   print "CHECK SHAPE: what_I_plot, x, y", what_I_plot.shape, x.shape, y.shape
    13991386   if len(shape) == 1:
     
    14021389   elif len(shape) == 2:
    14031390       if shape[1] == len(y) and shape[0] == len(x) and shape[0] != shape[1]:
    1404            print "INFO: swapaxes: ",what_I_plot.shape,shape ; what_I_plot = swapaxes(what_I_plot,0,1)
     1391           print "INFO: swapaxes: ",what_I_plot.shape,shape ; what_I_plot = np.swapaxes(what_I_plot,0,1)
    14051392       else:
    14061393           if shape[0] != len(y):       print "WARNING: shape[0] != len(y). Correcting." ; what_I_plot = what_I_plot[0:len(y),:]
     
    14451432               vecx=None,vecy=None,stride=2 ):
    14461433    ### an easy way to map a field over lat/lon grid
    1447     import numpy as np
    14481434    import matplotlib.pyplot as mpl
    14491435    from matplotlib.cm import get_cmap
     
    14961482      specificname_gcm = ['enfact']
    14971483
     1484      zncvar = znc.variables
     1485
    14981486      ## Check for variable in file:
    14991487      if mode == 'check':     
    15001488          varname = zvarname
    1501           varinfile=znc.variables.keys()
    1502           logical_novarname = zvarname not in znc.variables
     1489          varinfile=zncvar.keys()
     1490          logical_novarname = zvarname not in zncvar
    15031491          logical_nospecificname_meso = not ((ztypefile in ['meso']) and (zvarname in specificname_meso))
    15041492          logical_nospecificname_gcm = not ((ztypefile in ['gcm']) and (zvarname in specificname_gcm))
     
    15191507              all_var=get_tsat(yalt,tinput,zlon=ylon,zlat=ylat,zalt=yalt,ztime=ytime)
    15201508          ### ----------- 2. wind amplitude
    1521           elif ((zvarname in ['UV','uv','uvmet']) and (ztypefile in ['meso']) and (zvarname not in znc.variables)):
     1509          elif ((zvarname in ['UV','uv','uvmet']) and (ztypefile in ['meso']) and (zvarname not in zncvar)):
    15221510              all_var=windamplitude(znc,'amplitude')
    1523           elif ((zvarname in ['hodograph','hodograph_2']) and (ztypefile in ['meso']) and (zvarname not in znc.variables)):
     1511          elif ((zvarname in ['hodograph','hodograph_2']) and (ztypefile in ['meso']) and (zvarname not in zncvar)):
    15241512              plot_x, plot_y = windamplitude(znc,zvarname)
    15251513              if plot_x is not None: all_var=plot_x # dummy
    15261514              else: all_var=plot_y ; plot_x = None ; plot_y = None # Hodograph type 2 is not 'xy' mode
    1527           elif ((zvarname in ['slopexy','SLOPEXY']) and (ztypefile in ['meso']) and (zvarname not in znc.variables)):
     1515          elif ((zvarname in ['slopexy','SLOPEXY']) and (ztypefile in ['meso']) and (zvarname not in zncvar)):
    15281516              all_var=slopeamplitude(znc)
    15291517          ### ------------ 3. Near surface instability
    1530           elif ((zvarname in ['DELTAT','deltat']) and (ztypefile in ['meso']) and (zvarname not in znc.variables)):
     1518          elif ((zvarname in ['DELTAT','deltat']) and (ztypefile in ['meso']) and (zvarname not in zncvar)):
    15311519              all_var=deltat0t1(znc)
    15321520          ### ------------ 4. Enrichment factor
     
    15341522              all_var=enrichment_factor(znc,ylon,ylat,ytime)
    15351523          ### ------------ 5. teta -> temp
    1536           elif ((ztypefile in ['meso']) and (zvarname in ['tk']) and ('tk' not in znc.variables.keys())):
     1524          elif ((ztypefile in ['meso']) and (zvarname in ['tk']) and ('tk' not in zncvar.keys())):
    15371525              all_var=teta_to_tk(znc)
    15381526          else:
     
    15491537# (which is not efficient but it is still ok) and then, make the average (if the user wants to)
    15501538def spectrum(var,time,vert,lat,lon):
    1551     import numpy as np
    15521539    fft=np.fft.fft(var,axis=1)
    15531540    N=len(vert)
     
    15651552# Computes temperature from potential temperature for mesoscale files, without the need to use API, i.e. using natural vertical grid
    15661553def teta_to_tk(nc):
    1567     import numpy as np
    15681554    varinfile = nc.variables.keys()
    15691555    p0=610.
     
    15881574# 6/ in this slab, find the point at which the surface pressure is minimum
    15891575def find_devil(nc,indextime):
    1590     import numpy as np
    15911576    from scipy import ndimage
    15921577    from mymath import array2image,image2array
  • trunk/UTIL/PYTHON/myscript.py

    r865 r876  
    33    ### I/O
    44    parser.add_option('-f', '--file',   action='append',dest='file',     type="string",  default=None,  help='[NEEDED] filename. Append: different figures. Comma-separated: same figure (+ possible --operation). Regex OK: use -f "foo*" DONT FORGET QUOTES "" !!!!')
     5    parser.add_option('-L', '--large',  action='store_true',dest='monster',              default=False, help='speedy version for large files (EXPERIMENTAL)')
    56    parser.add_option('--seevar',       action='store_true',dest='seevar',               default=False, help='display the list of variables in the file')
    67    parser.add_option('-t', '--target', action='store',dest='tgt',       type="string",  default=None,  help='destination folder')
  • trunk/UTIL/PYTHON/planetoplot.py

    r874 r876  
    7878           streamflag=False,\
    7979           nocolorb=False,\
    80            analysis=None):
     80           analysis=None,\
     81           monster=False):
    8182
    8283    ####################################################################################################################
     
    8586    #################################
    8687    ### Load librairies and functions
    87     from netCDF4 import Dataset
    88     from myplot import getcoord2d,define_proj,makeplotres,simplinterv,vectorfield,ptitle,latinterv,getproj,wrfinterv,dumpbdy,\
    89                        fmtvar,definecolorvec,defcolorb,getprefix,putpoints,calculate_bounds,errormess,definesubplot,\
    90                        zoomset,getcoorddef,getwinddef,whatkindfile,reducefield,bounds,getstralt,getfield,smooth,nolow,\
    91                        getname,localtime,check_localtime,polarinterv,getsindex,define_axis,determineplot,readslices,bidimfind,getlschar,hole_bounds,\
    92                        getdimfromvar,select_getfield,find_devil
    93     from mymath import deg,max,min,mean,writeascii,fig2data,fig2img
     88    import netCDF4
     89
    9490    import matplotlib as mpl
    95     from matplotlib.pyplot import contour,contourf,hist, text,subplot, figure, rcParams, savefig, colorbar, \
    96                                   pcolor, show, plot, clabel, title, close, legend, xlabel, axis, ylabel, \
    97                                   subplots_adjust, axes, clabel
    98     from matplotlib.cm import get_cmap
     91    import matplotlib.pyplot
     92    import matplotlib.cm
    9993    from mpl_toolkits.basemap import cm
     94    if mrate is not None: from videosink import VideoSink
     95
    10096    import numpy as np
    10197    from numpy.core.defchararray import find
    102     from scipy.stats import gaussian_kde,describe
    103     from videosink import VideoSink
     98    import scipy
     99    if analysis in ['laplace']: import scipy.ndimage.laplace as laplace
     100
     101    import itertools
     102    import os
     103
     104    import myplot
     105    from mymath import deg,max,min,mean,writeascii,fig2data,fig2img
    104106    from times import sol2ls
    105     import subprocess
    106107    #from singlet import singlet
    107     from itertools import cycle
    108     import os
    109     from scipy import ndimage
    110108
    111109
     
    117115    print "********** WELCOME TO PLANETOPLOT **********"
    118116    print "********************************************"
     117    if monster:
     118        print "********* SPEED MODE. EXPERIMENTAL. ********"
     119        print "********************************************"
    119120### we ensure namefiles and var are arrays
    120121    if not isinstance(namefiles, np.ndarray): namefiles = [namefiles]
     
    132133    if trycol: clb = ["Greys","Blues","YlOrRd","jet","spectral","hot","RdBu","RdYlBu","Paired"] ; zetitle = clb ; var = [var[0]]*9
    133134### we avoid specific cases not yet implemented
    134     if mrate is not None and len(var) > 1: errormess("multivar not allowed in movies. should be fixed soon!")
     135    if mrate is not None and len(var) > 1: myplot.errormess("multivar not allowed in movies. should be fixed soon!")
    135136### we prepare number of plot fields [zelen] and number of plot instances [numplot] according to user choices
    136137### --> we support multifile and multivar plots : files + vars separated by commas are on the same figure
    137     nlon, nlat, nvert, ntime, mapmode, nslices = determineplot(slon, slat, svert, stime, redope)
     138    nlon, nlat, nvert, ntime, mapmode, nslices = myplot.determineplot(slon, slat, svert, stime, redope)
    138139    zelen = len(namefiles)*len(var)
     140    if (nslices > 1 and monster): myplot.errormess("multislice + monster not supported yet. to be done soon")
    139141### we have a special mode obtained by -p noproj in which lat/lon plots are just flat 2D plots
    140142    if proj == "noproj": mapmode = 0
     
    157159### LOOP OVER PLOT FIELDS ###
    158160#############################
    159     
     161   
    160162    for nnn in range(len(namefiles)):
    161163     for vvv in range(len(var)):
     
    163165    ### we load each NETCDF objects in namefiles
    164166      namefile = namefiles[nnn]
    165       nc  = Dataset(namefile)
     167      nc  = netCDF4.Dataset(namefile)
    166168    ### we explore the variables in the file
    167169      varinfile = nc.variables.keys()
    168170      if seevar: print varinfile ; exit()
    169171    ### we define the type of file we have (gcm, meso, etc...)
    170       typefile = whatkindfile(nc)
     172      typefile = myplot.whatkindfile(nc)
    171173      if firstfile:                 typefile0 = typefile
    172       elif typefile != typefile0:   errormess("Not the same kind of files !", [typefile0, typefile])
     174      elif typefile != typefile0:   myplot.errormess("Not the same kind of files !", [typefile0, typefile])
    173175    ### we care for input file being 1D simulations
    174176      is1d=999
    175       if "longitude" in nc.dimensions and "latitude" in nc.dimensions: is1d = len(nc.variables["longitude"][:])*len(nc.variables["latitude"][:])
    176       elif "lon" in nc.dimensions and "lat" in nc.dimensions: is1d = len(nc.variables["lon"][:])*len(nc.variables["lat"][:])
     177      if "longitude" in nc.dimensions and "latitude" in nc.dimensions: is1d = len(nc.dimensions["longitude"])*len(nc.dimensions["latitude"])
     178      elif "lon" in nc.dimensions and "lat" in nc.dimensions: is1d = len(nc.dimensions["lon"])*len(nc.dimensions["lat"])
    177179      if typefile in ['gcm','earthgcm'] and is1d == 1:       mapmode=0 ; winds=False
    178180    ### we create default vert and time prescriptions if not here in case mapping mode is on (lat/lon maps)
    179181      if redope is None and mapmode == 1:
    180           if svert is None:  svert = readslices(str(level)) ; nvert=1
     182          if svert is None:  svert = myplot.readslices(str(level)) ; nvert=1
    181183          if stime is None and mrate is None:
    182              stime = readslices(str(0)) ; ntime=1 ## this is a default choice
     184             stime = myplot.readslices(str(0)) ; ntime=1 ## this is a default choice
    183185             print "WELL... nothing about time axis. I took default: first time reference stored in file."
    184186    ### we get the names of variables to be read. in case only one available, we choose this one.
    185187    ### (we take out of the test specific names e.g. UV is not in the file but used to ask a wind speed computation)
    186       varname = select_getfield(zvarname=var[vvv],znc=nc,ztypefile=typefile,mode='check')
     188      varname = myplot.select_getfield(zvarname=var[vvv],znc=nc,ztypefile=typefile,mode='check')
    187189    ### we get the names of wind variables to be read (if any)
    188190      if winds:                                                   
    189          [uchar,vchar,metwind] = getwinddef(nc)             
     191         [uchar,vchar,metwind] = myplot.getwinddef(nc)             
    190192         if uchar == 'not found': winds = False
    191193    ### we tell the user that either no var or no wind is not acceptable
    192       if not varname and not winds: errormess("please set at least winds or var",printvar=nc.variables)
     194      if not varname and not winds: myplot.errormess("please set at least winds or var",printvar=nc.variables)
    193195    ### we get the coordinates lat/lon to be used
    194       [lon2d,lat2d] = getcoorddef(nc)
     196      [lon2d,lat2d] = myplot.getcoorddef(nc)
    195197    ### we get an adapted map projection if none is provided by the user
    196       if proj == None:   proj = getproj(nc)   
     198      if proj == None:   proj = myplot.getproj(nc)   
    197199    ### we define plot boundaries given projection or user choices
    198200      if firstfile:
    199          if proj in ["npstere","spstere"]: [wlon,wlat] = polarinterv(lon2d,lat2d)
    200          elif proj in ["lcc","laea"]:      [wlon,wlat] = wrfinterv(lon2d,lat2d)
    201          else:                             [wlon,wlat] = simplinterv(lon2d,lat2d)
    202          if zoom:                          [wlon,wlat] = zoomset(wlon,wlat,zoom)
    203          elif zarea is not None:           [wlon,wlat] = latinterv(area=zarea)
     201         if proj in ["npstere","spstere"]: [wlon,wlat] = myplot.polarinterv(lon2d,lat2d)
     202         elif proj in ["lcc","laea"]:      [wlon,wlat] = myplot.wrfinterv(lon2d,lat2d)
     203         else:                             [wlon,wlat] = myplot.simplinterv(lon2d,lat2d)
     204         if zoom:                          [wlon,wlat] = myplot.zoomset(wlon,wlat,zoom)
     205         elif zarea is not None:           [wlon,wlat] = myplot.latinterv(area=zarea)
    204206
    205207#############################################################
     
    228230          ### --> add a line here if your reference is not present
    229231          else:
    230               dadim = getdimfromvar(nc) ; print "No altitude found. Try to build a simple axis.",dadim
     232              dadim = myplot.getdimfromvar(nc) ; print "No altitude found. Try to build a simple axis.",dadim
    231233              if   len(dadim) == 4:  print "-- 4D field. Assume z is dim 2." ; vert = np.arange(dadim[-3])
    232234              elif len(dadim) == 3:  print "-- 3D field. Assume z is dim 1." ; vert = [0.]
    233235              else:                  vert = [0.]
    234236      ### we define time vector. either it is referenced or it is guessed based on last variable's dimensions.
    235           if "Time" in nc.variables:            time = nc.variables["Time"][:]
    236           elif "time_counter" in nc.variables:  time = nc.variables["time_counter"][:]/86400. #### convert from s to days
    237           elif "time" in nc.variables:          time = nc.variables["time"][:]
     237          if "Time" in nc.variables:            letime = "Time"
     238          elif "time_counter" in nc.variables:  letime = "time_counter"
     239          elif "time" in nc.variables:          letime = "time"
    238240          ### --> add a line here if your reference is not present
     241          else:                                 letime = None
     242          if letime is not None:         
     243              if monster:
     244                  ### very long simulation... we just retrieve 3 values for time
     245                  timelength = len(nc.dimensions[letime])
     246                  dafirst = nc.variables[letime][0]
     247                  dalast = nc.variables[letime][timelength-1]
     248                  step = nc.variables[letime][1] - dafirst
     249                  time = np.arange(dafirst,dalast,step)
     250              else:
     251                  ### if the time record is not too long, what follows is pretty quick
     252                  time = nc.variables[letime][:]
    239253          else:
    240254              print "No time found. Try to build a simple axis. Assume t is dim 1."
    241               dadim = getdimfromvar(nc)
     255              dadim = myplot.getdimfromvar(nc)
    242256              if   len(dadim) == 4:  time = np.arange(dadim[-4])
    243257              elif len(dadim) == 3:  time = np.arange(dadim[-3])
    244               else:                  time = [0.] #errormess("no time axis found.")
     258              else:                  time = [0.] #myplot.errormess("no time axis found.")
     259          ### (SPECIFIC?)
     260          if "time_counter" in nc.variables:  time = time / 86400. #### convert from s to days
    245261          ### (SPECIFIC. convert to Ls for Martian GCM files.)
    246262          if axtime in ["ls"]:
     
    256272          ### (simply ask for subscript)
    257273          if axtime in ["ind"]:
    258               dadim = getdimfromvar(nc)
     274              dadim = myplot.getdimfromvar(nc)
    259275              if   len(dadim) == 4:  time = np.arange(dadim[-4])
    260276              elif len(dadim) == 3:  time = np.arange(dadim[-3])
     
    280296                 if slon is not None:  vlon = slon[0][iii]  ### note: slon[:][0] does not work
    281297                 if slat is not None:  vlat = slat[0][jjj]  ### note: slon[:][0] does not work
    282                  indices[iii,jjj,:] = bidimfind(lon2d,lat2d,vlon,vlat,file=iwantawhereplot) 
     298                 indices[iii,jjj,:] = myplot.bidimfind(lon2d,lat2d,vlon,vlat,file=iwantawhereplot) 
    283299                 lonp,latp = ( lon2d[indices[iii,jjj,0],indices[iii,jjj,1]] , lat2d[indices[iii,jjj,0],indices[iii,jjj,1]] )
    284300              ### possible bug here if several --lat
     
    290306          ### we get rid of boundary relaxation zone for plots. important to do that now and not before.
    291307          if (typefile in ['meso'] and mapmode == 1):
    292              if '9999' not in getattr(nc,'START_DATE'): lon2d = dumpbdy(lon2d,6) ; lat2d = dumpbdy(lat2d,6) 
     308             if '9999' not in getattr(nc,'START_DATE'): lon2d = myplot.dumpbdy(lon2d,6) ; lat2d = myplot.dumpbdy(lat2d,6) 
    293309          ### we read the keyword for vertical dimension. we take care for vertical staggering.
    294310          if varname in ['PHTOT','W']:    vertdim='BOTTOM-TOP_PATCH_END_STAG'
     
    304320          ### we define the time axis and take care of various specificities (lt, ls, sol) or issues (concatenation)
    305321          if axtime in ["ls","sol"]:
    306               lstab, soltab, lttab = getlschar ( namefile, getaxis = True )
     322              lstab, soltab, lttab = myplot.getlschar ( namefile, getaxis = True )
    307323              if axtime == "ls":      time = lstab
    308324              elif axtime == "sol":   time = soltab
     
    315331          if axtime in ["lt"]:
    316332              ftime = np.zeros(len(time))
    317               for i in range(len(time)): ftime[i] = localtime ( time[i], slon , namefile )
    318               time=ftime ; time=check_localtime(time)
     333              for i in range(len(time)): ftime[i] = myplot.localtime ( time[i], slon , namefile )
     334              time=ftime ; time = myplot.check_localtime(time)
    319335              print "LOCAL TIMES.... ", time
    320336          ### we define the vertical axis (or lack thereof) and cover possibilities for it to be altitude, pressure, geopotential. quite SPECIFIC.
    321           if typefile in ['geo']:   vert = [0.] ; stime = readslices(str(0))
     337          if typefile in ['geo']:   vert = [0.] ; stime = myplot.readslices(str(0))
    322338          else:
    323339              if vertmode is None:  vertmode=0
     
    332348####################################################################
    333349
     350
    334351    ### we fill the arrays of varname, namefile, time, colorbar at the current step considered (NB: why use both k and nnn ?)
    335352      all_varname[k] = varname
    336353      all_namefile[k] = namefile
    337       all_time[k] = time
    338       all_vert[k] = vert
    339       all_lat[k] = lat
    340       all_lon[k] =  lon
    341354      all_colorb[k] = clb[vvv]
    342       if var2:  all_var2[k], plot_x[k], plot_y[k] = select_getfield(zvarname=var2,znc=nc,ztypefile=typefile,mode='getvar',ztsat=tsat,ylon=all_lon[k],ylat=all_lat[k],yalt=all_vert[k],ytime=all_time[k],analysis=analysis)
    343       if winds: all_windu[k] = getfield(nc,uchar) ; all_windv[k] = getfield(nc,vchar)
    344     ### we fill the arrays of fields to be plotted at the current step considered
    345       all_var[k], plot_x[k], plot_y[k] = select_getfield(zvarname=all_varname[k],znc=nc,ztypefile=typefile,mode='getvar',ztsat=tsat,ylon=all_lon[k],ylat=all_lat[k],yalt=all_vert[k],ytime=all_time[k],analysis=analysis)
     355
     356##############################################################################
     357##### LARGE FILE. WE'D BETTER NOT FILL THE MEMORY WITH THE STUPID WHOLE ARRAY!
     358      if monster:
     359        ####################################################################
     360        ## get all indexes to be taken into account for this subplot and then reduce field
     361        ## We plot 1) all lon slices 2) all lat slices 3) all vert slices 4) all time slices and then go to the next slice
     362        if ope is not None:
     363            if fileref is not None:      index_f = (k//(nlon*nlat*nvert*ntime))%(3*len(namefiles))  ## OK only 1 var,  see test in the beginning
     364            elif "var" in ope:           index_f = (k//(nlon*nlat*nvert*ntime))%(len(var)+1)        ## OK only 1 file, see test in the beginning
     365            elif "cat" in ope:           index_f = 0
     366        elif not (k == 0):
     367           #if len(namefiles) > 1 and len(var) == 1 and which == "unidim": pass ## TROUVER UN MOYEN POUR unidim
     368           if len(namefiles) > 1 and len(var) == 1: pass
     369           else: yeah = len(namefiles)*len(var) ; index_f = (k//(nlon*nlat*nvert*ntime))%yeah
     370        else: yeah = len(namefiles)*len(var) ; index_f = (k//(nlon*nlat*nvert*ntime))%yeah
     371
     372        ilon  = myplot.getsindex(sslon,k%nlon,lon)
     373        ilat  = myplot.getsindex(sslat,(k//nlon)%nlat,lat)
     374        ivert = myplot.getsindex(svert,(k//(nlon*nlat))%nvert,vert)
     375 
     376        if mrate is not None:                 itime = None
     377        else:                                 itime = myplot.getsindex(stime,(k//(nlon*nlat*nvert))%ntime,time)
     378        ltst = None
     379        if typefile in ['meso'] and itime is not None and len(itime) < 2: ltst = myplot.localtime ( itime, slon , all_namefile[index_f] )
     380 
     381        if ilat  is not None:  print "********** LAT : INDEX",ilat[0],  ilat[-1],  "VALUE",lat[ilat[0]],   lat[ilat[-1]]
     382        else:                  ilat = range(len(lat))
     383        if ilon  is not None:  print "********** LON : INDEX",ilon[0],  ilon[-1],  "VALUE",lon[ilon[0]],   lon[ilon[-1]]
     384        else:                  ilon = range(len(lon))
     385        if ivert is not None:  print "********** VERT: INDEX",ivert[0], ivert[-1], "VALUE",vert[ivert[0]], vert[ivert[-1]]
     386        else:                  ivert = range(len(vert))
     387        if itime is not None:  print "********** TIME: INDEX",itime[0], itime[-1], "VALUE",time[itime[0]], time[itime[-1]]
     388        else:                  itime = range(len(time))
     389
     390        all_time[k] = time[itime]
     391        all_vert[k] = vert[ivert]
     392        all_lat[k]  = lat[ilat]
     393        all_lon[k]  = lon[ilon]
     394
     395        all_var[k] = myplot.getfieldred(nc,all_varname[k],ilon,ilat,ivert,itime)
     396        if var2:   all_var2[k] = myplot.getfieldred(nc,var2,ilon,ilat,ivert,itime)
     397        if winds: 
     398            all_windu[k] = myplot.getfield(nc,uchar,ilon,ilat,ivert,itime)
     399            all_windv[k] = myplot.getfield(nc,vchar,ilon,ilat,ivert,itime)
     400        plot_x[k] = None ; plot_y[k] = None
     401
     402      else:
     403        ## regular stuff: not large array.
     404        all_time[k] = time
     405        all_vert[k] = vert
     406        all_lat[k]  = lat
     407        all_lon[k]  = lon
     408        if var2:  all_var2[k], plot_x[k], plot_y[k] = myplot.select_getfield(zvarname=var2,znc=nc,ztypefile=typefile,\
     409                         mode='getvar',ztsat=tsat,ylon=all_lon[k],ylat=all_lat[k],yalt=all_vert[k],ytime=all_time[k],analysis=analysis)
     410        if winds: all_windu[k] = myplot.getfield(nc,uchar) ; all_windv[k] = myplot.getfield(nc,vchar)
     411        ### we fill the arrays of fields to be plotted at the current step considered
     412        all_var[k], plot_x[k], plot_y[k] = myplot.select_getfield(zvarname=all_varname[k],znc=nc,ztypefile=typefile,\
     413                         mode='getvar',ztsat=tsat,ylon=all_lon[k],ylat=all_lat[k],yalt=all_vert[k],ytime=all_time[k],analysis=analysis)
     414####################################################################
    346415
    347416      # last line of for namefile in namefiles
     
    354423    if ope is not None and "var" in ope:
    355424         print "********** OPERATION: ",ope
    356          if len(namefiles) > 1: errormess("for this operation... please set only one file !")
    357          if len(var) > 2:       errormess("not sure this works for more than 2 vars... please check.")
     425         if len(namefiles) > 1: myplot.errormess("for this operation... please set only one file !")
     426         if len(var) > 2:       myplot.errormess("not sure this works for more than 2 vars... please check.")
    358427         if   "div_var" in ope: all_var[k] = all_var[k-2] / all_var[k-1] ; insert = '_div_'
    359428         elif "mul_var" in ope: all_var[k] = all_var[k-2] * all_var[k-1] ; insert = '_mul_'
    360429         elif "add_var" in ope: all_var[k] = all_var[k-2] + all_var[k-1] ; insert = '_add_'
    361430         elif "sub_var" in ope: all_var[k] = all_var[k-2] - all_var[k-1] ; insert = '_sub_'
    362          else:                    errormess(ope+" : non-implemented operation. Check pp.py --help")
     431         else:                    myplot.errormess(ope+" : non-implemented operation. Check pp.py --help")
    363432         plot_x[k] = None ; plot_y[k] = None
    364433         all_time[k] = all_time[k-1] ; all_vert[k] = all_vert[k-1] ; all_lat[k] = all_lat[k-1] ; all_lon[k] = all_lon[k-1] ; all_namefile[k] = all_namefile[k-1]
     
    383452       print "********** OPERATION: ",ope
    384453       for k in np.arange(zelen):
    385                if len(var) > 1: errormess("for this operation... please set only one var !")
     454               if len(var) > 1: myplot.errormess("for this operation... please set only one var !")
    386455               if ope in ["-","+","-%","-_only","+_only","-%_only","-_histo"]:
    387                   if fileref is None: errormess("fileref is missing!")
     456                  if fileref is None: myplot.errormess("fileref is missing!")
    388457                  else:ncref = Dataset(fileref)
    389458
     
    399468                        print "SETTING REFERENCE PLOT"
    400469                        all_varname[k] = all_varname[k-1] ; all_time[k] = all_time[k-1] ; all_vert[k] = all_vert[k-1] ; all_lat[k] = all_lat[k-1] ; all_lon[k] = all_lon[k-1] ; all_namefile[k] = all_namefile[k-1] ; all_var2[k] = all_var2[k-1] ; all_colorb[k] = all_colorb[k-1]
    401                         all_var[k], plot_x[k], plot_y[k] = select_getfield(zvarname=all_varname[k-1],znc=ncref,ztypefile=typefile,mode='getvar',ztsat=tsat,ylon=all_lon[k],ylat=all_lat[k],yalt=all_vert[k],ytime=all_time[k],analysis=analysis)
    402                         if winds: all_windu[k] = getfield(ncref,uchar) ; all_windv[k] = getfield(ncref,vchar)
     470                        all_var[k], plot_x[k], plot_y[k] = myplot.select_getfield(zvarname=all_varname[k-1],znc=ncref,ztypefile=typefile,mode='getvar',ztsat=tsat,ylon=all_lon[k],ylat=all_lat[k],yalt=all_vert[k],ytime=all_time[k],analysis=analysis)
     471                        if winds: all_windu[k] = myplot.getfield(ncref,uchar) ; all_windv[k] = myplot.getfield(ncref,vchar)
    403472
    404473                  if (k+1)%3==0: ## operation plots
     
    434503                  all_time[0] = np.array(tabtime) ; all_var[0] = np.array(tab) ; numplot = 1
    435504                  if var2: all_var2[0] = np.array(tab2)
    436                else: errormess(ope+" : non-implemented operation. Check pp.py --help")
     505               else: myplot.errormess(ope+" : non-implemented operation. Check pp.py --help")
    437506       if "only" in ope:
    438507           numplot = 1 ; all_var[0] = all_var[k]
     
    442511    ##################################
    443512    ### Open a figure and set subplots
    444     fig = figure()
    445     subv,subh = definesubplot( numplot, fig, ipreferline = (mapmode == 1) )
     513    fig = mpl.pyplot.figure()
     514    subv,subh = myplot.definesubplot( numplot, fig, ipreferline = (mapmode == 1) )
    446515    if ope in ['-','-%','-_histo'] and len(namefiles) ==1 : subv,subh = 2,2
    447516    elif ope in ['-','-%'] and len(namefiles)>1 : subv, subh = len(namefiles), 3
     
    450519    ### Time loop for plotting device
    451520    nplot = 1 ; error = False ; firstpass = True
    452     if lstyle is not None: linecycler = cycle(lstyle)
    453     else: linecycler = cycle(["-","--","-.",":"])
     521    if lstyle is not None: linecycler = itertools.cycle(lstyle)
     522    else: linecycler = itertools.cycle(["-","--","-.",":"])
    454523    print "********************************************"
    455524    while error is False:
     
    470539       else: yeah = len(namefiles)*len(var) ; index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%yeah
    471540       time = all_time[index_f] ; vert = all_vert[index_f] ; lat = all_lat[index_f] ; lon = all_lon[index_f]
    472        indexlon  = getsindex(sslon,(nplot-1)%nlon,lon)
    473        indexlat  = getsindex(sslat,((nplot-1)//nlon)%nlat,lat)
    474        indexvert = getsindex(svert,((nplot-1)//(nlon*nlat))%nvert,vert)
     541       indexlon  = myplot.getsindex(sslon,(nplot-1)%nlon,lon)
     542       indexlat  = myplot.getsindex(sslat,((nplot-1)//nlon)%nlat,lat)
     543       indexvert = myplot.getsindex(svert,((nplot-1)//(nlon*nlat))%nvert,vert)
    475544       plotx=plot_x[index_f] ; ploty=plot_y[index_f]
    476545       if mrate is not None:                 indextime = None
    477        else:                                 indextime = getsindex(stime,((nplot-1)//(nlon*nlat*nvert))%ntime,time)
     546       else:                                 indextime = myplot.getsindex(stime,((nplot-1)//(nlon*nlat*nvert))%ntime,time)
    478547       ltst = None
    479        if typefile in ['meso'] and indextime is not None and len(indextime) < 2: ltst = localtime ( indextime, slon , all_namefile[index_f])
    480 
    481 
    482        #if mapmode == 0:
    483        # if xlab is None:
    484        #  if indexlon is None:  xlab = "Longitude"
    485        #  elif indexlat is None: xlab = "Latitude"
    486        # if ylab is None:
    487        #  if indexvert is None: ylab = "Altitude"
    488 
    489 
    490        print "********** INDEX LON:",indexlon," LAT:",indexlat," VERT:",indexvert," TIME:",indextime
     548       if typefile in ['meso'] and indextime is not None and len(indextime) < 2: ltst = myplot.localtime ( indextime, slon , all_namefile[index_f] )
     549
     550       if not monster:
     551         if indexlat  is not None: print "********** LAT : INDEX",indexlat[0],  indexlat[-1],  "VALUE",lat[indexlat[0]],   lat[indexlat[-1]]
     552         if indexlon  is not None: print "********** LON : INDEX",indexlon[0],  indexlon[-1],  "VALUE",lon[indexlon[0]],   lon[indexlon[-1]]
     553         if indexvert is not None: print "********** VERT: INDEX",indexvert[0], indexvert[-1], "VALUE",vert[indexvert[0]], vert[indexvert[-1]]
     554         if indextime is not None: print "********** TIME: INDEX",indextime[0], indextime[-1], "VALUE",time[indextime[0]], time[indextime[-1]]
     555
    491556       ##var = nc.variables["phisinit"][:,:]
    492        ##contourf(np.transpose(var),30,cmap = get_cmap(name="Greys_r") ) ; axis('off') ; plot(indexlat,indexlon,'mx',mew=4.0,ms=20.0)
    493        ##show()
     557       ##contourf(np.transpose(var),30,cmap = get_cmap(name="Greys_r") ) ; mpl.pyplot.axis('off') ; plot(indexlat,indexlon,'mx',mew=4.0,ms=20.0)
     558       ##mpl.pyplot.show()
    494559       ##exit()
    495560       #truc = True
     
    503568       which=''
    504569       if varname:   ### what is shaded.
    505            what_I_plot, error = reducefield( all_var[index_f], d4=indextime, d1=indexlon, d2=indexlat, d3=indexvert, \
     570           what_I_plot, error = myplot.reducefield( all_var[index_f], d4=indextime, d1=indexlon, d2=indexlat, d3=indexvert, \
    506571                                             yint=yintegral, alt=vert, anomaly=anomaly, redope=redope, mesharea=area, unidim=is1d)
    507572           if add != 0.:      what_I_plot = what_I_plot + add
     
    510575
    511576       if var2:      ### what is contoured.
    512            what_I_plot_contour, error = reducefield( all_var2[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert, \
     577           what_I_plot_contour, error = myplot.reducefield( all_var2[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert, \
    513578                                                     yint=yintegral, alt=vert, redope=redope )
    514579       if winds:     ### what is plot as vectors.
    515            vecx, error = reducefield( all_windu[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert)
    516            vecy, error = reducefield( all_windv[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert)
     580           vecx, error = myplot.reducefield( all_windu[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert)
     581           vecy, error = myplot.reducefield( all_windv[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert)
    517582           if varname in [uchar,vchar]: what_I_plot = np.sqrt( np.square(vecx) + np.square(vecy) ) ; varname = "wind"
    518583 
    519584       if plotx is not None:
    520           plotx, error = reducefield( plotx, d4=indextime, d1=indexlon, d2=indexlat, d3=indexvert, \
     585          plotx, error = myplot.reducefield( plotx, d4=indextime, d1=indexlon, d2=indexlat, d3=indexvert, \
    521586                                             yint=yintegral, alt=vert, anomaly=anomaly, redope=redope, mesharea=area, unidim=is1d)
    522           ploty, error = reducefield( ploty, d4=indextime, d1=indexlon, d2=indexlat, d3=indexvert, \
     587          ploty, error = myplot.reducefield( ploty, d4=indextime, d1=indexlon, d2=indexlat, d3=indexvert, \
    523588                                             yint=yintegral, alt=vert, anomaly=anomaly, redope=redope, mesharea=area, unidim=is1d)
    524589          which='xy'
     
    526591       #if truc:
    527592       #   nx = what_I_plot.shape[2] ; ny = what_I_plot.shape[1] ; nz = what_I_plot.shape[0]
    528        #   for k in range(nz): print k,' over ',nz ; what_I_plot[k,:,:] = what_I_plot[k,:,:] / smooth(what_I_plot[k,:,:],12)
     593       #   for k in range(nz): print k,' over ',nz ; what_I_plot[k,:,:] = what_I_plot[k,:,:] / myplot.smooth(what_I_plot[k,:,:],12)
    529594       #   for iii in range(nx):
    530595       #    for jjj in range(ny):
     
    534599       #     if np.abs(what_I_plot[0,jjj,iii]) > 1.5:
    535600       #         print iii,jjj,what_I_plot[0,jjj,iii],int(abs(1.-mx)*100.),int(abs(1.-mn)*100.)
    536        #         plot(rel)
    537        #   show()
     601       #         mpl.pyplot.plot(rel)
     602       #   mpl.pyplot.show()
    538603       #   anomaly = True ### pour avoir les bons reglages plots
    539604       #   what_I_plot = what_I_plot[0,:,:] 
     
    543608       ### General plot settings
    544609       changesubplot = (numplot > 1) and (len(what_I_plot.shape) != 1) and (which != "xy")  ## default for 1D plots: superimposed. to be reworked for better flexibility.
    545        if changesubplot: subplot(subv,subh,nplot) #; subplots_adjust(wspace=0,hspace=0)
     610       if changesubplot: mpl.pyplot.subplot(subv,subh,nplot) #; mpl.pyplot.subplots_adjust(wspace=0,hspace=0)
    546611       colorb = all_colorb[index_f]
    547612       ####################################################################
    548613       if error:
    549                errormess("There is an error in reducing field !")
     614               myplot.errormess("There is an error in reducing field !")
    550615       else:
    551616               ticks = ndiv + 1
     
    565630                       if slon is not None or proj == "noproj": latyeah = lat2d[:,milieux]
    566631                       if slat is not None or proj == "noproj": lonyeah = lon2d[milieuy,:]
    567                    what_I_plot, x, y = define_axis(lonyeah,latyeah,vert,time,indexlon,indexlat,indexvert,\
     632                   what_I_plot, x, y = myplot.define_axis(lonyeah,latyeah,vert,time,indexlon,indexlat,indexvert,\
    568633                         itime,what_I_plot, len(all_var[index_f].shape),vertmode,redope)
    569634               ###
    570                if analysis in ['laplace']: what_I_plot = ndimage.laplace(what_I_plot)
     635               if analysis in ['laplace']: what_I_plot = laplace(what_I_plot)
    571636               ###
    572                if (fileref is not None) and ((index_f+1)%3 == 0):    zevmin, zevmax = calculate_bounds(what_I_plot,vmin=minop,vmax=maxop)
    573                else:                                                   zevmin, zevmax = calculate_bounds(what_I_plot,vmin=vmin,vmax=vmax)
     637               if (fileref is not None) and ((index_f+1)%3 == 0):    zevmin, zevmax = myplot.calculate_bounds(what_I_plot,vmin=minop,vmax=maxop)
     638               else:                                                   zevmin, zevmax = myplot.calculate_bounds(what_I_plot,vmin=vmin,vmax=vmax)
    574639               #if (fileref is not None) and (index_f == numplot-1):    colorb = "RdBu_r"
    575                if colorb in ["def","nobar","onebar"]:                  palette = get_cmap(name=defcolorb(fvar.upper()))
     640               if colorb in ["def","nobar","onebar"]:                  palette = mpl.cm.get_cmap(name=myplot.defcolorb(fvar.upper()))
    576641               elif colorb == "relief":                                palette = cm.GMT_relief
    577642               elif colorb == "haxby":                                 palette = cm.GMT_haxby
    578                else:                                                   palette = get_cmap(name=colorb)
     643               else:                                                   palette = mpl.cm.get_cmap(name=colorb)
    579644               #palette = cm.GMT_split
    580645               #palette = cm.GMT_globe
     
    585650               elif len(what_I_plot.shape) >= 4:
    586651                 print "WARNING!!! ",len(what_I_plot.shape),"-D PLOT NOT SUPPORTED !!! dimensions: ",what_I_plot.shape
    587                  errormess("Are you sure you did not forget to prescribe a dimension ?")
     652                 myplot.errormess("Are you sure you did not forget to prescribe a dimension ?")
    588653               ##### 2. HANDLE simple 1D/2D field and movies of 1D/2D fields
    589654               else:
     
    595660                    if var2 and which == '':               which = "contour" ## have to start with contours rather than shading
    596661                    elif which == '':                      which = "regular"
    597                     if mrate is None:      errormess("3D field. Use --rate RATE for movie or specify --time TIME. Exit.")
     662                    if mrate is None:      myplot.errormess("3D field. Use --rate RATE for movie or specify --time TIME. Exit.")
    598663                 elif len(what_I_plot.shape) == 2:
    599664                    if var2 and which == '':               which = "contour" ## have to start with contours rather than shading
     
    621686                    #if mrate is not None:     
    622687                    if mapmode == 1:
    623                         m = define_proj(proj,wlon,wlat,back=back,blat=blat,blon=blon)  ## this is dirty, defined above but out of imov loop
     688                        m = myplot.define_proj(proj,wlon,wlat,back=back,blat=blat,blon=blon)  ## this is dirty, defined above but out of imov loop
    624689                        x, y = m(lon2d, lat2d)                                         ## this is dirty, defined above but out of imov loop
    625690                    if (typefile in ['meso'] and mapmode == 1):
    626                        if '9999' not in getattr(nc,'START_DATE'): what_I_plot_frame = dumpbdy(what_I_plot_frame,6,condition=True)
    627 #                   if typefile in ['mesoideal']:    what_I_plot_frame = dumpbdy(what_I_plot_frame,0,stag='W',condition=dumped_vert_stag)
     691                       if '9999' not in getattr(nc,'START_DATE'): what_I_plot_frame = myplot.dumpbdy(what_I_plot_frame,6,condition=True)
     692#                   if typefile in ['mesoideal']:    what_I_plot_frame = myplot.dumpbdy(what_I_plot_frame,0,stag='W',condition=dumped_vert_stag)
    628693
    629694                    if which == "unidim":
     
    645710                        else:         zemarker = None
    646711                        this_is_a_regular_plot = (indexvert is not None) or (indextime is None) or (indexlat is None) or (indexlon is None)
    647                         if this_is_a_regular_plot:   plot(x,what_I_plot_frame,zeline,label=lbl,marker=zemarker)  ## vertical profile
    648                         else:                        plot(what_I_plot_frame,x,zeline,label=lbl,marker=zemarker)  ## regular plot
     712                        if this_is_a_regular_plot:   mpl.pyplot.plot(x,what_I_plot_frame,zeline,label=lbl,marker=zemarker)  ## vertical profile
     713                        else:                        mpl.pyplot.plot(what_I_plot_frame,x,zeline,label=lbl,marker=zemarker)  ## regular plot
    649714                        mpl.pyplot.grid(True)
    650                         if nplot > 1: legend(loc='best')
    651                         if indextime is None and axtime is not None and xlab is None:    xlabel(axtime.upper()) ## define the right label
     715                        if nplot > 1: mpl.pyplot.legend(loc='best')
     716                        if indextime is None and axtime is not None and xlab is None:    mpl.pyplot.xlabel(axtime.upper()) ## define the right label
    652717                        if save == 'txt':  writeascii(np.transpose([x,np.transpose(what_I_plot)]),'profile'+str(nplot*1000+imov)+'.txt')
    653718                        if axtime == "lt" and indextime is None:
     
    682747                                  else:
    683748                                     plotx = np.linspace(min(ploty.flatten()),max(ploty.flatten()),1000)
    684                                      density = gaussian_kde(ploty.flatten())
     749                                     density = scipy.stats.gaussian_kde(ploty.flatten())
    685750   #                                  density.covariance_factor = lambda : .25  # adjust the covariance factor to change the bandwidth if needed
    686751   #                                  density._compute_covariance()
    687752                                        # display the mean and variance of the kde:
    688753                                     sample = density.resample(size=20000)
    689                                      n, (smin, smax), sm, sv, ss, sk = describe(sample[0])
     754                                     n, (smin, smax), sm, sv, ss, sk = scipy.stats.describe(sample[0])
    690755                                     mpl.pyplot.plot(plotx,density(plotx), label = lbl+'\nmean: '+str(sm)[0:5]+'   std: '+str(np.sqrt(sv))[0:5]+'\nskewness: '+str(ss)[0:5]+'   kurtosis: '+str(sk)[0:5])
    691756                                     if analysis == 'histodensity':  # plot both histo and density (to assess the rightness of the kernel density estimate for exemple) and display the estimated variance
     
    693758                                     if index_f == zelen-1: mpl.pyplot.legend() ; mpl.pyplot.title(zetitle)
    694759                           else:
    695                               plot(plotx,ploty,label = lbl)
     760                              mpl.pyplot.plot(plotx,ploty,label = lbl)
    696761                              if index_f == zelen-1: mpl.pyplot.legend() ; mpl.pyplot.title(zetitle)
    697762                              mpl.pyplot.grid(True)
    698763                        else:
    699                            plot(plotx,ploty,label = lbl)
     764                           mpl.pyplot.plot(plotx,ploty,label = lbl)
    700765                           if index_f == zelen-1: mpl.pyplot.legend() ; mpl.pyplot.title(zetitle)
    701766                        if varname == 'hodograph':
     
    715780                                print 'INFO: Using stream file',streamfile, 'for stream lines'
    716781                                ncstream = Dataset(streamfile)
    717                                 psi = getfield(ncstream,'psi')
     782                                psi = myplot.getfield(ncstream,'psi')
    718783                                psi = psi[0,:,:,0] # time and longitude are dummy dimensions
    719784                                if psi.shape[1] != len(x) or psi.shape[0] != len(y):
    720                                     errormess('stream file does not fit! Dimensions: '+str(psi.shape)+' '+str(x.shape)+' '+str(y.shape))
     785                                    myplot.errormess('stream file does not fit! Dimensions: '+str(psi.shape)+' '+str(x.shape)+' '+str(y.shape))
    721786                                zelevels = np.arange(-1.e10,1.e10,1.e9)
    722787                                zemin = np.min(abs(zelevels))
    723788                                zemax = np.max(abs(zelevels))
    724789                                zewidth  =  (abs(zelevels)-zemin)*(5.- 0.5)/(zemax - zemin) + 0.5 # linewidth ranges from 5 to 0.5
    725                                 cs = contour( x,y,psi, zelevels, colors='k', linewidths = zewidth)
    726                                 clabel(cs, inline=True, fontsize = 4.*rcParams['font.size']/5., fmt="%1.1e")
     790                                cs = mpl.pyplot.contour( x,y,psi, zelevels, colors='k', linewidths = zewidth)
     791                                mpl.pyplot.clabel(cs, inline=True, fontsize = 4.*mpl.pyplot.rcParams['font.size']/5., fmt="%1.1e")
    727792                             else:
    728793                                print 'WARNING: STREAM FILE',streamfile, 'DOES NOT EXIST !'
    729794                             
    730                         if hole:         what_I_plot_frame = hole_bounds(what_I_plot_frame,zevmin,zevmax)
    731                         else:            what_I_plot_frame = bounds(what_I_plot_frame,zevmin,zevmax)
    732                         if flagnolow:    what_I_plot_frame = nolow(what_I_plot_frame)
     795                        if hole:         what_I_plot_frame = myplot.hole_bounds(what_I_plot_frame,zevmin,zevmax)
     796                        else:            what_I_plot_frame = myplot.bounds(what_I_plot_frame,zevmin,zevmax)
     797                        if flagnolow:    what_I_plot_frame = myplot.nolow(what_I_plot_frame)
    733798                        if not tile:
    734799                            #zelevels = np.linspace(zevmin*(1. + 1.e-7),zevmax*(1. - 1.e-7)) #,num=20)
    735800                            zelevels = np.linspace(zevmin,zevmax,num=ticks)
    736                             #what_I_plot_frame = smooth(what_I_plot_frame,100)
     801                            #what_I_plot_frame = myplot.smooth(what_I_plot_frame,100)
    737802                            if mapmode == 1:       m.contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans)
    738                             elif mapmode == 0:     contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans)
     803                            elif mapmode == 0:     mpl.pyplot.contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans)
    739804                        else:
    740805                            if mapmode == 1:       m.pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans)
    741                             elif mapmode == 0:     pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans)
     806                            elif mapmode == 0:     mpl.pyplot.pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans)
    742807
    743808                        if (cross is not None or markdevil) and mapmode == 1:
     
    748813                                  mpl.pyplot.plot([idx],[idy],'+k',mew=0.5,ms=18)
    749814                            elif markdevil:
    750                                 idx,idy=find_devil(nc,indextime)
     815                                idx,idy=myplot.find_devil(nc,indextime)
    751816                                idx,idy=x[idx,idy],y[idx,idy]
    752817                                mpl.pyplot.plot([idx],[idy],'+k',mew=0.5,ms=18)
     
    756821                            if (fileref is not None) and ((index_f+1)%3 == 0):   daformat = "%.3f"
    757822                            elif mult != 1:                                        daformat = "%.1f"
    758                             else:                                                  daformat = fmtvar(fvar.upper())
     823                            else:                                                  daformat = myplot.fmtvar(fvar.upper())
    759824                            if proj in ['moll']:  zeorientation="horizontal" ; zepad = 0.07 ; zefrac = 0.1 #zepad=0.05
    760825                            elif proj in ['cyl']: zeorientation="vertical" ; zepad = 0.03 ; zefrac = 0.023
    761826                            else:                 zeorientation="vertical" ; zepad = 0.03 ; zefrac = 0.05
    762827                            if mapmode == 0:      zefrac = 0.1
    763                             zecb = colorbar( fraction=zefrac,pad=zepad,format=daformat,orientation=zeorientation,\
     828                            zecb = mpl.pyplot.colorbar( fraction=zefrac,pad=zepad,format=daformat,orientation=zeorientation,\
    764829                                      ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional' )
    765830                            #if zeorientation == "horizontal":
     
    769834                        if winds:
    770835                            if typefile in ['meso']:
    771                                 if '9999' not in getattr(nc,'START_DATE') : [vecx_frame,vecy_frame] = [dumpbdy(vecx_frame,6,stag=uchar,condition=True), dumpbdy(vecy_frame,6,stag=vchar,condition=True)]
     836                                if '9999' not in getattr(nc,'START_DATE') : [vecx_frame,vecy_frame] = [myplot.dumpbdy(vecx_frame,6,stag=uchar,condition=True), myplot.dumpbdy(vecy_frame,6,stag=vchar,condition=True)]
    772837                                key = True
    773838                                if fvar in ['UV','uv','uvmet']: key = False
     
    775840                                key = False
    776841                            if metwind and mapmode == 1:   [vecx_frame,vecy_frame] = m.rotate_vector(vecx_frame, vecy_frame, lon2d, lat2d)
    777                             if trans != 0.0:   colorvec = definecolorvec(colorb)
    778                             else:              colorvec = definecolorvec(back)
    779                             vectorfield(vecx_frame, vecy_frame, x, y, stride=stride, csmooth=2,\
     842                            if trans != 0.0:   colorvec = myplot.definecolorvec(colorb)
     843                            else:              colorvec = myplot.definecolorvec(back)
     844                            myplot.vectorfield(vecx_frame, vecy_frame, x, y, stride=stride, csmooth=2,\
    780845                                             #scale=15., factor=300., color=colorvec, key=key)
    781846                                             scale=20., factor=250./facwind, color=colorvec, key=key)
     
    783848                        ### THIS IS A QUITE SPECIFIC PIECE (does not work for mesoscale files)
    784849                        if ope == '-_histo' and nplot == numplot: # this should work as long as ope is '-' guarantees 3 plots for 4 panels without contour
    785                             subplot(subv,subh,nplot+1)
    786                             rcParams["legend.fontsize"] = 'xx-large'
     850                            mpl.pyplot.subplot(subv,subh,nplot+1)
     851                            mpl.pyplot.rcParams["legend.fontsize"] = 'xx-large'
    787852                            if indexlat is None:
    788853                                latmin = -50.; latmax = 50. # latitude range for histogram of difference
     
    794859                            toplot = np.ravel(what_I_plot_frame[np.isnan(what_I_plot_frame)==False])
    795860                            zebins = np.linspace(zevmin,zevmax,num=30)
    796                             hist(toplot,bins=zebins,histtype='step',linewidth=2,color='k',normed=True)
     861                            mpl.pyplot.hist(toplot,bins=zebins,histtype='step',linewidth=2,color='k',normed=True)
    797862                            zestd = np.std(toplot);zemean = np.mean(toplot)
    798863                            zebins = np.linspace(zevmin,zevmax,num=300)
    799864                            zegauss = (1./(zestd * np.sqrt(2 * np.pi)) * np.exp( - (zebins - zemean)**2 / (2 * zestd**2) ) )
    800                             plot(zebins, zegauss, linewidth=1, color='r',label="mean: "+str(zemean)[0:5]+"\nstd: "+str(zestd)[0:5])
    801                             legend(loc=0,frameon=False)
    802                             subplot(subv,subh,nplot) # go back to last plot for title of contour difference
     865                            mpl.pyplot.plot(zebins, zegauss, linewidth=1, color='r',label="mean: "+str(zemean)[0:5]+"\nstd: "+str(zestd)[0:5])
     866                            mpl.pyplot.legend(loc=0,frameon=False)
     867                            mpl.pyplot.subplot(subv,subh,nplot) # go back to last plot for title of contour difference
    803868                        if ope is not None and "only" not in ope: title("fig(1) "+ope+" fig(2)")
    804869                        elif ope is not None and "only" in ope: title("fig(1) "+ope[0]+" fig(2)")
    805870                           
    806871                    elif which == "contour":
    807                         rcParams['contour.negative_linestyle'] = 'solid' # no dashed line for negative values
    808                         zevminc, zevmaxc = calculate_bounds(what_I_plot_frame, vmin=min(what_I_plot_frame), vmax=max(what_I_plot_frame))
     872                        mpl.pyplot.rcParams['contour.negative_linestyle'] = 'solid' # no dashed line for negative values
     873                        zevminc, zevmaxc = myplot.calculate_bounds(what_I_plot_frame, vmin=min(what_I_plot_frame), vmax=max(what_I_plot_frame))
    809874                        zelevels = np.linspace(zevminc,zevmaxc,ticks/2) #20)
    810875                        ### another dirty specific stuff in the wall
     
    814879                        elif var2 == 'wstar':    zelevels = np.arange(0,10,1.0)
    815880                        elif var2 == 'zmax_th':  zelevels = np.arange(0,10,2.0) ; what_I_plot_frame = what_I_plot_frame / 1000.
     881                        elif var2 in ['u']:      zelevels = np.arange(-400.,400.,10.)
    816882                        ###
    817883                        if mapmode == 0:   
    818                             what_I_plot_frame, x, y = define_axis( lonyeah,latyeah,vert,time,indexlon,indexlat,indexvert,\
     884                            what_I_plot_frame, x, y = myplot.define_axis( lonyeah,latyeah,vert,time,indexlon,indexlat,indexvert,\
    819885                                                              itime,what_I_plot_frame, len(all_var2[index_f].shape),vertmode,redope)
    820886                            ## is this needed? only if len(all_var2[index_f].shape) != len(all_var[index_f].shape)
    821                             cs = contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 0.33)#, alpha=0.5, linestyles='solid')
    822                             ##cs = contour( x,y,what_I_plot_frame, zelevels, colors='w', linewidths = 0.5)#, alpha=0.5, linestyles='solid')
    823                             #clabel(cs, inline=1, fontsize = 4.*rcParams['font.size']/5., fmt=fmtvar(var2.upper()))
     887                            cs = mpl.pyplot.contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 0.33)#, alpha=0.5, linestyles='solid')
     888                            ##cs = mpl.pyplot.contour( x,y,what_I_plot_frame, zelevels, colors='w', linewidths = 0.5)#, alpha=0.5, linestyles='solid')
     889                            #mpl.pyplot.clabel(cs, inline=1, fontsize = 4.*rcParams['font.size']/5., fmt=fmtvar(var2.upper()))
    824890                        elif mapmode == 1: 
    825891                            cs = m.contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 0.33)#, alpha=0.5, linestyles='solid')
    826                             #clabel(cs, inline=0, fontsize = rcParams['font.size'], fmt="%.0f") #fmtvar(var2.upper()))
     892                            #mpl.pyplot.clabel(cs, inline=0, fontsize = mpl.pyplot.rcParams['font.size'], fmt="%.0f") #myplot.fmtvar(var2.upper()))
    827893                    if which in ["regular","unidim","xy"]:
    828894
     
    842908                                mpl.pyplot.yscale('log')
    843909                           if invert_y:  ax = mpl.pyplot.gca() ; ax.set_ylim(ax.get_ylim()[::-1])
    844                            if xlab is not None: xlabel(xlab)
    845                            if ylab is not None: ylabel(ylab)
     910                           if xlab is not None: mpl.pyplot.xlabel(xlab)
     911                           if ylab is not None: mpl.pyplot.ylabel(ylab)
    846912
    847913                        if mrate is not None:
     
    855921                                moviename='movie' ;W,H = figframe.canvas.get_width_height()
    856922                                video = VideoSink((H,W), moviename, rate=mrate, byteorder="rgba")
    857                              video.run(mframe) ; close()
     923                             video.run(mframe) ; mpl.pyplot.close()
    858924                             if imov == iend: video.close()                           
    859925                           ### THIS IS A WEBPAGE MOVIE
    860926                           else:
    861927                             nameframe = "image"+str(1000+imov)
    862                              makeplotres(nameframe,res=100.,disp=False) ; close()
     928                             myplot.makeplotres(nameframe,res=100.,disp=False) ; mpl.pyplot.close()
    863929                             if imov == 0: myfile = open("zepics", 'w')
    864930                             myfile.write("modImages["+str(imov)+"] = '"+nameframe+"_100.png';"+ '\n')
     
    875941       zevarname = varname
    876942       if redope is not None: zevarname = zevarname + "_" + redope
    877        basename = getname(var=zevarname,var2=var2,winds=winds,anomaly=anomaly)
     943       basename = myplot.getname(var=zevarname,var2=var2,winds=winds,anomaly=anomaly)
    878944       if len(what_I_plot.shape) > 3:
    879            basename = basename + getstralt(nc,level)
     945           basename = basename + myplot.getstralt(nc,level)
    880946       if mrate is not None: basename = "movie_" + basename
    881947       if typefile in ['meso']:
     
    884950            plottitle = basename
    885951            ### dans le nouveau systeme time=ls,sol,lt cette ligne pourrait ne servir a rien (ou deplacer au dessus)
    886             if addchar and indextime is not None:   [addchar,gogol,gogol2] = getlschar ( all_namefile[index_f] )  ;  plottitle = plottitle + addchar
     952            if addchar and indextime is not None:   [addchar,gogol,gogol2] = myplot.getlschar ( all_namefile[index_f] )  ;  plottitle = plottitle + addchar
    887953            ### en fait redope is None doit etre remplace par : n'est ni maxt ni mint
    888954            if redope is None and ltst is not None and ( (mapmode == 0) or (proj in ["lcc","laea","merc","nsper"]) ):  plottitle = plottitle + "_LT" + str(ltst)
     
    905971#       if indexvert is not None:     plottitle = plottitle + " vert: " + str(min(vert[indexvert])) +" "+ str(max(vert[indexvert]))
    906972#       if indextime is not None:     plottitle = plottitle + " time: " + str(min(time[indextime])) +" "+ str(max(time[indextime]))
    907        if colorb != "onebar": title( plottitle )
     973       if colorb != "onebar": mpl.pyplot.title( plottitle )
    908974       if nplot >= numplot: error = True
    909975       nplot += 1
     
    913979
    914980    if colorb == "onebar":
    915         cax = axes([0.1, 0.2, 0.8, 0.03]) # a ameliorer
    916         zecb = colorbar(cax=cax, orientation="horizontal", format=fmtvar(fvar.upper()),\
     981        cax = mpl.pyplot.axes([0.1, 0.2, 0.8, 0.03]) # a ameliorer
     982        zecb = mpl.pyplot.colorbar(cax=cax, orientation="horizontal", format=myplot.fmtvar(fvar.upper()),\
    917983                 ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional')
    918984        if zetitle[0] != "fill": zecb.ax.set_xlabel(zetitle[index_f]) ; zetitle[index_f]=""
     
    922988    ### Save the figure in a file in the data folder or an user-defined folder
    923989    if outputname is None:
    924        if typefile in ['meso']:   prefix = getprefix(nc)
     990       if typefile in ['meso']:   prefix = myplot.getprefix(nc)
    925991       elif typefile in ['gcm']:            prefix = 'LMD_GCM_'
    926992       else:                                prefix = ''
     
    9421008        print "********** SAVE ", save
    9431009        if save == 'png':
    944             if display: makeplotres(zeplot,res=100.,pad_inches_value=pad_inches_value) #,erase=True)  ## a miniature
    945             makeplotres(zeplot,res=resolution,pad_inches_value=pad_inches_value,disp=False)
    946         elif save in ['eps','svg','pdf']:     makeplotres(zeplot,pad_inches_value=pad_inches_value,disp=False,ext=save)
    947         elif save == 'gui':                   show()
     1010            if display: myplot.makeplotres(zeplot,res=100.,pad_inches_value=pad_inches_value) #,erase=True)  ## a miniature
     1011            myplot.makeplotres(zeplot,res=resolution,pad_inches_value=pad_inches_value,disp=False)
     1012        elif save in ['eps','svg','pdf']:     myplot.makeplotres(zeplot,pad_inches_value=pad_inches_value,disp=False,ext=save)
     1013        elif save == 'gui':                   mpl.pyplot.show()
    9481014        elif save == 'donothing':             pass
    9491015        elif save == 'txt':                   print "Saved results in txt file."
    9501016        else:
    9511017            print "INFO: save mode not supported. using gui instead."
    952             show()
     1018            mpl.pyplot.show()
    9531019
    9541020    ###################################
  • trunk/UTIL/PYTHON/pp.py

    r865 r876  
    88if __name__ == "__main__":
    99    import sys
     10    import myplot
     11    import os
     12    import numpy as np
     13    import netCDF4
     14    import glob
     15
    1016    from optparse import OptionParser    ### to be replaced by argparse
    1117    from api_wrapper import api_onelevel
    1218    from gcm_transformations import call_zrecast
    13     from netCDF4 import Dataset
    14     from myplot import getlschar, separatenames, readslices, adjust_length, whatkindfile, errormess
    15     from os import system
    1619    from planetoplot import planetoplot
    1720    from myscript import getparseroptions
    18     import glob
    19     import numpy as np
    2021
    2122
     
    2324    ### Get options and variables
    2425    parser = OptionParser() ; getparseroptions(parser) ; (opt,args) = parser.parse_args()
    25     if opt.file is None:                                errormess("I want to eat one file at least ! Use pp.py -f name_of_my_file. Or type pp.py -h")
    26     if opt.var is None and opt.anomaly is True:         errormess("Cannot ask to compute anomaly if no variable is set")
    27     if opt.fref is not None and opt.operat is None:     errormess("you must specify an operation when using a reference file")
    28     if opt.operat in ["+","-"] and opt.fref is None:    errormess("you must specifiy a reference file when using inter-file operations")
     26    if opt.file is None:                                myplot.errormess("I want to eat one file at least ! Use pp.py -f name_of_my_file. Or type pp.py -h")
     27    if opt.var is None and opt.anomaly is True:         myplot.errormess("Cannot ask to compute anomaly if no variable is set")
     28    if opt.fref is not None and opt.operat is None:     myplot.errormess("you must specify an operation when using a reference file")
     29    if opt.operat in ["+","-"] and opt.fref is None:    myplot.errormess("you must specifiy a reference file when using inter-file operations")
    2930    if opt.fref is not None and opt.operat is not None and opt.itp is not None: interpref=True
    3031    else:   interpref=False
     
    3536    #############################
    3637    ### Get infos about slices
    37     zeslat  = readslices(opt.slat) ; zeslon  = readslices(opt.slon) ; zesvert = readslices(opt.svert) ; zestime = readslices(opt.stime)
     38    zeslat  = myplot.readslices(opt.slat) ; zeslon  = myplot.readslices(opt.slon) ; zesvert = myplot.readslices(opt.svert) ; zestime = myplot.readslices(opt.stime)
    3839
    3940    reffile = opt.fref
     
    5152    for i in range(len(opt.file)):
    5253
    53       zefiles = separatenames(opt.file[i])
     54      zefiles = myplot.separatenames(opt.file[i])
    5455
    55       typefile = whatkindfile(Dataset(zefiles[0])) ; stralt = None
     56      typefile = myplot.whatkindfile(netCDF4.Dataset(zefiles[0])) ; stralt = None
    5657      if typefile in ["meso"]:         
    57           [lschar,zehour,zehourin] = getlschar ( zefiles[0] )
     58          [lschar,zehour,zehourin] = myplot.getlschar ( zefiles[0] )
    5859          if opt.var is None:  opt.var = ["HGT"] ; opt.nocolorb = True
    5960      elif typefile in ["geo"]:
     
    7778      for j in range(len(opt.var)):
    7879
    79         zevars = separatenames(opt.var[j])
     80        zevars = myplot.separatenames(opt.var[j])
    8081
    81         inputnvert = separatenames(opt.lvl)
     82        inputnvert = myplot.separatenames(opt.lvl)
    8283        if np.array(inputnvert).size == 1:
    8384            zelevel = float(inputnvert[0])
     
    104105          if typefile in ["meso"]:
    105106            if zelevel == 0. and opt.itp == 4:  zelevel = 0.010
    106             if np.array(inputnvert).size == 1:  zesvert = readslices([str(zelevel)])
     107            if np.array(inputnvert).size == 1:  zesvert = myplot.readslices([str(zelevel)])
    107108            ### winds or no winds
    108109            if opt.winds            :  zefields = 'uvmet'
     
    165166        name = planetoplot (zefiles,level=int(zelevel),vertmode=opt.itp,\
    166167                proj=opt.proj,back=opt.back,target=opt.tgt,stride=opt.ste,var=zevars,\
    167                 clb=separatenames(opt.clb),winds=opt.winds,\
     168                clb=myplot.separatenames(opt.clb),winds=opt.winds,\
    168169                addchar=lschar,vmin=zevmin,vmax=zevmax,\
    169170                tile=opt.tile,zoom=opt.zoom,display=opt.display,\
    170171                hole=opt.hole,save=opt.save,\
    171172                anomaly=opt.anomaly,var2=opt.var2,ndiv=opt.ndiv,\
    172                 mult=opt.mult,add=opt.add,zetitle=separatenames(opt.zetitle),\
     173                mult=opt.mult,add=opt.add,zetitle=myplot.separatenames(opt.zetitle),\
    173174                slon=zeslon,slat=zeslat,svert=zesvert,stime=zestime,\
    174175                outputname=opt.out,resolution=opt.res,\
     
    177178                blat=opt.blat,blon=opt.blon,tsat=opt.tsat,flagnolow=opt.nolow,\
    178179                mrate=opt.rate,mquality=opt.quality,trans=opt.trans,zarea=opt.area,axtime=opt.axtime,\
    179                 redope=opt.redope,seevar=opt.seevar,xlab=opt.xlab,ylab=opt.ylab,lbls=separatenames(opt.labels),\
    180                 lstyle=separatenames(opt.linestyle),cross=readslices(opt.mark),markdevil=opt.mdevil,facwind=opt.facwind,\
    181                 trycol=opt.trycol,streamflag=opt.stream,nocolorb=opt.nocolorb,analysis=opt.analysis)
     180                redope=opt.redope,seevar=opt.seevar,xlab=opt.xlab,ylab=opt.ylab,lbls=myplot.separatenames(opt.labels),\
     181                lstyle=myplot.separatenames(opt.linestyle),cross=myplot.readslices(opt.mark),markdevil=opt.mdevil,facwind=opt.facwind,\
     182                trycol=opt.trycol,streamflag=opt.stream,nocolorb=opt.nocolorb,analysis=opt.analysis,monster=opt.monster)
    182183        print 'DONE: '+name
    183         system("rm -f to_be_erased")
     184        os.system("rm -f to_be_erased")
    184185 
    185186    #########################################################
     
    189190    #if typefile not in ["meso","mesoapi"]: name = 'pycommand'
    190191    if opt.save == "gui":    name = 'pycommand'
    191     elif opt.save == "html": system("cat $PYTHONPATH/header.html > anim.html ; cat zepics >> anim.html ; cat $PYTHONPATH/body.html >> anim.html ; rm -rf zepics "+name+" ; mkdir "+name+" ; mv anim.html image*png "+name)
     192    elif opt.save == "html": os.system("cat $PYTHONPATH/header.html > anim.html ; cat zepics >> anim.html ; cat $PYTHONPATH/body.html >> anim.html ; rm -rf zepics "+name+" ; mkdir "+name+" ; mv anim.html image*png "+name)
    192193    f = open(name+'.sh', 'w')
    193194    f.write(command)
Note: See TracChangeset for help on using the changeset viewer.