Skip to content
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
10 changes: 5 additions & 5 deletions docs/img/pbpk_elimination_subgraph.mmd
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
%% Elimination subgraph (plasma-referenced reporting parameters)
flowchart LR
arterial(["arterial blood"])
venous(["venous blood"])
spleen["spleen"]
eliminated[("eliminated")]
arterial(["arterial blood"])
kidney["kidney"]
gut["gut"]
liver["liver"]
gut["gut"]
spleen["spleen"]
pancreas["pancreas"]
arterial -->|"74.1 L/h"| kidney
kidney -->|"74.1 L/h"| venous
Expand All @@ -21,8 +21,8 @@ flowchart LR
liver -->|"CL 16.86 L/h (plasma)"| eliminated
kidney -->|"CL 0.24 L/h (plasma)"| eliminated
classDef c_blood fill:#C2373A,stroke:#222,color:#ffffff;
class venous,arterial c_blood;
class arterial,venous c_blood;
classDef c_compartment fill:#2B44C4,stroke:#222,color:#ffffff;
class spleen,kidney,gut,liver,pancreas c_compartment;
class kidney,liver,gut,spleen,pancreas c_compartment;
classDef c_sink fill:#586379,stroke:#222,color:#ffffff;
class eliminated c_sink;
33 changes: 33 additions & 0 deletions tests/test_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,39 @@ def test_connected_components_and_subgraph():
assert set(sub.nodes) == {"a", "b"} and len(sub.edges) == 1


def test_subgraph_order_is_reproducible_across_hash_seeds():
# String-set iteration order changes with PYTHONHASHSEED; a subgraph must
# follow the parent graph's order so its JSON and Mermaid are byte-stable.
import os
import subprocess
import sys

g = Graph("ordered")
for n in "fedcba":
g.add_node(n, "x")
g.add_edge("f", "a", "e")
assert list(g.subgraph(["a", "c", "f"]).nodes) == ["f", "c", "a"]
assert list(g.subgraph(reversed(["a", "c", "f"])).nodes) == ["f", "c", "a"]
with pytest.raises(KeyError, match="unknown nodes"):
g.subgraph(["a", "missing"])

code = ("from vh.body import PBPKModel, MIDAZOLAM\n"
"from vh.graph.physiology_graph import build_pbpk_graph\n"
"from vh.graph.render import to_mermaid\n"
"g, _ = build_pbpk_graph(PBPKModel(MIDAZOLAM))\n"
"ids = ['arterial', 'liver', 'kidney', 'venous', 'gut', 'spleen', 'pancreas', 'eliminated']\n"
"print(to_mermaid(g.subgraph(set(ids))))\n")
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
outputs = set()
for seed in ("0", "1", "2", "3"):
env = {**os.environ, "PYTHONHASHSEED": seed,
"PYTHONPATH": os.pathsep.join(filter(None, [root, os.environ.get("PYTHONPATH")]))}
run = subprocess.run([sys.executable, "-c", code], env=env, cwd=root,
capture_output=True, text=True, check=True, timeout=120)
outputs.add(run.stdout)
assert len(outputs) == 1


def test_schema_validation_catches_bad_edges():
schema = Schema(node_types={"blood": set(), "organ": {"volume"}},
edge_rules=[EdgeRule("flow", {"blood", "organ"}, {"blood", "organ"}, {"flow"})])
Expand Down
14 changes: 10 additions & 4 deletions vh/graph/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,18 @@ def degree(self, nid: str) -> int:

# --- subgraphs -----------------------------------------------------------
def subgraph(self, node_ids: Iterable[str], name: str | None = None) -> "Graph":
"""Induced subgraph on the given nodes (all edges with both ends inside)."""
"""Induced subgraph on the given nodes (all edges with both ends inside).

Nodes keep this graph's insertion order, not the order (or set-iteration
order) of `node_ids`, so serialization and rendering are reproducible."""
keep = set(node_ids)
unknown = keep - self.nodes.keys()
if unknown:
raise KeyError(f"subgraph references unknown nodes {sorted(unknown)!r}")
g = Graph(name or f"{self.name}:sub")
for nid in keep:
n = self.nodes[nid]
g.add_node(n.id, n.type, n.scale, n.label, **dict(n.attrs))
for n in self.nodes.values():
if n.id in keep:
g.add_node(n.id, n.type, n.scale, n.label, **dict(n.attrs))
for e in self.edges:
if e.src in keep and e.dst in keep:
g.add_edge(e.src, e.dst, e.type, e.directed, e.model, **dict(e.attrs))
Expand Down
Loading