Changeset 21253


Ignore:
Timestamp:
10/11/16 01:15:17 (8 years ago)
Author:
bdef
Message:

NEW:Some cosmetic changes and addition of mask and log abilities

Location:
issm/trunk-jpl/src/m/plot
Files:
7 edited

Legend:

Unmodified
Added
Removed
  • issm/trunk-jpl/src/m/plot/applyoptions.py

    r19493 r21253  
    3232        #ax=p.gca()
    3333
    34         #font {{{
     34        # {{{ font
    3535        fontsize=options.getfieldvalue('fontsize',8)
    3636        fontweight=options.getfieldvalue('fontweight','normal')
    3737        fontfamily=options.getfieldvalue('fontfamily','sans-serif')
    38         font={
    39                         'fontsize'              :fontsize,
    40                         'fontweight'    :fontweight,
    41                         'family'                        :fontfamily
    42                         }
    43         #}}}
    44 
    45         #title {{{
     38        font={'fontsize'                :fontsize,
     39                                'fontweight'    :fontweight,
     40                                'family'                        :fontfamily}
     41        # }}}
     42        # {{{ title
    4643        if options.exist('title'):
    4744                title=options.getfieldvalue('title')
     
    5956                titlefont['weight']=titlefontweight
    6057                ax.set_title(title,**titlefont)
    61         #}}}
    62                
    63         #xlabel, ylabel, zlabel {{{
     58        # }}}
     59        # {{{ xlabel, ylabel, zlabel
    6460        if options.exist('labelfontsize'):
    6561                labelfontsize=options.getfieldvalue('labelfontsize')
     
    8278        if options.exist('zlabel'):
    8379                ax.set_zlabel(options.getfieldvalue('zlabel'),**labelfont)
    84         #}}}
    85 
    86         #xticks, yticks, zticks (tick locations) {{{
     80        # }}}
     81        # {{{ xticks, yticks, zticks (tick locations)
    8782        if options.exist('xticks'):
    8883                if options.exist('xticklabels'):
     
    10398                else:
    10499                        ax.set_zticks(options.getfieldvalue('zticks'))
    105         #}}}
    106 
    107         #xticklabels,yticklabels,zticklabels {{{
     100        # }}}
     101        # {{{ xticklabels,yticklabels,zticklabels
    108102        if options.getfieldvalue('ticklabels','off')=='off' or options.getfieldvalue('ticklabels',0)==0:
    109103                options.addfielddefault('xticklabels',[])
     
    119113                zticklabels=options.getfieldvalue('zticklabels')
    120114                ax.set_zticklabels(zticklabels)
    121         #}}}
    122 
    123         #ticklabel notation {{{
     115        # }}}
     116        # {{{ ticklabel notation
    124117        #ax.ticklabel_format(style='sci',scilimits=(0,0))
    125         #}}}
    126 
    127         #ticklabelfontsize {{{
     118        # }}}
     119        # {{{ ticklabelfontsize
    128120        if options.exist('ticklabelfontsize'):
    129121                for label in ax.get_xticklabels() + ax.get_yticklabels():
     
    132124                        for label in ax.get_zticklabels():
    133125                                label.set_fontsize(options.getfieldvalue('ticklabelfontsize'))
    134         #}}}
    135 
    136         #view
     126        # }}}
     127        # {{{ view TOFIX
    137128        #if int(md.mesh.dimension) == 3 and options.exist('layer'):
    138129        #       #options.getfieldvalue('view') ?
    139130        #       ax=fig.gca(projection='3d')
    140131        #plt.show()
    141 
    142         #axis {{{
     132        # }}}
     133        # {{{ axis
    143134        if options.exist('axis'):
    144135                if options.getfieldvalue('axis',True)=='off':
     
    147138                        p.setp(ax.get_yticklabels(), visible=False)
    148139        # }}}
    149 
    150         #box
     140        # {{{ box
    151141        if options.exist('box'):
    152142                eval(options.getfieldvalue('box'))
    153 
    154         #xlim, ylim, zlim {{{
     143        # }}}
     144        # {{{ xlim, ylim, zlim
    155145        if options.exist('xlim'):
    156146                ax.set_xlim(options.getfieldvalue('xlim'))
     
    159149        if options.exist('zlim'):
    160150                ax.set_zlim(options.getfieldvalue('zlim'))
    161         #}}}
    162 
    163         #latlon
    164 
    165         #Basinzoom
    166 
    167         #ShowBasins
    168 
    169         #clim {{{
     151        # }}}
     152        # {{{ latlon TODO
     153        # }}}
     154        # {{{ Basinzoom TODO
     155        # }}}
     156        # {{{ ShowBasins TODO
     157        # }}}
     158        # {{{ clim
    170159        if options.exist('clim'):
    171160                lims=options.getfieldvalue('clim')
     
    178167                if len(data)>0: lims=[data.min(),data.max()]
    179168                else: lims=[0,1]
    180         #}}}
    181 
    182         #shading
     169        # }}}
     170        # {{{ shading TODO
    183171        #if options.exist('shading'):
    184 
    185         #grid {{{
     172        # }}}
     173        # {{{ grid
    186174        if options.exist('grid'):
    187175                if 'on' in options.getfieldvalue('grid','on'):
    188176                        ax.grid()
    189         #}}}
    190 
    191         #colormap {{{
     177        # }}}
     178        # {{{ colormap
    192179        # default sequential colormap
    193180        defaultmap=truncate_colormap(mpl.cm.gnuplot2,0.1,0.9,128)
    194181        cmap=options.getfieldvalue('colormap',defaultmap)
    195         norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1])
     182        if options.exist('log'):
     183                norm = mpl.colors.LogNorm(vmin=lims[0], vmax=lims[1])
     184        else:
     185                norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1])
    196186        options.addfield('colornorm',norm)
     187        if options.exist('cmap_set_bad'):
     188                NaNcolor=options.getfieldvalue('cmap_set_bad','w')
     189                cmap.set_bad(NaNcolor,1.0)
    197190        cbar_extend=0
    198191        if options.exist('cmap_set_over'):
     
    205198                cbar_extend+=2
    206199        options.addfield('colormap',cmap)
    207         #}}}
    208 
    209         #contours {{{
     200        # }}}
     201        # {{{ contours
    210202        if options.exist('contourlevels'):
    211203                plot_contour(md,data,options,ax)
    212         #}}}
    213 
    214         #wrapping
    215 
    216         #colorbar {{{
     204        # }}}
     205        # {{{ wrapping TODO
     206        # }}}
     207        # {{{ colorbar
    217208        if options.getfieldvalue('colorbar',1)==1:
    218             if cbar_extend==0:
    219                 extend='neither'
    220             elif cbar_extend==1:
    221                 extend='max'
    222             elif cbar_extend==2:
    223                 extend='min'
    224             elif cbar_extend==3:
    225                 extend='both'
    226             cb = mpl.colorbar.ColorbarBase(ax.cax, cmap=cmap, norm=norm, extend=extend)
    227             if options.exist('alpha'):
    228                 cb.set_alpha(options.getfieldvalue('alpha'))
    229             if options.exist('colorbarnumticks'):
    230                 cb.locator=MaxNLocator(nbins=options.getfieldvalue('colorbarnumticks',5))
    231             else:
    232                 cb.locator=MaxNLocator(nbins=5) # default 5 ticks
    233             if options.exist('colorbartickspacing'):
    234                 locs=npy.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbartickspacing'))
    235                 cb.set_ticks(locs)
    236             if options.exist('colorbarlines'):
    237                 locs=npy.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbarlines'))
    238                 cb.add_lines(locs,['k' for i in range(len(locs))],npy.ones_like(locs))
    239             if options.exist('colorbarlineatvalue'):
    240                 locs=options.getfieldvalue('colorbarlineatvalue')
    241                 colors=options.getfieldvalue('colorbarlineatvaluecolor',['k' for i in range (len(locs))])
    242                 widths=options.getfieldvalue('colorbarlineatvaluewidth',npy.ones_like(locs))
    243                 cb.add_lines(locs,colors,widths)
    244             if options.exist('colorbartitle'):
    245                 if options.exist('colorbartitlepad'):
    246                     cb.set_label(options.getfieldvalue('colorbartitle'),\
    247                             labelpad=options.getfieldvalue('colorbartitlepad'),fontsize=fontsize)
    248                 else:
    249                     cb.set_label(options.getfieldvalue('colorbartitle'),fontsize=fontsize)
    250             cb.ax.tick_params(labelsize=fontsize)
    251             cb.solids.set_rasterized(True)
    252             cb.update_ticks()
    253             cb.set_alpha(1)
    254             cb.draw_all()
    255             plt.sca(ax) # return to original axes control
    256         #}}}
    257 
    258         #expdisp {{{
    259         if options.exist('expdisp'):
    260             filename=options.getfieldvalue('expdisp')
    261             style=options.getfieldvalue('expstyle','k')
    262             linewidth=options.getfieldvalue('explinewidth',1)
    263             for i in xrange(len(filename)):
    264                 filenamei=filename[i]
    265                 stylei=style[i]
    266                 if type(linewidth)==list:
    267                     linewidthi=linewidth[i]
    268                 else:
    269                     linewidthi=linewidth
    270                 expdisp(filenamei,ax,linestyle=stylei,linewidth=linewidthi,unitmultiplier=options.getfieldvalue('unit',1))
    271         #}}}
    272 
    273         #area
    274 
    275         #text {{{
     209                if cbar_extend==0:
     210                        extend='neither'
     211                elif cbar_extend==1:
     212                        extend='max'
     213                elif cbar_extend==2:
     214                        extend='min'
     215                elif cbar_extend==3:
     216                        extend='both'
     217                cb = mpl.colorbar.ColorbarBase(ax.cax, cmap=cmap, norm=norm, extend=extend)
     218                if options.exist('alpha'):
     219                        cb.set_alpha(options.getfieldvalue('alpha'))
     220                if options.exist('colorbarnumticks'):
     221                        cb.locator=MaxNLocator(nbins=options.getfieldvalue('colorbarnumticks',5))
     222                else:
     223                        cb.locator=MaxNLocator(nbins=5) # default 5 ticks
     224                if options.exist('colorbartickspacing'):
     225                        locs=npy.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbartickspacing'))
     226                        cb.set_ticks(locs)
     227                if options.exist('colorbarlines'):
     228                        locs=npy.arange(lims[0],lims[1]+1,options.getfieldvalue('colorbarlines'))
     229                        cb.add_lines(locs,['k' for i in range(len(locs))],npy.ones_like(locs))
     230                if options.exist('colorbarlineatvalue'):
     231                        locs=options.getfieldvalue('colorbarlineatvalue')
     232                        colors=options.getfieldvalue('colorbarlineatvaluecolor',['k' for i in range (len(locs))])
     233                        widths=options.getfieldvalue('colorbarlineatvaluewidth',npy.ones_like(locs))
     234                        cb.add_lines(locs,colors,widths)
     235                if options.exist('colorbartitle'):
     236                        if options.exist('colorbartitlepad'):
     237                                cb.set_label(options.getfieldvalue('colorbartitle'),
     238                                                                                 labelpad=options.getfieldvalue('colorbartitlepad'),fontsize=fontsize)
     239                        else:
     240                                cb.set_label(options.getfieldvalue('colorbartitle'),fontsize=fontsize)
     241                                cb.ax.tick_params(labelsize=fontsize)
     242                                cb.solids.set_rasterized(True)
     243                                cb.update_ticks()
     244                                cb.set_alpha(1)
     245                                cb.draw_all()
     246                plt.sca(ax) # return to original axes control
     247        # }}}
     248        # {{{ expdisp
     249        if options.exist('expdisp'):
     250                filename=options.getfieldvalue('expdisp')
     251                style=options.getfieldvalue('expstyle','k')
     252                linewidth=options.getfieldvalue('explinewidth',1)
     253                for i in xrange(len(filename)):
     254                        filenamei=filename[i]
     255                        stylei=style[i]
     256                        if type(linewidth)==list:
     257                                linewidthi=linewidth[i]
     258                        else:
     259                                linewidthi=linewidth
     260                        expdisp(filenamei,ax,linestyle=stylei,linewidth=linewidthi,unitmultiplier=options.getfieldvalue('unit',1))
     261        # }}}
     262        # {{{ area TODO
     263        # }}}
     264        # {{{ text
    276265        if options.exist('text'):
    277             text=options.getfieldvalue('text')
    278             textx=options.getfieldvalue('textx')
    279             texty=options.getfieldvalue('texty')
    280             textcolor=options.getfieldvalue('textcolor')
    281             textweight=options.getfieldvalue('textweight')
    282             textrotation=options.getfieldvalue('textrotation')
    283             textfontsize=options.getfieldvalue('textfontsize')
    284             for label,x,y,size,color,weight,rotation in zip(text,textx,texty,textfontsize,textcolor,textweight,textrotation):
    285                 ax.text(x,y,label,transform=ax.transAxes,fontsize=size,color=color,weight=weight,rotation=rotation)
    286         #}}}
    287 
    288         #north arrow
    289 
    290         #scale ruler
    291 
    292         #streamlines
    293         if options.exist('streamlines'):
    294             plot_streamlines(md,options,ax)
    295 
    296 
    297         #axis positions
    298 
    299         #figure position
    300 
    301         #axes position
    302 
    303         #showregion
    304 
    305         #flat edges of a partition
    306 
    307         #scatter
    308 
    309         #backgroundcolor
    310 
    311         #figurebackgroundcolor
    312 
    313         #lighting
    314 
    315         #point cloud
    316 
    317         #inset
     266                text=options.getfieldvalue('text')
     267                textx=options.getfieldvalue('textx')
     268                texty=options.getfieldvalue('texty')
     269                textcolor=options.getfieldvalue('textcolor')
     270                textweight=options.getfieldvalue('textweight')
     271                textrotation=options.getfieldvalue('textrotation')
     272                textfontsize=options.getfieldvalue('textfontsize')
     273                for label,x,y,size,color,weight,rotation in zip(text,textx,texty,textfontsize,textcolor,textweight,textrotation):
     274                        ax.text(x,y,label,transform=ax.transAxes,fontsize=size,color=color,weight=weight,rotation=rotation)
     275        # }}}
     276        # {{{ north arrow TODO
     277        # }}}
     278        # {{{ scale ruler TODO
     279        # }}}
     280        # {{{ streamlines TOFIX
     281        if options.exist('streamlines'):
     282                plot_streamlines(md,options,ax)
     283        # }}}
     284        # {{{ axis positions TODO
     285        # }}}
     286        # {{{ figure position TODO
     287        # }}}
     288        # {{{ axes position TODO
     289        # }}}
     290        # {{{ showregion TODO
     291        # }}}
     292        # {{{ flat edges of a partition TODO
     293        # }}}
     294        # {{{ scatter TODO
     295        # }}}
     296        # {{{ backgroundcolor TODO
     297        # }}}
     298        # {{{ figurebackgroundcolor TODO
     299        # }}}
     300        # {{{ lighting TODO
     301        # }}}
     302        # {{{ point cloud TODO
     303        # }}}
     304        # {{{ inset TODO
     305        # }}}
     306       
  • issm/trunk-jpl/src/m/plot/checkplotoptions.py

    r19462 r21253  
    1 import numpy as npy
     1import numpy as np
    22
    33def checkplotoptions(md,options):
     
    1313        '''
    1414
    15 
    16         #units
     15        # {{{ units
    1716        if options.exist('unit'):
    1817                if 'km' in options.getfieldvalue('unit','km'):
     
    2019                elif '100km' in options.getfieldvalue('unit','100km'):
    2120                        options.changefieldvalue('unit',10**-5)
    22        
    23         #density
     21        # }}}
     22        # {{{ density
    2423        if options.exist('density'):
    2524                density=options.getfieldvalue('density')
    2625                options.changefieldvalue('density',abs(ceil(density)))
    27        
    28         #show section
     26        # }}}
     27        # {{{ show section
    2928        if options.exist('showsection'):
    3029                if 'on' in options.getfieldvalue('showsection','on'):
    3130                        options.changefieldvalue('showsection',4)
    32        
    33         #smooth values
     31        # }}}   
     32        # {{{ smooth values
    3433        if options.exist('smooth'):
    3534                if 'on' in options.getfieldvalue('smooth','on'):
    3635                        options.changefieldvalue('smooth',0)
    37 
    38         #contouronly values
     36        # }}}
     37        # {{{ contouronly values
    3938        if options.exist('contouronly'):
    4039                if 'on' in options.getfieldvalue('contouronly','on'):
    4140                        options.changefieldvalue('contouronly',1)
    42 
    43         #colorbar
     41        # }}}
     42        # {{{ colorbar
    4443        if options.exist('colorbar'):
    4544                if 'on' in options.getfieldvalue('colorbar','on'):
     
    4746                elif 'off' in options.getfieldvalue('colorbar','off'):
    4847                        options.changefieldvalue('colorbar',0)
    49 
    50         #text
     48        # }}}
     49        # {{{ text
    5150        if options.exist('text'):
    52 
    5351                # text values (coerce to list for consistent functionality)
    5452                textlist=[]
     
    5654                textlist.extend([text] if isinstance(text,str) else text)
    5755                numtext=len(textlist)
    58 
    5956                # text position
    6057                textpos=options.getfieldvalue('textposition',[0.5,0.5])
    6158                if not isinstance(textpos,list):
    6259                        raise Exception('textposition should be passed as a list')
    63                 if any(isinstance(i,list) for i in textpos):
     60                if any(isinstance(i,list) for i in textpos):
    6461                    textx=[item[0] for item in textpos]
    6562                    texty=[item[1] for item in textpos]
     
    7875                        sizelist=[12]
    7976                if len(sizelist)==1:
    80                         sizelist=npy.tile(sizelist,numtext)
     77                        sizelist=np.tile(sizelist,numtext)
    8178
    8279                # font color
     
    8885                        colorlist=['k']
    8986                if len(colorlist)==1:
    90                         colorlist=npy.tile(colorlist,numtext)
     87                        colorlist=np.tile(colorlist,numtext)
    9188
    9289                # textweight
     
    9895                        weightlist=['normal']
    9996                if len(weightlist)==1:
    100                         weightlist=npy.tile(weightlist,numtext)
     97                        weightlist=np.tile(weightlist,numtext)
    10198
    10299                # text rotation
     
    108105                        rotationlist=[0]
    109106                if len(rotationlist)==1:
    110                                 rotationlist=npy.tile(rotationlist,numtext)
     107                                rotationlist=np.tile(rotationlist,numtext)
    111108
    112109                options.changefieldvalue('text',textlist)
     
    117114                options.changefieldvalue('textweight',weightlist)
    118115                options.changefieldvalue('textrotation',rotationlist)
    119 
    120         #expdisp
     116        # }}}
     117        # {{{ expdisp
    121118        expdispvaluesarray=[]
    122119        expstylevaluesarray=[]
    123120        expstylevalues=[]
    124121        if options.exist('expstyle'):
    125                 expstylevalues=options.getfieldvalue('expstyle')
    126                 if type(expstylevalues)==str:
    127                     expstylevalues=[expstylevalues]
     122                expstylevalues=options.getfieldvalue('expstyle')
     123                if type(expstylevalues)==str:
     124                        expstylevalues=[expstylevalues]
    128125        if options.exist('expdisp'):
    129126                expdispvalues=options.getfieldvalue('expdisp')
    130                 if type(expdispvalues)==str:
    131                     expdispvalues=[expdispvalues]
    132                 for i in npy.arange(len(expdispvalues)):
     127                if type(expdispvalues)==str:
     128                        expdispvalues=[expdispvalues]
     129                for i in np.arange(len(expdispvalues)):
    133130                        expdispvaluesarray.append(expdispvalues[i])
    134131                        if len(expstylevalues)>i:
     
    136133                        else:
    137134                                expstylevaluesarray.append('-k')
    138 
    139135        options.changefieldvalue('expstyle',expstylevaluesarray)
    140136        options.changefieldvalue('expdisp',expdispvaluesarray)
    141 
    142         #latlonnumbering
     137        # }}}
     138        # {{{ latlonnumbering
    143139        if options.exist('latlonclick'):
    144140                if 'on' in options.getfieldvalue('latlonclick','on'):
    145141                        options.changefieldvalue('latlonclick',1)
    146 
    147         #northarrow
     142        # }}}
     143        # {{{ northarrow
    148144        if options.exist('northarrow'):
    149145                if 'on' in options.getfieldvalue('northarrow','on'):
     
    152148                        Ly=max(md.mesh.y)-min(md.mesh.y)
    153149                        options.changefieldvalue('northarrow',[min(md.mesh.x)+1./6.*Lx, min(md.mesh.y)+5./6.*Ly, 1./15.*Ly, 0.25, 1./250.*Ly])
    154 
    155         #scale ruler
     150        # }}}
     151        # {{{ scale ruler
    156152        if options.exist('scaleruler'):
    157153                if 'on' in options.exist('scaleruler','on'):
     
    159155                        Ly=max(md.mesh.y)-min(md.mesh.y)
    160156                        options.changefieldvalue('scaleruler',[min(md.mesh.x)+6./8.*Lx, min(md.mesh.y)+1./10.*Ly, 10**(ceil(log10(Lx)))/5, floor(Lx/100), 5])
    161 
    162         #log scale
     157        # }}}
     158        # {{{ log scale
    163159        if options.exist('log'):
    164                 if options.exist('clim'):
    165                         options.changefieldvalue('clim',log(options.getfieldvalue('clim'))/log(options.getfieldvalue('log')))
    166                 options.changefieldvalue('cutoff',log(options.getfieldvalue('cutoff',1.5))/log(options.getfieldvalue('log')))
    167 
     160                options.changefieldvalue('cutoff',np.log10(options.getfieldvalue('cutoff',1.5))/np.log10(options.getfieldvalue('log')))
     161        # }}}
    168162        return options
  • issm/trunk-jpl/src/m/plot/plot_manager.py

    r20922 r21253  
    3939        #parse options and get a structure of options
    4040        options=checkplotoptions(md,options)
    41 
    4241        #get data to be plotted
    4342        data=options.getfieldvalue('data')
    4443        #add ticklabel has a default option
    4544        options.addfielddefault('ticklabels','on')
    46         #initialize plot handle variable
    47         #handle=None
    4845
    49         # initialize subplot
    50         #p.subplot(nrows,ncols,i,aspect='equal')
    51 
    52         ##basemap plot
     46        # {{{ basemap plot TOFIX
    5347        #if options.exist('basemap'):
    5448        #       plot_basemap(md,data,options,nrows,ncols,i)
    55 
    56         #overlay plot
     49        # }}}
     50        # {{{ overlay plot
    5751        if options.exist('overlay') and overlaysupport:
    5852                plot_overlay(md,data,options,ax)
     
    6054                options.addfielddefault('xlim',[min(md.mesh.x),max(md.mesh.x)])
    6155                options.addfielddefault('ylim',[min(md.mesh.y),max(md.mesh.y)])
    62 
    63         #figure out if this is a special plot
     56        # }}}
     57        # {{{ dealing with special plot (mesh for now)
    6458        if isinstance(data,(str,unicode)):
    65 
    6659                # convert string to lower case for a case-insensitive comparison
    6760                if data.lower()=='mesh':
     
    7669                else:
    7770                        print "WARNING: '%s' is not implemented or is not a valid string for option 'data'" % data
    78 
    79         #elif data in vars(md):
    80         #else:
    81                 #print "'data' not a string, plotting model properties yet to be implemented..."
    82 
    83         #Gridded plot
    84 
    85         #Section plot
    86 
    87         #Profile plot
     71        # }}}
     72        # {{{ Gridded plot TODO
     73        # }}}
     74        # {{{ Section plot TODO
     75        # }}}
     76        # {{{ Profile plot TODO
     77        # }}}
    8878
    8979        #process data and model
    9080        x,y,z,elements,is2d,isplanet=processmesh(md,data,options)
    9181        data2,datatype=processdata(md,data,options)
     82        #plot unit
     83        plot_unit(x,y,z,elements,data2,is2d,isplanet,datatype,options,ax)
     84        #apply all options
     85        applyoptions(md,data2,options,fig,ax)
     86       
     87        #ground overlay on kml plot_unit
     88
     89        # Bits and pieces
     90        #initialize plot handle variable
     91        #handle=None
     92
     93        # initialize subplot
     94        #p.subplot(nrows,ncols,i,aspect='equal')
    9295
    9396        #standard plot
     
    9598        #       p.subplot(nrows,ncols,i,aspect='equal')
    9699
    97         #plot unit
    98         plot_unit(x,y,z,elements,data2,is2d,isplanet,datatype,options,ax)
    99 
    100         #apply all options
    101         applyoptions(md,data2,options,fig,ax)
    102        
    103         #ground overlay on kml plot_unit
     100        #elif data in vars(md):
     101        #else:
     102                #print "'data' not a string, plotting model properties yet to be implemented..."
  • issm/trunk-jpl/src/m/plot/plot_unit.py

    r19432 r21253  
    11from cmaptools import truncate_colormap
    22try:
    3     import pylab as p
    4     import matplotlib as mpl
    5     import matplotlib.pyplot as plt
    6     import numpy as npy
     3        import pylab as p
     4        import matplotlib as mpl
     5        import matplotlib.pyplot as plt
     6        import numpy as np
    77except ImportError:
    8     print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
     8        print "could not import pylab, matplotlib has not been installed, no plotting capabilities enabled"
     9       
     10def plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options,ax):
     11        """
     12        PLOT_UNIT - unit plot, display data
     13       
     14        Usage:
     15        plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
    916
    10 def plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options,ax):
    11     """
    12     PLOT_UNIT - unit plot, display data
     17        See also: PLOTMODEL, PLOT_MANAGER
     18        """
     19       
     20        #edgecolor
     21        edgecolor=options.getfieldvalue('edgecolor','None')
     22
     23        # colormap
     24        # {{{ give number of colorlevels and transparency
     25        colorlevels=options.getfieldvalue('colorlevels',128)
     26        alpha=options.getfieldvalue('alpha',1)
     27        # }}}
     28        # {{{ define wich colormap to use
     29        try:
     30                defaultmap=plt.cm.viridis
     31        except AttributeError:
     32                print("Viridis can't be found (probably too old Matplotlib) reverting to gnuplot colormap")
     33                defaultmap=truncate_colormap(mpl.cm.gnuplot2,0.1,0.9,128)
     34        cmap=options.getfieldvalue('colormap',defaultmap)
     35        if options.exist('cmap_set_over'):
     36                over=options.getfieldvalue('cmap_set_over','0.5')
     37                cmap.set_over(over)
     38        if options.exist('cmap_set_under'):
     39                under=options.getfieldvalue('cmap_set_under','0.5')
     40                cmap.set_under(under)
     41        # }}}   
     42        # {{{ Get the colormap limits
     43        if options.exist('clim'):
     44                lims=options.getfieldvalue('clim',[np.amin(data),np.amax(data)])
     45        elif options.exist('caxis'):
     46                lims=options.getfieldvalue('caxis',[np.amin(data),np.amax(data)])
     47        else:
     48                if np.amin(data)==np.amax(data):
     49                        lims=[np.amin(data)-0.5,np.amax(data)+0.5]
     50                else:
     51                        lims=[np.amin(data),np.amax(data)]
     52        # }}}
     53        # {{{ Set the spread of the colormap (default is normal
     54        if options.exist('log'):
     55                norm = mpl.colors.LogNorm(vmin=lims[0], vmax=lims[1])
     56        else:
     57                norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1])
     58        # }}}
     59       
     60        # Plot depending on the datatype
     61        # {{{ data are on elements
     62        if datatype==1:
     63                if is2d:
     64                        if options.exist('mask'):
     65                                triangles=mpl.tri.Triangulation(x,y,elements,data.mask)
     66                        else:
     67                                triangles=mpl.tri.Triangulation(x,y,elements)
     68                        tri=ax.tripcolor(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,edgecolors=edgecolor)
     69                else:
     70                        raise ValueError('plot_unit error: 3D element plot not supported yet')
     71                return
     72        # }}}
     73        # {{{ data are on nodes
     74        elif datatype==2:
     75                if is2d:
     76                        if options.exist('mask'):
     77                                EltMask=np.asarray([np.any(np.in1d(index,np.where(data.mask))) for index in elements])
     78                                triangles=mpl.tri.Triangulation(x,y,elements,EltMask)
     79                        else:
     80                                triangles=mpl.tri.Triangulation(x,y,elements)
     81                        ax.tricontourf(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha)
     82#                       ax.tricontourf(triangles,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,extend='both')
     83                        if edgecolor != 'None':
     84                                ax.triplot(x,y,elements,color=edgecolor)
     85                else:
     86                        raise ValueError('plot_unit error: 3D node plot not supported yet')
     87                return
     88        # }}}
     89        # {{{ plotting quiver (TODO)
     90        elif datatype==3:
     91                vx=data[:,0]
     92                vy=data[:,1]
     93                #TODO write plot_quiver.py to handle this here
     94                color=np.sqrt(vx**2+vy**2)
     95                scale=options.getfieldvalue('scale',1000)
     96                width=options.getfieldvalue('width',0.005*(np.amax(x)-np.amin(y)))
     97                headwidth=options.getfieldvalue('headwidth',3)
     98                headlength=options.getfieldvalue('headlength',5)
     99                Q=ax.quiver(x,y,vx,vy,color,cmap=cmap,norm=norm,scale=scale,
     100                                                        width=width,headwidth=headwidth,headlength=headlength)
     101                return
     102        # }}}
     103        # {{{ plotting P1 Patch (TODO)
     104        elif datatype==4:
     105                print 'plot_unit message: P1 patch plot not implemented yet'
     106                return
     107        # }}}
     108        # {{{ plotting P0 Patch (TODO)
     109        elif datatype==5:
     110                print 'plot_unit message: P0 patch plot not implemented yet'
     111                return
     112        # }}}
     113        else:
     114                raise ValueError('datatype=%d not supported' % datatype)
    13115   
    14         Usage:
    15                 plot_unit(x,y,z,elements,data,is2d,isplanet,datatype,options)
    16    
    17         See also: PLOTMODEL, PLOT_MANAGER
    18     """
    19    
    20     #edgecolor
    21     edgecolor=options.getfieldvalue('edgecolor','None')
    22    
    23     #number of colorlevels for plots
    24     colorlevels=options.getfieldvalue('colorlevels',128)
    25    
    26     alpha=options.getfieldvalue('alpha',1)
    27    
    28     #colormap
    29     # default sequential colormap
    30     defaultmap=truncate_colormap(mpl.cm.gnuplot2,0.1,0.9,128)
    31     cmap=options.getfieldvalue('colormap',defaultmap)
    32     if options.exist('cmap_set_over'):
    33         over=options.getfieldvalue('cmap_set_over','0.5')
    34         cmap.set_over(over)
    35     if options.exist('cmap_set_under'):
    36         under=options.getfieldvalue('cmap_set_under','0.5')
    37         cmap.set_under(under)
    38    
    39     #normalize colormap if clim/caxis specified
    40     if options.exist('clim'):
    41         lims=options.getfieldvalue('clim',[npy.amin(data),npy.amax(data)])
    42     elif options.exist('caxis'):
    43         lims=options.getfieldvalue('caxis',[npy.amin(data),npy.amax(data)])
    44     else:
    45         if npy.amin(data)==npy.amax(data):
    46             lims=[npy.amin(data)-0.5,npy.amax(data)+0.5]
    47         else:
    48             lims=[npy.amin(data),npy.amax(data)]
    49     norm = mpl.colors.Normalize(vmin=lims[0], vmax=lims[1])
    50     if datatype==1:
    51        #element plot
    52         if is2d:
    53             tri=ax.tripcolor(x,y,elements,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,edgecolors=edgecolor)
    54         else:
    55             raise ValueError('plot_unit error: 3D element plot not supported yet')
    56         return
    57    
    58     elif datatype==2:
    59         #node plot
    60         if is2d:
    61             tri=ax.tricontourf(x,y,elements,data,colorlevels,cmap=cmap,norm=norm,alpha=alpha,extend='both')
    62             if edgecolor != 'None':
    63                 ax.triplot(x,y,elements,color=edgecolor)
    64         else:
    65             raise ValueError('plot_unit error: 3D node plot not supported yet')
    66         return
    67    
    68     elif datatype==3:
    69         vx=data[:,0]
    70         vy=data[:,1]
    71         #TODO write plot_quiver.py to handle this here
    72         color=npy.sqrt(vx**2+vy**2)
    73         scale=options.getfieldvalue('scale',1000)
    74         width=options.getfieldvalue('width',0.005*(npy.amax(x)-npy.amin(y)))
    75         headwidth=options.getfieldvalue('headwidth',3)
    76         headlength=options.getfieldvalue('headlength',5)
    77         Q=ax.quiver(x,y,vx,vy,color,cmap=cmap,norm=norm,scale=scale,
    78                 width=width,headwidth=headwidth,headlength=headlength)
    79         return
    80    
    81     elif datatype==4:
    82         #P1 patch plot
    83         print 'plot_unit message: P1 patch plot not implemented yet'
    84         return
    85    
    86     elif datatype==5:
    87         print 'plot_unit message: P0 patch plot not implemented yet'
    88         return
    89    
    90     else:
    91         raise ValueError('datatype=%d not supported' % datatype)
    92    
  • issm/trunk-jpl/src/m/plot/plotmodel.py

    r19424 r21253  
    1313
    1414def plotmodel(md,*args):
    15         '''
    16         at command prompt, type 'plotdoc' for additional documentation
     15        '''     at command prompt, type 'plotdoc' for additional documentation
    1716        '''
    1817
  • issm/trunk-jpl/src/m/plot/processdata.py

    r19434 r21253  
    11from math import isnan
    2 import numpy as npy
     2import numpy as np
    33
    44def processdata(md,data,options):
    5     """
    6     PROCESSDATA - process data to be plotted
     5        """
     6        PROCESSDATA - process data to be plotted
     7       
     8        datatype = 1 -> elements
     9        datatype = 2 -> nodes
     10        datatype = 3 -> node quivers
     11        datatype = 4 -> patch
     12       
     13        Usage:
     14        data,datatype=processdata(md,data,options);
     15       
     16        See also: PLOTMODEL, PROCESSMESH
     17        """
     18        # {{{ Initialisation and grabbing auxiliaries
     19        # check format
     20        if (len(data)==0 or (len(data)==1 and not isinstance(data,dict) and isnan(data).all())):
     21                raise ValueError("processdata error message: 'data' provided is empty")
     22        if 'numberofvertices2d' in dir(md.mesh):
     23                numberofvertices2d=md.mesh.numberofvertices2d
     24                numberofelements2d=md.mesh.numberofelements2d
     25        else:
     26                numberofvertices2d=np.nan
     27                numberofelements2d=np.nan
     28        procdata=np.copy(data)
     29        #initialize datatype
     30        datatype=0
     31        # init patches
     32        # get datasize
     33        if np.ndim(procdata)==1:
     34                datasize=np.array([len(procdata),1])
     35        else:
     36                datasize=np.shape(procdata)
     37                if len(datasize)>2:
     38                        raise ValueError('data passed to plotmodel has more than 2 dimensions; check that column vectors are rank-1')
     39  # }}}     
     40        # {{{ process NaN's if any
     41        nanfill=options.getfieldvalue('nan',-9999)
     42        if np.any(np.isnan(procdata)):
     43                lb=np.nanmin(procdata)
     44                ub=np.nanmax(procdata)
     45                if lb==ub:
     46                        lb=lb-0.5
     47                        ub=ub+0.5
     48                        nanfill=lb-1
     49                        #procdata[np.isnan(procdata)]=nanfill
     50                procdata=np.ma.array(procdata,mask=np.isnan(procdata))
     51                options.addfielddefault('clim',[lb,ub])
     52                options.addfielddefault('cmap_set_under','1')
     53                print "WARNING: nan's treated as", nanfill, "by default.  Change using pairoption 'nan',nan_fill_value in plotmodel call"
     54  # }}} 
     55        # {{{ log
     56        if options.exist('log'):
     57                cutoff=options.getfieldvalue('log',1)
     58                procdata[np.where(procdata<cutoff)]=cutoff
     59        # }}}
     60        # {{{ quiver plot
     61        if datasize[1]>1 and datasize[0]!= md.mesh.numberofvertices+1:
     62                if datasize[0]==md.mesh.numberofvertices and datasize[1]==2:
     63                        datatype=3
     64                else:
     65                        raise ValueError('plotmodel error message: data should have two columns of length md.mesh.numberofvertices for a quiver plot')
     66        # }}} 
     67        # {{{ element data
     68        if datasize[0]==md.mesh.numberofelements and datasize[1]==1:
     69                print'ploting elements'
     70                #initialize datatype if non patch
     71                if datatype!=4 and datatype!=5:
     72                        datatype=1
     73                # {{{mask
     74                if options.exist('mask'):
     75                        flags=options.getfieldvalue('mask')
     76                        hide=np.invert(flags)
     77                        if np.size(flags)==md.mesh.numberofvertices:
     78                                EltMask=np.asarray([np.any(np.in1d(index,np.where(hide))) for index in md.mesh.elements-1])
     79                                procdata=np.ma.array(procdata,mask=EltMask)
     80                                options.addfielddefault('cmap_set_bad','w')
     81                        elif np.size(flags)==md.mesh.numberofelements:
     82                                procdata=np.ma.array(procdata,mask=hide)
     83                                options.addfielddefault('cmap_set_bad','w')
     84                        else:
     85                                print('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements')
     86                # }}} 
     87        # }}} 
     88        # {{{ node data
     89        if datasize[0]==md.mesh.numberofvertices and datasize[1]==1:
     90                print'ploting nodes'
     91                datatype=2
     92                # {{{ Mask
     93                if options.exist('mask'):
     94                        flags=options.getfieldvalue('mask')
     95                        hide=np.invert(flags)
     96                        if np.size(flags)==md.mesh.numberofvertices:
     97                                procdata=np.ma.array(procdata,mask=hide)
     98                                options.addfielddefault('cmap_set_bad','w')
     99                        elif np.size(flags)==md.mesh.numberofelements:
     100                                NodeMask=np.zeros(np.shape(md.mesh.x),dtype=bool)
     101                                HideElt=md.mesh.elements[np.where(hide)[0]]-1
     102                                NodeMask[HideElt]=True
     103                                procdata=np.ma.array(procdata,mask=NodeMask)
     104                                options.addfielddefault('cmap_set_bad','w')
     105                        else:
     106                                print('plotmodel warning: mask length not supported yet (supported length are md.mesh.numberofvertices and md.mesh.numberofelements')
     107          # }}} 
     108        # }}} 
     109        # {{{ spc time series
     110        if datasize[0]==md.mesh.numberofvertices+1:
     111                datatype=2
     112                spccol=options.getfieldvalue('spccol',0)
     113                print 'multiple-column spc field; specify column to plot using option "spccol"'
     114                print 'column ', spccol, ' plotted for time: ', procdata[-1,spccol]
     115                procdata=procdata[0:-1,spccol]
    7116   
    8         datatype = 1 -> elements
    9         datatype = 2 -> nodes
    10         datatype = 3 -> node quivers
    11         datatype = 4 -> patch
    12    
    13         Usage:
    14                 data,datatype=processdata(md,data,options);
    15    
    16         See also: PLOTMODEL, PROCESSMESH
    17     """
    18    
    19     #check format
    20     if (len(data)==0 or (len(data)==1 and not isinstance(data,dict) and isnan(data).all())):
    21         raise ValueError("processdata error message: 'data' provided is empty")
    22    
    23     #needed later on
    24     if 'numberofvertices2d' in dir(md.mesh):
    25         numberofvertices2d=md.mesh.numberofvertices2d
    26         numberofelements2d=md.mesh.numberofelements2d
    27     else:
    28         numberofvertices2d=npy.nan
    29         numberofelements2d=npy.nan
    30    
    31     procdata=npy.copy(data)
    32    
    33     #process patch
    34    
    35     #initialize datatype
    36     datatype=0
    37    
    38     #get datasize
    39     if npy.ndim(procdata)==1:
    40         datasize=npy.array([len(procdata),1])
    41     else:
    42         datasize=npy.shape(procdata)
    43         if len(datasize)>2:
    44             raise ValueError('data passed to plotmodel has more than 2 dimensions; check that column vectors are rank-1')
    45    
    46     #process NaN's if any
    47     nanfill=options.getfieldvalue('nan',-9999)
    48     if npy.any(npy.isnan(procdata)):
    49         lb=npy.min(data[~npy.isnan(data)])
    50         ub=npy.max(data[~npy.isnan(data)])
    51         if lb==ub:
    52             lb=lb-0.5
    53             ub=ub+0.5
    54             nanfill=lb-1
    55         procdata[npy.isnan(procdata)]=nanfill
    56         options.addfielddefault('clim',[lb,ub])
    57         options.addfielddefault('cmap_set_under','1')
    58         print "WARNING: nan's treated as", nanfill, "by default.  Change using pairoption 'nan',nan_fill_value in plotmodel call"
    59    
    60     #quiver plot
    61     if datasize[1]>1 and datasize[0]!= md.mesh.numberofvertices+1:
    62         if datasize[0]==md.mesh.numberofvertices and datasize[1]==2:
    63             datatype=3
    64         else:
    65             raise ValueError('plotmodel error message: data should have two columns of length md.mesh.numberofvertices for a quiver plot')
    66    
    67     #non-patch processing
    68    
    69     #element data
    70     if datasize[0]==md.mesh.numberofelements and datasize[1]==1:
    71        
    72         #initialize datatype if non patch
    73         if datatype!=4 and datatype!=5:
    74             datatype=1
    75    
    76         #mask?
    77    
    78         #log?
    79    
    80     #node data
    81     if datasize[0]==md.mesh.numberofvertices and datasize[1]==1:
    82         datatype=2
    83    
    84     #spc time series?
    85     if datasize[0]==md.mesh.numberofvertices+1:
    86         datatype=2
    87         spccol=options.getfieldvalue('spccol',0)
    88         print 'multiple-column spc field; specify column to plot using option "spccol"'
    89         print 'column ', spccol, ' plotted for time: ', procdata[-1,spccol]
    90         procdata=procdata[0:-1,spccol]
    91    
    92         #mask?
    93    
    94         #log?
     117                #mask?
    95118   
    96119    #layer projection?
    97120   
    98121    #control arrow density if quiver plot
    99    
    100     #convert rank-2 array to rank-1
    101     if npy.ndim(procdata)==2 and npy.shape(procdata)[1]==1:
    102         procdata=procdata.reshape(-1,)
    103    
    104     #if datatype is still zero, error out
    105     if datatype==0:
    106         raise ValueError("processdata error: data provided not recognized or not supported")
    107     else:
    108         return procdata, datatype
     122        # }}} 
     123        # {{{ convert rank-2 array to rank-1
     124        if np.ndim(procdata)==2 and np.shape(procdata)[1]==1:
     125                procdata=procdata.reshape(-1,)
     126        # }}} 
     127        # {{{ if datatype is still zero, error out
     128        if datatype==0:
     129                raise ValueError("processdata error: data provided not recognized or not supported")
     130        else:
     131                return procdata, datatype
     132  # }}} 
  • issm/trunk-jpl/src/m/plot/processmesh.py

    r17687 r21253  
    11from math import isnan
    2 import MatlabFuncs as m
    32import numpy as npy
    43
     
    1312        """
    1413
    15         #some checks
     14        # {{{ check mesh size parameters
    1615        if md.mesh.numberofvertices==0:
    1716                raise ValueError('processmesh error: mesh is empty')
    1817        if md.mesh.numberofvertices==md.mesh.numberofelements:
    1918                raise ValueError('processmesh error: the number of elements is the same as the number of nodes')
    20 
     19        # }}}
     20        # {{{ treating non data plots mesh
    2121        if len(data)==0 or not isinstance(data,dict):
    22                
    2322                if 'latlon' not in options.getfieldvalue('coord','xy').lower(): #convert to lower case for comparison
    24                         x=md.mesh.x
    25                         if 'x2d' in dir(md.mesh): x2d=md.mesh.x2d
    26                         y=md.mesh.y
    27                         if 'y2d' in dir(md.mesh): y2d=md.mesh.x2d
     23                        try:
     24                                x=md.mesh.x2d
     25                        except AttributeError:
     26                                x=md.mesh.x
     27                        try:
     28                                y=md.mesh.x2d
     29                        except AttributeError:                         
     30                                y=md.mesh.y
    2831                else:
    2932                        x=md.mesh.long
    3033                        y=md.mesh.lat
    31 
    32                 if 'z' in dir(md.mesh):
     34                try:
    3335                        z=md.mesh.z
    34                 else:
     36                except AttributeError:
    3537                        z=npy.zeros_like(md.mesh.x)
    3638               
    37                 if 'elements2d' in dir(md.mesh):
    38                         elements2d=md.mesh.elements2d
    39                         elements2d=elements2d-1  # subtract one since python indexes from zero
    40                 elements=md.mesh.elements
    41                 elements=elements-1
     39                try:
     40                        elements2d=md.mesh.elements2d-1
     41                except AttributeError:
     42                        elements=md.mesh.elements-1
    4243
    4344                #is it a 2D plot?
    44                 if md.mesh.dimension()==2:
     45                if md.mesh.dimension()==2 or options.getfieldvalue('layer',0)>=1:
    4546                        is2d=1
    4647                else:
    47                         if options.getfieldvalue('layer',0)>=1:
    48                                 is2d=1
    49                         else:
    50                                 is2d=0
     48                        is2d=0
    5149
    5250                #layer projection?
     
    5452                         if 'latlon' in options.getfieldvalue('coord','xy').lower():
    5553                                 raise ValueError('processmesh error: cannot work with 3D mesh in lat-lon coords')
    56                         #we modify the mesh temporarily to a 2D mesh from which the 3D mesh was extruded
    57                          x=x2d
    58                          y=y2d
    59                          z=zeros(size(x2d))
    60                          elements=elements2d
    61        
     54                         #we modify the mesh temporarily to a 2D mesh from which the 3D mesh was extruded
     55                   #Basile: does not seem necessary as we already picked x as x2d
     56                   # x=x2d
     57                         # y=y2d
     58                         # z=zeros(size(x2d))
     59                         # elements=elements2d
    6260        else:
    6361                #Process mesh for plotting
Note: See TracChangeset for help on using the changeset viewer.