File size: 6,575 Bytes
5427298 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | """
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()
|