-
Notifications
You must be signed in to change notification settings - Fork 1
/
OSSE_helper.py
executable file
·206 lines (175 loc) · 7.24 KB
/
OSSE_helper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
#!/usr/bin/env python
import math
import numpy as np
from netCDF4 import Dataset
from datetime import datetime
from datetime import timedelta
import glob
# given a template with {y4} {m2} {d2} {h2} {mn2} and {s2}
def get_filename_from_tpl(ftpl, time) :
return ftpl.format(y4=time.year, m2=str(time.month).zfill(2), \
d2 = str(time.day).zfill(2), h2=str(time.hour).zfill(2), \
mn2= str(time.minute).zfill(2), s2=str(time.second).zfill(2))
def get_time_from_filename(ftpl, filename):
last_ = ftpl.rfind('/')
fname = ftpl[last_+1:]
k_year = fname.find('{y4}')
k_mon = fname.find('{m2}')
k_day = fname.find('{d2}') - 2
k_hour = fname.find('{h2}') - 4
k_min = fname.find('{mn2}')- 6
k_sec = fname.find('{s2}') - 9
last_ = filename.rfind('/')
fname = filename[last_+1:]
YYYY = fname[k_year:k_year+4] if k_year >=0 else '0000'
MM = fname[k_mon:k_mon+2] if k_mon >=0 else '00'
DD = fname[k_day:k_day+2] if k_day >=0 else '00'
HH = fname[k_hour:k_hour+2] if k_hour >=0 else '00'
MN = fname[k_min:k_min+2] if k_min >=0 else '00'
SS = fname[k_sec:k_sec+2] if k_sec >=0 else '00'
time_format = '-'.join((YYYY,MM,DD))+' '+":".join((HH,MN,SS))
return datetime.fromisoformat(time_format)
def get_two_files_from_tpl(ftpl, time):
last_ = ftpl.rfind('/')
fpath = ftpl[:last_] if (last_ >=0) else '.'
fpath = get_filename_from_tpl(fpath, time)
fname = ftpl[last_+1:]
wild = fname.replace('{y4}','*').replace('{m2}','*').replace('{d2}','*').replace('{h2}','*').replace('{mn2}','*')
files = glob.glob(fpath+'/'+wild)
assert files, "cannot find files " + fpath+'/'+wild
if len(files) == 1:
files.append('')
return files[0], files[1]
def get_reference_time(ftpl, time):
file0, file1 = get_two_files_from_tpl(ftpl, time)
return get_time_from_filename(ftpl, file0)
def get_duration(collection, time):
ftpl = collection['template']
file0, file1 = get_two_files_from_tpl(ftpl, time)
# if only one file, need duration
if not file1 :
assert 'duration' in collection, "duration is needed when there is only one file: " + file0
return timedelta(seconds = int(collection['duration']))
ref_time0 = get_time_from_filename(ftpl, file0)
ref_time1 = get_time_from_filename(ftpl, file1)
return ref_time1-ref_time0
def get_pre_filename(collection, time):
duration = get_duration(collection, time)
ftpl = collection['template']
ref_time = get_reference_time(ftpl, time)
distance = math.floor((time -ref_time)/duration)
time_ = ref_time + distance * duration
return get_filename_from_tpl(ftpl, time_)
def get_post_filename(collection, time):
duration = get_duration(collection, time)
ftpl = collection['template']
ref_time = get_reference_time(ftpl, time)
distance = math.ceil((time -ref_time)/duration)
time_ = ref_time + distance * duration
return get_filename_from_tpl(ftpl, time_)
def get_file_numbers(collection, start_time, end_time):
duration = get_duration(collection, start_time)
first_file = get_pre_filename(collection, start_time)
last_file = get_pre_filename(collection, end_time)
ftpl = collection['template']
first_time = get_time_from_filename(ftpl, first_file)
last_time = get_time_from_filename (ftpl, last_file)
return int(1+(last_time - first_time)/duration)
def read_sat_data(collection, start_time, end_time):
#here collection is locations
k = get_file_numbers(collection, start_time, end_time)
duration = get_duration(collection, start_time)
lats = []
lons = []
seconds_increase = []
for i in range(k):
sat_fname = get_pre_filename(collection, start_time + i*duration)
print("\nReading satellit data file "+sat_fname)
fin = open(sat_fname,'r')
for j , line in enumerate(fin):
data = line.split()
YY =int(data[0])
MM =int(data[1])
DD =int(data[2])
HH =int(data[3])
M =int(data[4])
SS =int(data[5])
time = datetime(YY, MM, DD, HH, M, SS)
if (time < start_time):
continue
if (time > end_time):
break
dtime = time - start_time
seconds_increase.append(dtime.total_seconds())
lats.append(float(str(data[6][0:])))
lons.append(float(str(data[7][0:])))
fin.close()
return lats, lons, seconds_increase
def read_vars_from_collection(var_names, collection, start_time, end_time, lats, lons, seconds_increase,var_dict) :
k = get_file_numbers(collection, start_time, end_time)
duration = get_duration(collection, start_time)
fname = get_pre_filename(collection, start_time)
time_ = get_time_from_filename(collection['template'], fname)
offset = (start_time - time_).total_seconds()
fh = Dataset(fname,mode='r')
n_level = fh.dimensions['lev'].size
n_lat = fh.dimensions['lat'].size
n_lon = fh.dimensions['lon'].size
dlat = 180.0/n_lat
dlon = 360.0/n_lon
fh.close()
var = np.ndarray(shape=(n_level, len(lats)))
k0 = 0
k1 = 0
for i in range(k):
while k1 < len(lats) :
if (seconds_increase[k1] + offset >= (i+1) * duration.total_seconds()) :
break
k1 += 1
# for each file, figure out the time that passed in
fname = get_pre_filename(collection, time_)
fh = Dataset(fname,mode='r')
Is =((np.array(lats[k0:k1])+90.0 )/dlat).astype('int32')
Js =((np.array(lons[k0:k1])+180.0)/dlon).astype('int32')
var_list = var_names.split()
vars_str = ' '.join([vname for vname in var_list])
print("\nReading (" + vars_str + ") from " + fname)
for var_name in var_list:
var_in = fh.variables[var_name][:, :, :, :]
for ki in range(len(Is)):
var[:,k0+ki] = var_in[0,:,Is[ki],Js[ki]]
# this last file
if (i == k-1) :
var_dict[var_name] = (n_level, var, fh.variables[var_name].__dict__)
fh.close()
k0 = k1
time_ = time_ + duration
def write_variables(fname, start_time, var_dict, lats, lons, seconds_increase):
fh = Dataset(fname, 'w', format='NETCDF4')
index = fh.createDimension('index', len(lats))
val_ = next(iter(var_dict.values()))
level = fh.createDimension('lev', val_[0])
second_ = fh.createVariable('seconds_increase', np.float32, ('index',))
second_[:] = seconds_increase[:]
time_stamp = start_time.strftime('%s-%02d-%02d %02d:%02d:%02d'%(start_time.year, \
start_time.month,start_time.day,start_time.hour, start_time.minute, start_time.second))
second_.units = "seconds since " + time_stamp
second_.long_name = " seconds_increment" ;
lats_ = fh.createVariable('lat', np.float32, ('index',))
lats_.long_name = "latitude" ;
lats_.units = "degrees_north" ;
lons_ = fh.createVariable('lon', np.float32, ('index',))
lons_.long_name = "longitude" ;
lons_.units = "degrees_east" ;
for key, value in var_dict.items():
value_ = fh.createVariable(key, np.float32, ('lev','index',))
value_.setncatts(value[2])
value_[:,:] = value[1][:,:]
lats_[:] =lats[:]
lons_[:] =lons[:]
fh.close()
if __name__ == '__main__' :
ftmp = 'Year {y4} month {m2} day {d2} hour {h2} minute {mn2} second {s2}'
now = datetime.now()
name = get_filename_from_tpl(ftmp, now)
print(name)