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

Last change on this file since 226 was 225, checked in by aslmd, 14 years ago

MESOSCALE: python graphics. now possible for multi-files and multi-var. very easy to make an atlas.

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