""" Build distance-based adjacency matrices and heatmap visualisations for the Dianchi Water dataset. Usage ----- # Generate adjacency CSVs + combined heatmap at default thresholds: python build_adjacency.py # Single threshold: python build_adjacency.py --threshold-km 20 # Custom thresholds and output directory: python build_adjacency.py --thresholds-km 5,10,15,20,25,30 --output-dir ./outputs Requirements: numpy, pandas, matplotlib """ from __future__ import annotations import argparse from pathlib import Path from typing import List, Tuple import matplotlib.pyplot as plt import numpy as np import pandas as pd # ── adjacency construction ─────────────────────────────────────────── def build_adjacency_matrix( dist_df: pd.DataFrame, threshold_km: float, self_loop: float = 1.0, ) -> pd.DataFrame: """Linear-decay adjacency: w_ij = max(0, 1 - d_ij / threshold). Parameters ---------- dist_df : pd.DataFrame Square pairwise distance matrix (km) with station names as both index and columns. threshold_km : float Distance threshold in km. Pairs farther than this receive weight 0. self_loop : float Diagonal value (default 1.0). Set to 0.0 if your model adds self-loops separately. """ if threshold_km <= 0: raise ValueError("threshold_km must be positive.") adj = (1.0 - dist_df / threshold_km).clip(lower=0.0, upper=1.0) np.fill_diagonal(adj.values, float(self_loop)) return adj # ── visualisation ──────────────────────────────────────────────────── def plot_single_heatmap( df: pd.DataFrame, title: str, save_path: Path ) -> None: n = len(df) fig, ax = plt.subplots( figsize=(max(10, n * 0.6), max(8, n * 0.5)), dpi=220 ) im = ax.imshow(df.values, cmap="viridis", vmin=0, vmax=1, aspect="auto") ax.set_title(title, fontsize=14) ax.set_xticks(range(n)) ax.set_yticks(range(n)) ax.set_xticklabels(df.columns, rotation=90, fontsize=7) ax.set_yticklabels(df.index, fontsize=7) cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04) cbar.set_label("Adjacency weight", rotation=90) fig.tight_layout() fig.savefig(save_path, bbox_inches="tight") plt.close(fig) print(f" Saved: {save_path}") def plot_combined_heatmaps( panels: List[Tuple[float, pd.DataFrame]], save_path: Path ) -> None: n_panels = len(panels) ncols = min(n_panels, 3) nrows = (n_panels + ncols - 1) // ncols fig, axes = plt.subplots( nrows, ncols, figsize=(7.5 * ncols, 7 * nrows), dpi=220, constrained_layout=True, ) axes = np.atleast_1d(axes).flatten() im = None for idx, (threshold, df) in enumerate(panels): ax = axes[idx] im = ax.imshow( df.values, cmap="viridis", vmin=0, vmax=1, aspect="auto" ) ax.set_title(f"threshold = {threshold:g} km", fontsize=12) ax.set_xticks(range(len(df))) ax.set_yticks(range(len(df))) ax.set_xticklabels(df.columns, rotation=90, fontsize=6) ax.set_yticklabels(df.index, fontsize=6) for idx in range(n_panels, len(axes)): axes[idx].axis("off") if im is not None: fig.colorbar(im, ax=axes.tolist(), fraction=0.02, pad=0.02, label="Adjacency weight") fig.suptitle( "Distance-Based Adjacency Under Different Thresholds", fontsize=16 ) fig.savefig(save_path, bbox_inches="tight") plt.close(fig) print(f"Combined heatmap saved: {save_path}") # ── CLI ────────────────────────────────────────────────────────────── def parse_thresholds(text: str) -> List[float]: out = [float(t) for t in text.split(",") if t.strip()] if not out: raise ValueError("At least one threshold must be provided.") return out def main() -> None: parser = argparse.ArgumentParser( description="Build adjacency matrices and heatmaps from the " "Dianchi Water station distance matrix." ) parser.add_argument( "--distance-csv", default=str(Path(__file__).resolve().parent.parent / "data" / "dianchi_station_distance_km.csv"), help="Path to dianchi_station_distance_km.csv " "(default: ../data/dianchi_station_distance_km.csv)", ) parser.add_argument( "--output-dir", default=None, help="Output directory (default: same as --distance-csv).", ) parser.add_argument( "--threshold-km", type=float, default=None, help="Single distance threshold in km.", ) parser.add_argument( "--thresholds-km", default="10,15,20,25,30", help="Comma-separated distance thresholds (default: 10,15,20,25,30).", ) parser.add_argument( "--self-loop", type=float, default=1.0, help="Diagonal value of adjacency matrix (default: 1.0).", ) parser.add_argument( "--no-plot", action="store_true", help="Skip heatmap generation.", ) args = parser.parse_args() dist_path = Path(args.distance_csv) output_dir = Path(args.output_dir) if args.output_dir else dist_path.parent output_dir.mkdir(parents=True, exist_ok=True) dist_df = pd.read_csv(dist_path, index_col=0) print(f"Loaded distance matrix: {dist_path} ({len(dist_df)} stations)") thresholds = ( [args.threshold_km] if args.threshold_km is not None else parse_thresholds(args.thresholds_km) ) panels: List[Tuple[float, pd.DataFrame]] = [] for t in thresholds: adj = build_adjacency_matrix(dist_df, t, self_loop=args.self_loop) out = output_dir / f"adjacency_threshold_{t:g}km.csv" adj.to_csv(out, encoding="utf-8-sig") print(f"Adjacency matrix saved: {out}") panels.append((t, adj)) if not args.no_plot and panels: plot_combined_heatmaps( panels, output_dir / "adjacency_heatmaps_combined.png" ) for t, adj in panels: plot_single_heatmap( adj, f"Adjacency (threshold = {t:g} km)", output_dir / f"adjacency_heatmap_{t:g}km.png", ) if __name__ == "__main__": main()