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

Last change on this file since 389 was 388, checked in by acolaitis, 14 years ago

PYTHON.
#######
~
Added new option and routines that go along.
~
#######

M 387 meso.py
M 387 gcm.py
M 387 myscript.py
-------------------- Added the --tsat option. Allows the computation and plotting of Tsat-T instead of T when the z-axis is a pressure coordinate and the variable to plot is temperature. This is usefull to study saturation. Be carefull not to use the --column option, which uses a z-axis in meters, and would output wrong results with an axis in pressure. This could however be worked out in a future commit.

M 387 mymath.py
-------------------- Added several new functions, that may not be at their best place in mymath...:

  • get_tsat(pressure,temp=None,zlon=None,zlat=None,zalt=None,ztime=None) -->when given pressure only, the routine outputs a vertical profile of condensation temperature. -->when given all the inputs, the routine returns Tcond-T by taking care of all dimension problems, automatically finding the vertical axis in the temperature field, and taking care of eventual missing values by masking the one present in the input by the value 1e20 in the output.
  • get_dim(zlon,zlat,zalt,ztime,zvar): --> returns a dictionnary giving the position of each of the dimensions in zvar in the following form:

{'latitude': 2, 'altitude': 1, 'longitude': 3, 'Time': 0}

--> this works for any shape for zvar between 1 and 4 dimensions, and takes care of tricky cases when variable's dimensions are not in the right order, and when two dimensions have the same number of elements.

  • get_key(self,value) --> this function returns the key(s) associated to a value in a dictionnary. This is used to be able to access dictionnaries in the opposite way than the natural one.

M 387 planetoplot.py
-------------------- Added changes relative to the --tsat option

