source: trunk/src/file_Tbcorr_daily.py @ 698

Last change on this file since 698 was 698, checked in by pinsard, 8 years ago

add parameters on CLI

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