Skip to content

Commit

Permalink
run_model (#200)
Browse files Browse the repository at this point in the history
- model.run() om een model te runnen vanuit Python
- model.update_state() om een model te updaten op een tijdstip (als
timestamp is gegeven) of basin_outstate als niet
- alle regionale modellen worden nu eerst gerunt en state-updated
vóórdat ze worden samengevoegd tot het LHM

---------

Co-authored-by: Martijn Visser <[email protected]>
  • Loading branch information
DanielTollenaar and visr authored Dec 20, 2024
1 parent bc0aaea commit c2cc6ae
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 8 deletions.
18 changes: 13 additions & 5 deletions notebooks/samenvoegen_modellen.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,19 @@ def get_model_path(model, model_version):
# read model
ribasim_model = Model.read(model_path)

# TODO: make sure this isn't needed next round!
if model["authority"] in RESET_TABLES:
ribasim_model.remove_unassigned_basin_area()
ribasim_model = reset_static_tables(ribasim_model)

# run model
if not ribasim_model.basin_outstate.filepath.exists():
print("run model to update state")
returncode = ribasim_model.run()
if returncode != 0:
raise Exception("model won't run successfully!")
ribasim_model.update_state()

# add meta_waterbeheerder
for node_type in ribasim_model.node_table().df.node_type.unique():
ribasim_node = getattr(ribasim_model, pascal_to_snake_case(node_type))
Expand All @@ -203,11 +216,6 @@ def get_model_path(model, model_version):
if idx == 0:
lhm_model = ribasim_model
else:
# TODO: make sure this isn't needed next round!
if model["authority"] in RESET_TABLES:
ribasim_model.remove_unassigned_basin_area()
ribasim_model = reset_static_tables(ribasim_model)

lhm_model = concat([lhm_model, ribasim_model])
readme += f"""
**{model["authority"]}**: {model["model"]} ({model_version.version})"""
Expand Down
39 changes: 36 additions & 3 deletions src/ribasim_nl/ribasim_nl/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from ribasim_nl.case_conversions import pascal_to_snake_case
from ribasim_nl.geometry import split_basin
from ribasim_nl.run_model import run

manning_data = manning_resistance.Static(length=[100], manning_n=[0.04], profile_width=[10], profile_slope=[1])
level_data = level_boundary.Static(level=[0])
Expand Down Expand Up @@ -59,7 +60,7 @@ def node_properties_to_table(table, node_properties, node_id):
table_node_df.loc[node_id, [column]] = value


class BasinResults(BaseModel):
class Results(BaseModel):
filepath: Path
_df = None

Expand All @@ -71,16 +72,24 @@ def df(self) -> pd.DataFrame:


class Model(Model):
_basin_results: BasinResults | None = None
_basin_results: Results | None = None
_basin_outstate: Results | None = None
_graph: nx.Graph | None = None

@property
def basin_results(self):
if self._basin_results is None:
filepath = self.filepath.parent.joinpath(self.results_dir, "basin.arrow").absolute().resolve()
self._basin_results = BasinResults(filepath=filepath)
self._basin_results = Results(filepath=filepath)
return self._basin_results

@property
def basin_outstate(self):
if self._basin_outstate is None:
filepath = self.filepath.parent.joinpath(self.results_dir, "basin_state.arrow").absolute().resolve()
self._basin_outstate = Results(filepath=filepath)
return self._basin_outstate

@property
def graph(self):
# create a DiGraph from edge-table
Expand All @@ -97,6 +106,30 @@ def graph(self):
def next_node_id(self):
return self.node_table().df.index.max() + 1

def run(self, stream_output=True, returncode=True):
"""Run your Ribasim model
Args:
stream_output (bool, optional): stream output in IDE. Defaults to True.
returncode (bool, optional): return returncode after running model. Defaults to True.
"""
return run(self.filepath, stream_output=stream_output, returncode=returncode)

def update_state(self, time_stamp: pd.Timestamp | None = None):
"""Update basin.state with results or final basin_state (outstate)
Args:
time_stamp (pd.Timestamp | None, optional): Timestamp in results to update basin.state with . Defaults to None.
"""
if time_stamp is None:
df = self.basin_outstate.df
else:
df = self.basin_results.df.loc[time_stamp][["node_id", "level"]]
df.reset_index(inplace=True, drop=True)
df.index += 1
df.index.name = "fid"
self.basin.state.df = df

# methods relying on networkx. Discuss making this all in a subclass of Model
def _upstream_nodes(self, node_id):
# get upstream nodes
Expand Down

0 comments on commit c2cc6ae

Please sign in to comment.