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

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

PYTHON

M 393 mymath.py
----------------- Cosmetic change

M 393 make_netcdf.py
----------------- Cosmetic change

M 393 planetoplot.py
----------------- corrected bug with varname and --tsat

M 393 myplot.py
----------------- added possibility for the script to read ncdf files with NaN value and treat them correctly without messing with the mathematical operations.

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