forked from respec/HSPsquared
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
414 lines (361 loc) · 22.2 KB
/
main.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
''' Copyright (c) 2020 by RESPEC, INC.
Author: Robert Heaphy, Ph.D.
License: LGPL2
'''
from re import S
from numpy import float64, float32
from pandas import DataFrame, date_range
from pandas.tseries.offsets import Minute
from datetime import datetime as dt
import os
from HSP2.utilities import versions, get_timeseries, expand_timeseries_names, save_timeseries, get_gener_timeseries
from HSP2.configuration import activities, noop, expand_masslinks
from HSP2.state import *
from HSP2IO.io import IOManager, SupportsReadTS, Category
def main(io_manager:IOManager, saveall:bool=False, jupyterlab:bool=True) -> None:
"""Runs main HSP2 program.
Parameters
----------
saveall: Boolean - [optional] Default is False.
Saves all calculated data ignoring SAVE tables.
jupyterlab: Boolean - [optional] Default is True.
Flag for specific output behavior for jupyter lab.
Return
------------
None
"""
hdfname = './'
if not os.path.exists(hdfname):
raise FileNotFoundError(f'{hdfname} HDF5 File Not Found')
msg = messages()
msg(1, f'Processing started for file {hdfname}; saveall={saveall}')
# read user control, parameters, states, and flags uci and map to local variables
uci_obj = io_manager.read_uci()
opseq = uci_obj.opseq
ddlinks = uci_obj.ddlinks
ddmasslinks = uci_obj.ddmasslinks
ddext_sources = uci_obj.ddext_sources
ddgener = uci_obj.ddgener
uci = uci_obj.uci
siminfo = uci_obj.siminfo
ftables = uci_obj.ftables
specactions = uci_obj.specactions
monthdata = uci_obj.monthdata
specactions = {} # placeholder till added to uci parser
start, stop = siminfo['start'], siminfo['stop']
copy_instances = {}
gener_instances = {}
#######################################################################################
# initilize STATE dicts
#######################################################################################
# Set up Things in state that will be used in all modular activitis like SPECL
state = init_state_dicts()
state_siminfo_hsp2(uci_obj, siminfo)
# Add support for dynamic functins to operate on STATE
# - Load any dynamic components if present, and store variables on objects
state_load_dynamics_hsp2(state, io_manager, siminfo)
# - finally stash specactions in state, not domain (segment) dependent so do it once
state['specactions'] = specactions # stash the specaction dict in state
#######################################################################################
# main processing loop
msg(1, f'Simulation Start: {start}, Stop: {stop}')
tscat = {}
for _, operation, segment, delt in opseq.itertuples():
msg(2, f'{operation} {segment} DELT(minutes): {delt}')
siminfo['delt'] = delt
siminfo['tindex'] = date_range(start, stop, freq=Minute(delt))[1:]
siminfo['steps'] = len(siminfo['tindex'])
if operation == 'COPY':
copy_instances[segment] = activities[operation](io_manager, siminfo, ddext_sources[(operation,segment)])
elif operation == 'GENER':
try:
gener_instances[segment] = activities[operation](segment, siminfo, copy_instances, gener_instances, ddlinks, ddgener)
except NotImplementedError as e:
print(f"GENER '{segment}' encountered unsupported feature during initialization and may not function correctly. Unsupported feature: '{e}'")
else:
# now conditionally execute all activity modules for the op, segment
ts = get_timeseries(io_manager,ddext_sources[(operation,segment)],siminfo)
ts = get_gener_timeseries(ts, gener_instances, ddlinks[segment],ddmasslinks)
flags = uci[(operation, 'GENERAL', segment)]['ACTIVITY']
if operation == 'RCHRES':
# Add nutrient adsorption flags:
if flags['NUTRX'] == 1:
flags['TAMFG'] = uci[(operation, 'NUTRX', segment)]['FLAGS']['NH3FG']
flags['ADNHFG'] = uci[(operation, 'NUTRX', segment)]['FLAGS']['ADNHFG']
flags['PO4FG'] = uci[(operation, 'NUTRX', segment)]['FLAGS']['PO4FG']
flags['ADPOFG'] = uci[(operation, 'NUTRX', segment)]['FLAGS']['ADPOFG']
get_flows(io_manager, ts, flags, uci, segment, ddlinks, ddmasslinks, siminfo['steps'], msg)
for activity, function in activities[operation].items():
if function == noop: #or not flags[activity]:
continue
if (activity in flags) and (not flags[activity]):
continue
if (activity == 'RQUAL') and (not flags['OXRX']) and (not flags['NUTRX']) and (not flags['PLANK']) and (not flags['PHCARB']):
continue
msg(3, f'{activity}')
# Set context for dynamic executables.
state_context_hsp2(state, operation, segment, activity)
ui = uci[(operation, activity, segment)] # ui is a dictionary
if operation == 'PERLND' and activity == 'SEDMNT':
# special exception here to make CSNOFG available
ui['PARAMETERS']['CSNOFG'] = uci[(operation, 'PWATER', segment)]['PARAMETERS']['CSNOFG']
if operation == 'PERLND' and activity == 'PSTEMP':
# special exception here to make AIRTFG available
ui['PARAMETERS']['AIRTFG'] = flags['ATEMP']
if operation == 'PERLND' and activity == 'PWTGAS':
# special exception here to make CSNOFG available
ui['PARAMETERS']['CSNOFG'] = uci[(operation, 'PWATER', segment)]['PARAMETERS']['CSNOFG']
if operation == 'RCHRES':
if not 'PARAMETERS' in ui:
ui['PARAMETERS'] = {}
ui['PARAMETERS']['NEXITS'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['NEXITS']
if activity == 'ADCALC':
ui['PARAMETERS']['ADFG'] = flags['ADCALC']
ui['PARAMETERS']['KS'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['KS']
ui['PARAMETERS']['VOL'] = uci[(operation, 'HYDR', segment)]['STATES']['VOL']
ui['PARAMETERS']['ROS'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['ROS']
nexits = uci[(operation, 'HYDR', segment)]['PARAMETERS']['NEXITS']
for index in range(nexits):
ui['PARAMETERS']['OS' + str(index + 1)] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['OS'+ str(index + 1)]
if activity == 'HTRCH':
ui['PARAMETERS']['ADFG'] = flags['ADCALC']
ui['advectData'] = uci[(operation, 'ADCALC', segment)]['adcalcData']
# ui['STATES']['VOL'] = uci[(operation, 'HYDR', segment)]['STATES']['VOL']
if activity == 'CONS':
ui['advectData'] = uci[(operation, 'ADCALC', segment)]['adcalcData']
if activity == 'SEDTRN':
ui['PARAMETERS']['ADFG'] = flags['ADCALC']
ui['advectData'] = uci[(operation, 'ADCALC', segment)]['adcalcData']
# ui['STATES']['VOL'] = uci[(operation, 'HYDR', segment)]['STATES']['VOL']
ui['PARAMETERS']['HTFG'] = flags['HTRCH']
ui['PARAMETERS']['AUX3FG'] = 0
if flags['HYDR']:
ui['PARAMETERS']['LEN'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['LEN']
ui['PARAMETERS']['DELTH'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['DELTH']
ui['PARAMETERS']['DB50'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['DB50']
ui['PARAMETERS']['AUX3FG'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['AUX3FG']
if activity == 'GQUAL':
ui['advectData'] = uci[(operation, 'ADCALC', segment)]['adcalcData']
ui['PARAMETERS']['HTFG'] = flags['HTRCH']
ui['PARAMETERS']['SEDFG'] = flags['SEDTRN']
# ui['PARAMETERS']['REAMFG'] = uci[(operation, 'OXRX', segment)]['PARAMETERS']['REAMFG']
ui['PARAMETERS']['HYDRFG'] = flags['HYDR']
if flags['HYDR']:
ui['PARAMETERS']['LKFG'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['LKFG']
ui['PARAMETERS']['AUX1FG'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['AUX1FG']
ui['PARAMETERS']['AUX2FG'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['AUX2FG']
ui['PARAMETERS']['LEN'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['LEN']
ui['PARAMETERS']['DELTH'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['DELTH']
if flags['OXRX']:
ui['PARAMETERS']['LKFG'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['LKFG']
ui['PARAMETERS']['CFOREA'] = uci[(operation, 'OXRX', segment)]['PARAMETERS']['CFOREA']
if flags['SEDTRN']:
ui['PARAMETERS']['SSED1'] = uci[(operation, 'SEDTRN', segment)]['STATES']['SSED1']
ui['PARAMETERS']['SSED2'] = uci[(operation, 'SEDTRN', segment)]['STATES']['SSED2']
ui['PARAMETERS']['SSED3'] = uci[(operation, 'SEDTRN', segment)]['STATES']['SSED3']
if flags['HTRCH']:
ui['PARAMETERS']['CFSAEX'] = uci[(operation, 'HTRCH', segment)]['PARAMETERS']['CFSAEX']
elif flags['PLANK']:
if 'CFSAEX' in uci[(operation, 'PLANK', segment)]['PARAMETERS']:
ui['PARAMETERS']['CFSAEX'] = uci[(operation, 'PLANK', segment)]['PARAMETERS']['CFSAEX']
if activity == 'RQUAL':
# RQUAL inputs:
ui['advectData'] = uci[(operation, 'ADCALC', segment)]['adcalcData']
if flags['HYDR']:
ui['PARAMETERS']['LKFG'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['LKFG']
ui['FLAGS']['HTFG'] = flags['HTRCH']
ui['FLAGS']['SEDFG'] = flags['SEDTRN']
ui['FLAGS']['GQFG'] = flags['GQUAL']
ui['FLAGS']['OXFG'] = flags['OXFG']
ui['FLAGS']['NUTFG'] = flags['NUTRX']
ui['FLAGS']['PLKFG'] = flags['PLANK']
ui['FLAGS']['PHFG'] = flags['PHCARB']
if flags['CONS']:
if 'PARAMETERS' in uci[(operation, 'CONS', segment)]:
if 'NCONS' in uci[(operation, 'CONS', segment)]['PARAMETERS']:
ui['PARAMETERS']['NCONS'] = uci[(operation, 'CONS', segment)]['PARAMETERS']['NCONS']
# OXRX module inputs:
ui_oxrx = uci[(operation, 'OXRX', segment)]
if flags['HYDR']:
ui_oxrx['PARAMETERS']['LEN'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['LEN']
ui_oxrx['PARAMETERS']['DELTH'] = uci[(operation, 'HYDR', segment)]['PARAMETERS']['DELTH']
if flags['HTRCH']:
ui_oxrx['PARAMETERS']['ELEV'] = uci[(operation, 'HTRCH', segment)]['PARAMETERS']['ELEV']
if flags['SEDTRN']:
ui['PARAMETERS']['SSED1'] = uci[(operation, 'SEDTRN', segment)]['STATES']['SSED1']
ui['PARAMETERS']['SSED2'] = uci[(operation, 'SEDTRN', segment)]['STATES']['SSED2']
ui['PARAMETERS']['SSED3'] = uci[(operation, 'SEDTRN', segment)]['STATES']['SSED3']
# PLANK module inputs:
if flags['HTRCH']:
ui['PARAMETERS']['CFSAEX'] = uci[(operation, 'HTRCH', segment)]['PARAMETERS']['CFSAEX']
# NUTRX, PLANK, PHCARB module inputs:
ui_nutrx = uci[(operation, 'NUTRX', segment)]
ui_plank = uci[(operation, 'PLANK', segment)]
ui_phcarb = uci[(operation, 'PHCARB', segment)]
############ calls activity function like snow() ##############
if operation not in ['COPY','GENER']:
if (activity == 'HYDR'):
errors, errmessages = function(io_manager, siminfo, ui, ts, ftables, state)
elif (activity != 'RQUAL'):
errors, errmessages = function(io_manager, siminfo, ui, ts)
else:
errors, errmessages = function(io_manager, siminfo, ui, ui_oxrx, ui_nutrx, ui_plank, ui_phcarb, ts, monthdata)
###############################################################
for errorcnt, errormsg in zip(errors, errmessages):
if errorcnt > 0:
msg(4, f'Error count {errorcnt}: {errormsg}')
if 'SAVE' in ui:
save_timeseries(io_manager,ts,ui['SAVE'],siminfo,saveall,operation,segment,activity,jupyterlab)
if (activity == 'RQUAL'):
if 'SAVE' in ui_oxrx: save_timeseries(io_manager,ts,ui_oxrx['SAVE'],siminfo,saveall,operation,segment,'OXRX',jupyterlab)
if 'SAVE' in ui_nutrx and flags['NUTRX'] == 1: save_timeseries(io_manager,ts,ui_nutrx['SAVE'],siminfo,saveall,operation,segment,'NUTRX',jupyterlab)
if 'SAVE' in ui_plank and flags['PLANK'] == 1: save_timeseries(io_manager,ts,ui_plank['SAVE'],siminfo,saveall,operation,segment,'PLANK',jupyterlab)
if 'SAVE' in ui_phcarb and flags['PHCARB'] == 1: save_timeseries(io_manager,ts,ui_phcarb['SAVE'],siminfo,saveall,operation,segment,'PHCARB',jupyterlab)
msglist = msg(1, 'Done', final=True)
df = DataFrame(msglist, columns=['logfile'])
io_manager.write_log(df)
if jupyterlab:
df = versions(['jupyterlab', 'notebook'])
io_manager.write_versioning(df)
print('\n\n', df)
return
def messages():
'''Closure routine; msg() prints messages to screen and run log'''
start = dt.now()
mlist = []
def msg(indent, message, final=False):
now = dt.now()
m = str(now)[:22] + ' ' * indent + message
if final:
mn,sc = divmod((now-start).seconds, 60)
ms = (now-start).microseconds // 100_000
m = '; '.join((m, f'Run time is about {mn:02}:{sc:02}.{ms} (mm:ss)'))
print(m)
mlist.append(m)
return mlist
return msg
def get_flows(io_manager:SupportsReadTS, ts, flags, uci, segment, ddlinks, ddmasslinks, steps, msg):
# get inflows to this operation
for x in ddlinks[segment]:
if x.SVOL != 'GENER': # gener already handled in get_gener_timeseries
mldata = ddmasslinks[x.MLNO]
for dat in mldata:
recs = []
if x.MLNO == '': # Data from NETWORK part of Links table
rec = {}
rec['MFACTOR'] = x.MFACTOR
rec['SGRPN'] = x.SGRPN
rec['SMEMN'] = x.SMEMN
rec['SMEMSB1'] = x.SMEMSB1
rec['SMEMSB2'] = x.SMEMSB2
rec['TMEMN'] = x.TMEMN
rec['TMEMSB1'] = x.TMEMSB1
rec['TMEMSB2'] = x.TMEMSB2
rec['SVOL'] = x.SVOL
recs.append(rec)
else: # Data from SCHEMATIC part of Links table
if dat.SMEMN != '':
rec = {}
rec['MFACTOR'] = dat.MFACTOR
rec['SGRPN'] = dat.SGRPN
rec['SMEMN'] = dat.SMEMN
rec['SMEMSB1'] = dat.SMEMSB1
rec['SMEMSB2'] = dat.SMEMSB2
rec['TMEMN'] = dat.TMEMN
rec['TMEMSB1'] = dat.TMEMSB1
rec['TMEMSB2'] = dat.TMEMSB2
rec['SVOL'] = dat.SVOL
recs.append(rec)
else:
# this is the kind that needs to be expanded
if dat.SGRPN == "ROFLOW" or dat.SGRPN == "OFLOW":
recs = expand_masslinks(flags,uci,dat,recs)
for rec in recs:
mfactor = rec['MFACTOR']
sgrpn = rec['SGRPN']
smemn = rec['SMEMN']
smemsb1 = rec['SMEMSB1']
smemsb2 = rec['SMEMSB2']
tmemn = rec['TMEMN']
tmemsb1 = rec['TMEMSB1']
tmemsb2 = rec['TMEMSB2']
afactr = x.AFACTR
factor = afactr * mfactor
# KLUDGE until remaining HSP2 modules are available.
if tmemn not in {'IVOL', 'ICON', 'IHEAT', 'ISED', 'ISED1', 'ISED2', 'ISED3',
'IDQAL', 'ISQAL1', 'ISQAL2', 'ISQAL3',
'OXIF', 'NUIF1', 'NUIF2', 'PKIF', 'PHIF'}:
continue
if (sgrpn == 'OFLOW' and smemn == 'OVOL') or (sgrpn == 'ROFLOW' and smemn == 'ROVOL'):
sgrpn = 'HYDR'
if (sgrpn == 'OFLOW' and smemn == 'OHEAT') or (sgrpn == 'ROFLOW' and smemn == 'ROHEAT'):
sgrpn = 'HTRCH'
if (sgrpn == 'OFLOW' and smemn == 'OSED') or (sgrpn == 'ROFLOW' and smemn == 'ROSED'):
sgrpn = 'SEDTRN'
if (sgrpn == 'OFLOW' and smemn == 'ODQAL') or (sgrpn == 'ROFLOW' and smemn == 'RODQAL'):
sgrpn = 'GQUAL'
if (sgrpn == 'OFLOW' and smemn == 'OSQAL') or (sgrpn == 'ROFLOW' and smemn == 'ROSQAL'):
sgrpn = 'GQUAL'
if (sgrpn == 'OFLOW' and smemn == 'OXCF2') or (sgrpn == 'ROFLOW' and smemn == 'OXCF1'):
sgrpn = 'OXRX'
if (sgrpn == 'OFLOW' and (smemn == 'NUCF9' or smemn == 'OSNH4' or smemn == 'OSPO4')) or (sgrpn == 'ROFLOW' and (smemn == 'NUCF1' or smemn == 'NUFCF2')):
sgrpn = 'NUTRX'
if (sgrpn == 'OFLOW' and smemn == 'PKCF2') or (sgrpn == 'ROFLOW' and smemn == 'PKCF1'):
sgrpn = 'PLANK'
if (sgrpn == 'OFLOW' and smemn == 'PHCF2') or (sgrpn == 'ROFLOW' and smemn == 'PHCF1'):
sgrpn = 'PHCARB'
if tmemn == 'ISED' or tmemn == 'ISQAL':
tmemn = tmemn + tmemsb1 # need to add sand, silt, clay subscript
if (sgrpn == 'HYDR' and smemn == 'OVOL') or (sgrpn == 'HTRCH' and smemn == 'OHEAT'):
smemsb2 = ''
smemn, tmemn = expand_timeseries_names(sgrpn, smemn, smemsb1, smemsb2, tmemn, tmemsb1, tmemsb2)
path = f'RESULTS/{x.SVOL}_{x.SVOLNO}/{sgrpn}'
MFname = f'{x.SVOL}{x.SVOLNO}_MFACTOR'
AFname = f'{x.SVOL}{x.SVOLNO}_AFACTR'
data = f'{smemn}{smemsb1}{smemsb2}'
data_frame = io_manager.read_ts(Category.RESULTS,x.SVOL,x.SVOLNO, sgrpn)
try:
if data in data_frame.columns: t = data_frame[data].astype(float64).to_numpy()[0:steps]
else: t = data_frame[smemn].astype(float64).to_numpy()[0:steps]
if MFname in ts and AFname in ts:
t *= ts[MFname][:steps] * ts[AFname][0:steps]
msg(4, f'MFACTOR modified by timeseries {MFname}')
msg(4, f'AFACTR modified by timeseries {AFname}')
elif MFname in ts:
t *= afactr * ts[MFname][0:steps]
msg(4, f'MFACTOR modified by timeseries {MFname}')
elif AFname in ts:
t *= mfactor * ts[AFname][0:steps]
msg(4, f'AFACTR modified by timeseries {AFname}')
else:
t *= factor
# if poht to iheat, imprecision in hspf conversion factor requires a slight adjustment
if (smemn == 'POHT' or smemn == 'SOHT') and tmemn == 'IHEAT':
t *= 0.998553
if (smemn == 'PODOXM' or smemn == 'SODOXM') and tmemn == 'OXIF1':
t *= 1.000565
# ??? ISSUE: can fetched data be at different frequency - don't know how to transform.
if tmemn in ts:
ts[tmemn] += t
else:
ts[tmemn] = t
except KeyError:
print('ERROR in FLOWS, cant resolve ', path + ' ' + smemn)
return
'''
# This table defines the expansion to INFLOW, ROFLOW, OFLOW for RCHRES networks
d = [
['IVOL', 'ROVOL', 'OVOL', 'HYDRFG', 'HYDR'],
['ICON', 'ROCON', 'OCON', 'CONSFG', 'CONS'],
['IHEAT', 'ROHEAT', 'OHEAT', 'HTFG', 'HTRCH'],
['ISED', 'ROSED', 'OSED', 'SEDFG', 'SEDTRN'],
['IDQAL', 'RODQAL', 'ODQAL', 'GQALFG', 'GQUAL'],
['ISQAL', 'ROSQAL', 'OSQAL', 'GQALFG', 'GQUAL'],
['OXIF', 'OXCF1', 'OXCF2', 'OXFG', 'OXRX'],
['NUIF1', 'NUCF1', 'NUCF1', 'NUTFG', 'NUTRX'],
['NUIF2', 'NUCF2', 'NUCF9', 'NUTFG', 'NUTRX'],
['PKIF', 'PKCF1', 'PKCH2', 'PLKFG', 'PLANK'],
['PHIF', 'PHCF1', 'PHCF2', 'PHFG', 'PHCARB']]
df = pd.DataFrame(d, columns=['INFLOW', 'ROFLOW', 'OFLOW', 'Flag', 'Name'])
df.to_hdf(h2name, '/FLOWEXPANSION', format='t', data_columns=True)
'''