respec / HSPsquared

Hydrologic Simulation Program Python (HSPsquared)
GNU Affero General Public License v3.0
43 stars 17 forks source link

Dynamic python code loading for hsp2 runtime customization #113

Closed rburghol closed 8 months ago

rburghol commented 1 year ago

Overview (RFC)

This issue provides background information for pull request #119 which hs now been merged.

This PR contains code that:

Tasks

Supported Functions & Special Variables

Dynamic Loading of Code

Testing

Code 1: Set a dynamic withdrawal in RCHRES R001. See also https://github.com/respec/HSPsquared/blob/99c0e629d88d0665bb45f10250691b2f0679967e/tests/test10/HSP2results/test10.py

import sys
from numba import int8, float32, njit, types, typed # import the types

print("Loaded a set of  HSP2 code!")

@njit
def state_step_hydr(state_info, state_paths, state_ix, dict_ix, ts_ix, hydr_ix, step):
    if (step <= 1):
        print("Custom state_step_hydr() called for ", state_info['segment'])
        print("operation", state_info['operation'])
        print("state at start", state_ix)
        print("domain info", state_info)
        print("state_paths", state_paths)
    # Do a simple withdrawal of 10 MGGD from R001
    if (state_info['segment'] == 'R001') and (state_info['activity'] == 'HYDR'):
        state_ix[hydr_ix['O1']] = 10.0 * 1.547
    # Route point source return from segment R001 demand to R005 inflow (IVOL)
    # For demo purposes this will only use the last state_ix value for R001 demand
    # Realistic approach would run all segments simultaneously or use value from ts_ix (ts_ix loading TBD)
    if (state_info['segment'] == 'R005') and (state_info['activity'] == 'HYDR'):
        state_ix[hydr_ix['IVOL']] += 0.85 * state_ix[state_paths['/STATE/RCHRES_R001/HYDR/O1']]
        if (step <= 1):
            print("IVOL after", state_ix[hydr_ix['IVOL']])
    return
jdkleiner commented 12 months ago

Analysis of testing results:

import h5py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# read in results hdf5 file
filename = 'test10.h5'
h5 = h5py.File(filename, 'r')

# extract results table from hdf5 as pandas dataframe
df = pd.DataFrame(np.array(h5['RESULTS']['RCHRES_R001']['HYDR']['table']))

# print all column names
print(list(df.columns.values))

# simple line plot
df.plot(kind='line',
        x='index',
        y=['OVOL1','IVOL'])

plt.show()