Changeset 584


Ignore:
Timestamp:
Mar 15, 2012, 10:47:35 AM (13 years ago)
Author:
acolaitis
Message:

PYTHON
======

Modifications to the way the sparse module is written, so that sparse can now be called either in command line (exemple :)

sparse.py -f "/san0/acolmd/IDLplot/smith_opp.sav" -X "lt_opp_T_smith" -Y "t1m_opp_T_smith"

or called directly from a python script :

import sparse
sparse.sparse(oplot=mpl.pyplot,file="/san0/acolmd/IDLplot/smith_opp.sav",xvar="lt_opp_T_smith",yvar="t1m_opp_T_smith",xmin=zxmin,xmax=zxmax,ymin=zymin,ymax=zymax,save="return")

where the inputs of sparse() corresponds to the option, with the exception of 'save="return"' which means that you want to get the graphical objects instead of saving or displaying the graph, and 'oplot=mpl.pyplot' which is the current graphical object in which you want to overplot your sparse data.

It is possible (and may be done in the future) to interface directly sparse.py in pp.py, so that natural gcm/mesoscale plots can be overplotted with sparse data.

File:
1 edited

Legend:

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

    r573 r584  
    1717   from optparse import OptionParser    ### to be replaced by argparse
    1818   from os import system,path
    19    from scipy.io.idl import readsav
    2019   import numpy as np
    21    from myplot import separatenames, definesubplot, errormess, defcolorb, fmtvar, polarinterv, simplinterv, define_proj, readdata, makeplotres
    22    from mymath import min, max, writeascii
    23    import matplotlib as mpl
    24    from matplotlib.pyplot import subplot, figure, plot, scatter, colorbar, show,  title, close, legend, xlabel, ylabel, axis, hist
    25    from matplotlib.cm import get_cmap
    26    from mpl_toolkits.mplot3d import Axes3D
    27    parser = OptionParser()
    28    
     20   from sparse import sparse
     21
     22   parser = OptionParser()
     23
    2924   #############################
    3025   ### Options
     
    5146   parser.add_option('--blon',         action='store',dest='blon',      type="int",     default=None,  help='reference lon [computed]')
    5247   parser.add_option('-b', '--back',   action='store',dest='back',      type="string",  default=None,  help='background image [None]')
    53    parser.add_option('-m', '--min',    action='store',dest='vmin',      type="float",   default=None,  help='bounding minimum value [min]')   
    54    parser.add_option('-M', '--max',    action='store',dest='vmax',      type="float",   default=None,  help='bounding maximum value [max]') 
     48   parser.add_option('-m', '--min',    action='store',dest='vmin',      type="float",   default=None,  help='bounding minimum value [min]')
     49   parser.add_option('-M', '--max',    action='store',dest='vmax',      type="float",   default=None,  help='bounding maximum value [max]')
    5550   parser.add_option('--div',          action='store',dest='ndiv',      type="int",     default=10,    help='number of divisions in histogram [10]')
    5651   parser.add_option('-S', '--save',   action='store',dest='save',      type="string",  default="gui", help='save mode (gui,png,eps,svg,pdf,txt,html,avi) [gui]')
     
    6156   (opt,args) = parser.parse_args()
    6257
     58   sparse(oplot=None,file=opt.file,ftype=opt.ftype,xvar=opt.xvar,yvar=opt.yvar,zvar=opt.zvar,cvar=opt.cvar,xmin=opt.xmin,xmax=opt.xmax,ymin=opt.ymin,ymax=opt.ymax,zmin=opt.zmin,zmax=opt.zmax,cmin=opt.cmin,cmax=opt.cmax,cond=opt.cond,merge=opt.merge,clb=opt.clb,trans=opt.trans,proj=opt.proj,blat=opt.blat,blon=opt.blon,back=opt.back,vmin=opt.vmin,vmax=opt.vmax,ndiv=opt.ndiv,save=opt.save)
     59
     60def sparse(oplot=None,file=None,ftype=None,xvar=None,yvar=None,zvar=None,cvar=None,xmin=None,xmax=None,ymin=None,ymax=None,zmin=None,zmax=None,cmin=None,cmax=None,cond=None,merge=False,clb="def",trans=1.,proj=None,blat=None,blon=None,back=None,vmin=None,vmax=None,ndiv=10,save="gui"):
     61
     62   import sys
     63   from os import system,path
     64   from scipy.io.idl import readsav
     65   import numpy as np
     66   from myplot import separatenames, definesubplot, errormess, defcolorb, fmtvar, polarinterv, simplinterv, define_proj, readdata, makeplotres
     67   from mymath import min, max, writeascii
     68   import matplotlib as mpl
     69   from matplotlib.pyplot import subplot, figure, plot, scatter, colorbar, show,  title, close, legend, xlabel, ylabel, axis, hist
     70   from matplotlib.cm import get_cmap
     71   from mpl_toolkits.mplot3d import Axes3D
     72
     73
    6374   #############################
    6475   ### Load and check data
     
    6778   ### Load and check data
    6879
    69    if opt.file is None:
     80   if file is None:
    7081      print "You must specify at least a file to process with -f."
    7182      exit()
    72    if opt.xvar is None:
     83   if xvar is None:
    7384      print "You must specify at least a 1st field with -X."
    7485      exit()
    75    if opt.proj is not None and opt.yvar is None:
     86   if proj is not None and yvar is None:
    7687      print "Why did you ask a projection with only one variable?"
    7788      exit()
    7889     
    79    filename=separatenames(opt.file)
    80    
    81    #print 'conditions', opt.cond
    82    
    83    print opt.vmax
    84    print opt.vmin
    85    
    86    if opt.cond is None: nslices = 1
    87    else:                nslices = len(opt.cond)
     90   filename=separatenames(file)
     91   
     92   #print 'conditions', cond
     93   
     94   print vmax
     95   print vmin
     96   
     97   if cond is None: nslices = 1
     98   else:                nslices = len(cond)
    8899   numplot   = nslices
    89    if opt.merge is False: numplot = numplot*len(filename)
     100   if merge is False: numplot = numplot*len(filename)
    90101   
    91102   print ' '
    92    if opt.merge is False:
     103   if merge is False:
    93104      print nslices, 'condition(s) and', len(filename), 'file(s) without merging ---->', numplot, 'plot(s)'
    94105   else:
     
    111122   
    112123##### Find file type
    113      if opt.ftype is None:
     124     if ftype is None:
    114125      if filename[k].find('.sav') is not -1:
    115126         all_type[k] ='sav'
     
    126137         errormess('Not suported')
    127138     else:
    128         all_type[k] = opt.ftype       
     139        all_type[k] = ftype       
    129140
    130141##### Read file       
     
    138149       all_data[k] = np.loadtxt(filename[k])
    139150       
    140      all_x[k] = readdata(all_data,all_type[k],k,opt.xvar)
    141      if opt.yvar is not None: all_y[k] = readdata(all_data,all_type[k],k,opt.yvar)
     151     all_x[k] = readdata(all_data,all_type[k],k,xvar)
     152     if yvar is not None: all_y[k] = readdata(all_data,all_type[k],k,yvar)
    142153     else:                    all_y[k] = None
    143      if opt.zvar is not None: all_z[k] = readdata(all_data,all_type[k],k,opt.zvar)
     154     if zvar is not None: all_z[k] = readdata(all_data,all_type[k],k,zvar)
    144155     else:                    all_z[k] = None
    145      if opt.cvar is not None: all_c[k] = readdata(all_data,all_type[k],k,opt.cvar)
     156     if cvar is not None: all_c[k] = readdata(all_data,all_type[k],k,cvar)
    146157     else:                    all_c[k] = None
    147158       
    148      if opt.merge is True and k >=1 :
     159     if merge is True and k >=1 :
    149160          all_x[0] = np.concatenate((all_x[0],all_x[k]))
    150           if opt.yvar is not None: all_y[0] = np.concatenate((all_y[0],all_y[k]))
    151           if opt.zvar is not None: all_z[0] = np.concatenate((all_z[0],all_z[k]))
    152           if opt.cvar is not None: all_c[0] = np.concatenate((all_c[0],all_c[k]))
     161          if yvar is not None: all_y[0] = np.concatenate((all_y[0],all_y[k]))
     162          if zvar is not None: all_z[0] = np.concatenate((all_z[0],all_z[k]))
     163          if cvar is not None: all_c[0] = np.concatenate((all_c[0],all_c[k]))
    153164       
    154165   
     
    158169
    159170## Open a figure and set subplots
    160    fig = figure()
     171   if plot is not None: fig=oplot
     172   else: fig = figure()
    161173   subv,subh = definesubplot(numplot,fig)
    162    palette = get_cmap(name=opt.clb)
     174   palette = get_cmap(name=clb)
    163175   
    164176   
     
    168180       
    169181###### Find which data and which file for plot nplot
    170        if opt.merge is False:
     182       if merge is False:
    171183          index_s = ((nplot)//len(filename))%nslices
    172184          index_f = ((nplot-1)//nslices)%len(filename)
     
    179191###### Select point under conditions defined in -w option
    180192       index = np.isfinite(all_x[index_f])
    181        if opt.cond is not None:
    182            zecond = separatenames(opt.cond[index_s])
    183            #print 'hello', opt.cond[index_s], zecond
     193       if cond is not None:
     194           zecond = separatenames(cond[index_s])
     195           #print 'hello', cond[index_s], zecond
    184196           for i in range(len(zecond)):
    185197              zecondi = zecond[i]
     
    187199                 variable = zecondi[0:zecondi.find('>')]
    188200                 value = float(zecondi[zecondi.find('>')+1:len(zecondi)])
    189                  if opt.merge is True: # ultra moche de reconcatener a chaque fois, mais bon on s'en fout c'est du python
     201                 if merge is True: # ultra moche de reconcatener a chaque fois, mais bon on s'en fout c'est du python
    190202                    zedata = []
    191203                    for k in range(len(filename)):
     
    198210                 variable = zecondi[0:zecondi.find('<')]
    199211                 value = float(zecondi[zecondi.find('<')+1:len(zecondi)])
    200                  if opt.merge is True:
     212                 if merge is True:
    201213                    zedata = []
    202214                    for k in range(len(filename)):
     
    227239       
    228240###### Projection
    229        if opt.proj is not None: # Nota : NEVER TRY TO DO A MESHGRID ON SPARSE DATA. WAY TOO MUCH POINTS.
     241       if proj is not None: # Nota : NEVER TRY TO DO A MESHGRID ON SPARSE DATA. WAY TOO MUCH POINTS.
    230242          wlon = [min(all_x[index_f][index]),max(all_x[index_f][index])]
    231243          wlat = [min(all_y[index_f][index]),max(all_y[index_f][index])]
    232           m = define_proj(opt.proj,wlon,wlat,back=opt.back,blat=opt.blat,blon=opt.blon)
     244          m = define_proj(proj,wlon,wlat,back=back,blat=blat,blon=blon)
    233245          x, y = m(all_x[index_f][index],all_y[index_f][index])
    234246       else:
    235247          x = all_x[index_f][index]
    236           if opt.yvar is not None: y = all_y[index_f][index]                             
     248          if yvar is not None: y = all_y[index_f][index]                             
    237249       
    238250###### Plot: 1D histogram
    239        if opt.yvar is None:
    240           hist(x,bins=opt.ndiv,histtype='step',linewidth=2)
    241           if opt.save == 'txt':
     251       if yvar is None:
     252          hist(x,bins=ndiv,histtype='step',linewidth=2)
     253          if save == 'txt':
    242254              print 'saving file profile'+str(nplot+1)+'.txt'
    243255              writeascii(np.transpose(x),'profile'+str(nplot+1)+'.txt')
    244256###### Plot: 2D cloud
    245        elif opt.zvar is None and opt.cvar is None :
     257       elif zvar is None and cvar is None :
    246258          plot(x,y,'.b')
    247           if opt.save == 'txt':
     259          if save == 'txt':
    248260               print 'saving file profile'+str(nplot+1)+'.txt'
    249261               writeascii(np.transpose(np.array([x,y])),'profile'+str(nplot+1)+'.txt')
    250262###### Plot: 2D cloud with color
    251        elif opt.zvar is None and opt.cvar is not None :
    252           if opt.save == 'txt':
     263       elif zvar is None and cvar is not None :
     264          if save == 'txt':
    253265               print 'saving file profile'+str(nplot+1)+'.txt'
    254266               writeascii(np.transpose(np.array([x,y,all_c[index_f][index]])),'profile'+str(nplot+1)+'.txt')
    255267          scatter(x,y,c=all_c[index_f][index],\
    256           marker='o', edgecolor='None',cmap = palette, alpha=opt.trans, vmin = opt.vmin,vmax = opt.vmax)
     268          marker='o', edgecolor='None',cmap = palette, alpha=trans, vmin = vmin,vmax = vmax)
    257269###### Plot: 3D cloud
    258        elif opt.zvar is not None and opt.cvar is None :
     270       elif zvar is not None and cvar is None :
    259271          ax = fig.add_subplot(subv,subh,nplot+1, projection='3d')
    260272          ax.plot(x,y,all_z[index_f][index],'.b')
     
    263275          ax = fig.add_subplot(subv,subh,nplot+1, projection='3d')
    264276          ax.scatter(x,y,all_z[index_f][index],c=all_c[index_f][index],\
    265           marker='o', edgecolor='None', cmap = palette, alpha=opt.trans,vmin = opt.vmin,vmax = opt.vmax)
     277          marker='o', edgecolor='None', cmap = palette, alpha=trans,vmin = vmin,vmax = vmax)
    266278   
    267279###### Colorbar: http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps?action=AttachFile&do=get&target=colormaps3.png
    268        if opt.clb != 'nobar' and all_c[index_f] is not None and all_z[index_f] is None: # pourquoi la colorbar marche pas en 3d?
     280       if clb != 'nobar' and all_c[index_f] is not None and all_z[index_f] is None: # pourquoi la colorbar marche pas en 3d?
    269281          colorbar( fraction=0.05,pad=0.03,format='%0.2f',\
    270282          extend='neither',spacing='proportional' )
    271283       
    272284###### Plot limits (options --xmin, --xmax, etc ..)
    273        if opt.proj is None:
    274           xlabel(opt.xvar)
    275           ylabel(opt.yvar)
    276           if opt.zvar is None :
    277              if opt.xmin is not None: mpl.pyplot.xlim(xmin=opt.xmin)
     285       if proj is None:
     286          xlabel(xvar)
     287          ylabel(yvar)
     288          if zvar is None :
     289             if xmin is not None: mpl.pyplot.xlim(xmin=xmin)
    278290             else:                    mpl.pyplot.xlim(xmin=min(all_x[index_f][index]))
    279              if opt.xmax is not None: mpl.pyplot.xlim(xmax=opt.xmax)
     291             if xmax is not None: mpl.pyplot.xlim(xmax=xmax)
    280292             else:                    mpl.pyplot.xlim(xmax=max(all_x[index_f][index]))
    281              if opt.yvar is not None:
    282                 if opt.ymin is not None: mpl.pyplot.ylim(ymin=opt.ymin)
     293             if yvar is not None:
     294                if ymin is not None: mpl.pyplot.ylim(ymin=ymin)
    283295                else:                    mpl.pyplot.ylim(ymin=min(all_y[index_f][index]))
    284                 if opt.ymax is not None: mpl.pyplot.ylim(ymax=opt.ymax)
     296                if ymax is not None: mpl.pyplot.ylim(ymax=ymax)
    285297                else:                    mpl.pyplot.ylim(ymax=max(all_y[index_f][index]))
    286298
    287299         
    288        if opt.cond is not None:
    289           title(opt.cond[index_s])
     300       if cond is not None:
     301          title(cond[index_s])
    290302       else:
    291303          title('all point selected')
    292304       
    293305   zeplot = "output"
    294    if opt.save in ['png','eps','svg','pdf']:     makeplotres(zeplot,ext=opt.save)#,res=resolution,pad_inches_value=pad_inches_value,disp=False,ext=save)
    295    elif opt.save == 'gui':                       show()
     306   if save in ['png','eps','svg','pdf']:     makeplotres(zeplot,ext=save)#,res=resolution,pad_inches_value=pad_inches_value,disp=False,ext=save)
     307   elif save == 'gui':                       show()
     308   elif save == 'return':                    return mpl.pyplot
    296309   else:                                         print "INFO: save mode not supported. using gui instead." ; show()
    297310   print ''
Note: See TracChangeset for help on using the changeset viewer.