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

Last change on this file since 419 was 403, checked in by acolaitis, 14 years ago

PYTHON.

############################################
1/------------------------------------------
############################################
# First version of a new command line routine
# that takes in input a diagfi and a MCS datafile
# as formatted by Luca Montabone
# and find the values in the diagfi temp field
# corresponding to daytime and nightime localtimes in MCS file
# (at each longitude and latitude, which is especially important at the poles
# where the spacecraft covers multiple local times for each bin)
# The selected diagfi data is then binned at the Ls of the MCS file
# and written as a diagfi_MCS.nc file.
#
# Example: (you have to be connected on Penn, as the file is on the local disk)

/san0/acolmd/SVN/trunk/UTIL/PYTHON/mcs.py -f /home/local_home/colaitis/Polar_simulations/Polar_All_Th/diagfi16.nc -m /san0/acolmd/DATA/MCS/MCS_processeddata/MCSdata_binned_MY29.nc

# It is then easy to compare the resulting gcm re-arranged data to the MCS dataset using
# your favorite pp command. Note that in this first version of the routine, only the temperature field is
# recomputed. A more complex version will come out later, with variable selection and conservation of
# fields needed to then use zrecast or hrecast.

############################################
2/------------------------------------------
############################################

# Added python versions of ls2sol and sol2ls
# which can work either with single values or arrays
# These routines are in times.py so that you can add
# in your script:

from times import ls2sol,sol2ls

############################################
2/------------------------------------------
############################################

# Added new routine in mymath, which finds the index of the
# element nearest to "value" in "array". The array
# can be masked or not, the output is an array.
# If the value is a NaN, the routine returns a NaN.
# One can specify the option "strict=True" so that
# the routine will return a NaN if the value asked is not
# between the min and max of the array.

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