source: trunk/MESOSCALE_DEV/PLOT/PYTHON/mylib/myplot.py @ 214

Last change on this file since 214 was 207, checked in by aslmd, 14 years ago

MESOSCALE: A GENERAL CLEAN-UP FOLLOWING UPDATING THE USER MANUAL. EVERYTHING ESSENTIAL IS IN MESOSCALE (much lighter than before). EVERYTHING FOR DEVELOPPERS OR EXPERTS IS IN MESOSCALE_DEV.

File size: 11.6 KB
Line 
1def latinterv (area):
2        if   area == "Europe": 
3                wlat = [20.,80.]
4                wlon = [-50.,50.]
5        elif area == "Central_America":
6                wlat = [-10.,40.]
7                wlon = [230.,300.]
8        elif area == "Africa":
9                wlat = [-20.,50.]
10                wlon = [-50.,50.]
11        elif area == "Whole":
12                wlat = [-90.,90.]
13                wlon = [-180.,180.]
14        elif area == "Southern_Hemisphere":
15                wlat = [-90.,60.]
16                wlon = [-180.,180.]
17        elif area == "Northern_Hemisphere":
18                wlat = [-60.,90.]
19                wlon = [-180.,180.]
20        elif area == "Tharsis":
21                wlat = [-30.,60.]
22                wlon = [-170.,-10.]
23        elif area == "Whole_No_High":
24                wlat = [-60.,60.]
25                wlon = [-180.,180.]
26        elif area == "Chryse":
27                wlat = [-60.,60.]
28                wlon = [-60.,60.]
29        elif area == "North_Pole":
30                wlat = [60.,90.]
31                wlon = [-180.,180.]
32        elif area == "Close_North_Pole":
33                wlat = [75.,90.]
34                wlon = [-180.,180.]
35        return wlon,wlat
36
37#def landers (map)
38#    map.plot(blue_calf_lon,blue_calf_lat, 'gs')
39#    return
40
41def getlschar ( namefile ):
42    #### strangely enough this does not work for api or ncrcat results!
43    from netCDF4 import Dataset
44    from timestuff import sol2ls
45    nc  = Dataset(namefile)
46    if 'Times' in nc.variables and 'vert' not in nc.variables:
47        zetime = nc.variables['Times'][0]
48        zetimestart = getattr(nc, 'START_DATE')
49        zeday = int(zetime[8]+zetime[9]) - int(zetimestart[8]+zetimestart[9])
50        if zeday < 0:    lschar=""  ## might have crossed a month... fix soon
51        else:            lschar="_Ls"+str( int( sol2ls ( getattr( nc, 'JULDAY' ) + zeday ) ) )
52        ###
53        zetime2 = nc.variables['Times'][1]
54        one  = int(zetime[11]+zetime[12]) + int(zetime[14]+zetime[15])/37.
55        next = int(zetime2[11]+zetime2[12]) + int(zetime2[14]+zetime2[15])/37. 
56        zehour    = one
57        zehourin  = abs ( next - one )
58    else:
59        lschar=""
60        zehour = 0
61        zehourin = 1 
62    return lschar, zehour, zehourin
63
64def getprefix (nc):
65    prefix = 'LMD_MMM_'
66    prefix = prefix + 'd'+str(getattr(nc,'GRID_ID'))+'_'
67    prefix = prefix + str(int(getattr(nc,'DX')/1000.))+'km_'
68    return prefix
69
70def getproj (nc):
71    map_proj = getattr(nc, 'MAP_PROJ')
72    cen_lat  = getattr(nc, 'CEN_LAT')
73    if map_proj == 2:
74        if cen_lat > 10.:   
75            proj="npstere"
76            print "NP stereographic polar domain" 
77        else:           
78            proj="spstere"
79            print "SP stereographic polar domain"
80    elif map_proj == 1: 
81        print "lambert projection domain" 
82        proj="lcc"
83    elif map_proj == 3: 
84        print "mercator projection"
85        proj="merc"
86    else:
87        proj="merc"
88    return proj   
89
90def ptitle (name):
91    from matplotlib.pyplot import title
92    title(name)
93    print name
94
95def simplinterv (lon2d,lat2d):
96    import numpy as np
97    return [[np.min(lon2d),np.max(lon2d)],[np.min(lat2d),np.max(lat2d)]]
98
99def wrfinterv (lon2d,lat2d):
100    nx = len(lon2d[0,:])-1
101    ny = len(lon2d[:,0])-1
102    return [[lon2d[0,0],lon2d[nx,ny]],[lat2d[0,0],lat2d[nx,ny]]]
103
104def makeplotpngres (filename,res,pad_inches_value=0.25,folder='',disp=True):
105    import  matplotlib.pyplot as plt
106    res = int(res)
107    name = filename+"_"+str(res)+".png"
108    if folder != '':      name = folder+'/'+name
109    plt.savefig(name,dpi=res,bbox_inches='tight',pad_inches=pad_inches_value)
110    if disp:              display(name)         
111    return
112
113def makeplotpng (filename,pad_inches_value=0.25,minres=100.,folder=''):
114    makeplotpngres(filename,minres,     pad_inches_value=pad_inches_value,folder=folder)
115    makeplotpngres(filename,minres+200.,pad_inches_value=pad_inches_value,folder=folder,disp=False)
116    return
117
118def dumpbdy (field):
119    nx = len(field[0,:])-1
120    ny = len(field[:,0])-1
121    return field[5:ny-5,5:nx-5]
122
123def getcoord2d (nc,nlat='XLAT',nlon='XLONG',is1d=False):
124    import numpy as np
125    if is1d:
126        lat = nc.variables[nlat][:]
127        lon = nc.variables[nlon][:]
128        [lon2d,lat2d] = np.meshgrid(lon,lat)
129    else:
130        lat = nc.variables[nlat][0,:,:]
131        lon = nc.variables[nlon][0,:,:]
132        [lon2d,lat2d] = [lon,lat]
133    return lon2d,lat2d
134
135def smooth (field, coeff):
136        ## actually blur_image could work with different coeff on x and y
137        if coeff > 1:   result = blur_image(field,int(coeff))
138        else:           result = field
139        return result
140
141def gauss_kern(size, sizey=None):
142        import numpy as np
143        ## FROM COOKBOOK http://www.scipy.org/Cookbook/SignalSmooth     
144        # Returns a normalized 2D gauss kernel array for convolutions
145        size = int(size)
146        if not sizey:
147                sizey = size
148        else:
149                sizey = int(sizey)
150        x, y = np.mgrid[-size:size+1, -sizey:sizey+1]
151        g = np.exp(-(x**2/float(size)+y**2/float(sizey)))
152        return g / g.sum()
153
154def blur_image(im, n, ny=None) :
155        from scipy.signal import convolve
156        ## FROM COOKBOOK http://www.scipy.org/Cookbook/SignalSmooth
157        # blurs the image by convolving with a gaussian kernel of typical size n.
158        # The optional keyword argument ny allows for a different size in the y direction.
159        g = gauss_kern(n, sizey=ny)
160        improc = convolve(im, g, mode='same')
161        return improc
162
163def getwinds (nc,charu='Um',charv='Vm'):
164    import numpy as np
165    u = nc.variables[charu]
166    v = nc.variables[charv]
167    if charu == 'U': u = u[:, :, :, 0:len(u[0,0,0,:])-1]
168    if charv == 'V': v = v[:, :, 0:len(v[0,0,:,0])-1, :]
169                     ### ou alors prendre les coordonnees speciales
170    return u,v
171
172def vectorfield (u, v, x, y, stride=3, scale=15., factor=250., color='black', csmooth=1, key=True):
173    ## scale regle la reference du vecteur
174    ## factor regle toutes les longueurs (dont la reference). l'AUGMENTER pour raccourcir les vecteurs.
175    import  matplotlib.pyplot               as plt
176    import  numpy                           as np
177    posx = np.min(x) - np.std(x) / 10.
178    posy = np.min(y) - np.std(y) / 10.
179    u = smooth(u,csmooth)
180    v = smooth(v,csmooth)
181    widthvec = 0.003 #0.005 #0.003
182    q = plt.quiver( x[::stride,::stride],\
183                    y[::stride,::stride],\
184                    u[::stride,::stride],\
185                    v[::stride,::stride],\
186                    angles='xy',color=color,\
187                    scale=factor,width=widthvec )
188    if color in ['white','yellow']:     kcolor='black'
189    else:                               kcolor=color
190    if key: p = plt.quiverkey(q,posx,posy,scale,\
191                   str(int(scale)),coordinates='data',color=kcolor,labelpos='S',labelsep = 0.03)
192    return 
193
194def display (name):
195    from os import system
196    system("display "+name+" > /dev/null 2> /dev/null &")
197    return name
198
199def findstep (wlon):
200    steplon = int((wlon[1]-wlon[0])/4.)  #3
201    step = 120.
202    while step > steplon and step > 15. :       step = step / 2.
203    if step <= 15.:
204        while step > steplon and step > 5.  :   step = step - 5.
205    if step <= 5.:
206        while step > steplon and step > 1.  :   step = step - 1.
207    if step <= 1.:
208        step = 1. 
209    return step
210
211def define_proj (char,wlon,wlat,back="."):
212    from    mpl_toolkits.basemap            import Basemap
213    import  numpy                           as np
214    import  matplotlib                      as mpl
215    meanlon = 0.5*(wlon[0]+wlon[1])
216    meanlat = 0.5*(wlat[0]+wlat[1])
217    if   wlat[0] >= 80.:   blat =  40. 
218    elif wlat[0] <= -80.:  blat = -40. 
219    else:                  blat = wlat[0]
220    h = 50.  ## en km
221    radius = 3397200.
222    if   char == "cyl":     m = Basemap(rsphere=radius,projection='cyl',\
223                              llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1])
224    elif char == "moll":    m = Basemap(rsphere=radius,projection='moll',lon_0=meanlon)
225    elif char == "ortho":   m = Basemap(rsphere=radius,projection='ortho',lon_0=meanlon,lat_0=meanlat)
226    elif char == "lcc":     m = Basemap(rsphere=radius,projection='lcc',lat_1=meanlat,lat_0=meanlat,lon_0=meanlon,\
227                              llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1])
228    elif char == "npstere": m = Basemap(rsphere=radius,projection='npstere', boundinglat=blat, lon_0=0.)
229    elif char == "spstere": m = Basemap(rsphere=radius,projection='spstere', boundinglat=blat, lon_0=0.)
230    elif char == "nplaea":  m = Basemap(rsphere=radius,projection='nplaea', boundinglat=wlat[0], lon_0=meanlon)
231    elif char == "laea":    m = Basemap(rsphere=radius,projection='laea',lon_0=meanlon,lat_0=meanlat,lat_ts=meanlat,\
232                              llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1])
233    elif char == "nsper":   m = Basemap(rsphere=radius,projection='nsper',lon_0=meanlon,lat_0=meanlat,satellite_height=h*1000.)
234    elif char == "merc":    m = Basemap(rsphere=radius,projection='merc',lat_ts=0.,\
235                              llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1])
236    fontsizemer = int(mpl.rcParams['font.size']*3./4.)
237    if char in ["cyl","lcc","merc","nsper","laea"]:   step = findstep(wlon)
238    else:                                             step = 10.
239    m.drawmeridians(np.r_[-180.:180.:step*2.], labels=[0,0,0,1], color='grey', fontsize=fontsizemer)
240    m.drawparallels(np.r_[-90.:90.:step], labels=[1,0,0,0], color='grey', fontsize=fontsizemer)
241    if back == ".":      m.warpimage(marsmap(),scale=0.75)
242    elif back == None:   pass 
243    else:                m.warpimage(marsmap(back),scale=0.75)
244    return m
245
246def fmtvar (whichvar="def"):
247    fmtvar    =     { \
248             "tk":           "%.0f",\
249             "tpot":         "%.0f",\
250             "def":          "%.1e",\
251             "PTOT":         "%.0f",\
252             "HGT":          "%.1e",\
253             "USTM":         "%.2f",\
254                    }
255    if whichvar not in fmtvar:
256        whichvar = "def"
257    return fmtvar[whichvar]
258
259def defcolorb (whichone="def"):
260    whichcolorb =    { \
261             "def":          "spectral",\
262             "HGT":          "spectral",\
263             "tk":           "gist_heat",\
264             "QH2O":         "PuBu",\
265             "USTM":         "YlOrRd",\
266#"RdPu",\
267                     }
268    if whichone not in whichcolorb:
269        whichone = "def"
270    return whichcolorb[whichone]
271
272def definecolorvec (whichone="def"):
273        whichcolor =    { \
274                "def":          "black",\
275                "vis":          "yellow",\
276                "vishires":     "yellow",\
277                "molabw":       "yellow",\
278                "mola":         "black",\
279                "gist_heat":    "white",\
280                "hot":          "tk",\
281                "gist_rainbow": "black",\
282                "spectral":     "black",\
283                "gray":         "red",\
284                "PuBu":         "black",\
285                        }
286        if whichone not in whichcolor:
287                whichone = "def"
288        return whichcolor[whichone]
289
290def marsmap (whichone="vishires"):
291        whichlink =     { \
292                "vis":          "http://maps.jpl.nasa.gov/pix/mar0kuu2.jpg",\
293                "vishires":     "http://dl.dropbox.com/u/11078310/MarsMap_2500x1250.jpg",\
294                "mola":         "http://www.lns.cornell.edu/~seb/celestia/mars-mola-2k.jpg",\
295                "molabw":       "http://dl.dropbox.com/u/11078310/MarsElevation_2500x1250.jpg",\
296                        }
297        if whichone not in whichlink: 
298                print "marsmap: choice not defined... you'll get the default one... "
299                whichone = "vishires" 
300        return whichlink[whichone]
301
302def earthmap (whichone):
303        if   whichone == "contrast":    whichlink="http://users.info.unicaen.fr/~karczma/TEACH/InfoGeo/Images/Planets/EarthMapAtmos_2500x1250.jpg"
304        elif whichone == "bw":          whichlink="http://users.info.unicaen.fr/~karczma/TEACH/InfoGeo/Images/Planets/EarthElevation_2500x1250.jpg"
305        elif whichone == "nice":        whichlink="http://users.info.unicaen.fr/~karczma/TEACH/InfoGeo/Images/Planets/earthmap1k.jpg"
306        return whichlink
307
Note: See TracBrowser for help on using the repository browser.