1 | #!/usr/bin/env python |
---|
2 | # -*- coding: utf-8 -*- |
---|
3 | |
---|
4 | # import |
---|
5 | |
---|
6 | import argparse |
---|
7 | |
---|
8 | import inspect |
---|
9 | from datetime import datetime |
---|
10 | import logging |
---|
11 | |
---|
12 | #from pylab import * |
---|
13 | import glob |
---|
14 | #from datetime import date |
---|
15 | from useCorrTb_daily import * |
---|
16 | import itertools as it |
---|
17 | from multiprocessing import Pool |
---|
18 | from functools import partial |
---|
19 | import matplotlib.gridspec as gridspec |
---|
20 | import time |
---|
21 | |
---|
22 | |
---|
23 | def file_Tbcorr_daily(): |
---|
24 | |
---|
25 | """ |
---|
26 | correct AMSU, MHS and METOP files |
---|
27 | """ |
---|
28 | project_id_env = os.environ['PROJECT_ID'] |
---|
29 | |
---|
30 | rep_fic=project_id_env |
---|
31 | |
---|
32 | parser = argparse.ArgumentParser(description=__doc__, |
---|
33 | formatter_class=argparse.RawDescriptionHelpFormatter) |
---|
34 | |
---|
35 | parser.add_argument("--verbose", |
---|
36 | action='store_true', |
---|
37 | default=False, |
---|
38 | help=("run in verbose mode.")) |
---|
39 | |
---|
40 | ### Satellite, Instrument, Produit Level, Channel |
---|
41 | parser.add_argument('--sat', |
---|
42 | dest='sat', |
---|
43 | nargs="*", |
---|
44 | choices=['M02','M01','N19','N18','N16','N15'], |
---|
45 | metavar="<satellite>", |
---|
46 | default=['M02','M01','N19','N18','N16','N15'], |
---|
47 | help=("satellite")) |
---|
48 | |
---|
49 | parser.add_argument('--inst', |
---|
50 | dest='inst', |
---|
51 | nargs="*", |
---|
52 | choices=['MHS','MHS','MHS','MHS','AMSUB','AMSUB'], |
---|
53 | metavar="<instrument>", |
---|
54 | default=['MHS','MHS','MHS','MHS','AMSUB','AMSUB'], |
---|
55 | help=("instrument")) |
---|
56 | |
---|
57 | parser.add_argument('--level', |
---|
58 | dest='lvl', |
---|
59 | action='store', |
---|
60 | metavar='<level>', |
---|
61 | default='L1C', |
---|
62 | help=("level")) |
---|
63 | |
---|
64 | parser.add_argument('--ch', |
---|
65 | dest='ch', |
---|
66 | nargs='*', |
---|
67 | choices=['B1','B2','B3','B4','B5'], |
---|
68 | metavar='<channel>', |
---|
69 | default=['B1','B2','B3','B4','B5'], |
---|
70 | help=("channel")) |
---|
71 | |
---|
72 | ### Period |
---|
73 | def valid_date(datestring): |
---|
74 | """ |
---|
75 | used to parse yyyymmdd argument in CLI |
---|
76 | """ |
---|
77 | |
---|
78 | return datetime.datetime.strptime(datestring, '%Y%m%d') |
---|
79 | |
---|
80 | parser.add_argument('--dmin', |
---|
81 | dest='dmin', |
---|
82 | action='store', |
---|
83 | type=valid_date, |
---|
84 | metavar='<yyyymmdd>', |
---|
85 | default=datetime.date(2008,5,1), |
---|
86 | help=('first date yyyymmdd')) |
---|
87 | |
---|
88 | parser.add_argument('--dmax', |
---|
89 | dest='dmax', |
---|
90 | action='store', |
---|
91 | type=valid_date, |
---|
92 | metavar='<yyyymmdd>', |
---|
93 | default=datetime.date(2008,5,3), |
---|
94 | help=('last date yyyymmdd')) |
---|
95 | |
---|
96 | # Zone |
---|
97 | #LS = -1. |
---|
98 | #LN = 4. |
---|
99 | #LS = 7. |
---|
100 | #LN = 12. |
---|
101 | #LW = -10. |
---|
102 | #LE = 5. |
---|
103 | |
---|
104 | # New Grid |
---|
105 | resol = .5 |
---|
106 | |
---|
107 | opts = vars(parser.parse_args()) |
---|
108 | is_verbose = opts['verbose'] |
---|
109 | lvl = opts['lvl'] |
---|
110 | sat = opts['sat'] |
---|
111 | inst = opts['inst'] |
---|
112 | ch = opts['ch'] |
---|
113 | dmin = opts['dmin'] |
---|
114 | dmax = opts['dmax'] |
---|
115 | |
---|
116 | latvec = arange(-34.5,34.6,resol) |
---|
117 | lonvec = arange(-180.,179.76,resol) |
---|
118 | |
---|
119 | # define log file |
---|
120 | command = '{0}'.format(inspect.stack()[0][3]) |
---|
121 | log_date = datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ') |
---|
122 | log = '{0}/{1}.log.{2}'.format(os.environ['PROJECT_LOG'], command, log_date) |
---|
123 | |
---|
124 | logger = logging.getLogger() |
---|
125 | handler = logging.FileHandler(log) |
---|
126 | logger.addHandler(handler) |
---|
127 | if is_verbose: |
---|
128 | logger.setLevel(logging.DEBUG) |
---|
129 | else: |
---|
130 | logger.setLevel(logging.INFO) |
---|
131 | |
---|
132 | logger = logging.getLogger() |
---|
133 | logger.info('[Context]') |
---|
134 | logger.info('PID={0}'.format(os.getpid())) |
---|
135 | logger.info('command={0}'.format(command)) |
---|
136 | import socket |
---|
137 | logger.info('hostname={0}'.format(socket.getfqdn())) |
---|
138 | logger.info('runtime={0}'.format(log_date)) |
---|
139 | logger.info('log={0}'.format(log)) |
---|
140 | |
---|
141 | logger.info('[Parameters]') |
---|
142 | logger.info('lvl={0}'.format(lvl)) |
---|
143 | logger.info('sat={0}'.format(sat)) |
---|
144 | logger.info('inst={0}'.format(inst)) |
---|
145 | logger.info('ch={0}'.format(ch)) |
---|
146 | logger.info('dmin={0}'.format(dmin)) |
---|
147 | logger.info('dmax={0}'.format(dmax)) |
---|
148 | |
---|
149 | # number of processes |
---|
150 | npr = 10 |
---|
151 | |
---|
152 | for day in rrule(DAILY,dtstart=dmin,until=dmax): |
---|
153 | logger.info('{0}'.format(day)) |
---|
154 | ### File list |
---|
155 | repday = [day.strftime('%Y_%m_%d')]#[ff.strftime('%Y_%m_%d') for ff in rrule(DAILY,dtstart=day+relativedelta(days=-1),until=day+relativedelta(days=+1))] |
---|
156 | repsat = [ii+ss for ii,ss in zip(inst,sat)] |
---|
157 | fname = hstack([glob.glob('/bdd/AMSU-1C/%s/L1C/*/%s/*.L1C'%(reps,repd)) for reps,repd in it.product(repsat,repday)]) |
---|
158 | |
---|
159 | ### Read files (in parallel with Pool) |
---|
160 | pool = Pool(processes=npr) |
---|
161 | res = pool.map(partial(applycorr2orb,lonvec=lonvec,latvec=latvec,ch=ch),fname) |
---|
162 | pool.close() |
---|
163 | pool.join() |
---|
164 | |
---|
165 | logger.info('Join') |
---|
166 | |
---|
167 | tbcorr, tobs, satvec = [dstack([proc[var] for proc in res if size(proc[var])]) for var in xrange(3)] |
---|
168 | del res |
---|
169 | |
---|
170 | # Sort ??? sur le temps ??? |
---|
171 | isort = argsort(nanmean(tobs.squeeze(),axis=0)) |
---|
172 | tbcorr = tbcorr[:,:,isort] |
---|
173 | tobs = tobs.squeeze()[:,isort] |
---|
174 | satvec = satvec.squeeze()[isort] |
---|
175 | |
---|
176 | # Satellite/Instrument identification |
---|
177 | satdef = SatName() |
---|
178 | satnum = satdef.get_satnum(satvec.squeeze()) |
---|
179 | |
---|
180 | ### Fillvalue |
---|
181 | tbcorr[isnan(tbcorr)] = -99.99 |
---|
182 | |
---|
183 | ### Save in netcdf file |
---|
184 | logger.info('Save in nc') |
---|
185 | nsat = satvec.size |
---|
186 | nlon = lonvec.size |
---|
187 | nlat = latvec.size |
---|
188 | torig = date(day.year,1,1) |
---|
189 | for cc, ich in enumerate(ch): |
---|
190 | # Output file name |
---|
191 | output = '%sTbCorr_AMSUMHS_%s_%3.2fdeg_%s.nc'%(rep_fic,ich,resol,day.strftime('%Y%m%d')) |
---|
192 | # Creation du fichier |
---|
193 | ncfile = netCDF4.Dataset(output,'w',format='NETCDF4_CLASSIC') |
---|
194 | # Definition des dimensions |
---|
195 | ncfile.createDimension('lon',nlon) |
---|
196 | ncfile.createDimension('lat',nlat) |
---|
197 | ncfile.createDimension('satellite',nsat) |
---|
198 | |
---|
199 | # Creation des variables dimensions |
---|
200 | lons = ncfile.createVariable('lon',dtype('float32').char,('lon',)) |
---|
201 | lons.long_name = 'Longitude' |
---|
202 | lons.units = 'degrees_east' |
---|
203 | lons.actual_range = '%4.2f,%4.2f'%(lonvec.min(),lonvec.max()) |
---|
204 | lons[:] = lonvec |
---|
205 | |
---|
206 | lats = ncfile.createVariable('lat',dtype('float32').char,('lat',)) |
---|
207 | lats.long_name = 'Latitude' |
---|
208 | lats.units = 'degrees_north' |
---|
209 | lats.actual_range = '%4.2f,%4.2f'%(latvec.min(),latvec.max()) |
---|
210 | lats[:] = latvec |
---|
211 | |
---|
212 | sats = ncfile.createVariable('satellite',dtype('int16').char,('satellite',)) |
---|
213 | sats.long_name = 'Satellite' |
---|
214 | sats.description = [str(num)+' = '+ns +', ' for num,ns in zip(satdef.satnum,satdef.satname)] |
---|
215 | sats[:] = satnum |
---|
216 | |
---|
217 | # Creation variable |
---|
218 | dates = ncfile.createVariable('time',dtype('float').char,('lat','lon','satellite',)) |
---|
219 | dates.long_name = 'Time' |
---|
220 | dates.units = 'hours since %s'%torig.strftime('%Y-%m-%d %H:%M:%S') |
---|
221 | #dates[:] = (fix((tobs-date2num(torig))*24.*100)/100.).reshape(nlat,nlon,nsat) |
---|
222 | dates[:] = ((tobs-date2num(torig))*24.).reshape(nlat,nlon,nsat) |
---|
223 | |
---|
224 | sclfactor = .01 |
---|
225 | tbfinal = ncfile.createVariable('tbcorr',dtype('int16').char,('lat','lon','satellite',),fill_value=-9999.) |
---|
226 | tbfinal.description = 'Corrected Tb of channel %s'%ich |
---|
227 | tbfinal.units = 'Kelvin' |
---|
228 | tbfinal.scale_factor = sclfactor |
---|
229 | #tbfinal._FillValue = -9999. |
---|
230 | tbfinal[:] = tbcorr[cc,:,:].reshape(nlat,nlon,nsat) |
---|
231 | |
---|
232 | # Fermeture du fichier |
---|
233 | ncfile.close() |
---|
234 | logger.info('{0} created'.format(output)) |
---|
235 | |
---|
236 | |
---|
237 | if __name__ == '__main__': |
---|
238 | file_Tbcorr_daily() |
---|