# hardy_cross_plot.py """ Headless plotting utility for the Hardy Cross app. - Uses the non-GUI Agg backend (safe on HF Spaces / Docker servers). - Accepts a DataFrame of final flows (must have 'pipe_id' and 'Q' columns). - Uses 'start_node' / 'end_node' columns when present; otherwise infers endpoints from 'pipe_id' (e.g. "AB" → "A", "B"; "P1-P2" → "P1", "P2"). - For numeric pipe IDs (e.g. "101") the plot degrades gracefully by using generic node labels N0, N1 … instead of collapsing all to one node. - Lays nodes out on a circle unless explicit positions are supplied. - Convergence status banner is shown at the top of the plot. Example ------- import pandas as pd from hardy_cross_plot import plot_hardy_cross_network df = pd.DataFrame({ "pipe_id": ["AB", "BC", "CD", "DA", "BD"], "Q": [0.08, 0.05, -0.06, -0.07, 0.02], "converged": [True]*5, }) path = plot_hardy_cross_network(df, save_path="result.png") """ import os import math import matplotlib matplotlib.use("Agg") # headless – must come before pyplot import import matplotlib.pyplot as plt import matplotlib.patheffects as pe from typing import Dict, List, Optional, Tuple import pandas as pd import numpy as np # ───────────────────────────────────────────────────────────────────────────── # Endpoint inference # ───────────────────────────────────────────────────────────────────────────── def _infer_endpoints(pipe_id: str) -> Tuple[str, str]: """ Derive (start_node, end_node) from a pipe_id string. Rules (tried in order): 1. Split on common separators (- — > →). 2. Extract all alphanumeric *chunks*; if ≥2 chunks and at least one chunk is non-numeric, return first and last chunk. 3. If the string is exactly 2 chars (classic "AB"), return each char. 4. Numeric-only IDs: return ("?", pipe_id) as a sentinel that the caller can detect and replace with synthetic node labels. """ if not isinstance(pipe_id, str) or not pipe_id.strip(): return ("?", "?") s = pipe_id.strip() # Rule 1 – separator split for sep in ("-", "—", ">", "→"): if sep in s: parts = [p.strip() for p in s.split(sep) if p.strip()] if len(parts) >= 2: return (parts[0], parts[-1]) # Rule 2 – alphanumeric chunks chunks, cur = [], [] for ch in s: if ch.isalnum(): cur.append(ch) elif cur: chunks.append("".join(cur)) cur = [] if cur: chunks.append("".join(cur)) if len(chunks) >= 2 and not all(c.isdigit() for c in chunks): return (chunks[0], chunks[-1]) # Rule 3 – classic two-letter id if len(s) == 2: return (s[0], s[1]) # Rule 4 – numeric / ambiguous: signal with "?" sentinel return ("?", s) def _collect_nodes(df: pd.DataFrame) -> pd.DataFrame: """ Ensure df has 'start_node' and 'end_node' columns. Replaces '?' sentinels with synthetic node labels (N0, N1 …). """ df2 = df.copy() if "start_node" not in df2.columns or "end_node" not in df2.columns: starts, ends = [], [] for pid in df2["pipe_id"].astype(str): s, e = _infer_endpoints(pid) starts.append(s) ends.append(e) df2["start_node"] = starts df2["end_node"] = ends # Replace '?' sentinels with unique synthetic labels synthetic_counter = [0] node_map: Dict[str, str] = {} def _resolve(val: str) -> str: if val == "?": label = f"N{synthetic_counter[0]}" synthetic_counter[0] += 1 return label return val df2["start_node"] = df2["start_node"].apply(_resolve) df2["end_node"] = df2["end_node"].apply(_resolve) return df2 def _circle_positions(nodes: List[str]) -> Dict[str, Tuple[float, float]]: """Place nodes evenly on a unit circle.""" n = max(len(nodes), 1) return { node: (math.cos(2 * math.pi * i / n), math.sin(2 * math.pi * i / n)) for i, node in enumerate(nodes) } # ───────────────────────────────────────────────────────────────────────────── # Main plotting function # ───────────────────────────────────────────────────────────────────────────── def plot_hardy_cross_network( final_flows: pd.DataFrame, save_path: str = "hardy_cross_network_result.png", node_positions: Optional[Dict[str, Tuple[float, float]]] = None, figsize: Tuple[int, int] = (9, 6), ) -> str: """ Render a flow-direction diagram and save as PNG. Parameters ---------- final_flows : pd.DataFrame Must contain 'pipe_id' and 'Q' (m³/s). Optional columns: 'start_node', 'end_node', 'converged'. save_path : str Output file path (should end in .png). node_positions : dict, optional {node_name: (x, y)}. Auto-computed if None. figsize : tuple Matplotlib figure size (width, height) in inches. Returns ------- str – path to the saved PNG. """ def _placeholder(msg: str) -> str: fig, ax = plt.subplots(figsize=figsize) ax.text(0.5, 0.5, msg, ha="center", va="center", fontsize=13, transform=ax.transAxes) ax.axis("off") fig.tight_layout() _safe_save(fig, save_path) return save_path if final_flows is None or len(final_flows) == 0: return _placeholder("No flow data to display.") if "pipe_id" not in final_flows.columns or "Q" not in final_flows.columns: return _placeholder("Missing required columns: 'pipe_id' and 'Q'.") # ── Resolve convergence flag ────────────────────────────────────────── if "converged" in final_flows.columns: converged = bool(final_flows["converged"].iloc[0]) else: converged = None # unknown df = _collect_nodes(final_flows) # ── Node positions ──────────────────────────────────────────────────── nodes = sorted( set(df["start_node"].astype(str)) | set(df["end_node"].astype(str)) ) if not node_positions: node_positions = _circle_positions(nodes) # ── Flow magnitude scaling ──────────────────────────────────────────── q_abs = final_flows["Q"].abs().replace(0.0, np.nan) _non_nan = q_abs.dropna() q_max = float(_non_nan.max()) if len(_non_nan) > 0 else 1.0 if not np.isfinite(q_max) or q_max <= 0: q_max = 1.0 # ── Figure ──────────────────────────────────────────────────────────── fig, ax = plt.subplots(figsize=figsize) ax.set_aspect("equal") ax.axis("off") # Convergence banner if converged is True: banner = "✔ Converged" banner_color = "#2ecc71" elif converged is False: banner = "⚠ Did NOT converge – try more iterations" banner_color = "#e74c3c" else: banner = "" banner_color = "black" title_text = "Hardy Cross – Final Pipe Flows" if banner: title_text += f"\n{banner}" ax.set_title(title_text, fontsize=13, pad=10, color="black", fontweight="bold") # ── Draw nodes ──────────────────────────────────────────────────────── for node in nodes: x, y = node_positions.get(node, (0.0, 0.0)) ax.plot(x, y, "o", ms=9, color="#2c3e50", zorder=4) ax.text( x, y + 0.09, str(node), ha="center", va="bottom", fontsize=11, fontweight="bold", color="#2c3e50", zorder=5, path_effects=[pe.withStroke(linewidth=2, foreground="white")], ) # ── Draw pipes ──────────────────────────────────────────────────────── for _, row in df.iterrows(): pid = str(row["pipe_id"]) sn = str(row["start_node"]) en = str(row["end_node"]) q = float(row["Q"]) x1, y1 = node_positions.get(sn, (0.0, 0.0)) x2, y2 = node_positions.get(en, (0.0, 0.0)) # Arrow direction follows sign of Q if q >= 0: sx, sy, tx, ty = x1, y1, x2, y2 else: sx, sy, tx, ty = x2, y2, x1, y1 frac = abs(q) / q_max lw = 1.2 + 3.5 * frac m_scale = 10 + 28 * frac color = plt.cm.Blues(0.35 + 0.55 * frac) # light→dark blue ax.annotate( "", xy=(tx, ty), xytext=(sx, sy), arrowprops=dict( arrowstyle="-|>", lw=lw, shrinkA=7, shrinkB=7, mutation_scale=m_scale, color=color, ), zorder=3, ) # Pipe label near midpoint mx = 0.5 * (x1 + x2) my = 0.5 * (y1 + y2) label = f"{pid}\n{q:+.4f} m³/s" ax.text( mx, my, label, ha="center", va="center", fontsize=8.5, color="#1a5276", zorder=6, path_effects=[pe.withStroke(linewidth=2.5, foreground="white")], ) fig.tight_layout() _safe_save(fig, save_path) return save_path def _safe_save(fig, save_path: str) -> None: """Create parent directories if needed, then save and close.""" out_dir = os.path.dirname(save_path) if out_dir: os.makedirs(out_dir, exist_ok=True) fig.savefig(save_path, dpi=150, bbox_inches="tight") plt.close(fig)