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

Last change on this file since 542 was 504, checked in by lfita, 10 years ago

Changing to `seconds' as unit of time

File size: 6.1 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')
[459]89        valuespar=line.split('(')
90
91        sec = ncvar.reduce_spaces(valuespar[0])
92        Nsec = len(sec)
[461]93        ncvar.set_attribute(newvar, 'name', ncvar.numVector_String(sec[0:Nsec-3],' '))
[459]94        ncvar.set_attribute(newvar, 'acronym',sec[Nsec-1])
95
96        sec = ncvar.reduce_spaces(valuespar[1])
97        Nsec = len(sec)
[351]98        ncvar.set_attribute(newvar, 'real_lon',                                      \
[459]99          np.float(sec[1].replace(',','').replace('(','').replace(')','')) )
[351]100        ncvar.set_attribute(newvar, 'real_lat',                                      \
[459]101          np.float(sec[0].replace(',','').replace('(','').replace(')','')) )
102
103        sec = ncvar.reduce_spaces(valuespar[2])
104        Nsec = len(sec)
[351]105        ncvar.set_attribute(newvar, 'x_grid_point',                                  \
[459]106          int(sec[0].replace(',','').replace('(','').replace(')','')) )
[351]107        ncvar.set_attribute(newvar, 'y_grid_point',                                  \
[459]108          int(sec[1].replace(',','').replace('(','').replace(')','')) )
109
110        sec = ncvar.reduce_spaces(valuespar[3])
111        Nsec = len(sec)
[351]112        ncvar.set_attribute(newvar, 'model_lon',                                     \
[459]113          np.float(sec[1].replace(',','').replace('(','').replace(')','')) )
[351]114        ncvar.set_attribute(newvar, 'model_lat',                                     \
[459]115          np.float(sec[0].replace(',','').replace('(','').replace(')','')) )
[351]116        ncvar.set_attribute(newvar, 'model_height',                                  \
[459]117          np.float(sec[2].replace(',','').replace('(','').replace(')','')) )
[352]118        simstarttime = refdate
[351]119    else:
120        tsvals[itz] = values
[352]121        time_step.append(np.float(values[1]))
122        itz = itz + 1
[351]123    iline = iline + 1
124
125dimt = len(time_step)
126
[352]127print '  Found:',dimt,'time steps'
[351]128objlfile.close()
129
130time_stepv = np.zeros((dimt), dtype=np.float)
[352]131tsvaluesv = np.zeros( (dimt,Ntsvariables), dtype= np.float)
[351]132
[353]133pracc = np.zeros((dimt), dtype=np.float)
134
[351]135itz = 0
136for it in range(dimt):
137    time_stepv[it] = np.float(time_step[it])
138
[352]139    for iv in range(Ntsvariables):
140        tsvaluesv[it,iv] = np.float(tsvals[itz][iv+5])
[351]141
[353]142    pracc[it] = np.float(tsvals[it][16]) + np.float(tsvals[it][17])
[352]143    itz = itz + 1
[353]144
145# time
[352]146newvar = objofile.createVariable('time','f8',('time'))
[504]147newvar[:] = time_stepv*3600.
148newattr = ncvar.basicvardef(newvar, 'time', 'time', 'seconds since ' +               \
[351]149  simstarttime.replace('_',' '))
[352]150ncvar.set_attribute(newvar, 'calendar', 'standard')
[351]151
[352]152# time-series variables
[351]153for iv in range(Ntsvariables):
[352]154    newvar = objofile.createVariable(tsvn[iv], 'f4', ('time'))
155    newvar[:] = tsvaluesv[:,iv]
[351]156    newattr = ncvar.basicvardef(newvar, tsvn[iv], tsvln[iv], tsvu[iv] )
157
[353]158# Extra vars
159
160# pr
161varvals = np.zeros((dimt), dtype=np.float)
162varvals[1:dimt] = pracc[1:dimt] - pracc[0:dimt-1]
163
164newvar = objofile.createVariable('pr', 'f4', ('time'))
165newvar[:] = varvals
166newattr = ncvar.basicvardef(newvar, 'pr', 'precipitation', 'mm' )
167
[351]168objofile.sync()
169objofile.close()
170
[352]171print 'Successfull generation of Time-Series netCDF file "' + ofile + '" !!!!!'
Note: See TracBrowser for help on using the repository browser.