source: lmdz_wrf/trunk/tools/TS_ASCII_netCDF.py @ 369

Last change on this file since 369 was 353, checked in by lfita, 10 years ago

Adding de-accumulated total precipitation 'pr'

File size: 5.8 KB
RevLine 
[351]1# Python script to transfomr ASCII LIDAR outputs to netCDF
[352]2## g.e. # TS_ASCII_netCDF.py -f //media/ExtDiskD/bkup/ciclad/etudes/WL_HyMeX/iop15/wrf/run/control/stations_20121018000000-20121022000000/h0001.d01.TS -s 20121018000000
[351]3
4import os
5from optparse import OptionParser
6import numpy as np
7from netCDF4 import Dataset as NetCDFFile
8import nc_var_tools as ncvar
9
10main = 'TS_ASCII_netCDF.py'
11errormsg='ERROR -- error -- ERROR -- error'
12warnmsg='WARNING -- warning -- WARNING -- warning'
13
14fillValue = 1.e20
15
16####### ###### ##### #### ### ## #
17
18parser = OptionParser()
19parser.add_option("-f", "--TS_file", dest="lfile",
[352]20  help="Time Series ASCII text file to use", metavar="FILE")
21parser.add_option("-s", "--SimulationStartTime", dest="stime",
22  help="Starting time of the simulation ([YYYY][MM][DD][HH][MI][SS] format)", metavar="DATE")
[351]23
24(opts, args) = parser.parse_args()
25
26
27tsvn = ['t', 'q', 'u', 'v', 'psfc', 'glw', 'gsw', 'hfx', 'lh', 'tsk', 'tslb1', 'rainc', 'rainnc', 'clw']
28
29tsvln = ['2 m Temperature', '2 m vapor mixing ratio', '10 m U wind (earth-relative)', '10 m V wind (earth-relative)', 'surface pressure', 'downward longwave radiation flux at the ground (downward is positive)', 'net shortwave radiation flux at the ground (downward is positive)', 'surface sensible heat flux (upward is positive)', 'surface latent heat flux (upward is positive)', 'skin temperature', 'top soil layer temperature', 'rainfall from a cumulus scheme', 'rainfall from an explicit scheme', 'total column-integrated water vapor and cloud variables']
30
[352]31tsvu = ['K', 'kg/kg', 'm/s', 'm/s', 'Pa', 'W/m2', 'W/m2', 'W/m2', 'W/m2', 'K', 'K', 'mm', 'mm', '1']
[351]32
33#######    #######
34## MAIN
35    #######
36
37ofile = 'ts.nc'
38Ntsvariables = len(tsvn)
39
40if not os.path.isfile(opts.lfile):
41    print errormsg
[352]42    print '  ' + main + ': Time-Series ASCII text file "' + opts.lfile +             \
43      '" does not exist !!'
[351]44    print errormsg
45    quit()
46
[352]47if opts.stime is None:
48    print errormsg
49    print '  ' + main + ': No initial date/time of the simulation is provided!'
50    quit(-1)
51else:
52    stime = opts.stime
53    refdate = stime[0:4] + '-' + stime[4:6] + '-' + stime[6:8] + ' ' + stime[8:10] + \
54      ':' + stime[10:12] + ':' + stime[12:14]
55
[351]56objlfile = open(opts.lfile, 'r')
57
58objofile = NetCDFFile(ofile, 'w')
59
60# Creation of dimensions
61##
62objofile.createDimension('time',None)
63
64ncvar.set_attribute(objofile, 'author', 'Lluis Fita Borrell')
65ncvar.set_attribute(objofile, 'institution', 'Laboratoire Meteorologique Dynamique')
66ncvar.set_attribute(objofile, 'university', 'University Pierre et Marie Curie')
67ncvar.set_attribute(objofile, 'center', 'Centre national de la recherche scientifique')
68ncvar.set_attribute(objofile, 'country', 'France')
69ncvar.set_attribute(objofile, 'city', 'Paris')
70ncvar.set_attribute(objofile, 'script', 'TS_ASCII_netCFD.py')
71ncvar.set_attribute(objofile, 'version', '1.0')
72
73time_step = []
74psfc = []
75rainc = []
76rainnc = []
77drydens = []
78
79tsvals = {}
80
81iline=0
82itz = 0
83for line in objlfile:
84    values = ncvar.reduce_spaces(line)
85#    print iline, values[0], dimz, Searchdimz
86# Writting general information
87    if iline == 0:
88        newvar = objofile.createVariable('station','c')
89        ncvar.set_attribute(newvar, 'name',values[0])
90        ncvar.set_attribute(newvar, 'acronym',values[3])
91        ncvar.set_attribute(newvar, 'real_lon',                                      \
92          np.float(values[6].replace(',','').replace('(','').replace(')','')) )
93        ncvar.set_attribute(newvar, 'real_lat',                                      \
94          np.float(values[5].replace(',','').replace('(','').replace(')','')) )
95        ncvar.set_attribute(newvar, 'x_grid_point',                                  \
96          int(values[8].replace(',','').replace('(','').replace(')','')) )
97        ncvar.set_attribute(newvar, 'y_grid_point',                                  \
98          int(values[9].replace(',','').replace('(','').replace(')','')) )
99        ncvar.set_attribute(newvar, 'model_lon',                                     \
100          np.float(values[12].replace(',','').replace('(','').replace(')','')) )
101        ncvar.set_attribute(newvar, 'model_lat',                                     \
102          np.float(values[11].replace(',','').replace('(','').replace(')','')) )
103        ncvar.set_attribute(newvar, 'model_height',                                  \
104          np.float(values[13].replace(',','').replace('(','').replace(')','')) )
[352]105        simstarttime = refdate
[351]106    else:
107        tsvals[itz] = values
[352]108        time_step.append(np.float(values[1]))
109        itz = itz + 1
[351]110    iline = iline + 1
111
112dimt = len(time_step)
113
[352]114print '  Found:',dimt,'time steps'
[351]115objlfile.close()
116
117time_stepv = np.zeros((dimt), dtype=np.float)
[352]118tsvaluesv = np.zeros( (dimt,Ntsvariables), dtype= np.float)
[351]119
[353]120pracc = np.zeros((dimt), dtype=np.float)
121
[351]122itz = 0
123for it in range(dimt):
124    time_stepv[it] = np.float(time_step[it])
125
[352]126    for iv in range(Ntsvariables):
127        tsvaluesv[it,iv] = np.float(tsvals[itz][iv+5])
[351]128
[353]129    pracc[it] = np.float(tsvals[it][16]) + np.float(tsvals[it][17])
[352]130    itz = itz + 1
[353]131
132# time
[352]133newvar = objofile.createVariable('time','f8',('time'))
[351]134newvar[:] = time_stepv
135newattr = ncvar.basicvardef(newvar, 'time', 'time', 'hours since ' +                 \
136  simstarttime.replace('_',' '))
[352]137ncvar.set_attribute(newvar, 'calendar', 'standard')
[351]138
[352]139# time-series variables
[351]140for iv in range(Ntsvariables):
[352]141    newvar = objofile.createVariable(tsvn[iv], 'f4', ('time'))
142    newvar[:] = tsvaluesv[:,iv]
[351]143    newattr = ncvar.basicvardef(newvar, tsvn[iv], tsvln[iv], tsvu[iv] )
144
[353]145# Extra vars
146
147# pr
148varvals = np.zeros((dimt), dtype=np.float)
149varvals[1:dimt] = pracc[1:dimt] - pracc[0:dimt-1]
150
151newvar = objofile.createVariable('pr', 'f4', ('time'))
152newvar[:] = varvals
153newattr = ncvar.basicvardef(newvar, 'pr', 'precipitation', 'mm' )
154
[351]155objofile.sync()
156objofile.close()
157
[352]158print 'Successfull generation of Time-Series netCDF file "' + ofile + '" !!!!!'
Note: See TracBrowser for help on using the repository browser.