{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "MIT License\n\nCopyright (c) 2026 ANONYMOUS\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE." ] }, { "cell_type": "markdown", "id": "7b0f8c0e", "metadata": {}, "source": [ "# Solver Comparison (NetworkX + Pathfinding + Grid)\n", "\n", "This notebook generates a single sample at a chosen resolution using `passage.generate.generate_sample`,\n", "then compares NetworkX, Pathfinding and internal Grid (NumPy) solvers from `passage.generate.find_path`.\n", "\n", "It records computation time, summarizes results, and visualizes all paths on the elevation map.\n", "\n", "We report solve time statistics; for a set of times $t_i$, the mean is $\\mu = \\frac{1}{N}\\sum_i t_i$ and the maximum is $\\max_i t_i$.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "cb548b04", "metadata": {}, "outputs": [], "source": [ "import json\n", "import logging\n", "import sys\n", "import time\n", "from pathlib import Path\n", "\n", "import matplotlib.pyplot as plt\n", "import matplotlib.cm as cm\n", "import numpy as np\n", "import pandas as pd\n", "import yaml\n", "from loguru import logger as loguru_logger\n", "\n", "# Configure info logging\n", "logging.basicConfig(level=logging.INFO, format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n", "logger = logging.getLogger(__name__)\n", "logger.setLevel(logging.INFO)\n", "\n", "# Configure loguru for info level\n", "loguru_logger.remove()\n", "loguru_logger.add(sys.stderr, level=\"INFO\")\n", "\n", "# Add src to path for imports\n", "ROOT = Path(\"..\").resolve()\n", "sys.path.insert(0, str(ROOT / \"src\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "625f6f13", "metadata": {}, "outputs": [], "source": [ "from passage.generate import generate_sample, find_path, lat_to_str, lon_to_str, _resolve_obstacle_config\n", "from passage.visualization import tensor_to_image" ] }, { "cell_type": "code", "execution_count": null, "id": "2baab49f", "metadata": { "tags": [ "parameters" ] }, "outputs": [], "source": [ "# Parameters (papermill)\n", "RESOLUTION = 512" ] }, { "cell_type": "code", "execution_count": null, "id": "94a64955", "metadata": {}, "outputs": [], "source": [ "# Solvers list (moved to top for visibility)\n", "CONFIG_PATH = ROOT / \"config\" / \"config.yaml\"\n", "DEFAULT_COST_MODEL = \"elevation\"\n", "\n", "try:\n", " with open(CONFIG_PATH) as f:\n", " _config = yaml.safe_load(f) or {}\n", " _solver_cfg = _config.get(\"solver\", {})\n", " _obstacle_settings = _resolve_obstacle_config(_config)\n", " COST_MODEL = (\n", " _solver_cfg.get(\"grid\", {}).get(\"cost_model\")\n", " or _solver_cfg.get(\"networkx\", {}).get(\"cost_model\")\n", " or _solver_cfg.get(\"pathfinding\", {}).get(\"cost_model\")\n", " or DEFAULT_COST_MODEL\n", " )\n", " OBSTACLES_ENABLED = bool(_obstacle_settings.get(\"enabled\", False))\n", " OBSTACLE_PENALTY = float(_obstacle_settings.get(\"obstacle_penalty\", 1e8))\n", "except Exception:\n", " COST_MODEL = DEFAULT_COST_MODEL\n", " OBSTACLES_ENABLED = False\n", " OBSTACLE_PENALTY = 1e8\n", "\n", "SOLVERS = [\n", " # NetworkX\n", " {\"name\": \"networkx:astar\", \"heuristic\": \"euclidean\", \"cost_model\": COST_MODEL, \"label\": \"NetworkX A* (Euclidean)\"},\n", " {\n", " \"name\": \"networkx:astar_bi\",\n", " \"heuristic\": \"euclidean\",\n", " \"cost_model\": COST_MODEL,\n", " \"label\": \"NetworkX A* (Bidirectional)\",\n", " },\n", " {\"name\": \"networkx:dijkstra\", \"cost_model\": COST_MODEL, \"label\": \"NetworkX Dijkstra\"},\n", " {\"name\": \"networkx:dijkstra_bi\", \"cost_model\": COST_MODEL, \"label\": \"NetworkX Dijkstra (Bidirectional)\"},\n", " {\"name\": \"networkx:bellman_ford\", \"cost_model\": COST_MODEL, \"label\": \"NetworkX Bellman-Ford\"},\n", " {\"name\": \"networkx:unweighted\", \"cost_model\": COST_MODEL, \"label\": \"NetworkX Unweighted (BFS)\"},\n", " # Pathfinding\n", " {\n", " \"name\": \"pathfinding:astar\",\n", " \"heuristic\": \"euclidean\",\n", " \"cost_model\": COST_MODEL,\n", " \"label\": \"Pathfinding A* (Euclidean)\",\n", " },\n", " {\"name\": \"pathfinding:dijkstra\", \"cost_model\": COST_MODEL, \"label\": \"Pathfinding Dijkstra\"},\n", " {\n", " \"name\": \"pathfinding:best_first\",\n", " \"heuristic\": \"euclidean\",\n", " \"cost_model\": COST_MODEL,\n", " \"label\": \"Pathfinding Best-First\",\n", " },\n", " # Grid (NumPy-based internal solvers)\n", " {\"name\": \"grid:astar\", \"heuristic\": \"euclidean\", \"cost_model\": COST_MODEL, \"label\": \"Grid A* (NumPy)\"},\n", " {\"name\": \"grid:dijkstra\", \"cost_model\": COST_MODEL, \"label\": \"Grid Dijkstra (NumPy)\"},\n", "]" ] }, { "cell_type": "markdown", "id": "a0e9f208", "metadata": {}, "source": [ "## Configuration\n", "\n", "Choose a resolution and where to store the generated sample." ] }, { "cell_type": "code", "execution_count": null, "id": "c8de1380", "metadata": {}, "outputs": [], "source": [ "# Sample generation settings\n", "RESOLUTION = 256 # 64, 128, 256, 512, 1024, 2048, 4096\n", "SAMPLE_INDEX = 0\n", "CENTER_LAT = None # Set to int if known\n", "CENTER_LON = None # Set to int if known\n", "DISABLE_IMAGES = False\n", "OVERRIDE_EXISTING = True\n", "\n", "# Paths\n", "OUTPUTS_DIR = ROOT / \"outputs\" / \"solve\"\n", "TILES_DIR = ROOT / \"outputs\" / \"download\" / \"tiles\"\n", "CALIBRATE_PATH = ROOT / \"outputs\" / \"calibrate\" / \"calibrate.json\"\n", "OBSTACLE_SETTINGS = _resolve_obstacle_config(_config if \"_config\" in globals() else {})\n", "USE_OBSTACLES = bool(OBSTACLE_SETTINGS.get(\"enabled\", False))\n", "OBSTACLE_PENALTY = float(OBSTACLE_SETTINGS.get(\"obstacle_penalty\", 1e8))\n", "\n", "# Solver defaults for sample generation (used only to ensure a valid path exists)\n", "GEN_SOLVER_CONFIG = {\n", " \"name\": \"grid:astar\",\n", " \"diagonal_movement\": \"always\",\n", " \"weight\": 30.0,\n", " \"cost_model\": COST_MODEL,\n", " \"heuristic\": \"euclidean\",\n", "}\n", "\n", "# Solver comparison settings\n", "WEIGHT = 30.0\n", "DIAGONAL_MOVEMENT = \"always\"\n", "COST_MODEL = COST_MODEL # Pathfinding supports elevation, distance, absolute_elevation" ] }, { "cell_type": "markdown", "id": "b275ed67", "metadata": {}, "source": [ "## Generate or Load Sample\n", "\n", "This uses `generate_sample` from `passage.generate` to create a single tensor if it does not exist yet." ] }, { "cell_type": "code", "execution_count": null, "id": "c2971a50", "metadata": {}, "outputs": [], "source": [ "# Validate required inputs\n", "if not CALIBRATE_PATH.exists():\n", " raise FileNotFoundError(f\"Calibration file not found: {CALIBRATE_PATH}. Run 'passage calibrate' first.\")\n", "if not TILES_DIR.exists():\n", " raise FileNotFoundError(f\"Tiles directory not found: {TILES_DIR}. Run 'passage download' first.\")\n", "\n", "# Load calibration data\n", "with open(CALIBRATE_PATH) as f:\n", " calibration = json.load(f)\n", "global_min = float(calibration[\"global_min\"])\n", "global_max = float(calibration[\"global_max\"])\n", "tile_stats_df = pd.DataFrame(calibration[\"tile_stats\"])\n", "\n", "\n", "def resolve_sample_paths(outputs_dir: Path, resolution: int, index: int, center_lat=None, center_lon=None):\n", " tensors_root = outputs_dir / str(resolution) / \"tensors\"\n", " metadata_root = outputs_dir / str(resolution) / \"metadata\"\n", " if center_lat is not None and center_lon is not None:\n", " lat_dir = lat_to_str(int(center_lat))\n", " lon_dir = lon_to_str(int(center_lon))\n", " tensor_path = tensors_root / lat_dir / lon_dir / f\"{index:010d}.npy\"\n", " metadata_path = metadata_root / lat_dir / lon_dir / f\"{index:010d}.yaml\"\n", " return tensor_path, metadata_path\n", " tensor_matches = list(tensors_root.rglob(f\"{index:010d}.npy\"))\n", " metadata_matches = list(metadata_root.rglob(f\"{index:010d}.yaml\"))\n", " tensor_path = tensor_matches[0] if tensor_matches else tensors_root / f\"{index:010d}.npy\"\n", " metadata_path = metadata_matches[0] if metadata_matches else metadata_root / f\"{index:010d}.yaml\"\n", " return tensor_path, metadata_path\n", "\n", "\n", "# Generate sample if not present (or if OVERRIDE_EXISTING is True)\n", "tensor_path, metadata_path = resolve_sample_paths(OUTPUTS_DIR, RESOLUTION, SAMPLE_INDEX, CENTER_LAT, CENTER_LON)\n", "\n", "if OVERRIDE_EXISTING or not tensor_path.exists() or not metadata_path.exists():\n", " OUTPUTS_DIR.mkdir(parents=True, exist_ok=True)\n", " args = (\n", " SAMPLE_INDEX,\n", " TILES_DIR,\n", " OUTPUTS_DIR,\n", " RESOLUTION,\n", " tile_stats_df,\n", " global_min,\n", " global_max,\n", " DISABLE_IMAGES,\n", " GEN_SOLVER_CONFIG,\n", " OBSTACLE_SETTINGS,\n", " )\n", " index, success, message, duration = generate_sample(args)\n", " print(f\"Generate sample: success={success}, message='{message}', duration={duration:.2f}s\")\n", " if not success:\n", " raise RuntimeError(\"Sample generation failed. Try a different resolution or re-run calibration.\")\n", "else:\n", " print(f\"Using existing tensor: {tensor_path}\")\n", "\n", "# Load tensor (shape: H, W, 3) -> channels: elevation (normalized), markers, obstacles\n", "tensor = np.load(tensor_path)\n", "elevation_norm = tensor[:, :, 0]\n", "markers = tensor[:, :, 1]\n", "obstacles_mask = tensor[:, :, 2] if tensor.shape[2] > 2 else np.zeros_like(markers)\n", "# elevation_raw is the unnormalized elevation in the original units\n", "elevation_raw = elevation_norm * (global_max - global_min) + global_min" ] }, { "cell_type": "markdown", "id": "4f8c657f", "metadata": {}, "source": [ "## Extract Markers\n", "\n", "Use the marker channel to recover the start/end coordinates." ] }, { "cell_type": "code", "execution_count": null, "id": "957e9865", "metadata": {}, "outputs": [], "source": [ "start_positions = np.argwhere(np.isclose(markers, 0.0))\n", "end_positions = np.argwhere(markers > 0.5)\n", "if len(start_positions) < 1 or len(end_positions) < 1:\n", " raise ValueError(\"Expected start and end markers in the tensor.\")\n", "\n", "start = tuple(start_positions[0])\n", "end = tuple(end_positions[0])\n", "\n", "print(f\"Start: {start}\")\n", "print(f\"End: {end}\")\n", "print(f\"Euclidean distance: {np.hypot(start[0] - end[0], start[1] - end[1]):.1f} pixels\")" ] }, { "cell_type": "markdown", "id": "2b7b951d", "metadata": {}, "source": [ "## Visualize Elevation Map\n", "\n", "Visualize elevation map and markers." ] }, { "cell_type": "code", "execution_count": null, "id": "f7817ebc", "metadata": {}, "outputs": [], "source": [ "# Display elevation map with matplotlib and show markers if available\n", "fig, ax = plt.subplots(figsize=(8, 8))\n", "im = ax.imshow(elevation_norm, cmap=\"terrain\", origin=\"upper\")\n", "ax.set_title(f\"Elevation (normalized) - {RESOLUTION}x{RESOLUTION} (obstacles={'on' if USE_OBSTACLES else 'off'})\")\n", "plt.colorbar(im, ax=ax, label=\"Normalized elevation\")\n", "\n", "if USE_OBSTACLES:\n", " obs_overlay = np.ma.masked_where(obstacles_mask == 0, obstacles_mask)\n", " ax.imshow(obs_overlay, cmap=\"Reds\", alpha=0.35, origin=\"upper\")\n", "\n", "# Plot start/end markers if present\n", "try:\n", " s = start\n", " e = end\n", "except NameError:\n", " start_positions = np.argwhere(np.isclose(markers, 0.0))\n", " end_positions = np.argwhere(markers > 0.5)\n", " s = tuple(start_positions[0]) if len(start_positions) > 0 else None\n", " e = tuple(end_positions[0]) if len(end_positions) > 0 else None\n", "\n", "if s is not None:\n", " ax.plot(s[1], s[0], \"o\", color=\"lime\", markersize=8, label=\"Start\")\n", "if e is not None:\n", " ax.plot(e[1], e[0], \"x\", color=\"cyan\", markersize=8, label=\"End\")\n", "\n", "ax.legend()\n", "ax.axis(\"off\")\n", "plt.tight_layout()\n", "plt.show()\n", "\n", "# Show tensor_to_image visualization (terrain colormap + overlays)\n", "# Extract path pixels and elevation bounds from metadata, then call tensor_to_image\n", "path_pixels = None\n", "elev_range = None\n", "try:\n", " if metadata_path.exists():\n", " with open(metadata_path) as f:\n", " md_local = yaml.safe_load(f)\n", " if md_local is not None:\n", " # Prefer with_obstacles when obstacles enabled, else without_obstacles\n", " if \"paths\" in md_local:\n", " path_section = md_local.get(\"paths\", {}).get(\"with_obstacles\") or md_local.get(\"paths\", {}).get(\n", " \"without_obstacles\"\n", " )\n", " if path_section is None:\n", " path_section = md_local.get(\"path\", {})\n", " else:\n", " path_section = md_local.get(\"path\", {})\n", "\n", " if path_section:\n", " path_pixels = [(p[\"i\"], p[\"j\"]) for p in path_section.get(\"pixels\", [])]\n", "\n", " crop_info = md_local.get(\"crop\", {})\n", " if \"min_elevation\" in crop_info and \"max_elevation\" in crop_info:\n", " elev_range = (crop_info.get(\"min_elevation\"), crop_info.get(\"max_elevation\"))\n", "except Exception:\n", " path_pixels = None\n", "\n", "tensor_vis = np.stack([elevation_norm, markers, obstacles_mask], axis=-1)\n", "img_bgr = tensor_to_image(tensor_vis, path_pixels=path_pixels, elev_range=elev_range)\n", "img_rgb = img_bgr[:, :, ::-1]\n", "\n", "fig2, ax2 = plt.subplots(figsize=(8, 8))\n", "ax2.imshow(img_rgb, origin=\"upper\")\n", "ax2.set_title(\"tensor_to_image visualization (terrain + obstacles + markers)\")\n", "ax2.axis(\"off\")\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "f243d356", "metadata": {}, "source": [ "## Run Solver Comparison\n", "\n", "Compare all NetworkX and Pathfinding solvers and record execution time." ] }, { "cell_type": "code", "execution_count": null, "id": "914168d5", "metadata": {}, "outputs": [], "source": [ "# Apply obstacles if configured\n", "elevation_input = elevation_raw\n", "if USE_OBSTACLES:\n", " elevation_input = elevation_raw.copy()\n", " elevation_input[obstacles_mask == 1] = elevation_input.max() + OBSTACLE_PENALTY\n", "\n", "# Prebuild NetworkX graphs for each cost_model used by networkx solvers (reuse if multiple solvers use same model)\n", "networkx_solvers = [s for s in SOLVERS if s[\"name\"].split(\":\", 1)[0] == \"networkx\"]\n", "G_prebuilt_map = {}\n", "if networkx_solvers:\n", " from passage.generate import build_graph_from_elevation\n", "\n", " # Build a shared graph per cost_model (defaults to global COST_MODEL)\n", " cost_models = set(s.get(\"cost_model\", COST_MODEL) for s in networkx_solvers)\n", " for cost_model_name in cost_models:\n", " G_prebuilt_map[cost_model_name] = build_graph_from_elevation(\n", " elevation_input, weight=WEIGHT, diagonal_movement=DIAGONAL_MOVEMENT, cost_model=cost_model_name\n", " )\n", "\n", "results = []\n", "\n", "for solver_info in SOLVERS:\n", " solver_config = {\n", " \"name\": solver_info[\"name\"],\n", " \"diagonal_movement\": DIAGONAL_MOVEMENT,\n", " \"weight\": WEIGHT,\n", " \"cost_model\": solver_info.get(\"cost_model\", COST_MODEL),\n", " }\n", " if \"heuristic\" in solver_info:\n", " solver_config[\"heuristic\"] = solver_info[\"heuristic\"]\n", "\n", " t0 = time.perf_counter()\n", "\n", " backend_name = solver_info[\"name\"].split(\":\", 1)[0]\n", " if backend_name == \"networkx\":\n", " prebuilt = G_prebuilt_map.get(solver_config[\"cost_model\"])\n", " path = find_path(elevation_input, start, end, solver_config, prebuilt_graph=prebuilt)\n", " else:\n", " path = find_path(elevation_input, start, end, solver_config)\n", "\n", " elapsed = (time.perf_counter() - t0) * 1000\n", "\n", " results.append(\n", " {\n", " \"solver\": solver_info[\"label\"],\n", " \"backend\": backend_name,\n", " \"path_length\": len(path),\n", " \"time_ms\": elapsed,\n", " \"path\": path,\n", " }\n", " )\n", "\n", " print(f\"{solver_info['label']}: path_len={len(path)}, time={elapsed:.1f} ms\")\n", "\n", "\n", "timings_df = pd.DataFrame(\n", " [\n", " {\"Solver\": r[\"solver\"], \"Backend\": r[\"backend\"], \"Path Length\": r[\"path_length\"], \"Time (ms)\": r[\"time_ms\"]}\n", " for r in results\n", " ]\n", ")\n", "csv_path = OUTPUTS_DIR / f\"solver_times_{RESOLUTION}_{SAMPLE_INDEX:010d}.csv\"\n", "csv_path.parent.mkdir(parents=True, exist_ok=True)\n", "\n", "timings_df.to_csv(csv_path, index=False)\n", "print(f\"Saved timings to: {csv_path}\")" ] }, { "cell_type": "markdown", "id": "298c4433", "metadata": {}, "source": [ "**Note:** The *Grid* solvers (`grid:astar`, `grid:dijkstra`) are internal NumPy\u2011based implementations that avoid constructing a NetworkX graph. They typically run faster and use less memory for large grids (e.g., 1024, 2048, 4096). Consider using these when performance is a priority." ] }, { "cell_type": "markdown", "id": "bac3c234", "metadata": {}, "source": [ "## Results Summary\n", "\n", "Sort the solvers by execution time." ] }, { "cell_type": "code", "execution_count": null, "id": "0b4d422c", "metadata": {}, "outputs": [], "source": [ "df = timings_df.sort_values(\"Time (ms)\").reset_index(drop=True)\n", "df" ] }, { "cell_type": "markdown", "id": "0ea3ad7b", "metadata": {}, "source": [ "## Timing Bar Chart" ] }, { "cell_type": "code", "execution_count": null, "id": "655c84fe", "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots(figsize=(10, 6))\n", "y_pos = range(len(df))\n", "bars = ax.barh(y_pos, df[\"Time (ms)\"], color=\"steelblue\")\n", "ax.set_yticks(y_pos)\n", "ax.set_yticklabels(df[\"Solver\"])\n", "ax.set_xlabel(\"Time (ms)\")\n", "ax.set_title(f\"Solver Comparison - {RESOLUTION}x{RESOLUTION}\")\n", "ax.invert_yaxis()\n", "\n", "# Add time labels\n", "for i, (bar, time_val) in enumerate(zip(bars, df[\"Time (ms)\"])):\n", " ax.text(bar.get_width() + 0.5, bar.get_y() + bar.get_height() / 2, f\"{time_val:.1f} ms\", va=\"center\", fontsize=9)\n", "\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "eef28b05", "metadata": {}, "source": [ "## Path Visualization (All Solvers)\n", "\n", "Overlay all solver paths on the elevation map." ] }, { "cell_type": "code", "execution_count": null, "id": "ef48fc78", "metadata": {}, "outputs": [], "source": [ "fig, ax = plt.subplots(figsize=(10, 10))\n", "ax.imshow(elevation_norm, cmap=\"terrain\", alpha=0.85, origin=\"upper\")\n", "\n", "if USE_OBSTACLES:\n", " obs_overlay = np.ma.masked_where(obstacles_mask == 0, obstacles_mask)\n", " ax.imshow(obs_overlay, cmap=\"Reds\", alpha=0.25, origin=\"upper\")\n", "\n", "# Use a colormap for different solvers\n", "\n", "colors = cm.tab20(np.linspace(0, 1, len(results)))\n", "\n", "for idx, result in enumerate(results):\n", " path = result[\"path\"]\n", " if len(path) == 0:\n", " continue\n", " path_arr = np.array(path)\n", " ax.plot(path_arr[:, 1], path_arr[:, 0], linewidth=2, color=colors[idx], label=result[\"solver\"])\n", "\n", "ax.plot(start[1], start[0], \"o\", color=\"lime\", markersize=8, label=\"Start\")\n", "ax.plot(end[1], end[0], \"x\", color=\"cyan\", markersize=8, label=\"End\")\n", "\n", "ax.set_title(\"All Solver Paths\")\n", "ax.legend(loc=\"upper left\", fontsize=8, bbox_to_anchor=(1.02, 1))\n", "ax.axis(\"off\")\n", "plt.tight_layout()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "b4b011ca", "metadata": {}, "source": [ "## Path Visualization (Per Solver)\n", "\n", "Show one subplot per solver to compare route shapes." ] }, { "cell_type": "code", "execution_count": null, "id": "63d892f6", "metadata": {}, "outputs": [], "source": [ "n_solvers = len(results)\n", "cols = min(3, n_solvers)\n", "rows = (n_solvers + cols - 1) // cols\n", "\n", "fig, axes = plt.subplots(rows, cols, figsize=(5 * cols, 5 * rows))\n", "if rows == 1:\n", " axes = axes.reshape(1, -1)\n", "if cols == 1:\n", " axes = axes.reshape(-1, 1)\n", "\n", "for idx, result in enumerate(results):\n", " r = idx // cols\n", " c = idx % cols\n", " ax = axes[r, c]\n", "\n", " ax.imshow(elevation_norm, cmap=\"terrain\", alpha=0.85, origin=\"upper\")\n", "\n", " if USE_OBSTACLES:\n", " obs_overlay = np.ma.masked_where(obstacles_mask == 0, obstacles_mask)\n", " ax.imshow(obs_overlay, cmap=\"Reds\", alpha=0.25, origin=\"upper\")\n", "\n", " path = result[\"path\"]\n", " if len(path) > 0:\n", " path_arr = np.array(path)\n", " ax.plot(path_arr[:, 1], path_arr[:, 0], \"r-\", linewidth=2)\n", "\n", " ax.plot(start[1], start[0], \"o\", color=\"lime\", markersize=6)\n", " ax.plot(end[1], end[0], \"x\", color=\"cyan\", markersize=6)\n", " ax.set_title(f\"{result['solver']}\\n{result['time_ms']:.1f}ms, {result['path_length']} px\", fontsize=9)\n", " ax.axis(\"off\")\n", "\n", "# Hide empty subplots\n", "for idx in range(n_solvers, rows * cols):\n", " r = idx // cols\n", " c = idx % cols\n", " axes[r, c].axis(\"off\")\n", "\n", "plt.tight_layout()\n", "plt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "passage (3.12.3)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.3" } }, "nbformat": 4, "nbformat_minor": 5 }