File size: 5.1 KB
Line 
1def min (field,axis=None): 
2        import numpy as np
3        if field is None: return None
4        else: return np.array(field).min(axis=axis)
5
6def max (field,axis=None):
7        import numpy as np
8        if field is None: return None
9        else: return np.array(field).max(axis=axis)
10
11def mean (field,axis=None):
12        import numpy as np
13        if field is None: return None
14        else: return np.array(field).mean(axis=axis)
15
16def deg ():
17        return u'\u00b0'
18
19def writeascii ( tab, filename ):
20    mydata = tab
21    myfile = open(filename, 'w')
22    for line in mydata:
23        myfile.write(str(line) + '\n')
24    myfile.close()
25    return
26
27
28# A.C. routine to compute saturation temperature
29def get_tsat(pressure,temp=None,zlon=None,zlat=None,zalt=None,ztime=None):
30    import math as mt
31    import numpy as np
32    acond=3.2403751E-04
33    bcond=7.3383721E-03
34    # if temp is not in input, the routine simply outputs the vertical profile
35    # of Tsat
36    if temp is None:
37      # Identify dimensions in temperature field
38      output=np.zeros(np.array(pressure).shape)
39      if len(np.array(pressure).shape) is 1:
40         #pressure field is a 1d column, (i.e. the altitude coordinate)
41         #temperature has to have a z-axis
42         i=0
43         for pp in pressure:
44            output[i]=1./(bcond-acond*mt.log(.0095*pp))         
45            i=i+1
46      else:
47         #pressure field is a field present in the file. Unhandled
48         #by this routine for now, which only loads unique variables.
49         print "3D pressure field not handled for now, exiting in tsat"
50         print "Use a vertical pressure coordinate if you want to compute Tsat"
51         exit()
52    # if temp is in input, the routine computes Tsat-T by detecting where the
53    # vertical axis is in temp
54    else:
55      output=np.zeros(np.array(temp).shape)
56      vardim=get_dim(zlon,zlat,zalt,ztime,temp)
57#      m=np.ma.masked_where(temp[temp == -1],temp,copy=False)
58#      print temp
59#      mindex=np.ma.nonzero(m.mask)
60#      print mindex[0]
61      if 'altitude' not in vardim.keys():
62         print 'no altitude coordinate in temperature field for Tsat computation'
63         exit()
64      zdim=vardim['altitude']
65      ndim=len(np.array(temp).shape)
66      print '--- in tsat(). vardim,zdim,ndim: ',vardim,zdim,ndim
67      i=0
68      for pp in pressure:
69        if ndim is 1:
70           output[i]=1./(bcond-acond*mt.log(.0095*pp))-temp[i]
71        elif ndim is 2:
72           if zdim is 0:
73              output[i,:]=1./(bcond-acond*mt.log(.0095*pp))-temp[i,:]
74           elif zdim is 1:
75              output[:,i]=1./(bcond-acond*mt.log(.0095*pp))-temp[:,i]
76           else:
77              print "stop in get_tsat: zdim: ",zdim
78              exit()
79        elif ndim is 3:
80           if zdim is 0:
81              output[i,:,:]=1./(bcond-acond*mt.log(.0095*pp))-temp[i,:,:]
82           elif zdim is 1:
83              output[:,i,:]=1./(bcond-acond*mt.log(.0095*pp))-temp[:,i,:]
84           elif zdim is 2:
85              output[:,:,i]=1./(bcond-acond*mt.log(.0095*pp))-temp[:,:,i]
86           else:
87              print "stop in get_tsat: zdim: ",zdim
88              exit()
89        elif ndim is 4:
90           if zdim is 0:
91              output[i,:,:,:]=1./(bcond-acond*mt.log(.0095*pp))-temp[i,:,:,:]
92           elif zdim is 1:
93              output[:,i,:,:]=1./(bcond-acond*mt.log(.0095*pp))-temp[:,i,:,:]
94           elif zdim is 2:
95              output[:,:,i,:]=1./(bcond-acond*mt.log(.0095*pp))-temp[:,:,i,:]
96           elif zdim is 3:
97              output[:,:,:,i]=1./(bcond-acond*mt.log(.0095*pp))-temp[:,:,:,i]
98           else:
99              print "stop in get_tsat: zdim: ", zdim
100              exit()
101        else:
102           print "stop in get_tsat: ndim: ",ndim
103           exit()
104        i=i+1
105    m=np.ma.masked_where(temp == 0,temp,copy=False)
106    zoutput=np.ma.array(output,mask=m.mask)#,fill_value=-999999)
107    zout=zoutput.filled()
108    return zout
109
110# A.C. Dirty routine to determine where are the axis of a variable
111def get_dim(zlon,zlat,zalt,ztime,zvar):
112   import numpy as np
113   nx,ny,nz,nt=0,0,0,0
114   if zlon is not None:
115      nx=len(zlon)
116   if zlat is not None:
117      ny=len(zlat)
118   if zalt is not None:
119      nz=len(zalt)
120   if ztime is not None:
121      nt=len(ztime)
122   zdims={}
123   zdims['longitude']=nx
124   zdims['latitude']=ny
125   zdims['altitude']=nz
126   zdims['Time']=nt
127   zvardim=np.array(zvar).shape
128   ndim=len(zvardim)
129   zzvardim=[[]]*ndim
130   j=0
131   output={}
132   for dim in zvardim:
133       if dim not in zdims.values():
134          print "WARNING -----------------------------"
135          print "Dimensions given to subroutine do not match variables dimensions :"
136          exit()
137       else:
138          a=get_key(zdims,dim)
139          if len(a) is not 1:
140             if j is 0:                ##this should solve most conflicts with Time
141                zzvardim[j]=a[1]
142             else:
143                zzvardim[j]=a[0]
144          else:
145              zzvardim[j]=a[0]
146          output[zzvardim[j]]=j
147          j=j+1
148   return output
149
150# A.C. routine that gets keys from a dictionnary value
151def get_key(self, value):
152    """find the key(s) as a list given a value"""
153    return [item[0] for item in self.items() if item[1] == value]
154
Note: See TracBrowser for help on using the repository browser.