-
Notifications
You must be signed in to change notification settings - Fork 0
/
mflst.py
374 lines (324 loc) · 13.6 KB
/
mflst.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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import os
import re
from datetime import datetime,timedelta
import numpy as np
import pandas
class lstbudget():
def __init__(self,file_name):
raise Exception('base class lstbudget does not have a constructor - must call a derived class')
def to_pandas(self):
'''creates flux and vol dataframes with a multiindex of entry order (in list file) and (in,out)
'''
tss,sps = [],[]
for ts,sp,seekpoint in self.idx_map:
tss.append(ts)
sps.append(sp)
df_flux,df_vol = None,None
if self.flux:
in_dict = {}
out_dict = {}
for entry,record in self.flux.iteritems():
in_dict[entry] = record[0]
out_dict[entry] = record[1]
df_in = pandas.DataFrame(in_dict,index=[tss,sps])
df_out = pandas.DataFrame(out_dict,index=[tss,sps])
df_flux = pandas.concat([df_in,df_out],axis=1,keys=('in','out'))
if self.cumu:
in_dict = {}
out_dict = {}
for entry,record in self.cumu.iteritems():
in_dict[entry] = record[0]
out_dict[entry] = record[1]
df_in = pandas.DataFrame(in_dict,index=[tss,sps])
df_out = pandas.DataFrame(out_dict,index=[tss,sps])
df_vol = pandas.concat([df_in,df_out],axis=1,keys=('in','out'))
return df_flux,df_vol
def build_index(self,maxentries):
print 'building index...'
self.idx_map = self.get_index(maxentries)
print '\ndone - found',len(self.idx_map),'entries'
def get_index(self,maxentries):
#--parse throught the file looking for matches and parsing ts and sp
idxs = []
l_count = 1
while True:
seekpoint = self.f.tell()
line = self.f.readline()
if line == '':
break
#if self.lstkey.match(line.strip()) != None:
if self.lstkey in line:
for l in range(self.tssp_lines):
line = self.f.readline()
try:
ts,sp = self.get_ts_sp(line)
except:
print 'unable to cast ts,sp on line number',l_count,' line: ',line
break
print 'info found for timestep stress period',ts,sp,'\r',
idxs.append([ts,sp,seekpoint])
if maxentries and len(idxs) >= maxentries:
break
#------------------testing------------------
#if sp == 10:
# break
return idxs
def get_ts_sp(self,line):
ts = int(line[self.ts_idxs[0]:self.ts_idxs[1]])
sp = int(line[self.sp_idxs[0]:self.sp_idxs[1]])
return ts,sp
def set_entries(self):
if self.entries:
raise Exception('entries already set'+str(self.enties))
if not self.idx_map:
raise Exception('must call build_index before call set_entries')
try:
influx,incu,outflux,outcu = self.get_sp(self.idx_map[0][0],self.idx_map[0][1],self.idx_map[0][2])
except:
raise Exception('unable to read budget information from first entry in list file')
self.entries = influx.keys()
null_entries = {}
for entry in influx.keys():
self.flux[entry] = [[],[]]
self.cumu[entry] = [[],[]]
null_entries[entry] = np.NaN
self.null_entries = [null_entries,null_entries,null_entries,null_entries]
def load(self,maxentries=None):
self.build_index(maxentries)
self.set_entries()
for ts,sp,seekpoint in self.idx_map:
#print 'loading stress period, timestep',sp,ts
influx,incu,outflux,outcu = self.get_sp(ts,sp,seekpoint)
for entry in self.entries:
self.flux[entry][0].append(influx[entry])
self.flux[entry][1].append(outflux[entry])
self.cumu[entry][0].append(incu[entry])
self.cumu[entry][1].append(outcu[entry])
return
def get_sp(self,ts,sp,seekpoint):
self.f.seek(seekpoint)
#--read to the start of the "in" budget information
while True:
line = self.f.readline()
if line == '':
#raise Exception('end of file found while seeking budget information')
print 'end of file found while seeking budget information for ts,sp',ts,sp
return self.null_entries
#--if there are two '=' in this line, then it is a budget line
if len(re.findall('=',line)) == 2:
break
infx,incu = {},{}
while True:
if line == '':
#raise Exception('end of file found while seeking budget information')
print 'end of file found while seeking budget information for ts,sp',ts,sp
return self.null_entries
if line == '\n' or len(re.findall('=',line)) != 2:
break
try:
entry,flux,cumu = self.parse_budget_line(line)
except e:
print 'error parsing budget line in ts,sp',ts,sp
return self.null_entries
if flux is None:
print 'error casting in flux for',entry,' to float in ts,sp',ts,sp
return self.null_entries
if cumu is None:
print 'error casting in cumu for',entry,' to float in ts,sp',ts,sp
return self.null_entries
infx[entry] = flux
incu[entry] = cumu
line = self.f.readline()
#--read to the start of the "OUT" budget information
while True:
line = self.f.readline()
if line == '':
#raise Exception('end of file found while seeking budget information')
print 'end of file found while seeking budget information'
return self.null_entries
if len(re.findall('=',line)) == 2 and 'TOTAL' not in line.upper():
break
outfx,outcu = {},{}
while True:
if line == '':
#raise Exception('end of file found while seeking budget information')
print 'end of file found while seeking budget information'
return self.null_entries
if line == '\n' or len(re.findall('=',line)) != 2:
break
try:
entry,flux,cumu = self.parse_budget_line(line)
except e:
print 'error parsing budget line in ts,sp',ts,sp
return self.null_entries
if flux is None:
print 'error casting out flux for',entry,' to float in ts,sp',ts,sp
return self.null_entries
if cumu is None:
print 'error casting out cumu for',entry,' to float in ts,sp',ts,sp
return self.null_entries
outfx[entry] = flux
outcu[entry] = cumu
line = self.f.readline()
return infx,incu,outfx,outcu
def parse_budget_line(self,line):
raw = line.strip().split()
entry = line.strip().split('=')[0].strip()
cu_str = line[self.cumu_idxs[0]:self.cumu_idxs[1]]
fx_str = line[self.flux_idxs[0]:self.flux_idxs[1]]
flux,cumu = None,None
try:
cumu = float(cu_str)
except:
if 'NAN' in cu_str.strip().upper():
cumu = np.NaN
try:
flux = float(fx_str)
except:
if 'NAN' in fx_str.strip().upper():
flux = np.NaN
return entry,flux,cumu
class seawatbudget(lstbudget):
def __init__(self,file_name,key_string='MASS BUDGET FOR ENTIRE MODEL'):
assert os.path.exists(file_name)
self.file_name = file_name
self.f = open(file_name,'r')
#self.lstkey = re.compile(key_string)
self.lstkey = key_string
self.idx_map = []
self.entries = []
self.null_entries = []
self.flux = {}
self.cumu = {}
self.cumu_idxs = [22,40]
self.flux_idxs = [63,80]
self.ts_idxs = [50,54]
self.sp_idxs = [70,75]
self.tssp_lines = 0
class mfbudget(lstbudget):
def __init__(self,file_name,key_string='VOLUMETRIC BUDGET FOR ENTIRE MODEL'):
assert os.path.exists(file_name)
self.file_name = file_name
self.f = open(file_name,'r')
#self.lstkey = re.compile(key_string)
self.lstkey = key_string
self.idx_map = []
self.entries = []
self.null_entries = []
self.flux = {}
self.cumu = {}
self.cumu_idxs = [22,40]
self.flux_idxs = [63,80]
self.ts_idxs = [56,61]
self.sp_idxs = [76,80]
self.tssp_lines = 0
class swrbudget(lstbudget):
def __init__(self,file_name,key_string='VOLUMETRIC SURFACE WATER BUDGET FOR ENTIRE MODEL'):
assert os.path.exists(file_name)
self.file_name = file_name
self.f = open(file_name,'r')
#self.lstkey = re.compile(key_string)
self.lstkey = key_string
self.idx_map = []
self.entries = []
self.null_entries = []
self.flux = {}
self.cumu = {}
self.cumu_idxs = [25,43]
self.flux_idxs = [66,84]
self.ts_idxs = [39,46]
self.sp_idxs = [62,68]
self.tssp_lines = 1
class lsttime(lstbudget):
'''class to extract time information from lst file
passing a start datetime results in casting the totim to dts from start
'''
def __init__(self,file_name,timeunit='days',key_str='TIME SUMMARY AT END',start=None,flow=True):
assert os.path.exists(file_name)
self.file_name = file_name
self.f = open(file_name,'r')
self.idx_map = []
self.tslen = []
self.sptim = []
self.totim = []
#self.lstkey = re.compile(key_str)
self.lstkey = key_str
self.tssp_lines = 0
if flow:
self.ts_idxs = [42,47]
self.sp_idxs = [63,69]
else:
self.ts_idxs = [65,71]
self.sp_idxs = [87,92]
self.time_line_idx = 20
if timeunit.upper() =='DAYS':
self.timeunit = 'D'
self.time_idx = 3
else:
raise Exception('need to reset time_idxs attribute to use units other than days and check usage of timedelta')
self.null_entries = [np.NaN,np.NaN,np.NaN]
self.start = start
if start:
self.dt = []
def to_pandas(self):
tss,sps = [],[]
for ts,sp,seekpoint in self.idx_map:
tss.append(ts)
sps.append(sp)
if self.start is None:
df = pandas.DataFrame({'tslen':self.tslen,'sptim':self.sptim,'totim':self.totim},index=[tss,sps])
else:
df = pandas.DataFrame({'tslen':self.tslen,'sptim':self.sptim,'totim':self.totim,'datetime':self.dt},index=[tss,sps])
return df
def load(self,maxentries=None):
self.build_index(maxentries)
for i,[ts,sp,seekpoint] in enumerate(self.idx_map):
#print 'loading stress period, timestep',sp,ts,
tslen,sptim,totim = self.get_sp(ts,sp,seekpoint)
self.tslen.append(tslen)
self.sptim.append(sptim)
self.totim.append(totim)
if self.start is not None:
self.dt = self.cast_totim()
return
def cast_totim(self):
if self.timeunit == 'D':
totim = []
for to in self.totim:
t = timedelta(days=to)
totim.append(self.start + t)
return totim
def get_sp(self,ts,sp,seekpoint):
self.f.seek(seekpoint)
#--read two lines
for i in range(3):
line = self.f.readline()
if line == '':
#raise Exception('end of file found while seeking budget information')
print 'end of file found while seeking time information for ts,sp',ts,sp
return self.null_entries
tslen = self.parse_time_line(self.f.readline())
if tslen == None:
print 'error parsing tslen for ts,sp',ts,sp
return self.null_entries
sptim = self.parse_time_line(self.f.readline())
if sptim == None:
print 'error parsing sptim for ts,sp',ts,sp
return self.null_entries
totim = self.parse_time_line(self.f.readline())
if totim == None:
print 'error parsing totim for ts,sp',ts,sp
return self.null_entries
return tslen,sptim,totim
def parse_time_line(self,line):
if line == '':
print 'end of file found while parsing time information'
return None
try:
time_str = line[self.time_line_idx:]
raw = time_str.split()
tval = float(raw[self.time_idx])
except:
print 'error parsing tslen information',time_str
return None
return tval