- Timestamp:
- 04/27/16 01:37:34 (8 years ago)
- Location:
- trunk/src
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/src/file_Tbcorr_daily.py
r707 r708 13 13 import os 14 14 from pylab import date2num 15 from numpy import arange, size, hstack, dstack, dtype, argsort, nanmean, isnan15 from numpy import arange, size, hstack, dstack, dtype, argsort, mean, nanmean, isnan 16 16 from dateutil.rrule import rrule, DAILY 17 17 from useCorrTb_daily import applycorr2orb, SatName … … 85 85 type=valid_date, 86 86 metavar='<yyyymmdd>', 87 default=datetime.date(20 08, 5, 1),87 default=datetime.date(2011, 1, 3), 88 88 help=('first date yyyymmdd')) 89 89 … … 93 93 type=valid_date, 94 94 metavar='<yyyymmdd>', 95 default=datetime.date(20 08, 5, 3),95 default=datetime.date(2011, 1, 3), 96 96 help=('last date yyyymmdd')) 97 97 … … 150 150 151 151 # number of processes 152 npr = 10 153 152 npr = 30 154 153 for day in rrule(DAILY, dtstart=dmin, until=dmax): 155 154 logger.info('{0}'.format(day)) … … 159 158 repsat = [ii+ss for ii, ss in zip(inst, sat)] 160 159 fname = hstack([glob('/bdd/AMSU-1C/%s/L1C/*/%s/*.L1C' % (reps, repd)) for reps, repd in it.product(repsat, repday)]) 161 160 162 161 ### Read files (in parallel with Pool) 163 162 pool = multiprocessing.Pool(processes=npr) … … 183 182 184 183 # Fillvalue 185 tbcorr[isnan(tbcorr)] = -99.99 184 fvalue = -9999 185 tbcorr[isnan(tbcorr)] = fvalue 186 186 187 187 # Save in netcdf file 188 188 logger.info('Save in nc') 189 nsat = satvec.size190 189 nlon = lonvec.size 191 190 nlat = latvec.size 192 191 torig = datetime.date(1970, 1, 1) 193 192 for cc, ich in enumerate(ch): 193 # Index to remove orbites completly 194 iorb = (mean(tbcorr[cc,:,:].squeeze(),axis=0) != fvalue) 195 nsat = satvec[iorb].size 194 196 # Output file name 195 197 output = '%sTbCorr_AMSUMHS_%s_%3.2fdeg_%s.nc' % (rep_fic, ich, resol, day.strftime('%Y%m%d')) … … 217 219 sats.long_name = 'Satellite' 218 220 sats.description = [str(num)+' = '+ns +', ' for num, ns in zip(satdef.satnum, satdef.satname)] 219 sats[:] = satnum 221 sats[:] = satnum[iorb] 220 222 221 223 # Creation variable … … 223 225 dates.long_name = 'Time' 224 226 dates.units = 'hours since %s'%torig.strftime('%Y-%m-%d %H:%M:%S') 225 dates[:] = ((tobs -date2num(torig))*24.).reshape(nlat, nlon, nsat)227 dates[:] = ((tobs[:,iorb]-date2num(torig))*24.).reshape(nlat, nlon, nsat) 226 228 227 229 sclfactor = .01 228 tbfinal = ncfile.createVariable('tbcorr', dtype('int16').char, ('lat', 'lon', 'satellite', ), fill_value= -9999.)230 tbfinal = ncfile.createVariable('tbcorr', dtype('int16').char, ('lat', 'lon', 'satellite', ), fill_value=fvalue) 229 231 tbfinal.description = 'Corrected Tb of channel %s'%ich 230 232 tbfinal.units = 'Kelvin' 231 233 tbfinal.scale_factor = sclfactor 232 tbfinal[:] = tbcorr[cc, :, :].reshape(nlat, nlon, nsat)234 tbfinal[:] = tbcorr[cc, :, iorb].reshape(nlat, nlon, nsat) 233 235 234 236 # Fermeture du fichier -
trunk/src/useCorrTb_daily.py
r707 r708 8 8 import time 9 9 import netCDF4 10 from pylab import date2num, num2date , flatten11 from numpy import array, arange, float32, NaN, transpose, int16, diff, logical_and, meshgrid, ravel, zeros, unique, nanmean 10 from pylab import date2num, num2date#, flatten 11 from numpy import array, arange, float32, NaN, transpose, int16, diff, logical_and, meshgrid, ravel, zeros, unique, nanmean, isnan, hstack 12 12 from ReadRawFile import ReadRawFile 13 13 from scipy import spatial … … 50 50 logger = logging.getLogger() 51 51 52 if ch[0].lower() == 'all': 53 ch = ['B1', 'B2', 'B3', 'B4', 'B5'] 54 52 55 # Read orbit file 53 56 lon, lat, dt, tb, fov = load_amsub_mhs(fname, ch, area) 54 57 55 58 try: 56 # C lass of each orbit points57 c lz = find_class(lat, lon)58 no zero = (clz != 0)59 60 except ValueError:59 # Coef of correction as a function of classification, fov and day of year 60 coefz = find_corrcoef(dt, lon, lat, fov, ch) 61 nonan = ~isnan(coefz[0,:]) 62 63 except StandardError: 61 64 logger.error('Orbit is out of the area: {0}'.format(fname)) 62 65 return [], [], [] 63 66 64 67 else: 65 # Coef of correction as a function of classification, fov and day of year 66 coefz = find_corrcoef(dt[nozero], fov[nozero], clz[nozero], ch=ch) 67 tbcorr = array(tb)[:, nozero] - coefz 68 tbcorr = array(tb)[:,nonan] - coefz[:,nonan] 68 69 # Average on new grid 69 tbcorrm, tobsm = newgrid(lonvec, latvec, lon[no zero], lat[nozero], dt[nozero], tbcorr)70 tbcorrm, tobsm = newgrid(lonvec, latvec, lon[nonan], lat[nonan], dt[nonan], tbcorr) 70 71 71 72 logger.info('Deal {0} in: {1}'.format(fname, time.time()-t)) … … 78 79 *Inputs: 79 80 fname = file name 80 ch = list of extrated channel ('B1', 'B2', 'B3', 'B4', 'B5' or 'All'), default 'All'81 area = limits [LS, LN, LW, LE] for extracted area, default is world(ie [-35, 35, -180., 180])81 ch = list of extrated channel ('B1', 'B2', 'B3', 'B4', 'B5') 82 area = limits [LS, LN, LW, LE] for extracted area, default is Tropics (ie [-35, 35, -180., 180]) 82 83 83 84 *Outputs: … … 90 91 """ 91 92 92 # Index of channel 93 ch = [cch.lower() for cch in ch] 94 if ch[0] == 'all': 95 ich = arange(5) 96 else: 97 ich = array([int(cch[1])-1 for cch in ch]) 93 # Index channel to extract 94 ich = array([int(cch[1])-1 for cch in ch]) 98 95 99 96 project = os.environ['PROJECT'] … … 188 185 return h, m, s 189 186 190 # ---Find classes--- # 191 def find_class(lat, lon): 192 """Find class of each given (lat, lon) 193 *Inputs: 187 # ---Find coefficient of correction--- # 188 def find_corrcoef(dt, lon, lat, fov, ch): 189 """Find the coefficient of correction 190 *Inputs: 191 dt = Python date 194 192 lat = Latitude (degrees) 195 193 lon = Longitude (degrees) 196 197 *Outputs:198 clpt = class of each point (same shape as lat and lon)199 """200 project = os.environ['PROJECT']201 # Read the classification file202 fic_class = '{0}/data/classifERAI_Trop.nc'.format(project)203 fileID = netCDF4.Dataset(fic_class)204 lat_class = fileID.variables['lat'][:]205 lon_class = fileID.variables['lon'][:]206 classif = int16(fileID.variables['classif_tot'][:])207 fileID.close()208 209 # Latitude limits of classification (ie tropical band)210 latstep = abs(diff(lat_class))[0]211 latmin = lat_class.min()-latstep/2.212 latmax = lat_class.max()+latstep/2.213 # Only points in the area of classification214 inclass = logical_and(lat >= latmin, lat <= latmax)215 216 # Geographic projection (lon/lat in degrees to x/y in m)217 projG = pyproj.Proj("+proj=merc +ellps=WGS84 +datum=WGS84")218 longd_class, latgd_class = meshgrid(lon_class, lat_class)219 xclass, yclass = projG(longd_class, latgd_class)220 xx, yy = projG(lon[inclass], lat[inclass])221 222 # Find the nearest neighbour (euclidian distance) with a kd-tree223 tree = spatial.cKDTree(zip(ravel(xclass), ravel(yclass)))224 _, ind = tree.query(zip(xx, yy))225 clpt = zeros(lat.shape, dtype=int16)226 clpt[inclass] = classif.flatten()[ind]227 228 return clpt229 230 # ---Find the coefficient of correction--- #231 def find_corrcoef(dt, fov, cl, ch=['All']):232 """Find the coefficient of correction233 *Inputs:234 dt = Python date235 194 fov = Location in the swath 236 cl = Class 237 ch = list of extrated channel ('B1', 'B2', 'B3', 'B4', 'B5' or 'All'), default 'All' 195 ch = list of extrated channel ('B1', 'B2', 'B3', 'B4', 'B5') 238 196 239 197 *Outputs: 240 198 coef = Coefficient of correction 241 199 """ 242 # Index of channel243 ch = [cch.lower() for cch in ch]244 if ch[0] == 'all':245 ich = arange(5)246 else:247 ich = array([int(cch[1])-1 for cch in ch])248 249 # Read the classification file250 project = os.environ['PROJECT']251 fic_corr = '{0}/data/corrTb_AMSUB_MHS_L1C.nc'.format(project)252 fileID = netCDF4.Dataset(fic_corr)253 day_corr = fileID.variables['day'][:]254 coef_corr = fileID.variables['coefcorr'][:, :, :, ich]255 fileID.close()256 200 257 201 # Find the day of year 258 202 yday = array([d.timetuple().tm_yday for d in dt]) 259 # Find the day of correction 260 nday = day_corr.size 261 daystep = diff(day_corr)[0] 262 icorr = list(flatten([[ii]*daystep for ii in xrange(nday)])) + [0]*6 263 iday = array(icorr)[yday-1] 264 265 # Find correction 266 noclass = (cl == 0) 267 icl = array(cl-1, dtype=int) 268 ifov = array(fov-1, dtype=int) 203 269 204 coef = [] 270 for ii in ich: 271 dd = zeros(cl.shape)+NaN 272 dd[~noclass] = coef_corr[iday[~noclass], icl[~noclass], ifov[~noclass], ii] 273 coef.append(dd) 205 # Read the coefficient correction file for each channel 206 for ich in ch: 207 fic_corr = '/homedata/mleduc/CorrTb/corrTb_AMSUB_MHS_L1C_smooth_%s.nc' % ich 208 fileID = netCDF4.Dataset(fic_corr) 209 coef_corr = fileID.variables['corrTb'][:] 210 if ich == ch[0]: 211 lat_corr = fileID.variables['lat'][:] 212 lon_corr = fileID.variables['lon'][:] 213 day_corr = fileID.variables['day'][:] 214 215 # Latitude limits of classification (ie tropical band) 216 latstep = abs(diff(lat_corr))[0] 217 latmin = lat_corr.min()-latstep/2. 218 latmax = lat_corr.max()+latstep/2. 219 220 # Geographic projection (lon/lat in degrees to x/y in m) 221 projG = pyproj.Proj("+proj=merc +ellps=WGS84 +datum=WGS84") 222 longd_corr, latgd_corr = meshgrid(lon_corr, lat_corr) 223 xcorr, ycorr = projG(longd_corr, latgd_corr) 224 225 # Kd-tree to find the nearest neighbour (euclidian distance) 226 tree = spatial.cKDTree(zip(ravel(xcorr), ravel(ycorr))) 227 228 # Find the day of correction 229 nday = day_corr.size 230 daystep = int(abs(diff(day_corr))[0]) 231 icorr = [[ii]*daystep for ii in xrange(nday)] + [0]*6 232 233 fileID.close() 234 # Only points in the area of classification 235 inclass = logical_and(lat >= latmin, lat <= latmax) 236 # index for days 237 iday = hstack(icorr)[yday[inclass]-1] 238 # index for location in the swath 239 ifov = array(fov[inclass]-1, dtype=int) 240 # index for lon/lat 241 xx, yy = projG(lon[inclass], lat[inclass]) 242 _, ind = tree.query(zip(xx, yy)) 243 # Find coefficient of correction 244 coefch = zeros(lat.shape, dtype=float32)+NaN 245 coefch[inclass] = [coef_corr[dd, :, :, ff].flatten()[ii] for dd, ff, ii in zip(iday, ifov, ind)] 246 # Concatenate channel 247 coef.append(coefch) 274 248 275 249 return float32(coef)
Note: See TracChangeset
for help on using the changeset viewer.