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

Last change on this file since 571 was 571, checked in by lfita, 9 years ago

Using `leaving_last_spaces' on the name of the station

File size: 5.7 KB
Line 
1# Python script to transfomr ASCII LIDAR outputs to netCDF
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
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
16def ts_header(ln):
17    """ Function to get the values of the header of the *.TS files
18      line=ASCII lines with the header of the TS file
19      getting the line format from WRFV3.3 'EMCORE' in file 'share/wrf_timeseries.F'
20    """
21    fname = 'ts_header'
22
23    fmts=['A26', 'I2', 'I3', 'A6', 'A2', 'F7.3', 'A1', 'F8.3', 'A3', 'I4', 'A1', 'I4',\
24      'A3', 'F7.3', 'A1', 'F8.3', 'A2', 'F6.1', 'A7']
25
26    headervalues = ncvar.values_fortran_fmt(ln,fmts)
27
28    return headervalues
29
30####### ###### ##### #### ### ## #
31
32parser = OptionParser()
33parser.add_option("-f", "--TS_file", dest="lfile",
34  help="Time Series ASCII text file to use", metavar="FILE")
35parser.add_option("-s", "--SimulationStartTime", dest="stime",
36  help="Starting time of the simulation ([YYYY][MM][DD][HH][MI][SS] format)", metavar="DATE")
37
38(opts, args) = parser.parse_args()
39
40
41tsvn = ['t', 'q', 'u', 'v', 'psfc', 'glw', 'gsw', 'hfx', 'lh', 'tsk', 'tslb1', 'rainc', 'rainnc', 'clw']
42
43tsvln = ['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']
44
45tsvu = ['K', 'kg/kg', 'm/s', 'm/s', 'Pa', 'W/m2', 'W/m2', 'W/m2', 'W/m2', 'K', 'K', 'mm', 'mm', '1']
46
47#######    #######
48## MAIN
49    #######
50
51ofile = 'ts.nc'
52Ntsvariables = len(tsvn)
53
54if not os.path.isfile(opts.lfile):
55    print errormsg
56    print '  ' + main + ': Time-Series ASCII text file "' + opts.lfile +             \
57      '" does not exist !!'
58    print errormsg
59    quit()
60
61if opts.stime is None:
62    print errormsg
63    print '  ' + main + ': No initial date/time of the simulation is provided!'
64    quit(-1)
65else:
66    stime = opts.stime
67    refdate = stime[0:4] + '-' + stime[4:6] + '-' + stime[6:8] + ' ' + stime[8:10] + \
68      ':' + stime[10:12] + ':' + stime[12:14]
69
70objlfile = open(opts.lfile, 'r')
71
72objofile = NetCDFFile(ofile, 'w')
73
74# Creation of dimensions
75##
76objofile.createDimension('time',None)
77
78ncvar.set_attribute(objofile, 'author', 'Lluis Fita Borrell')
79ncvar.set_attribute(objofile, 'institution', 'Laboratoire Meteorologique Dynamique')
80ncvar.set_attribute(objofile, 'university', 'University Pierre et Marie Curie')
81ncvar.set_attribute(objofile, 'center', 'Centre national de la recherche scientifique')
82ncvar.set_attribute(objofile, 'country', 'France')
83ncvar.set_attribute(objofile, 'city', 'Paris')
84ncvar.set_attribute(objofile, 'script', 'TS_ASCII_netCFD.py')
85ncvar.set_attribute(objofile, 'version', '1.0')
86
87time_step = []
88psfc = []
89rainc = []
90rainnc = []
91drydens = []
92
93tsvals = {}
94
95iline=0
96itz = 0
97for line in objlfile:
98    values = ncvar.reduce_spaces(line)
99#    print iline, values[0], dimz, Searchdimz
100# Writting general information
101    if iline == 0:
102        newvar = objofile.createVariable('station','c')
103        valueshead = ts_header(line)
104
105        ncvar.set_attribute(newvar, 'name', ncvar.reduce_last_spaces(valueshead[0]))
106        ncvar.set_attribute(newvar, 'acronym',valueshead[3].replace(' ',''))
107
108        ncvar.set_attribute(newvar, 'real_lon', valueshead[5])
109        ncvar.set_attribute(newvar, 'real_lat', valueshead[7])
110
111        ncvar.set_attribute(newvar, 'x_grid_point', valueshead[9])
112        ncvar.set_attribute(newvar, 'y_grid_point', valueshead[11])
113
114        ncvar.set_attribute(newvar, 'model_lon', valueshead[13])
115        ncvar.set_attribute(newvar, 'model_lat', valueshead[15])
116        ncvar.set_attribute(newvar, 'model_height', valueshead[17])
117        simstarttime = refdate
118    else:
119        tsvals[itz] = values
120        time_step.append(np.float(values[1]))
121        itz = itz + 1
122    iline = iline + 1
123
124dimt = len(time_step)
125
126print '  Found:',dimt,'time steps'
127objlfile.close()
128
129time_stepv = np.zeros((dimt), dtype=np.float)
130tsvaluesv = np.zeros( (dimt,Ntsvariables), dtype= np.float)
131
132pracc = np.zeros((dimt), dtype=np.float)
133
134itz = 0
135for it in range(dimt):
136    time_stepv[it] = np.float(time_step[it])
137
138    for iv in range(Ntsvariables):
139        tsvaluesv[it,iv] = np.float(tsvals[itz][iv+5])
140
141    pracc[it] = np.float(tsvals[it][16]) + np.float(tsvals[it][17])
142    itz = itz + 1
143
144# time
145newvar = objofile.createVariable('time','f8',('time'))
146newvar[:] = time_stepv*3600.
147newattr = ncvar.basicvardef(newvar, 'time', 'time', 'seconds since ' +               \
148  simstarttime.replace('_',' '))
149ncvar.set_attribute(newvar, 'calendar', 'standard')
150
151# time-series variables
152for iv in range(Ntsvariables):
153    newvar = objofile.createVariable(tsvn[iv], 'f4', ('time'))
154    newvar[:] = tsvaluesv[:,iv]
155    newattr = ncvar.basicvardef(newvar, tsvn[iv], tsvln[iv], tsvu[iv] )
156
157# Extra vars
158
159# pr
160varvals = np.zeros((dimt), dtype=np.float)
161varvals[1:dimt] = pracc[1:dimt] - pracc[0:dimt-1]
162
163newvar = objofile.createVariable('pr', 'f4', ('time'))
164newvar[:] = varvals
165newattr = ncvar.basicvardef(newvar, 'pr', 'precipitation', 'mm' )
166
167objofile.sync()
168objofile.close()
169
170print 'Successfull generation of Time-Series netCDF file "' + ofile + '" !!!!!'
Note: See TracBrowser for help on using the repository browser.