source: trunk/UTIL/PYTHON/mcs.py @ 403

Last change on this file since 403 was 403, checked in by acolaitis, 13 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.

  • Property svn:executable set to *
File size: 7.3 KB
Line 
1#!/usr/bin/env python
2
3### A. Colaitis
4
5##
6#   This routine transforms a diagfi.nc file into a diagfi_MCS.nc file where
7#   the fields are directly comparable to those contained in MCS data, i.e.
8#   fields are re-binned at times over the ranges specified in the MCS file.
9###
10
11###########################################################################################
12###########################################################################################
13### What is below relate to running the file as a command line executable (very convenient)
14if __name__ == "__main__":
15   import sys
16   from optparse import OptionParser    ### to be replaced by argparse
17   from netCDF4 import Dataset
18   from os import system
19   from times import sol2ls
20   import numpy as np
21   from mymath import find_nearest
22   from myplot import getfield
23   from make_netcdf import make_gcm_netcdf
24   parser = OptionParser() 
25
26   #############################
27   ### Options
28   parser.add_option('-f', '--file',   action='store',dest='file',     type="string",  default=None,  help='[NEEDED] filename.')
29   parser.add_option('-m', '--mfile',  action='store',dest='mcsfile',     type="string",  default=None,  help='[NEEDED] filename for MCS comparison.')
30
31   #############################
32   ### Get options and variables
33   (opt,args) = parser.parse_args()
34
35   #############################
36   ### Load and check data
37
38   # Files
39
40   nc=Dataset(opt.file)
41   ncmcs=Dataset(opt.mcsfile)
42
43   # Dimensions
44
45   lon=nc.variables["longitude"][:]
46   lat=nc.variables["latitude"][:]
47   alt=nc.variables["altitude"][:]
48   time=nc.variables["Time"][:] # in fraction of sols
49   controle=nc.variables["controle"][:]
50   day_ini=controle[3]%669
51   time[:]=time[:]+day_ini
52   nx=len(lon)
53   ny=len(lat)
54   nz=len(alt)
55   nt=len(time)
56   lstime=sol2ls(time)
57
58   # MCS
59
60   dtimemintmp=ncmcs.variables["dtimemin"][:,:,:]
61   dtimemaxtmp=ncmcs.variables["dtimemax"][:,:,:]
62   ntimemintmp=ncmcs.variables["ntimemin"][:,:,:]
63   ntimemaxtmp=ncmcs.variables["ntimemax"][:,:,:]
64   lonmcs=ncmcs.variables["longitude"][:]
65   latmcs=ncmcs.variables["latitude"][:]
66   timemcs=ncmcs.variables["time"][:]%360 # IN LS
67
68   dtimemin=np.ma.masked_where(dtimemintmp < 0.,dtimemintmp)
69   dtimemin.set_fill_value([np.NaN])
70   dtimemax=np.ma.masked_where(dtimemaxtmp < 0.,dtimemaxtmp)
71   dtimemax.set_fill_value([np.NaN])
72   ntimemin=np.ma.masked_where(ntimemintmp < 0.,ntimemintmp)
73   ntimemin.set_fill_value([np.NaN])
74   ntimemax=np.ma.masked_where(ntimemaxtmp < 0.,ntimemaxtmp)
75   ntimemax.set_fill_value([np.NaN])
76
77   # Variables
78
79   temp=getfield(nc,"temp")
80   dimensions = np.array(temp).shape
81   print "temp"
82   print dimensions
83   #aps=nc.variables["aps"][:]
84   #bps=nc.variables["bps"][:]
85
86   #############################
87   ### Building
88   #############################
89
90   ### We loop over chunks of gcm data corresponding to MCS time dimension
91   ### Bin sizes for mcs data is 5 degrees ls centered on value
92   varday=np.zeros([len(timemcs),nz,ny,nx])
93   varnight=np.zeros([len(timemcs),nz,ny,nx])
94   vardayout=np.ma.masked_invalid(varday)
95   varnightout=np.ma.masked_invalid(varnight)
96   i=0
97   for ls in timemcs:
98       lsstart=ls-2.5
99       lsstop=ls+2.5
100       istart=find_nearest(lstime,lsstart,strict=True)
101       istop=find_nearest(lstime,lsstop,strict=True)
102       if ((istart is np.NaN) or (istop is np.NaN)):
103          vardayout[i,:,:,:]=np.NaN
104          varnightout[i,:,:,:]=np.NaN
105          print "Time interval skipped. Ls MCS: (",lsstart,';',lsstop,')',"// Ls diagfi: (",lstime.min(),';',lstime.max(),')'
106          i=i+1
107          continue
108       print "--->> Processing Data. Ls MCS: (",lsstart,';',lsstop,')',"// Ls diagfi: (",lstime.min(),';',lstime.max(),')'
109
110       varchk=temp[istart:istop,:,:,:]
111       varchktime=time[istart:istop]
112       ndays=np.floor(varchktime[len(varchktime)-1])-np.floor(varchktime[0])
113       dtmichk=dtimemin[i,:,:]
114       dtmachk=dtimemax[i,:,:]
115       ntmichk=ntimemin[i,:,:]
116       ntmachk=ntimemax[i,:,:]
117       dtmichk.set_fill_value(np.NaN)
118       dtmachk.set_fill_value(np.NaN)
119       ntmichk.set_fill_value(np.NaN)
120       ntmachk.set_fill_value(np.NaN)
121       dtmichk=dtmichk.filled()
122       dtmachk=dtmachk.filled()
123       ntmichk=ntmichk.filled()
124       ntmachk=ntmachk.filled()
125
126   ### We iterate for each day in the chunk, on each grid point we find
127   ### the closest corresponding MCS grid point and the index of the
128   ### time in the chunk closest to the time in the closest MCS grid point.
129   ### (yea it's complicated)
130
131       vartmpnight=np.zeros([ndays,nz,ny,nx])
132       vartmpday=np.zeros([ndays,nz,ny,nx])
133       nd=0
134       
135
136       while nd < ndays:
137
138          daystart=find_nearest(varchktime-varchktime[0],nd)
139          daystop=find_nearest(varchktime-varchktime[0],nd+1)
140#          varchktime_lon=np.zeros([daystop-daystart+1,len(lon)])
141          ix=0
142          for x in lon:
143
144             varchktime_lon = 24.*(varchktime[daystart:daystop+1]-varchktime[daystart]) + x/15.
145
146             iy=0
147             for y in lat:
148                niy=find_nearest(latmcs,y)
149                nix=find_nearest(lonmcs,x)
150                nitdtmichk=find_nearest(varchktime_lon,dtmichk[niy,nix])
151                nitdtmachk=find_nearest(varchktime_lon,dtmachk[niy,nix])
152                nitntmichk=find_nearest(varchktime_lon,ntmichk[niy,nix])
153                nitntmachk=find_nearest(varchktime_lon,ntmachk[niy,nix])
154                if ((nitdtmichk is np.NaN) or (nitdtmachk is np.NaN)):
155                    vartmpday[nd,:,iy,ix]=np.NaN
156                elif nitdtmichk > nitdtmachk:
157                    vartmpday[nd,:,iy,ix]=(np.mean(varchk[daystart+nitdtmichk:daystop+1,:,iy,ix],axis=0)+np.mean(varchk[daystart:daystart+nitdtmachk+1,:,iy,ix],axis=0))/2.
158                else:
159                    vartmpday[nd,:,iy,ix]=np.mean(varchk[daystart+nitdtmichk:daystart+nitdtmachk+1,:,iy,ix],axis=0)
160                if ((nitntmichk is np.NaN) or (nitntmachk is np.NaN)):
161                    vartmpnight[nd,:,iy,ix]=np.NaN
162                elif nitntmichk > nitntmachk:
163                    vartmpnight[nd,:,iy,ix]=(np.mean(varchk[daystart+nitntmichk:daystop+1,:,iy,ix],axis=0)+np.mean(varchk[daystart:daystart+nitntmachk+1,:,iy,ix],axis=0))/2.
164                else:                                                           
165                    vartmpnight[nd,:,iy,ix]=np.mean(varchk[daystart+nitntmichk:daystart+nitntmachk+1,:,iy,ix],axis=0)
166
167                iy=iy+1
168             ix=ix+1
169          nd=nd+1
170
171       vartmpdaymasked=np.ma.masked_invalid(vartmpday)
172       vartmpnightmasked=np.ma.masked_invalid(vartmpnight)
173
174       vardayout[i,:,:,:]=np.ma.mean(vartmpdaymasked[:,:,:,:],axis=0)
175       varnightout[i,:,:,:]=np.ma.mean(vartmpnightmasked[:,:,:,:],axis=0)
176       i=i+1
177
178   vardayout=np.ma.masked_invalid(vardayout)
179   varnightout=np.ma.masked_invalid(varnightout)
180   vardayout.set_fill_value([np.NaN])
181   varnightout.set_fill_value([np.NaN])
182
183   vardayncdf=vardayout.filled()
184   varnightncdf=varnightout.filled()
185
186   make_gcm_netcdf (zfilename="diagfi_MCS.nc", \
187                        zdescription="Temperatures from diagfi reworked to match MCS format", \
188                        zlon=lon, \
189                        zlat=lat, \
190                        zalt=alt, \
191                        ztime=timemcs, \
192                        zvariables=[vardayncdf,varnightncdf], \
193                        znames=["dtemp","ntemp"])
Note: See TracBrowser for help on using the repository browser.