Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix duplicate boundaries in Delwaq generation. #1903

Merged
merged 2 commits into from
Oct 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 38 additions & 3 deletions python/ribasim/ribasim/delwaq/generate.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Setup a Delwaq model from a Ribasim model and results."""

import csv
import logging
import shutil
import sys
from datetime import timedelta
Expand Down Expand Up @@ -31,6 +32,7 @@
write_volumes,
)

logger = logging.getLogger(__name__)
delwaq_dir = Path(__file__).parent
output_folder = delwaq_dir / "model"

Expand Down Expand Up @@ -131,7 +133,7 @@

for outneighbor_id in out.keys():
if outneighbor_id in remove_nodes:
print("Not making edge to removed node.")
logger.debug("Not making edge to removed node.")

Check warning on line 136 in python/ribasim/ribasim/delwaq/generate.py

View check run for this annotation

Codecov / codecov/patch

python/ribasim/ribasim/delwaq/generate.py#L136

Added line #L136 was not covered by tests
continue
edge = (inneighbor_id, outneighbor_id)
edge_id = G.get_edge_data(node_id, outneighbor_id)["id"][0]
Expand All @@ -156,13 +158,27 @@
G.nodes[loop[0]]["type"] != "UserDemand"
and G.nodes[loop[1]]["type"] != "UserDemand"
):
print("Found cycle that is not a UserDemand.")
logger.debug("Found cycle that is not a UserDemand.")

Check warning on line 161 in python/ribasim/ribasim/delwaq/generate.py

View check run for this annotation

Codecov / codecov/patch

python/ribasim/ribasim/delwaq/generate.py#L161

Added line #L161 was not covered by tests
else:
edge_ids = G.edges[loop]["id"]
G.edges[reversed(loop)]["id"].extend(edge_ids)
merge_edges.extend(edge_ids)
G.remove_edge(*loop)

# Remove boundary to boundary edges
remove_double_edges = []
for x in G.edges(data=True):
a, b, d = x
if G.nodes[a]["type"] == "Terminal" and G.nodes[b]["type"] == "UserDemand":
logger.debug("Removing edge between Terminal and UserDemand")
remove_double_edges.append(a)
elif G.nodes[a]["type"] == "UserDemand" and G.nodes[b]["type"] == "Terminal":
remove_double_edges.append(b)
logger.debug("Removing edge between UserDemand and Terminal")

Check warning on line 177 in python/ribasim/ribasim/delwaq/generate.py

View check run for this annotation

Codecov / codecov/patch

python/ribasim/ribasim/delwaq/generate.py#L169-L177

Added lines #L169 - L177 were not covered by tests

for node_id in remove_double_edges:
G.remove_node(node_id)

Check warning on line 180 in python/ribasim/ribasim/delwaq/generate.py

View check run for this annotation

Codecov / codecov/patch

python/ribasim/ribasim/delwaq/generate.py#L179-L180

Added lines #L179 - L180 were not covered by tests

# Relabel the nodes as consecutive integers for Delwaq
# Note that the node["id"] is the original node_id
basin_id = 0
Expand All @@ -183,7 +199,7 @@
boundary_id -= 1
node_mapping[node_id] = boundary_id
else:
raise Exception(f"Found unexpected node {node_id} in delwaq graph.")
raise ValueError(f"Found unexpected node {node_id} in delwaq graph.")

Check warning on line 202 in python/ribasim/ribasim/delwaq/generate.py

View check run for this annotation

Codecov / codecov/patch

python/ribasim/ribasim/delwaq/generate.py#L202

Added line #L202 was not covered by tests

nx.relabel_nodes(G, node_mapping, copy=False)

Expand Down Expand Up @@ -463,6 +479,25 @@
bnd["fid"] = list(map(_boundary_name, bnd["node_id"], bnd["node_type"]))
bnd["comment"] = ""
bnd = bnd[["fid", "comment", "node_type"]]

def prefix(d):

Check warning on line 483 in python/ribasim/ribasim/delwaq/generate.py

View check run for this annotation

Codecov / codecov/patch

python/ribasim/ribasim/delwaq/generate.py#L483

Added line #L483 was not covered by tests
"""Replace duplicate boundary names with unique names.

As the string length is fixed, we replace the first
character with a unique number.
"""
n = len(d)
if n == 1:
return d
elif n == 2:
logger.debug(f"Renaming duplicate boundaries {d.iloc[0]}")
return [str(i) for i in range(n)] + d.str.lstrip("U")

Check warning on line 494 in python/ribasim/ribasim/delwaq/generate.py

View check run for this annotation

Codecov / codecov/patch

python/ribasim/ribasim/delwaq/generate.py#L489-L494

Added lines #L489 - L494 were not covered by tests
else:
raise ValueError("Found boundary with more than 2 duplicates.")

Check warning on line 496 in python/ribasim/ribasim/delwaq/generate.py

View check run for this annotation

Codecov / codecov/patch

python/ribasim/ribasim/delwaq/generate.py#L496

Added line #L496 was not covered by tests

bnd["fid"] = bnd.groupby("fid").fid.transform(prefix)
assert bnd["fid"].is_unique

Check warning on line 499 in python/ribasim/ribasim/delwaq/generate.py

View check run for this annotation

Codecov / codecov/patch

python/ribasim/ribasim/delwaq/generate.py#L498-L499

Added lines #L498 - L499 were not covered by tests

bnd.to_csv(
output_folder / "ribasim_bndlist.inc",
index=False,
Expand Down
2 changes: 1 addition & 1 deletion python/ribasim/ribasim/delwaq/template/delwaq.inp.j2
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ INCLUDE 'ribasim.atr' ; From UI: attributes file
1.0 1.0 1.0 ; Scale factors for 3 directions

; Default dispersion:
1 0.0 1E-07 ; constant dispersion
0.0 0.0 0.0 ; constant dispersion

; Area file
-2 ; areas will be interpolated from a binary file
Expand Down
Loading