source: trunk/UTIL/PYTHON/mymath.py @ 430

Last change on this file since 430 was 430, checked in by acolaitis, 13 years ago


PYTHON

Added... movies !


Example :


pp.py -f wrfout_d01_9999-01-01_07:11:40 --var upward --lat 50 --time 5 -m 0 -M 10 -c Spectral_r --div 20 --ymax 200

will generate a 2D altitude-latitude plot of upward tracer concentration, whereas :

pp.py -f wrfout_d01_9999-01-01_07:11:40 --var upward --lat 50 -m 0 -M 10 -c Spectral_r --div 20 --ymax 200

will generate a movie of the previous plot, along the time axis (default axis for movies for now).


Requirements :


The way the movie maker is written is very light-weight and fast, as no intermediary pictures are saved. The data is buffered and streamed right into an encoder.
I could not make this work with ffmpeg... So you MUST have mencoder installed. It is not on the farm... It is on ciclad, and I know that Aymeric installed it on his machine (at least before getting Ulrich).


Known problems :


I spent litteraly all day making this work, but the option is still basic for now, i.e. it is not yea possible to use -w with movies, or 1D plot movies. (several other stuff are not possible yet, like title specification, axis limits (ylim,xlim), etc... I know how to make it work, I just need some time.

Default name for the output movie is "test.avi" for now.

Tested with LES data without projections. Not test on meso or gcm in mapmode 1.


Details :


A videosink.py
----------------- New class that contains some routines for video stuff. This could either be transformed in a function in an other .py, or other functions could be added to this class to make it more usefull.

M 427 mymath.py
----------------- New routines to convert figures to RGBA data (4-dimensions arrays of pixel data) and figures to PIL images.

M * 428 planetoplot.py
----------------- Added support for movies of 2D plots without overlines

M * 428 myplot.py
----------------- Minor stuff about LES and dumpbdy for W. This could be made in a much cleaner way... maybe later.

File size: 8.1 KB
Line 
1def min (field,axis=None): 
2        import numpy as np
3        if field is None: return None
4        if type(field).__name__=='MaskedArray':
5              field.set_fill_value(np.NaN)
6              return np.ma.array(field).min(axis=axis)
7        elif (np.isnan(np.sum(field)) and (type(field).__name__ not in 'MaskedArray')):
8              return np.ma.masked_invalid(field).min(axis=axis)
9        else: return np.array(field).min(axis=axis)
10
11def max (field,axis=None):
12        import numpy as np
13        if field is None: return None
14        if type(field).__name__=='MaskedArray':
15              field.set_fill_value(np.NaN)
16              return np.ma.array(field).max(axis=axis)
17        elif (np.isnan(np.sum(field)) and (type(field).__name__ not in 'MaskedArray')):
18              return np.ma.masked_invalid(field).max(axis=axis) 
19        else: return np.array(field).max(axis=axis)
20
21def mean (field,axis=None):
22        import numpy as np
23        if field is None: return None
24        else: 
25           if type(field).__name__=='MaskedArray':
26              field.set_fill_value(np.NaN)
27              zout=np.ma.array(field).mean(axis=axis)
28              if axis is not None:
29                 zout.set_fill_value(np.NaN)
30                 return zout.filled()
31              else:return zout
32           elif (np.isnan(np.sum(field)) and (type(field).__name__ not in 'MaskedArray')):
33              zout=np.ma.masked_invalid(field).mean(axis=axis)
34              if axis is not None:
35                 zout.set_fill_value([np.NaN])
36                 return zout.filled()
37              else:return zout
38           else: 
39              return np.array(field).mean(axis=axis)
40
41def deg ():
42        return u'\u00b0'
43
44def writeascii ( tab, filename ):
45    mydata = tab
46    myfile = open(filename, 'w')
47    for line in mydata:
48        myfile.write(str(line) + '\n')
49    myfile.close()
50    return
51
52
53# A.C. routine to compute saturation temperature
54# Be Carefull, when asking for tsat-t, this routine outputs a masked array.
55# To be correctly handled, this call to tsat must be done before the call to
56# reduce_field, which handles correctly masked array with the new mean() function.
57def get_tsat(pressure,temp=None,zlon=None,zlat=None,zalt=None,ztime=None):
58    import math as mt
59    import numpy as np
60    acond=3.2403751E-04
61    bcond=7.3383721E-03
62    # if temp is not in input, the routine simply outputs the vertical profile
63    # of Tsat
64    if temp is None:
65      # Identify dimensions in temperature field
66      output=np.zeros(np.array(pressure).shape)
67      if len(np.array(pressure).shape) is 1:
68         #pressure field is a 1d column, (i.e. the altitude coordinate)
69         #temperature has to have a z-axis
70         i=0
71         for pp in pressure:
72            output[i]=1./(bcond-acond*mt.log(.0095*pp))         
73            i=i+1
74      else:
75         #pressure field is a field present in the file. Unhandled
76         #by this routine for now, which only loads unique variables.
77         print "3D pressure field not handled for now, exiting in tsat"
78         print "Use a vertical pressure coordinate if you want to compute Tsat"
79         exit()
80    # if temp is in input, the routine computes Tsat-T by detecting where the
81    # vertical axis is in temp
82    else:
83      output=np.zeros(np.array(temp).shape)
84      vardim=get_dim(zlon,zlat,zalt,ztime,temp)
85      if 'altitude' not in vardim.keys():
86         print 'no altitude coordinate in temperature field for Tsat computation'
87         exit()
88      zdim=vardim['altitude']
89      ndim=len(np.array(temp).shape)
90      print '--- in tsat(). vardim,zdim,ndim: ',vardim,zdim,ndim
91      i=0
92      for pp in pressure:
93        if ndim is 1:
94           output[i]=1./(bcond-acond*mt.log(.0095*pp))-temp[i]
95        elif ndim is 2:
96           if zdim is 0:
97              output[i,:]=1./(bcond-acond*mt.log(.0095*pp))-temp[i,:]
98           elif zdim is 1:
99              output[:,i]=1./(bcond-acond*mt.log(.0095*pp))-temp[:,i]
100           else:
101              print "stop in get_tsat: zdim: ",zdim
102              exit()
103        elif ndim is 3:
104           if zdim is 0:
105              output[i,:,:]=1./(bcond-acond*mt.log(.0095*pp))-temp[i,:,:]
106           elif zdim is 1:
107              output[:,i,:]=1./(bcond-acond*mt.log(.0095*pp))-temp[:,i,:]
108           elif zdim is 2:
109              output[:,:,i]=1./(bcond-acond*mt.log(.0095*pp))-temp[:,:,i]
110           else:
111              print "stop in get_tsat: zdim: ",zdim
112              exit()
113        elif ndim is 4:
114           if zdim is 0:
115              output[i,:,:,:]=1./(bcond-acond*mt.log(.0095*pp))-temp[i,:,:,:]
116           elif zdim is 1:
117              output[:,i,:,:]=1./(bcond-acond*mt.log(.0095*pp))-temp[:,i,:,:]
118           elif zdim is 2:
119              output[:,:,i,:]=1./(bcond-acond*mt.log(.0095*pp))-temp[:,:,i,:]
120           elif zdim is 3:
121              output[:,:,:,i]=1./(bcond-acond*mt.log(.0095*pp))-temp[:,:,:,i]
122           else:
123              print "stop in get_tsat: zdim: ", zdim
124              exit()
125        else:
126           print "stop in get_tsat: ndim: ",ndim
127           exit()
128        i=i+1
129    m=np.ma.masked_invalid(temp,copy=False)
130    zoutput=np.ma.array(output,mask=m.mask,fill_value=np.NaN)
131    return zoutput
132
133# A.C. Dirty routine to determine where are the axis of a variable
134def get_dim(zlon,zlat,zalt,ztime,zvar):
135   import numpy as np
136   nx,ny,nz,nt=0,0,0,0
137   if zlon is not None:
138      nx=len(zlon)
139   if zlat is not None:
140      ny=len(zlat)
141   if zalt is not None:
142      nz=len(zalt)
143   if ztime is not None:
144      nt=len(ztime)
145   zdims={}
146   zdims['longitude']=nx
147   zdims['latitude']=ny
148   zdims['altitude']=nz
149   zdims['Time']=nt
150   zvardim=np.array(zvar).shape
151   ndim=len(zvardim)
152   zzvardim=[[]]*ndim
153   j=0
154   output={}
155   for dim in zvardim:
156       if dim not in zdims.values():
157          print "WARNING -----------------------------"
158          print "Dimensions given to subroutine do not match variables dimensions :"
159          exit()
160       else:
161          a=get_key(zdims,dim)
162          if len(a) is not 1:
163             if j is 0:                ##this should solve most conflicts with Time
164                zzvardim[j]=a[1]
165             else:
166                zzvardim[j]=a[0]
167          else:
168              zzvardim[j]=a[0]
169          output[zzvardim[j]]=j
170          j=j+1
171   return output
172
173# A.C. routine that gets keys from a dictionnary value
174def get_key(self, value):
175    """find the key(s) as a list given a value"""
176    return [item[0] for item in self.items() if item[1] == value]
177
178# A.C. routine that gets the nearest value index of array and value
179def find_nearest(arr,value,axis=None,strict=False):
180    import numpy as np
181    # Special case when the value is nan
182    if value*0 != 0: return np.NaN
183    # Check that the value we search is inside the array for the strict mode
184    if strict:
185       min=arr.min()
186       max=arr.max()
187       if ((value > max) or (value < min)): return np.NaN
188
189    if type(arr).__name__=='MaskedArray':
190       mask=np.ma.getmask(arr)
191       idx=np.ma.argmin(np.abs(arr-value),axis=axis)
192    # Special case when there are only missing values on the axis
193       if mask[idx]:
194          idx=np.NaN
195    else:
196       idx=(np.abs(arr-value)).argmin(axis=axis)
197    return idx
198
199def fig2data ( fig ):
200    import numpy
201    """
202    @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
203    @param fig a matplotlib figure
204    @return a numpy 3D array of RGBA values
205    """
206    # draw the renderer
207    fig.canvas.draw ( )
208 
209    # Get the RGBA buffer from the figure
210    w,h = fig.canvas.get_width_height()
211    buf = numpy.fromstring ( fig.canvas.tostring_argb(), dtype=numpy.uint8 )
212    buf.shape = ( w, h,4 )
213 
214    # canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
215    buf = numpy.roll ( buf, 3, axis = 2 )
216    return buf
217
218def fig2img ( fig ):
219    import Image
220    import numpy
221    """
222    @brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it
223    @param fig a matplotlib figure
224    @return a Python Imaging Library ( PIL ) image
225    """
226    # put the figure pixmap into a numpy array
227    buf = fig2data ( fig )
228    w, h, d = buf.shape
229    return Image.fromstring( "RGBA", ( w ,h ), buf.tostring( ) )
Note: See TracBrowser for help on using the repository browser.