Upload folder using huggingface_hub
Browse files- __init__.py +1 -0
- __pycache__/__init__.cpython-312.pyc +0 -0
- __pycache__/sync_bundle.cpython-312.pyc +0 -0
- bundle/README.md +94 -0
- bundle/app.py +557 -0
- bundle/cloudie/samples/synthetic_ir.npy +3 -0
- bundle/config/config.yaml +233 -0
- bundle/config/config_incyde.yaml +201 -0
- bundle/config/config_smoke.yaml +196 -0
- bundle/config/incyde_cpu.yaml +41 -0
- bundle/requirements.txt +8 -0
- bundle/src/__init__.py +6 -0
- bundle/src/baselines.py +1854 -0
- bundle/src/cache_frames.py +72 -0
- bundle/src/calibration.py +345 -0
- bundle/src/config.py +68 -0
- bundle/src/data_loader.py +102 -0
- bundle/src/device.py +390 -0
- bundle/src/evaluate.py +1218 -0
- bundle/src/features.py +899 -0
- bundle/src/incyde.py +778 -0
- bundle/src/inference.py +1313 -0
- bundle/src/labels.py +216 -0
- bundle/src/make_smoke_data.py +153 -0
- bundle/src/metrics.py +174 -0
- bundle/src/model.py +262 -0
- bundle/src/model_access.py +26 -0
- bundle/src/nasa_tc.py +360 -0
- bundle/src/plots.py +109 -0
- bundle/src/preprocessing.py +314 -0
- bundle/src/reproducibility.py +46 -0
- bundle/src/schema.py +342 -0
- bundle/src/sequences.py +171 -0
- bundle/src/splits.py +318 -0
- bundle/src/tcir.py +591 -0
- bundle/src/train.py +2356 -0
- bundle/src/verify_splits.py +220 -0
- bundle/sync_bundle.py +103 -0
- requirements.txt +8 -8
__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Hugging Face Space package. The Gradio entry is ``space.app``."""
|
__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (224 Bytes). View file
|
|
|
__pycache__/sync_bundle.cpython-312.pyc
ADDED
|
Binary file (5.28 kB). View file
|
|
|
bundle/README.md
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Cloudie
|
| 3 |
+
emoji: "🌀"
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: red
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.31.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
python_version: "3.11"
|
| 10 |
+
hardware: cpu-basic
|
| 11 |
+
suggested_hardware: cpu-basic
|
| 12 |
+
short_description: Cyclone IR demo. Not a forecast.
|
| 13 |
+
pinned: false
|
| 14 |
+
fullWidth: false
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
# Cloudie
|
| 18 |
+
|
| 19 |
+
Academic demo that reads one infrared frame and, when a checkpoint is allowed
|
| 20 |
+
to answer, reports a wind speed in knots and this project's own intensity
|
| 21 |
+
grouping. The page shows the same permanent banner as the web demo
|
| 22 |
+
(`NO_TRAINED_MODEL_BANNER` in `src/inference.py`). It is not a forecast or a
|
| 23 |
+
warning system. No trained weights are in this bundle.
|
| 24 |
+
|
| 25 |
+
The greyscale cyclone-IR gate and `RunCheckpoint` live in `src/inference.py`.
|
| 26 |
+
A colour frame is refused with that gate's message and no wind. Confidence
|
| 27 |
+
and the wind interval stay labelled uncalibrated. The interval is a dash.
|
| 28 |
+
Nearest Indian coastal states appear only after latitude and longitude, and
|
| 29 |
+
they are labelled with the config note that this is not a landfall forecast.
|
| 30 |
+
The bundled `synthetic_ir.npy` sample is synthetic. It is not a satellite image.
|
| 31 |
+
|
| 32 |
+
A wind number appears in two cases:
|
| 33 |
+
|
| 34 |
+
- The checkpoint is the synthetic software check. The page says so.
|
| 35 |
+
- `paths.runs/<run_id>/` contains the checkpoint and `metrics.json` from
|
| 36 |
+
`src.train`, or `CLOUDIE_HF_MODEL_REPO` / `paths.hf_model_repo` names a
|
| 37 |
+
model repo with that same layout, and the record passes the held-out
|
| 38 |
+
storm check in `src.inference.ConfidenceScore`. Until that record exists,
|
| 39 |
+
the page shows no wind.
|
| 40 |
+
|
| 41 |
+
`CLOUDIE_RUN_ID` selects the run directory. `CLOUDIE_CHECKPOINT` may point
|
| 42 |
+
at one local file for the operator. The form does not ask the visitor for a path.
|
| 43 |
+
|
| 44 |
+
## Bundle
|
| 45 |
+
|
| 46 |
+
The GitHub repository keeps `src/` as the canonical copy. `cloudie/`
|
| 47 |
+
re-exports those modules. The Space imports `src` only. From a checkout:
|
| 48 |
+
|
| 49 |
+
```bash
|
| 50 |
+
python space/sync_bundle.py --out /tmp/cloudie-space
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
The directory passed to `--out` is what gets uploaded. It contains `app.py`,
|
| 54 |
+
`requirements.txt`, this `README.md`, `src/`, `config/`, and
|
| 55 |
+
`cloudie/samples/synthetic_ir.npy`. The script does not copy `data/`,
|
| 56 |
+
`artifacts/`, or checkpoints.
|
| 57 |
+
|
| 58 |
+
CPU torch is pinned in `requirements.txt` through the PyTorch CPU index.
|
| 59 |
+
Gradio is selected by `sdk_version` above and is not pinned again in
|
| 60 |
+
`requirements.txt`. Hardware is `cpu-basic`. Do not select a GPU flavor.
|
| 61 |
+
|
| 62 |
+
## Deploy
|
| 63 |
+
|
| 64 |
+
Do this after the GitHub change is merged, with a token that can create and
|
| 65 |
+
write the Space. This checkout does not push the Space.
|
| 66 |
+
|
| 67 |
+
1. Create a fine-grained token at <https://huggingface.co/settings/tokens>
|
| 68 |
+
with write access limited to the Space `Anlea/cloudie`. To create the
|
| 69 |
+
repo, the token also needs permission to create a Space under the user
|
| 70 |
+
`Anlea` (contributor permission, or a classic token whose role is
|
| 71 |
+
`write`). A read-only token cannot upload the bundle.
|
| 72 |
+
2. Build the bundle from the merged commit: `python space/sync_bundle.py --out /tmp/cloudie-space`.
|
| 73 |
+
3. Log in: `hf auth login`.
|
| 74 |
+
4. Create the Space on free CPU hardware:
|
| 75 |
+
|
| 76 |
+
```bash
|
| 77 |
+
hf repos create Anlea/cloudie --type space --space-sdk gradio --flavor cpu-basic --public --exist-ok
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
5. Upload the bundle, not the GitHub root:
|
| 81 |
+
|
| 82 |
+
```bash
|
| 83 |
+
hf upload Anlea/cloudie /tmp/cloudie-space . --repo-type space --commit-message "Cloudie CPU Space"
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
6. Leave the hardware on `cpu-basic`. If a later settings change is required:
|
| 87 |
+
`hf spaces settings Anlea/cloudie --hardware cpu-basic`.
|
| 88 |
+
|
| 89 |
+
The running Space reads `CLOUDIE_HF_MODEL_REPO` from a Space variable when a
|
| 90 |
+
real checkpoint exists, and a Space secret named `HF_TOKEN` with read access
|
| 91 |
+
to that model repo when the repo is private. Leave both unset until a
|
| 92 |
+
held-out real-data record exists. Creating a Gradio Space can require a Hub
|
| 93 |
+
plan even though `cpu-basic` has no hourly charge. This app does not request
|
| 94 |
+
a GPU.
|
bundle/app.py
ADDED
|
@@ -0,0 +1,557 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Gradio page for the Cloudie Space.
|
| 2 |
+
|
| 3 |
+
Project code is imported from ``src`` only. The permanent banner is
|
| 4 |
+
``NO_TRAINED_MODEL_BANNER`` in ``src.inference``, the same constant the web
|
| 5 |
+
demo re-exports. This page is not a forecast or a warning system.
|
| 6 |
+
|
| 7 |
+
``RunCheckpoint`` loads ``paths.runs/<run_id>/`` or a Hub repo that mirrors
|
| 8 |
+
that run directory. A wind is shown for the synthetic software-check file,
|
| 9 |
+
flagged as such, and for a real run whose record passes the held-out storm
|
| 10 |
+
check. Visitors do not choose the file.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import sys
|
| 16 |
+
import warnings
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class SpaceLayout:
|
| 24 |
+
"""Locate the checkout or the synced Space bundle and put it on ``sys.path``."""
|
| 25 |
+
|
| 26 |
+
@staticmethod
|
| 27 |
+
def root() -> Path:
|
| 28 |
+
here = Path(__file__).resolve().parent
|
| 29 |
+
if (here / "src" / "inference.py").is_file():
|
| 30 |
+
return here
|
| 31 |
+
parent = here.parent
|
| 32 |
+
if (parent / "src" / "inference.py").is_file():
|
| 33 |
+
return parent
|
| 34 |
+
raise FileNotFoundError(
|
| 35 |
+
"src/inference.py is not beside this app. Run python space/sync_bundle.py."
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
@staticmethod
|
| 39 |
+
def install() -> Path:
|
| 40 |
+
root = SpaceLayout.root()
|
| 41 |
+
entry = str(root)
|
| 42 |
+
if entry not in sys.path:
|
| 43 |
+
sys.path.insert(0, entry)
|
| 44 |
+
return root
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
ROOT = SpaceLayout.install()
|
| 48 |
+
|
| 49 |
+
from src.config import load_config # noqa: E402
|
| 50 |
+
from src.inference import ( # noqa: E402
|
| 51 |
+
CONFIDENCE_NOTE,
|
| 52 |
+
GROUPING_LABEL,
|
| 53 |
+
NO_TRAINED_MODEL_BANNER,
|
| 54 |
+
PAGE_LEAD,
|
| 55 |
+
SCALE_NOTE,
|
| 56 |
+
CoastalContext,
|
| 57 |
+
RunCheckpoint,
|
| 58 |
+
)
|
| 59 |
+
from src.schema import wind_to_imd5 # noqa: E402
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
import spaces
|
| 64 |
+
_gpu_decorator = spaces.GPU
|
| 65 |
+
except (ImportError, AttributeError):
|
| 66 |
+
def _gpu_decorator(fn):
|
| 67 |
+
return fn
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
DEFAULT_HF_MODEL_REPO = "Anlea/cloudie-weights"
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class SpaceConfig:
|
| 74 |
+
"""The NASA config. Smoke stays a local software check."""
|
| 75 |
+
|
| 76 |
+
DEFAULT_REPO = DEFAULT_HF_MODEL_REPO
|
| 77 |
+
|
| 78 |
+
@staticmethod
|
| 79 |
+
def load(root: Path | None = None) -> dict:
|
| 80 |
+
base = root or SpaceLayout.root()
|
| 81 |
+
config = load_config(base / "config" / "config.yaml")
|
| 82 |
+
if not config.get("paths", {}).get("hf_model_repo"):
|
| 83 |
+
config.setdefault("paths", {})["hf_model_repo"] = SpaceConfig.DEFAULT_REPO
|
| 84 |
+
return config
|
| 85 |
+
|
| 86 |
+
@staticmethod
|
| 87 |
+
def uncalibrated(config: dict) -> str:
|
| 88 |
+
label = str(config["predict"]["confidence"]["uncalibrated_label"]).strip()
|
| 89 |
+
if not label:
|
| 90 |
+
raise ValueError("config predict.confidence.uncalibrated_label is empty")
|
| 91 |
+
return label
|
| 92 |
+
|
| 93 |
+
class SpaceSamples:
|
| 94 |
+
"""Bundled frames. The synthetic sample is not a satellite image."""
|
| 95 |
+
|
| 96 |
+
HINT = "The bundled frame is synthetic. It is not a satellite image."
|
| 97 |
+
|
| 98 |
+
@staticmethod
|
| 99 |
+
def label(name: str) -> str:
|
| 100 |
+
if name == "synthetic_ir.npy":
|
| 101 |
+
return "synthetic_ir.npy — bundled synthetic sample"
|
| 102 |
+
return name
|
| 103 |
+
|
| 104 |
+
@staticmethod
|
| 105 |
+
def choices(root: Path | None = None) -> list[tuple[str, str]]:
|
| 106 |
+
base = root or SpaceLayout.root()
|
| 107 |
+
rows = [("(none)", "(none)")]
|
| 108 |
+
sample = base / "cloudie" / "samples" / "synthetic_ir.npy"
|
| 109 |
+
if sample.is_file():
|
| 110 |
+
rows.append((SpaceSamples.label(sample.name), sample.name))
|
| 111 |
+
return rows
|
| 112 |
+
|
| 113 |
+
@staticmethod
|
| 114 |
+
def load(name: str, root: Path) -> np.ndarray | None:
|
| 115 |
+
if name.strip() in {"", "(none)", "none"}:
|
| 116 |
+
return None
|
| 117 |
+
if name != Path(name).name or ".." in name:
|
| 118 |
+
raise ValueError("That example frame is not available.")
|
| 119 |
+
path = root / "cloudie" / "samples" / name
|
| 120 |
+
if not path.is_file():
|
| 121 |
+
raise ValueError("That example frame is not available.")
|
| 122 |
+
return np.load(path, allow_pickle=False)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class SpaceFrame:
|
| 126 |
+
"""Turn a Gradio upload or the bundled sample into one array."""
|
| 127 |
+
|
| 128 |
+
@staticmethod
|
| 129 |
+
def path_of(upload) -> Path | None:
|
| 130 |
+
if upload is None:
|
| 131 |
+
return None
|
| 132 |
+
if isinstance(upload, (str, Path)):
|
| 133 |
+
text = str(upload).strip()
|
| 134 |
+
return Path(text) if text else None
|
| 135 |
+
if isinstance(upload, dict):
|
| 136 |
+
raw = upload.get("path") or upload.get("name")
|
| 137 |
+
return Path(str(raw)) if raw else None
|
| 138 |
+
name = getattr(upload, "name", None)
|
| 139 |
+
if name:
|
| 140 |
+
return Path(str(name))
|
| 141 |
+
return None
|
| 142 |
+
|
| 143 |
+
@staticmethod
|
| 144 |
+
def choose(image, npy_file, sample: str, root: Path) -> np.ndarray | None:
|
| 145 |
+
"""An upload replaces the bundled sample, as on the web demo."""
|
| 146 |
+
npy_path = SpaceFrame.path_of(npy_file)
|
| 147 |
+
if npy_path is not None:
|
| 148 |
+
if npy_path.suffix.lower() != ".npy":
|
| 149 |
+
raise ValueError("The extra frame must be a .npy file.")
|
| 150 |
+
return np.asarray(np.load(npy_path, allow_pickle=False))
|
| 151 |
+
if image is not None:
|
| 152 |
+
return np.asarray(image)
|
| 153 |
+
return SpaceSamples.load(sample or "(none)", root)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class SpacePreview:
|
| 157 |
+
"""A display image. The gate still sees the original array."""
|
| 158 |
+
|
| 159 |
+
@staticmethod
|
| 160 |
+
def rgb(image: np.ndarray) -> np.ndarray:
|
| 161 |
+
array = np.asarray(image)
|
| 162 |
+
if array.ndim == 3 and array.shape[-1] in (3, 4):
|
| 163 |
+
scaled = SpacePreview._uint8(array[..., :3])
|
| 164 |
+
return scaled
|
| 165 |
+
field = array[..., 0] if array.ndim == 3 else array
|
| 166 |
+
scaled = SpacePreview._uint8(field)
|
| 167 |
+
return np.stack([scaled, scaled, scaled], axis=-1)
|
| 168 |
+
|
| 169 |
+
@staticmethod
|
| 170 |
+
def _uint8(array: np.ndarray) -> np.ndarray:
|
| 171 |
+
values = np.asarray(array, dtype=np.float64)
|
| 172 |
+
if values.ndim == 2:
|
| 173 |
+
finite = values[np.isfinite(values)]
|
| 174 |
+
scaled = SpacePreview._scale(values, finite)
|
| 175 |
+
return scaled.astype(np.uint8)
|
| 176 |
+
channels = [
|
| 177 |
+
SpacePreview._scale(values[..., index], values[..., index][np.isfinite(values[..., index])])
|
| 178 |
+
for index in range(values.shape[-1])
|
| 179 |
+
]
|
| 180 |
+
return np.stack(channels, axis=-1).astype(np.uint8)
|
| 181 |
+
|
| 182 |
+
@staticmethod
|
| 183 |
+
def _scale(values: np.ndarray, finite: np.ndarray) -> np.ndarray:
|
| 184 |
+
if finite.size == 0:
|
| 185 |
+
return np.zeros(values.shape, dtype=np.float64)
|
| 186 |
+
low, high = np.percentile(finite, [1, 99])
|
| 187 |
+
if high <= low:
|
| 188 |
+
high = low + 1.0
|
| 189 |
+
return np.clip((values - low) / (high - low), 0.0, 1.0) * 255.0
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class SpaceCoast:
|
| 194 |
+
"""Nearest configured coastal states. A position is required. Not a landfall forecast."""
|
| 195 |
+
|
| 196 |
+
@staticmethod
|
| 197 |
+
def idle(config: dict) -> str:
|
| 198 |
+
note = str(config["predict"]["landfall_note"]).strip()
|
| 199 |
+
return (
|
| 200 |
+
"Nearest coastal states are listed only when latitude and longitude "
|
| 201 |
+
f"are both provided. {note}."
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
@staticmethod
|
| 205 |
+
def coordinate(value) -> float | None:
|
| 206 |
+
if value is None or value == "":
|
| 207 |
+
return None
|
| 208 |
+
return float(value)
|
| 209 |
+
|
| 210 |
+
@staticmethod
|
| 211 |
+
def line(config: dict, latitude, longitude) -> str:
|
| 212 |
+
note = str(config["predict"]["landfall_note"]).strip()
|
| 213 |
+
try:
|
| 214 |
+
lat = SpaceCoast.coordinate(latitude)
|
| 215 |
+
lon = SpaceCoast.coordinate(longitude)
|
| 216 |
+
except (TypeError, ValueError):
|
| 217 |
+
return f"Latitude and longitude must be numbers. {note}."
|
| 218 |
+
if lat is None and lon is None:
|
| 219 |
+
return SpaceCoast.idle(config)
|
| 220 |
+
try:
|
| 221 |
+
names, landfall, reference = CoastalContext.describe(config, lat, lon, None)
|
| 222 |
+
except ValueError as exc:
|
| 223 |
+
return f"{exc}. {note}."
|
| 224 |
+
if not names:
|
| 225 |
+
return f"No coastal reference was returned. {note}."
|
| 226 |
+
heading = str(config["predict"]["coastal_heading"]).strip()
|
| 227 |
+
parts = [f"{heading}: {', '.join(names)}", landfall or note]
|
| 228 |
+
if reference:
|
| 229 |
+
parts.append(str(reference).strip())
|
| 230 |
+
return "\n\n".join(part for part in parts if part)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
@dataclass(frozen=True)
|
| 234 |
+
class SpaceView:
|
| 235 |
+
"""Text the page shows. ``show_wind`` is false whenever the knots stay hidden."""
|
| 236 |
+
|
| 237 |
+
permanent_banner: str
|
| 238 |
+
status: str
|
| 239 |
+
wind: str
|
| 240 |
+
category: str
|
| 241 |
+
confidence: str
|
| 242 |
+
interval: str
|
| 243 |
+
interval_note: str
|
| 244 |
+
grouping: str
|
| 245 |
+
coastal: str
|
| 246 |
+
show_wind: bool
|
| 247 |
+
preview: np.ndarray | None = None
|
| 248 |
+
|
| 249 |
+
def outputs(self):
|
| 250 |
+
return (
|
| 251 |
+
self.status,
|
| 252 |
+
self.wind,
|
| 253 |
+
self.category,
|
| 254 |
+
self.confidence,
|
| 255 |
+
self.interval,
|
| 256 |
+
self.interval_note,
|
| 257 |
+
self.grouping,
|
| 258 |
+
self.coastal,
|
| 259 |
+
self.preview,
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class SpacePage:
|
| 264 |
+
"""Score one frame with the project inference code and the shared banner."""
|
| 265 |
+
|
| 266 |
+
ASK_FOR_FRAME = "Add an infrared frame, then predict intensity."
|
| 267 |
+
|
| 268 |
+
@staticmethod
|
| 269 |
+
def idle(config: dict | None = None) -> SpaceView:
|
| 270 |
+
loaded = config or SpaceConfig.load()
|
| 271 |
+
uncalibrated = SpaceConfig.uncalibrated(loaded)
|
| 272 |
+
return SpaceView(
|
| 273 |
+
permanent_banner=NO_TRAINED_MODEL_BANNER,
|
| 274 |
+
status="",
|
| 275 |
+
wind="—",
|
| 276 |
+
category="—",
|
| 277 |
+
confidence=f"— ({uncalibrated})",
|
| 278 |
+
interval="—",
|
| 279 |
+
interval_note=f"{uncalibrated}. No numeric range is shown.",
|
| 280 |
+
grouping=str(loaded["data"]["grouping_note"]).strip(),
|
| 281 |
+
coastal=SpaceCoast.idle(loaded),
|
| 282 |
+
show_wind=False,
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
@staticmethod
|
| 286 |
+
def _blank(config: dict, status: str, coastal: str, preview, *, show_wind: bool = False) -> SpaceView:
|
| 287 |
+
idle = SpacePage.idle(config)
|
| 288 |
+
return SpaceView(
|
| 289 |
+
permanent_banner=NO_TRAINED_MODEL_BANNER,
|
| 290 |
+
status=status,
|
| 291 |
+
wind=idle.wind,
|
| 292 |
+
category=idle.category,
|
| 293 |
+
confidence=idle.confidence,
|
| 294 |
+
interval=idle.interval,
|
| 295 |
+
interval_note=idle.interval_note,
|
| 296 |
+
grouping=idle.grouping,
|
| 297 |
+
coastal=coastal,
|
| 298 |
+
show_wind=show_wind,
|
| 299 |
+
preview=preview,
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
LABELS = {
|
| 303 |
+
"D_DD": "Depression / Deep Depression",
|
| 304 |
+
"CS": "Cyclonic Storm",
|
| 305 |
+
"SCS": "Severe Cyclonic Storm",
|
| 306 |
+
"VSCS": "Very Severe Cyclonic Storm",
|
| 307 |
+
"ESCS_SUCS": "Extremely Severe / Super Cyclonic Storm",
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
@staticmethod
|
| 311 |
+
def _category(config: dict, estimate) -> str:
|
| 312 |
+
if estimate.wind_kt is None:
|
| 313 |
+
return "—"
|
| 314 |
+
edges = estimate.edges or tuple(float(edge) for edge in config["data"]["imd5_edges_kt"])
|
| 315 |
+
names = estimate.names or tuple(str(name) for name in config["data"]["imd5_names"])
|
| 316 |
+
code = wind_to_imd5(float(estimate.wind_kt), edges, names)
|
| 317 |
+
if code is None:
|
| 318 |
+
return "Below depression"
|
| 319 |
+
return SpacePage.LABELS.get(code, code)
|
| 320 |
+
|
| 321 |
+
@staticmethod
|
| 322 |
+
def _from_estimate(config: dict, estimate, coastal: str, preview) -> SpaceView:
|
| 323 |
+
uncalibrated = SpaceConfig.uncalibrated(config)
|
| 324 |
+
show = estimate.outcome == "ok" and estimate.wind_kt is not None
|
| 325 |
+
status_bits = []
|
| 326 |
+
if estimate.operational_disclaimer:
|
| 327 |
+
status_bits.append(str(estimate.operational_disclaimer))
|
| 328 |
+
if show and estimate.is_synthetic:
|
| 329 |
+
if estimate.honesty:
|
| 330 |
+
status_bits.append(str(estimate.honesty))
|
| 331 |
+
status_bits.append("The number is a software check. It is not a forecast.")
|
| 332 |
+
elif estimate.banner:
|
| 333 |
+
status_bits.append(str(estimate.banner))
|
| 334 |
+
grouping = str(estimate.grouping_note or config["data"]["grouping_note"]).strip()
|
| 335 |
+
grouping = f"{grouping} This is the project's own grouping, not an official IMD class."
|
| 336 |
+
if not show:
|
| 337 |
+
return SpaceView(
|
| 338 |
+
permanent_banner=NO_TRAINED_MODEL_BANNER,
|
| 339 |
+
status="\n".join(bit for bit in status_bits if bit),
|
| 340 |
+
wind="—",
|
| 341 |
+
category="—",
|
| 342 |
+
confidence=f"— ({uncalibrated})",
|
| 343 |
+
interval="—",
|
| 344 |
+
interval_note=f"{uncalibrated}. No numeric range is shown.",
|
| 345 |
+
grouping=grouping,
|
| 346 |
+
coastal=coastal,
|
| 347 |
+
show_wind=False,
|
| 348 |
+
preview=preview,
|
| 349 |
+
)
|
| 350 |
+
percent = "—" if estimate.confidence is None else f"{estimate.confidence * 100:.0f}%"
|
| 351 |
+
label = estimate.confidence_status or uncalibrated
|
| 352 |
+
wind = f"{estimate.wind_kt:.1f} kt"
|
| 353 |
+
if estimate.wind_kmh is not None:
|
| 354 |
+
wind = f"{wind} ({estimate.wind_kmh:.1f} km/h)"
|
| 355 |
+
if label == uncalibrated:
|
| 356 |
+
interval_note = f"{uncalibrated}. No numeric range is shown. {CONFIDENCE_NOTE}"
|
| 357 |
+
else:
|
| 358 |
+
interval_note = (
|
| 359 |
+
f"{label}. {uncalibrated}. No numeric range is shown. {CONFIDENCE_NOTE}"
|
| 360 |
+
)
|
| 361 |
+
return SpaceView(
|
| 362 |
+
permanent_banner=NO_TRAINED_MODEL_BANNER,
|
| 363 |
+
status="\n".join(bit for bit in status_bits if bit),
|
| 364 |
+
wind=wind,
|
| 365 |
+
category=SpacePage._category(config, estimate),
|
| 366 |
+
confidence=f"{percent} ({label})",
|
| 367 |
+
interval="—",
|
| 368 |
+
interval_note=interval_note,
|
| 369 |
+
grouping=grouping,
|
| 370 |
+
coastal=coastal,
|
| 371 |
+
show_wind=True,
|
| 372 |
+
preview=preview,
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
@staticmethod
|
| 376 |
+
def view(
|
| 377 |
+
image,
|
| 378 |
+
npy_file,
|
| 379 |
+
sample: str,
|
| 380 |
+
latitude,
|
| 381 |
+
longitude,
|
| 382 |
+
*,
|
| 383 |
+
config: dict | None = None,
|
| 384 |
+
root: Path | None = None,
|
| 385 |
+
checkpoint: Path | None | object = None,
|
| 386 |
+
resolve_checkpoint: bool = False,
|
| 387 |
+
) -> SpaceView:
|
| 388 |
+
"""Ask ``src.inference.RunCheckpoint`` to gate the frame and load a run.
|
| 389 |
+
|
| 390 |
+
``resolve_checkpoint`` is what the button uses. Tests pass ``checkpoint``
|
| 391 |
+
themselves. A missing file yields no wind. A colour frame yields the
|
| 392 |
+
gate refusal and no wind.
|
| 393 |
+
"""
|
| 394 |
+
loaded = config or SpaceConfig.load()
|
| 395 |
+
base = root or SpaceLayout.root()
|
| 396 |
+
coastal = SpaceCoast.line(loaded, latitude, longitude)
|
| 397 |
+
try:
|
| 398 |
+
frame = SpaceFrame.choose(image, npy_file, sample or "(none)", base)
|
| 399 |
+
except (OSError, ValueError) as exc:
|
| 400 |
+
return SpacePage._blank(loaded, str(exc), coastal, None)
|
| 401 |
+
if frame is None:
|
| 402 |
+
return SpacePage._blank(loaded, SpacePage.ASK_FOR_FRAME, coastal, None)
|
| 403 |
+
preview = SpacePreview.rgb(frame)
|
| 404 |
+
try:
|
| 405 |
+
lat = SpaceCoast.coordinate(latitude)
|
| 406 |
+
lon = SpaceCoast.coordinate(longitude)
|
| 407 |
+
except (TypeError, ValueError):
|
| 408 |
+
lat, lon = None, None
|
| 409 |
+
if lat is None or lon is None:
|
| 410 |
+
lat, lon = None, None
|
| 411 |
+
if resolve_checkpoint:
|
| 412 |
+
estimate = RunCheckpoint.estimate(
|
| 413 |
+
loaded,
|
| 414 |
+
[frame],
|
| 415 |
+
latitude=lat,
|
| 416 |
+
longitude=lon,
|
| 417 |
+
root=base,
|
| 418 |
+
resolve=True,
|
| 419 |
+
)
|
| 420 |
+
else:
|
| 421 |
+
explicit = None if checkpoint is None else Path(checkpoint)
|
| 422 |
+
estimate = RunCheckpoint.estimate(
|
| 423 |
+
loaded,
|
| 424 |
+
[frame],
|
| 425 |
+
latitude=lat,
|
| 426 |
+
longitude=lon,
|
| 427 |
+
root=base,
|
| 428 |
+
path=explicit,
|
| 429 |
+
resolve=False,
|
| 430 |
+
)
|
| 431 |
+
return SpacePage._from_estimate(loaded, estimate, coastal, preview)
|
| 432 |
+
|
| 433 |
+
@staticmethod
|
| 434 |
+
@_gpu_decorator
|
| 435 |
+
def on_click(image, npy_file, sample, latitude, longitude):
|
| 436 |
+
view = SpacePage.view(
|
| 437 |
+
image,
|
| 438 |
+
npy_file,
|
| 439 |
+
sample,
|
| 440 |
+
latitude,
|
| 441 |
+
longitude,
|
| 442 |
+
resolve_checkpoint=True,
|
| 443 |
+
)
|
| 444 |
+
return view.outputs()
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
class SpaceApp:
|
| 448 |
+
"""The Blocks page. ``demo`` is the object the Space runtime launches."""
|
| 449 |
+
|
| 450 |
+
CSS = """
|
| 451 |
+
.gradio-container, main, .contain { max-width: 920px !important; margin-left: auto !important; margin-right: auto !important; }
|
| 452 |
+
#no-trained-model-banner {
|
| 453 |
+
background: #f0d2c4;
|
| 454 |
+
color: #4a2c22;
|
| 455 |
+
border-left: 4px solid #8d3d24;
|
| 456 |
+
padding: 0.85rem 1rem;
|
| 457 |
+
font-family: "Avenir Next", "Segoe UI", sans-serif;
|
| 458 |
+
}
|
| 459 |
+
"""
|
| 460 |
+
|
| 461 |
+
@staticmethod
|
| 462 |
+
def build():
|
| 463 |
+
import gradio as gr
|
| 464 |
+
|
| 465 |
+
config = SpaceConfig.load()
|
| 466 |
+
idle = SpacePage.idle(config)
|
| 467 |
+
disclaimer = str(config["predict"]["operational_disclaimer"]).strip()
|
| 468 |
+
with warnings.catch_warnings():
|
| 469 |
+
warnings.filterwarnings(
|
| 470 |
+
"ignore",
|
| 471 |
+
message="The parameters have been moved from the Blocks constructor",
|
| 472 |
+
category=UserWarning,
|
| 473 |
+
)
|
| 474 |
+
with gr.Blocks(title="Cloudie", theme=gr.themes.Soft(), css=SpaceApp.CSS) as demo:
|
| 475 |
+
gr.Markdown("# Cloudie")
|
| 476 |
+
gr.Markdown(PAGE_LEAD)
|
| 477 |
+
gr.Markdown(NO_TRAINED_MODEL_BANNER, elem_id="no-trained-model-banner")
|
| 478 |
+
gr.Markdown(SCALE_NOTE)
|
| 479 |
+
gr.Markdown(disclaimer)
|
| 480 |
+
gr.Markdown(CONFIDENCE_NOTE)
|
| 481 |
+
with gr.Row():
|
| 482 |
+
image = gr.Image(
|
| 483 |
+
type="numpy",
|
| 484 |
+
label="Infrared image",
|
| 485 |
+
sources=["upload", "clipboard"],
|
| 486 |
+
)
|
| 487 |
+
with gr.Column():
|
| 488 |
+
sample = gr.Radio(
|
| 489 |
+
choices=SpaceSamples.choices(),
|
| 490 |
+
value="(none)",
|
| 491 |
+
label="Bundled sample",
|
| 492 |
+
info=SpaceSamples.HINT,
|
| 493 |
+
)
|
| 494 |
+
latitude = gr.Textbox(
|
| 495 |
+
label="Latitude",
|
| 496 |
+
value="",
|
| 497 |
+
placeholder="optional",
|
| 498 |
+
info="Optional. Nearest coastal states need both coordinates.",
|
| 499 |
+
)
|
| 500 |
+
longitude = gr.Textbox(
|
| 501 |
+
label="Longitude",
|
| 502 |
+
value="",
|
| 503 |
+
placeholder="optional",
|
| 504 |
+
info=str(config["predict"]["landfall_note"]).strip(),
|
| 505 |
+
)
|
| 506 |
+
npy_file = gr.File(
|
| 507 |
+
label="Or a .npy infrared frame",
|
| 508 |
+
file_types=[".npy"],
|
| 509 |
+
type="filepath",
|
| 510 |
+
)
|
| 511 |
+
button = gr.Button("Predict intensity", variant="primary")
|
| 512 |
+
status = gr.Markdown(idle.status)
|
| 513 |
+
with gr.Row():
|
| 514 |
+
wind = gr.Textbox(label="Wind speed", value=idle.wind, interactive=False)
|
| 515 |
+
category = gr.Textbox(
|
| 516 |
+
label=GROUPING_LABEL,
|
| 517 |
+
value=idle.category,
|
| 518 |
+
interactive=False,
|
| 519 |
+
)
|
| 520 |
+
confidence = gr.Textbox(
|
| 521 |
+
label="Confidence (uncalibrated)",
|
| 522 |
+
value=idle.confidence,
|
| 523 |
+
interactive=False,
|
| 524 |
+
)
|
| 525 |
+
interval = gr.Textbox(
|
| 526 |
+
label="Wind interval (uncalibrated)",
|
| 527 |
+
value=idle.interval,
|
| 528 |
+
interactive=False,
|
| 529 |
+
)
|
| 530 |
+
interval_note = gr.Markdown(idle.interval_note)
|
| 531 |
+
grouping = gr.Markdown(idle.grouping)
|
| 532 |
+
coastal = gr.Markdown(idle.coastal)
|
| 533 |
+
preview = gr.Image(label="Frame passed to the gate", interactive=False)
|
| 534 |
+
button.click(
|
| 535 |
+
SpacePage.on_click,
|
| 536 |
+
inputs=[image, npy_file, sample, latitude, longitude],
|
| 537 |
+
outputs=[
|
| 538 |
+
status,
|
| 539 |
+
wind,
|
| 540 |
+
category,
|
| 541 |
+
confidence,
|
| 542 |
+
interval,
|
| 543 |
+
interval_note,
|
| 544 |
+
grouping,
|
| 545 |
+
coastal,
|
| 546 |
+
preview,
|
| 547 |
+
],
|
| 548 |
+
api_name="predict",
|
| 549 |
+
)
|
| 550 |
+
return demo
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
demo = SpaceApp.build()
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
if __name__ == "__main__":
|
| 557 |
+
demo.launch()
|
bundle/cloudie/samples/synthetic_ir.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e1e134d31885023900fb7ec901be5f5d97e8a9ed98de30ae19897b5c25796f2f
|
| 3 |
+
size 16512
|
bundle/config/config.yaml
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
project:
|
| 2 |
+
name: cyclone-intensity-estimation
|
| 3 |
+
seed: 42
|
| 4 |
+
honesty: >
|
| 5 |
+
No trained weights are shipped. Smoke images are synthetic.
|
| 6 |
+
This is not an operational forecast or warning system.
|
| 7 |
+
Best-track labels are noisy, and agreement with them is not ground truth.
|
| 8 |
+
No survey or smoke number is a result of this project.
|
| 9 |
+
paths:
|
| 10 |
+
manifest: data/manifest.csv
|
| 11 |
+
artifacts: artifacts
|
| 12 |
+
reports: reports
|
| 13 |
+
checkpoint_name: checkpoint.pt
|
| 14 |
+
run_records: artifacts/run_records
|
| 15 |
+
runs: artifacts/runs
|
| 16 |
+
nasa_root: data/nasa_tc
|
| 17 |
+
tcir_files: []
|
| 18 |
+
tcir_manifest_dir: data/tcir
|
| 19 |
+
frame_cache: artifacts/frame_cache
|
| 20 |
+
# Extracted Cropped_cyclone_data directory. This file does not download it.
|
| 21 |
+
incyde_root: data/incyde
|
| 22 |
+
# Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.
|
| 23 |
+
run_id: null
|
| 24 |
+
hf_model_repo: null
|
| 25 |
+
data:
|
| 26 |
+
dataset: nasa
|
| 27 |
+
# null or native keeps each chip's height and width. NASA TorchGeo chips
|
| 28 |
+
# are 366x366 (Gurung et al. 2023). TCIR chips are 201x201. An integer
|
| 29 |
+
# resizes the deep model to that square. Classical features stay native.
|
| 30 |
+
image_size: native
|
| 31 |
+
channels: 1
|
| 32 |
+
normalize: zscore
|
| 33 |
+
max_missing_fraction: 0.30
|
| 34 |
+
plausible_wind_kt: [0, 200]
|
| 35 |
+
# NASA TropicalCyclone labels are HURDAT2 maximum sustained wind, a
|
| 36 |
+
# 1-minute average. Do not mix this with 10-minute winds.
|
| 37 |
+
wind_averaging: 1min
|
| 38 |
+
# Project bins for error tables. Not an IMD warning, and not the IMD
|
| 39 |
+
# 3-minute scale. IMD uses 3-minute winds. These edges are this project's
|
| 40 |
+
# own grouping: [17, 34) D_DD, [34, 48) CS, [48, 64) SCS, [64, 91) VSCS,
|
| 41 |
+
# and 91 kt and above ESCS_SUCS.
|
| 42 |
+
imd5_edges_kt: [17, 34, 48, 64, 91]
|
| 43 |
+
imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]
|
| 44 |
+
# International knot. Used only to display a second unit.
|
| 45 |
+
kt_to_kmh: 1.852
|
| 46 |
+
# letterbox pads to a square before the checkpoint resize. stretch is the old path.
|
| 47 |
+
resize: letterbox
|
| 48 |
+
pad: median
|
| 49 |
+
grouping_note: >
|
| 50 |
+
Intensity category is this project's grouping on the configured knot bins.
|
| 51 |
+
It is not an official IMD class.
|
| 52 |
+
labels:
|
| 53 |
+
# Training target for TCIR, NASA, and INCYDE. Raw knots stay on wind_speed_kt.
|
| 54 |
+
label_column: wind_kt_3min
|
| 55 |
+
# Derived at-sea factor, not a WMO constant. See docs/TRAINING.md.
|
| 56 |
+
wind_1min_to_3min: 0.93
|
| 57 |
+
# flag: still multiply near-land 1-minute rows and set conversion_exposure_flag.
|
| 58 |
+
# raw: leave those rows at the 1-minute label.
|
| 59 |
+
near_land_policy: flag
|
| 60 |
+
# The factor is for open water farther offshore than this, in kilometres.
|
| 61 |
+
open_water_km: 20
|
| 62 |
+
incyde:
|
| 63 |
+
# null uses incyde/audit/storm_split.csv and exclusions.csv.
|
| 64 |
+
manifest_csv: null
|
| 65 |
+
storm_split_csv: null
|
| 66 |
+
exclusions_csv: null
|
| 67 |
+
archive: null
|
| 68 |
+
drop_qc_flags: []
|
| 69 |
+
n_folds: 5
|
| 70 |
+
cv_val_fold: 0
|
| 71 |
+
cv_seed: 42
|
| 72 |
+
# Optional storm_id,fold file. When set, it replaces the seeded folds.
|
| 73 |
+
cv_folds_csv: null
|
| 74 |
+
# null uses incyde/audit/frame_flags.csv. Unknown cells stay unknown.
|
| 75 |
+
frame_flags_csv: null
|
| 76 |
+
# When true, also report validation metrics on explicit on_fix frames.
|
| 77 |
+
# The overall validation metrics stay the full validation split.
|
| 78 |
+
on_fix_only_eval: false
|
| 79 |
+
split:
|
| 80 |
+
strategy: storm_wise
|
| 81 |
+
test_fraction: 0.2
|
| 82 |
+
val_fraction: 0.2
|
| 83 |
+
holdout_years: []
|
| 84 |
+
holdout_basin: null
|
| 85 |
+
seed: 42
|
| 86 |
+
model:
|
| 87 |
+
name: simple_cnn
|
| 88 |
+
pretrained: false
|
| 89 |
+
dropout: 0.3
|
| 90 |
+
mc_samples: 20
|
| 91 |
+
# Used when model.name is convlstm. The sequence length stays 4.
|
| 92 |
+
n_frames: 4
|
| 93 |
+
hidden: 16
|
| 94 |
+
train:
|
| 95 |
+
batch_size: 16
|
| 96 |
+
epochs: 20
|
| 97 |
+
lr: 0.001
|
| 98 |
+
weight_decay: 0.0001
|
| 99 |
+
patience: 5
|
| 100 |
+
# auto picks xpu, then cuda, then cpu. XPU and CUDA need CLOUDIE_ALLOW_GPU=1.
|
| 101 |
+
device: auto
|
| 102 |
+
max_steps: null
|
| 103 |
+
grad_accum_steps: 1
|
| 104 |
+
num_workers: 2
|
| 105 |
+
# Fraction of max(1, CPU output magnitude). Leaves room for bf16 versus fp32.
|
| 106 |
+
device_parity_tol: 0.05
|
| 107 |
+
class_loss_weight: 0.1
|
| 108 |
+
# Applied only when r34_nmi and rmw_nmi exist on the train split.
|
| 109 |
+
size_loss_weight: 0.1
|
| 110 |
+
# none leaves Smooth L1 unweighted. The other modes reweight the five
|
| 111 |
+
# project bins on the 3-minute target, using train originals only.
|
| 112 |
+
loss_weighting: none
|
| 113 |
+
# Draw train rows with inverse-frequency weights so each occurring bin
|
| 114 |
+
# has the same expected count. Off by default.
|
| 115 |
+
balanced_sampling: false
|
| 116 |
+
predict:
|
| 117 |
+
# Review flag, not a warning threshold.
|
| 118 |
+
advisory_jump_kt: 20
|
| 119 |
+
operational_disclaimer: "This is not an operational forecast."
|
| 120 |
+
no_run_record_review: "no matching real-data run record"
|
| 121 |
+
no_run_record_refusal: >
|
| 122 |
+
This checkpoint has no matching real-data run record.
|
| 123 |
+
There is no model output. This is not a forecast.
|
| 124 |
+
held_out_refusal: >
|
| 125 |
+
This checkpoint's real-data run record has not passed the held-out
|
| 126 |
+
storm check. There is no model output. This is not a forecast.
|
| 127 |
+
landfall_note: "not a landfall forecast"
|
| 128 |
+
coast_reference_note: >
|
| 129 |
+
Reference points are approximate coastal coordinates, not a shoreline
|
| 130 |
+
survey and not a landfall forecast.
|
| 131 |
+
coastal_heading: "nearest Indian coastal states to the current position"
|
| 132 |
+
coastal_count: 3
|
| 133 |
+
earth_radius_km: 6371.0
|
| 134 |
+
latitude_keys: [latitude, lat]
|
| 135 |
+
longitude_keys: [longitude, lon]
|
| 136 |
+
# Image mean must sit within this many training standard deviations.
|
| 137 |
+
training_mean_width: 3
|
| 138 |
+
# Same storm, resized, should stay inside this knot span.
|
| 139 |
+
scale_tolerance_kt: 1.0
|
| 140 |
+
sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]
|
| 141 |
+
confidence:
|
| 142 |
+
uncalibrated_label: uncalibrated
|
| 143 |
+
coverage_label: "real-data coverage recorded"
|
| 144 |
+
gate_weight: 0.4
|
| 145 |
+
mc_weight: 0.4
|
| 146 |
+
interval_weight: 0.2
|
| 147 |
+
mc_std_scale_kt: 15
|
| 148 |
+
interval_scale_kt: 30
|
| 149 |
+
gate:
|
| 150 |
+
refusal: "not a tropical cyclone IR image"
|
| 151 |
+
grayscale_tolerance: 0.08
|
| 152 |
+
min_std: 0.02
|
| 153 |
+
min_symmetry: 0.45
|
| 154 |
+
min_cold_concentration: 0.36
|
| 155 |
+
cold_radius_fraction: 0.45
|
| 156 |
+
cold_tail_fraction: 0.25
|
| 157 |
+
eye_radius_fraction: 0.12
|
| 158 |
+
eyewall_outer_fraction: 0.32
|
| 159 |
+
outer_inner_fraction: 0.55
|
| 160 |
+
outer_outer_fraction: 0.95
|
| 161 |
+
min_wall_contrast: 0.45
|
| 162 |
+
radial_bins: 8
|
| 163 |
+
cold_value: auto
|
| 164 |
+
max_dropout_std_kt: 50
|
| 165 |
+
concentration_reference: 0.75
|
| 166 |
+
# Approximate public reference points, not Survey of India boundaries.
|
| 167 |
+
coast:
|
| 168 |
+
- {name: Gujarat, lat: 21.64, lon: 69.61}
|
| 169 |
+
- {name: Maharashtra, lat: 18.94, lon: 72.84}
|
| 170 |
+
- {name: Goa, lat: 15.49, lon: 73.83}
|
| 171 |
+
- {name: Karnataka, lat: 12.91, lon: 74.86}
|
| 172 |
+
- {name: Kerala, lat: 9.93, lon: 76.26}
|
| 173 |
+
- {name: Tamil Nadu, lat: 13.08, lon: 80.27}
|
| 174 |
+
- {name: Puducherry, lat: 11.94, lon: 79.83}
|
| 175 |
+
- {name: Andhra Pradesh, lat: 17.69, lon: 83.22}
|
| 176 |
+
- {name: Odisha, lat: 19.81, lon: 85.83}
|
| 177 |
+
- {name: West Bengal, lat: 21.63, lon: 87.51}
|
| 178 |
+
- {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}
|
| 179 |
+
- {name: Lakshadweep, lat: 10.57, lon: 72.64}
|
| 180 |
+
- {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}
|
| 181 |
+
forbidden_features:
|
| 182 |
+
- wind_speed_kt
|
| 183 |
+
- r34_nmi
|
| 184 |
+
- rmw_nmi
|
| 185 |
+
- imd5_class
|
| 186 |
+
- intensity_bin
|
| 187 |
+
features:
|
| 188 |
+
# Name distributional stats tb_* only when a calibration table was applied.
|
| 189 |
+
calibrated: false
|
| 190 |
+
cold_thresholds: [200, 210, 220, 230, 240]
|
| 191 |
+
radial_bins: 8
|
| 192 |
+
eye_radius_fraction: 0.12
|
| 193 |
+
cdo_outer_fraction: 0.35
|
| 194 |
+
eye_contrast_min: 2.0
|
| 195 |
+
dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]
|
| 196 |
+
dav_annulus_width_fraction: 0.08
|
| 197 |
+
glcm_levels: 16
|
| 198 |
+
glcm_distance: 1
|
| 199 |
+
selection:
|
| 200 |
+
correlation_threshold: 0.95
|
| 201 |
+
max_features: 25
|
| 202 |
+
method: correlation_rf
|
| 203 |
+
n_estimators: 80
|
| 204 |
+
seed: 42
|
| 205 |
+
baselines:
|
| 206 |
+
n_splits: 3
|
| 207 |
+
seed: 42
|
| 208 |
+
# Validation per-class intervals. Each resample draws storms with replacement.
|
| 209 |
+
# The generator seed is baselines.seed. Rows are not resampled.
|
| 210 |
+
bootstrap_resamples: 1000
|
| 211 |
+
# List each storm inside a class that has fewer than 3 storms.
|
| 212 |
+
per_storm_breakdown: true
|
| 213 |
+
regression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]
|
| 214 |
+
classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]
|
| 215 |
+
use_smote: true
|
| 216 |
+
ridge_alpha: 1.0
|
| 217 |
+
knn_neighbors: 5
|
| 218 |
+
svr_c: 1.0
|
| 219 |
+
svc_c: 1.0
|
| 220 |
+
rf_estimators: 200
|
| 221 |
+
rf_max_depth: 6
|
| 222 |
+
xgb_estimators: 80
|
| 223 |
+
xgb_max_depth: 3
|
| 224 |
+
xgb_learning_rate: 0.1
|
| 225 |
+
max_iter: 1000
|
| 226 |
+
# Grouped CV. train folds the training storms only. train_val folds
|
| 227 |
+
# train and val together and never includes test. The group column stays
|
| 228 |
+
# intact inside a fold. cv_collapse_rare remaps a stratify label that
|
| 229 |
+
# sits in fewer groups than n_splits, for fold assignment only.
|
| 230 |
+
cv_pool: train
|
| 231 |
+
cv_group_column: storm_id
|
| 232 |
+
cv_collapse_rare: false
|
| 233 |
+
cv_assign: stratified
|
bundle/config/config_incyde.yaml
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
project:
|
| 2 |
+
name: cyclone-intensity-estimation
|
| 3 |
+
seed: 42
|
| 4 |
+
honesty: >
|
| 5 |
+
No trained weights are shipped. Smoke images are synthetic.
|
| 6 |
+
This is not an operational forecast or warning system.
|
| 7 |
+
Best-track labels are noisy, and agreement with them is not ground truth.
|
| 8 |
+
No survey or smoke number is a result of this project.
|
| 9 |
+
paths:
|
| 10 |
+
manifest: data/incyde/manifest.csv
|
| 11 |
+
artifacts: artifacts
|
| 12 |
+
reports: reports
|
| 13 |
+
checkpoint_name: checkpoint.pt
|
| 14 |
+
run_records: artifacts/run_records
|
| 15 |
+
runs: artifacts/runs
|
| 16 |
+
nasa_root: data/nasa_tc
|
| 17 |
+
tcir_files: []
|
| 18 |
+
tcir_manifest_dir: data/tcir
|
| 19 |
+
frame_cache: artifacts/frame_cache
|
| 20 |
+
# Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.
|
| 21 |
+
run_id: null
|
| 22 |
+
hf_model_repo: null
|
| 23 |
+
data:
|
| 24 |
+
dataset: incyde
|
| 25 |
+
# null or native keeps each chip's height and width. NASA TorchGeo chips
|
| 26 |
+
# are 366x366 (Gurung et al. 2023). TCIR chips are 201x201. An integer
|
| 27 |
+
# resizes the deep model to that square. Classical features stay native.
|
| 28 |
+
image_size: native
|
| 29 |
+
channels: 1
|
| 30 |
+
normalize: zscore
|
| 31 |
+
max_missing_fraction: 0.30
|
| 32 |
+
plausible_wind_kt: [0, 200]
|
| 33 |
+
# Raw IMD 3-minute sustained winds from the INCYDE labels CSV.
|
| 34 |
+
# Do not convert them to 1-minute. wind_averaging_s is 180 on every row.
|
| 35 |
+
wind_averaging: 3-min
|
| 36 |
+
# Project bins for error tables. Not an IMD warning, and not the IMD
|
| 37 |
+
# 3-minute scale. IMD uses 3-minute winds. These edges are this project's
|
| 38 |
+
# own grouping: [17, 34) D_DD, [34, 48) CS, [48, 64) SCS, [64, 91) VSCS,
|
| 39 |
+
# and 91 kt and above ESCS_SUCS.
|
| 40 |
+
imd5_edges_kt: [17, 34, 48, 64, 91]
|
| 41 |
+
imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]
|
| 42 |
+
# International knot. Used only to display a second unit.
|
| 43 |
+
kt_to_kmh: 1.852
|
| 44 |
+
# letterbox pads to a square before the checkpoint resize. stretch is the old path.
|
| 45 |
+
resize: letterbox
|
| 46 |
+
pad: median
|
| 47 |
+
grouping_note: >
|
| 48 |
+
Intensity category is this project's grouping on the configured knot bins.
|
| 49 |
+
It is not an official IMD class.
|
| 50 |
+
split:
|
| 51 |
+
strategy: recorded
|
| 52 |
+
test_fraction: 0.2
|
| 53 |
+
val_fraction: 0.2
|
| 54 |
+
holdout_years: []
|
| 55 |
+
holdout_basin: null
|
| 56 |
+
seed: 42
|
| 57 |
+
model:
|
| 58 |
+
name: simple_cnn
|
| 59 |
+
pretrained: false
|
| 60 |
+
dropout: 0.3
|
| 61 |
+
mc_samples: 20
|
| 62 |
+
# Used when model.name is convlstm. The sequence length stays 4.
|
| 63 |
+
n_frames: 4
|
| 64 |
+
hidden: 16
|
| 65 |
+
train:
|
| 66 |
+
batch_size: 16
|
| 67 |
+
epochs: 20
|
| 68 |
+
lr: 0.001
|
| 69 |
+
weight_decay: 0.0001
|
| 70 |
+
patience: 5
|
| 71 |
+
# auto picks xpu, then cuda, then cpu. XPU and CUDA need CLOUDIE_ALLOW_GPU=1.
|
| 72 |
+
device: auto
|
| 73 |
+
max_steps: null
|
| 74 |
+
grad_accum_steps: 1
|
| 75 |
+
num_workers: 2
|
| 76 |
+
# Fraction of max(1, CPU output magnitude). Leaves room for bf16 versus fp32.
|
| 77 |
+
device_parity_tol: 0.05
|
| 78 |
+
class_loss_weight: 0.1
|
| 79 |
+
# Applied only when r34_nmi and rmw_nmi exist on the train split.
|
| 80 |
+
size_loss_weight: 0.1
|
| 81 |
+
predict:
|
| 82 |
+
# Review flag, not a warning threshold.
|
| 83 |
+
advisory_jump_kt: 20
|
| 84 |
+
operational_disclaimer: "This is not an operational forecast."
|
| 85 |
+
no_run_record_review: "no matching real-data run record"
|
| 86 |
+
no_run_record_refusal: >
|
| 87 |
+
This checkpoint has no matching real-data run record.
|
| 88 |
+
There is no model output. This is not a forecast.
|
| 89 |
+
held_out_refusal: >
|
| 90 |
+
This checkpoint's real-data run record has not passed the held-out
|
| 91 |
+
storm check. There is no model output. This is not a forecast.
|
| 92 |
+
landfall_note: "not a landfall forecast"
|
| 93 |
+
coast_reference_note: >
|
| 94 |
+
Reference points are approximate coastal coordinates, not a shoreline
|
| 95 |
+
survey and not a landfall forecast.
|
| 96 |
+
coastal_heading: "nearest Indian coastal states to the current position"
|
| 97 |
+
coastal_count: 3
|
| 98 |
+
earth_radius_km: 6371.0
|
| 99 |
+
latitude_keys: [latitude, lat]
|
| 100 |
+
longitude_keys: [longitude, lon]
|
| 101 |
+
# Image mean must sit within this many training standard deviations.
|
| 102 |
+
training_mean_width: 3
|
| 103 |
+
# Same storm, resized, should stay inside this knot span.
|
| 104 |
+
scale_tolerance_kt: 1.0
|
| 105 |
+
sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]
|
| 106 |
+
confidence:
|
| 107 |
+
uncalibrated_label: uncalibrated
|
| 108 |
+
coverage_label: "real-data coverage recorded"
|
| 109 |
+
gate_weight: 0.4
|
| 110 |
+
mc_weight: 0.4
|
| 111 |
+
interval_weight: 0.2
|
| 112 |
+
mc_std_scale_kt: 15
|
| 113 |
+
interval_scale_kt: 30
|
| 114 |
+
gate:
|
| 115 |
+
refusal: "not a tropical cyclone IR image"
|
| 116 |
+
grayscale_tolerance: 0.08
|
| 117 |
+
min_std: 0.02
|
| 118 |
+
min_symmetry: 0.45
|
| 119 |
+
min_cold_concentration: 0.36
|
| 120 |
+
cold_radius_fraction: 0.45
|
| 121 |
+
cold_tail_fraction: 0.25
|
| 122 |
+
eye_radius_fraction: 0.12
|
| 123 |
+
eyewall_outer_fraction: 0.32
|
| 124 |
+
outer_inner_fraction: 0.55
|
| 125 |
+
outer_outer_fraction: 0.95
|
| 126 |
+
min_wall_contrast: 0.45
|
| 127 |
+
radial_bins: 8
|
| 128 |
+
cold_value: auto
|
| 129 |
+
max_dropout_std_kt: 50
|
| 130 |
+
concentration_reference: 0.75
|
| 131 |
+
# Approximate public reference points, not Survey of India boundaries.
|
| 132 |
+
coast:
|
| 133 |
+
- {name: Gujarat, lat: 21.64, lon: 69.61}
|
| 134 |
+
- {name: Maharashtra, lat: 18.94, lon: 72.84}
|
| 135 |
+
- {name: Goa, lat: 15.49, lon: 73.83}
|
| 136 |
+
- {name: Karnataka, lat: 12.91, lon: 74.86}
|
| 137 |
+
- {name: Kerala, lat: 9.93, lon: 76.26}
|
| 138 |
+
- {name: Tamil Nadu, lat: 13.08, lon: 80.27}
|
| 139 |
+
- {name: Puducherry, lat: 11.94, lon: 79.83}
|
| 140 |
+
- {name: Andhra Pradesh, lat: 17.69, lon: 83.22}
|
| 141 |
+
- {name: Odisha, lat: 19.81, lon: 85.83}
|
| 142 |
+
- {name: West Bengal, lat: 21.63, lon: 87.51}
|
| 143 |
+
- {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}
|
| 144 |
+
- {name: Lakshadweep, lat: 10.57, lon: 72.64}
|
| 145 |
+
- {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}
|
| 146 |
+
forbidden_features:
|
| 147 |
+
- wind_speed_kt
|
| 148 |
+
- r34_nmi
|
| 149 |
+
- rmw_nmi
|
| 150 |
+
- imd5_class
|
| 151 |
+
- intensity_bin
|
| 152 |
+
features:
|
| 153 |
+
# Name distributional stats tb_* only when a calibration table was applied.
|
| 154 |
+
calibrated: false
|
| 155 |
+
cold_thresholds: [200, 210, 220, 230, 240]
|
| 156 |
+
radial_bins: 8
|
| 157 |
+
eye_radius_fraction: 0.12
|
| 158 |
+
cdo_outer_fraction: 0.35
|
| 159 |
+
eye_contrast_min: 2.0
|
| 160 |
+
dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]
|
| 161 |
+
dav_annulus_width_fraction: 0.08
|
| 162 |
+
glcm_levels: 16
|
| 163 |
+
glcm_distance: 1
|
| 164 |
+
selection:
|
| 165 |
+
correlation_threshold: 0.95
|
| 166 |
+
max_features: 25
|
| 167 |
+
method: correlation_rf
|
| 168 |
+
n_estimators: 80
|
| 169 |
+
seed: 42
|
| 170 |
+
baselines:
|
| 171 |
+
# Five folds, seed 42, groups dealt round-robin. The file
|
| 172 |
+
# results/incyde_baselines/cv_folds.csv is storm_id,fold for train+val
|
| 173 |
+
# only, and each cooccurrence_group stays in one fold.
|
| 174 |
+
n_splits: 5
|
| 175 |
+
seed: 42
|
| 176 |
+
# Validation per-class intervals. Each resample draws storms with replacement.
|
| 177 |
+
# The generator seed is baselines.seed. Rows are not resampled.
|
| 178 |
+
bootstrap_resamples: 1000
|
| 179 |
+
# List each storm inside a class that has fewer than 3 storms.
|
| 180 |
+
per_storm_breakdown: true
|
| 181 |
+
regression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]
|
| 182 |
+
classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]
|
| 183 |
+
use_smote: true
|
| 184 |
+
ridge_alpha: 1.0
|
| 185 |
+
knn_neighbors: 5
|
| 186 |
+
svr_c: 1.0
|
| 187 |
+
svc_c: 1.0
|
| 188 |
+
rf_estimators: 200
|
| 189 |
+
rf_max_depth: 6
|
| 190 |
+
xgb_estimators: 80
|
| 191 |
+
xgb_max_depth: 3
|
| 192 |
+
xgb_learning_rate: 0.1
|
| 193 |
+
max_iter: 1000
|
| 194 |
+
# Grouped CV. train folds the training storms only. train_val folds
|
| 195 |
+
# train and val together and never includes test. The group column stays
|
| 196 |
+
# intact inside a fold. cv_collapse_rare remaps a stratify label that
|
| 197 |
+
# sits in fewer groups than n_splits, for fold assignment only.
|
| 198 |
+
cv_pool: train_val
|
| 199 |
+
cv_group_column: cv_group
|
| 200 |
+
cv_collapse_rare: false
|
| 201 |
+
cv_assign: round_robin
|
bundle/config/config_smoke.yaml
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
project:
|
| 2 |
+
name: cyclone-intensity-estimation-smoke
|
| 3 |
+
seed: 7
|
| 4 |
+
honesty: >
|
| 5 |
+
Smoke images are synthetic. Metrics from this config are a software
|
| 6 |
+
check, not a scientific result and not a forecast.
|
| 7 |
+
paths:
|
| 8 |
+
manifest: data/smoke/manifest.csv
|
| 9 |
+
artifacts: artifacts/smoke
|
| 10 |
+
reports: reports/smoke
|
| 11 |
+
checkpoint_name: checkpoint.pt
|
| 12 |
+
run_records: artifacts/run_records
|
| 13 |
+
runs: artifacts/runs
|
| 14 |
+
nasa_root: data/nasa_tc
|
| 15 |
+
tcir_files: []
|
| 16 |
+
tcir_manifest_dir: data/tcir
|
| 17 |
+
frame_cache: artifacts/frame_cache
|
| 18 |
+
incyde_root: data/incyde
|
| 19 |
+
# Empty until a real run is published. CLOUDIE_RUN_ID and CLOUDIE_HF_MODEL_REPO override these.
|
| 20 |
+
run_id: null
|
| 21 |
+
hf_model_repo: null
|
| 22 |
+
data:
|
| 23 |
+
dataset: smoke
|
| 24 |
+
# Small square so the software check stays fast. The NASA config uses native.
|
| 25 |
+
image_size: 64
|
| 26 |
+
channels: 1
|
| 27 |
+
normalize: zscore
|
| 28 |
+
max_missing_fraction: 0.30
|
| 29 |
+
plausible_wind_kt: [0, 200]
|
| 30 |
+
# Smoke labels are synthetic. They are not HURDAT2 1-minute winds.
|
| 31 |
+
wind_averaging: synthetic
|
| 32 |
+
# Same project bins as config.yaml. IMD itself uses 3-minute winds.
|
| 33 |
+
# 17/34/48/64/91 kt is this project's grouping, not that IMD scale.
|
| 34 |
+
imd5_edges_kt: [17, 34, 48, 64, 91]
|
| 35 |
+
imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]
|
| 36 |
+
kt_to_kmh: 1.852
|
| 37 |
+
resize: letterbox
|
| 38 |
+
pad: median
|
| 39 |
+
grouping_note: >
|
| 40 |
+
Intensity category is this project's grouping on the configured knot bins.
|
| 41 |
+
It is not an official IMD class.
|
| 42 |
+
labels:
|
| 43 |
+
label_column: wind_kt_3min
|
| 44 |
+
wind_1min_to_3min: 0.93
|
| 45 |
+
near_land_policy: flag
|
| 46 |
+
open_water_km: 20
|
| 47 |
+
incyde:
|
| 48 |
+
manifest_csv: null
|
| 49 |
+
storm_split_csv: null
|
| 50 |
+
exclusions_csv: null
|
| 51 |
+
archive: null
|
| 52 |
+
drop_qc_flags: []
|
| 53 |
+
n_folds: 5
|
| 54 |
+
cv_val_fold: 0
|
| 55 |
+
cv_seed: 42
|
| 56 |
+
cv_folds_csv: null
|
| 57 |
+
frame_flags_csv: null
|
| 58 |
+
on_fix_only_eval: false
|
| 59 |
+
split:
|
| 60 |
+
strategy: storm_wise
|
| 61 |
+
test_fraction: 0.2
|
| 62 |
+
val_fraction: 0.2
|
| 63 |
+
holdout_years: [2021]
|
| 64 |
+
holdout_basin: NIO
|
| 65 |
+
seed: 7
|
| 66 |
+
model:
|
| 67 |
+
name: simple_cnn
|
| 68 |
+
pretrained: false
|
| 69 |
+
dropout: 0.3
|
| 70 |
+
mc_samples: 20
|
| 71 |
+
n_frames: 4
|
| 72 |
+
hidden: 8
|
| 73 |
+
train:
|
| 74 |
+
batch_size: 8
|
| 75 |
+
epochs: 2
|
| 76 |
+
lr: 0.001
|
| 77 |
+
weight_decay: 0.0001
|
| 78 |
+
patience: 1
|
| 79 |
+
device: auto
|
| 80 |
+
max_steps: null
|
| 81 |
+
grad_accum_steps: 1
|
| 82 |
+
num_workers: 2
|
| 83 |
+
device_parity_tol: 0.05
|
| 84 |
+
class_loss_weight: 0.1
|
| 85 |
+
size_loss_weight: 0.1
|
| 86 |
+
loss_weighting: none
|
| 87 |
+
balanced_sampling: false
|
| 88 |
+
predict:
|
| 89 |
+
advisory_jump_kt: 20
|
| 90 |
+
operational_disclaimer: "This is not an operational forecast."
|
| 91 |
+
no_run_record_review: "no matching real-data run record"
|
| 92 |
+
no_run_record_refusal: >
|
| 93 |
+
This checkpoint has no matching real-data run record.
|
| 94 |
+
There is no model output. This is not a forecast.
|
| 95 |
+
held_out_refusal: >
|
| 96 |
+
This checkpoint's real-data run record has not passed the held-out
|
| 97 |
+
storm check. There is no model output. This is not a forecast.
|
| 98 |
+
landfall_note: "not a landfall forecast"
|
| 99 |
+
coast_reference_note: >
|
| 100 |
+
Reference points are approximate coastal coordinates, not a shoreline
|
| 101 |
+
survey and not a landfall forecast.
|
| 102 |
+
coastal_heading: "nearest Indian coastal states to the current position"
|
| 103 |
+
coastal_count: 3
|
| 104 |
+
earth_radius_km: 6371.0
|
| 105 |
+
latitude_keys: [latitude, lat]
|
| 106 |
+
longitude_keys: [longitude, lon]
|
| 107 |
+
training_mean_width: 3
|
| 108 |
+
scale_tolerance_kt: 1.0
|
| 109 |
+
sklearn_features: [symmetry, cold_concentration, wall_contrast, eye_contrast]
|
| 110 |
+
confidence:
|
| 111 |
+
uncalibrated_label: uncalibrated
|
| 112 |
+
coverage_label: "real-data coverage recorded"
|
| 113 |
+
gate_weight: 0.4
|
| 114 |
+
mc_weight: 0.4
|
| 115 |
+
interval_weight: 0.2
|
| 116 |
+
mc_std_scale_kt: 15
|
| 117 |
+
interval_scale_kt: 30
|
| 118 |
+
gate:
|
| 119 |
+
refusal: "not a tropical cyclone IR image"
|
| 120 |
+
grayscale_tolerance: 0.08
|
| 121 |
+
min_std: 0.02
|
| 122 |
+
min_symmetry: 0.45
|
| 123 |
+
min_cold_concentration: 0.36
|
| 124 |
+
cold_radius_fraction: 0.45
|
| 125 |
+
cold_tail_fraction: 0.25
|
| 126 |
+
eye_radius_fraction: 0.12
|
| 127 |
+
eyewall_outer_fraction: 0.32
|
| 128 |
+
outer_inner_fraction: 0.55
|
| 129 |
+
outer_outer_fraction: 0.95
|
| 130 |
+
min_wall_contrast: 0.45
|
| 131 |
+
radial_bins: 8
|
| 132 |
+
cold_value: auto
|
| 133 |
+
max_dropout_std_kt: 50
|
| 134 |
+
concentration_reference: 0.75
|
| 135 |
+
coast:
|
| 136 |
+
- {name: Gujarat, lat: 21.64, lon: 69.61}
|
| 137 |
+
- {name: Maharashtra, lat: 18.94, lon: 72.84}
|
| 138 |
+
- {name: Goa, lat: 15.49, lon: 73.83}
|
| 139 |
+
- {name: Karnataka, lat: 12.91, lon: 74.86}
|
| 140 |
+
- {name: Kerala, lat: 9.93, lon: 76.26}
|
| 141 |
+
- {name: Tamil Nadu, lat: 13.08, lon: 80.27}
|
| 142 |
+
- {name: Puducherry, lat: 11.94, lon: 79.83}
|
| 143 |
+
- {name: Andhra Pradesh, lat: 17.69, lon: 83.22}
|
| 144 |
+
- {name: Odisha, lat: 19.81, lon: 85.83}
|
| 145 |
+
- {name: West Bengal, lat: 21.63, lon: 87.51}
|
| 146 |
+
- {name: Andaman and Nicobar Islands, lat: 11.67, lon: 92.74}
|
| 147 |
+
- {name: Lakshadweep, lat: 10.57, lon: 72.64}
|
| 148 |
+
- {name: Dadra and Nagar Haveli and Daman and Diu, lat: 20.42, lon: 72.83}
|
| 149 |
+
features:
|
| 150 |
+
calibrated: false
|
| 151 |
+
cold_thresholds: [200, 210, 220, 230, 240]
|
| 152 |
+
radial_bins: 8
|
| 153 |
+
eye_radius_fraction: 0.12
|
| 154 |
+
cdo_outer_fraction: 0.35
|
| 155 |
+
eye_contrast_min: 2.0
|
| 156 |
+
dav_radii_fractions: [0.15, 0.30, 0.45, 0.60]
|
| 157 |
+
dav_annulus_width_fraction: 0.08
|
| 158 |
+
glcm_levels: 16
|
| 159 |
+
glcm_distance: 1
|
| 160 |
+
selection:
|
| 161 |
+
correlation_threshold: 0.95
|
| 162 |
+
max_features: 25
|
| 163 |
+
method: correlation_rf
|
| 164 |
+
n_estimators: 20
|
| 165 |
+
seed: 7
|
| 166 |
+
baselines:
|
| 167 |
+
n_splits: 2
|
| 168 |
+
seed: 7
|
| 169 |
+
# Validation per-class intervals. Each resample draws storms with replacement.
|
| 170 |
+
# The generator seed is baselines.seed. Rows are not resampled.
|
| 171 |
+
bootstrap_resamples: 1000
|
| 172 |
+
# List each storm inside a class that has fewer than 3 storms.
|
| 173 |
+
per_storm_breakdown: true
|
| 174 |
+
regression_models: [mean, persistence, ridge, lr, knn, rf, xgboost, svr]
|
| 175 |
+
classification_models: [mean, persistence, logreg, knn, rf, xgboost, svc]
|
| 176 |
+
use_smote: true
|
| 177 |
+
ridge_alpha: 1.0
|
| 178 |
+
knn_neighbors: 3
|
| 179 |
+
svr_c: 1.0
|
| 180 |
+
svc_c: 1.0
|
| 181 |
+
rf_estimators: 20
|
| 182 |
+
rf_max_depth: 4
|
| 183 |
+
xgb_estimators: 20
|
| 184 |
+
xgb_max_depth: 3
|
| 185 |
+
xgb_learning_rate: 0.1
|
| 186 |
+
max_iter: 400
|
| 187 |
+
cv_pool: train
|
| 188 |
+
cv_group_column: storm_id
|
| 189 |
+
cv_collapse_rare: false
|
| 190 |
+
cv_assign: stratified
|
| 191 |
+
forbidden_features:
|
| 192 |
+
- wind_speed_kt
|
| 193 |
+
- r34_nmi
|
| 194 |
+
- rmw_nmi
|
| 195 |
+
- imd5_class
|
| 196 |
+
- intensity_bin
|
bundle/config/incyde_cpu.yaml
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# INCYDE CPU model v0.1 (SimpleCNN). Used by scripts/incyde_cpu/*.
|
| 2 |
+
# Device-neutral: device auto picks xpu, then cuda, then cpu (GPU needs CLOUDIE_ALLOW_GPU=1).
|
| 3 |
+
project:
|
| 4 |
+
seed: 42
|
| 5 |
+
labels:
|
| 6 |
+
# Standard: IMD 3-minute sustained wind. INCYDE labels are used unchanged.
|
| 7 |
+
# 1-minute sources (TCIR, NASA) are converted with ONE factor:
|
| 8 |
+
# 0.93, derived from WMO/TD-1555 Tables 1.1 and 1.2, at-sea exposure
|
| 9 |
+
# (Harper, Kepert & Ginger 2010). Derived, NOT a WMO constant.
|
| 10 |
+
# Pending Researchy's verification.
|
| 11 |
+
one_to_three_min_factor: 0.93
|
| 12 |
+
one_to_three_min_factor_status: derived_pending_verification
|
| 13 |
+
# Rows whose centre is within this distance of land are flagged (near_land).
|
| 14 |
+
near_land_km: 20
|
| 15 |
+
# false: near-land TCIR rows are left out of pretraining instead of converted.
|
| 16 |
+
pretrain_keep_near_land: false
|
| 17 |
+
data:
|
| 18 |
+
image_size: 96
|
| 19 |
+
# Main's project bins (src/schema.py). Not official IMD classes.
|
| 20 |
+
imd5_edges_kt: [17, 34, 48, 64, 91]
|
| 21 |
+
imd5_names: [D_DD, CS, SCS, VSCS, ESCS_SUCS]
|
| 22 |
+
model:
|
| 23 |
+
name: simple_cnn
|
| 24 |
+
dropout: 0.3
|
| 25 |
+
channels: 1
|
| 26 |
+
train:
|
| 27 |
+
device: auto
|
| 28 |
+
batch_size: 64
|
| 29 |
+
epochs: 30
|
| 30 |
+
lr: 0.001
|
| 31 |
+
weight_decay: 0.0001
|
| 32 |
+
patience: 6
|
| 33 |
+
class_loss_weight: 0.5
|
| 34 |
+
num_workers: 0
|
| 35 |
+
cv:
|
| 36 |
+
n_folds: 5
|
| 37 |
+
seed: 42
|
| 38 |
+
augment:
|
| 39 |
+
rot_180: true
|
| 40 |
+
masked_rotation: true
|
| 41 |
+
flips: false
|
bundle/requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 2 |
+
torch==2.9.1+cpu
|
| 3 |
+
torchvision==0.24.1+cpu
|
| 4 |
+
numpy>=1.24
|
| 5 |
+
pandas>=2.0
|
| 6 |
+
pyyaml>=6.0
|
| 7 |
+
pillow>=10.0
|
| 8 |
+
scikit-learn>=1.3
|
bundle/src/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tropical cyclone intensity estimation framework.
|
| 2 |
+
|
| 3 |
+
No trained weights are shipped. This is not a warning system.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
__version__ = "0.2.0"
|
bundle/src/baselines.py
ADDED
|
@@ -0,0 +1,1854 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Classical intensity baselines on storm-grouped, train-selected features.
|
| 2 |
+
|
| 3 |
+
``run_from_config`` assigns storms with ``src.splits.assign_storms`` when
|
| 4 |
+
``split.strategy`` is ``storm_wise``. ``recorded`` keeps the ``split`` column
|
| 5 |
+
already on the manifest and does not redraw it. An official competition side
|
| 6 |
+
stays in ``source_split`` and is never the modeling split. Models are fit on
|
| 7 |
+
train storms and scored on val storms. The test split is never passed to a
|
| 8 |
+
headline fit and is never scored.
|
| 9 |
+
|
| 10 |
+
Learned models are sklearn ``Pipeline`` objects. Inner ``StratifiedGroupKFold``
|
| 11 |
+
is a comparison diagnostic. The default pool is the training storms and the
|
| 12 |
+
default group is ``storm_id``. ``baselines.cv_pool: train_val`` uses train and
|
| 13 |
+
val together, still excluding test, and ``baselines.cv_group_column`` names
|
| 14 |
+
the group that must stay inside one fold. It is not a license to tune on the
|
| 15 |
+
locked test storms.
|
| 16 |
+
|
| 17 |
+
SMOTE, when enabled, resamples the current training fold and never the
|
| 18 |
+
validation rows. Otherwise those classifiers use class weights inside the
|
| 19 |
+
fold. Regression does not use SMOTE. Persistence is a reference baseline:
|
| 20 |
+
the previous frame's best-track label, not the imagery. It is not a feature
|
| 21 |
+
and it is not fit. Image-only models cannot be compared against it.
|
| 22 |
+
ADT, SATCON, and Dvorak columns
|
| 23 |
+
are left empty until those products are actually joined.
|
| 24 |
+
|
| 25 |
+
Regression scores also write ``per_class_metrics.csv`` on the validation
|
| 26 |
+
split only. Intervals resample storm IDs. A ``wind_averaging`` column is
|
| 27 |
+
grouped when present. An ``on_fix`` column adds the rows on a best-track
|
| 28 |
+
fix. The test split is not scored in that table.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
from __future__ import annotations
|
| 32 |
+
|
| 33 |
+
import argparse
|
| 34 |
+
import hashlib
|
| 35 |
+
import json
|
| 36 |
+
import logging
|
| 37 |
+
import shlex
|
| 38 |
+
import subprocess
|
| 39 |
+
import sys
|
| 40 |
+
from dataclasses import dataclass
|
| 41 |
+
from pathlib import Path
|
| 42 |
+
|
| 43 |
+
import numpy as np
|
| 44 |
+
import pandas as pd
|
| 45 |
+
from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
|
| 46 |
+
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
|
| 47 |
+
from sklearn.impute import SimpleImputer
|
| 48 |
+
from sklearn.linear_model import LinearRegression, LogisticRegression, Ridge
|
| 49 |
+
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
|
| 50 |
+
from sklearn.pipeline import Pipeline
|
| 51 |
+
from sklearn.preprocessing import LabelEncoder, StandardScaler
|
| 52 |
+
from sklearn.svm import SVC, SVR
|
| 53 |
+
|
| 54 |
+
from src.config import load_config
|
| 55 |
+
from src.data_loader import load_manifest
|
| 56 |
+
from src.features import FeatureSpec, extract_feature_table, model_matrix, select_features
|
| 57 |
+
from src.metrics import classification_metrics, metrics_by_class, regression_metrics
|
| 58 |
+
from src.plots import save_confusion_matrix, save_feature_importance, save_regression_scatter
|
| 59 |
+
from src.schema import DEFAULT_NAMES, FORBIDDEN_FEATURES, parse_is_synthetic, wind_to_imd5
|
| 60 |
+
from src.splits import (
|
| 61 |
+
LeakageError,
|
| 62 |
+
assert_no_forbidden_inputs,
|
| 63 |
+
assert_no_group_leakage,
|
| 64 |
+
assign_storms,
|
| 65 |
+
observation_order,
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
logger = logging.getLogger(__name__)
|
| 69 |
+
|
| 70 |
+
BANNER = (
|
| 71 |
+
"Software check only. Do not quote these numbers as experimental results. "
|
| 72 |
+
"Operational baselines (ADT, SATCON, Dvorak) are not joined. "
|
| 73 |
+
"The locked test split was not used for fitting, selection, or SMOTE. "
|
| 74 |
+
"This is not a forecast or a warning."
|
| 75 |
+
)
|
| 76 |
+
PERSISTENCE_NOTE = (
|
| 77 |
+
"Persistence is a reference baseline. It uses the previous frame's "
|
| 78 |
+
"best-track label, not the imagery. Image-only models cannot be compared against it."
|
| 79 |
+
)
|
| 80 |
+
REFERENCE_ROLE = "reference_baseline"
|
| 81 |
+
IMAGE_ROLE = "image_features"
|
| 82 |
+
OPERATIONAL_COLUMNS = ("adt_mae_kt", "satcon_mae_kt", "dvorak_mae_kt")
|
| 83 |
+
COMPARISON_COLUMNS = (
|
| 84 |
+
"task",
|
| 85 |
+
"model",
|
| 86 |
+
"role",
|
| 87 |
+
"split_protocol",
|
| 88 |
+
"inner_cv",
|
| 89 |
+
"n_train_rows",
|
| 90 |
+
"n_val_rows",
|
| 91 |
+
"n_train_storms",
|
| 92 |
+
"n_val_storms",
|
| 93 |
+
"n_features",
|
| 94 |
+
"mae_kt",
|
| 95 |
+
"rmse_kt",
|
| 96 |
+
"bias_kt",
|
| 97 |
+
"cv_mae_kt_mean",
|
| 98 |
+
"cv_mae_kt_std",
|
| 99 |
+
*[f"mae_{name}" for name in DEFAULT_NAMES],
|
| 100 |
+
"macro_f1",
|
| 101 |
+
"cv_macro_f1_mean",
|
| 102 |
+
"cv_macro_f1_std",
|
| 103 |
+
*[f"recall_{name}" for name in DEFAULT_NAMES],
|
| 104 |
+
*OPERATIONAL_COLUMNS,
|
| 105 |
+
"fit_notes",
|
| 106 |
+
"quote_as_result",
|
| 107 |
+
"synthetic",
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class BaselineDataError(ValueError):
|
| 112 |
+
"""The frame cannot support a leak-free baseline comparison."""
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class MeanRegressor(BaseEstimator, RegressorMixin):
|
| 116 |
+
"""Predict the mean of the labels it was fit on."""
|
| 117 |
+
|
| 118 |
+
def fit(self, X, y):
|
| 119 |
+
target = np.asarray(y, dtype=np.float64).ravel()
|
| 120 |
+
self.mean_ = float(np.mean(target))
|
| 121 |
+
self.n_features_in_ = int(np.asarray(X).shape[1])
|
| 122 |
+
return self
|
| 123 |
+
|
| 124 |
+
def predict(self, X):
|
| 125 |
+
return np.full(np.asarray(X).shape[0], self.mean_, dtype=np.float64)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class MostFrequentClassifier(BaseEstimator, ClassifierMixin):
|
| 129 |
+
"""Predict the most common training class. Ties take the sorted label."""
|
| 130 |
+
|
| 131 |
+
def fit(self, X, y):
|
| 132 |
+
labels, counts = np.unique(np.asarray(y).ravel(), return_counts=True)
|
| 133 |
+
self.classes_ = labels
|
| 134 |
+
self.constant_ = labels[int(np.argmax(counts))]
|
| 135 |
+
self.n_features_in_ = int(np.asarray(X).shape[1])
|
| 136 |
+
return self
|
| 137 |
+
|
| 138 |
+
def predict(self, X):
|
| 139 |
+
return np.full(np.asarray(X).shape[0], self.constant_)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
_MAJORITY_CLASSIFIERS = frozenset({"most_frequent", "mean"})
|
| 143 |
+
PER_CLASS_COLUMNS = (
|
| 144 |
+
"task",
|
| 145 |
+
"model",
|
| 146 |
+
"split",
|
| 147 |
+
"subset",
|
| 148 |
+
"wind_averaging",
|
| 149 |
+
"row_kind",
|
| 150 |
+
"intensity_class",
|
| 151 |
+
"storm_id",
|
| 152 |
+
"n_rows",
|
| 153 |
+
"n_storms",
|
| 154 |
+
"rmse_kt",
|
| 155 |
+
"mae_kt",
|
| 156 |
+
"bias_kt",
|
| 157 |
+
"rmse_kt_ci_low",
|
| 158 |
+
"rmse_kt_ci_high",
|
| 159 |
+
"mae_kt_ci_low",
|
| 160 |
+
"mae_kt_ci_high",
|
| 161 |
+
"bias_kt_ci_low",
|
| 162 |
+
"bias_kt_ci_high",
|
| 163 |
+
"ci_level",
|
| 164 |
+
"n_resamples",
|
| 165 |
+
"seed",
|
| 166 |
+
"resample",
|
| 167 |
+
"status",
|
| 168 |
+
"quote_as_result",
|
| 169 |
+
"synthetic",
|
| 170 |
+
)
|
| 171 |
+
_PER_CLASS_MD_COLUMNS = (
|
| 172 |
+
"model",
|
| 173 |
+
"subset",
|
| 174 |
+
"wind_averaging",
|
| 175 |
+
"row_kind",
|
| 176 |
+
"intensity_class",
|
| 177 |
+
"storm_id",
|
| 178 |
+
"n_rows",
|
| 179 |
+
"n_storms",
|
| 180 |
+
"rmse_kt",
|
| 181 |
+
"rmse_kt_ci_low",
|
| 182 |
+
"rmse_kt_ci_high",
|
| 183 |
+
"mae_kt",
|
| 184 |
+
"mae_kt_ci_low",
|
| 185 |
+
"mae_kt_ci_high",
|
| 186 |
+
"bias_kt",
|
| 187 |
+
"bias_kt_ci_low",
|
| 188 |
+
"bias_kt_ci_high",
|
| 189 |
+
"status",
|
| 190 |
+
"quote_as_result",
|
| 191 |
+
)
|
| 192 |
+
_MARKDOWN_COLUMNS = (
|
| 193 |
+
"task",
|
| 194 |
+
"model",
|
| 195 |
+
"role",
|
| 196 |
+
"n_train_rows",
|
| 197 |
+
"n_val_rows",
|
| 198 |
+
"n_train_storms",
|
| 199 |
+
"n_val_storms",
|
| 200 |
+
"mae_kt",
|
| 201 |
+
"rmse_kt",
|
| 202 |
+
"bias_kt",
|
| 203 |
+
"macro_f1",
|
| 204 |
+
"fit_notes",
|
| 205 |
+
"quote_as_result",
|
| 206 |
+
"synthetic",
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def persistence_predictions(frame: pd.DataFrame) -> np.ndarray:
|
| 211 |
+
"""Previous ``wind_speed_kt`` inside the same storm.
|
| 212 |
+
|
| 213 |
+
Order is ``timestamp`` when that column exists, otherwise
|
| 214 |
+
``relative_time_s``, otherwise the given row order. The first row of
|
| 215 |
+
each storm is NaN. Wind from another storm is never used. This is a
|
| 216 |
+
baseline, not a model feature.
|
| 217 |
+
"""
|
| 218 |
+
if "storm_id" not in frame.columns or "wind_speed_kt" not in frame.columns:
|
| 219 |
+
raise ValueError("persistence needs storm_id and wind_speed_kt")
|
| 220 |
+
winds = pd.to_numeric(frame["wind_speed_kt"], errors="coerce").to_numpy(dtype=np.float64)
|
| 221 |
+
table = pd.DataFrame(
|
| 222 |
+
{
|
| 223 |
+
"storm_id": frame["storm_id"].astype(str).to_numpy(),
|
| 224 |
+
"wind": winds,
|
| 225 |
+
"order": observation_order(frame).to_numpy(),
|
| 226 |
+
"row": np.arange(len(frame)),
|
| 227 |
+
}
|
| 228 |
+
)
|
| 229 |
+
table = table.sort_values(["storm_id", "order", "row"], kind="mergesort")
|
| 230 |
+
table["prediction"] = table.groupby("storm_id", sort=False)["wind"].shift(1)
|
| 231 |
+
table = table.sort_values("row", kind="mergesort")
|
| 232 |
+
return table["prediction"].to_numpy(dtype=np.float64)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def persistence_class_predictions(frame: pd.DataFrame) -> np.ndarray:
|
| 236 |
+
"""Previous same-storm wind, mapped with this project's five bins."""
|
| 237 |
+
winds = persistence_predictions(frame)
|
| 238 |
+
classes = np.empty(len(winds), dtype=object)
|
| 239 |
+
for index, value in enumerate(winds):
|
| 240 |
+
if not np.isfinite(value):
|
| 241 |
+
classes[index] = None
|
| 242 |
+
else:
|
| 243 |
+
classes[index] = wind_to_imd5(float(value))
|
| 244 |
+
return classes
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _known_class_mask(truth: np.ndarray, predicted: np.ndarray) -> np.ndarray:
|
| 248 |
+
known = set(DEFAULT_NAMES)
|
| 249 |
+
return np.asarray(
|
| 250 |
+
[item in known and guess in known for item, guess in zip(truth, predicted, strict=True)],
|
| 251 |
+
dtype=bool,
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
@dataclass(frozen=True)
|
| 256 |
+
class BaselineReport:
|
| 257 |
+
comparison: pd.DataFrame
|
| 258 |
+
selected_features: tuple[str, ...]
|
| 259 |
+
train_storms: frozenset[str]
|
| 260 |
+
val_storms: frozenset[str]
|
| 261 |
+
test_storms: frozenset[str]
|
| 262 |
+
fitted_storms: frozenset[str]
|
| 263 |
+
n_rows_used_for_selection: int
|
| 264 |
+
out_dir: Path
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def xgboost_available() -> bool:
|
| 268 |
+
try:
|
| 269 |
+
import xgboost # noqa: F401
|
| 270 |
+
except ImportError:
|
| 271 |
+
return False
|
| 272 |
+
return True
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
_BASELINE_KEYS = (
|
| 276 |
+
"n_splits",
|
| 277 |
+
"seed",
|
| 278 |
+
"regression_models",
|
| 279 |
+
"classification_models",
|
| 280 |
+
"use_smote",
|
| 281 |
+
"ridge_alpha",
|
| 282 |
+
"knn_neighbors",
|
| 283 |
+
"svr_c",
|
| 284 |
+
"svc_c",
|
| 285 |
+
"rf_estimators",
|
| 286 |
+
"rf_max_depth",
|
| 287 |
+
"xgb_estimators",
|
| 288 |
+
"xgb_max_depth",
|
| 289 |
+
"xgb_learning_rate",
|
| 290 |
+
"max_iter",
|
| 291 |
+
"bootstrap_resamples",
|
| 292 |
+
"per_storm_breakdown",
|
| 293 |
+
"cv_pool",
|
| 294 |
+
"cv_group_column",
|
| 295 |
+
"cv_collapse_rare",
|
| 296 |
+
"cv_assign",
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def baseline_params(config: dict) -> dict:
|
| 301 |
+
"""Hyperparameters from ``baselines`` in the YAML config. No fallbacks."""
|
| 302 |
+
raw = config.get("baselines")
|
| 303 |
+
if not isinstance(raw, dict):
|
| 304 |
+
raise KeyError("config baselines is required")
|
| 305 |
+
missing = [key for key in _BASELINE_KEYS if key not in raw]
|
| 306 |
+
if missing:
|
| 307 |
+
raise KeyError(f"config baselines missing {missing}")
|
| 308 |
+
return {key: raw[key] for key in _BASELINE_KEYS}
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def selection_params(config: dict) -> dict:
|
| 312 |
+
"""Feature-selection hyperparameters from ``features.selection``."""
|
| 313 |
+
raw = config["features"]["selection"]
|
| 314 |
+
return {
|
| 315 |
+
"correlation_threshold": float(raw["correlation_threshold"]),
|
| 316 |
+
"max_features": int(raw["max_features"]),
|
| 317 |
+
"method": str(raw["method"]),
|
| 318 |
+
"n_estimators": int(raw["n_estimators"]),
|
| 319 |
+
"seed": int(raw["seed"]),
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def iter_stratified_group_folds(y_strat, groups, n_splits: int, seed: int):
|
| 324 |
+
"""Yield train/val indices. A storm never sits on both sides of a fold."""
|
| 325 |
+
labels = np.asarray(y_strat).ravel()
|
| 326 |
+
group_ids = np.asarray(groups).ravel()
|
| 327 |
+
if len(labels) != len(group_ids):
|
| 328 |
+
raise BaselineDataError("stratify labels and groups must align")
|
| 329 |
+
if n_splits < 2:
|
| 330 |
+
raise BaselineDataError("n_splits must be at least 2")
|
| 331 |
+
table = pd.DataFrame({"y": labels.astype(str), "g": group_ids.astype(str)})
|
| 332 |
+
for label, part in table.groupby("y"):
|
| 333 |
+
n_groups = int(part["g"].nunique())
|
| 334 |
+
if n_groups < n_splits:
|
| 335 |
+
raise BaselineDataError(
|
| 336 |
+
f"class {label} is in {n_groups} storms but n_splits={n_splits}"
|
| 337 |
+
)
|
| 338 |
+
from sklearn.model_selection import StratifiedGroupKFold
|
| 339 |
+
|
| 340 |
+
splitter = StratifiedGroupKFold(
|
| 341 |
+
n_splits=n_splits, shuffle=True, random_state=seed
|
| 342 |
+
)
|
| 343 |
+
yield from splitter.split(np.zeros(len(labels)), table["y"], table["g"])
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def _require_cv_pool(params: dict) -> str:
|
| 347 |
+
pool = params["cv_pool"]
|
| 348 |
+
if not isinstance(pool, str) or pool.strip().lower() not in {"train", "train_val"}:
|
| 349 |
+
raise BaselineDataError("cv_pool must be train or train_val")
|
| 350 |
+
return pool.strip().lower()
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def _require_cv_bool(params: dict) -> bool:
|
| 354 |
+
value = params["cv_collapse_rare"]
|
| 355 |
+
if not isinstance(value, bool):
|
| 356 |
+
raise BaselineDataError("cv_collapse_rare must be true or false")
|
| 357 |
+
return value
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def _cv_group_ids(frame: pd.DataFrame, params: dict) -> np.ndarray:
|
| 361 |
+
column = params["cv_group_column"]
|
| 362 |
+
if not isinstance(column, str) or not column.strip():
|
| 363 |
+
raise BaselineDataError("cv_group_column must name a column")
|
| 364 |
+
column = column.strip()
|
| 365 |
+
if column not in frame.columns:
|
| 366 |
+
raise BaselineDataError(f"cv_group_column {column} is not on the frame")
|
| 367 |
+
return frame[column].astype(str).to_numpy()
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def collapse_rare_stratify_labels(
|
| 371 |
+
labels: np.ndarray,
|
| 372 |
+
groups: np.ndarray,
|
| 373 |
+
n_splits: int,
|
| 374 |
+
enabled: bool,
|
| 375 |
+
) -> tuple[np.ndarray, str]:
|
| 376 |
+
"""Fold-assignment labels. The scored target is not changed here.
|
| 377 |
+
|
| 378 |
+
When ``enabled`` is false the labels are unchanged. A label that sits in
|
| 379 |
+
fewer groups than ``n_splits`` is mapped onto the most common label that
|
| 380 |
+
already has enough groups, and only for the fold splitter.
|
| 381 |
+
"""
|
| 382 |
+
text = np.asarray(labels).astype(str)
|
| 383 |
+
group_ids = np.asarray(groups).astype(str)
|
| 384 |
+
if not enabled:
|
| 385 |
+
return text, ""
|
| 386 |
+
table = pd.DataFrame({"y": text, "g": group_ids})
|
| 387 |
+
counts = table.groupby("y")["g"].nunique()
|
| 388 |
+
rare = [label for label, count in counts.items() if int(count) < n_splits]
|
| 389 |
+
if not rare:
|
| 390 |
+
return text, ""
|
| 391 |
+
eligible = [label for label, count in counts.items() if int(count) >= n_splits]
|
| 392 |
+
if not eligible:
|
| 393 |
+
raise BaselineDataError(f"every stratify label is in fewer than {n_splits} groups")
|
| 394 |
+
host = str(table.loc[table["y"].isin(eligible), "y"].value_counts().index[0])
|
| 395 |
+
collapsed = text.copy()
|
| 396 |
+
for label in rare:
|
| 397 |
+
collapsed[collapsed == str(label)] = host
|
| 398 |
+
note = "stratify_collapsed:" + ",".join(
|
| 399 |
+
f"{label}->{host}" for label in sorted(str(label) for label in rare)
|
| 400 |
+
)
|
| 401 |
+
return collapsed, note
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _require_cv_assign(params: dict) -> str:
|
| 405 |
+
method = params["cv_assign"]
|
| 406 |
+
if not isinstance(method, str) or method.strip().lower() not in {"stratified", "round_robin"}:
|
| 407 |
+
raise BaselineDataError("cv_assign must be stratified or round_robin")
|
| 408 |
+
return method.strip().lower()
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def round_robin_group_folds(frame: pd.DataFrame, params: dict) -> pd.DataFrame:
|
| 412 |
+
"""Train+val storms only. One row per storm: ``storm_id``, ``fold``.
|
| 413 |
+
|
| 414 |
+
Co-occurrence groups are sorted, shuffled with ``baselines.seed``, and
|
| 415 |
+
dealt round-robin across ``n_splits`` folds. Every storm in a group
|
| 416 |
+
gets that group's fold. Test storms are omitted. This is the same deal
|
| 417 |
+
as a seed-42 group shuffle with the configured fold count.
|
| 418 |
+
"""
|
| 419 |
+
if _require_cv_pool(params) != "train_val":
|
| 420 |
+
raise BaselineDataError("round_robin folds are assigned on train and val only")
|
| 421 |
+
column = str(params["cv_group_column"]).strip()
|
| 422 |
+
if column not in frame.columns:
|
| 423 |
+
raise BaselineDataError(f"cv_group_column {column} is not on the frame")
|
| 424 |
+
n_folds = int(params["n_splits"])
|
| 425 |
+
if n_folds < 2:
|
| 426 |
+
raise BaselineDataError("n_splits must be at least 2")
|
| 427 |
+
pool = frame.loc[frame["split"].astype(str).isin(["train", "val"])].copy()
|
| 428 |
+
if pool.empty:
|
| 429 |
+
raise BaselineDataError("round_robin folds need train and val rows")
|
| 430 |
+
pool["storm_id"] = pool["storm_id"].astype(str)
|
| 431 |
+
if bool((pool.groupby("storm_id")["split"].nunique() > 1).any()):
|
| 432 |
+
raise LeakageError("a storm is in more than one split")
|
| 433 |
+
group_ids = pool[column].map(lambda value: str(int(value)))
|
| 434 |
+
if bool((pool.groupby(group_ids)["split"].nunique() > 1).any()):
|
| 435 |
+
raise LeakageError("a co-occurrence group is in more than one split")
|
| 436 |
+
storms = pool.groupby("storm_id", as_index=False).agg(
|
| 437 |
+
group=(column, "first"),
|
| 438 |
+
split=("split", "first"),
|
| 439 |
+
)
|
| 440 |
+
groups = sorted({int(value) for value in storms["group"].tolist()})
|
| 441 |
+
order = np.random.default_rng(int(params["seed"])).permutation(len(groups))
|
| 442 |
+
shuffled = [groups[int(index)] for index in order]
|
| 443 |
+
group_fold = {group: index % n_folds for index, group in enumerate(shuffled)}
|
| 444 |
+
folds = pd.DataFrame(
|
| 445 |
+
{
|
| 446 |
+
"storm_id": storms["storm_id"].astype(str).tolist(),
|
| 447 |
+
"fold": [int(group_fold[int(value)]) for value in storms["group"].tolist()],
|
| 448 |
+
}
|
| 449 |
+
)
|
| 450 |
+
test_ids = set(frame.loc[frame["split"].astype(str) == "test", "storm_id"].astype(str))
|
| 451 |
+
if set(folds["storm_id"]) & test_ids:
|
| 452 |
+
raise LeakageError("round_robin folds include a test storm")
|
| 453 |
+
return folds.sort_values(["fold", "storm_id"]).reset_index(drop=True)[["storm_id", "fold"]]
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def attach_round_robin_folds(frame: pd.DataFrame, params: dict) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 457 |
+
"""Add ``cv_fold`` on train and val rows. The returned table is the CSV."""
|
| 458 |
+
folds = round_robin_group_folds(frame, params)
|
| 459 |
+
work = frame.copy()
|
| 460 |
+
work["storm_id"] = work["storm_id"].astype(str)
|
| 461 |
+
if "cv_fold" in work.columns:
|
| 462 |
+
work = work.drop(columns=["cv_fold"])
|
| 463 |
+
work = work.merge(folds, on="storm_id", how="left")
|
| 464 |
+
work = work.rename(columns={"fold": "cv_fold"})
|
| 465 |
+
held = work["split"].astype(str).isin(["train", "val"])
|
| 466 |
+
if work.loc[held, "cv_fold"].isna().any():
|
| 467 |
+
raise BaselineDataError("a train or val storm has no cv_fold")
|
| 468 |
+
if work.loc[work["split"].astype(str) == "test", "cv_fold"].notna().any():
|
| 469 |
+
raise LeakageError("a test storm was given a cv_fold")
|
| 470 |
+
return work, folds
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def _preassigned_folds(frame: pd.DataFrame) -> list[tuple[np.ndarray, np.ndarray]] | None:
|
| 474 |
+
if "cv_fold" not in frame.columns or not frame["cv_fold"].notna().all():
|
| 475 |
+
return None
|
| 476 |
+
folds = frame["cv_fold"].astype(int).to_numpy()
|
| 477 |
+
pairs = []
|
| 478 |
+
for fold in sorted(set(folds.tolist())):
|
| 479 |
+
val_index = np.flatnonzero(folds == fold)
|
| 480 |
+
train_index = np.flatnonzero(folds != fold)
|
| 481 |
+
if val_index.size == 0 or train_index.size == 0:
|
| 482 |
+
raise BaselineDataError(f"cv_fold {fold} does not leave both sides non-empty")
|
| 483 |
+
pairs.append((train_index, val_index))
|
| 484 |
+
if len(pairs) < 2:
|
| 485 |
+
raise BaselineDataError("cv_fold needs at least 2 folds")
|
| 486 |
+
return pairs
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def cv_pool_frame(
|
| 490 |
+
train: pd.DataFrame,
|
| 491 |
+
val: pd.DataFrame,
|
| 492 |
+
test: pd.DataFrame,
|
| 493 |
+
params: dict,
|
| 494 |
+
) -> pd.DataFrame:
|
| 495 |
+
"""Rows for the grouped CV. ``train_val`` never includes the test split."""
|
| 496 |
+
pool = _require_cv_pool(params)
|
| 497 |
+
if pool == "train":
|
| 498 |
+
source = train.copy()
|
| 499 |
+
if source.empty:
|
| 500 |
+
raise BaselineDataError("CV pool train is empty")
|
| 501 |
+
if set(source["split"].astype(str)) - {"train"}:
|
| 502 |
+
raise LeakageError("train CV pool includes a non-train row")
|
| 503 |
+
return source.reset_index(drop=True)
|
| 504 |
+
source = pd.concat([train, val], ignore_index=True)
|
| 505 |
+
if source.empty:
|
| 506 |
+
raise BaselineDataError("CV pool train_val is empty")
|
| 507 |
+
if set(source["split"].astype(str)) - {"train", "val"}:
|
| 508 |
+
raise LeakageError("train_val CV pool includes a row outside train and val")
|
| 509 |
+
if set(test["storm_id"].astype(str)) & set(source["storm_id"].astype(str)):
|
| 510 |
+
raise LeakageError("train_val CV includes a test storm")
|
| 511 |
+
column = str(params["cv_group_column"]).strip()
|
| 512 |
+
if column in source.columns and column in test.columns:
|
| 513 |
+
assert_no_group_leakage(source, test, group_col=column)
|
| 514 |
+
return source
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
def impute_train_val(X_train: np.ndarray, X_val: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 518 |
+
"""Median imputer fit on the training fold only."""
|
| 519 |
+
imputer = SimpleImputer(strategy="median", keep_empty_features=True)
|
| 520 |
+
train = np.asarray(imputer.fit_transform(X_train), dtype=np.float64)
|
| 521 |
+
val = np.asarray(imputer.transform(X_val), dtype=np.float64)
|
| 522 |
+
return (
|
| 523 |
+
np.where(np.isfinite(train), train, 0.0),
|
| 524 |
+
np.where(np.isfinite(val), val, 0.0),
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def resample_training_fold(
|
| 529 |
+
X_train: np.ndarray, y_train: np.ndarray, seed: int, enabled: bool
|
| 530 |
+
) -> tuple[np.ndarray, np.ndarray, str]:
|
| 531 |
+
"""SMOTE the training fold only. Validation rows are not an argument."""
|
| 532 |
+
if not enabled:
|
| 533 |
+
return X_train, y_train, "class_weight"
|
| 534 |
+
try:
|
| 535 |
+
from imblearn.over_sampling import SMOTE
|
| 536 |
+
except ImportError:
|
| 537 |
+
return X_train, y_train, "class_weight_imblearn_missing"
|
| 538 |
+
labels, counts = np.unique(y_train, return_counts=True)
|
| 539 |
+
if len(labels) < 2:
|
| 540 |
+
return X_train, y_train, "class_weight_single_class"
|
| 541 |
+
minority = int(counts.min())
|
| 542 |
+
if minority < 2:
|
| 543 |
+
return X_train, y_train, "class_weight_minority_lt_2"
|
| 544 |
+
sampler = SMOTE(k_neighbors=min(5, minority - 1), random_state=seed)
|
| 545 |
+
try:
|
| 546 |
+
resampled_x, resampled_y = sampler.fit_resample(X_train, y_train)
|
| 547 |
+
except ValueError:
|
| 548 |
+
return X_train, y_train, "class_weight_smote_failed"
|
| 549 |
+
return np.asarray(resampled_x), np.asarray(resampled_y), "smote"
|
| 550 |
+
|
| 551 |
+
|
| 552 |
+
def _balanced_weights(y: np.ndarray) -> np.ndarray:
|
| 553 |
+
labels, counts = np.unique(y, return_counts=True)
|
| 554 |
+
total = len(y)
|
| 555 |
+
n_class = len(labels)
|
| 556 |
+
table = {
|
| 557 |
+
label: total / (n_class * count) for label, count in zip(labels, counts, strict=True)
|
| 558 |
+
}
|
| 559 |
+
return np.asarray([table[label] for label in y], dtype=np.float64)
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def _make_estimator(name: str, task: str, params: dict, class_weight: str | None, n_train: int, seed: int):
|
| 563 |
+
weight = "balanced" if class_weight == "balanced" else None
|
| 564 |
+
neighbors = max(1, min(int(params["knn_neighbors"]), int(n_train)))
|
| 565 |
+
if task == "regression":
|
| 566 |
+
if name == "mean":
|
| 567 |
+
return MeanRegressor()
|
| 568 |
+
if name == "lr":
|
| 569 |
+
return LinearRegression()
|
| 570 |
+
if name == "ridge":
|
| 571 |
+
return Ridge(alpha=float(params["ridge_alpha"]))
|
| 572 |
+
if name == "knn":
|
| 573 |
+
return KNeighborsRegressor(n_neighbors=neighbors)
|
| 574 |
+
if name == "svr":
|
| 575 |
+
return SVR(C=float(params["svr_c"]), kernel="rbf")
|
| 576 |
+
if name == "rf":
|
| 577 |
+
return RandomForestRegressor(
|
| 578 |
+
n_estimators=int(params["rf_estimators"]),
|
| 579 |
+
max_depth=int(params["rf_max_depth"]),
|
| 580 |
+
random_state=seed,
|
| 581 |
+
n_jobs=1,
|
| 582 |
+
)
|
| 583 |
+
if name == "xgboost":
|
| 584 |
+
from xgboost import XGBRegressor
|
| 585 |
+
|
| 586 |
+
return XGBRegressor(
|
| 587 |
+
n_estimators=int(params["xgb_estimators"]),
|
| 588 |
+
max_depth=int(params["xgb_max_depth"]),
|
| 589 |
+
learning_rate=float(params["xgb_learning_rate"]),
|
| 590 |
+
random_state=seed,
|
| 591 |
+
n_jobs=1,
|
| 592 |
+
verbosity=0,
|
| 593 |
+
tree_method="hist",
|
| 594 |
+
)
|
| 595 |
+
else:
|
| 596 |
+
if name in _MAJORITY_CLASSIFIERS:
|
| 597 |
+
return MostFrequentClassifier()
|
| 598 |
+
if name == "logreg":
|
| 599 |
+
return LogisticRegression(max_iter=int(params["max_iter"]), class_weight=weight)
|
| 600 |
+
if name == "knn":
|
| 601 |
+
return KNeighborsClassifier(n_neighbors=neighbors)
|
| 602 |
+
if name == "svc":
|
| 603 |
+
return SVC(C=float(params["svc_c"]), kernel="rbf", class_weight=weight)
|
| 604 |
+
if name == "rf":
|
| 605 |
+
return RandomForestClassifier(
|
| 606 |
+
n_estimators=int(params["rf_estimators"]),
|
| 607 |
+
max_depth=int(params["rf_max_depth"]),
|
| 608 |
+
random_state=seed,
|
| 609 |
+
n_jobs=1,
|
| 610 |
+
class_weight=weight,
|
| 611 |
+
)
|
| 612 |
+
if name == "xgboost":
|
| 613 |
+
from xgboost import XGBClassifier
|
| 614 |
+
|
| 615 |
+
return XGBClassifier(
|
| 616 |
+
n_estimators=int(params["xgb_estimators"]),
|
| 617 |
+
max_depth=int(params["xgb_max_depth"]),
|
| 618 |
+
learning_rate=float(params["xgb_learning_rate"]),
|
| 619 |
+
random_state=seed,
|
| 620 |
+
n_jobs=1,
|
| 621 |
+
verbosity=0,
|
| 622 |
+
tree_method="hist",
|
| 623 |
+
)
|
| 624 |
+
raise BaselineDataError(f"unknown model {name} for {task}")
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def fit_numeric_pipeline(
|
| 628 |
+
X_train: np.ndarray,
|
| 629 |
+
y_train: np.ndarray,
|
| 630 |
+
X_val: np.ndarray,
|
| 631 |
+
*,
|
| 632 |
+
task: str,
|
| 633 |
+
model_name: str,
|
| 634 |
+
params: dict,
|
| 635 |
+
seed: int,
|
| 636 |
+
train_storms,
|
| 637 |
+
fitted_storms: set[str],
|
| 638 |
+
) -> tuple[np.ndarray, Pipeline, str]:
|
| 639 |
+
"""Fit on training rows and predict validation rows.
|
| 640 |
+
|
| 641 |
+
``train_storms`` is recorded so a caller can prove val and test storms
|
| 642 |
+
never entered a fit. SMOTE sees only the imputed training matrix.
|
| 643 |
+
"""
|
| 644 |
+
fitted_storms.update(str(storm) for storm in np.asarray(train_storms).ravel())
|
| 645 |
+
X_train_imp, X_val_imp = impute_train_val(X_train, X_val)
|
| 646 |
+
note = "no_smote"
|
| 647 |
+
X_fit, y_fit = X_train_imp, np.asarray(y_train).ravel()
|
| 648 |
+
if task == "classification" and model_name not in _MAJORITY_CLASSIFIERS:
|
| 649 |
+
X_fit, y_fit, note = resample_training_fold(
|
| 650 |
+
X_train_imp,
|
| 651 |
+
y_fit,
|
| 652 |
+
seed,
|
| 653 |
+
enabled=bool(params["use_smote"]),
|
| 654 |
+
)
|
| 655 |
+
if model_name == "knn" and note != "smote":
|
| 656 |
+
note = "unweighted_knn"
|
| 657 |
+
elif task == "classification":
|
| 658 |
+
note = "majority_train_class"
|
| 659 |
+
|
| 660 |
+
class_weight = None
|
| 661 |
+
if (
|
| 662 |
+
task == "classification"
|
| 663 |
+
and model_name not in _MAJORITY_CLASSIFIERS | {"knn"}
|
| 664 |
+
and note != "smote"
|
| 665 |
+
):
|
| 666 |
+
class_weight = "balanced"
|
| 667 |
+
estimator = _make_estimator(
|
| 668 |
+
model_name, task, params, class_weight, n_train=len(X_fit), seed=seed
|
| 669 |
+
)
|
| 670 |
+
sample_weight = None
|
| 671 |
+
if model_name == "xgboost" and class_weight == "balanced":
|
| 672 |
+
sample_weight = _balanced_weights(y_fit)
|
| 673 |
+
estimator = _make_estimator(
|
| 674 |
+
model_name, task, params, None, n_train=len(X_fit), seed=seed
|
| 675 |
+
)
|
| 676 |
+
note = f"{note},xgb_sample_weight"
|
| 677 |
+
encoder = None
|
| 678 |
+
y_model = y_fit
|
| 679 |
+
if task == "classification" and model_name == "xgboost":
|
| 680 |
+
encoder = LabelEncoder()
|
| 681 |
+
y_model = encoder.fit_transform(np.asarray(y_fit).ravel())
|
| 682 |
+
pipeline = Pipeline([("scaler", StandardScaler()), ("model", estimator)])
|
| 683 |
+
if sample_weight is None:
|
| 684 |
+
pipeline.fit(X_fit, y_model)
|
| 685 |
+
else:
|
| 686 |
+
pipeline.fit(X_fit, y_model, model__sample_weight=sample_weight)
|
| 687 |
+
raw = np.asarray(pipeline.predict(X_val_imp)).ravel()
|
| 688 |
+
if encoder is not None:
|
| 689 |
+
raw = encoder.inverse_transform(raw.astype(int))
|
| 690 |
+
elif task == "regression":
|
| 691 |
+
raw = raw.astype(np.float64)
|
| 692 |
+
return raw, pipeline, note
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def _synthetic_flag(frame: pd.DataFrame) -> str:
|
| 696 |
+
"""Track synthetic rows. A missing column is unknown, never a silent no.
|
| 697 |
+
|
| 698 |
+
Ambiguous values raise. They are not coerced to real observations.
|
| 699 |
+
"""
|
| 700 |
+
if "is_synthetic" not in frame.columns:
|
| 701 |
+
return "unknown"
|
| 702 |
+
flags = [parse_is_synthetic(value) for value in frame["is_synthetic"].tolist()]
|
| 703 |
+
if not flags:
|
| 704 |
+
return "unknown"
|
| 705 |
+
if all(flags):
|
| 706 |
+
return "yes"
|
| 707 |
+
if any(flags):
|
| 708 |
+
return "mixed"
|
| 709 |
+
return "no"
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
def _inner_cv_name(params: dict) -> str:
|
| 713 |
+
return "round_robin" if _require_cv_assign(params) == "round_robin" else "StratifiedGroupKFold"
|
| 714 |
+
|
| 715 |
+
|
| 716 |
+
def _empty_metric_row(
|
| 717 |
+
task: str,
|
| 718 |
+
model: str,
|
| 719 |
+
note: str,
|
| 720 |
+
synthetic: str,
|
| 721 |
+
n_features: int,
|
| 722 |
+
inner_cv: str = "StratifiedGroupKFold",
|
| 723 |
+
) -> dict:
|
| 724 |
+
row = {column: np.nan for column in COMPARISON_COLUMNS}
|
| 725 |
+
row.update(
|
| 726 |
+
{
|
| 727 |
+
"task": task,
|
| 728 |
+
"model": model,
|
| 729 |
+
"role": REFERENCE_ROLE if model == "persistence" else IMAGE_ROLE,
|
| 730 |
+
"split_protocol": "train_fit_val_score_test_locked",
|
| 731 |
+
"inner_cv": inner_cv,
|
| 732 |
+
"n_features": n_features,
|
| 733 |
+
"fit_notes": note,
|
| 734 |
+
"quote_as_result": "no",
|
| 735 |
+
"synthetic": synthetic,
|
| 736 |
+
}
|
| 737 |
+
)
|
| 738 |
+
for column in OPERATIONAL_COLUMNS:
|
| 739 |
+
row[column] = np.nan
|
| 740 |
+
return row
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
def _cross_val(
|
| 744 |
+
train: pd.DataFrame,
|
| 745 |
+
selected: tuple[str, ...],
|
| 746 |
+
*,
|
| 747 |
+
task: str,
|
| 748 |
+
model_name: str,
|
| 749 |
+
params: dict,
|
| 750 |
+
fitted_storms: set[str],
|
| 751 |
+
) -> tuple[float, float, str]:
|
| 752 |
+
matrix = model_matrix(train, selected)
|
| 753 |
+
groups = _cv_group_ids(train, params)
|
| 754 |
+
storms = train["storm_id"].astype(str).to_numpy()
|
| 755 |
+
n_splits = int(params["n_splits"])
|
| 756 |
+
preassigned = _preassigned_folds(train)
|
| 757 |
+
collapse_note = ""
|
| 758 |
+
if preassigned is None:
|
| 759 |
+
if task == "regression":
|
| 760 |
+
stratify = (
|
| 761 |
+
train["imd5_class"]
|
| 762 |
+
.astype(object)
|
| 763 |
+
.where(train["imd5_class"].notna(), "below")
|
| 764 |
+
.astype(str)
|
| 765 |
+
.to_numpy()
|
| 766 |
+
)
|
| 767 |
+
else:
|
| 768 |
+
stratify = train["imd5_class"].astype(str).to_numpy()
|
| 769 |
+
stratify, collapse_note = collapse_rare_stratify_labels(
|
| 770 |
+
stratify, groups, n_splits, _require_cv_bool(params)
|
| 771 |
+
)
|
| 772 |
+
folds = list(
|
| 773 |
+
iter_stratified_group_folds(
|
| 774 |
+
stratify, groups, n_splits=n_splits, seed=int(params["seed"])
|
| 775 |
+
)
|
| 776 |
+
)
|
| 777 |
+
else:
|
| 778 |
+
folds = preassigned
|
| 779 |
+
if task == "regression":
|
| 780 |
+
target = train["wind_speed_kt"].to_numpy(dtype=np.float64)
|
| 781 |
+
else:
|
| 782 |
+
target = train["imd5_class"].astype(str).to_numpy()
|
| 783 |
+
scores: list[float] = []
|
| 784 |
+
notes: list[str] = []
|
| 785 |
+
for fold_index, (train_index, val_index) in enumerate(folds):
|
| 786 |
+
if set(groups[train_index]) & set(groups[val_index]):
|
| 787 |
+
raise LeakageError("a CV group is on both sides of a fold")
|
| 788 |
+
predicted, _pipeline, note = fit_numeric_pipeline(
|
| 789 |
+
matrix[train_index],
|
| 790 |
+
target[train_index],
|
| 791 |
+
matrix[val_index],
|
| 792 |
+
task=task,
|
| 793 |
+
model_name=model_name,
|
| 794 |
+
params=params,
|
| 795 |
+
seed=int(params["seed"]) + fold_index + 1,
|
| 796 |
+
train_storms=storms[train_index],
|
| 797 |
+
fitted_storms=fitted_storms,
|
| 798 |
+
)
|
| 799 |
+
notes.append(note)
|
| 800 |
+
if task == "regression":
|
| 801 |
+
scores.append(regression_metrics(target[val_index], predicted)["mae_kt"])
|
| 802 |
+
else:
|
| 803 |
+
scores.append(
|
| 804 |
+
classification_metrics(target[val_index], predicted, DEFAULT_NAMES)["macro_f1"]
|
| 805 |
+
)
|
| 806 |
+
pool = _require_cv_pool(params)
|
| 807 |
+
column = str(params["cv_group_column"]).strip()
|
| 808 |
+
assign = _require_cv_assign(params)
|
| 809 |
+
prefix = f"cv_pool:{pool};cv_group:{column};cv_assign:{assign}"
|
| 810 |
+
if collapse_note:
|
| 811 |
+
prefix = f"{prefix};{collapse_note}"
|
| 812 |
+
return float(np.mean(scores)), float(np.std(scores)), prefix + ";inner_cv:" + "|".join(notes)
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
def _persistence_metric(frame: pd.DataFrame, task: str) -> float | None:
|
| 816 |
+
if frame.empty:
|
| 817 |
+
return None
|
| 818 |
+
if task == "regression":
|
| 819 |
+
predicted = persistence_predictions(frame)
|
| 820 |
+
mask = np.isfinite(predicted)
|
| 821 |
+
if int(mask.sum()) == 0:
|
| 822 |
+
return None
|
| 823 |
+
truth = frame["wind_speed_kt"].to_numpy(dtype=np.float64)[mask]
|
| 824 |
+
return regression_metrics(truth, predicted[mask])["mae_kt"]
|
| 825 |
+
truth = frame["imd5_class"].astype(object).to_numpy()
|
| 826 |
+
predicted = persistence_class_predictions(frame)
|
| 827 |
+
mask = _known_class_mask(truth, predicted)
|
| 828 |
+
if int(mask.sum()) == 0:
|
| 829 |
+
return None
|
| 830 |
+
return classification_metrics(truth[mask], predicted[mask], DEFAULT_NAMES)["macro_f1"]
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
def _persistence_cv(frame: pd.DataFrame, task: str, params: dict) -> tuple[float, float, str]:
|
| 834 |
+
groups = _cv_group_ids(frame, params)
|
| 835 |
+
n_splits = int(params["n_splits"])
|
| 836 |
+
preassigned = _preassigned_folds(frame)
|
| 837 |
+
collapse_note = ""
|
| 838 |
+
if preassigned is None:
|
| 839 |
+
stratify = (
|
| 840 |
+
frame["imd5_class"]
|
| 841 |
+
.astype(object)
|
| 842 |
+
.where(frame["imd5_class"].notna(), "below")
|
| 843 |
+
.astype(str)
|
| 844 |
+
.to_numpy()
|
| 845 |
+
)
|
| 846 |
+
stratify, collapse_note = collapse_rare_stratify_labels(
|
| 847 |
+
stratify, groups, n_splits, _require_cv_bool(params)
|
| 848 |
+
)
|
| 849 |
+
folds = list(
|
| 850 |
+
iter_stratified_group_folds(
|
| 851 |
+
stratify, groups, n_splits=n_splits, seed=int(params["seed"])
|
| 852 |
+
)
|
| 853 |
+
)
|
| 854 |
+
else:
|
| 855 |
+
folds = preassigned
|
| 856 |
+
scores: list[float] = []
|
| 857 |
+
for train_index, val_index in folds:
|
| 858 |
+
if set(groups[train_index]) & set(groups[val_index]):
|
| 859 |
+
raise LeakageError("a CV group is on both sides of a fold")
|
| 860 |
+
score = _persistence_metric(frame.iloc[val_index], task)
|
| 861 |
+
if score is not None:
|
| 862 |
+
scores.append(score)
|
| 863 |
+
pool = _require_cv_pool(params)
|
| 864 |
+
column = str(params["cv_group_column"]).strip()
|
| 865 |
+
assign = _require_cv_assign(params)
|
| 866 |
+
prefix = f"cv_pool:{pool};cv_group:{column};cv_assign:{assign}"
|
| 867 |
+
if collapse_note:
|
| 868 |
+
prefix = f"{prefix};{collapse_note}"
|
| 869 |
+
if not scores:
|
| 870 |
+
return float("nan"), float("nan"), f"{prefix};inner_cv:no_previous_frame"
|
| 871 |
+
return (
|
| 872 |
+
float(np.mean(scores)),
|
| 873 |
+
float(np.std(scores)),
|
| 874 |
+
f"{prefix};inner_cv:previous_same_storm_wind",
|
| 875 |
+
)
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
def _format_cell(value: object) -> str:
|
| 879 |
+
if isinstance(value, (float, np.floating)):
|
| 880 |
+
number = float(value)
|
| 881 |
+
if not np.isfinite(number):
|
| 882 |
+
return ""
|
| 883 |
+
return f"{number:.4f}"
|
| 884 |
+
try:
|
| 885 |
+
if pd.isna(value):
|
| 886 |
+
return ""
|
| 887 |
+
except (TypeError, ValueError):
|
| 888 |
+
pass
|
| 889 |
+
return str(value).replace("|", "/")
|
| 890 |
+
|
| 891 |
+
|
| 892 |
+
def _markdown_table(frame: pd.DataFrame, columns: tuple[str, ...]) -> str:
|
| 893 |
+
header = "| " + " | ".join(columns) + " |"
|
| 894 |
+
rule = "| " + " | ".join("---" for _ in columns) + " |"
|
| 895 |
+
body = [
|
| 896 |
+
"| " + " | ".join(_format_cell(row[column]) for column in columns) + " |"
|
| 897 |
+
for _, row in frame.iterrows()
|
| 898 |
+
]
|
| 899 |
+
return "\n".join([header, rule, *body])
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
def _comparison_frame(rows: list[dict]) -> pd.DataFrame:
|
| 903 |
+
comparison = pd.DataFrame(rows, columns=list(COMPARISON_COLUMNS))
|
| 904 |
+
for column in OPERATIONAL_COLUMNS:
|
| 905 |
+
comparison[column] = np.nan
|
| 906 |
+
comparison["quote_as_result"] = "no"
|
| 907 |
+
return comparison
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
def write_comparison_files(
|
| 911 |
+
destination: Path, rows: list[dict], metadata: dict | None
|
| 912 |
+
) -> pd.DataFrame:
|
| 913 |
+
"""Write the CSV and markdown comparison. Numbers stay `quote_as_result=no`."""
|
| 914 |
+
comparison = _comparison_frame(rows)
|
| 915 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 916 |
+
comparison.to_csv(destination / "baseline_comparison.csv", index=False)
|
| 917 |
+
lines = [
|
| 918 |
+
"# Baseline comparison",
|
| 919 |
+
"",
|
| 920 |
+
BANNER,
|
| 921 |
+
"",
|
| 922 |
+
"Validation scores. The test split was not used for fitting, selection, or SMOTE.",
|
| 923 |
+
PERSISTENCE_NOTE,
|
| 924 |
+
"Learned models are sklearn pipelines. SMOTE and class weights stay inside the training fold.",
|
| 925 |
+
"The official competition side, when present, stays in `source_split`.",
|
| 926 |
+
"`quote_as_result` is no. This is not a forecast and not an operational-readiness claim.",
|
| 927 |
+
"Per-class validation RMSE, MAE, and bias are in `per_class_metrics.csv`.",
|
| 928 |
+
"Those intervals resample storm IDs. The test split is not in that table.",
|
| 929 |
+
"",
|
| 930 |
+
]
|
| 931 |
+
if metadata:
|
| 932 |
+
lines.extend(["## Run", ""])
|
| 933 |
+
for key, value in metadata.items():
|
| 934 |
+
lines.append(f"- {key}: `{value}`")
|
| 935 |
+
lines.append("")
|
| 936 |
+
lines.extend([_markdown_table(comparison, _MARKDOWN_COLUMNS), ""])
|
| 937 |
+
(destination / "baseline_comparison.md").write_text("\n".join(lines), encoding="utf-8")
|
| 938 |
+
(destination / "README.txt").write_text(BANNER + "\n", encoding="utf-8")
|
| 939 |
+
if metadata:
|
| 940 |
+
(destination / "run_record.json").write_text(
|
| 941 |
+
json.dumps(metadata, indent=2, sort_keys=True) + "\n", encoding="utf-8"
|
| 942 |
+
)
|
| 943 |
+
record = [
|
| 944 |
+
"# Baseline run",
|
| 945 |
+
"",
|
| 946 |
+
BANNER,
|
| 947 |
+
"",
|
| 948 |
+
"Official competition labels stay in `source_split`. The modeling split is storm-wise.",
|
| 949 |
+
"The test split was not fit. `quote_as_result` is no.",
|
| 950 |
+
PERSISTENCE_NOTE,
|
| 951 |
+
"Per-class validation metrics are in `per_class_metrics.csv`. Intervals resample storm IDs. The test split is not scored there.",
|
| 952 |
+
"A `wind_averaging` column, when present, is grouped and not converted. An `on_fix` column, when present, adds rows on a best-track fix.",
|
| 953 |
+
"Classes with fewer than 3 storms are marked indicative (n_storms<3).",
|
| 954 |
+
"",
|
| 955 |
+
]
|
| 956 |
+
if str(metadata.get("wind_averaging")) == "3-min" and str(metadata.get("wind_averaging_s")) == "180":
|
| 957 |
+
record.extend(
|
| 958 |
+
[
|
| 959 |
+
"All metrics use raw 3-minute IMD labels. wind_averaging is 3-min and wind_averaging_s is 180 on every row. There is no 1-minute conversion.",
|
| 960 |
+
"",
|
| 961 |
+
]
|
| 962 |
+
)
|
| 963 |
+
for key, value in metadata.items():
|
| 964 |
+
record.append(f"- {key}: `{value}`")
|
| 965 |
+
record.append("")
|
| 966 |
+
(destination / "RUN.md").write_text("\n".join(record), encoding="utf-8")
|
| 967 |
+
return comparison
|
| 968 |
+
|
| 969 |
+
|
| 970 |
+
def write_per_class_files(destination: Path, rows: list[dict]) -> pd.DataFrame:
|
| 971 |
+
"""Write the validation per-class table. Numbers stay ``quote_as_result=no``."""
|
| 972 |
+
frame = pd.DataFrame(rows, columns=list(PER_CLASS_COLUMNS))
|
| 973 |
+
if not frame.empty:
|
| 974 |
+
if not frame["split"].astype(str).eq("val").all():
|
| 975 |
+
raise LeakageError("per-class table contains a split other than val")
|
| 976 |
+
frame["quote_as_result"] = "no"
|
| 977 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 978 |
+
frame.to_csv(destination / "per_class_metrics.csv", index=False)
|
| 979 |
+
lines = [
|
| 980 |
+
"# Per-class validation metrics",
|
| 981 |
+
"",
|
| 982 |
+
BANNER,
|
| 983 |
+
"",
|
| 984 |
+
"Validation split only. The test split was not scored.",
|
| 985 |
+
"Bias is prediction minus true wind.",
|
| 986 |
+
"Intervals are 95% percentile bootstrap confidence intervals.",
|
| 987 |
+
"Each resample draws storm IDs with replacement and keeps every row of a drawn storm.",
|
| 988 |
+
"Rows are not resampled on their own.",
|
| 989 |
+
"Bins are this project's grouping, IMD-style names, not an IMD warning.",
|
| 990 |
+
"A `wind_averaging` column, when present, is copied through and grouped. Periods are not converted.",
|
| 991 |
+
"An `on_fix` column, when present, adds `subset=on_fix` for rows on a best-track fix.",
|
| 992 |
+
"Classes with fewer than 3 storms are marked `indicative (n_storms<3)`.",
|
| 993 |
+
"When per-storm breakdown is on, those classes also list each storm.",
|
| 994 |
+
"`quote_as_result` is no. This is not a forecast and not an operational-readiness claim.",
|
| 995 |
+
"",
|
| 996 |
+
]
|
| 997 |
+
if frame.empty:
|
| 998 |
+
lines.extend(["No regression validation rows were scored.", ""])
|
| 999 |
+
else:
|
| 1000 |
+
lines.extend([_markdown_table(frame, _PER_CLASS_MD_COLUMNS), ""])
|
| 1001 |
+
(destination / "per_class_metrics.md").write_text("\n".join(lines), encoding="utf-8")
|
| 1002 |
+
return frame
|
| 1003 |
+
|
| 1004 |
+
|
| 1005 |
+
def _bootstrap_settings(params: dict) -> tuple[int, int, bool]:
|
| 1006 |
+
resamples = params["bootstrap_resamples"]
|
| 1007 |
+
if isinstance(resamples, bool) or not isinstance(resamples, (int, np.integer)):
|
| 1008 |
+
raise BaselineDataError("bootstrap_resamples must be a positive integer")
|
| 1009 |
+
n_resamples = int(resamples)
|
| 1010 |
+
if n_resamples < 1:
|
| 1011 |
+
raise BaselineDataError("bootstrap_resamples must be a positive integer")
|
| 1012 |
+
breakdown = params["per_storm_breakdown"]
|
| 1013 |
+
if not isinstance(breakdown, bool):
|
| 1014 |
+
raise BaselineDataError("per_storm_breakdown must be true or false")
|
| 1015 |
+
return n_resamples, int(params["seed"]), breakdown
|
| 1016 |
+
|
| 1017 |
+
|
| 1018 |
+
def _record_regression_classes(
|
| 1019 |
+
rows: list[dict],
|
| 1020 |
+
model_name: str,
|
| 1021 |
+
frame: pd.DataFrame,
|
| 1022 |
+
predicted: np.ndarray,
|
| 1023 |
+
*,
|
| 1024 |
+
n_resamples: int,
|
| 1025 |
+
seed: int,
|
| 1026 |
+
synthetic: str,
|
| 1027 |
+
per_storm_breakdown: bool,
|
| 1028 |
+
) -> None:
|
| 1029 |
+
"""Score one regression model on the validation rows it was given."""
|
| 1030 |
+
from src.evaluate import intensity_class_evaluation
|
| 1031 |
+
|
| 1032 |
+
if "split" not in frame.columns:
|
| 1033 |
+
raise BaselineDataError("per-class evaluation needs a split column")
|
| 1034 |
+
if len(frame) != len(np.asarray(predicted)):
|
| 1035 |
+
raise BaselineDataError("per-class predictions must align with the validation rows")
|
| 1036 |
+
observed = set(frame["split"].astype(str).unique())
|
| 1037 |
+
if observed - {"val"}:
|
| 1038 |
+
raise LeakageError(
|
| 1039 |
+
"per-class evaluation scores the validation split only; "
|
| 1040 |
+
f"refusing {sorted(observed - {'val'})}"
|
| 1041 |
+
)
|
| 1042 |
+
table = intensity_class_evaluation(
|
| 1043 |
+
frame["wind_speed_kt"].to_numpy(dtype=np.float64),
|
| 1044 |
+
np.asarray(predicted, dtype=np.float64),
|
| 1045 |
+
frame["storm_id"].to_numpy(),
|
| 1046 |
+
frame["imd5_class"].to_numpy(),
|
| 1047 |
+
frame["split"].astype(str).to_numpy(),
|
| 1048 |
+
wind_averaging=(
|
| 1049 |
+
frame["wind_averaging"].to_numpy() if "wind_averaging" in frame.columns else None
|
| 1050 |
+
),
|
| 1051 |
+
on_fix=frame["on_fix"].to_numpy() if "on_fix" in frame.columns else None,
|
| 1052 |
+
n_resamples=n_resamples,
|
| 1053 |
+
seed=seed,
|
| 1054 |
+
per_storm_breakdown=per_storm_breakdown,
|
| 1055 |
+
)
|
| 1056 |
+
for record in table.to_dict(orient="records"):
|
| 1057 |
+
record["task"] = "regression"
|
| 1058 |
+
record["model"] = model_name
|
| 1059 |
+
record["split"] = "val"
|
| 1060 |
+
record["quote_as_result"] = "no"
|
| 1061 |
+
record["synthetic"] = synthetic
|
| 1062 |
+
rows.append(record)
|
| 1063 |
+
|
| 1064 |
+
|
| 1065 |
+
def _score_persistence(
|
| 1066 |
+
train: pd.DataFrame,
|
| 1067 |
+
val: pd.DataFrame,
|
| 1068 |
+
task: str,
|
| 1069 |
+
params: dict,
|
| 1070 |
+
synthetic: str,
|
| 1071 |
+
n_features: int,
|
| 1072 |
+
destination: Path,
|
| 1073 |
+
class_rows: list[dict] | None = None,
|
| 1074 |
+
cv_frame: pd.DataFrame | None = None,
|
| 1075 |
+
) -> dict:
|
| 1076 |
+
"""Score the previous same-storm wind. Nothing is fit and val storms stay out.
|
| 1077 |
+
|
| 1078 |
+
The headline score uses ``val`` only. ``cv_frame`` is the grouped-CV pool.
|
| 1079 |
+
"""
|
| 1080 |
+
cv_mean, cv_std, cv_note = _persistence_cv(train if cv_frame is None else cv_frame, task, params)
|
| 1081 |
+
note = (
|
| 1082 |
+
"reference_baseline;previous_best_track_label;not_imagery;"
|
| 1083 |
+
f"previous_same_storm_wind;not_a_feature;no_pipeline;{cv_note}"
|
| 1084 |
+
)
|
| 1085 |
+
row = _empty_metric_row(
|
| 1086 |
+
task, "persistence", note, synthetic, n_features, inner_cv=_inner_cv_name(params)
|
| 1087 |
+
)
|
| 1088 |
+
if task == "regression":
|
| 1089 |
+
train_pred = persistence_predictions(train)
|
| 1090 |
+
val_pred = persistence_predictions(val)
|
| 1091 |
+
train_mask = np.isfinite(train_pred)
|
| 1092 |
+
val_mask = np.isfinite(val_pred)
|
| 1093 |
+
if int(val_mask.sum()) == 0:
|
| 1094 |
+
row["fit_notes"] = f"{note};no_previous_frame"
|
| 1095 |
+
return row
|
| 1096 |
+
truth = val["wind_speed_kt"].to_numpy(dtype=np.float64)[val_mask]
|
| 1097 |
+
predicted = val_pred[val_mask]
|
| 1098 |
+
scores = regression_metrics(truth, predicted)
|
| 1099 |
+
by_class = metrics_by_class(truth, predicted, val["imd5_class"].to_numpy()[val_mask])
|
| 1100 |
+
row.update(
|
| 1101 |
+
{
|
| 1102 |
+
"n_train_rows": int(train_mask.sum()),
|
| 1103 |
+
"n_val_rows": int(val_mask.sum()),
|
| 1104 |
+
"n_train_storms": int(train.iloc[np.flatnonzero(train_mask)]["storm_id"].nunique()),
|
| 1105 |
+
"n_val_storms": int(val.iloc[np.flatnonzero(val_mask)]["storm_id"].nunique()),
|
| 1106 |
+
"mae_kt": scores["mae_kt"],
|
| 1107 |
+
"rmse_kt": scores["rmse_kt"],
|
| 1108 |
+
"bias_kt": scores["bias_kt"],
|
| 1109 |
+
"cv_mae_kt_mean": cv_mean,
|
| 1110 |
+
"cv_mae_kt_std": cv_std,
|
| 1111 |
+
}
|
| 1112 |
+
)
|
| 1113 |
+
for class_name in DEFAULT_NAMES:
|
| 1114 |
+
class_scores = by_class.get(class_name)
|
| 1115 |
+
row[f"mae_{class_name}"] = np.nan if class_scores is None else class_scores["mae_kt"]
|
| 1116 |
+
save_regression_scatter(
|
| 1117 |
+
truth,
|
| 1118 |
+
predicted,
|
| 1119 |
+
destination / "scatter_persistence.png",
|
| 1120 |
+
title="persistence val scatter — not a forecast",
|
| 1121 |
+
)
|
| 1122 |
+
if class_rows is not None:
|
| 1123 |
+
n_resamples, seed, breakdown = _bootstrap_settings(params)
|
| 1124 |
+
scored = val.iloc[np.flatnonzero(val_mask)]
|
| 1125 |
+
_record_regression_classes(
|
| 1126 |
+
class_rows,
|
| 1127 |
+
"persistence",
|
| 1128 |
+
scored,
|
| 1129 |
+
predicted,
|
| 1130 |
+
n_resamples=n_resamples,
|
| 1131 |
+
seed=seed,
|
| 1132 |
+
synthetic=synthetic,
|
| 1133 |
+
per_storm_breakdown=breakdown,
|
| 1134 |
+
)
|
| 1135 |
+
return row
|
| 1136 |
+
train_truth = train["imd5_class"].astype(object).to_numpy()
|
| 1137 |
+
val_truth = val["imd5_class"].astype(object).to_numpy()
|
| 1138 |
+
train_pred = persistence_class_predictions(train)
|
| 1139 |
+
val_pred = persistence_class_predictions(val)
|
| 1140 |
+
train_mask = _known_class_mask(train_truth, train_pred)
|
| 1141 |
+
val_mask = _known_class_mask(val_truth, val_pred)
|
| 1142 |
+
if int(val_mask.sum()) == 0:
|
| 1143 |
+
row["fit_notes"] = f"{note};no_previous_class"
|
| 1144 |
+
return row
|
| 1145 |
+
truth = val_truth[val_mask].astype(str)
|
| 1146 |
+
predicted = val_pred[val_mask].astype(str)
|
| 1147 |
+
scores = classification_metrics(truth, predicted, DEFAULT_NAMES)
|
| 1148 |
+
row.update(
|
| 1149 |
+
{
|
| 1150 |
+
"n_train_rows": int(train_mask.sum()),
|
| 1151 |
+
"n_val_rows": int(val_mask.sum()),
|
| 1152 |
+
"n_train_storms": int(train.iloc[np.flatnonzero(train_mask)]["storm_id"].nunique()),
|
| 1153 |
+
"n_val_storms": int(val.iloc[np.flatnonzero(val_mask)]["storm_id"].nunique()),
|
| 1154 |
+
"macro_f1": scores["macro_f1"],
|
| 1155 |
+
"cv_macro_f1_mean": cv_mean,
|
| 1156 |
+
"cv_macro_f1_std": cv_std,
|
| 1157 |
+
}
|
| 1158 |
+
)
|
| 1159 |
+
for class_name in DEFAULT_NAMES:
|
| 1160 |
+
row[f"recall_{class_name}"] = scores[f"recall_{class_name}"]
|
| 1161 |
+
save_confusion_matrix(
|
| 1162 |
+
truth,
|
| 1163 |
+
predicted,
|
| 1164 |
+
destination / "confusion_persistence.png",
|
| 1165 |
+
title="persistence val counts — not a forecast",
|
| 1166 |
+
)
|
| 1167 |
+
return row
|
| 1168 |
+
|
| 1169 |
+
|
| 1170 |
+
def run_baselines(
|
| 1171 |
+
frame: pd.DataFrame,
|
| 1172 |
+
feature_names: tuple[str, ...] | list[str],
|
| 1173 |
+
config: dict,
|
| 1174 |
+
out_dir: str | Path,
|
| 1175 |
+
metadata: dict | None = None,
|
| 1176 |
+
) -> BaselineReport:
|
| 1177 |
+
"""Select on train, compare models on val, and leave the test split locked."""
|
| 1178 |
+
required = {"split", "storm_id", "wind_speed_kt", "imd5_class", "sample_id"}
|
| 1179 |
+
missing = required - set(frame.columns)
|
| 1180 |
+
if missing:
|
| 1181 |
+
raise BaselineDataError(f"baseline frame is missing {sorted(missing)}")
|
| 1182 |
+
unknown = set(frame["split"].astype(str).unique()) - {"train", "val", "test"}
|
| 1183 |
+
if unknown:
|
| 1184 |
+
raise BaselineDataError(f"unknown splits: {sorted(unknown)}")
|
| 1185 |
+
names = tuple(feature_names)
|
| 1186 |
+
assert_no_forbidden_inputs(names, "refusing to train on")
|
| 1187 |
+
parts = [frame[frame["split"] == name] for name in ("train", "val", "test")]
|
| 1188 |
+
assert_no_group_leakage(*parts)
|
| 1189 |
+
train = parts[0].copy()
|
| 1190 |
+
val = parts[1].copy()
|
| 1191 |
+
test = parts[2].copy()
|
| 1192 |
+
if train.empty or val.empty:
|
| 1193 |
+
raise BaselineDataError("train and val must both be non-empty")
|
| 1194 |
+
if train["storm_id"].nunique() < 3:
|
| 1195 |
+
raise BaselineDataError("need at least 3 training storms")
|
| 1196 |
+
|
| 1197 |
+
params = baseline_params(config)
|
| 1198 |
+
n_resamples, bootstrap_seed, per_storm_breakdown = _bootstrap_settings(params)
|
| 1199 |
+
choose = selection_params(config)
|
| 1200 |
+
selection = select_features(
|
| 1201 |
+
train,
|
| 1202 |
+
names,
|
| 1203 |
+
train["wind_speed_kt"].to_numpy(dtype=np.float64),
|
| 1204 |
+
source_split="train",
|
| 1205 |
+
correlation_threshold=choose["correlation_threshold"],
|
| 1206 |
+
max_features=choose["max_features"],
|
| 1207 |
+
method=choose["method"],
|
| 1208 |
+
n_estimators=choose["n_estimators"],
|
| 1209 |
+
seed=choose["seed"],
|
| 1210 |
+
)
|
| 1211 |
+
if selection.train_storms != frozenset(train["storm_id"].astype(str)):
|
| 1212 |
+
raise LeakageError("feature selection used storms outside the training split")
|
| 1213 |
+
selected = selection.names
|
| 1214 |
+
if not selected:
|
| 1215 |
+
raise BaselineDataError("feature selection returned no columns")
|
| 1216 |
+
destination = Path(out_dir)
|
| 1217 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 1218 |
+
synthetic = _synthetic_flag(frame)
|
| 1219 |
+
fitted: set[str] = set()
|
| 1220 |
+
cv_fitted: set[str] = set()
|
| 1221 |
+
pool = _require_cv_pool(params)
|
| 1222 |
+
cv_bucket = fitted if pool == "train" else cv_fitted
|
| 1223 |
+
if _require_cv_assign(params) == "round_robin":
|
| 1224 |
+
combined = pd.concat([train, val, test], ignore_index=True)
|
| 1225 |
+
combined, fold_table = attach_round_robin_folds(combined, params)
|
| 1226 |
+
fold_table.to_csv(destination / "cv_folds.csv", index=False)
|
| 1227 |
+
train = combined.loc[combined["split"].astype(str) == "train"].reset_index(drop=True)
|
| 1228 |
+
val = combined.loc[combined["split"].astype(str) == "val"].reset_index(drop=True)
|
| 1229 |
+
test = combined.loc[combined["split"].astype(str) == "test"].reset_index(drop=True)
|
| 1230 |
+
cv_reg = cv_pool_frame(train, val, test, params)
|
| 1231 |
+
rows: list[dict] = []
|
| 1232 |
+
class_rows: list[dict] = []
|
| 1233 |
+
|
| 1234 |
+
for model_name in list(params["regression_models"]):
|
| 1235 |
+
logger.info("Regression baseline %s", model_name)
|
| 1236 |
+
if model_name == "persistence":
|
| 1237 |
+
rows.append(
|
| 1238 |
+
_score_persistence(
|
| 1239 |
+
train,
|
| 1240 |
+
val,
|
| 1241 |
+
"regression",
|
| 1242 |
+
params,
|
| 1243 |
+
synthetic,
|
| 1244 |
+
len(selected),
|
| 1245 |
+
destination,
|
| 1246 |
+
class_rows,
|
| 1247 |
+
cv_frame=cv_reg,
|
| 1248 |
+
)
|
| 1249 |
+
)
|
| 1250 |
+
write_comparison_files(destination, rows, metadata)
|
| 1251 |
+
write_per_class_files(destination, class_rows)
|
| 1252 |
+
continue
|
| 1253 |
+
if model_name == "xgboost" and not xgboost_available():
|
| 1254 |
+
rows.append(
|
| 1255 |
+
_empty_metric_row(
|
| 1256 |
+
"regression",
|
| 1257 |
+
model_name,
|
| 1258 |
+
"not_installed",
|
| 1259 |
+
synthetic,
|
| 1260 |
+
len(selected),
|
| 1261 |
+
inner_cv=_inner_cv_name(params),
|
| 1262 |
+
)
|
| 1263 |
+
)
|
| 1264 |
+
write_comparison_files(destination, rows, metadata)
|
| 1265 |
+
continue
|
| 1266 |
+
cv_mean, cv_std, cv_note = _cross_val(
|
| 1267 |
+
cv_reg, selected, task="regression", model_name=model_name, params=params, fitted_storms=cv_bucket
|
| 1268 |
+
)
|
| 1269 |
+
predicted, _pipeline, note = fit_numeric_pipeline(
|
| 1270 |
+
model_matrix(train, selected),
|
| 1271 |
+
train["wind_speed_kt"].to_numpy(dtype=np.float64),
|
| 1272 |
+
model_matrix(val, selected),
|
| 1273 |
+
task="regression",
|
| 1274 |
+
model_name=model_name,
|
| 1275 |
+
params=params,
|
| 1276 |
+
seed=int(params["seed"]),
|
| 1277 |
+
train_storms=train["storm_id"].astype(str),
|
| 1278 |
+
fitted_storms=fitted,
|
| 1279 |
+
)
|
| 1280 |
+
scores = regression_metrics(val["wind_speed_kt"], predicted)
|
| 1281 |
+
by_class = metrics_by_class(
|
| 1282 |
+
val["wind_speed_kt"].to_numpy(), predicted, val["imd5_class"].to_numpy()
|
| 1283 |
+
)
|
| 1284 |
+
row = _empty_metric_row(
|
| 1285 |
+
"regression",
|
| 1286 |
+
model_name,
|
| 1287 |
+
f"{note};{cv_note}",
|
| 1288 |
+
synthetic,
|
| 1289 |
+
len(selected),
|
| 1290 |
+
inner_cv=_inner_cv_name(params),
|
| 1291 |
+
)
|
| 1292 |
+
row.update(
|
| 1293 |
+
{
|
| 1294 |
+
"n_train_rows": int(len(train)),
|
| 1295 |
+
"n_val_rows": int(len(val)),
|
| 1296 |
+
"n_train_storms": int(train["storm_id"].nunique()),
|
| 1297 |
+
"n_val_storms": int(val["storm_id"].nunique()),
|
| 1298 |
+
"mae_kt": scores["mae_kt"],
|
| 1299 |
+
"rmse_kt": scores["rmse_kt"],
|
| 1300 |
+
"bias_kt": scores["bias_kt"],
|
| 1301 |
+
"cv_mae_kt_mean": cv_mean,
|
| 1302 |
+
"cv_mae_kt_std": cv_std,
|
| 1303 |
+
}
|
| 1304 |
+
)
|
| 1305 |
+
for class_name in DEFAULT_NAMES:
|
| 1306 |
+
class_scores = by_class.get(class_name)
|
| 1307 |
+
row[f"mae_{class_name}"] = np.nan if class_scores is None else class_scores["mae_kt"]
|
| 1308 |
+
rows.append(row)
|
| 1309 |
+
save_regression_scatter(
|
| 1310 |
+
val["wind_speed_kt"].to_numpy(),
|
| 1311 |
+
predicted,
|
| 1312 |
+
destination / f"scatter_{model_name}.png",
|
| 1313 |
+
title=f"{model_name} val scatter — not a forecast",
|
| 1314 |
+
)
|
| 1315 |
+
_record_regression_classes(
|
| 1316 |
+
class_rows,
|
| 1317 |
+
model_name,
|
| 1318 |
+
val,
|
| 1319 |
+
predicted,
|
| 1320 |
+
n_resamples=n_resamples,
|
| 1321 |
+
seed=bootstrap_seed,
|
| 1322 |
+
synthetic=synthetic,
|
| 1323 |
+
per_storm_breakdown=per_storm_breakdown,
|
| 1324 |
+
)
|
| 1325 |
+
write_comparison_files(destination, rows, metadata)
|
| 1326 |
+
write_per_class_files(destination, class_rows)
|
| 1327 |
+
|
| 1328 |
+
train_cls = train[train["imd5_class"].notna()].copy()
|
| 1329 |
+
val_cls = val[val["imd5_class"].notna()].copy()
|
| 1330 |
+
if train_cls.empty or val_cls.empty:
|
| 1331 |
+
raise BaselineDataError("classification needs labeled rows in train and val")
|
| 1332 |
+
cv_cls = cv_pool_frame(train_cls, val_cls, test, params)
|
| 1333 |
+
for model_name in list(params["classification_models"]):
|
| 1334 |
+
logger.info("Classification baseline %s", model_name)
|
| 1335 |
+
if model_name == "persistence":
|
| 1336 |
+
rows.append(
|
| 1337 |
+
_score_persistence(
|
| 1338 |
+
train,
|
| 1339 |
+
val,
|
| 1340 |
+
"classification",
|
| 1341 |
+
params,
|
| 1342 |
+
synthetic,
|
| 1343 |
+
len(selected),
|
| 1344 |
+
destination,
|
| 1345 |
+
cv_frame=cv_cls,
|
| 1346 |
+
)
|
| 1347 |
+
)
|
| 1348 |
+
write_comparison_files(destination, rows, metadata)
|
| 1349 |
+
continue
|
| 1350 |
+
if model_name == "xgboost" and not xgboost_available():
|
| 1351 |
+
rows.append(
|
| 1352 |
+
_empty_metric_row(
|
| 1353 |
+
"classification",
|
| 1354 |
+
model_name,
|
| 1355 |
+
"not_installed",
|
| 1356 |
+
synthetic,
|
| 1357 |
+
len(selected),
|
| 1358 |
+
inner_cv=_inner_cv_name(params),
|
| 1359 |
+
)
|
| 1360 |
+
)
|
| 1361 |
+
write_comparison_files(destination, rows, metadata)
|
| 1362 |
+
continue
|
| 1363 |
+
cv_mean, cv_std, cv_note = _cross_val(
|
| 1364 |
+
cv_cls,
|
| 1365 |
+
selected,
|
| 1366 |
+
task="classification",
|
| 1367 |
+
model_name=model_name,
|
| 1368 |
+
params=params,
|
| 1369 |
+
fitted_storms=cv_bucket,
|
| 1370 |
+
)
|
| 1371 |
+
predicted, _pipeline, note = fit_numeric_pipeline(
|
| 1372 |
+
model_matrix(train_cls, selected),
|
| 1373 |
+
train_cls["imd5_class"].astype(str).to_numpy(),
|
| 1374 |
+
model_matrix(val_cls, selected),
|
| 1375 |
+
task="classification",
|
| 1376 |
+
model_name=model_name,
|
| 1377 |
+
params=params,
|
| 1378 |
+
seed=int(params["seed"]),
|
| 1379 |
+
train_storms=train_cls["storm_id"].astype(str),
|
| 1380 |
+
fitted_storms=fitted,
|
| 1381 |
+
)
|
| 1382 |
+
scores = classification_metrics(
|
| 1383 |
+
val_cls["imd5_class"].astype(str).to_numpy(), predicted, DEFAULT_NAMES
|
| 1384 |
+
)
|
| 1385 |
+
row = _empty_metric_row(
|
| 1386 |
+
"classification",
|
| 1387 |
+
model_name,
|
| 1388 |
+
f"{note};{cv_note}",
|
| 1389 |
+
synthetic,
|
| 1390 |
+
len(selected),
|
| 1391 |
+
inner_cv=_inner_cv_name(params),
|
| 1392 |
+
)
|
| 1393 |
+
row.update(
|
| 1394 |
+
{
|
| 1395 |
+
"n_train_rows": int(len(train_cls)),
|
| 1396 |
+
"n_val_rows": int(len(val_cls)),
|
| 1397 |
+
"n_train_storms": int(train_cls["storm_id"].nunique()),
|
| 1398 |
+
"n_val_storms": int(val_cls["storm_id"].nunique()),
|
| 1399 |
+
"macro_f1": scores["macro_f1"],
|
| 1400 |
+
"cv_macro_f1_mean": cv_mean,
|
| 1401 |
+
"cv_macro_f1_std": cv_std,
|
| 1402 |
+
}
|
| 1403 |
+
)
|
| 1404 |
+
for class_name in DEFAULT_NAMES:
|
| 1405 |
+
row[f"recall_{class_name}"] = scores[f"recall_{class_name}"]
|
| 1406 |
+
rows.append(row)
|
| 1407 |
+
save_confusion_matrix(
|
| 1408 |
+
val_cls["imd5_class"].astype(str).to_numpy(),
|
| 1409 |
+
predicted,
|
| 1410 |
+
destination / f"confusion_{model_name}.png",
|
| 1411 |
+
title=f"{model_name} val counts — not a forecast",
|
| 1412 |
+
)
|
| 1413 |
+
write_comparison_files(destination, rows, metadata)
|
| 1414 |
+
|
| 1415 |
+
comparison = write_comparison_files(destination, rows, metadata)
|
| 1416 |
+
write_per_class_files(destination, class_rows)
|
| 1417 |
+
payload = {
|
| 1418 |
+
"source_split": selection.source_split,
|
| 1419 |
+
"names": list(selection.names),
|
| 1420 |
+
"importances": selection.importances,
|
| 1421 |
+
"dropped_variance": list(selection.dropped_variance),
|
| 1422 |
+
"dropped_correlation": list(selection.dropped_correlation),
|
| 1423 |
+
"train_storms": sorted(selection.train_storms),
|
| 1424 |
+
"quote_as_result": "no",
|
| 1425 |
+
}
|
| 1426 |
+
(destination / "selected_features.json").write_text(
|
| 1427 |
+
json.dumps(payload, indent=2), encoding="utf-8"
|
| 1428 |
+
)
|
| 1429 |
+
save_feature_importance(
|
| 1430 |
+
selection.importances,
|
| 1431 |
+
destination / "feature_importance.png",
|
| 1432 |
+
title="Train-only selection scores — not a skill claim",
|
| 1433 |
+
)
|
| 1434 |
+
report = BaselineReport(
|
| 1435 |
+
comparison=comparison,
|
| 1436 |
+
selected_features=selected,
|
| 1437 |
+
train_storms=frozenset(train["storm_id"].astype(str)),
|
| 1438 |
+
val_storms=frozenset(val["storm_id"].astype(str)),
|
| 1439 |
+
test_storms=frozenset(test["storm_id"].astype(str)),
|
| 1440 |
+
fitted_storms=frozenset(fitted),
|
| 1441 |
+
n_rows_used_for_selection=int(len(train)),
|
| 1442 |
+
out_dir=destination,
|
| 1443 |
+
)
|
| 1444 |
+
leaked = report.fitted_storms & (report.val_storms | report.test_storms)
|
| 1445 |
+
if leaked:
|
| 1446 |
+
raise LeakageError(f"fit saw held-out storms: {sorted(leaked)}")
|
| 1447 |
+
if not report.fitted_storms <= report.train_storms:
|
| 1448 |
+
raise LeakageError("fit saw storms that are not in the training split")
|
| 1449 |
+
if pool == "train_val":
|
| 1450 |
+
cv_test = frozenset(cv_fitted) & report.test_storms
|
| 1451 |
+
if cv_test:
|
| 1452 |
+
raise LeakageError(f"grouped CV saw test storms: {sorted(cv_test)}")
|
| 1453 |
+
return report
|
| 1454 |
+
|
| 1455 |
+
|
| 1456 |
+
def frame_for_storm_split(frame: pd.DataFrame, config: dict) -> pd.DataFrame:
|
| 1457 |
+
"""Assign a storm-wise split. Drop any incoming ``split`` column first.
|
| 1458 |
+
|
| 1459 |
+
``source_split`` is left untouched. It is the official competition side
|
| 1460 |
+
and is not the modeling split.
|
| 1461 |
+
"""
|
| 1462 |
+
split_cfg = config["split"]
|
| 1463 |
+
strategy = str(split_cfg["strategy"]).lower().strip()
|
| 1464 |
+
if "year_holdout" in strategy:
|
| 1465 |
+
raise BaselineDataError(
|
| 1466 |
+
"year_holdout is not a baseline split and is not run; "
|
| 1467 |
+
f"refusing split.strategy={strategy}"
|
| 1468 |
+
)
|
| 1469 |
+
if strategy != "storm_wise":
|
| 1470 |
+
raise BaselineDataError(
|
| 1471 |
+
"baselines use storm-wise splits only via src.splits.assign_storms; "
|
| 1472 |
+
f"refusing split.strategy={strategy}"
|
| 1473 |
+
)
|
| 1474 |
+
work = frame.copy()
|
| 1475 |
+
if "split" in work.columns:
|
| 1476 |
+
work = work.drop(columns=["split"])
|
| 1477 |
+
holdout_basin = split_cfg["holdout_basin"] or None
|
| 1478 |
+
assigned = assign_storms(
|
| 1479 |
+
work,
|
| 1480 |
+
"storm_wise",
|
| 1481 |
+
test_fraction=float(split_cfg["test_fraction"]),
|
| 1482 |
+
val_fraction=float(split_cfg["val_fraction"]),
|
| 1483 |
+
seed=int(split_cfg["seed"]),
|
| 1484 |
+
holdout_years=[int(year) for year in (split_cfg["holdout_years"] or [])],
|
| 1485 |
+
holdout_basin=None if holdout_basin in {None, ""} else str(holdout_basin),
|
| 1486 |
+
)
|
| 1487 |
+
if "source_split" in frame.columns and "source_split" not in assigned.columns:
|
| 1488 |
+
raise BaselineDataError("source_split was dropped while assigning storms")
|
| 1489 |
+
return assigned
|
| 1490 |
+
|
| 1491 |
+
|
| 1492 |
+
def frame_for_recorded_split(frame: pd.DataFrame) -> pd.DataFrame:
|
| 1493 |
+
"""Keep the manifest ``split`` column. Do not redraw storms.
|
| 1494 |
+
|
| 1495 |
+
A ``cv_group`` column must not cross modeling splits. ``source_split``
|
| 1496 |
+
stays a reference.
|
| 1497 |
+
"""
|
| 1498 |
+
if "split" not in frame.columns:
|
| 1499 |
+
raise BaselineDataError("recorded split needs a split column on the manifest")
|
| 1500 |
+
work = frame.copy()
|
| 1501 |
+
unknown = set(work["split"].astype(str).unique()) - {"train", "val", "test"}
|
| 1502 |
+
if unknown:
|
| 1503 |
+
raise BaselineDataError(f"recorded split has unknown values: {sorted(unknown)}")
|
| 1504 |
+
parts = [work.loc[work["split"].astype(str) == name] for name in ("train", "val", "test")]
|
| 1505 |
+
for name, part in zip(("train", "val", "test"), parts, strict=True):
|
| 1506 |
+
if part.empty:
|
| 1507 |
+
raise BaselineDataError(f"recorded split has no {name} rows")
|
| 1508 |
+
assert_no_group_leakage(*parts)
|
| 1509 |
+
if "cv_group" in work.columns:
|
| 1510 |
+
assert_no_group_leakage(*parts, group_col="cv_group")
|
| 1511 |
+
return work
|
| 1512 |
+
|
| 1513 |
+
|
| 1514 |
+
def _git_commit() -> str:
|
| 1515 |
+
try:
|
| 1516 |
+
return subprocess.check_output(
|
| 1517 |
+
["git", "rev-parse", "HEAD"], text=True, stderr=subprocess.DEVNULL
|
| 1518 |
+
).strip()
|
| 1519 |
+
except (OSError, subprocess.CalledProcessError):
|
| 1520 |
+
return "unknown"
|
| 1521 |
+
|
| 1522 |
+
|
| 1523 |
+
def _assignment_digest(frame: pd.DataFrame, group_column: str) -> str:
|
| 1524 |
+
groups = (
|
| 1525 |
+
frame[group_column].astype(str)
|
| 1526 |
+
if group_column in frame.columns
|
| 1527 |
+
else pd.Series([""] * len(frame), index=frame.index)
|
| 1528 |
+
)
|
| 1529 |
+
lines = [
|
| 1530 |
+
f"{sample}|{split}|{group}"
|
| 1531 |
+
for sample, split, group in zip(
|
| 1532 |
+
frame["sample_id"].astype(str), frame["split"].astype(str), groups, strict=True
|
| 1533 |
+
)
|
| 1534 |
+
]
|
| 1535 |
+
return hashlib.sha256("\n".join(lines).encode()).hexdigest()
|
| 1536 |
+
|
| 1537 |
+
|
| 1538 |
+
def _count_block(frame: pd.DataFrame, column: str) -> str:
|
| 1539 |
+
parts = []
|
| 1540 |
+
for name in sorted(frame[column].astype(str).unique()):
|
| 1541 |
+
part = frame.loc[frame[column].astype(str) == name]
|
| 1542 |
+
parts.append(f"{name}:rows={len(part)},storms={part['storm_id'].nunique()}")
|
| 1543 |
+
return "; ".join(parts)
|
| 1544 |
+
|
| 1545 |
+
|
| 1546 |
+
def _run_metadata(
|
| 1547 |
+
assigned: pd.DataFrame,
|
| 1548 |
+
table: pd.DataFrame,
|
| 1549 |
+
config: dict,
|
| 1550 |
+
*,
|
| 1551 |
+
command: str | None,
|
| 1552 |
+
manifest_command: str | None,
|
| 1553 |
+
manifest: Path,
|
| 1554 |
+
dropped: int,
|
| 1555 |
+
workers: int,
|
| 1556 |
+
) -> dict[str, str]:
|
| 1557 |
+
both = 0
|
| 1558 |
+
if "source_split" in assigned.columns:
|
| 1559 |
+
sides = [
|
| 1560 |
+
set(assigned.loc[assigned["source_split"].astype(str) == side, "storm_id"].astype(str))
|
| 1561 |
+
for side in sorted(assigned["source_split"].astype(str).unique())
|
| 1562 |
+
]
|
| 1563 |
+
both = len(set.intersection(*sides)) if len(sides) > 1 else 0
|
| 1564 |
+
strategy = str(config["split"]["strategy"]).strip().lower()
|
| 1565 |
+
recorded = strategy == "recorded"
|
| 1566 |
+
metadata = {
|
| 1567 |
+
"command": command or "",
|
| 1568 |
+
"manifest_command": manifest_command or "",
|
| 1569 |
+
"manifest": str(manifest),
|
| 1570 |
+
"git_commit": _git_commit(),
|
| 1571 |
+
"split_strategy": strategy,
|
| 1572 |
+
"split_seed": "not_used" if recorded else str(int(config["split"]["seed"])),
|
| 1573 |
+
"baseline_seed": str(int(config["baselines"]["seed"])),
|
| 1574 |
+
"feature_selection_seed": str(int(config["features"]["selection"]["seed"])),
|
| 1575 |
+
"test_fraction": "not_used" if recorded else str(float(config["split"]["test_fraction"])),
|
| 1576 |
+
"val_fraction": "not_used" if recorded else str(float(config["split"]["val_fraction"])),
|
| 1577 |
+
"cv_pool": str(config["baselines"]["cv_pool"]),
|
| 1578 |
+
"cv_group_column": str(config["baselines"]["cv_group_column"]),
|
| 1579 |
+
"cv_collapse_rare": str(bool(config["baselines"]["cv_collapse_rare"])),
|
| 1580 |
+
"cv_assign": str(config["baselines"]["cv_assign"]),
|
| 1581 |
+
"workers": str(int(workers)),
|
| 1582 |
+
"rows": str(int(len(assigned))),
|
| 1583 |
+
"storms": str(int(assigned["storm_id"].nunique())),
|
| 1584 |
+
"rows_after_features": str(int(len(table))),
|
| 1585 |
+
"storms_after_features": str(int(table["storm_id"].nunique())),
|
| 1586 |
+
"modeling_split": _count_block(assigned, "split"),
|
| 1587 |
+
"dropped_cross_split_links": str(int(dropped)),
|
| 1588 |
+
"use_smote": str(bool(config["baselines"]["use_smote"])),
|
| 1589 |
+
"bootstrap_resamples": str(int(config["baselines"]["bootstrap_resamples"])),
|
| 1590 |
+
"per_storm_breakdown": str(bool(config["baselines"]["per_storm_breakdown"])),
|
| 1591 |
+
"per_class_eval_split": "val",
|
| 1592 |
+
"per_class_resample": "storm_id",
|
| 1593 |
+
"quote_as_result": "no",
|
| 1594 |
+
"official_split_used_for_training": "no",
|
| 1595 |
+
}
|
| 1596 |
+
if "source_split" in assigned.columns:
|
| 1597 |
+
metadata["source_split"] = _count_block(assigned, "source_split")
|
| 1598 |
+
metadata["storms_on_both_source_sides"] = str(both)
|
| 1599 |
+
if "wind_averaging" in assigned.columns:
|
| 1600 |
+
metadata["wind_averaging"] = ",".join(
|
| 1601 |
+
sorted({str(value) for value in assigned["wind_averaging"].tolist()})
|
| 1602 |
+
)
|
| 1603 |
+
if "wind_averaging_s" in assigned.columns:
|
| 1604 |
+
metadata["wind_averaging_s"] = ",".join(
|
| 1605 |
+
sorted({str(int(value)) for value in pd.to_numeric(assigned["wind_averaging_s"]).tolist()})
|
| 1606 |
+
)
|
| 1607 |
+
summary_path = manifest.with_suffix(manifest.suffix + ".summary.json")
|
| 1608 |
+
if summary_path.is_file():
|
| 1609 |
+
summary = json.loads(summary_path.read_text(encoding="utf-8"))
|
| 1610 |
+
for key in (
|
| 1611 |
+
"label_scope",
|
| 1612 |
+
"comparability",
|
| 1613 |
+
"metrics_use",
|
| 1614 |
+
"on_fix_definition",
|
| 1615 |
+
"augmented_dropped",
|
| 1616 |
+
"default_excluded_originals",
|
| 1617 |
+
"flagged_not_default_originals",
|
| 1618 |
+
"drop_flagged",
|
| 1619 |
+
"on_fix_rows",
|
| 1620 |
+
"on_fix_false_rows",
|
| 1621 |
+
"on_fix_unknown_rows",
|
| 1622 |
+
"near_land_unknown_rows",
|
| 1623 |
+
"distance_to_land_unknown_rows",
|
| 1624 |
+
"frame_flags_source",
|
| 1625 |
+
"originals_before_exclusions",
|
| 1626 |
+
"rows_written",
|
| 1627 |
+
"pixel_units",
|
| 1628 |
+
"year_holdout_2019",
|
| 1629 |
+
"zenodo_doi",
|
| 1630 |
+
"zip_md5",
|
| 1631 |
+
):
|
| 1632 |
+
if key in summary:
|
| 1633 |
+
metadata[key] = summary[key] if isinstance(summary[key], str) else json.dumps(summary[key])
|
| 1634 |
+
return metadata
|
| 1635 |
+
|
| 1636 |
+
|
| 1637 |
+
def _cache_key(manifest: Path, config: dict, frame: pd.DataFrame | None = None) -> dict[str, object]:
|
| 1638 |
+
strategy = str(config["split"]["strategy"]).strip().lower()
|
| 1639 |
+
if strategy == "recorded":
|
| 1640 |
+
if frame is None:
|
| 1641 |
+
raise BaselineDataError("recorded split cache key needs the assigned frame")
|
| 1642 |
+
return {
|
| 1643 |
+
"manifest": str(manifest.resolve()),
|
| 1644 |
+
"strategy": "recorded",
|
| 1645 |
+
"assignments": _assignment_digest(frame, str(config["baselines"]["cv_group_column"])),
|
| 1646 |
+
"feature_seed": int(config["features"]["selection"]["seed"]),
|
| 1647 |
+
"calibrated": bool(config["features"]["calibrated"]),
|
| 1648 |
+
}
|
| 1649 |
+
return {
|
| 1650 |
+
"manifest": str(manifest.resolve()),
|
| 1651 |
+
"strategy": "storm_wise",
|
| 1652 |
+
"split_seed": int(config["split"]["seed"]),
|
| 1653 |
+
"test_fraction": float(config["split"]["test_fraction"]),
|
| 1654 |
+
"val_fraction": float(config["split"]["val_fraction"]),
|
| 1655 |
+
"feature_seed": int(config["features"]["selection"]["seed"]),
|
| 1656 |
+
}
|
| 1657 |
+
|
| 1658 |
+
|
| 1659 |
+
def restrict_to_orig_size(
|
| 1660 |
+
table: pd.DataFrame, manifest_path: str | Path, orig_size: int
|
| 1661 |
+
) -> tuple[pd.DataFrame, dict[str, str]]:
|
| 1662 |
+
"""Keep rows whose manifest ``orig_size`` matches. The ``split`` column stays.
|
| 1663 |
+
|
| 1664 |
+
The storm assignment is not recomputed. Storms that have no frame of this
|
| 1665 |
+
size drop out of the scored table; the returned note lists them.
|
| 1666 |
+
"""
|
| 1667 |
+
raw = pd.read_csv(manifest_path, usecols=["sample_id", "orig_size"])
|
| 1668 |
+
raw["sample_id"] = raw["sample_id"].astype(str)
|
| 1669 |
+
sizes = raw.drop_duplicates("sample_id").set_index("sample_id")["orig_size"]
|
| 1670 |
+
work = table.copy()
|
| 1671 |
+
work["sample_id"] = work["sample_id"].astype(str)
|
| 1672 |
+
if "split" not in work.columns:
|
| 1673 |
+
raise BaselineDataError("orig_size filter needs the cached storm split")
|
| 1674 |
+
parent_counts = {
|
| 1675 |
+
name: {
|
| 1676 |
+
"rows": int((work["split"].astype(str) == name).sum()),
|
| 1677 |
+
"storms": int(work.loc[work["split"].astype(str) == name, "storm_id"].nunique()),
|
| 1678 |
+
}
|
| 1679 |
+
for name in ("train", "val", "test")
|
| 1680 |
+
}
|
| 1681 |
+
work["orig_size"] = pd.to_numeric(work["sample_id"].map(sizes), errors="coerce")
|
| 1682 |
+
missing = int(work["orig_size"].isna().sum())
|
| 1683 |
+
if missing:
|
| 1684 |
+
raise BaselineDataError(f"{missing} feature rows have no orig_size on the manifest")
|
| 1685 |
+
kept = work.loc[work["orig_size"].astype(int) == int(orig_size)].copy()
|
| 1686 |
+
if kept.empty:
|
| 1687 |
+
raise BaselineDataError(f"no rows with orig_size={orig_size}")
|
| 1688 |
+
absent = {}
|
| 1689 |
+
for name in ("train", "val", "test"):
|
| 1690 |
+
parent = set(work.loc[work["split"].astype(str) == name, "storm_id"].astype(str))
|
| 1691 |
+
scored = set(kept.loc[kept["split"].astype(str) == name, "storm_id"].astype(str))
|
| 1692 |
+
absent[name] = sorted(parent - scored)
|
| 1693 |
+
note = {
|
| 1694 |
+
"orig_size_kept": str(int(orig_size)),
|
| 1695 |
+
"parent_split": _count_block(work, "split"),
|
| 1696 |
+
"scored_split": _count_block(kept, "split"),
|
| 1697 |
+
"val_storms_in_parent_split": str(parent_counts["val"]["storms"]),
|
| 1698 |
+
"val_storms_with_orig_size": str(
|
| 1699 |
+
int(kept.loc[kept["split"].astype(str) == "val", "storm_id"].nunique())
|
| 1700 |
+
),
|
| 1701 |
+
"val_storms_without_orig_size": str(len(absent["val"])),
|
| 1702 |
+
"val_storm_ids_without_orig_size": ",".join(absent["val"]),
|
| 1703 |
+
"like_for_like": (
|
| 1704 |
+
f"Phase 1 CNN trains only on orig_size {int(orig_size)} frames. "
|
| 1705 |
+
"This table keeps the storm split already stored on the feature cache "
|
| 1706 |
+
"and scores only those frames. Persistence remains a reference baseline "
|
| 1707 |
+
"that uses the previous best-track label, not the imagery."
|
| 1708 |
+
),
|
| 1709 |
+
}
|
| 1710 |
+
return kept, note
|
| 1711 |
+
|
| 1712 |
+
|
| 1713 |
+
def run_from_config(
|
| 1714 |
+
config_path: str | Path,
|
| 1715 |
+
manifest_path: str | Path | None = None,
|
| 1716 |
+
out_dir: str | Path | None = None,
|
| 1717 |
+
workers: int = 1,
|
| 1718 |
+
feature_cache: str | Path | None = None,
|
| 1719 |
+
command: str | None = None,
|
| 1720 |
+
manifest_command: str | None = None,
|
| 1721 |
+
orig_size: int | None = None,
|
| 1722 |
+
) -> BaselineReport:
|
| 1723 |
+
"""Run the Phase 2 comparison. Does not download imagery.
|
| 1724 |
+
|
| 1725 |
+
``storm_wise`` redraws storms. ``recorded`` keeps the manifest split.
|
| 1726 |
+
A ``source_split`` column is reference only. ``year_holdout`` is refused.
|
| 1727 |
+
"""
|
| 1728 |
+
config = load_config(config_path)
|
| 1729 |
+
strategy = str(config["split"]["strategy"]).strip().lower()
|
| 1730 |
+
if "year_holdout" in strategy:
|
| 1731 |
+
raise BaselineDataError(
|
| 1732 |
+
"year_holdout is not a baseline split and is not run; "
|
| 1733 |
+
f"refusing split.strategy={strategy}"
|
| 1734 |
+
)
|
| 1735 |
+
manifest = Path(manifest_path or config["paths"]["manifest"])
|
| 1736 |
+
if not manifest.is_file():
|
| 1737 |
+
raise FileNotFoundError(
|
| 1738 |
+
f"missing manifest {manifest}. Point paths.manifest at a local file. "
|
| 1739 |
+
"This command does not download NASA, TCIR, or INSAT imagery."
|
| 1740 |
+
)
|
| 1741 |
+
destination = Path(out_dir) if out_dir else Path(config["paths"]["reports"]) / "baselines"
|
| 1742 |
+
loaded = load_manifest(manifest)
|
| 1743 |
+
if strategy == "recorded":
|
| 1744 |
+
frame = frame_for_recorded_split(loaded)
|
| 1745 |
+
elif strategy == "storm_wise":
|
| 1746 |
+
frame = frame_for_storm_split(loaded, config)
|
| 1747 |
+
else:
|
| 1748 |
+
raise BaselineDataError(
|
| 1749 |
+
"baselines accept storm_wise or recorded splits; "
|
| 1750 |
+
f"refusing split.strategy={strategy}"
|
| 1751 |
+
)
|
| 1752 |
+
spec = FeatureSpec.from_config(config)
|
| 1753 |
+
cache = Path(feature_cache) if feature_cache else None
|
| 1754 |
+
meta_path = cache.with_suffix(cache.suffix + ".meta.json") if cache else None
|
| 1755 |
+
key = _cache_key(manifest, config, frame)
|
| 1756 |
+
table = None
|
| 1757 |
+
dropped = 0
|
| 1758 |
+
if cache and cache.is_file() and meta_path and meta_path.is_file():
|
| 1759 |
+
saved = json.loads(meta_path.read_text(encoding="utf-8"))
|
| 1760 |
+
if saved.get("key") == key:
|
| 1761 |
+
table = pd.read_csv(cache)
|
| 1762 |
+
dropped = int(saved.get("dropped_cross_split_links", 0))
|
| 1763 |
+
logger.info("Loaded feature cache %s", cache)
|
| 1764 |
+
if table is None:
|
| 1765 |
+
checkpoint = cache.with_suffix(cache.suffix + ".images.csv") if cache else None
|
| 1766 |
+
table, dropped = extract_table(
|
| 1767 |
+
frame, manifest, spec, config, workers=workers, image_checkpoint=checkpoint
|
| 1768 |
+
)
|
| 1769 |
+
if cache:
|
| 1770 |
+
cache.parent.mkdir(parents=True, exist_ok=True)
|
| 1771 |
+
table.to_csv(cache, index=False)
|
| 1772 |
+
meta_path.write_text(
|
| 1773 |
+
json.dumps({"key": key, "dropped_cross_split_links": int(dropped)}, indent=2),
|
| 1774 |
+
encoding="utf-8",
|
| 1775 |
+
)
|
| 1776 |
+
logger.info("Dropped %s cross-split temporal links", dropped)
|
| 1777 |
+
if orig_size is not None:
|
| 1778 |
+
table, size_note = restrict_to_orig_size(table, manifest, int(orig_size))
|
| 1779 |
+
logger.info("Kept orig_size %s: %s", orig_size, size_note["scored_split"])
|
| 1780 |
+
else:
|
| 1781 |
+
size_note = {}
|
| 1782 |
+
metadata = _run_metadata(
|
| 1783 |
+
frame,
|
| 1784 |
+
table,
|
| 1785 |
+
config,
|
| 1786 |
+
command=command,
|
| 1787 |
+
manifest_command=manifest_command,
|
| 1788 |
+
manifest=manifest,
|
| 1789 |
+
dropped=dropped,
|
| 1790 |
+
workers=workers,
|
| 1791 |
+
)
|
| 1792 |
+
metadata.update(size_note)
|
| 1793 |
+
return run_baselines(table, spec.feature_names(), config, destination, metadata=metadata)
|
| 1794 |
+
|
| 1795 |
+
|
| 1796 |
+
def extract_table(
|
| 1797 |
+
frame,
|
| 1798 |
+
manifest,
|
| 1799 |
+
spec: FeatureSpec,
|
| 1800 |
+
config: dict,
|
| 1801 |
+
workers: int = 1,
|
| 1802 |
+
image_checkpoint: str | Path | None = None,
|
| 1803 |
+
):
|
| 1804 |
+
return extract_feature_table(
|
| 1805 |
+
frame,
|
| 1806 |
+
manifest,
|
| 1807 |
+
spec,
|
| 1808 |
+
max_missing_fraction=float(config["data"]["max_missing_fraction"]),
|
| 1809 |
+
workers=workers,
|
| 1810 |
+
image_checkpoint=image_checkpoint,
|
| 1811 |
+
)
|
| 1812 |
+
|
| 1813 |
+
|
| 1814 |
+
def main(argv: list[str] | None = None) -> None:
|
| 1815 |
+
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
| 1816 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 1817 |
+
parser.add_argument("--config", type=Path, required=True)
|
| 1818 |
+
parser.add_argument("--manifest", type=Path, default=None)
|
| 1819 |
+
parser.add_argument("--out", type=Path, default=None)
|
| 1820 |
+
parser.add_argument("--workers", type=int, default=1)
|
| 1821 |
+
parser.add_argument("--feature-cache", type=Path, default=None)
|
| 1822 |
+
parser.add_argument(
|
| 1823 |
+
"--manifest-command",
|
| 1824 |
+
default="",
|
| 1825 |
+
help="Exact command that built the manifest. Recorded in RUN.md. This command does not run it.",
|
| 1826 |
+
)
|
| 1827 |
+
parser.add_argument(
|
| 1828 |
+
"--orig-size",
|
| 1829 |
+
type=int,
|
| 1830 |
+
default=None,
|
| 1831 |
+
help="Score only frames with this manifest orig_size. Keeps the cached storm split.",
|
| 1832 |
+
)
|
| 1833 |
+
args = parser.parse_args(argv)
|
| 1834 |
+
command = "python -m src.baselines " + " ".join(shlex.quote(arg) for arg in (argv if argv is not None else sys.argv[1:]))
|
| 1835 |
+
report = run_from_config(
|
| 1836 |
+
args.config,
|
| 1837 |
+
args.manifest,
|
| 1838 |
+
args.out,
|
| 1839 |
+
workers=args.workers,
|
| 1840 |
+
feature_cache=args.feature_cache,
|
| 1841 |
+
command=command,
|
| 1842 |
+
manifest_command=args.manifest_command or None,
|
| 1843 |
+
orig_size=args.orig_size,
|
| 1844 |
+
)
|
| 1845 |
+
print(BANNER)
|
| 1846 |
+
print(f"Wrote {report.out_dir / 'baseline_comparison.csv'}")
|
| 1847 |
+
print(f"Wrote {report.out_dir / 'baseline_comparison.md'}")
|
| 1848 |
+
print(f"Wrote {report.out_dir / 'per_class_metrics.csv'}")
|
| 1849 |
+
print(f"Wrote {report.out_dir / 'per_class_metrics.md'}")
|
| 1850 |
+
print("quote_as_result=no for every row. Test storms were not fit or scored.")
|
| 1851 |
+
|
| 1852 |
+
|
| 1853 |
+
if __name__ == "__main__":
|
| 1854 |
+
main()
|
bundle/src/cache_frames.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Write fp16 ``.npy`` frames and an index CSV for one dataset.
|
| 2 |
+
|
| 3 |
+
Training reads this cache when ``paths.frame_cache/<dataset>/index.csv``
|
| 4 |
+
exists and otherwise reads the source files. Nothing is downloaded.
|
| 5 |
+
Workers then load a small array instead of decoding the source.
|
| 6 |
+
|
| 7 |
+
``python -m src.cache_frames --dataset nasa``
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import re
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import pandas as pd
|
| 18 |
+
|
| 19 |
+
_SAMPLE_CHARS = re.compile(r"[^A-Za-z0-9._-]+")
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _safe_name(sample_id: str) -> str:
|
| 23 |
+
cleaned = _SAMPLE_CHARS.sub("_", sample_id.strip())
|
| 24 |
+
return cleaned or "frame"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def cache_dataset(dataset: str, config: dict) -> Path:
|
| 28 |
+
"""Read one local dataset and write fp16 frames plus ``index.csv``."""
|
| 29 |
+
from src.data_loader import load_image
|
| 30 |
+
from src.train import load_training_frame
|
| 31 |
+
|
| 32 |
+
name = str(dataset).strip().lower()
|
| 33 |
+
root = Path(config["paths"]["frame_cache"])
|
| 34 |
+
frame, _excluded = load_training_frame(name, config)
|
| 35 |
+
dest_dir = root / name / "frames"
|
| 36 |
+
dest_dir.mkdir(parents=True, exist_ok=True)
|
| 37 |
+
rows: list[dict[str, str]] = []
|
| 38 |
+
for row in frame.itertuples(index=False):
|
| 39 |
+
array = np.asarray(load_image(row.image_path), dtype=np.float16)
|
| 40 |
+
path = dest_dir / f"{_safe_name(str(row.sample_id))}.npy"
|
| 41 |
+
np.save(path, array)
|
| 42 |
+
rows.append(
|
| 43 |
+
{
|
| 44 |
+
"sample_id": str(row.sample_id),
|
| 45 |
+
"cache_path": path.resolve().as_posix(),
|
| 46 |
+
"source_path": str(row.image_path),
|
| 47 |
+
"dataset": name,
|
| 48 |
+
"dtype": "float16",
|
| 49 |
+
}
|
| 50 |
+
)
|
| 51 |
+
index = root / name / "index.csv"
|
| 52 |
+
pd.DataFrame(rows).to_csv(index, index=False)
|
| 53 |
+
print(f"Wrote {index} ({len(rows)} fp16 frames). Not a model result.")
|
| 54 |
+
return index
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def main(argv: list[str] | None = None) -> Path:
|
| 58 |
+
"""``python -m src.cache_frames --config config/config.yaml --dataset nasa``."""
|
| 59 |
+
from src.config import load_config
|
| 60 |
+
from src.train import _DATASETS
|
| 61 |
+
|
| 62 |
+
parser = argparse.ArgumentParser(
|
| 63 |
+
description="Cache one dataset as fp16 npy frames. Does not download imagery."
|
| 64 |
+
)
|
| 65 |
+
parser.add_argument("--config", type=Path, default=Path("config/config.yaml"))
|
| 66 |
+
parser.add_argument("--dataset", required=True, choices=_DATASETS)
|
| 67 |
+
args = parser.parse_args(argv)
|
| 68 |
+
return cache_dataset(args.dataset, load_config(args.config))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if __name__ == "__main__":
|
| 72 |
+
main()
|
bundle/src/calibration.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Torch-free calibration diagnostics for uncertainty intervals.
|
| 2 |
+
|
| 3 |
+
Compares raw MC Dropout intervals with validation-fit scaled conformal
|
| 4 |
+
intervals. Computes MACE, ENCE, 90% coverage and width, and Spearman
|
| 5 |
+
rank correlation between predicted uncertainty and absolute error.
|
| 6 |
+
|
| 7 |
+
This module does **not** import torch. All inputs are NumPy arrays.
|
| 8 |
+
|
| 9 |
+
Terminology
|
| 10 |
+
-----------
|
| 11 |
+
- *Raw MC*: central percentile interval from MC-dropout samples.
|
| 12 |
+
- *Scaled conformal*: MC-dropout intervals whose half-widths are rescaled
|
| 13 |
+
by a single scalar fit on validation residuals so that empirical coverage
|
| 14 |
+
matches the nominal level on the validation set.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import math
|
| 20 |
+
from dataclasses import dataclass, field
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
# Data containers
|
| 27 |
+
# ---------------------------------------------------------------------------
|
| 28 |
+
|
| 29 |
+
@dataclass(frozen=True)
|
| 30 |
+
class IntervalResult:
|
| 31 |
+
"""Coverage and width for one interval method at one nominal level."""
|
| 32 |
+
|
| 33 |
+
nominal: float
|
| 34 |
+
empirical_coverage: float
|
| 35 |
+
mean_width_kt: float
|
| 36 |
+
median_width_kt: float
|
| 37 |
+
n: int
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@dataclass(frozen=True)
|
| 41 |
+
class CalibrationReport:
|
| 42 |
+
"""Full calibration comparison between raw MC and scaled conformal."""
|
| 43 |
+
|
| 44 |
+
# Per-level results
|
| 45 |
+
raw_mc: dict[str, IntervalResult] = field(default_factory=dict)
|
| 46 |
+
scaled_conformal: dict[str, IntervalResult] = field(default_factory=dict)
|
| 47 |
+
|
| 48 |
+
# Aggregate scalar metrics
|
| 49 |
+
mace: float = float("nan")
|
| 50 |
+
ence: float = float("nan")
|
| 51 |
+
coverage_90_raw: float = float("nan")
|
| 52 |
+
width_90_raw_kt: float = float("nan")
|
| 53 |
+
coverage_90_scaled: float = float("nan")
|
| 54 |
+
width_90_scaled_kt: float = float("nan")
|
| 55 |
+
spearman_rho: float = float("nan")
|
| 56 |
+
spearman_p: float = float("nan")
|
| 57 |
+
|
| 58 |
+
def to_dict(self) -> dict:
|
| 59 |
+
"""Serialize to a plain dict for JSON output."""
|
| 60 |
+
out: dict = {
|
| 61 |
+
"mace": _safe_float(self.mace),
|
| 62 |
+
"ence": _safe_float(self.ence),
|
| 63 |
+
"spearman_rho": _safe_float(self.spearman_rho),
|
| 64 |
+
"spearman_p": _safe_float(self.spearman_p),
|
| 65 |
+
"coverage_90_raw": _safe_float(self.coverage_90_raw),
|
| 66 |
+
"width_90_raw_kt": _safe_float(self.width_90_raw_kt),
|
| 67 |
+
"coverage_90_scaled": _safe_float(self.coverage_90_scaled),
|
| 68 |
+
"width_90_scaled_kt": _safe_float(self.width_90_scaled_kt),
|
| 69 |
+
}
|
| 70 |
+
for label, bucket in (("raw_mc", self.raw_mc), ("scaled_conformal", self.scaled_conformal)):
|
| 71 |
+
out[label] = {
|
| 72 |
+
key: {
|
| 73 |
+
"nominal": result.nominal,
|
| 74 |
+
"empirical_coverage": result.empirical_coverage,
|
| 75 |
+
"mean_width_kt": result.mean_width_kt,
|
| 76 |
+
"median_width_kt": result.median_width_kt,
|
| 77 |
+
"n": result.n,
|
| 78 |
+
}
|
| 79 |
+
for key, result in bucket.items()
|
| 80 |
+
}
|
| 81 |
+
return out
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _safe_float(value: float) -> float | None:
|
| 85 |
+
"""Return None for nan/inf so JSON serialization works."""
|
| 86 |
+
if not np.isfinite(value):
|
| 87 |
+
return None
|
| 88 |
+
return float(value)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# ---------------------------------------------------------------------------
|
| 92 |
+
# Low-level interval helpers (no torch)
|
| 93 |
+
# ---------------------------------------------------------------------------
|
| 94 |
+
|
| 95 |
+
def _mc_intervals(
|
| 96 |
+
samples: np.ndarray, level: float
|
| 97 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 98 |
+
"""Central percentile interval from MC-dropout draws.
|
| 99 |
+
|
| 100 |
+
Parameters
|
| 101 |
+
----------
|
| 102 |
+
samples : array, shape (n_draws, n_rows)
|
| 103 |
+
level : float in (0, 1)
|
| 104 |
+
|
| 105 |
+
Returns
|
| 106 |
+
-------
|
| 107 |
+
lower, upper : arrays of shape (n_rows,)
|
| 108 |
+
"""
|
| 109 |
+
draws = np.asarray(samples, dtype=np.float64)
|
| 110 |
+
if draws.ndim != 2 or draws.shape[0] < 2:
|
| 111 |
+
raise ValueError("samples must have shape (n_draws, n_rows) with >= 2 draws")
|
| 112 |
+
alpha = (1.0 - level) / 2.0
|
| 113 |
+
lower = np.quantile(draws, alpha, axis=0, method="linear")
|
| 114 |
+
upper = np.quantile(draws, 1.0 - alpha, axis=0, method="linear")
|
| 115 |
+
return np.asarray(lower, np.float64), np.asarray(upper, np.float64)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _coverage_and_width(
|
| 119 |
+
y_true: np.ndarray,
|
| 120 |
+
lower: np.ndarray,
|
| 121 |
+
upper: np.ndarray,
|
| 122 |
+
) -> tuple[float, float, float]:
|
| 123 |
+
"""Empirical coverage, mean width, median width."""
|
| 124 |
+
covered = (y_true >= lower) & (y_true <= upper)
|
| 125 |
+
widths = upper - lower
|
| 126 |
+
return float(np.mean(covered)), float(np.mean(widths)), float(np.median(widths))
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _fit_conformal_scale(
|
| 130 |
+
y_true_val: np.ndarray,
|
| 131 |
+
mc_samples_val: np.ndarray,
|
| 132 |
+
level: float,
|
| 133 |
+
) -> float:
|
| 134 |
+
"""Fit a single multiplicative scalar on validation residuals.
|
| 135 |
+
|
| 136 |
+
The scalar *s* is chosen so that the rescaled MC intervals (center ± s·hw)
|
| 137 |
+
achieve exactly the requested coverage on the validation set, using
|
| 138 |
+
conformalized quantile regression with a single global scale.
|
| 139 |
+
"""
|
| 140 |
+
draws = np.asarray(mc_samples_val, dtype=np.float64)
|
| 141 |
+
means = draws.mean(axis=0)
|
| 142 |
+
lower, upper = _mc_intervals(draws, level)
|
| 143 |
+
half_widths = (upper - lower) / 2.0
|
| 144 |
+
# Avoid division by zero for constant predictions.
|
| 145 |
+
half_widths = np.maximum(half_widths, 1e-12)
|
| 146 |
+
conformity_scores = np.abs(y_true_val - means) / half_widths
|
| 147 |
+
# The conformal quantile: the smallest s such that coverage >= level.
|
| 148 |
+
quantile = np.quantile(conformity_scores, level, method="higher")
|
| 149 |
+
return float(quantile)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _scaled_intervals(
|
| 153 |
+
mc_samples: np.ndarray, scale: float, level: float
|
| 154 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 155 |
+
"""Apply conformal scale to MC intervals."""
|
| 156 |
+
draws = np.asarray(mc_samples, dtype=np.float64)
|
| 157 |
+
means = draws.mean(axis=0)
|
| 158 |
+
lower_raw, upper_raw = _mc_intervals(draws, level)
|
| 159 |
+
half_widths = (upper_raw - lower_raw) / 2.0
|
| 160 |
+
lower = means - scale * half_widths
|
| 161 |
+
upper = means + scale * half_widths
|
| 162 |
+
return lower, upper
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
# ---------------------------------------------------------------------------
|
| 166 |
+
# Aggregate calibration metrics
|
| 167 |
+
# ---------------------------------------------------------------------------
|
| 168 |
+
|
| 169 |
+
def compute_mace(
|
| 170 |
+
y_true: np.ndarray,
|
| 171 |
+
mc_samples: np.ndarray,
|
| 172 |
+
n_bins: int = 10,
|
| 173 |
+
) -> float:
|
| 174 |
+
"""Mean Absolute Calibration Error (MACE).
|
| 175 |
+
|
| 176 |
+
Evaluates the raw MC intervals at ``n_bins`` equally spaced nominal
|
| 177 |
+
levels from 0.1 to 0.9 and returns the mean absolute gap between
|
| 178 |
+
nominal and empirical coverage.
|
| 179 |
+
"""
|
| 180 |
+
levels = np.linspace(0.1, 0.9, n_bins)
|
| 181 |
+
gaps: list[float] = []
|
| 182 |
+
for level in levels:
|
| 183 |
+
lower, upper = _mc_intervals(mc_samples, float(level))
|
| 184 |
+
cov, _, _ = _coverage_and_width(y_true, lower, upper)
|
| 185 |
+
gaps.append(abs(cov - float(level)))
|
| 186 |
+
return float(np.mean(gaps))
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def compute_ence(
|
| 190 |
+
y_true: np.ndarray,
|
| 191 |
+
mc_samples: np.ndarray,
|
| 192 |
+
n_bins: int = 10,
|
| 193 |
+
) -> float:
|
| 194 |
+
"""Expected Normalized Calibration Error (ENCE).
|
| 195 |
+
|
| 196 |
+
Groups rows by predicted uncertainty (MC std), computes per-bin RMSE and
|
| 197 |
+
mean predicted std, then averages the relative gap.
|
| 198 |
+
"""
|
| 199 |
+
draws = np.asarray(mc_samples, dtype=np.float64)
|
| 200 |
+
pred_mean = draws.mean(axis=0)
|
| 201 |
+
pred_std = draws.std(axis=0, ddof=0)
|
| 202 |
+
n = len(y_true)
|
| 203 |
+
if n < n_bins:
|
| 204 |
+
n_bins = max(1, n)
|
| 205 |
+
order = np.argsort(pred_std)
|
| 206 |
+
bin_edges = np.array_split(order, n_bins)
|
| 207 |
+
ence_terms: list[float] = []
|
| 208 |
+
for indices in bin_edges:
|
| 209 |
+
if len(indices) == 0:
|
| 210 |
+
continue
|
| 211 |
+
rmse = float(np.sqrt(np.mean((y_true[indices] - pred_mean[indices]) ** 2)))
|
| 212 |
+
mean_std = float(np.mean(pred_std[indices]))
|
| 213 |
+
if mean_std > 0:
|
| 214 |
+
ence_terms.append(abs(rmse - mean_std) / mean_std)
|
| 215 |
+
else:
|
| 216 |
+
ence_terms.append(0.0 if rmse == 0 else float("inf"))
|
| 217 |
+
return float(np.mean(ence_terms)) if ence_terms else float("nan")
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def compute_spearman(
|
| 221 |
+
y_true: np.ndarray,
|
| 222 |
+
mc_samples: np.ndarray,
|
| 223 |
+
) -> tuple[float, float]:
|
| 224 |
+
"""Spearman ρ between predicted uncertainty (MC std) and |error|.
|
| 225 |
+
|
| 226 |
+
A higher ρ means the model's uncertainty tracks its actual errors.
|
| 227 |
+
"""
|
| 228 |
+
draws = np.asarray(mc_samples, dtype=np.float64)
|
| 229 |
+
pred_mean = draws.mean(axis=0)
|
| 230 |
+
pred_std = draws.std(axis=0, ddof=0)
|
| 231 |
+
abs_error = np.abs(y_true - pred_mean)
|
| 232 |
+
if pred_std.std() == 0 or abs_error.std() == 0:
|
| 233 |
+
return 0.0, 1.0
|
| 234 |
+
try:
|
| 235 |
+
from scipy import stats as sp_stats
|
| 236 |
+
|
| 237 |
+
result = sp_stats.spearmanr(pred_std, abs_error)
|
| 238 |
+
return float(result.statistic), float(result.pvalue)
|
| 239 |
+
except ImportError:
|
| 240 |
+
import pandas as pd
|
| 241 |
+
|
| 242 |
+
rho = float(pd.Series(pred_std).corr(pd.Series(abs_error), method="spearman"))
|
| 243 |
+
n = len(pred_std)
|
| 244 |
+
if n > 2 and abs(rho) < 1.0:
|
| 245 |
+
t_stat = rho * np.sqrt((n - 2) / (1.0 - rho**2))
|
| 246 |
+
pval = float(2.0 * (1.0 - 0.5 * (1.0 + math.erf(abs(t_stat) / np.sqrt(2)))))
|
| 247 |
+
else:
|
| 248 |
+
pval = 0.0 if abs(rho) == 1.0 else 1.0
|
| 249 |
+
return rho, pval
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
# ---------------------------------------------------------------------------
|
| 253 |
+
# Main calibration comparison
|
| 254 |
+
# ---------------------------------------------------------------------------
|
| 255 |
+
|
| 256 |
+
NOMINAL_LEVELS = (0.50, 0.80, 0.90, 0.95)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def compare_calibration(
|
| 260 |
+
y_true_val: np.ndarray,
|
| 261 |
+
mc_samples_val: np.ndarray,
|
| 262 |
+
y_true_test: np.ndarray,
|
| 263 |
+
mc_samples_test: np.ndarray,
|
| 264 |
+
levels: tuple[float, ...] = NOMINAL_LEVELS,
|
| 265 |
+
) -> CalibrationReport:
|
| 266 |
+
"""Compare raw MC Dropout vs validation-fit scaled conformal intervals.
|
| 267 |
+
|
| 268 |
+
Parameters
|
| 269 |
+
----------
|
| 270 |
+
y_true_val, mc_samples_val
|
| 271 |
+
Validation ground truth and MC draws (n_draws, n_val).
|
| 272 |
+
y_true_test, mc_samples_test
|
| 273 |
+
Test ground truth and MC draws (n_draws, n_test).
|
| 274 |
+
levels
|
| 275 |
+
Nominal coverage levels to evaluate.
|
| 276 |
+
|
| 277 |
+
Returns
|
| 278 |
+
-------
|
| 279 |
+
CalibrationReport
|
| 280 |
+
"""
|
| 281 |
+
y_val = np.asarray(y_true_val, dtype=np.float64).ravel()
|
| 282 |
+
y_test = np.asarray(y_true_test, dtype=np.float64).ravel()
|
| 283 |
+
mc_val = np.asarray(mc_samples_val, dtype=np.float64)
|
| 284 |
+
mc_test = np.asarray(mc_samples_test, dtype=np.float64)
|
| 285 |
+
|
| 286 |
+
if mc_val.ndim != 2 or mc_val.shape[0] < 2:
|
| 287 |
+
raise ValueError("mc_samples_val must have shape (n_draws, n_val)")
|
| 288 |
+
if mc_test.ndim != 2 or mc_test.shape[0] < 2:
|
| 289 |
+
raise ValueError("mc_samples_test must have shape (n_draws, n_test)")
|
| 290 |
+
if mc_val.shape[1] != y_val.size:
|
| 291 |
+
raise ValueError("mc_samples_val columns must match y_true_val length")
|
| 292 |
+
if mc_test.shape[1] != y_test.size:
|
| 293 |
+
raise ValueError("mc_samples_test columns must match y_true_test length")
|
| 294 |
+
|
| 295 |
+
raw_results: dict[str, IntervalResult] = {}
|
| 296 |
+
scaled_results: dict[str, IntervalResult] = {}
|
| 297 |
+
|
| 298 |
+
for level in levels:
|
| 299 |
+
key = f"{level:.2f}"
|
| 300 |
+
|
| 301 |
+
# Raw MC on test
|
| 302 |
+
raw_lo, raw_hi = _mc_intervals(mc_test, level)
|
| 303 |
+
cov_r, mw_r, mdw_r = _coverage_and_width(y_test, raw_lo, raw_hi)
|
| 304 |
+
raw_results[key] = IntervalResult(
|
| 305 |
+
nominal=level,
|
| 306 |
+
empirical_coverage=cov_r,
|
| 307 |
+
mean_width_kt=mw_r,
|
| 308 |
+
median_width_kt=mdw_r,
|
| 309 |
+
n=y_test.size,
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
# Scaled conformal on test (scale fit on val)
|
| 313 |
+
scale = _fit_conformal_scale(y_val, mc_val, level)
|
| 314 |
+
sc_lo, sc_hi = _scaled_intervals(mc_test, scale, level)
|
| 315 |
+
cov_s, mw_s, mdw_s = _coverage_and_width(y_test, sc_lo, sc_hi)
|
| 316 |
+
scaled_results[key] = IntervalResult(
|
| 317 |
+
nominal=level,
|
| 318 |
+
empirical_coverage=cov_s,
|
| 319 |
+
mean_width_kt=mw_s,
|
| 320 |
+
median_width_kt=mdw_s,
|
| 321 |
+
n=y_test.size,
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
# Aggregate metrics on test set using raw MC
|
| 325 |
+
mace = compute_mace(y_test, mc_test)
|
| 326 |
+
ence = compute_ence(y_test, mc_test)
|
| 327 |
+
rho, pval = compute_spearman(y_test, mc_test)
|
| 328 |
+
|
| 329 |
+
cov_90_raw = raw_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).empirical_coverage
|
| 330 |
+
w_90_raw = raw_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).mean_width_kt
|
| 331 |
+
cov_90_sc = scaled_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).empirical_coverage
|
| 332 |
+
w_90_sc = scaled_results.get("0.90", IntervalResult(0.9, float("nan"), float("nan"), float("nan"), 0)).mean_width_kt
|
| 333 |
+
|
| 334 |
+
return CalibrationReport(
|
| 335 |
+
raw_mc=raw_results,
|
| 336 |
+
scaled_conformal=scaled_results,
|
| 337 |
+
mace=mace,
|
| 338 |
+
ence=ence,
|
| 339 |
+
coverage_90_raw=cov_90_raw,
|
| 340 |
+
width_90_raw_kt=w_90_raw,
|
| 341 |
+
coverage_90_scaled=cov_90_sc,
|
| 342 |
+
width_90_scaled_kt=w_90_sc,
|
| 343 |
+
spearman_rho=rho,
|
| 344 |
+
spearman_p=pval,
|
| 345 |
+
)
|
bundle/src/config.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""YAML config loader. Training and baselines must read hyperparameters from here."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import yaml
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def load_config(path: str | Path) -> dict:
|
| 11 |
+
with Path(path).open(encoding="utf-8") as handle:
|
| 12 |
+
raw = yaml.safe_load(handle)
|
| 13 |
+
if not isinstance(raw, dict):
|
| 14 |
+
raise ValueError("config root must be a mapping")
|
| 15 |
+
return raw
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def parse_image_size(value: object) -> int | None:
|
| 19 |
+
"""Square side to resize to, or None to keep the chip's height and width.
|
| 20 |
+
|
| 21 |
+
``None`` and the string ``native`` do not resize. An integer resizes to
|
| 22 |
+
that square. NASA TorchGeo chips are 366 by 366 and TCIR chips are 201
|
| 23 |
+
by 201; this function does not assume either size and does not download
|
| 24 |
+
imagery.
|
| 25 |
+
"""
|
| 26 |
+
if value is None:
|
| 27 |
+
return None
|
| 28 |
+
if isinstance(value, str):
|
| 29 |
+
text = value.strip().lower()
|
| 30 |
+
if text in {"native", "null", "none"}:
|
| 31 |
+
return None
|
| 32 |
+
if not text:
|
| 33 |
+
raise ValueError("data.image_size is blank")
|
| 34 |
+
try:
|
| 35 |
+
value = int(text)
|
| 36 |
+
except ValueError as exc:
|
| 37 |
+
raise ValueError(
|
| 38 |
+
"data.image_size must be native or a positive integer"
|
| 39 |
+
) from exc
|
| 40 |
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
| 41 |
+
raise ValueError(
|
| 42 |
+
f"data.image_size must be native or a positive integer, got {value!r}"
|
| 43 |
+
)
|
| 44 |
+
size = int(value)
|
| 45 |
+
if size < 1 or float(value) != float(size):
|
| 46 |
+
raise ValueError("data.image_size must be native or a positive integer")
|
| 47 |
+
return size
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def image_sizes_match(left: object, right: object) -> bool:
|
| 51 |
+
"""True when both sides resize to the same square, or both stay native."""
|
| 52 |
+
return parse_image_size(left) == parse_image_size(right)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def checkpoint_path(config: dict, root: str | Path | None = None) -> Path:
|
| 56 |
+
"""Path of the deep-model checkpoint named in ``paths``.
|
| 57 |
+
|
| 58 |
+
``paths.artifacts`` is the directory. ``paths.checkpoint_name`` is a
|
| 59 |
+
file name, not a directory. ``root`` prefixes a relative path.
|
| 60 |
+
"""
|
| 61 |
+
artifacts = Path(config["paths"]["artifacts"])
|
| 62 |
+
name = str(config["paths"]["checkpoint_name"])
|
| 63 |
+
if not name or name != Path(name).name:
|
| 64 |
+
raise ValueError("paths.checkpoint_name must be a file name, not a path")
|
| 65 |
+
path = artifacts / name
|
| 66 |
+
if root is not None and not path.is_absolute():
|
| 67 |
+
path = Path(root) / path
|
| 68 |
+
return path
|
bundle/src/data_loader.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Manifest loading. Image paths are relative to the manifest directory."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from PIL import Image
|
| 10 |
+
|
| 11 |
+
from src.preprocessing import (
|
| 12 |
+
MAX_MISSING_FRACTION,
|
| 13 |
+
NormStats,
|
| 14 |
+
prepare_image,
|
| 15 |
+
stack_prepared,
|
| 16 |
+
)
|
| 17 |
+
from src.schema import require_valid
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def load_manifest(path: str | Path) -> pd.DataFrame:
|
| 21 |
+
frame = pd.read_csv(path)
|
| 22 |
+
return require_valid(frame)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def resolve_image(manifest_path: str | Path, image_path: str) -> Path:
|
| 26 |
+
candidate = Path(image_path)
|
| 27 |
+
if candidate.is_absolute():
|
| 28 |
+
return candidate
|
| 29 |
+
return Path(manifest_path).parent / candidate
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def load_image(path: str | Path) -> np.ndarray:
|
| 33 |
+
file_path = Path(path)
|
| 34 |
+
if not file_path.is_file():
|
| 35 |
+
raise FileNotFoundError(file_path)
|
| 36 |
+
if file_path.suffix == ".npy":
|
| 37 |
+
return np.load(file_path)
|
| 38 |
+
return np.asarray(Image.open(file_path), dtype=np.float32)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def apply_frame_cache(
|
| 42 |
+
frame: pd.DataFrame, dataset: str, cache_root: str | Path | None
|
| 43 |
+
) -> pd.DataFrame:
|
| 44 |
+
"""Point rows at cached fp16 ``.npy`` files when that dataset's index exists.
|
| 45 |
+
|
| 46 |
+
A missing cache leaves ``image_path`` unchanged. A sample that is not
|
| 47 |
+
in the index, or whose file is gone, keeps its source path.
|
| 48 |
+
"""
|
| 49 |
+
if cache_root in (None, "", "null"):
|
| 50 |
+
return frame
|
| 51 |
+
index = Path(cache_root) / str(dataset).strip().lower() / "index.csv"
|
| 52 |
+
if not index.is_file():
|
| 53 |
+
return frame
|
| 54 |
+
cached = pd.read_csv(index)
|
| 55 |
+
if "sample_id" not in cached.columns or "cache_path" not in cached.columns:
|
| 56 |
+
raise ValueError(f"frame cache index {index} needs sample_id and cache_path")
|
| 57 |
+
mapping = {
|
| 58 |
+
str(sample): str(path)
|
| 59 |
+
for sample, path in zip(cached["sample_id"], cached["cache_path"], strict=False)
|
| 60 |
+
}
|
| 61 |
+
out = frame.copy()
|
| 62 |
+
paths: list[str] = []
|
| 63 |
+
replaced = 0
|
| 64 |
+
for sample_id, image_path in zip(out["sample_id"].astype(str), out["image_path"].astype(str)):
|
| 65 |
+
candidate = mapping.get(sample_id)
|
| 66 |
+
if candidate and Path(candidate).is_file():
|
| 67 |
+
paths.append(str(Path(candidate).resolve()))
|
| 68 |
+
if paths[-1] != str(Path(image_path).resolve()):
|
| 69 |
+
replaced += 1
|
| 70 |
+
else:
|
| 71 |
+
paths.append(image_path)
|
| 72 |
+
out["image_path"] = paths
|
| 73 |
+
if replaced:
|
| 74 |
+
print(f"{dataset} frame cache supplied {replaced} fp16 frames from {index}")
|
| 75 |
+
return out
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def prepare_split(
|
| 79 |
+
frame: pd.DataFrame,
|
| 80 |
+
manifest_path: str | Path,
|
| 81 |
+
split: str,
|
| 82 |
+
image_size: int | str | None,
|
| 83 |
+
stats: NormStats | None,
|
| 84 |
+
max_missing_fraction: float = MAX_MISSING_FRACTION,
|
| 85 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 86 |
+
"""Load one split. ``stats`` must already have been fit on train.
|
| 87 |
+
|
| 88 |
+
``image_size`` comes from ``data.image_size``. ``native`` keeps each
|
| 89 |
+
chip's height and width, and those chips must already share a shape.
|
| 90 |
+
"""
|
| 91 |
+
rows = frame[frame["split"] == split]
|
| 92 |
+
images = []
|
| 93 |
+
winds = []
|
| 94 |
+
for row in rows.itertuples(index=False):
|
| 95 |
+
path = resolve_image(manifest_path, row.image_path)
|
| 96 |
+
images.append(
|
| 97 |
+
prepare_image(load_image(path), image_size, stats, max_missing_fraction)
|
| 98 |
+
)
|
| 99 |
+
winds.append(float(row.wind_speed_kt))
|
| 100 |
+
if not images:
|
| 101 |
+
raise ValueError(f"split {split} has no rows")
|
| 102 |
+
return stack_prepared(images), np.asarray(winds, dtype=np.float32)
|
bundle/src/device.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Device selection and mixed precision for native PyTorch.
|
| 2 |
+
|
| 3 |
+
The order is XPU, then CUDA, then CPU. XPU means ``torch.xpu`` in an
|
| 4 |
+
official PyTorch build (2.5 or newer; 2.15 is the pinned Windows wheel).
|
| 5 |
+
This module does not import or call the archived IPEX package.
|
| 6 |
+
|
| 7 |
+
``CLOUDIE_ALLOW_GPU=1`` is required for XPU and CUDA alike. An explicit
|
| 8 |
+
accelerator without that gate is refused. Auto falls back to CPU and
|
| 9 |
+
logs the reason. CPU stays fp32. CUDA fp16 is the only path that uses
|
| 10 |
+
GradScaler. XPU uses bf16 autocast when native bf16 is supported, and
|
| 11 |
+
fp32 otherwise. ``cudnn.benchmark`` is not enabled.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import inspect
|
| 17 |
+
import logging
|
| 18 |
+
import math
|
| 19 |
+
import os
|
| 20 |
+
from collections.abc import Iterator
|
| 21 |
+
from contextlib import contextmanager, nullcontext
|
| 22 |
+
from dataclasses import dataclass
|
| 23 |
+
|
| 24 |
+
LOGGER = logging.getLogger("src.device")
|
| 25 |
+
|
| 26 |
+
DEVICE_CHOICES = ("auto", "xpu", "cuda", "cpu")
|
| 27 |
+
GPU_DEVICES = ("xpu", "cuda")
|
| 28 |
+
GPU_GATE = "CLOUDIE_ALLOW_GPU"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _torch():
|
| 32 |
+
import torch
|
| 33 |
+
|
| 34 |
+
return torch
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def accelerator_available(torch_module, name: str) -> bool:
|
| 38 |
+
"""True when this torch build can see ``name``. Missing XPU attributes are false."""
|
| 39 |
+
if name == "cpu":
|
| 40 |
+
return True
|
| 41 |
+
if name == "xpu":
|
| 42 |
+
xpu = getattr(torch_module, "xpu", None)
|
| 43 |
+
checker = getattr(xpu, "is_available", None) if xpu is not None else None
|
| 44 |
+
if not callable(checker):
|
| 45 |
+
return False
|
| 46 |
+
try:
|
| 47 |
+
return bool(checker())
|
| 48 |
+
except Exception:
|
| 49 |
+
return False
|
| 50 |
+
if name == "cuda":
|
| 51 |
+
try:
|
| 52 |
+
return bool(torch_module.cuda.is_available())
|
| 53 |
+
except Exception:
|
| 54 |
+
return False
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def xpu_native_bf16(torch_module) -> bool:
|
| 59 |
+
"""True when native XPU bf16 is supported.
|
| 60 |
+
|
| 61 |
+
Uses ``torch.xpu.is_bf16_supported(including_emulation=False)`` when
|
| 62 |
+
that parameter exists, so emulated bf16 does not select the autocast
|
| 63 |
+
path. Older builds without the function, or whose call fails, stay
|
| 64 |
+
on fp32. A build that has the function but not the parameter is
|
| 65 |
+
called with no arguments.
|
| 66 |
+
"""
|
| 67 |
+
xpu = getattr(torch_module, "xpu", None)
|
| 68 |
+
checker = getattr(xpu, "is_bf16_supported", None) if xpu is not None else None
|
| 69 |
+
if not callable(checker):
|
| 70 |
+
return False
|
| 71 |
+
try:
|
| 72 |
+
parameters = inspect.signature(checker).parameters
|
| 73 |
+
has_kwarg = "including_emulation" in parameters
|
| 74 |
+
except (TypeError, ValueError):
|
| 75 |
+
has_kwarg = False
|
| 76 |
+
try:
|
| 77 |
+
if has_kwarg:
|
| 78 |
+
return bool(checker(including_emulation=False))
|
| 79 |
+
return bool(checker())
|
| 80 |
+
except TypeError:
|
| 81 |
+
try:
|
| 82 |
+
return bool(checker())
|
| 83 |
+
except Exception:
|
| 84 |
+
return False
|
| 85 |
+
except Exception:
|
| 86 |
+
return False
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@dataclass(frozen=True)
|
| 90 |
+
class AmpPolicy:
|
| 91 |
+
"""How one device runs the forward and the backward."""
|
| 92 |
+
|
| 93 |
+
precision: str
|
| 94 |
+
autocast_device: str | None
|
| 95 |
+
dtype: object | None
|
| 96 |
+
use_grad_scaler: bool
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def amp_policy_for(device, torch_module=None) -> AmpPolicy:
|
| 100 |
+
"""fp16+GradScaler on CUDA, native bf16 on XPU, fp32 everywhere else.
|
| 101 |
+
|
| 102 |
+
GradScaler is never constructed for XPU or CPU. A missing native bf16
|
| 103 |
+
on XPU falls back to fp32 with no autocast.
|
| 104 |
+
"""
|
| 105 |
+
torch_module = torch_module or _torch()
|
| 106 |
+
kind = device.type if hasattr(device, "type") else str(device)
|
| 107 |
+
if kind == "cuda":
|
| 108 |
+
return AmpPolicy("fp16", "cuda", torch_module.float16, True)
|
| 109 |
+
if kind == "xpu":
|
| 110 |
+
if xpu_native_bf16(torch_module):
|
| 111 |
+
return AmpPolicy("bf16", "xpu", torch_module.bfloat16, False)
|
| 112 |
+
return AmpPolicy("fp32", None, None, False)
|
| 113 |
+
return AmpPolicy("fp32", None, None, False)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@contextmanager
|
| 117 |
+
def autocast_context(policy: AmpPolicy) -> Iterator[None]:
|
| 118 |
+
"""Enter ``torch.autocast`` for the policy, or do nothing for fp32."""
|
| 119 |
+
if policy.autocast_device is None or policy.dtype is None:
|
| 120 |
+
with nullcontext():
|
| 121 |
+
yield
|
| 122 |
+
return
|
| 123 |
+
torch_module = _torch()
|
| 124 |
+
with torch_module.autocast(policy.autocast_device, dtype=policy.dtype):
|
| 125 |
+
yield
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def make_grad_scaler(policy: AmpPolicy):
|
| 129 |
+
"""A CUDA fp16 GradScaler, or None. XPU and CPU never get one."""
|
| 130 |
+
if not policy.use_grad_scaler:
|
| 131 |
+
return None
|
| 132 |
+
if policy.precision != "fp16" or policy.autocast_device != "cuda":
|
| 133 |
+
raise RuntimeError("GradScaler is used only for cuda fp16")
|
| 134 |
+
torch_module = _torch()
|
| 135 |
+
scaler_cls = getattr(getattr(torch_module, "amp", None), "GradScaler", None)
|
| 136 |
+
if scaler_cls is not None:
|
| 137 |
+
try:
|
| 138 |
+
return scaler_cls("cuda")
|
| 139 |
+
except TypeError:
|
| 140 |
+
pass
|
| 141 |
+
return torch_module.cuda.amp.GradScaler()
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def resolve_device(name: str):
|
| 145 |
+
"""Pick a ``torch.device``. Auto order is xpu, cuda, cpu.
|
| 146 |
+
|
| 147 |
+
Explicit xpu or cuda without ``CLOUDIE_ALLOW_GPU=1`` raises. Auto
|
| 148 |
+
that would have picked an accelerator falls back to cpu and logs why.
|
| 149 |
+
"""
|
| 150 |
+
choice = str(name).strip().lower()
|
| 151 |
+
if choice not in DEVICE_CHOICES:
|
| 152 |
+
raise ValueError("device must be auto, xpu, cuda, or cpu")
|
| 153 |
+
torch_module = _torch()
|
| 154 |
+
if choice == "auto":
|
| 155 |
+
if accelerator_available(torch_module, "xpu"):
|
| 156 |
+
picked = "xpu"
|
| 157 |
+
elif accelerator_available(torch_module, "cuda"):
|
| 158 |
+
picked = "cuda"
|
| 159 |
+
else:
|
| 160 |
+
picked = "cpu"
|
| 161 |
+
if picked != "cpu" and os.environ.get(GPU_GATE) != "1":
|
| 162 |
+
message = (
|
| 163 |
+
f"Refusing auto-picked device {picked} because {GPU_GATE} is not 1. "
|
| 164 |
+
"Falling back to cpu. An XPU or GPU run needs misty wind's approval. "
|
| 165 |
+
f"Set {GPU_GATE}=1 only after that approval."
|
| 166 |
+
)
|
| 167 |
+
LOGGER.warning(message)
|
| 168 |
+
print(message)
|
| 169 |
+
return torch_module.device("cpu")
|
| 170 |
+
choice = picked
|
| 171 |
+
if choice in GPU_DEVICES and os.environ.get(GPU_GATE) != "1":
|
| 172 |
+
raise RuntimeError(
|
| 173 |
+
f"Refusing device {choice}. An XPU or GPU run needs misty wind's approval. "
|
| 174 |
+
f"Set {GPU_GATE}=1 only after that approval."
|
| 175 |
+
)
|
| 176 |
+
if choice == "xpu" and not accelerator_available(torch_module, "xpu"):
|
| 177 |
+
raise RuntimeError("device xpu was approved but XPU is not available")
|
| 178 |
+
if choice == "cuda" and not accelerator_available(torch_module, "cuda"):
|
| 179 |
+
raise RuntimeError("device cuda was approved but CUDA is not available")
|
| 180 |
+
try:
|
| 181 |
+
return torch_module.device(choice)
|
| 182 |
+
except RuntimeError as exc:
|
| 183 |
+
raise RuntimeError(f"device {choice} is not supported by this torch build") from exc
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def reset_peak_memory(device) -> None:
|
| 187 |
+
"""Clear the allocator peak for the device that tracks it. CPU is a no-op."""
|
| 188 |
+
torch_module = _torch()
|
| 189 |
+
if getattr(device, "type", None) == "cuda":
|
| 190 |
+
reset = getattr(torch_module.cuda, "reset_peak_memory_stats", None)
|
| 191 |
+
if callable(reset):
|
| 192 |
+
try:
|
| 193 |
+
reset()
|
| 194 |
+
except Exception:
|
| 195 |
+
return
|
| 196 |
+
if getattr(device, "type", None) == "xpu":
|
| 197 |
+
xpu = getattr(torch_module, "xpu", None)
|
| 198 |
+
reset = getattr(xpu, "reset_peak_memory_stats", None) if xpu is not None else None
|
| 199 |
+
if callable(reset):
|
| 200 |
+
try:
|
| 201 |
+
reset()
|
| 202 |
+
except Exception:
|
| 203 |
+
return
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def peak_memory_bytes(device) -> int | None:
|
| 207 |
+
"""Peak bytes from XPU or CUDA, or null when the device does not report it.
|
| 208 |
+
|
| 209 |
+
XPU peak memory is trustworthy on the torch 2.15 line. Older builds
|
| 210 |
+
may return a number that is not the true peak; the value is still
|
| 211 |
+
whatever ``max_memory_allocated`` reports.
|
| 212 |
+
"""
|
| 213 |
+
torch_module = _torch()
|
| 214 |
+
kind = getattr(device, "type", None)
|
| 215 |
+
if kind == "xpu":
|
| 216 |
+
xpu = getattr(torch_module, "xpu", None)
|
| 217 |
+
reader = getattr(xpu, "max_memory_allocated", None) if xpu is not None else None
|
| 218 |
+
if not callable(reader):
|
| 219 |
+
return None
|
| 220 |
+
try:
|
| 221 |
+
return int(reader())
|
| 222 |
+
except Exception:
|
| 223 |
+
return None
|
| 224 |
+
if kind == "cuda":
|
| 225 |
+
reader = getattr(torch_module.cuda, "max_memory_allocated", None)
|
| 226 |
+
if not callable(reader):
|
| 227 |
+
return None
|
| 228 |
+
try:
|
| 229 |
+
return int(reader())
|
| 230 |
+
except Exception:
|
| 231 |
+
return None
|
| 232 |
+
return None
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _jsonable(value):
|
| 236 |
+
if value is None or isinstance(value, (str, int, float, bool)):
|
| 237 |
+
if isinstance(value, float) and not math.isfinite(value):
|
| 238 |
+
return None
|
| 239 |
+
return value
|
| 240 |
+
if isinstance(value, (list, tuple)):
|
| 241 |
+
return [_jsonable(item) for item in value]
|
| 242 |
+
return str(value)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def xpu_device_properties(device) -> dict | None:
|
| 246 |
+
"""``torch.xpu.get_device_properties`` as a JSON object, or null off XPU."""
|
| 247 |
+
if getattr(device, "type", None) != "xpu":
|
| 248 |
+
return None
|
| 249 |
+
torch_module = _torch()
|
| 250 |
+
xpu = getattr(torch_module, "xpu", None)
|
| 251 |
+
getter = getattr(xpu, "get_device_properties", None) if xpu is not None else None
|
| 252 |
+
if not callable(getter):
|
| 253 |
+
return None
|
| 254 |
+
index = 0
|
| 255 |
+
current = getattr(xpu, "current_device", None)
|
| 256 |
+
if callable(current):
|
| 257 |
+
try:
|
| 258 |
+
index = int(current())
|
| 259 |
+
except Exception:
|
| 260 |
+
index = 0
|
| 261 |
+
try:
|
| 262 |
+
props = getter(index)
|
| 263 |
+
except Exception:
|
| 264 |
+
return None
|
| 265 |
+
if hasattr(props, "_asdict"):
|
| 266 |
+
raw = dict(props._asdict())
|
| 267 |
+
else:
|
| 268 |
+
raw = {}
|
| 269 |
+
for key in dir(props):
|
| 270 |
+
if key.startswith("_"):
|
| 271 |
+
continue
|
| 272 |
+
try:
|
| 273 |
+
value = getattr(props, key)
|
| 274 |
+
except Exception:
|
| 275 |
+
continue
|
| 276 |
+
if callable(value):
|
| 277 |
+
continue
|
| 278 |
+
raw[key] = value
|
| 279 |
+
return {str(key): _jsonable(value) for key, value in raw.items()}
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def parity_verdict(
|
| 283 |
+
output_max_abs: float,
|
| 284 |
+
loss_max_abs: float,
|
| 285 |
+
tolerance: float,
|
| 286 |
+
reference_scale: float,
|
| 287 |
+
) -> dict:
|
| 288 |
+
"""Decide whether a device-versus-CPU gap is inside the tolerance.
|
| 289 |
+
|
| 290 |
+
``tolerance`` is a fraction. The allowed absolute gap is
|
| 291 |
+
``tolerance * max(1, reference_scale)``. The floor of 1 keeps a small
|
| 292 |
+
bf16-versus-fp32 drift from failing when the CPU output is near zero.
|
| 293 |
+
A larger wind head may move by that fraction of its magnitude.
|
| 294 |
+
This does not convert physical units. It only compares two forwards.
|
| 295 |
+
"""
|
| 296 |
+
if isinstance(tolerance, bool) or not isinstance(tolerance, (int, float)):
|
| 297 |
+
raise ValueError("device_parity_tol must be a finite number >= 0")
|
| 298 |
+
if not math.isfinite(float(tolerance)) or float(tolerance) < 0:
|
| 299 |
+
raise ValueError("device_parity_tol must be a finite number >= 0")
|
| 300 |
+
output = float(output_max_abs)
|
| 301 |
+
loss = float(loss_max_abs)
|
| 302 |
+
if not math.isfinite(output) or not math.isfinite(loss):
|
| 303 |
+
worst = float("inf")
|
| 304 |
+
else:
|
| 305 |
+
worst = max(output, loss)
|
| 306 |
+
scale = float(reference_scale)
|
| 307 |
+
if not math.isfinite(scale) or scale < 1.0:
|
| 308 |
+
scale = 1.0
|
| 309 |
+
limit = float(tolerance) * scale
|
| 310 |
+
return {
|
| 311 |
+
"output_max_abs": output,
|
| 312 |
+
"loss_max_abs": loss,
|
| 313 |
+
"max_abs_diff": worst,
|
| 314 |
+
"reference_scale": scale,
|
| 315 |
+
"tolerance": float(tolerance),
|
| 316 |
+
"limit": limit,
|
| 317 |
+
"ok": bool(worst <= limit),
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def warn_if_parity_failed(result: dict) -> None:
|
| 322 |
+
"""Loud warning when the seeded forward disagrees. Training still continues."""
|
| 323 |
+
if result.get("ok"):
|
| 324 |
+
return
|
| 325 |
+
message = (
|
| 326 |
+
"WARNING: device parity check failed. "
|
| 327 |
+
f"max abs diff {result['max_abs_diff']:.6g} exceeds limit {result['limit']:.6g} "
|
| 328 |
+
f"(tolerance {result['tolerance']:.6g}, scale {result['reference_scale']:.6g}). "
|
| 329 |
+
"device_parity_ok is false. Training continues. This is not a forecast."
|
| 330 |
+
)
|
| 331 |
+
LOGGER.warning(message)
|
| 332 |
+
print(message)
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def seeded_parity_batch(batch_size: int, channels: int, side: int, seed: int = 0, n_frames: int = 1):
|
| 336 |
+
"""One fixed CPU batch. The same tensors are copied onto the device."""
|
| 337 |
+
torch_module = _torch()
|
| 338 |
+
generator = torch_module.Generator(device="cpu")
|
| 339 |
+
generator.manual_seed(int(seed))
|
| 340 |
+
if n_frames > 1:
|
| 341 |
+
images = torch_module.randn(
|
| 342 |
+
int(batch_size), int(n_frames), int(channels), int(side), int(side), generator=generator
|
| 343 |
+
)
|
| 344 |
+
else:
|
| 345 |
+
images = torch_module.randn(
|
| 346 |
+
int(batch_size), int(channels), int(side), int(side), generator=generator
|
| 347 |
+
)
|
| 348 |
+
winds = torch_module.rand(int(batch_size), 1, generator=generator)
|
| 349 |
+
return images, winds
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def _forward_wind_loss(model, images, winds):
|
| 353 |
+
import torch.nn.functional as F
|
| 354 |
+
|
| 355 |
+
torch_module = _torch()
|
| 356 |
+
was_training = model.training
|
| 357 |
+
model.eval()
|
| 358 |
+
try:
|
| 359 |
+
with torch_module.no_grad():
|
| 360 |
+
output = model(images)
|
| 361 |
+
wind = output[0] if isinstance(output, tuple) else output
|
| 362 |
+
loss = F.smooth_l1_loss(wind.float().view(-1), winds.float().view(-1))
|
| 363 |
+
return wind.detach().float().cpu(), loss.detach().float().cpu()
|
| 364 |
+
finally:
|
| 365 |
+
model.train(was_training)
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def compare_model_parity(model, images, winds, device, tolerance: float, *, policy=None) -> dict:
|
| 369 |
+
"""Run one forward on ``device`` and on CPU. Record the max absolute gap.
|
| 370 |
+
|
| 371 |
+
The training model is copied. Its weights are not updated. The device
|
| 372 |
+
copy uses the same autocast policy as training when one is passed.
|
| 373 |
+
"""
|
| 374 |
+
import copy
|
| 375 |
+
|
| 376 |
+
cpu_model = copy.deepcopy(model).to("cpu").eval()
|
| 377 |
+
device_model = copy.deepcopy(model).to(device).eval()
|
| 378 |
+
cpu_wind, cpu_loss = _forward_wind_loss(cpu_model, images, winds)
|
| 379 |
+
if policy is None:
|
| 380 |
+
policy = amp_policy_for(device)
|
| 381 |
+
with autocast_context(policy):
|
| 382 |
+
dev_wind, dev_loss = _forward_wind_loss(
|
| 383 |
+
device_model, images.to(device), winds.to(device)
|
| 384 |
+
)
|
| 385 |
+
output_diff = float((dev_wind - cpu_wind).abs().max())
|
| 386 |
+
loss_diff = abs(float(dev_loss) - float(cpu_loss))
|
| 387 |
+
scale = max(1.0, float(cpu_wind.abs().max()), abs(float(cpu_loss)))
|
| 388 |
+
result = parity_verdict(output_diff, loss_diff, float(tolerance), scale)
|
| 389 |
+
warn_if_parity_failed(result)
|
| 390 |
+
return result
|
bundle/src/evaluate.py
ADDED
|
@@ -0,0 +1,1218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Held-out intensity scores for supplied wind predictions.
|
| 2 |
+
|
| 3 |
+
Bins are our own grouping, IMD-style names at 17/34/48/64/91 kt. VSCS and
|
| 4 |
+
ESCS/SuCS are always reported. IMD class definitions use 3-minute winds.
|
| 5 |
+
NASA HURDAT2 labels are 1-minute winds. ``wind_averaging`` is stored on the
|
| 6 |
+
report (for example ``1min`` for NASA) and mixed periods are refused. This
|
| 7 |
+
module does not convert one averaging period into another.
|
| 8 |
+
|
| 9 |
+
The evaluated storms are the test side of ``storm_ids_by_split``. Pixel
|
| 10 |
+
normalization uses ``fit_split_normalization`` (defined on ``src.train``,
|
| 11 |
+
which already calls the splits helper; ``cloudie.train`` re-exports it).
|
| 12 |
+
Mean, ridge, and persistence reuse ``src.baselines``. Persistence is a
|
| 13 |
+
reference baseline (``src.baselines.persistence_predictions``): the previous
|
| 14 |
+
frame's best-track label, not the imagery. Image-only models cannot be
|
| 15 |
+
compared against it.
|
| 16 |
+
|
| 17 |
+
Monte Carlo dropout coverage reads a NumPy array of draws. This module does
|
| 18 |
+
not import torch. Residual-quantile widths are fit on validation storms and
|
| 19 |
+
scored on test storms. A coverage gap larger than the tolerance is labeled
|
| 20 |
+
``uncalibrated``. ``quote_as_result`` stays ``no``. This is not a forecast
|
| 21 |
+
and not an operational-readiness claim.
|
| 22 |
+
|
| 23 |
+
``intensity_class_evaluation`` scores regression predictions on the
|
| 24 |
+
validation split only. It reports RMSE, MAE, and bias (prediction minus
|
| 25 |
+
true wind) overall and in each project intensity bin, with row counts,
|
| 26 |
+
distinct storm counts, and 95% percentile intervals from a bootstrap that
|
| 27 |
+
resamples storm IDs. Test rows are refused. A ``wind_averaging`` column is
|
| 28 |
+
copied through and grouped when it is present. An ``on_fix`` column, when
|
| 29 |
+
present, adds the same table on rows whose label sits on a best-track fix.
|
| 30 |
+
Classes with fewer than 3 storms are marked indicative. ``evaluate`` still
|
| 31 |
+
scores the test storms with point metrics and does not run this bootstrap
|
| 32 |
+
on them.
|
| 33 |
+
|
| 34 |
+
Checkpoint scoring stays in ``cloudie.evaluate``.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
from __future__ import annotations
|
| 38 |
+
|
| 39 |
+
import argparse
|
| 40 |
+
import json
|
| 41 |
+
import os
|
| 42 |
+
from pathlib import Path
|
| 43 |
+
from typing import Sequence
|
| 44 |
+
|
| 45 |
+
os.environ.setdefault("MPLBACKEND", "Agg")
|
| 46 |
+
|
| 47 |
+
import numpy as np
|
| 48 |
+
import pandas as pd
|
| 49 |
+
|
| 50 |
+
from src.baselines import baseline_params, fit_numeric_pipeline, persistence_predictions
|
| 51 |
+
from src.config import load_config
|
| 52 |
+
from src.features import model_matrix
|
| 53 |
+
from src.metrics import (
|
| 54 |
+
mean_baseline,
|
| 55 |
+
metrics_by_class,
|
| 56 |
+
regression_metrics,
|
| 57 |
+
storm_bootstrap_metrics,
|
| 58 |
+
)
|
| 59 |
+
from src.plots import save_regression_scatter
|
| 60 |
+
from src.schema import (
|
| 61 |
+
DEFAULT_EDGES_KT,
|
| 62 |
+
DEFAULT_NAMES,
|
| 63 |
+
recorded_wind_averaging,
|
| 64 |
+
require_valid,
|
| 65 |
+
wind_to_imd5,
|
| 66 |
+
)
|
| 67 |
+
from src.splits import (
|
| 68 |
+
LeakageError,
|
| 69 |
+
assert_no_forbidden_inputs,
|
| 70 |
+
assign_storms,
|
| 71 |
+
storm_ids_by_split,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
BINNING_LABEL = "our own grouping, IMD-style names"
|
| 75 |
+
INDICATIVE_STATUS = "indicative (n_storms<3)"
|
| 76 |
+
_SMALL_CLASS_STORMS = 3
|
| 77 |
+
_ON_FIX_TRUE = frozenset({"1", "true", "yes", "y", "t"})
|
| 78 |
+
_ON_FIX_FALSE = frozenset({"0", "false", "no", "n", "f"})
|
| 79 |
+
_CLASS_TABLE_COLUMNS = (
|
| 80 |
+
"wind_averaging",
|
| 81 |
+
"subset",
|
| 82 |
+
"row_kind",
|
| 83 |
+
"intensity_class",
|
| 84 |
+
"storm_id",
|
| 85 |
+
"n_rows",
|
| 86 |
+
"n_storms",
|
| 87 |
+
"rmse_kt",
|
| 88 |
+
"mae_kt",
|
| 89 |
+
"bias_kt",
|
| 90 |
+
"rmse_kt_ci_low",
|
| 91 |
+
"rmse_kt_ci_high",
|
| 92 |
+
"mae_kt_ci_low",
|
| 93 |
+
"mae_kt_ci_high",
|
| 94 |
+
"bias_kt_ci_low",
|
| 95 |
+
"bias_kt_ci_high",
|
| 96 |
+
"ci_level",
|
| 97 |
+
"n_resamples",
|
| 98 |
+
"seed",
|
| 99 |
+
"resample",
|
| 100 |
+
"status",
|
| 101 |
+
)
|
| 102 |
+
HIGHLIGHT_CODES = ("VSCS", "ESCS_SUCS")
|
| 103 |
+
HIGHLIGHT_DISPLAY = {"VSCS": "VSCS", "ESCS_SUCS": "ESCS/SuCS"}
|
| 104 |
+
WIND_AVERAGING_NOTE = (
|
| 105 |
+
"IMD class definitions use 3-minute winds. "
|
| 106 |
+
"NASA HURDAT2 labels are 1-minute winds and can be recorded as "
|
| 107 |
+
"wind_averaging='1min'. This report stores the period it was given "
|
| 108 |
+
"and does not convert between averaging periods."
|
| 109 |
+
)
|
| 110 |
+
BANNER = (
|
| 111 |
+
"Software check only. Do not quote these numbers as experimental results. "
|
| 112 |
+
"Bins are our own grouping, IMD-style names. "
|
| 113 |
+
"IMD class definitions use 3-minute winds. NASA HURDAT2 labels are "
|
| 114 |
+
"1-minute winds. wind_averaging is recorded and is not converted. "
|
| 115 |
+
"Monte Carlo dropout coverage is not a calibrated forecast interval. "
|
| 116 |
+
"Residual-quantile intervals are labeled uncalibrated when held-out "
|
| 117 |
+
"coverage misses the nominal level by more than the tolerance. "
|
| 118 |
+
"This is not a forecast, a warning, or an operational-readiness claim."
|
| 119 |
+
)
|
| 120 |
+
_EMPTY_METRICS = {"n": 0.0, "mae_kt": None, "rmse_kt": None, "bias_kt": None}
|
| 121 |
+
_LEVELS = (0.80, 0.90)
|
| 122 |
+
_TOLERANCE = 0.05
|
| 123 |
+
# Float slack so a gap that lands on the tolerance is not marked uncalibrated.
|
| 124 |
+
_GAP_SLACK = 1e-9
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _pyplot():
|
| 128 |
+
import matplotlib
|
| 129 |
+
|
| 130 |
+
matplotlib.use("Agg", force=True)
|
| 131 |
+
import matplotlib.pyplot as plt
|
| 132 |
+
|
| 133 |
+
return plt
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _level_key(level: float) -> str:
|
| 137 |
+
return f"{float(level):.2f}"
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _check_levels(levels: Sequence[float]) -> tuple[float, ...]:
|
| 141 |
+
values = tuple(float(level) for level in levels)
|
| 142 |
+
if not values:
|
| 143 |
+
raise ValueError("at least one nominal coverage level is required")
|
| 144 |
+
for level in values:
|
| 145 |
+
if not 0.0 < level < 1.0:
|
| 146 |
+
raise ValueError(f"coverage level must be between 0 and 1, got {level}")
|
| 147 |
+
return values
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def interval_status(empirical: float, nominal: float, tolerance: float) -> str:
|
| 151 |
+
"""Label an interval ``uncalibrated`` when coverage misses by more than ``tolerance``."""
|
| 152 |
+
if tolerance < 0:
|
| 153 |
+
raise ValueError("coverage tolerance must be non-negative")
|
| 154 |
+
gap = abs(float(empirical) - float(nominal))
|
| 155 |
+
if gap > float(tolerance) + _GAP_SLACK:
|
| 156 |
+
return "uncalibrated"
|
| 157 |
+
return "within_tolerance"
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _bin_spec(config: dict) -> tuple[tuple[float, ...], tuple[str, ...]]:
|
| 161 |
+
data = dict(config.get("data") or {})
|
| 162 |
+
edges = tuple(float(edge) for edge in data.get("imd5_edges_kt", DEFAULT_EDGES_KT))
|
| 163 |
+
names = tuple(str(name) for name in data.get("imd5_names", DEFAULT_NAMES))
|
| 164 |
+
if len(edges) != len(names) or not edges:
|
| 165 |
+
raise ValueError("intensity edges and names must be non-empty and the same length")
|
| 166 |
+
return edges, names
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def assign_bins(
|
| 170 |
+
winds: np.ndarray,
|
| 171 |
+
edges: Sequence[float] = DEFAULT_EDGES_KT,
|
| 172 |
+
names: Sequence[str] = DEFAULT_NAMES,
|
| 173 |
+
) -> np.ndarray:
|
| 174 |
+
"""Project target wind onto our own grouping, IMD-style names.
|
| 175 |
+
|
| 176 |
+
Winds below the first edge are None. The names are not a warning product.
|
| 177 |
+
"""
|
| 178 |
+
edge_tuple = tuple(float(edge) for edge in edges)
|
| 179 |
+
name_tuple = tuple(str(name) for name in names)
|
| 180 |
+
values = np.asarray(winds, dtype=np.float64).ravel()
|
| 181 |
+
return np.asarray(
|
| 182 |
+
[wind_to_imd5(float(wind), edge_tuple, name_tuple) for wind in values],
|
| 183 |
+
dtype=object,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _empty_metrics() -> dict[str, float | None]:
|
| 188 |
+
return dict(_EMPTY_METRICS)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def _highlight(by_bin: dict[str, dict]) -> dict[str, dict]:
|
| 192 |
+
highlighted: dict[str, dict] = {}
|
| 193 |
+
for code in HIGHLIGHT_CODES:
|
| 194 |
+
metrics = dict(by_bin.get(code) or _empty_metrics())
|
| 195 |
+
metrics["display_name"] = HIGHLIGHT_DISPLAY[code]
|
| 196 |
+
highlighted[code] = metrics
|
| 197 |
+
return highlighted
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def score_winds(
|
| 201 |
+
y_true: np.ndarray,
|
| 202 |
+
y_pred: np.ndarray,
|
| 203 |
+
edges: Sequence[float] = DEFAULT_EDGES_KT,
|
| 204 |
+
names: Sequence[str] = DEFAULT_NAMES,
|
| 205 |
+
) -> dict:
|
| 206 |
+
"""MAE, RMSE, and bias overall and per target-wind bin.
|
| 207 |
+
|
| 208 |
+
Empty bins, including VSCS and ESCS/SuCS when absent, keep null errors.
|
| 209 |
+
A zero error is not invented for an empty bin.
|
| 210 |
+
"""
|
| 211 |
+
truth = np.asarray(y_true, dtype=np.float64).ravel()
|
| 212 |
+
pred = np.asarray(y_pred, dtype=np.float64).ravel()
|
| 213 |
+
if truth.size == 0:
|
| 214 |
+
by_bin = {str(name): _empty_metrics() for name in names}
|
| 215 |
+
for code in HIGHLIGHT_CODES:
|
| 216 |
+
by_bin.setdefault(code, _empty_metrics())
|
| 217 |
+
return {
|
| 218 |
+
"overall": _empty_metrics(),
|
| 219 |
+
"by_bin": by_bin,
|
| 220 |
+
"highlight": _highlight(by_bin),
|
| 221 |
+
"n_below_lowest_edge": 0,
|
| 222 |
+
}
|
| 223 |
+
labels = assign_bins(truth, edges, names)
|
| 224 |
+
found = metrics_by_class(truth, pred, labels)
|
| 225 |
+
by_bin: dict[str, dict] = {}
|
| 226 |
+
for name in tuple(names) + HIGHLIGHT_CODES:
|
| 227 |
+
key = str(name)
|
| 228 |
+
if key in by_bin:
|
| 229 |
+
continue
|
| 230 |
+
by_bin[key] = dict(found[key]) if key in found else _empty_metrics()
|
| 231 |
+
below = int(sum(label is None for label in labels))
|
| 232 |
+
return {
|
| 233 |
+
"overall": regression_metrics(truth, pred),
|
| 234 |
+
"by_bin": by_bin,
|
| 235 |
+
"highlight": _highlight(by_bin),
|
| 236 |
+
"n_below_lowest_edge": below,
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def _missing_label(value: object) -> bool:
|
| 241 |
+
if value is None:
|
| 242 |
+
return True
|
| 243 |
+
try:
|
| 244 |
+
missing = pd.isna(value)
|
| 245 |
+
except (TypeError, ValueError):
|
| 246 |
+
return False
|
| 247 |
+
if missing is True:
|
| 248 |
+
return True
|
| 249 |
+
if isinstance(missing, np.ndarray):
|
| 250 |
+
return False
|
| 251 |
+
return bool(missing)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _parse_on_fix(value: object) -> bool:
|
| 255 |
+
"""Explicit true or false. Null and unrecognized values raise."""
|
| 256 |
+
if isinstance(value, (bool, np.bool_)):
|
| 257 |
+
return bool(value)
|
| 258 |
+
if _missing_label(value):
|
| 259 |
+
raise ValueError("on_fix is null; each row must be an explicit true or false")
|
| 260 |
+
if isinstance(value, str):
|
| 261 |
+
text = value.strip().lower()
|
| 262 |
+
if text in _ON_FIX_TRUE:
|
| 263 |
+
return True
|
| 264 |
+
if text in _ON_FIX_FALSE:
|
| 265 |
+
return False
|
| 266 |
+
raise ValueError(f"on_fix value {value!r} is not an explicit true or false")
|
| 267 |
+
item = getattr(value, "item", None)
|
| 268 |
+
if callable(item) and not isinstance(value, (str, bytes, bool)):
|
| 269 |
+
try:
|
| 270 |
+
unpacked = item()
|
| 271 |
+
except (TypeError, ValueError):
|
| 272 |
+
unpacked = value
|
| 273 |
+
else:
|
| 274 |
+
if type(unpacked) is not type(value):
|
| 275 |
+
return _parse_on_fix(unpacked)
|
| 276 |
+
if isinstance(value, (int, np.integer)) and not isinstance(value, bool):
|
| 277 |
+
if int(value) in (0, 1):
|
| 278 |
+
return bool(int(value))
|
| 279 |
+
raise ValueError(f"on_fix value {value!r} is not an explicit true or false")
|
| 280 |
+
if isinstance(value, float) and value in (0.0, 1.0):
|
| 281 |
+
return bool(value)
|
| 282 |
+
raise ValueError(f"on_fix value {value!r} is not an explicit true or false")
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def _on_fix_mask(values: np.ndarray | None, n_rows: int) -> np.ndarray | None:
|
| 286 |
+
if values is None:
|
| 287 |
+
return None
|
| 288 |
+
raw = np.asarray(values, dtype=object).ravel()
|
| 289 |
+
if raw.size != n_rows:
|
| 290 |
+
raise ValueError("on_fix must align with y_true")
|
| 291 |
+
return np.asarray([_parse_on_fix(value) for value in raw.tolist()], dtype=bool)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def _require_validation_split(splits: np.ndarray, n_rows: int) -> None:
|
| 295 |
+
labels = np.asarray(splits, dtype=object).ravel()
|
| 296 |
+
if labels.size != n_rows:
|
| 297 |
+
raise ValueError("splits must align with y_true")
|
| 298 |
+
refused = sorted({str(value) for value in labels.tolist()} - {"val"})
|
| 299 |
+
if refused:
|
| 300 |
+
raise LeakageError(
|
| 301 |
+
"intensity-class evaluation scores the validation split only; "
|
| 302 |
+
f"refusing {refused}"
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def _class_labels(classes: np.ndarray, n_rows: int) -> np.ndarray:
|
| 307 |
+
raw = np.asarray(classes, dtype=object).ravel()
|
| 308 |
+
if raw.size != n_rows:
|
| 309 |
+
raise ValueError("classes must align with y_true")
|
| 310 |
+
labels = np.empty(n_rows, dtype=object)
|
| 311 |
+
for index, value in enumerate(raw.tolist()):
|
| 312 |
+
labels[index] = None if _missing_label(value) else str(value)
|
| 313 |
+
return labels
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def _averaging_blocks(
|
| 317 |
+
n_rows: int, wind_averaging: np.ndarray | None
|
| 318 |
+
) -> list[tuple[object, np.ndarray]]:
|
| 319 |
+
"""One block when the column is absent. Otherwise group, without converting."""
|
| 320 |
+
if wind_averaging is None:
|
| 321 |
+
return [(None, np.arange(n_rows, dtype=np.int64))]
|
| 322 |
+
raw = np.asarray(wind_averaging, dtype=object).ravel()
|
| 323 |
+
if raw.size != n_rows:
|
| 324 |
+
raise ValueError("wind_averaging must align with y_true")
|
| 325 |
+
order: list[object] = []
|
| 326 |
+
buckets: dict[object, list[int]] = {}
|
| 327 |
+
for index, value in enumerate(raw.tolist()):
|
| 328 |
+
key: object = None if _missing_label(value) else str(value)
|
| 329 |
+
if key not in buckets:
|
| 330 |
+
buckets[key] = []
|
| 331 |
+
order.append(key)
|
| 332 |
+
buckets[key].append(index)
|
| 333 |
+
if not order and n_rows == 0:
|
| 334 |
+
return [(None, np.zeros(0, dtype=np.int64))]
|
| 335 |
+
return [(key, np.asarray(buckets[key], dtype=np.int64)) for key in order]
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def _class_names_in_order(labels: np.ndarray, class_names: Sequence[str]) -> list[str]:
|
| 339 |
+
ordered: list[str] = []
|
| 340 |
+
seen: set[str] = set()
|
| 341 |
+
for name in class_names:
|
| 342 |
+
key = str(name)
|
| 343 |
+
if key not in seen:
|
| 344 |
+
ordered.append(key)
|
| 345 |
+
seen.add(key)
|
| 346 |
+
for label in labels.tolist():
|
| 347 |
+
if label is None or label in seen:
|
| 348 |
+
continue
|
| 349 |
+
ordered.append(str(label))
|
| 350 |
+
seen.add(str(label))
|
| 351 |
+
return ordered
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def _empty_class_metrics(n_resamples: int, seed: int, ci_level: float) -> dict[str, object]:
|
| 355 |
+
return {
|
| 356 |
+
"n_rows": 0,
|
| 357 |
+
"n_storms": 0,
|
| 358 |
+
"rmse_kt": np.nan,
|
| 359 |
+
"mae_kt": np.nan,
|
| 360 |
+
"bias_kt": np.nan,
|
| 361 |
+
"rmse_kt_ci_low": np.nan,
|
| 362 |
+
"rmse_kt_ci_high": np.nan,
|
| 363 |
+
"mae_kt_ci_low": np.nan,
|
| 364 |
+
"mae_kt_ci_high": np.nan,
|
| 365 |
+
"bias_kt_ci_low": np.nan,
|
| 366 |
+
"bias_kt_ci_high": np.nan,
|
| 367 |
+
"ci_level": float(ci_level),
|
| 368 |
+
"n_resamples": int(n_resamples),
|
| 369 |
+
"seed": int(seed),
|
| 370 |
+
"resample": "storm_id",
|
| 371 |
+
"status": "",
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _metric_record(
|
| 376 |
+
truth: np.ndarray,
|
| 377 |
+
pred: np.ndarray,
|
| 378 |
+
storm_ids: np.ndarray,
|
| 379 |
+
*,
|
| 380 |
+
wind_averaging: object,
|
| 381 |
+
subset: str,
|
| 382 |
+
row_kind: str,
|
| 383 |
+
intensity_class: str,
|
| 384 |
+
storm_id: object,
|
| 385 |
+
n_resamples: int,
|
| 386 |
+
seed: int,
|
| 387 |
+
ci_level: float,
|
| 388 |
+
) -> dict[str, object]:
|
| 389 |
+
if truth.size == 0:
|
| 390 |
+
metrics: dict[str, object] = _empty_class_metrics(n_resamples, seed, ci_level)
|
| 391 |
+
else:
|
| 392 |
+
metrics = dict(
|
| 393 |
+
storm_bootstrap_metrics(
|
| 394 |
+
truth,
|
| 395 |
+
pred,
|
| 396 |
+
storm_ids,
|
| 397 |
+
n_resamples=n_resamples,
|
| 398 |
+
seed=seed,
|
| 399 |
+
ci_level=ci_level,
|
| 400 |
+
)
|
| 401 |
+
)
|
| 402 |
+
n_storms = int(metrics["n_storms"])
|
| 403 |
+
metrics["status"] = (
|
| 404 |
+
INDICATIVE_STATUS if 0 < n_storms < _SMALL_CLASS_STORMS else ""
|
| 405 |
+
)
|
| 406 |
+
metrics.update(
|
| 407 |
+
{
|
| 408 |
+
"wind_averaging": np.nan if wind_averaging is None else wind_averaging,
|
| 409 |
+
"subset": subset,
|
| 410 |
+
"row_kind": row_kind,
|
| 411 |
+
"intensity_class": intensity_class,
|
| 412 |
+
"storm_id": np.nan if storm_id is None else storm_id,
|
| 413 |
+
}
|
| 414 |
+
)
|
| 415 |
+
return metrics
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def _storm_ids_in_order(storm_ids: np.ndarray) -> list[str]:
|
| 419 |
+
seen: dict[str, None] = {}
|
| 420 |
+
for storm in np.asarray(storm_ids, dtype=object).ravel().tolist():
|
| 421 |
+
seen.setdefault(str(storm), None)
|
| 422 |
+
return list(seen)
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def intensity_class_evaluation(
|
| 426 |
+
y_true: np.ndarray,
|
| 427 |
+
y_pred: np.ndarray,
|
| 428 |
+
storm_ids: np.ndarray,
|
| 429 |
+
classes: np.ndarray,
|
| 430 |
+
splits: np.ndarray,
|
| 431 |
+
*,
|
| 432 |
+
wind_averaging: np.ndarray | None = None,
|
| 433 |
+
on_fix: np.ndarray | None = None,
|
| 434 |
+
class_names: Sequence[str] = DEFAULT_NAMES,
|
| 435 |
+
n_resamples: int = 1000,
|
| 436 |
+
seed: int = 0,
|
| 437 |
+
ci_level: float = 0.95,
|
| 438 |
+
per_storm_breakdown: bool = True,
|
| 439 |
+
) -> pd.DataFrame:
|
| 440 |
+
"""Validation RMSE, MAE, and bias by this project's intensity bins.
|
| 441 |
+
|
| 442 |
+
Bias is prediction minus true wind. Intervals resample storm IDs. The
|
| 443 |
+
default is 1000 resamples and a 95% percentile interval. ``splits`` must
|
| 444 |
+
be ``val`` on every row.
|
| 445 |
+
|
| 446 |
+
``classes`` are the existing project labels, usually ``imd5_class``.
|
| 447 |
+
Every configured bin is reported. A bin with no rows keeps null errors.
|
| 448 |
+
Unlabeled rows stay in the overall line only.
|
| 449 |
+
|
| 450 |
+
``wind_averaging``, when given, is copied onto the table and the metrics
|
| 451 |
+
are computed inside each distinct period. Periods are not converted and
|
| 452 |
+
mixed periods are not pooled. Omit it when the column is absent.
|
| 453 |
+
|
| 454 |
+
``on_fix``, when given, must be an explicit boolean per row. The table
|
| 455 |
+
then also contains ``subset='on_fix'``, restricted to rows on a
|
| 456 |
+
best-track fix. ``subset='all'`` is always reported.
|
| 457 |
+
|
| 458 |
+
A class with at least one row and fewer than 3 storms is marked
|
| 459 |
+
``indicative (n_storms<3)``. The same mark is applied to an overall
|
| 460 |
+
line with fewer than 3 storms. When ``per_storm_breakdown`` is true,
|
| 461 |
+
each such class also lists one row per storm.
|
| 462 |
+
"""
|
| 463 |
+
if not isinstance(per_storm_breakdown, bool):
|
| 464 |
+
raise ValueError("per_storm_breakdown must be true or false")
|
| 465 |
+
truth = np.asarray(y_true, dtype=np.float64).ravel()
|
| 466 |
+
pred = np.asarray(y_pred, dtype=np.float64).ravel()
|
| 467 |
+
if truth.shape != pred.shape:
|
| 468 |
+
raise ValueError("y_true and y_pred must be the same shape")
|
| 469 |
+
if truth.size and (not np.isfinite(truth).all() or not np.isfinite(pred).all()):
|
| 470 |
+
raise ValueError("y_true and y_pred must be finite")
|
| 471 |
+
n_rows = int(truth.size)
|
| 472 |
+
_require_validation_split(splits, n_rows)
|
| 473 |
+
ids = np.asarray(storm_ids, dtype=object).ravel()
|
| 474 |
+
if ids.size != n_rows:
|
| 475 |
+
raise ValueError("storm_ids must align with y_true")
|
| 476 |
+
labels = _class_labels(classes, n_rows)
|
| 477 |
+
fix_mask = _on_fix_mask(on_fix, n_rows)
|
| 478 |
+
if not class_names:
|
| 479 |
+
raise ValueError("at least one intensity class name is required")
|
| 480 |
+
rows: list[dict[str, object]] = []
|
| 481 |
+
for period, positions in _averaging_blocks(n_rows, wind_averaging):
|
| 482 |
+
subsets = [("all", positions)]
|
| 483 |
+
if fix_mask is not None:
|
| 484 |
+
subsets.append(("on_fix", positions[fix_mask[positions]]))
|
| 485 |
+
for subset, index in subsets:
|
| 486 |
+
slice_truth = truth[index]
|
| 487 |
+
slice_pred = pred[index]
|
| 488 |
+
slice_storms = ids[index]
|
| 489 |
+
slice_labels = labels[index]
|
| 490 |
+
overall = _metric_record(
|
| 491 |
+
slice_truth,
|
| 492 |
+
slice_pred,
|
| 493 |
+
slice_storms,
|
| 494 |
+
wind_averaging=period,
|
| 495 |
+
subset=subset,
|
| 496 |
+
row_kind="overall",
|
| 497 |
+
intensity_class="overall",
|
| 498 |
+
storm_id=None,
|
| 499 |
+
n_resamples=n_resamples,
|
| 500 |
+
seed=seed,
|
| 501 |
+
ci_level=ci_level,
|
| 502 |
+
)
|
| 503 |
+
rows.append(overall)
|
| 504 |
+
for name in _class_names_in_order(slice_labels, class_names):
|
| 505 |
+
chosen = np.flatnonzero(slice_labels == name)
|
| 506 |
+
class_row = _metric_record(
|
| 507 |
+
slice_truth[chosen],
|
| 508 |
+
slice_pred[chosen],
|
| 509 |
+
slice_storms[chosen],
|
| 510 |
+
wind_averaging=period,
|
| 511 |
+
subset=subset,
|
| 512 |
+
row_kind="class",
|
| 513 |
+
intensity_class=name,
|
| 514 |
+
storm_id=None,
|
| 515 |
+
n_resamples=n_resamples,
|
| 516 |
+
seed=seed,
|
| 517 |
+
ci_level=ci_level,
|
| 518 |
+
)
|
| 519 |
+
rows.append(class_row)
|
| 520 |
+
n_storms = int(class_row["n_storms"])
|
| 521 |
+
if per_storm_breakdown and 0 < n_storms < _SMALL_CLASS_STORMS:
|
| 522 |
+
class_storms = slice_storms[chosen]
|
| 523 |
+
class_truth = slice_truth[chosen]
|
| 524 |
+
class_pred = slice_pred[chosen]
|
| 525 |
+
for storm in _storm_ids_in_order(class_storms):
|
| 526 |
+
storm_index = np.flatnonzero(
|
| 527 |
+
np.asarray([str(item) for item in class_storms.tolist()]) == storm
|
| 528 |
+
)
|
| 529 |
+
rows.append(
|
| 530 |
+
_metric_record(
|
| 531 |
+
class_truth[storm_index],
|
| 532 |
+
class_pred[storm_index],
|
| 533 |
+
class_storms[storm_index],
|
| 534 |
+
wind_averaging=period,
|
| 535 |
+
subset=subset,
|
| 536 |
+
row_kind="storm",
|
| 537 |
+
intensity_class=name,
|
| 538 |
+
storm_id=storm,
|
| 539 |
+
n_resamples=n_resamples,
|
| 540 |
+
seed=seed,
|
| 541 |
+
ci_level=ci_level,
|
| 542 |
+
)
|
| 543 |
+
)
|
| 544 |
+
return pd.DataFrame(rows, columns=list(_CLASS_TABLE_COLUMNS))
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
def mc_dropout_intervals(
|
| 548 |
+
samples: np.ndarray, level: float
|
| 549 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 550 |
+
"""Central interval from draws shaped ``(n_draws, n_rows)``.
|
| 551 |
+
|
| 552 |
+
The draws are an array. Nothing here runs a network.
|
| 553 |
+
"""
|
| 554 |
+
(level,) = _check_levels((level,))
|
| 555 |
+
draws = np.asarray(samples, dtype=np.float64)
|
| 556 |
+
if draws.ndim != 2 or draws.shape[0] < 2:
|
| 557 |
+
raise ValueError("samples must have shape (n_draws, n_rows) with at least 2 draws")
|
| 558 |
+
if not np.isfinite(draws).all():
|
| 559 |
+
raise ValueError("MC-dropout samples must be finite")
|
| 560 |
+
alpha = (1.0 - level) / 2.0
|
| 561 |
+
lower = np.quantile(draws, alpha, axis=0, method="linear")
|
| 562 |
+
upper = np.quantile(draws, 1.0 - alpha, axis=0, method="linear")
|
| 563 |
+
return np.asarray(lower, dtype=np.float64), np.asarray(upper, dtype=np.float64)
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def _sample_matrix(samples: np.ndarray, n_rows: int) -> np.ndarray:
|
| 567 |
+
array = np.asarray(samples, dtype=np.float64)
|
| 568 |
+
if array.ndim == 3 and array.shape[-1] == 1:
|
| 569 |
+
array = array[..., 0]
|
| 570 |
+
if array.ndim != 2:
|
| 571 |
+
raise ValueError("MC-dropout samples must have shape (n_draws, n_rows)")
|
| 572 |
+
if array.shape[0] == n_rows and array.shape[1] != n_rows:
|
| 573 |
+
raise ValueError("samples must have shape (n_draws, n_rows), with draws on axis 0")
|
| 574 |
+
if array.shape[0] < 2 or array.shape[1] != n_rows:
|
| 575 |
+
raise ValueError(
|
| 576 |
+
"samples must have shape (n_draws, n_rows) with at least 2 draws; "
|
| 577 |
+
f"got {array.shape} for {n_rows} rows"
|
| 578 |
+
)
|
| 579 |
+
if not np.isfinite(array).all():
|
| 580 |
+
raise ValueError("MC-dropout samples must be finite")
|
| 581 |
+
return array
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def mc_dropout_coverage(
|
| 585 |
+
y_true: np.ndarray,
|
| 586 |
+
samples: np.ndarray,
|
| 587 |
+
levels: Sequence[float] = _LEVELS,
|
| 588 |
+
tolerance: float = _TOLERANCE,
|
| 589 |
+
) -> dict[str, dict]:
|
| 590 |
+
"""Empirical coverage of central intervals drawn from ``samples``.
|
| 591 |
+
|
| 592 |
+
``samples`` is ``(n_draws, n_rows)`` aligned with ``y_true``. A level whose
|
| 593 |
+
coverage misses the nominal rate by more than ``tolerance`` is
|
| 594 |
+
``uncalibrated``.
|
| 595 |
+
"""
|
| 596 |
+
truth = np.asarray(y_true, dtype=np.float64).ravel()
|
| 597 |
+
if truth.size == 0 or not np.isfinite(truth).all():
|
| 598 |
+
raise ValueError("MC-dropout coverage needs finite targets")
|
| 599 |
+
draws = _sample_matrix(samples, truth.size)
|
| 600 |
+
checked = _check_levels(levels)
|
| 601 |
+
report: dict[str, dict] = {}
|
| 602 |
+
for level in checked:
|
| 603 |
+
lower, upper = mc_dropout_intervals(draws, level)
|
| 604 |
+
covered = (truth >= lower) & (truth <= upper)
|
| 605 |
+
empirical = float(np.mean(covered))
|
| 606 |
+
report[_level_key(level)] = {
|
| 607 |
+
"nominal": float(level),
|
| 608 |
+
"empirical_coverage": empirical,
|
| 609 |
+
"n": float(truth.size),
|
| 610 |
+
"n_covered": float(np.sum(covered)),
|
| 611 |
+
"mean_interval_width_kt": float(np.mean(upper - lower)),
|
| 612 |
+
"status": interval_status(empirical, level, tolerance),
|
| 613 |
+
}
|
| 614 |
+
return report
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
def residual_quantile_coverage(
|
| 618 |
+
y_true_val: np.ndarray,
|
| 619 |
+
y_pred_val: np.ndarray,
|
| 620 |
+
y_true_test: np.ndarray,
|
| 621 |
+
y_pred_test: np.ndarray,
|
| 622 |
+
levels: Sequence[float] = _LEVELS,
|
| 623 |
+
tolerance: float = _TOLERANCE,
|
| 624 |
+
) -> dict[str, dict]:
|
| 625 |
+
"""Fit quantiles of ``|residual|`` on validation rows and score test rows.
|
| 626 |
+
|
| 627 |
+
The half-width is the validation quantile at the nominal level. Test
|
| 628 |
+
coverage is the fraction of test rows with ``|residual|`` at or below that
|
| 629 |
+
width. Validation rows are not included in the coverage count.
|
| 630 |
+
"""
|
| 631 |
+
val_truth = np.asarray(y_true_val, dtype=np.float64).ravel()
|
| 632 |
+
val_pred = np.asarray(y_pred_val, dtype=np.float64).ravel()
|
| 633 |
+
test_truth = np.asarray(y_true_test, dtype=np.float64).ravel()
|
| 634 |
+
test_pred = np.asarray(y_pred_test, dtype=np.float64).ravel()
|
| 635 |
+
if val_truth.shape != val_pred.shape or val_truth.size == 0:
|
| 636 |
+
raise ValueError("validation residuals need a non-empty aligned pair")
|
| 637 |
+
if test_truth.shape != test_pred.shape or test_truth.size == 0:
|
| 638 |
+
raise ValueError("test residuals need a non-empty aligned pair")
|
| 639 |
+
if not (
|
| 640 |
+
np.isfinite(val_truth).all()
|
| 641 |
+
and np.isfinite(val_pred).all()
|
| 642 |
+
and np.isfinite(test_truth).all()
|
| 643 |
+
and np.isfinite(test_pred).all()
|
| 644 |
+
):
|
| 645 |
+
raise ValueError("residual-quantile inputs must be finite")
|
| 646 |
+
val_abs = np.abs(val_pred - val_truth)
|
| 647 |
+
test_abs = np.abs(test_pred - test_truth)
|
| 648 |
+
report: dict[str, dict] = {}
|
| 649 |
+
for level in _check_levels(levels):
|
| 650 |
+
half_width = float(np.quantile(val_abs, level, method="linear"))
|
| 651 |
+
covered = test_abs <= half_width
|
| 652 |
+
empirical = float(np.mean(covered))
|
| 653 |
+
report[_level_key(level)] = {
|
| 654 |
+
"nominal": float(level),
|
| 655 |
+
"absolute_residual_quantile_kt": half_width,
|
| 656 |
+
"empirical_coverage": empirical,
|
| 657 |
+
"n": float(test_truth.size),
|
| 658 |
+
"n_covered": float(np.sum(covered)),
|
| 659 |
+
"fit_split": "val",
|
| 660 |
+
"eval_split": "test",
|
| 661 |
+
"status": interval_status(empirical, level, tolerance),
|
| 662 |
+
}
|
| 663 |
+
return report
|
| 664 |
+
|
| 665 |
+
|
| 666 |
+
def _positions(frame: pd.DataFrame, split_name: str) -> np.ndarray:
|
| 667 |
+
return np.flatnonzero(frame["split"].astype(str).to_numpy() == split_name)
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
def _ensure_split(frame: pd.DataFrame, config: dict) -> pd.DataFrame:
|
| 671 |
+
"""Keep a complete storm split, or assign one. Random frame splits raise."""
|
| 672 |
+
if "split" in frame.columns:
|
| 673 |
+
if bool(frame["split"].isna().any()):
|
| 674 |
+
raise LeakageError("split has nulls; refusing to fill them frame by frame")
|
| 675 |
+
unknown = set(frame["split"].astype(str).unique()) - {"train", "val", "test"}
|
| 676 |
+
if unknown:
|
| 677 |
+
raise LeakageError(f"unknown splits: {sorted(unknown)}")
|
| 678 |
+
return frame
|
| 679 |
+
split_cfg = dict(config.get("split") or {})
|
| 680 |
+
strategy = str(split_cfg.get("strategy", "storm_wise"))
|
| 681 |
+
holdout_basin = split_cfg.get("holdout_basin") or None
|
| 682 |
+
if holdout_basin in {None, "", "null"}:
|
| 683 |
+
holdout_basin = None
|
| 684 |
+
return assign_storms(
|
| 685 |
+
frame,
|
| 686 |
+
strategy,
|
| 687 |
+
test_fraction=float(split_cfg.get("test_fraction", 0.2)),
|
| 688 |
+
val_fraction=float(split_cfg.get("val_fraction", 0.2)),
|
| 689 |
+
seed=int(split_cfg.get("seed", 0)),
|
| 690 |
+
holdout_years=[int(year) for year in (split_cfg.get("holdout_years") or [])],
|
| 691 |
+
holdout_basin=holdout_basin,
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
|
| 695 |
+
def _require_finite_predictions(frame: pd.DataFrame, column: str, split_name: str) -> np.ndarray:
|
| 696 |
+
if column not in frame.columns:
|
| 697 |
+
raise ValueError(f"missing prediction column {column}")
|
| 698 |
+
positions = _positions(frame, split_name)
|
| 699 |
+
if positions.size == 0:
|
| 700 |
+
raise ValueError(f"split {split_name} has no rows")
|
| 701 |
+
values = pd.to_numeric(frame.iloc[positions][column], errors="coerce").to_numpy(dtype=np.float64)
|
| 702 |
+
if not np.isfinite(values).all():
|
| 703 |
+
raise ValueError(f"{split_name} predictions must be finite")
|
| 704 |
+
return values
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
def _train_norm_stats(frame: pd.DataFrame, manifest: str | Path, config: dict):
|
| 708 |
+
"""Fit train-only pixel stats through the existing helper."""
|
| 709 |
+
from src.train import fit_split_normalization
|
| 710 |
+
|
| 711 |
+
prepared = frame.copy()
|
| 712 |
+
if "_class" not in prepared.columns:
|
| 713 |
+
prepared["_class"] = None
|
| 714 |
+
stats = fit_split_normalization(prepared, manifest, config)
|
| 715 |
+
if stats.source_split != "train":
|
| 716 |
+
raise LeakageError("normalization stats may be fit on the train split only")
|
| 717 |
+
return stats
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
def _synthetic_label(frame: pd.DataFrame) -> str:
|
| 721 |
+
flags = frame["is_synthetic"].astype(bool)
|
| 722 |
+
if bool(flags.all()):
|
| 723 |
+
return "yes"
|
| 724 |
+
if bool(flags.any()):
|
| 725 |
+
return "mixed"
|
| 726 |
+
return "no"
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
def _baseline_predictions(
|
| 730 |
+
frame: pd.DataFrame,
|
| 731 |
+
feature_names: Sequence[str],
|
| 732 |
+
config: dict,
|
| 733 |
+
train_pos: np.ndarray,
|
| 734 |
+
test_pos: np.ndarray,
|
| 735 |
+
) -> tuple[np.ndarray, np.ndarray, list[str], str, str]:
|
| 736 |
+
"""Fit mean and ridge on train rows. Return test predictions and fit notes."""
|
| 737 |
+
names = tuple(feature_names)
|
| 738 |
+
if not names:
|
| 739 |
+
raise ValueError("ridge needs at least one feature column")
|
| 740 |
+
train = frame.iloc[train_pos]
|
| 741 |
+
test = frame.iloc[test_pos]
|
| 742 |
+
x_train = model_matrix(train, names)
|
| 743 |
+
x_test = model_matrix(test, names)
|
| 744 |
+
y_train = train["wind_speed_kt"].to_numpy(dtype=np.float64)
|
| 745 |
+
params = baseline_params(config)
|
| 746 |
+
fitted: set[str] = set()
|
| 747 |
+
seed = int(params["seed"])
|
| 748 |
+
mean_hat, _mean_pipe, mean_note = fit_numeric_pipeline(
|
| 749 |
+
x_train,
|
| 750 |
+
y_train,
|
| 751 |
+
x_test,
|
| 752 |
+
task="regression",
|
| 753 |
+
model_name="mean",
|
| 754 |
+
params=params,
|
| 755 |
+
seed=seed,
|
| 756 |
+
train_storms=train["storm_id"].astype(str),
|
| 757 |
+
fitted_storms=fitted,
|
| 758 |
+
)
|
| 759 |
+
ridge_hat, _ridge_pipe, ridge_note = fit_numeric_pipeline(
|
| 760 |
+
x_train,
|
| 761 |
+
y_train,
|
| 762 |
+
x_test,
|
| 763 |
+
task="regression",
|
| 764 |
+
model_name="ridge",
|
| 765 |
+
params=params,
|
| 766 |
+
seed=seed,
|
| 767 |
+
train_storms=train["storm_id"].astype(str),
|
| 768 |
+
fitted_storms=fitted,
|
| 769 |
+
)
|
| 770 |
+
reference = mean_baseline(y_train, test_pos.size)
|
| 771 |
+
if not np.allclose(mean_hat, reference):
|
| 772 |
+
raise RuntimeError("mean baseline disagreed with src.metrics.mean_baseline")
|
| 773 |
+
return (
|
| 774 |
+
np.asarray(mean_hat, dtype=np.float64),
|
| 775 |
+
np.asarray(ridge_hat, dtype=np.float64),
|
| 776 |
+
sorted(fitted),
|
| 777 |
+
str(mean_note),
|
| 778 |
+
str(ridge_note),
|
| 779 |
+
)
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
def _plain(value):
|
| 783 |
+
if isinstance(value, np.ndarray):
|
| 784 |
+
return _plain(value.tolist())
|
| 785 |
+
if isinstance(value, dict):
|
| 786 |
+
return {str(key): _plain(item) for key, item in value.items()}
|
| 787 |
+
if isinstance(value, (list, tuple)):
|
| 788 |
+
return [_plain(item) for item in value]
|
| 789 |
+
if isinstance(value, (np.floating, float)):
|
| 790 |
+
number = float(value)
|
| 791 |
+
if not np.isfinite(number):
|
| 792 |
+
return None
|
| 793 |
+
return number
|
| 794 |
+
if isinstance(value, (np.integer,)):
|
| 795 |
+
return int(value)
|
| 796 |
+
if isinstance(value, (np.bool_,)):
|
| 797 |
+
return bool(value)
|
| 798 |
+
return value
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
def _csv_metric_row(series: str, bin_name: str, metrics: dict, report: dict) -> dict:
|
| 802 |
+
return {
|
| 803 |
+
"series": series,
|
| 804 |
+
"bin": bin_name,
|
| 805 |
+
"n": metrics.get("n"),
|
| 806 |
+
"mae_kt": metrics.get("mae_kt"),
|
| 807 |
+
"rmse_kt": metrics.get("rmse_kt"),
|
| 808 |
+
"bias_kt": metrics.get("bias_kt"),
|
| 809 |
+
"wind_averaging": report["wind_averaging"],
|
| 810 |
+
"binning": report["binning"],
|
| 811 |
+
"quote_as_result": report["quote_as_result"],
|
| 812 |
+
"synthetic": report["synthetic"],
|
| 813 |
+
"status": "",
|
| 814 |
+
}
|
| 815 |
+
|
| 816 |
+
|
| 817 |
+
def _metric_table(report: dict) -> pd.DataFrame:
|
| 818 |
+
rows: list[dict] = []
|
| 819 |
+
blocks = (
|
| 820 |
+
("model", report["model"]),
|
| 821 |
+
("mean", report["baselines"]["mean"]),
|
| 822 |
+
("ridge", report["baselines"]["ridge"]),
|
| 823 |
+
("persistence", report["baselines"]["persistence"]),
|
| 824 |
+
("paired_model", report["baselines"]["paired"]["model"]),
|
| 825 |
+
("paired_mean", report["baselines"]["paired"]["mean"]),
|
| 826 |
+
("paired_ridge", report["baselines"]["paired"]["ridge"]),
|
| 827 |
+
("paired_persistence", report["baselines"]["paired"]["persistence"]),
|
| 828 |
+
)
|
| 829 |
+
for series, block in blocks:
|
| 830 |
+
rows.append(_csv_metric_row(series, "overall", block["overall"], report))
|
| 831 |
+
for name, metrics in block["by_bin"].items():
|
| 832 |
+
rows.append(_csv_metric_row(series, name, metrics, report))
|
| 833 |
+
uncertainty = report["uncertainty"]
|
| 834 |
+
for method in ("mc_dropout", "residual_quantile"):
|
| 835 |
+
payload = uncertainty.get(method)
|
| 836 |
+
if not payload:
|
| 837 |
+
continue
|
| 838 |
+
for level, metrics in payload["levels"].items():
|
| 839 |
+
rows.append(
|
| 840 |
+
{
|
| 841 |
+
"series": method,
|
| 842 |
+
"bin": level,
|
| 843 |
+
"n": metrics.get("n"),
|
| 844 |
+
"mae_kt": None,
|
| 845 |
+
"rmse_kt": None,
|
| 846 |
+
"bias_kt": None,
|
| 847 |
+
"wind_averaging": report["wind_averaging"],
|
| 848 |
+
"binning": report["binning"],
|
| 849 |
+
"quote_as_result": report["quote_as_result"],
|
| 850 |
+
"synthetic": report["synthetic"],
|
| 851 |
+
"status": metrics.get("status"),
|
| 852 |
+
"nominal": metrics.get("nominal"),
|
| 853 |
+
"empirical_coverage": metrics.get("empirical_coverage"),
|
| 854 |
+
}
|
| 855 |
+
)
|
| 856 |
+
return pd.DataFrame(rows)
|
| 857 |
+
|
| 858 |
+
|
| 859 |
+
def save_error_by_bin(by_bin: dict[str, dict], names: Sequence[str], path: str | Path) -> Path:
|
| 860 |
+
"""Bar chart of MAE by bin. Empty bins are marked n=0 and have no bar."""
|
| 861 |
+
plt = _pyplot()
|
| 862 |
+
ordered = [str(name) for name in names]
|
| 863 |
+
for code in HIGHLIGHT_CODES:
|
| 864 |
+
if code not in ordered:
|
| 865 |
+
ordered.append(code)
|
| 866 |
+
values = []
|
| 867 |
+
for name in ordered:
|
| 868 |
+
mae = (by_bin.get(name) or _empty_metrics())["mae_kt"]
|
| 869 |
+
values.append(np.nan if mae is None else float(mae))
|
| 870 |
+
figure, axis = plt.subplots(figsize=(7.2, 4.4))
|
| 871 |
+
positions = np.arange(len(ordered))
|
| 872 |
+
finite = [value for value in values if np.isfinite(value)]
|
| 873 |
+
for position, value in zip(positions, values, strict=True):
|
| 874 |
+
if np.isfinite(value):
|
| 875 |
+
color = "#9b2226" if ordered[position] in HIGHLIGHT_CODES else "#1d3557"
|
| 876 |
+
axis.bar(position, value, color=color, width=0.72)
|
| 877 |
+
else:
|
| 878 |
+
axis.text(position, 0.0, "n=0", ha="center", va="bottom", fontsize=8, color="#6c757d")
|
| 879 |
+
labels = [HIGHLIGHT_DISPLAY.get(name, name) for name in ordered]
|
| 880 |
+
axis.set_xticks(positions, labels, rotation=20, ha="right")
|
| 881 |
+
for tick, name in zip(axis.get_xticklabels(), ordered, strict=True):
|
| 882 |
+
if name in HIGHLIGHT_CODES:
|
| 883 |
+
tick.set_fontweight("bold")
|
| 884 |
+
axis.set_ylabel("MAE (kt)")
|
| 885 |
+
axis.set_xlabel(BINNING_LABEL)
|
| 886 |
+
axis.set_title("Error by bin on held-out storms. VSCS and ESCS/SuCS are marked. Not a forecast.")
|
| 887 |
+
if finite:
|
| 888 |
+
axis.set_ylim(0.0, max(finite) * 1.25 + 1.0)
|
| 889 |
+
else:
|
| 890 |
+
axis.set_ylim(0.0, 1.0)
|
| 891 |
+
figure.tight_layout()
|
| 892 |
+
destination = Path(path)
|
| 893 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 894 |
+
figure.savefig(destination, dpi=100)
|
| 895 |
+
plt.close(figure)
|
| 896 |
+
return destination
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
def save_coverage_figure(uncertainty: dict, path: str | Path) -> Path:
|
| 900 |
+
"""Nominal versus empirical coverage. Misses are annotated uncalibrated."""
|
| 901 |
+
plt = _pyplot()
|
| 902 |
+
figure, axis = plt.subplots(figsize=(5.6, 5.2))
|
| 903 |
+
tolerance = float(uncertainty["coverage_tolerance"])
|
| 904 |
+
grid = np.linspace(0.0, 1.0, 40)
|
| 905 |
+
axis.fill_between(
|
| 906 |
+
grid,
|
| 907 |
+
grid - tolerance,
|
| 908 |
+
grid + tolerance,
|
| 909 |
+
color="#dee2e6",
|
| 910 |
+
label="tolerance",
|
| 911 |
+
)
|
| 912 |
+
axis.plot([0.0, 1.0], [0.0, 1.0], color="#6c757d", linewidth=1)
|
| 913 |
+
series = (
|
| 914 |
+
("MC dropout", uncertainty.get("mc_dropout"), "#1d3557"),
|
| 915 |
+
("residual quantile", uncertainty.get("residual_quantile"), "#9b2226"),
|
| 916 |
+
)
|
| 917 |
+
for label, payload, color in series:
|
| 918 |
+
if not payload:
|
| 919 |
+
continue
|
| 920 |
+
nominals = []
|
| 921 |
+
empiricals = []
|
| 922 |
+
for row in payload["levels"].values():
|
| 923 |
+
nominals.append(float(row["nominal"]))
|
| 924 |
+
empiricals.append(float(row["empirical_coverage"]))
|
| 925 |
+
if row["status"] == "uncalibrated":
|
| 926 |
+
axis.annotate(
|
| 927 |
+
"uncalibrated",
|
| 928 |
+
(float(row["nominal"]), float(row["empirical_coverage"])),
|
| 929 |
+
textcoords="offset points",
|
| 930 |
+
xytext=(6, 6),
|
| 931 |
+
fontsize=8,
|
| 932 |
+
color=color,
|
| 933 |
+
)
|
| 934 |
+
axis.plot(nominals, empiricals, marker="o", color=color, label=label)
|
| 935 |
+
axis.set_xlim(0.0, 1.0)
|
| 936 |
+
axis.set_ylim(0.0, 1.0)
|
| 937 |
+
axis.set_xlabel("Nominal coverage")
|
| 938 |
+
axis.set_ylabel("Empirical coverage on test storms")
|
| 939 |
+
axis.set_title("Held-out coverage. Not a calibrated forecast.")
|
| 940 |
+
axis.legend(frameon=False)
|
| 941 |
+
figure.tight_layout()
|
| 942 |
+
destination = Path(path)
|
| 943 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 944 |
+
figure.savefig(destination, dpi=100)
|
| 945 |
+
plt.close(figure)
|
| 946 |
+
return destination
|
| 947 |
+
|
| 948 |
+
|
| 949 |
+
def _write_report(report: dict, destination: Path) -> dict[str, str]:
|
| 950 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 951 |
+
_pyplot()
|
| 952 |
+
(destination / "README.txt").write_text(BANNER + "\n", encoding="utf-8")
|
| 953 |
+
metrics_path = destination / "metrics.json"
|
| 954 |
+
table_path = destination / "metrics.csv"
|
| 955 |
+
_metric_table(report).to_csv(table_path, index=False)
|
| 956 |
+
test_truth = np.asarray(report["_plot_truth"], dtype=np.float64)
|
| 957 |
+
test_pred = np.asarray(report["_plot_pred"], dtype=np.float64)
|
| 958 |
+
parity = save_regression_scatter(
|
| 959 |
+
test_truth,
|
| 960 |
+
test_pred,
|
| 961 |
+
destination / "parity.png",
|
| 962 |
+
title="Held-out parity. Not a forecast.",
|
| 963 |
+
)
|
| 964 |
+
error_path = save_error_by_bin(
|
| 965 |
+
report["model"]["by_bin"],
|
| 966 |
+
report["bin_names"],
|
| 967 |
+
destination / "error_by_bin.png",
|
| 968 |
+
)
|
| 969 |
+
coverage_path = save_coverage_figure(report["uncertainty"], destination / "coverage.png")
|
| 970 |
+
outputs = {
|
| 971 |
+
"metrics_json": str(metrics_path),
|
| 972 |
+
"metrics_csv": str(table_path),
|
| 973 |
+
"readme": str(destination / "README.txt"),
|
| 974 |
+
"parity": str(parity),
|
| 975 |
+
"error_by_bin": str(error_path),
|
| 976 |
+
"coverage": str(coverage_path),
|
| 977 |
+
}
|
| 978 |
+
report["outputs"] = outputs
|
| 979 |
+
public = {key: value for key, value in report.items() if not key.startswith("_")}
|
| 980 |
+
metrics_path.write_text(json.dumps(_plain(public), indent=2) + "\n", encoding="utf-8")
|
| 981 |
+
return outputs
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
def evaluate(
|
| 985 |
+
frame: pd.DataFrame,
|
| 986 |
+
manifest: str | Path,
|
| 987 |
+
config: dict,
|
| 988 |
+
*,
|
| 989 |
+
feature_names: Sequence[str],
|
| 990 |
+
prediction_column: str = "y_pred",
|
| 991 |
+
out_dir: str | Path | None = None,
|
| 992 |
+
levels: Sequence[float] = _LEVELS,
|
| 993 |
+
coverage_tolerance: float | None = None,
|
| 994 |
+
samples: np.ndarray | None = None,
|
| 995 |
+
samples_aligned_to: str = "test",
|
| 996 |
+
) -> dict:
|
| 997 |
+
"""Score test storms and write figures plus a metrics file under ``out_dir``.
|
| 998 |
+
|
| 999 |
+
``frame`` carries the storm split, targets, predictions, and the feature
|
| 1000 |
+
columns used by ridge. Images referenced by ``manifest`` are used only to
|
| 1001 |
+
fit train normalization. Train storms are not part of the evaluated set.
|
| 1002 |
+
"""
|
| 1003 |
+
limits = list((config.get("data") or {}).get("plausible_wind_kt") or [0, 200])
|
| 1004 |
+
work = require_valid(
|
| 1005 |
+
frame,
|
| 1006 |
+
wind_min_kt=float(limits[0]),
|
| 1007 |
+
wind_max_kt=float(limits[1]),
|
| 1008 |
+
)
|
| 1009 |
+
work = _ensure_split(work, config).reset_index(drop=True)
|
| 1010 |
+
groups = storm_ids_by_split(work)
|
| 1011 |
+
if not groups["train"] or not groups["val"] or not groups["test"]:
|
| 1012 |
+
raise LeakageError("train, val, and test storms are all required")
|
| 1013 |
+
if groups["train"] & groups["test"] or groups["train"] & groups["val"]:
|
| 1014 |
+
raise LeakageError("train storms leaked into a held-out split")
|
| 1015 |
+
edges, names = _bin_spec(config)
|
| 1016 |
+
wind_averaging = recorded_wind_averaging(work)
|
| 1017 |
+
train_pos = _positions(work, "train")
|
| 1018 |
+
val_pos = _positions(work, "val")
|
| 1019 |
+
test_pos = _positions(work, "test")
|
| 1020 |
+
evaluated = frozenset(work.iloc[test_pos]["storm_id"].astype(str))
|
| 1021 |
+
if evaluated & groups["train"]:
|
| 1022 |
+
raise LeakageError(f"train storms are in the evaluated set: {sorted(evaluated & groups['train'])}")
|
| 1023 |
+
if evaluated != groups["test"]:
|
| 1024 |
+
raise LeakageError("evaluated storms are not exactly the test storms")
|
| 1025 |
+
assert_no_forbidden_inputs(feature_names, "refusing to fit ridge on")
|
| 1026 |
+
val_pred = _require_finite_predictions(work, prediction_column, "val")
|
| 1027 |
+
test_pred = _require_finite_predictions(work, prediction_column, "test")
|
| 1028 |
+
val_truth = work.iloc[val_pos]["wind_speed_kt"].to_numpy(dtype=np.float64)
|
| 1029 |
+
test_truth = work.iloc[test_pos]["wind_speed_kt"].to_numpy(dtype=np.float64)
|
| 1030 |
+
stats = _train_norm_stats(work, manifest, config)
|
| 1031 |
+
checked_levels = _check_levels(levels)
|
| 1032 |
+
if coverage_tolerance is None:
|
| 1033 |
+
configured = dict(config.get("evaluate") or {})
|
| 1034 |
+
tolerance = float(configured.get("coverage_tolerance", _TOLERANCE))
|
| 1035 |
+
else:
|
| 1036 |
+
tolerance = float(coverage_tolerance)
|
| 1037 |
+
if tolerance < 0:
|
| 1038 |
+
raise ValueError("coverage tolerance must be non-negative")
|
| 1039 |
+
|
| 1040 |
+
model_block = score_winds(test_truth, test_pred, edges, names)
|
| 1041 |
+
model_block["storms"] = sorted(evaluated)
|
| 1042 |
+
mean_hat, ridge_hat, fitted_ids, mean_note, ridge_note = _baseline_predictions(
|
| 1043 |
+
work, feature_names, config, train_pos, test_pos
|
| 1044 |
+
)
|
| 1045 |
+
fitted = frozenset(fitted_ids)
|
| 1046 |
+
if not fitted <= groups["train"]:
|
| 1047 |
+
raise LeakageError("baseline fit saw storms outside the training split")
|
| 1048 |
+
held_out = groups["val"] | groups["test"]
|
| 1049 |
+
if fitted & held_out:
|
| 1050 |
+
leaked = sorted(fitted & held_out)
|
| 1051 |
+
raise LeakageError(f"baseline fit saw held-out storms: {leaked}")
|
| 1052 |
+
|
| 1053 |
+
persist_all = persistence_predictions(work)
|
| 1054 |
+
persist_test = persist_all[test_pos]
|
| 1055 |
+
paired = np.isfinite(persist_test)
|
| 1056 |
+
mean_block = score_winds(test_truth, mean_hat, edges, names)
|
| 1057 |
+
ridge_block = score_winds(test_truth, ridge_hat, edges, names)
|
| 1058 |
+
if int(np.sum(paired)) == 0:
|
| 1059 |
+
persistence_block = score_winds([], [], edges, names)
|
| 1060 |
+
paired_model = score_winds([], [], edges, names)
|
| 1061 |
+
paired_mean = score_winds([], [], edges, names)
|
| 1062 |
+
paired_ridge = score_winds([], [], edges, names)
|
| 1063 |
+
paired_persistence = score_winds([], [], edges, names)
|
| 1064 |
+
else:
|
| 1065 |
+
persistence_block = score_winds(test_truth[paired], persist_test[paired], edges, names)
|
| 1066 |
+
paired_model = score_winds(test_truth[paired], test_pred[paired], edges, names)
|
| 1067 |
+
paired_mean = score_winds(test_truth[paired], mean_hat[paired], edges, names)
|
| 1068 |
+
paired_ridge = score_winds(test_truth[paired], ridge_hat[paired], edges, names)
|
| 1069 |
+
paired_persistence = persistence_block
|
| 1070 |
+
persistence_storms = sorted(
|
| 1071 |
+
set(work.iloc[test_pos]["storm_id"].astype(str).to_numpy()[paired])
|
| 1072 |
+
)
|
| 1073 |
+
mean_block["storms"] = sorted(evaluated)
|
| 1074 |
+
ridge_block["storms"] = sorted(evaluated)
|
| 1075 |
+
persistence_block["storms"] = persistence_storms
|
| 1076 |
+
|
| 1077 |
+
if samples is None:
|
| 1078 |
+
mc_report = None
|
| 1079 |
+
else:
|
| 1080 |
+
if samples_aligned_to == "test":
|
| 1081 |
+
draw_matrix = _sample_matrix(samples, test_pos.size)
|
| 1082 |
+
mc_truth = test_truth
|
| 1083 |
+
elif samples_aligned_to == "frame":
|
| 1084 |
+
draw_matrix = _sample_matrix(samples, len(work))[:, test_pos]
|
| 1085 |
+
mc_truth = test_truth
|
| 1086 |
+
else:
|
| 1087 |
+
raise ValueError("samples_aligned_to must be 'test' or 'frame'")
|
| 1088 |
+
mc_report = {
|
| 1089 |
+
"source": "sampled predictions",
|
| 1090 |
+
"imports_torch": False,
|
| 1091 |
+
"levels": mc_dropout_coverage(mc_truth, draw_matrix, checked_levels, tolerance),
|
| 1092 |
+
}
|
| 1093 |
+
residual_report = {
|
| 1094 |
+
"fit_split": "val",
|
| 1095 |
+
"eval_split": "test",
|
| 1096 |
+
"val_storms": sorted(groups["val"]),
|
| 1097 |
+
"test_storms": sorted(groups["test"]),
|
| 1098 |
+
"levels": residual_quantile_coverage(
|
| 1099 |
+
val_truth, val_pred, test_truth, test_pred, checked_levels, tolerance
|
| 1100 |
+
),
|
| 1101 |
+
}
|
| 1102 |
+
reports_root = Path((config.get("paths") or {}).get("reports", "reports"))
|
| 1103 |
+
destination = Path(out_dir) if out_dir is not None else reports_root / "heldout"
|
| 1104 |
+
report = {
|
| 1105 |
+
"note": BANNER,
|
| 1106 |
+
"quote_as_result": "no",
|
| 1107 |
+
"present_as_forecast": False,
|
| 1108 |
+
"binning": BINNING_LABEL,
|
| 1109 |
+
"reported_especially": [HIGHLIGHT_DISPLAY[code] for code in HIGHLIGHT_CODES],
|
| 1110 |
+
"wind_averaging": wind_averaging,
|
| 1111 |
+
"wind_averaging_note": WIND_AVERAGING_NOTE,
|
| 1112 |
+
"edges_kt": [float(edge) for edge in edges],
|
| 1113 |
+
"bin_names": [str(name) for name in names],
|
| 1114 |
+
"eval_split": "test",
|
| 1115 |
+
"synthetic": _synthetic_label(work),
|
| 1116 |
+
"train_storms": sorted(groups["train"]),
|
| 1117 |
+
"val_storms": sorted(groups["val"]),
|
| 1118 |
+
"test_storms": sorted(groups["test"]),
|
| 1119 |
+
"evaluated_storms": sorted(evaluated),
|
| 1120 |
+
"normalization": {
|
| 1121 |
+
"mean": float(stats.mean),
|
| 1122 |
+
"std": float(stats.std),
|
| 1123 |
+
"source_split": str(stats.source_split),
|
| 1124 |
+
"helper": "src.train.fit_split_normalization",
|
| 1125 |
+
},
|
| 1126 |
+
"model": model_block,
|
| 1127 |
+
"baselines": {
|
| 1128 |
+
"fit_split": "train",
|
| 1129 |
+
"score_split": "test",
|
| 1130 |
+
"fitted_storms": sorted(fitted),
|
| 1131 |
+
"mean_fit_notes": mean_note,
|
| 1132 |
+
"ridge_fit_notes": ridge_note,
|
| 1133 |
+
"persistence_definition": (
|
| 1134 |
+
"reference baseline: previous best-track wind_speed_kt in the "
|
| 1135 |
+
"same storm, not the imagery; image-only models cannot be "
|
| 1136 |
+
"compared against it; the first frame of a storm is not scored"
|
| 1137 |
+
),
|
| 1138 |
+
"mean": mean_block,
|
| 1139 |
+
"ridge": ridge_block,
|
| 1140 |
+
"persistence": persistence_block,
|
| 1141 |
+
"paired": {
|
| 1142 |
+
"rows": "test rows with a previous best-track wind in the same storm",
|
| 1143 |
+
"model": paired_model,
|
| 1144 |
+
"mean": paired_mean,
|
| 1145 |
+
"ridge": paired_ridge,
|
| 1146 |
+
"persistence": paired_persistence,
|
| 1147 |
+
},
|
| 1148 |
+
},
|
| 1149 |
+
"uncertainty": {
|
| 1150 |
+
"coverage_tolerance": tolerance,
|
| 1151 |
+
"nominal_levels": [float(level) for level in checked_levels],
|
| 1152 |
+
"mc_dropout": mc_report,
|
| 1153 |
+
"residual_quantile": residual_report,
|
| 1154 |
+
},
|
| 1155 |
+
"_plot_truth": test_truth,
|
| 1156 |
+
"_plot_pred": test_pred,
|
| 1157 |
+
}
|
| 1158 |
+
_write_report(report, destination)
|
| 1159 |
+
return {key: value for key, value in report.items() if not key.startswith("_")}
|
| 1160 |
+
|
| 1161 |
+
|
| 1162 |
+
def main(argv: list[str] | None = None) -> dict:
|
| 1163 |
+
"""CLI entry point. Prints paths and the honesty banner, not a score to quote."""
|
| 1164 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 1165 |
+
parser.add_argument("--config", type=Path, required=True)
|
| 1166 |
+
parser.add_argument(
|
| 1167 |
+
"--frame",
|
| 1168 |
+
type=Path,
|
| 1169 |
+
required=True,
|
| 1170 |
+
help="CSV with storms, winds, y_pred, and features",
|
| 1171 |
+
)
|
| 1172 |
+
parser.add_argument(
|
| 1173 |
+
"--manifest",
|
| 1174 |
+
type=Path,
|
| 1175 |
+
default=None,
|
| 1176 |
+
help="Path used to resolve image_path. Defaults to --frame.",
|
| 1177 |
+
)
|
| 1178 |
+
parser.add_argument("--features", nargs="+", required=True)
|
| 1179 |
+
parser.add_argument("--prediction-column", default="y_pred")
|
| 1180 |
+
parser.add_argument("--out", type=Path, default=None)
|
| 1181 |
+
parser.add_argument("--levels", nargs="+", type=float, default=list(_LEVELS))
|
| 1182 |
+
parser.add_argument("--coverage-tolerance", type=float, default=None)
|
| 1183 |
+
parser.add_argument(
|
| 1184 |
+
"--samples",
|
| 1185 |
+
type=Path,
|
| 1186 |
+
default=None,
|
| 1187 |
+
help="NPY array of MC-dropout draws, shape (n_draws, n_test_rows)",
|
| 1188 |
+
)
|
| 1189 |
+
parser.add_argument(
|
| 1190 |
+
"--samples-aligned-to",
|
| 1191 |
+
choices=("test", "frame"),
|
| 1192 |
+
default="test",
|
| 1193 |
+
)
|
| 1194 |
+
args = parser.parse_args(argv)
|
| 1195 |
+
config = load_config(args.config)
|
| 1196 |
+
table = pd.read_csv(args.frame)
|
| 1197 |
+
samples = None if args.samples is None else np.load(args.samples)
|
| 1198 |
+
report = evaluate(
|
| 1199 |
+
table,
|
| 1200 |
+
args.manifest or args.frame,
|
| 1201 |
+
config,
|
| 1202 |
+
feature_names=args.features,
|
| 1203 |
+
prediction_column=args.prediction_column,
|
| 1204 |
+
out_dir=args.out,
|
| 1205 |
+
levels=args.levels,
|
| 1206 |
+
coverage_tolerance=args.coverage_tolerance,
|
| 1207 |
+
samples=samples,
|
| 1208 |
+
samples_aligned_to=args.samples_aligned_to,
|
| 1209 |
+
)
|
| 1210 |
+
print(BANNER)
|
| 1211 |
+
print(f"wind_averaging={report['wind_averaging']}")
|
| 1212 |
+
print("quote_as_result=no")
|
| 1213 |
+
print(f"Wrote {report['outputs']['metrics_json']}")
|
| 1214 |
+
return report
|
| 1215 |
+
|
| 1216 |
+
|
| 1217 |
+
if __name__ == "__main__":
|
| 1218 |
+
main()
|
bundle/src/features.py
ADDED
|
@@ -0,0 +1,899 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Physically motivated image features for classical intensity baselines.
|
| 2 |
+
|
| 3 |
+
Distributional statistics are called ``tb_*`` only when the caller has set
|
| 4 |
+
``features.calibrated``. Otherwise they are ``pixel_*``. Nothing here converts
|
| 5 |
+
digital numbers to brightness temperature.
|
| 6 |
+
|
| 7 |
+
The simplified DAV terms are the circular variance of the angle between the
|
| 8 |
+
image gradient and the radial direction, at fixed fractions of the crop
|
| 9 |
+
half-width. That is not operational deviation-angle variance: there is no
|
| 10 |
+
radius search, no flight-level wind, and no agency radius product.
|
| 11 |
+
|
| 12 |
+
Radial, eye, and DAV features assume the storm is already near the image
|
| 13 |
+
center. This module does not recenter with a best-track fix.
|
| 14 |
+
|
| 15 |
+
Temporal deltas use the previous frame of the same storm after cross-split
|
| 16 |
+
links have been removed. Wind, R34, RMW, and class labels are not features.
|
| 17 |
+
|
| 18 |
+
Crop height and width are the array shape. ``data.image_size`` may be
|
| 19 |
+
``native`` or a square resize for the deep model. It is not applied here.
|
| 20 |
+
Feature selection calls
|
| 21 |
+
``storm_ids_by_split`` and fits only the training storms.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
import json
|
| 27 |
+
import logging
|
| 28 |
+
from dataclasses import dataclass
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
import numpy as np
|
| 32 |
+
import pandas as pd
|
| 33 |
+
from sklearn.ensemble import RandomForestRegressor
|
| 34 |
+
from sklearn.feature_selection import RFE
|
| 35 |
+
from sklearn.impute import SimpleImputer
|
| 36 |
+
|
| 37 |
+
from src.data_loader import load_image, resolve_image
|
| 38 |
+
from src.preprocessing import MAX_MISSING_FRACTION, as_channel_first, missing_fraction
|
| 39 |
+
from src.schema import FORBIDDEN_FEATURES, parse_is_synthetic, wind_to_imd5
|
| 40 |
+
from src.splits import (
|
| 41 |
+
LeakageError,
|
| 42 |
+
add_previous_frame_id,
|
| 43 |
+
assert_no_forbidden_inputs,
|
| 44 |
+
null_cross_split_links,
|
| 45 |
+
storm_ids_by_split,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
logger = logging.getLogger(__name__)
|
| 49 |
+
|
| 50 |
+
GLCM_NAMES = (
|
| 51 |
+
"glcm_contrast",
|
| 52 |
+
"glcm_dissimilarity",
|
| 53 |
+
"glcm_homogeneity",
|
| 54 |
+
"glcm_energy",
|
| 55 |
+
"glcm_correlation",
|
| 56 |
+
"glcm_asm",
|
| 57 |
+
)
|
| 58 |
+
HAAR_NAMES = (
|
| 59 |
+
"haar_energy_ll",
|
| 60 |
+
"haar_energy_lh",
|
| 61 |
+
"haar_energy_hl",
|
| 62 |
+
"haar_energy_hh",
|
| 63 |
+
)
|
| 64 |
+
EYE_NAMES = (
|
| 65 |
+
"eye_center_mean",
|
| 66 |
+
"cdo_annulus_mean",
|
| 67 |
+
"eye_cdo_contrast",
|
| 68 |
+
"eye_present",
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@dataclass(frozen=True)
|
| 73 |
+
class FeatureSpec:
|
| 74 |
+
"""Geometry of one feature vector. Thresholds are in image units."""
|
| 75 |
+
|
| 76 |
+
calibrated: bool = False
|
| 77 |
+
cold_thresholds: tuple[float, ...] = (200.0, 210.0, 220.0, 230.0, 240.0)
|
| 78 |
+
radial_bins: int = 8
|
| 79 |
+
eye_radius_fraction: float = 0.12
|
| 80 |
+
cdo_outer_fraction: float = 0.35
|
| 81 |
+
eye_contrast_min: float = 2.0
|
| 82 |
+
dav_radii_fractions: tuple[float, ...] = (0.15, 0.30, 0.45, 0.60)
|
| 83 |
+
dav_annulus_width_fraction: float = 0.08
|
| 84 |
+
glcm_levels: int = 16
|
| 85 |
+
glcm_distance: int = 1
|
| 86 |
+
|
| 87 |
+
def __post_init__(self) -> None:
|
| 88 |
+
if not self.cold_thresholds:
|
| 89 |
+
raise ValueError("cold_thresholds must not be empty")
|
| 90 |
+
if self.radial_bins < 2:
|
| 91 |
+
raise ValueError("radial_bins must be at least 2")
|
| 92 |
+
if not 0 < self.eye_radius_fraction < self.cdo_outer_fraction <= 1:
|
| 93 |
+
raise ValueError("eye radius must sit inside the CDO annulus")
|
| 94 |
+
if self.eye_contrast_min < 0:
|
| 95 |
+
raise ValueError("eye_contrast_min must be >= 0")
|
| 96 |
+
if any(not 0 < radius < 1 for radius in self.dav_radii_fractions):
|
| 97 |
+
raise ValueError("DAV radii must be fractions of the half-width")
|
| 98 |
+
if not 0 < self.dav_annulus_width_fraction < 0.5:
|
| 99 |
+
raise ValueError("DAV annulus width fraction is out of range")
|
| 100 |
+
if not 8 <= self.glcm_levels <= 32:
|
| 101 |
+
raise ValueError("glcm_levels must be between 8 and 32")
|
| 102 |
+
if self.glcm_distance < 1:
|
| 103 |
+
raise ValueError("glcm_distance must be >= 1")
|
| 104 |
+
|
| 105 |
+
@property
|
| 106 |
+
def prefix(self) -> str:
|
| 107 |
+
return "tb" if self.calibrated else "pixel"
|
| 108 |
+
|
| 109 |
+
@classmethod
|
| 110 |
+
def from_config(cls, config: dict) -> FeatureSpec:
|
| 111 |
+
raw = config.get("features")
|
| 112 |
+
if not isinstance(raw, dict):
|
| 113 |
+
raise KeyError("config features is required")
|
| 114 |
+
required = (
|
| 115 |
+
"calibrated",
|
| 116 |
+
"cold_thresholds",
|
| 117 |
+
"radial_bins",
|
| 118 |
+
"eye_radius_fraction",
|
| 119 |
+
"cdo_outer_fraction",
|
| 120 |
+
"eye_contrast_min",
|
| 121 |
+
"dav_radii_fractions",
|
| 122 |
+
"dav_annulus_width_fraction",
|
| 123 |
+
"glcm_levels",
|
| 124 |
+
"glcm_distance",
|
| 125 |
+
)
|
| 126 |
+
missing = [key for key in required if key not in raw]
|
| 127 |
+
if missing:
|
| 128 |
+
raise KeyError(f"config features missing {missing}")
|
| 129 |
+
return cls(
|
| 130 |
+
calibrated=bool(raw["calibrated"]),
|
| 131 |
+
cold_thresholds=tuple(float(value) for value in raw["cold_thresholds"]),
|
| 132 |
+
radial_bins=int(raw["radial_bins"]),
|
| 133 |
+
eye_radius_fraction=float(raw["eye_radius_fraction"]),
|
| 134 |
+
cdo_outer_fraction=float(raw["cdo_outer_fraction"]),
|
| 135 |
+
eye_contrast_min=float(raw["eye_contrast_min"]),
|
| 136 |
+
dav_radii_fractions=tuple(float(value) for value in raw["dav_radii_fractions"]),
|
| 137 |
+
dav_annulus_width_fraction=float(raw["dav_annulus_width_fraction"]),
|
| 138 |
+
glcm_levels=int(raw["glcm_levels"]),
|
| 139 |
+
glcm_distance=int(raw["glcm_distance"]),
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
def feature_groups(self) -> dict[str, tuple[str, ...]]:
|
| 143 |
+
"""Feature names by group.
|
| 144 |
+
|
| 145 |
+
``pixel_stats`` are order statistics of the stored image values.
|
| 146 |
+
They are not brightness temperature unless ``calibrated`` is set,
|
| 147 |
+
in which case the same slots use the ``tb_`` prefix.
|
| 148 |
+
``dav_simplified`` is gradient-angle variance, not operational DAV.
|
| 149 |
+
"""
|
| 150 |
+
prefix = self.prefix
|
| 151 |
+
return {
|
| 152 |
+
"pixel_stats": (
|
| 153 |
+
f"{prefix}_min",
|
| 154 |
+
f"{prefix}_max",
|
| 155 |
+
f"{prefix}_mean",
|
| 156 |
+
f"{prefix}_std",
|
| 157 |
+
f"{prefix}_p10",
|
| 158 |
+
f"{prefix}_p25",
|
| 159 |
+
f"{prefix}_p50",
|
| 160 |
+
f"{prefix}_p75",
|
| 161 |
+
f"{prefix}_p90",
|
| 162 |
+
f"{prefix}_iqr",
|
| 163 |
+
),
|
| 164 |
+
"cold_cloud": tuple(
|
| 165 |
+
f"cold_frac_{_token(threshold)}" for threshold in self.cold_thresholds
|
| 166 |
+
),
|
| 167 |
+
"radial": tuple(f"radial_mean_{index:02d}" for index in range(self.radial_bins)),
|
| 168 |
+
"eye_cdo": EYE_NAMES,
|
| 169 |
+
"dav_simplified": tuple(
|
| 170 |
+
f"dav_simplified_r{index:02d}" for index in range(len(self.dav_radii_fractions))
|
| 171 |
+
),
|
| 172 |
+
"glcm": GLCM_NAMES,
|
| 173 |
+
"haar": HAAR_NAMES,
|
| 174 |
+
"temporal": (
|
| 175 |
+
"has_prev",
|
| 176 |
+
f"delta_{prefix}_mean",
|
| 177 |
+
f"delta_{prefix}_min",
|
| 178 |
+
"delta_cold_primary",
|
| 179 |
+
"delta_eye_cdo_contrast",
|
| 180 |
+
"delta_radial_mean_00",
|
| 181 |
+
),
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
def image_feature_names(self) -> tuple[str, ...]:
|
| 185 |
+
groups = self.feature_groups()
|
| 186 |
+
names: list[str] = []
|
| 187 |
+
for key in (
|
| 188 |
+
"pixel_stats",
|
| 189 |
+
"cold_cloud",
|
| 190 |
+
"radial",
|
| 191 |
+
"eye_cdo",
|
| 192 |
+
"dav_simplified",
|
| 193 |
+
"glcm",
|
| 194 |
+
"haar",
|
| 195 |
+
):
|
| 196 |
+
names.extend(groups[key])
|
| 197 |
+
return tuple(names)
|
| 198 |
+
|
| 199 |
+
def feature_names(self) -> tuple[str, ...]:
|
| 200 |
+
return self.image_feature_names() + self.feature_groups()["temporal"]
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
@dataclass(frozen=True)
|
| 204 |
+
class FeatureSelection:
|
| 205 |
+
names: tuple[str, ...]
|
| 206 |
+
source_split: str
|
| 207 |
+
importances: dict[str, float]
|
| 208 |
+
dropped_variance: tuple[str, ...]
|
| 209 |
+
dropped_correlation: tuple[str, ...]
|
| 210 |
+
train_storms: frozenset[str] = frozenset()
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _token(value: float) -> str:
|
| 214 |
+
number = float(value)
|
| 215 |
+
if number.is_integer():
|
| 216 |
+
return str(int(number))
|
| 217 |
+
return str(number).replace("-", "m").replace(".", "p")
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _single_channel(image: np.ndarray) -> np.ndarray:
|
| 221 |
+
return as_channel_first(image)[0]
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _finite_fill(image: np.ndarray) -> np.ndarray:
|
| 225 |
+
filled = np.array(image, dtype=np.float64, copy=True)
|
| 226 |
+
finite = np.isfinite(filled)
|
| 227 |
+
fill = float(np.median(filled[finite])) if finite.any() else 0.0
|
| 228 |
+
filled[~finite] = fill
|
| 229 |
+
return filled
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def _distribution(image: np.ndarray, prefix: str) -> dict[str, float]:
|
| 233 |
+
finite = image[np.isfinite(image)]
|
| 234 |
+
if finite.size == 0:
|
| 235 |
+
keys = (
|
| 236 |
+
"min",
|
| 237 |
+
"max",
|
| 238 |
+
"mean",
|
| 239 |
+
"std",
|
| 240 |
+
"p10",
|
| 241 |
+
"p25",
|
| 242 |
+
"p50",
|
| 243 |
+
"p75",
|
| 244 |
+
"p90",
|
| 245 |
+
"iqr",
|
| 246 |
+
)
|
| 247 |
+
return {f"{prefix}_{key}": float("nan") for key in keys}
|
| 248 |
+
percentiles = np.percentile(finite, [10, 25, 50, 75, 90])
|
| 249 |
+
return {
|
| 250 |
+
f"{prefix}_min": float(finite.min()),
|
| 251 |
+
f"{prefix}_max": float(finite.max()),
|
| 252 |
+
f"{prefix}_mean": float(finite.mean()),
|
| 253 |
+
f"{prefix}_std": float(finite.std()),
|
| 254 |
+
f"{prefix}_p10": float(percentiles[0]),
|
| 255 |
+
f"{prefix}_p25": float(percentiles[1]),
|
| 256 |
+
f"{prefix}_p50": float(percentiles[2]),
|
| 257 |
+
f"{prefix}_p75": float(percentiles[3]),
|
| 258 |
+
f"{prefix}_p90": float(percentiles[4]),
|
| 259 |
+
f"{prefix}_iqr": float(percentiles[3] - percentiles[1]),
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def _cold_coverage(image: np.ndarray, thresholds: tuple[float, ...]) -> dict[str, float]:
|
| 264 |
+
finite = image[np.isfinite(image)]
|
| 265 |
+
out: dict[str, float] = {}
|
| 266 |
+
for threshold in thresholds:
|
| 267 |
+
key = f"cold_frac_{_token(threshold)}"
|
| 268 |
+
if finite.size == 0:
|
| 269 |
+
out[key] = float("nan")
|
| 270 |
+
else:
|
| 271 |
+
out[key] = float(np.mean(finite < threshold))
|
| 272 |
+
return out
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def _radial_and_eye(image: np.ndarray, spec: FeatureSpec) -> dict[str, float]:
|
| 276 |
+
height, width = image.shape
|
| 277 |
+
yy, xx = np.mgrid[0:height, 0:width]
|
| 278 |
+
center_y = (height - 1) / 2.0
|
| 279 |
+
center_x = (width - 1) / 2.0
|
| 280 |
+
radius = np.hypot(yy - center_y, xx - center_x)
|
| 281 |
+
max_radius = max(float(radius.max()), 1e-6)
|
| 282 |
+
edges = np.linspace(0.0, max_radius + 1e-6, spec.radial_bins + 1)
|
| 283 |
+
out: dict[str, float] = {}
|
| 284 |
+
for index in range(spec.radial_bins):
|
| 285 |
+
mask = (radius >= edges[index]) & (radius < edges[index + 1]) & np.isfinite(image)
|
| 286 |
+
out[f"radial_mean_{index:02d}"] = (
|
| 287 |
+
float(image[mask].mean()) if mask.any() else float("nan")
|
| 288 |
+
)
|
| 289 |
+
half = min(height, width) / 2.0
|
| 290 |
+
eye = radius <= spec.eye_radius_fraction * half
|
| 291 |
+
annulus = (radius > spec.eye_radius_fraction * half) & (
|
| 292 |
+
radius <= spec.cdo_outer_fraction * half
|
| 293 |
+
)
|
| 294 |
+
eye_values = image[eye & np.isfinite(image)]
|
| 295 |
+
annulus_values = image[annulus & np.isfinite(image)]
|
| 296 |
+
eye_mean = float(eye_values.mean()) if eye_values.size else float("nan")
|
| 297 |
+
annulus_mean = float(annulus_values.mean()) if annulus_values.size else float("nan")
|
| 298 |
+
contrast = eye_mean - annulus_mean
|
| 299 |
+
eye_present = (
|
| 300 |
+
0.0
|
| 301 |
+
if not np.isfinite(contrast)
|
| 302 |
+
else float(contrast >= spec.eye_contrast_min)
|
| 303 |
+
)
|
| 304 |
+
out["eye_center_mean"] = eye_mean
|
| 305 |
+
out["cdo_annulus_mean"] = annulus_mean
|
| 306 |
+
out["eye_cdo_contrast"] = float(contrast)
|
| 307 |
+
out["eye_present"] = eye_present
|
| 308 |
+
return out
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def _deviation_angle_variance(image: np.ndarray, spec: FeatureSpec) -> dict[str, float]:
|
| 312 |
+
"""Circular variance of gradient angle minus radial angle. Not operational DAV."""
|
| 313 |
+
height, width = image.shape
|
| 314 |
+
yy, xx = np.mgrid[0:height, 0:width]
|
| 315 |
+
center_y = (height - 1) / 2.0
|
| 316 |
+
center_x = (width - 1) / 2.0
|
| 317 |
+
dy = yy - center_y
|
| 318 |
+
dx = xx - center_x
|
| 319 |
+
radius = np.hypot(dy, dx)
|
| 320 |
+
half = min(height, width) / 2.0
|
| 321 |
+
gradient_y, gradient_x = np.gradient(image)
|
| 322 |
+
magnitude = np.hypot(gradient_y, gradient_x)
|
| 323 |
+
radial_angle = np.arctan2(dy, dx)
|
| 324 |
+
gradient_angle = np.arctan2(gradient_y, gradient_x)
|
| 325 |
+
deviation = np.arctan2(
|
| 326 |
+
np.sin(gradient_angle - radial_angle),
|
| 327 |
+
np.cos(gradient_angle - radial_angle),
|
| 328 |
+
)
|
| 329 |
+
# Keep the ring at least two pixels thick. On a small crop the fractional
|
| 330 |
+
# width can otherwise fall between grid points and the statistic is empty.
|
| 331 |
+
width_px = max(spec.dav_annulus_width_fraction * half, 2.0)
|
| 332 |
+
out: dict[str, float] = {}
|
| 333 |
+
for index, fraction in enumerate(spec.dav_radii_fractions):
|
| 334 |
+
radius_px = fraction * half
|
| 335 |
+
annulus = (radius >= radius_px - width_px / 2.0) & (
|
| 336 |
+
radius <= radius_px + width_px / 2.0
|
| 337 |
+
)
|
| 338 |
+
# A zero gradient has no direction. arctan2(0, 0) is 0 and would
|
| 339 |
+
# look like a full circle of disagreement.
|
| 340 |
+
selected = deviation[annulus & (magnitude > 1e-6)]
|
| 341 |
+
if selected.size < 8:
|
| 342 |
+
out[f"dav_simplified_r{index:02d}"] = float("nan")
|
| 343 |
+
continue
|
| 344 |
+
mean_vector = np.exp(1j * selected).mean()
|
| 345 |
+
out[f"dav_simplified_r{index:02d}"] = float(1.0 - np.abs(mean_vector))
|
| 346 |
+
return out
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def _pair_counts(
|
| 350 |
+
bins: np.ndarray, valid: np.ndarray, dy: int, dx: int, levels: int
|
| 351 |
+
) -> np.ndarray | None:
|
| 352 |
+
height, width = bins.shape
|
| 353 |
+
if abs(dy) >= height or abs(dx) >= width:
|
| 354 |
+
return None
|
| 355 |
+
if dy >= 0:
|
| 356 |
+
src_y, dst_y = slice(0, height - dy), slice(dy, height)
|
| 357 |
+
else:
|
| 358 |
+
src_y, dst_y = slice(-dy, height), slice(0, height + dy)
|
| 359 |
+
if dx >= 0:
|
| 360 |
+
src_x, dst_x = slice(0, width - dx), slice(dx, width)
|
| 361 |
+
else:
|
| 362 |
+
src_x, dst_x = slice(-dx, width), slice(0, width + dx)
|
| 363 |
+
mask = valid[src_y, src_x] & valid[dst_y, dst_x]
|
| 364 |
+
if not mask.any():
|
| 365 |
+
return None
|
| 366 |
+
source = bins[src_y, src_x][mask].ravel()
|
| 367 |
+
dest = bins[dst_y, dst_x][mask].ravel()
|
| 368 |
+
flat = source.astype(np.int64) * levels + dest.astype(np.int64)
|
| 369 |
+
counts = np.bincount(flat, minlength=levels * levels).reshape(levels, levels)
|
| 370 |
+
total = float(counts.sum())
|
| 371 |
+
if total <= 0:
|
| 372 |
+
return None
|
| 373 |
+
return counts.astype(np.float64) / total
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def _haralick(probs: np.ndarray) -> dict[str, float]:
|
| 377 |
+
levels = probs.shape[0]
|
| 378 |
+
rows, cols = np.indices((levels, levels))
|
| 379 |
+
contrast = float(((rows - cols) ** 2 * probs).sum())
|
| 380 |
+
dissimilarity = float((np.abs(rows - cols) * probs).sum())
|
| 381 |
+
homogeneity = float((probs / (1.0 + (rows - cols) ** 2)).sum())
|
| 382 |
+
asm = float((probs**2).sum())
|
| 383 |
+
energy = float(np.sqrt(asm))
|
| 384 |
+
mean_i = float((rows * probs).sum())
|
| 385 |
+
mean_j = float((cols * probs).sum())
|
| 386 |
+
std_i = float(np.sqrt(((rows - mean_i) ** 2 * probs).sum()))
|
| 387 |
+
std_j = float(np.sqrt(((cols - mean_j) ** 2 * probs).sum()))
|
| 388 |
+
if std_i < 1e-12 or std_j < 1e-12:
|
| 389 |
+
correlation = 0.0
|
| 390 |
+
else:
|
| 391 |
+
correlation = float(
|
| 392 |
+
((rows - mean_i) * (cols - mean_j) * probs).sum() / (std_i * std_j)
|
| 393 |
+
)
|
| 394 |
+
return {
|
| 395 |
+
"glcm_contrast": contrast,
|
| 396 |
+
"glcm_dissimilarity": dissimilarity,
|
| 397 |
+
"glcm_homogeneity": homogeneity,
|
| 398 |
+
"glcm_energy": energy,
|
| 399 |
+
"glcm_correlation": correlation,
|
| 400 |
+
"glcm_asm": asm,
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def _glcm_features(image: np.ndarray, levels: int, distance: int) -> dict[str, float]:
|
| 405 |
+
height, width = image.shape
|
| 406 |
+
empty = {name: float("nan") for name in GLCM_NAMES}
|
| 407 |
+
if height <= distance or width <= distance:
|
| 408 |
+
return empty
|
| 409 |
+
finite = image[np.isfinite(image)]
|
| 410 |
+
if finite.size == 0:
|
| 411 |
+
return empty
|
| 412 |
+
low = float(finite.min())
|
| 413 |
+
high = float(finite.max())
|
| 414 |
+
if high - low < 1e-6:
|
| 415 |
+
bins = np.zeros(image.shape, dtype=np.int32)
|
| 416 |
+
else:
|
| 417 |
+
scaled = np.clip((image - low) / (high - low), 0.0, 1.0)
|
| 418 |
+
bins = np.minimum((scaled * levels).astype(np.int32), levels - 1)
|
| 419 |
+
valid = np.isfinite(image)
|
| 420 |
+
offsets = (
|
| 421 |
+
(0, distance),
|
| 422 |
+
(-distance, distance),
|
| 423 |
+
(-distance, 0),
|
| 424 |
+
(-distance, -distance),
|
| 425 |
+
)
|
| 426 |
+
collected = []
|
| 427 |
+
for dy, dx in offsets:
|
| 428 |
+
probs = _pair_counts(bins, valid, dy, dx, levels)
|
| 429 |
+
if probs is not None:
|
| 430 |
+
collected.append(_haralick(probs))
|
| 431 |
+
if not collected:
|
| 432 |
+
return empty
|
| 433 |
+
return {
|
| 434 |
+
name: float(np.mean([item[name] for item in collected])) for name in GLCM_NAMES
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def _haar_energies(image: np.ndarray) -> dict[str, float]:
|
| 439 |
+
band = image
|
| 440 |
+
if band.shape[0] % 2:
|
| 441 |
+
band = band[:-1, :]
|
| 442 |
+
if band.shape[1] % 2:
|
| 443 |
+
band = band[:, :-1]
|
| 444 |
+
if min(band.shape) < 2:
|
| 445 |
+
return {name: float("nan") for name in HAAR_NAMES}
|
| 446 |
+
even_even = band[0::2, 0::2]
|
| 447 |
+
even_odd = band[0::2, 1::2]
|
| 448 |
+
odd_even = band[1::2, 0::2]
|
| 449 |
+
odd_odd = band[1::2, 1::2]
|
| 450 |
+
low_low = (even_even + even_odd + odd_even + odd_odd) / 4.0
|
| 451 |
+
low_high = (even_even + odd_even - even_odd - odd_odd) / 4.0
|
| 452 |
+
high_low = (even_even - odd_even + even_odd - odd_odd) / 4.0
|
| 453 |
+
high_high = (even_even - odd_even - even_odd + odd_odd) / 4.0
|
| 454 |
+
energies = {
|
| 455 |
+
"haar_energy_ll": float(np.mean(low_low**2)),
|
| 456 |
+
"haar_energy_lh": float(np.mean(low_high**2)),
|
| 457 |
+
"haar_energy_hl": float(np.mean(high_low**2)),
|
| 458 |
+
"haar_energy_hh": float(np.mean(high_high**2)),
|
| 459 |
+
}
|
| 460 |
+
total = sum(energies.values())
|
| 461 |
+
if total <= 1e-12:
|
| 462 |
+
return {name: 0.0 for name in HAAR_NAMES}
|
| 463 |
+
return {name: value / total for name, value in energies.items()}
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def native_shape(image: np.ndarray) -> tuple[int, int]:
|
| 467 |
+
"""Height and width of one crop. This is not ``data.image_size``."""
|
| 468 |
+
channel = _single_channel(image)
|
| 469 |
+
return int(channel.shape[0]), int(channel.shape[1])
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def extract_image_features(
|
| 473 |
+
image: np.ndarray,
|
| 474 |
+
spec: FeatureSpec,
|
| 475 |
+
max_missing_fraction: float = MAX_MISSING_FRACTION,
|
| 476 |
+
) -> dict[str, float]:
|
| 477 |
+
"""Features of one centered IR crop. The label is not an input.
|
| 478 |
+
|
| 479 |
+
The crop is not resized. Callers that need the crop size use
|
| 480 |
+
``native_shape``, which reads the array. ``data.image_size`` is not applied.
|
| 481 |
+
"""
|
| 482 |
+
channel = _single_channel(image)
|
| 483 |
+
fraction = missing_fraction(channel)
|
| 484 |
+
if fraction > max_missing_fraction:
|
| 485 |
+
raise ValueError(
|
| 486 |
+
f"missing fraction {fraction:.2f} exceeds {max_missing_fraction:.2f}"
|
| 487 |
+
)
|
| 488 |
+
if not np.isfinite(channel).any():
|
| 489 |
+
raise ValueError("image has no finite pixels")
|
| 490 |
+
dense = _finite_fill(channel)
|
| 491 |
+
features: dict[str, float] = {}
|
| 492 |
+
features.update(_distribution(channel, spec.prefix))
|
| 493 |
+
features.update(_cold_coverage(channel, spec.cold_thresholds))
|
| 494 |
+
features.update(_radial_and_eye(channel, spec))
|
| 495 |
+
features.update(_deviation_angle_variance(dense, spec))
|
| 496 |
+
features.update(_glcm_features(dense, spec.glcm_levels, spec.glcm_distance))
|
| 497 |
+
features.update(_haar_energies(dense))
|
| 498 |
+
expected = spec.image_feature_names()
|
| 499 |
+
missing = [name for name in expected if name not in features]
|
| 500 |
+
if missing:
|
| 501 |
+
raise RuntimeError(f"feature extractor omitted {missing}")
|
| 502 |
+
return {name: float(features[name]) for name in expected}
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def _temporal_defaults(spec: FeatureSpec) -> dict[str, float]:
|
| 506 |
+
prefix = spec.prefix
|
| 507 |
+
return {
|
| 508 |
+
"has_prev": 0.0,
|
| 509 |
+
f"delta_{prefix}_mean": float("nan"),
|
| 510 |
+
f"delta_{prefix}_min": float("nan"),
|
| 511 |
+
"delta_cold_primary": float("nan"),
|
| 512 |
+
"delta_eye_cdo_contrast": float("nan"),
|
| 513 |
+
"delta_radial_mean_00": float("nan"),
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
|
| 517 |
+
# Optional frame labels. Copied when the manifest has them. Not model features.
|
| 518 |
+
_CARRIED_COLUMNS = (
|
| 519 |
+
"timestamp",
|
| 520 |
+
"relative_time_s",
|
| 521 |
+
"source_split",
|
| 522 |
+
"wind_averaging",
|
| 523 |
+
"wind_averaging_s",
|
| 524 |
+
"on_fix",
|
| 525 |
+
"near_land",
|
| 526 |
+
"distance_to_land_km",
|
| 527 |
+
"cv_group",
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def _extract_path(task: tuple[str, FeatureSpec, float]) -> dict[str, float]:
|
| 532 |
+
"""Load one image and return its feature dict. Used by the worker pool."""
|
| 533 |
+
path, spec, max_missing_fraction = task
|
| 534 |
+
return extract_image_features(load_image(path), spec, max_missing_fraction)
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def _spec_fingerprint(spec: FeatureSpec, max_missing_fraction: float) -> str:
|
| 538 |
+
"""Identity of the extractor settings stored next to an image checkpoint."""
|
| 539 |
+
payload = {
|
| 540 |
+
"calibrated": bool(spec.calibrated),
|
| 541 |
+
"cold_thresholds": [float(value) for value in spec.cold_thresholds],
|
| 542 |
+
"radial_bins": int(spec.radial_bins),
|
| 543 |
+
"eye_radius_fraction": float(spec.eye_radius_fraction),
|
| 544 |
+
"cdo_outer_fraction": float(spec.cdo_outer_fraction),
|
| 545 |
+
"eye_contrast_min": float(spec.eye_contrast_min),
|
| 546 |
+
"dav_radii_fractions": [float(value) for value in spec.dav_radii_fractions],
|
| 547 |
+
"dav_annulus_width_fraction": float(spec.dav_annulus_width_fraction),
|
| 548 |
+
"glcm_levels": int(spec.glcm_levels),
|
| 549 |
+
"glcm_distance": int(spec.glcm_distance),
|
| 550 |
+
"max_missing_fraction": float(max_missing_fraction),
|
| 551 |
+
}
|
| 552 |
+
return json.dumps(payload, sort_keys=True)
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def _checkpoint_spec_path(path: Path) -> Path:
|
| 556 |
+
return path.with_suffix(path.suffix + ".spec.json")
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
def _image_checkpoint_rows(
|
| 560 |
+
path: Path, spec: FeatureSpec, max_missing_fraction: float
|
| 561 |
+
) -> dict[str, dict[str, float]]:
|
| 562 |
+
if not path.is_file():
|
| 563 |
+
return {}
|
| 564 |
+
spec_path = _checkpoint_spec_path(path)
|
| 565 |
+
if not spec_path.is_file():
|
| 566 |
+
return {}
|
| 567 |
+
saved_spec = json.loads(spec_path.read_text(encoding="utf-8"))
|
| 568 |
+
if saved_spec.get("fingerprint") != _spec_fingerprint(spec, max_missing_fraction):
|
| 569 |
+
return {}
|
| 570 |
+
saved = pd.read_csv(path)
|
| 571 |
+
if "sample_id" not in saved.columns:
|
| 572 |
+
return {}
|
| 573 |
+
rows: dict[str, dict[str, float]] = {}
|
| 574 |
+
for record in saved.to_dict(orient="records"):
|
| 575 |
+
sample_id = str(record.pop("sample_id"))
|
| 576 |
+
rows[sample_id] = record
|
| 577 |
+
return rows
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def _write_image_checkpoint(
|
| 581 |
+
path: Path,
|
| 582 |
+
rows: dict[str, dict[str, float]],
|
| 583 |
+
spec: FeatureSpec,
|
| 584 |
+
max_missing_fraction: float,
|
| 585 |
+
) -> None:
|
| 586 |
+
records = [{"sample_id": sample_id, **features} for sample_id, features in rows.items()]
|
| 587 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 588 |
+
pd.DataFrame(records).to_csv(path, index=False)
|
| 589 |
+
_checkpoint_spec_path(path).write_text(
|
| 590 |
+
json.dumps(
|
| 591 |
+
{"fingerprint": _spec_fingerprint(spec, max_missing_fraction)},
|
| 592 |
+
indent=2,
|
| 593 |
+
sort_keys=True,
|
| 594 |
+
)
|
| 595 |
+
+ "\n",
|
| 596 |
+
encoding="utf-8",
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
def extract_feature_table(
|
| 601 |
+
frame: pd.DataFrame,
|
| 602 |
+
manifest_path: str,
|
| 603 |
+
spec: FeatureSpec,
|
| 604 |
+
max_missing_fraction: float = MAX_MISSING_FRACTION,
|
| 605 |
+
workers: int = 1,
|
| 606 |
+
image_checkpoint: str | Path | None = None,
|
| 607 |
+
) -> tuple[pd.DataFrame, int]:
|
| 608 |
+
"""Extract features and same-split temporal deltas.
|
| 609 |
+
|
| 610 |
+
Previous-frame ids are recomputed from ``storm_id`` and the observation
|
| 611 |
+
clock (``timestamp``, else NASA ``relative_time_s``), then any link that
|
| 612 |
+
crosses ``split`` is dropped before the delta is taken. ``workers`` above
|
| 613 |
+
1 only parallelizes the per-image extract. It does not change the values.
|
| 614 |
+
``image_checkpoint``, when set, stores per-image features so a restarted
|
| 615 |
+
run does not re-read frames that already finished. Temporal deltas are
|
| 616 |
+
still computed after every frame in this call has image features.
|
| 617 |
+
"""
|
| 618 |
+
if "split" not in frame.columns:
|
| 619 |
+
raise LeakageError("feature extraction requires a split column")
|
| 620 |
+
if workers < 1:
|
| 621 |
+
raise ValueError("workers must be at least 1")
|
| 622 |
+
linked = add_previous_frame_id(frame)
|
| 623 |
+
linked, dropped = null_cross_split_links(linked)
|
| 624 |
+
rows_in = linked.to_dict(orient="records")
|
| 625 |
+
tasks = [
|
| 626 |
+
(str(resolve_image(manifest_path, str(row["image_path"]))), spec, max_missing_fraction)
|
| 627 |
+
for row in rows_in
|
| 628 |
+
]
|
| 629 |
+
expected = spec.image_feature_names()
|
| 630 |
+
checkpoint = Path(image_checkpoint) if image_checkpoint else None
|
| 631 |
+
stored = (
|
| 632 |
+
_image_checkpoint_rows(checkpoint, spec, max_missing_fraction) if checkpoint else {}
|
| 633 |
+
)
|
| 634 |
+
extracted: list[dict[str, float] | None] = [None] * len(rows_in)
|
| 635 |
+
pending: list[int] = []
|
| 636 |
+
for index, row in enumerate(rows_in):
|
| 637 |
+
sample_id = str(row["sample_id"])
|
| 638 |
+
cached = stored.get(sample_id)
|
| 639 |
+
if cached is not None and all(name in cached for name in expected):
|
| 640 |
+
extracted[index] = {name: float(cached[name]) for name in expected}
|
| 641 |
+
else:
|
| 642 |
+
pending.append(index)
|
| 643 |
+
if pending:
|
| 644 |
+
logger.info("Extracting %s images (%s already cached)", len(pending), len(rows_in) - len(pending))
|
| 645 |
+
|
| 646 |
+
def _finish(index: int) -> tuple[int, dict[str, float]]:
|
| 647 |
+
return index, _extract_path(tasks[index])
|
| 648 |
+
|
| 649 |
+
batch = 200
|
| 650 |
+
if workers == 1:
|
| 651 |
+
for start in range(0, len(pending), batch):
|
| 652 |
+
chunk = pending[start : start + batch]
|
| 653 |
+
for index in chunk:
|
| 654 |
+
_index, features = _finish(index)
|
| 655 |
+
extracted[_index] = features
|
| 656 |
+
stored[str(rows_in[_index]["sample_id"])] = features
|
| 657 |
+
if checkpoint:
|
| 658 |
+
_write_image_checkpoint(checkpoint, stored, spec, max_missing_fraction)
|
| 659 |
+
logger.info("Image features %s/%s", min(start + batch, len(pending)), len(pending))
|
| 660 |
+
else:
|
| 661 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 662 |
+
|
| 663 |
+
with ThreadPoolExecutor(max_workers=workers) as pool:
|
| 664 |
+
for start in range(0, len(pending), batch):
|
| 665 |
+
chunk = pending[start : start + batch]
|
| 666 |
+
for index, features in pool.map(_finish, chunk):
|
| 667 |
+
extracted[index] = features
|
| 668 |
+
stored[str(rows_in[index]["sample_id"])] = features
|
| 669 |
+
if checkpoint:
|
| 670 |
+
_write_image_checkpoint(checkpoint, stored, spec, max_missing_fraction)
|
| 671 |
+
logger.info("Image features %s/%s", min(start + batch, len(pending)), len(pending))
|
| 672 |
+
if any(item is None for item in extracted):
|
| 673 |
+
raise RuntimeError("image feature extraction left a row empty")
|
| 674 |
+
cache: dict[str, tuple[str, dict[str, float]]] = {}
|
| 675 |
+
packed: list[tuple[dict[str, object], dict[str, float]]] = []
|
| 676 |
+
for row, image_features in zip(rows_in, extracted, strict=True):
|
| 677 |
+
sample_id = str(row["sample_id"])
|
| 678 |
+
cache[sample_id] = (str(row["split"]), image_features)
|
| 679 |
+
packed.append((row, image_features))
|
| 680 |
+
|
| 681 |
+
prefix = spec.prefix
|
| 682 |
+
cold_key = f"cold_frac_{_token(spec.cold_thresholds[0])}"
|
| 683 |
+
rows: list[dict[str, object]] = []
|
| 684 |
+
for row, image_features in packed:
|
| 685 |
+
temporal = _temporal_defaults(spec)
|
| 686 |
+
prev = row.get("prev_sample_id")
|
| 687 |
+
if not pd.isna(prev) and str(prev) in cache:
|
| 688 |
+
prev_split, previous = cache[str(prev)]
|
| 689 |
+
if prev_split != str(row["split"]):
|
| 690 |
+
raise LeakageError(
|
| 691 |
+
f"temporal feature for {row['sample_id']} crossed a split"
|
| 692 |
+
)
|
| 693 |
+
temporal["has_prev"] = 1.0
|
| 694 |
+
temporal[f"delta_{prefix}_mean"] = (
|
| 695 |
+
image_features[f"{prefix}_mean"] - previous[f"{prefix}_mean"]
|
| 696 |
+
)
|
| 697 |
+
temporal[f"delta_{prefix}_min"] = (
|
| 698 |
+
image_features[f"{prefix}_min"] - previous[f"{prefix}_min"]
|
| 699 |
+
)
|
| 700 |
+
temporal["delta_cold_primary"] = image_features[cold_key] - previous[cold_key]
|
| 701 |
+
temporal["delta_eye_cdo_contrast"] = (
|
| 702 |
+
image_features["eye_cdo_contrast"] - previous["eye_cdo_contrast"]
|
| 703 |
+
)
|
| 704 |
+
temporal["delta_radial_mean_00"] = (
|
| 705 |
+
image_features["radial_mean_00"] - previous["radial_mean_00"]
|
| 706 |
+
)
|
| 707 |
+
klass = row.get("imd5_class")
|
| 708 |
+
if pd.isna(klass):
|
| 709 |
+
klass = wind_to_imd5(float(row["wind_speed_kt"]))
|
| 710 |
+
built: dict[str, object] = {
|
| 711 |
+
"sample_id": str(row["sample_id"]),
|
| 712 |
+
"storm_id": str(row["storm_id"]),
|
| 713 |
+
"split": str(row["split"]),
|
| 714 |
+
"wind_speed_kt": float(row["wind_speed_kt"]),
|
| 715 |
+
"imd5_class": klass,
|
| 716 |
+
}
|
| 717 |
+
if "is_synthetic" in row:
|
| 718 |
+
built["is_synthetic"] = parse_is_synthetic(row["is_synthetic"])
|
| 719 |
+
for column in _CARRIED_COLUMNS:
|
| 720 |
+
if column in row:
|
| 721 |
+
built[column] = row[column]
|
| 722 |
+
built.update(image_features)
|
| 723 |
+
built.update(temporal)
|
| 724 |
+
rows.append(built)
|
| 725 |
+
table = pd.DataFrame(rows)
|
| 726 |
+
assert_no_forbidden_inputs(spec.feature_names(), "feature names include labels")
|
| 727 |
+
return table, dropped
|
| 728 |
+
|
| 729 |
+
|
| 730 |
+
def model_matrix(frame: pd.DataFrame, names: tuple[str, ...] | list[str]) -> np.ndarray:
|
| 731 |
+
"""Numeric feature matrix. Raises if a label column is requested."""
|
| 732 |
+
assert_no_forbidden_inputs(names, "forbidden features in model matrix")
|
| 733 |
+
missing = [name for name in names if name not in frame.columns]
|
| 734 |
+
if missing:
|
| 735 |
+
raise KeyError(f"missing feature columns: {missing}")
|
| 736 |
+
return frame.loc[:, list(names)].to_numpy(dtype=np.float64)
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
def _impute_matrix(values: np.ndarray) -> np.ndarray:
|
| 740 |
+
imputer = SimpleImputer(strategy="median", keep_empty_features=True)
|
| 741 |
+
filled = imputer.fit_transform(values)
|
| 742 |
+
return np.where(np.isfinite(filled), filled, 0.0)
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
def _training_view(
|
| 746 |
+
frame: pd.DataFrame, target: np.ndarray
|
| 747 |
+
) -> tuple[pd.DataFrame, np.ndarray, frozenset[str]]:
|
| 748 |
+
"""Rows whose storm is in the train side of ``storm_ids_by_split``.
|
| 749 |
+
|
| 750 |
+
Val and test rows stay in ``frame`` so a caller can pass a full manifest,
|
| 751 |
+
and they are dropped before any selection statistic is computed. A storm
|
| 752 |
+
that sits in two splits raises ``LeakageError``.
|
| 753 |
+
"""
|
| 754 |
+
if "storm_id" not in frame.columns or "split" not in frame.columns:
|
| 755 |
+
raise LeakageError("feature selection requires storm_id and split")
|
| 756 |
+
y = np.asarray(target, dtype=np.float64).ravel()
|
| 757 |
+
if len(y) != len(frame):
|
| 758 |
+
raise ValueError("target must align with the selection frame")
|
| 759 |
+
groups = storm_ids_by_split(frame)
|
| 760 |
+
train_ids = groups["train"]
|
| 761 |
+
if not train_ids:
|
| 762 |
+
raise LeakageError("feature selection needs at least one training storm")
|
| 763 |
+
mask = frame["storm_id"].astype(str).isin(train_ids).to_numpy()
|
| 764 |
+
mask = mask & (frame["split"].astype(str) == "train").to_numpy()
|
| 765 |
+
train = frame.loc[mask].reset_index(drop=True)
|
| 766 |
+
if train.empty:
|
| 767 |
+
raise LeakageError("feature selection needs at least one training storm")
|
| 768 |
+
return train, y[mask], train_ids
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
def select_features(
|
| 772 |
+
frame: pd.DataFrame,
|
| 773 |
+
feature_names: tuple[str, ...] | list[str],
|
| 774 |
+
target: np.ndarray,
|
| 775 |
+
*,
|
| 776 |
+
source_split: str,
|
| 777 |
+
correlation_threshold: float = 0.95,
|
| 778 |
+
max_features: int = 25,
|
| 779 |
+
method: str = "correlation_rf",
|
| 780 |
+
n_estimators: int = 40,
|
| 781 |
+
seed: int = 42,
|
| 782 |
+
) -> FeatureSelection:
|
| 783 |
+
"""Fit a correlation filter and RF importance or RFE on train storms.
|
| 784 |
+
|
| 785 |
+
Correlation filtering does not look at the label. Forest importance and
|
| 786 |
+
RFE do. Both see only the storms ``storm_ids_by_split`` assigns to train.
|
| 787 |
+
Changing val or test rows does not change the returned names.
|
| 788 |
+
"""
|
| 789 |
+
if source_split != "train":
|
| 790 |
+
raise LeakageError("feature selection is allowed on the train split only")
|
| 791 |
+
names = tuple(feature_names)
|
| 792 |
+
assert_no_forbidden_inputs(names, "forbidden features in selection")
|
| 793 |
+
train, y, train_storms = _training_view(frame, target)
|
| 794 |
+
if len(train) < 5:
|
| 795 |
+
raise ValueError("feature selection needs at least 5 training rows")
|
| 796 |
+
method = method.lower().strip()
|
| 797 |
+
if method not in {"correlation_rf", "rfe", "none"}:
|
| 798 |
+
raise ValueError(f"unknown selection method: {method}")
|
| 799 |
+
|
| 800 |
+
values = _impute_matrix(model_matrix(train, names))
|
| 801 |
+
variance = values.var(axis=0)
|
| 802 |
+
kept_mask = variance > 1e-8
|
| 803 |
+
dropped_variance = tuple(name for name, keep in zip(names, kept_mask, strict=True) if not keep)
|
| 804 |
+
kept_names = [name for name, keep in zip(names, kept_mask, strict=True) if keep]
|
| 805 |
+
kept_values = values[:, kept_mask]
|
| 806 |
+
if not kept_names:
|
| 807 |
+
raise ValueError("every candidate feature was constant on the train split")
|
| 808 |
+
|
| 809 |
+
dropped_correlation: list[str] = []
|
| 810 |
+
if method in {"correlation_rf", "rfe", "none"} and len(kept_names) > 1:
|
| 811 |
+
corr = np.corrcoef(kept_values, rowvar=False)
|
| 812 |
+
corr = np.where(np.isfinite(corr), corr, 0.0)
|
| 813 |
+
drop_flags = np.zeros(len(kept_names), dtype=bool)
|
| 814 |
+
for left in range(len(kept_names)):
|
| 815 |
+
if drop_flags[left]:
|
| 816 |
+
continue
|
| 817 |
+
for right in range(left + 1, len(kept_names)):
|
| 818 |
+
if drop_flags[right]:
|
| 819 |
+
continue
|
| 820 |
+
if abs(corr[left, right]) > correlation_threshold:
|
| 821 |
+
drop_flags[right] = True
|
| 822 |
+
dropped_correlation.append(kept_names[right])
|
| 823 |
+
kept_names = [name for name, drop in zip(kept_names, drop_flags, strict=True) if not drop]
|
| 824 |
+
kept_values = kept_values[:, ~drop_flags]
|
| 825 |
+
|
| 826 |
+
cap = max(1, int(max_features))
|
| 827 |
+
if method == "none":
|
| 828 |
+
chosen = kept_names[:cap]
|
| 829 |
+
importances: dict[str, float] = {}
|
| 830 |
+
elif method == "correlation_rf":
|
| 831 |
+
rank_cap = cap if len(kept_names) > cap else len(kept_names)
|
| 832 |
+
ranked, importances = _rank_by_forest(
|
| 833 |
+
kept_values, y, kept_names, rank_cap, n_estimators, seed
|
| 834 |
+
)
|
| 835 |
+
chosen = ranked if len(kept_names) > cap else kept_names
|
| 836 |
+
else:
|
| 837 |
+
chosen, importances = _rank_by_rfe(
|
| 838 |
+
kept_values, y, kept_names, min(cap, len(kept_names)), n_estimators, seed
|
| 839 |
+
)
|
| 840 |
+
|
| 841 |
+
return FeatureSelection(
|
| 842 |
+
names=tuple(chosen),
|
| 843 |
+
source_split=source_split,
|
| 844 |
+
importances=importances,
|
| 845 |
+
dropped_variance=dropped_variance,
|
| 846 |
+
dropped_correlation=tuple(dropped_correlation),
|
| 847 |
+
train_storms=train_storms,
|
| 848 |
+
)
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
def _rank_by_forest(
|
| 852 |
+
values: np.ndarray,
|
| 853 |
+
target: np.ndarray,
|
| 854 |
+
names: list[str],
|
| 855 |
+
cap: int,
|
| 856 |
+
n_estimators: int,
|
| 857 |
+
seed: int,
|
| 858 |
+
) -> tuple[list[str], dict[str, float]]:
|
| 859 |
+
forest = RandomForestRegressor(
|
| 860 |
+
n_estimators=max(10, int(n_estimators)),
|
| 861 |
+
max_depth=4,
|
| 862 |
+
random_state=seed,
|
| 863 |
+
n_jobs=1,
|
| 864 |
+
)
|
| 865 |
+
forest.fit(values, target)
|
| 866 |
+
importance = np.asarray(forest.feature_importances_, dtype=np.float64)
|
| 867 |
+
order = sorted(
|
| 868 |
+
range(len(names)),
|
| 869 |
+
key=lambda index: (-importance[index], names[index]),
|
| 870 |
+
)
|
| 871 |
+
chosen = [names[index] for index in order[:cap]]
|
| 872 |
+
return chosen, {names[index]: float(importance[index]) for index in order}
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def _rank_by_rfe(
|
| 876 |
+
values: np.ndarray,
|
| 877 |
+
target: np.ndarray,
|
| 878 |
+
names: list[str],
|
| 879 |
+
cap: int,
|
| 880 |
+
n_estimators: int,
|
| 881 |
+
seed: int,
|
| 882 |
+
) -> tuple[list[str], dict[str, float]]:
|
| 883 |
+
forest = RandomForestRegressor(
|
| 884 |
+
n_estimators=max(10, int(n_estimators)),
|
| 885 |
+
max_depth=4,
|
| 886 |
+
random_state=seed,
|
| 887 |
+
n_jobs=1,
|
| 888 |
+
)
|
| 889 |
+
step = max(1, len(names) // 10)
|
| 890 |
+
selector = RFE(
|
| 891 |
+
forest,
|
| 892 |
+
n_features_to_select=max(1, min(cap, len(names))),
|
| 893 |
+
step=step,
|
| 894 |
+
)
|
| 895 |
+
selector.fit(values, target)
|
| 896 |
+
ranking = np.asarray(selector.ranking_)
|
| 897 |
+
chosen = [name for name, keep in zip(names, selector.support_, strict=True) if keep]
|
| 898 |
+
importance = {name: float(1.0 / rank) for name, rank in zip(names, ranking, strict=True)}
|
| 899 |
+
return chosen, importance
|
bundle/src/incyde.py
ADDED
|
@@ -0,0 +1,778 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""INCYDE loader for the cropped INSAT-3D North Indian Ocean set.
|
| 2 |
+
|
| 3 |
+
Images come from the Zenodo 8015544 file ``Cropped_cyclone_data.zip``
|
| 4 |
+
(MD5 ``ed5dac254c689e5a327dee7580324347``). This module never downloads
|
| 5 |
+
that zip. Point ``paths.incyde_root`` at an extracted copy.
|
| 6 |
+
|
| 7 |
+
Filename times are IST (UTC+05:30). ``Sequence`` in the labels CSV is the
|
| 8 |
+
storm key. The trailing ``obj`` index is not a storm id. The default split
|
| 9 |
+
and the exclusion list are ``incyde/audit/storm_split.csv`` and
|
| 10 |
+
``incyde/audit/exclusions.csv``.
|
| 11 |
+
|
| 12 |
+
``on_fix``, ``distance_to_land_km``, and ``near_land`` are joined from
|
| 13 |
+
``incyde/audit/frame_flags.csv`` on the source filename. A ``rot_180``
|
| 14 |
+
copy inherits that source row. A filename the table does not list stays
|
| 15 |
+
unknown: ``on_fix`` is ``unknown``, the distance is null, and
|
| 16 |
+
``near_land`` is ``unknown``. Those gaps are not filled with false or
|
| 17 |
+
zero. The labels are already 3-minute winds, so the join does not
|
| 18 |
+
rescale them. ``basin`` value ``LAND`` is the IMD basin of a land
|
| 19 |
+
depression, not a frame landfall.
|
| 20 |
+
|
| 21 |
+
Only original frames and ``rot_180`` copies are kept. ``rot_180`` is
|
| 22 |
+
synthetic, stays with its source storm, and is train-only. Flips reverse
|
| 23 |
+
cyclone spin. ``rot_90`` and ``rot_270`` add black bars. Both are dropped.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import argparse
|
| 29 |
+
import hashlib
|
| 30 |
+
import re
|
| 31 |
+
from datetime import datetime, timedelta, timezone
|
| 32 |
+
from pathlib import Path
|
| 33 |
+
|
| 34 |
+
import numpy as np
|
| 35 |
+
import pandas as pd
|
| 36 |
+
|
| 37 |
+
from src.schema import require_valid
|
| 38 |
+
from src.splits import LeakageError
|
| 39 |
+
|
| 40 |
+
ZIP_MD5 = "ed5dac254c689e5a327dee7580324347"
|
| 41 |
+
WIND_AVERAGING = "3min"
|
| 42 |
+
WIND_AVERAGING_S = 180
|
| 43 |
+
CV_SEED = 42
|
| 44 |
+
YEAR_HOLDOUT_NOTE = (
|
| 45 |
+
"indicative only: different training years and images from "
|
| 46 |
+
"Agrawal et al. 2024, arXiv:2410.08218. Landfall frames are kept; "
|
| 47 |
+
"the audit outputs have no landfall flag."
|
| 48 |
+
)
|
| 49 |
+
KEPT_AUG = frozenset({"", "rot_180"})
|
| 50 |
+
DROPPED_AUG = frozenset({"flip_h", "flip_v", "rot_90", "rot_270"})
|
| 51 |
+
_IST = timezone(timedelta(hours=5, minutes=30))
|
| 52 |
+
_MONTHS = {
|
| 53 |
+
name: index
|
| 54 |
+
for index, name in enumerate(
|
| 55 |
+
("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"),
|
| 56 |
+
start=1,
|
| 57 |
+
)
|
| 58 |
+
}
|
| 59 |
+
_FILENAME = re.compile(
|
| 60 |
+
r"^(?P<day>\d{2})(?P<mon>[A-Za-z]{3})(?P<year>\d{4})_"
|
| 61 |
+
r"(?P<hour>\d{2})(?P<minute>\d{2})_(?P<obj>\d+)"
|
| 62 |
+
r"(?:_(?P<aug>flip_h|flip_v|rot_90|rot_180|rot_270))?\.jpe?g$",
|
| 63 |
+
re.IGNORECASE,
|
| 64 |
+
)
|
| 65 |
+
_AUG_SUFFIX = re.compile(
|
| 66 |
+
r"_(?:flip_h|flip_v|rot_90|rot_180|rot_270)(?=\.jpe?g$)",
|
| 67 |
+
re.IGNORECASE,
|
| 68 |
+
)
|
| 69 |
+
_STORM_ID = re.compile(r"^INCYDE-S\d+_IMD-(?P<year>\d{4})-\d+$")
|
| 70 |
+
_AUDIT_DIR = Path(__file__).resolve().parents[1] / "incyde" / "audit"
|
| 71 |
+
DEFAULT_STORM_SPLIT = _AUDIT_DIR / "storm_split.csv"
|
| 72 |
+
DEFAULT_EXCLUSIONS = _AUDIT_DIR / "exclusions.csv"
|
| 73 |
+
DEFAULT_FRAME_FLAGS = _AUDIT_DIR / "frame_flags.csv"
|
| 74 |
+
_FRAME_FLAG_COLUMNS = ("filename", "on_fix", "distance_to_land_km", "near_land")
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def imd_class_of(wind_kt: float) -> str:
|
| 78 |
+
"""IMD class on a 3-minute wind, in knots.
|
| 79 |
+
|
| 80 |
+
D ≤27, DD ≤33, CS ≤47, SCS ≤63, VSCS ≤89, ESCS ≤119, SuCS ≥120.
|
| 81 |
+
Below 17 kt is ``<17``. These are not the project's 17/34/48/64/91 bins.
|
| 82 |
+
"""
|
| 83 |
+
wind = float(wind_kt)
|
| 84 |
+
if wind < 17:
|
| 85 |
+
return "<17"
|
| 86 |
+
if wind <= 27:
|
| 87 |
+
return "D"
|
| 88 |
+
if wind <= 33:
|
| 89 |
+
return "DD"
|
| 90 |
+
if wind <= 47:
|
| 91 |
+
return "CS"
|
| 92 |
+
if wind <= 63:
|
| 93 |
+
return "SCS"
|
| 94 |
+
if wind <= 89:
|
| 95 |
+
return "VSCS"
|
| 96 |
+
if wind <= 119:
|
| 97 |
+
return "ESCS"
|
| 98 |
+
return "SuCS"
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def storm_year(storm_id: object) -> int:
|
| 102 |
+
"""Year from ``INCYDE-Sxx_IMD-yyyy-nnn``. Filename dates are not used."""
|
| 103 |
+
match = _STORM_ID.match(str(storm_id).strip())
|
| 104 |
+
if match is None:
|
| 105 |
+
raise ValueError(f"storm_id {storm_id!r} is not INCYDE-Sxx_IMD-yyyy-nnn")
|
| 106 |
+
return int(match.group("year"))
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def assert_one_storm_year(frame: pd.DataFrame) -> pd.Series:
|
| 110 |
+
"""Each storm id maps to one IMD year. A filename that crosses 1 January does not add a second year."""
|
| 111 |
+
years = frame["storm_id"].map(storm_year)
|
| 112 |
+
counts = pd.DataFrame({"storm_id": frame["storm_id"].astype(str), "year": years}).groupby("storm_id")["year"].nunique()
|
| 113 |
+
if bool((counts > 1).any()):
|
| 114 |
+
raise LeakageError("a storm_id maps to more than one year")
|
| 115 |
+
return years
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def archive_md5(path: str | Path) -> str:
|
| 119 |
+
"""MD5 of a local file. Does not download."""
|
| 120 |
+
digest = hashlib.md5(usedforsecurity=False)
|
| 121 |
+
with Path(path).open("rb") as handle:
|
| 122 |
+
for chunk in iter(lambda: handle.read(1 << 20), b""):
|
| 123 |
+
digest.update(chunk)
|
| 124 |
+
return digest.hexdigest()
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def assert_archive_md5(path: str | Path) -> None:
|
| 128 |
+
"""Refuse a cropped-zip copy whose MD5 is not the Zenodo value."""
|
| 129 |
+
found = archive_md5(path)
|
| 130 |
+
if found != ZIP_MD5:
|
| 131 |
+
raise ValueError(f"INCYDE archive md5 is {found}, expected {ZIP_MD5}")
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _optional_path(value: object, default: Path) -> Path:
|
| 135 |
+
if value is None:
|
| 136 |
+
return default
|
| 137 |
+
text = str(value).strip()
|
| 138 |
+
if text.lower() in {"", "none", "null"}:
|
| 139 |
+
return default
|
| 140 |
+
return Path(text)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def read_storm_split(path: str | Path | None = None) -> pd.DataFrame:
|
| 144 |
+
"""One row per Sequence. ``proposed_split`` is Bean's grouped split."""
|
| 145 |
+
table = pd.read_csv(_optional_path(path, DEFAULT_STORM_SPLIT))
|
| 146 |
+
table.columns = [str(column).strip() for column in table.columns]
|
| 147 |
+
required = {"Sequence", "storm_id", "proposed_split", "cooccurrence_group"}
|
| 148 |
+
missing = sorted(required - set(table.columns))
|
| 149 |
+
if missing:
|
| 150 |
+
raise ValueError(f"storm_split.csv missing {missing}")
|
| 151 |
+
out = table.copy()
|
| 152 |
+
out["Sequence"] = pd.to_numeric(out["Sequence"], errors="raise").astype(int)
|
| 153 |
+
out["storm_id"] = out["storm_id"].astype(str).str.strip()
|
| 154 |
+
out["proposed_split"] = out["proposed_split"].astype(str).str.strip()
|
| 155 |
+
out["cooccurrence_group"] = pd.to_numeric(out["cooccurrence_group"], errors="raise").astype(int)
|
| 156 |
+
if out["storm_id"].duplicated().any() or out["Sequence"].duplicated().any():
|
| 157 |
+
raise ValueError("storm_split.csv repeats a storm")
|
| 158 |
+
bad = sorted(set(out["proposed_split"]) - {"train", "val", "test"})
|
| 159 |
+
if bad:
|
| 160 |
+
raise ValueError(f"storm_split.csv has unknown splits {bad}")
|
| 161 |
+
assert_one_storm_year(out)
|
| 162 |
+
return out
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def read_exclusions(path: str | Path | None = None) -> pd.DataFrame:
|
| 166 |
+
table = pd.read_csv(_optional_path(path, DEFAULT_EXCLUSIONS))
|
| 167 |
+
table.columns = [str(column).strip() for column in table.columns]
|
| 168 |
+
required = {"filename", "qc_flag", "default_exclude"}
|
| 169 |
+
missing = sorted(required - set(table.columns))
|
| 170 |
+
if missing:
|
| 171 |
+
raise ValueError(f"exclusions.csv missing {missing}")
|
| 172 |
+
out = table.copy()
|
| 173 |
+
out["filename"] = out["filename"].astype(str).map(lambda name: Path(name).name)
|
| 174 |
+
out["qc_flag"] = out["qc_flag"].fillna("").astype(str)
|
| 175 |
+
out["default_exclude"] = [_is_true(value) for value in out["default_exclude"].tolist()]
|
| 176 |
+
if out["filename"].duplicated().any():
|
| 177 |
+
raise ValueError("exclusions.csv repeats a filename")
|
| 178 |
+
return out
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _is_true(value: object) -> bool:
|
| 182 |
+
if isinstance(value, (bool, np.bool_)):
|
| 183 |
+
return bool(value)
|
| 184 |
+
return str(value).strip().lower() in {"1", "true", "yes", "y", "t"}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _blank_flag(value: object) -> bool:
|
| 188 |
+
if value is None:
|
| 189 |
+
return True
|
| 190 |
+
try:
|
| 191 |
+
if pd.isna(value):
|
| 192 |
+
return True
|
| 193 |
+
except (TypeError, ValueError):
|
| 194 |
+
return False
|
| 195 |
+
return str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _on_fix_value(value: object) -> bool | str:
|
| 199 |
+
"""Explicit bool, or ``unknown`` when the audit did not decide.
|
| 200 |
+
|
| 201 |
+
``unknown`` is not stored as false. A later on-fix metric uses only
|
| 202 |
+
the true rows.
|
| 203 |
+
"""
|
| 204 |
+
if isinstance(value, (bool, np.bool_)):
|
| 205 |
+
return bool(value)
|
| 206 |
+
if _blank_flag(value):
|
| 207 |
+
return "unknown"
|
| 208 |
+
text = str(value).strip().lower()
|
| 209 |
+
if text in {"1", "true", "yes", "y", "t"}:
|
| 210 |
+
return True
|
| 211 |
+
if text in {"0", "false", "no", "n", "f"}:
|
| 212 |
+
return False
|
| 213 |
+
if text in {"unknown", "na", "n/a"}:
|
| 214 |
+
return "unknown"
|
| 215 |
+
raise ValueError(f"on_fix value {value!r} is not true, false, or unknown")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _near_land_token(value: object) -> str:
|
| 219 |
+
"""``true``, ``false``, or ``unknown``. Blank stays unknown."""
|
| 220 |
+
if isinstance(value, (bool, np.bool_)):
|
| 221 |
+
return "true" if bool(value) else "false"
|
| 222 |
+
if _blank_flag(value):
|
| 223 |
+
return "unknown"
|
| 224 |
+
text = str(value).strip().lower()
|
| 225 |
+
if text in {"1", "true", "yes", "y", "t"}:
|
| 226 |
+
return "true"
|
| 227 |
+
if text in {"0", "false", "no", "n", "f"}:
|
| 228 |
+
return "false"
|
| 229 |
+
if text in {"unknown", "na", "n/a"}:
|
| 230 |
+
return "unknown"
|
| 231 |
+
raise ValueError(f"near_land value {value!r} is not true, false, or unknown")
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _distance_km(value: object) -> float:
|
| 235 |
+
"""Kilometres, or NaN when the audit left the cell blank."""
|
| 236 |
+
if _blank_flag(value):
|
| 237 |
+
return float("nan")
|
| 238 |
+
try:
|
| 239 |
+
number = float(value)
|
| 240 |
+
except (TypeError, ValueError) as exc:
|
| 241 |
+
raise ValueError(f"distance_to_land_km value {value!r} is not a distance") from exc
|
| 242 |
+
if not np.isfinite(number):
|
| 243 |
+
return float("nan")
|
| 244 |
+
return number
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def read_frame_flags(path: str | Path | None = None) -> pd.DataFrame:
|
| 248 |
+
"""Original-frame flags. Augmented filenames are not required in the file."""
|
| 249 |
+
table = pd.read_csv(_optional_path(path, DEFAULT_FRAME_FLAGS))
|
| 250 |
+
table.columns = [str(column).strip() for column in table.columns]
|
| 251 |
+
missing = [column for column in _FRAME_FLAG_COLUMNS if column not in table.columns]
|
| 252 |
+
if missing:
|
| 253 |
+
raise ValueError(f"frame_flags.csv missing {missing}")
|
| 254 |
+
on_fix = [_on_fix_value(value) for value in table["on_fix"].tolist()]
|
| 255 |
+
out = pd.DataFrame(
|
| 256 |
+
{
|
| 257 |
+
"filename": table["filename"].astype(str).map(lambda name: Path(name).name),
|
| 258 |
+
"distance_to_land_km": [_distance_km(value) for value in table["distance_to_land_km"].tolist()],
|
| 259 |
+
"near_land": [_near_land_token(value) for value in table["near_land"].tolist()],
|
| 260 |
+
}
|
| 261 |
+
)
|
| 262 |
+
# Object dtype so a homogeneous true/false column stays a Python bool
|
| 263 |
+
# and an unknown cell is not coerced to false.
|
| 264 |
+
out["on_fix"] = pd.Series(on_fix, index=out.index, dtype=object)
|
| 265 |
+
if out["filename"].duplicated().any():
|
| 266 |
+
raise ValueError("frame_flags.csv repeats a filename")
|
| 267 |
+
return out
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def _flag_key(frame: pd.DataFrame) -> pd.Series:
|
| 271 |
+
"""Source filename. Augmented copies inherit; they are not their own key."""
|
| 272 |
+
if "source_frame_id" in frame.columns:
|
| 273 |
+
return frame["source_frame_id"].astype(str).map(lambda name: Path(name).name)
|
| 274 |
+
if "filename" in frame.columns:
|
| 275 |
+
return frame["filename"].astype(str).map(lambda name: Path(_AUG_SUFFIX.sub("", name)).name)
|
| 276 |
+
raise ValueError("frame flags need source_frame_id or filename")
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def attach_frame_flags(frame: pd.DataFrame, flags: pd.DataFrame) -> pd.DataFrame:
|
| 280 |
+
"""Add ``on_fix``, ``distance_to_land_km``, and ``near_land``.
|
| 281 |
+
|
| 282 |
+
The lookup key is the source filename, so a ``rot_180`` copy receives
|
| 283 |
+
the original frame's row. A miss stays unknown. Distance is not filled
|
| 284 |
+
with 0, and ``on_fix`` is not filled with false.
|
| 285 |
+
"""
|
| 286 |
+
lookup = flags.drop_duplicates("filename").set_index("filename")
|
| 287 |
+
on_fix: list[object] = []
|
| 288 |
+
distance: list[float] = []
|
| 289 |
+
near: list[str] = []
|
| 290 |
+
for key in _flag_key(frame).tolist():
|
| 291 |
+
if key not in lookup.index:
|
| 292 |
+
on_fix.append("unknown")
|
| 293 |
+
distance.append(float("nan"))
|
| 294 |
+
near.append("unknown")
|
| 295 |
+
continue
|
| 296 |
+
row = lookup.loc[key]
|
| 297 |
+
if isinstance(row, pd.DataFrame):
|
| 298 |
+
raise ValueError(f"frame_flags.csv repeats {key}")
|
| 299 |
+
on_fix.append(_on_fix_value(row["on_fix"]))
|
| 300 |
+
distance.append(_distance_km(row["distance_to_land_km"]))
|
| 301 |
+
near.append(_near_land_token(row["near_land"]))
|
| 302 |
+
out = frame.copy()
|
| 303 |
+
out["on_fix"] = pd.Series(on_fix, index=out.index, dtype=object)
|
| 304 |
+
out["distance_to_land_km"] = np.asarray(distance, dtype=float)
|
| 305 |
+
out["near_land"] = near
|
| 306 |
+
return out
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def parse_filename(filename: str) -> dict[str, object]:
|
| 310 |
+
"""Parse ``DDMONYYYY_HHMM_<obj>[_aug].jpg``. ``obj`` is not a storm id."""
|
| 311 |
+
name = Path(str(filename)).name
|
| 312 |
+
match = _FILENAME.match(name)
|
| 313 |
+
if match is None:
|
| 314 |
+
raise ValueError(
|
| 315 |
+
f"INCYDE filename {name} does not match DDMONYYYY_HHMM_<obj>[_aug].jpg"
|
| 316 |
+
)
|
| 317 |
+
parts = match.groupdict()
|
| 318 |
+
month = _MONTHS.get(parts["mon"].upper())
|
| 319 |
+
if month is None:
|
| 320 |
+
raise ValueError(f"INCYDE filename {name} has an unknown month")
|
| 321 |
+
ist = datetime(
|
| 322 |
+
int(parts["year"]),
|
| 323 |
+
month,
|
| 324 |
+
int(parts["day"]),
|
| 325 |
+
int(parts["hour"]),
|
| 326 |
+
int(parts["minute"]),
|
| 327 |
+
tzinfo=_IST,
|
| 328 |
+
)
|
| 329 |
+
utc = ist.astimezone(timezone.utc)
|
| 330 |
+
aug = "" if not parts["aug"] else parts["aug"].lower()
|
| 331 |
+
return {
|
| 332 |
+
"filename": name,
|
| 333 |
+
"time_ist": ist.isoformat(),
|
| 334 |
+
"time_utc": utc.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
| 335 |
+
"object_index": int(parts["obj"]),
|
| 336 |
+
"aug_type": aug,
|
| 337 |
+
"source_frame_id": _AUG_SUFFIX.sub("", name),
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def _source_table(frame: pd.DataFrame) -> pd.DataFrame:
|
| 342 |
+
"""Labels CSV or the audit manifest, reduced to one column set."""
|
| 343 |
+
columns = {str(column).strip(): column for column in frame.columns}
|
| 344 |
+
renamed = frame.rename(columns={raw: clean for clean, raw in columns.items()})
|
| 345 |
+
if "Sequence" in renamed.columns and ("MSWS kts" in renamed.columns or "label_kt" in renamed.columns):
|
| 346 |
+
wind_column = "MSWS kts" if "MSWS kts" in renamed.columns else "label_kt"
|
| 347 |
+
filename = renamed["filename"] if "filename" in renamed.columns else renamed["file"]
|
| 348 |
+
out = pd.DataFrame(
|
| 349 |
+
{
|
| 350 |
+
"sequence": pd.to_numeric(renamed["Sequence"], errors="raise").astype(int),
|
| 351 |
+
"filename": filename.astype(str),
|
| 352 |
+
"wind_kt": pd.to_numeric(renamed[wind_column], errors="coerce"),
|
| 353 |
+
"source_category": renamed["Category"].astype(str) if "Category" in renamed.columns else "",
|
| 354 |
+
"incyde_set": renamed["Set"].astype(str) if "Set" in renamed.columns else "",
|
| 355 |
+
"given_storm_id": renamed["storm_id"].astype(str) if "storm_id" in renamed.columns else pd.NA,
|
| 356 |
+
}
|
| 357 |
+
)
|
| 358 |
+
return out
|
| 359 |
+
if "storm_id" in renamed.columns and "label_kt" in renamed.columns:
|
| 360 |
+
filename = renamed["filename"] if "filename" in renamed.columns else renamed["file"]
|
| 361 |
+
sequence = renamed["incyde_sequence"] if "incyde_sequence" in renamed.columns else pd.Series(pd.NA, index=renamed.index)
|
| 362 |
+
category = renamed["label_class_imd"] if "label_class_imd" in renamed.columns else ""
|
| 363 |
+
return pd.DataFrame(
|
| 364 |
+
{
|
| 365 |
+
"sequence": pd.to_numeric(sequence, errors="coerce"),
|
| 366 |
+
"filename": filename.astype(str),
|
| 367 |
+
"wind_kt": pd.to_numeric(renamed["label_kt"], errors="coerce"),
|
| 368 |
+
"source_category": category.astype(str) if not isinstance(category, str) else category,
|
| 369 |
+
"incyde_set": renamed["incyde_set"].astype(str) if "incyde_set" in renamed.columns else "",
|
| 370 |
+
"given_storm_id": renamed["storm_id"].astype(str),
|
| 371 |
+
}
|
| 372 |
+
)
|
| 373 |
+
raise ValueError(
|
| 374 |
+
"INCYDE manifest needs the labels columns (Sequence, MSWS kts, filename) "
|
| 375 |
+
"or the audit columns (storm_id, label_kt, file)"
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def _locate_labels(root: Path) -> Path:
|
| 380 |
+
candidates = [
|
| 381 |
+
root / "Cropped_cyclone_labels.csv",
|
| 382 |
+
root / "Cropped_cyclone_data" / "Cropped_cyclone_labels.csv",
|
| 383 |
+
root / "labels.csv",
|
| 384 |
+
]
|
| 385 |
+
for path in candidates:
|
| 386 |
+
if path.is_file():
|
| 387 |
+
return path
|
| 388 |
+
raise FileNotFoundError(
|
| 389 |
+
f"No INCYDE labels CSV under {root}. This loader does not download imagery."
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def locate_image(root: Path, filename: str) -> Path:
|
| 394 |
+
name = Path(filename).name
|
| 395 |
+
candidates = [
|
| 396 |
+
root / name,
|
| 397 |
+
root / "Cropped_cyclone_images" / name,
|
| 398 |
+
root / "Cropped_cyclone_data" / "Cropped_cyclone_images" / name,
|
| 399 |
+
root / "Cropped_cyclone_data" / name,
|
| 400 |
+
]
|
| 401 |
+
for path in candidates:
|
| 402 |
+
if path.is_file():
|
| 403 |
+
return path
|
| 404 |
+
raise FileNotFoundError(
|
| 405 |
+
f"INCYDE image {name} is missing under {root}. This loader does not download imagery."
|
| 406 |
+
)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def _qc_tokens(flag: object) -> set[str]:
|
| 410 |
+
text = "" if flag is None or (isinstance(flag, float) and np.isnan(flag)) else str(flag)
|
| 411 |
+
return {part.strip() for part in text.split(";") if part.strip()}
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def _drop_reason(aug: str, exclude: bool, qc_flag: str, drop_qc_flags: set[str]) -> str | None:
|
| 415 |
+
if exclude:
|
| 416 |
+
return "default_exclude"
|
| 417 |
+
if aug in DROPPED_AUG:
|
| 418 |
+
return f"dropped aug {aug}"
|
| 419 |
+
if aug not in KEPT_AUG:
|
| 420 |
+
return f"unknown aug {aug or 'blank'}"
|
| 421 |
+
if drop_qc_flags and _qc_tokens(qc_flag) & drop_qc_flags:
|
| 422 |
+
return "drop_qc_flags"
|
| 423 |
+
return None
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def read_rows(
|
| 427 |
+
root: str | Path,
|
| 428 |
+
*,
|
| 429 |
+
manifest_csv: str | Path | None = None,
|
| 430 |
+
storm_split_csv: str | Path | None = None,
|
| 431 |
+
exclusions_csv: str | Path | None = None,
|
| 432 |
+
frame_flags_csv: str | Path | None = None,
|
| 433 |
+
drop_qc_flags: list[str] | tuple[str, ...] | None = None,
|
| 434 |
+
check_images: bool = True,
|
| 435 |
+
) -> tuple[pd.DataFrame, int]:
|
| 436 |
+
"""Frame rows before the final split. ``rot_180`` is still present.
|
| 437 |
+
|
| 438 |
+
Flips, ``rot_90``, ``rot_270``, and ``default_exclude`` rows are gone.
|
| 439 |
+
The returned count is how many source rows were dropped here.
|
| 440 |
+
"""
|
| 441 |
+
root = Path(root)
|
| 442 |
+
if not root.is_dir():
|
| 443 |
+
raise FileNotFoundError(
|
| 444 |
+
f"INCYDE root {root} is missing. Set paths.incyde_root to the extracted "
|
| 445 |
+
"Cropped_cyclone_data directory. This entrypoint does not download imagery."
|
| 446 |
+
)
|
| 447 |
+
label_path = Path(manifest_csv) if manifest_csv not in (None, "", "null") else _locate_labels(root)
|
| 448 |
+
if not label_path.is_file():
|
| 449 |
+
raise FileNotFoundError(f"INCYDE manifest {label_path} is missing. Nothing is downloaded.")
|
| 450 |
+
storms = read_storm_split(storm_split_csv)
|
| 451 |
+
exclusions = read_exclusions(exclusions_csv)
|
| 452 |
+
source = _source_table(pd.read_csv(label_path, encoding="utf-8-sig"))
|
| 453 |
+
parsed = [parse_filename(name) for name in source["filename"].tolist()]
|
| 454 |
+
parsed_frame = pd.DataFrame(parsed).drop(columns=["filename"])
|
| 455 |
+
work = pd.concat([source.reset_index(drop=True), parsed_frame], axis=1)
|
| 456 |
+
work["filename"] = work["filename"].map(lambda name: Path(str(name)).name)
|
| 457 |
+
by_sequence = storms.set_index("Sequence")
|
| 458 |
+
by_storm = storms.drop_duplicates("storm_id").set_index("storm_id")
|
| 459 |
+
storm_ids: list[str] = []
|
| 460 |
+
sequences: list[int] = []
|
| 461 |
+
proposed: list[str] = []
|
| 462 |
+
groups: list[int] = []
|
| 463 |
+
names: list[str] = []
|
| 464 |
+
basins: list[str] = []
|
| 465 |
+
for sequence, given in zip(work["sequence"].tolist(), work["given_storm_id"].tolist(), strict=True):
|
| 466 |
+
row = None
|
| 467 |
+
if pd.notna(sequence) and int(sequence) in by_sequence.index:
|
| 468 |
+
row = by_sequence.loc[int(sequence)]
|
| 469 |
+
elif isinstance(given, str) and given in by_storm.index:
|
| 470 |
+
row = by_storm.loc[given]
|
| 471 |
+
if row is None:
|
| 472 |
+
raise ValueError(f"no storm_split row for sequence {sequence!r} storm {given!r}")
|
| 473 |
+
if isinstance(row, pd.DataFrame):
|
| 474 |
+
raise ValueError(f"storm_split matched more than one row for sequence {sequence}")
|
| 475 |
+
storm_id = str(row["storm_id"]) if "storm_id" in row.index else str(row.name)
|
| 476 |
+
sequence_id = int(row["Sequence"]) if "Sequence" in row.index else int(row.name)
|
| 477 |
+
if isinstance(given, str) and given not in {"", "nan", "<NA>"} and given != storm_id:
|
| 478 |
+
raise ValueError(f"manifest storm_id {given} does not match storm_split.csv ({storm_id})")
|
| 479 |
+
storm_ids.append(storm_id)
|
| 480 |
+
sequences.append(sequence_id)
|
| 481 |
+
proposed.append(str(row["proposed_split"]))
|
| 482 |
+
groups.append(int(row["cooccurrence_group"]))
|
| 483 |
+
names.append("" if "name" not in row.index or pd.isna(row["name"]) else str(row["name"]))
|
| 484 |
+
basins.append("" if "basin" not in row.index or pd.isna(row["basin"]) else str(row["basin"]))
|
| 485 |
+
work["storm_id"] = storm_ids
|
| 486 |
+
work["sequence"] = sequences
|
| 487 |
+
work["proposed_split"] = proposed
|
| 488 |
+
work["cooccurrence_group"] = groups
|
| 489 |
+
work["name"] = names
|
| 490 |
+
work["basin"] = basins
|
| 491 |
+
qc = exclusions.set_index("filename")
|
| 492 |
+
flags = []
|
| 493 |
+
exclude = []
|
| 494 |
+
for filename in work["filename"].tolist():
|
| 495 |
+
if filename in qc.index:
|
| 496 |
+
flags.append(str(qc.at[filename, "qc_flag"]))
|
| 497 |
+
exclude.append(bool(qc.at[filename, "default_exclude"]))
|
| 498 |
+
else:
|
| 499 |
+
flags.append("")
|
| 500 |
+
exclude.append(False)
|
| 501 |
+
work["qc_flag"] = flags
|
| 502 |
+
drop_flags = {str(flag).strip() for flag in (drop_qc_flags or []) if str(flag).strip()}
|
| 503 |
+
reasons = [
|
| 504 |
+
_drop_reason(aug, dropped, flag, drop_flags)
|
| 505 |
+
for aug, dropped, flag in zip(work["aug_type"], exclude, work["qc_flag"], strict=True)
|
| 506 |
+
]
|
| 507 |
+
dropped_count = sum(reason is not None for reason in reasons)
|
| 508 |
+
kept = work.loc[[reason is None for reason in reasons]].reset_index(drop=True)
|
| 509 |
+
if kept.empty:
|
| 510 |
+
raise ValueError("INCYDE filters removed every row")
|
| 511 |
+
if kept["filename"].duplicated().any():
|
| 512 |
+
raise ValueError("INCYDE labels repeat a filename")
|
| 513 |
+
years = assert_one_storm_year(kept)
|
| 514 |
+
image_paths: list[str] = []
|
| 515 |
+
heights: list[int] = []
|
| 516 |
+
widths: list[int] = []
|
| 517 |
+
if check_images:
|
| 518 |
+
from PIL import Image
|
| 519 |
+
|
| 520 |
+
for filename in kept["filename"].tolist():
|
| 521 |
+
path = locate_image(root, filename)
|
| 522 |
+
image_paths.append(path.resolve().as_posix())
|
| 523 |
+
with Image.open(path) as image:
|
| 524 |
+
widths.append(int(image.width))
|
| 525 |
+
heights.append(int(image.height))
|
| 526 |
+
else:
|
| 527 |
+
image_paths = kept["filename"].tolist()
|
| 528 |
+
heights = [0] * len(kept)
|
| 529 |
+
widths = [0] * len(kept)
|
| 530 |
+
frame = pd.DataFrame(
|
| 531 |
+
{
|
| 532 |
+
"sample_id": [Path(name).stem for name in kept["filename"].tolist()],
|
| 533 |
+
"image_path": image_paths,
|
| 534 |
+
"storm_id": kept["storm_id"].astype(str),
|
| 535 |
+
"wind_speed_kt": kept["wind_kt"].to_numpy(dtype=float),
|
| 536 |
+
"wind_kt": kept["wind_kt"].to_numpy(dtype=float),
|
| 537 |
+
"wind_averaging": WIND_AVERAGING,
|
| 538 |
+
"wind_averaging_s": WIND_AVERAGING_S,
|
| 539 |
+
"is_synthetic": [aug == "rot_180" for aug in kept["aug_type"].tolist()],
|
| 540 |
+
"imd_class": [imd_class_of(wind) for wind in kept["wind_kt"].tolist()],
|
| 541 |
+
"split": kept["proposed_split"].astype(str),
|
| 542 |
+
"proposed_split": kept["proposed_split"].astype(str),
|
| 543 |
+
"cooccurrence_group": kept["cooccurrence_group"].astype(int),
|
| 544 |
+
"time_utc": kept["time_utc"].astype(str),
|
| 545 |
+
"time_ist": kept["time_ist"].astype(str),
|
| 546 |
+
"storm_year": years.to_numpy(dtype=int),
|
| 547 |
+
"aug_type": kept["aug_type"].astype(str),
|
| 548 |
+
"source_frame_id": kept["source_frame_id"].astype(str),
|
| 549 |
+
"object_index": kept["object_index"].astype(int),
|
| 550 |
+
"qc_flag": kept["qc_flag"].astype(str),
|
| 551 |
+
"incyde_sequence": kept["sequence"].astype(int),
|
| 552 |
+
"incyde_set": kept["incyde_set"].astype(str),
|
| 553 |
+
"source_category": kept["source_category"].astype(str),
|
| 554 |
+
"name": kept["name"].astype(str),
|
| 555 |
+
"basin": kept["basin"].astype(str),
|
| 556 |
+
"native_height": heights,
|
| 557 |
+
"native_width": widths,
|
| 558 |
+
"orig_size": [height if height == width else -1 for height, width in zip(heights, widths, strict=True)],
|
| 559 |
+
"sensor": "INSAT-3D",
|
| 560 |
+
"channel": "IR",
|
| 561 |
+
"pixel_units": "jpeg_uncalibrated",
|
| 562 |
+
"label_source": "incyde_imd_3min",
|
| 563 |
+
"center_source": "dataset_precentered",
|
| 564 |
+
}
|
| 565 |
+
)
|
| 566 |
+
# Join after the row filter so dropped augs are not looked up. The
|
| 567 |
+
# source filename is the key; unknown audit cells stay unknown.
|
| 568 |
+
flagged = attach_frame_flags(frame, read_frame_flags(frame_flags_csv))
|
| 569 |
+
return require_valid(flagged), int(dropped_count)
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def build_cv_folds(storms: pd.DataFrame, n_folds: int, seed: int) -> pd.DataFrame:
|
| 573 |
+
"""Storm-grouped folds over train+val only. Test storms are absent.
|
| 574 |
+
|
| 575 |
+
Groups are shuffled with ``seed`` and dealt round-robin, so every storm
|
| 576 |
+
in one ``cooccurrence_group`` shares a fold. The training path passes
|
| 577 |
+
``incyde.cv_seed`` (42 in the YAML).
|
| 578 |
+
"""
|
| 579 |
+
folds = int(n_folds)
|
| 580 |
+
if folds < 2:
|
| 581 |
+
raise ValueError("incyde.n_folds must be at least 2")
|
| 582 |
+
pool = storms.loc[storms["proposed_split"].astype(str).isin(["train", "val"])].drop_duplicates("storm_id")
|
| 583 |
+
if pool.empty:
|
| 584 |
+
raise ValueError("storm_cv needs train and val storms")
|
| 585 |
+
groups = sorted({int(group) for group in pool["cooccurrence_group"].tolist()})
|
| 586 |
+
order = np.random.default_rng(int(seed)).permutation(len(groups))
|
| 587 |
+
shuffled = [groups[int(index)] for index in order]
|
| 588 |
+
group_fold = {group: index % folds for index, group in enumerate(shuffled)}
|
| 589 |
+
out = pd.DataFrame(
|
| 590 |
+
{
|
| 591 |
+
"storm_id": pool["storm_id"].astype(str).tolist(),
|
| 592 |
+
"fold": [int(group_fold[int(group)]) for group in pool["cooccurrence_group"].tolist()],
|
| 593 |
+
}
|
| 594 |
+
)
|
| 595 |
+
return out.sort_values(["fold", "storm_id"]).reset_index(drop=True)
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def read_cv_folds(path: str | Path) -> pd.DataFrame:
|
| 599 |
+
"""Use a folds file verbatim. Columns are ``storm_id`` and ``fold``."""
|
| 600 |
+
table = pd.read_csv(path)
|
| 601 |
+
table.columns = [str(column).strip() for column in table.columns]
|
| 602 |
+
if "storm_id" not in table.columns or "fold" not in table.columns:
|
| 603 |
+
raise ValueError("cv folds csv needs columns storm_id and fold")
|
| 604 |
+
out = pd.DataFrame(
|
| 605 |
+
{
|
| 606 |
+
"storm_id": table["storm_id"].astype(str).str.strip(),
|
| 607 |
+
"fold": pd.to_numeric(table["fold"], errors="raise").astype(int),
|
| 608 |
+
}
|
| 609 |
+
)
|
| 610 |
+
if out["storm_id"].duplicated().any():
|
| 611 |
+
raise ValueError("cv folds csv repeats a storm_id")
|
| 612 |
+
return out.reset_index(drop=True)
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def validate_cv_folds(folds: pd.DataFrame, storms: pd.DataFrame) -> None:
|
| 616 |
+
"""No test storm, and no cooccurrence group spread across folds."""
|
| 617 |
+
test_ids = set(storms.loc[storms["proposed_split"].astype(str) == "test", "storm_id"].astype(str))
|
| 618 |
+
listed = set(folds["storm_id"].astype(str))
|
| 619 |
+
leaked = sorted(listed & test_ids)
|
| 620 |
+
if leaked:
|
| 621 |
+
raise LeakageError(f"cv folds include test storms {leaked[:8]}")
|
| 622 |
+
pool = storms.loc[storms["proposed_split"].astype(str).isin(["train", "val"])].drop_duplicates("storm_id")
|
| 623 |
+
pool_ids = set(pool["storm_id"].astype(str))
|
| 624 |
+
missing = sorted(pool_ids - listed)
|
| 625 |
+
extra = sorted(listed - pool_ids)
|
| 626 |
+
if missing:
|
| 627 |
+
raise ValueError(f"cv folds omit train/val storms {missing[:8]}")
|
| 628 |
+
if extra:
|
| 629 |
+
raise ValueError(f"cv folds name storms that are not train/val {extra[:8]}")
|
| 630 |
+
merged = pool.assign(storm_id=pool["storm_id"].astype(str)).merge(folds, on="storm_id", how="left")
|
| 631 |
+
spread = merged.groupby("cooccurrence_group")["fold"].nunique()
|
| 632 |
+
if bool((spread > 1).any()):
|
| 633 |
+
groups = [int(group) for group in spread.index[spread > 1].tolist()]
|
| 634 |
+
raise LeakageError(f"cooccurrence_group spans folds {groups[:8]}")
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def _folds_for(storms: pd.DataFrame, n_folds: int, seed: int, cv_folds_csv: str | Path | None) -> pd.DataFrame:
|
| 638 |
+
if cv_folds_csv not in (None, "", "null"):
|
| 639 |
+
folds = read_cv_folds(cv_folds_csv)
|
| 640 |
+
else:
|
| 641 |
+
folds = build_cv_folds(storms, n_folds, seed)
|
| 642 |
+
validate_cv_folds(folds, storms)
|
| 643 |
+
return folds
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def _assert_storms(frame: pd.DataFrame) -> None:
|
| 647 |
+
per_storm = frame.groupby(frame["storm_id"].astype(str))["split"].nunique()
|
| 648 |
+
if bool((per_storm > 1).any()):
|
| 649 |
+
raise LeakageError("a storm is in more than one split")
|
| 650 |
+
synthetic = frame["is_synthetic"].astype(bool) & frame["split"].astype(str).ne("train")
|
| 651 |
+
if bool(synthetic.any()):
|
| 652 |
+
raise LeakageError("synthetic INCYDE rows are train-only")
|
| 653 |
+
bad_aug = sorted(set(frame["aug_type"].astype(str)) - KEPT_AUG)
|
| 654 |
+
if bad_aug:
|
| 655 |
+
raise LeakageError(f"INCYDE kept dropped augmentations {bad_aug}")
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def _assert_groups(frame: pd.DataFrame) -> None:
|
| 659 |
+
spread = frame.groupby("cooccurrence_group")["split"].nunique()
|
| 660 |
+
if bool((spread > 1).any()):
|
| 661 |
+
raise LeakageError("a cooccurrence_group is in more than one split")
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def assign_incyde_split(
|
| 665 |
+
frame: pd.DataFrame,
|
| 666 |
+
strategy: str,
|
| 667 |
+
*,
|
| 668 |
+
n_folds: int = 5,
|
| 669 |
+
cv_val_fold: int = 0,
|
| 670 |
+
cv_seed: int = CV_SEED,
|
| 671 |
+
cv_folds_csv: str | Path | None = None,
|
| 672 |
+
) -> tuple[pd.DataFrame, int]:
|
| 673 |
+
"""Write ``split`` and drop synthetic rows that are not in train.
|
| 674 |
+
|
| 675 |
+
``storm_wise`` uses ``proposed_split`` (60/14/17 on the audit file).
|
| 676 |
+
``storm_cv`` keeps test storms out of the folds. ``year_holdout_2019``
|
| 677 |
+
puts 2019 in test and 2021 in val. The year comes from ``storm_id``.
|
| 678 |
+
"""
|
| 679 |
+
name = str(strategy).strip().lower()
|
| 680 |
+
work = frame.copy()
|
| 681 |
+
if "proposed_split" not in work.columns:
|
| 682 |
+
raise ValueError("INCYDE rows need proposed_split from storm_split.csv")
|
| 683 |
+
storms = work.groupby("storm_id", as_index=False).agg(
|
| 684 |
+
proposed_split=("proposed_split", "first"),
|
| 685 |
+
cooccurrence_group=("cooccurrence_group", "first"),
|
| 686 |
+
)
|
| 687 |
+
assert_one_storm_year(work)
|
| 688 |
+
if name in {"storm_wise", "proposed", "bean"}:
|
| 689 |
+
work["split"] = work["proposed_split"].astype(str)
|
| 690 |
+
_assert_groups(work)
|
| 691 |
+
elif name == "storm_cv":
|
| 692 |
+
using_file = cv_folds_csv not in (None, "", "null")
|
| 693 |
+
folds = _folds_for(storms, n_folds, cv_seed, cv_folds_csv)
|
| 694 |
+
chosen = int(cv_val_fold)
|
| 695 |
+
if not using_file and (chosen < 0 or chosen >= int(n_folds)):
|
| 696 |
+
raise ValueError("incyde.cv_val_fold is outside 0 .. n_folds-1")
|
| 697 |
+
fold_of = dict(zip(folds["storm_id"].astype(str), folds["fold"].astype(int), strict=True))
|
| 698 |
+
splits = []
|
| 699 |
+
for storm_id, proposed in zip(work["storm_id"].astype(str), work["proposed_split"].astype(str), strict=True):
|
| 700 |
+
if proposed == "test":
|
| 701 |
+
splits.append("test")
|
| 702 |
+
else:
|
| 703 |
+
splits.append("val" if fold_of[storm_id] == chosen else "train")
|
| 704 |
+
work["split"] = splits
|
| 705 |
+
work["cv_fold"] = work["storm_id"].astype(str).map(lambda storm_id: fold_of.get(storm_id, pd.NA))
|
| 706 |
+
_assert_groups(work)
|
| 707 |
+
elif name == "year_holdout_2019":
|
| 708 |
+
years = work["storm_id"].map(storm_year)
|
| 709 |
+
work["split"] = np.where(years.eq(2019), "test", np.where(years.eq(2021), "val", "train"))
|
| 710 |
+
else:
|
| 711 |
+
raise LeakageError(f"unknown INCYDE split strategy {strategy}")
|
| 712 |
+
synthetic_eval = work["is_synthetic"].astype(bool) & work["split"].astype(str).ne("train")
|
| 713 |
+
dropped = int(synthetic_eval.sum())
|
| 714 |
+
work = work.loc[~synthetic_eval].reset_index(drop=True)
|
| 715 |
+
_assert_storms(work)
|
| 716 |
+
for split_name in ("train", "val", "test"):
|
| 717 |
+
if split_name not in set(work["split"].astype(str)):
|
| 718 |
+
raise LeakageError(f"INCYDE split {name} produced no {split_name} rows")
|
| 719 |
+
return work, dropped
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
def load_frame(config: dict) -> tuple[pd.DataFrame, int]:
|
| 723 |
+
"""Rows for ``python -m src.train --dataset incyde``. Nothing is downloaded."""
|
| 724 |
+
paths = config["paths"]
|
| 725 |
+
block = config["incyde"]
|
| 726 |
+
archive = block["archive"]
|
| 727 |
+
if archive not in (None, "", "null"):
|
| 728 |
+
assert_archive_md5(archive)
|
| 729 |
+
frame, dropped = read_rows(
|
| 730 |
+
paths["incyde_root"],
|
| 731 |
+
manifest_csv=block["manifest_csv"],
|
| 732 |
+
storm_split_csv=block["storm_split_csv"],
|
| 733 |
+
exclusions_csv=block["exclusions_csv"],
|
| 734 |
+
frame_flags_csv=block.get("frame_flags_csv"),
|
| 735 |
+
drop_qc_flags=list(block["drop_qc_flags"] or []),
|
| 736 |
+
check_images=True,
|
| 737 |
+
)
|
| 738 |
+
assigned, synthetic_dropped = assign_incyde_split(
|
| 739 |
+
frame,
|
| 740 |
+
str(config["split"]["strategy"]),
|
| 741 |
+
n_folds=int(block["n_folds"]),
|
| 742 |
+
cv_val_fold=int(block["cv_val_fold"]),
|
| 743 |
+
cv_seed=int(block["cv_seed"]),
|
| 744 |
+
cv_folds_csv=block["cv_folds_csv"],
|
| 745 |
+
)
|
| 746 |
+
return assigned, int(dropped) + int(synthetic_dropped)
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def main(argv: list[str] | None = None) -> Path:
|
| 750 |
+
"""Write a manifest from a local extracted tree. Does not download."""
|
| 751 |
+
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
| 752 |
+
parser.add_argument("--root", type=Path, required=True)
|
| 753 |
+
parser.add_argument("--manifest-csv", type=Path, default=None)
|
| 754 |
+
parser.add_argument("--storm-split", type=Path, default=None)
|
| 755 |
+
parser.add_argument("--exclusions", type=Path, default=None)
|
| 756 |
+
parser.add_argument("--frame-flags", type=Path, default=None)
|
| 757 |
+
parser.add_argument("--out", type=Path, required=True)
|
| 758 |
+
parser.add_argument("--strategy", default="storm_wise")
|
| 759 |
+
parser.add_argument("--archive", type=Path, default=None)
|
| 760 |
+
args = parser.parse_args(argv)
|
| 761 |
+
if args.archive is not None:
|
| 762 |
+
assert_archive_md5(args.archive)
|
| 763 |
+
frame, dropped = read_rows(
|
| 764 |
+
args.root,
|
| 765 |
+
manifest_csv=args.manifest_csv,
|
| 766 |
+
storm_split_csv=args.storm_split,
|
| 767 |
+
exclusions_csv=args.exclusions,
|
| 768 |
+
frame_flags_csv=args.frame_flags,
|
| 769 |
+
)
|
| 770 |
+
assigned, synthetic_dropped = assign_incyde_split(frame, args.strategy)
|
| 771 |
+
args.out.parent.mkdir(parents=True, exist_ok=True)
|
| 772 |
+
assigned.to_csv(args.out, index=False)
|
| 773 |
+
print(f"Wrote {args.out} ({len(assigned)} rows, dropped {dropped + synthetic_dropped}). Not a forecast.")
|
| 774 |
+
return args.out
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
if __name__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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Image gate, scale-relative geometry, and an honest intensity estimate.
|
| 2 |
+
|
| 3 |
+
This is not an operational forecast. A single infrared frame cannot
|
| 4 |
+
forecast landfall. Confidence is uncalibrated unless a matching
|
| 5 |
+
real-data run record includes a coverage check or a held-out storm
|
| 6 |
+
check. The intensity category is this project's grouping on the
|
| 7 |
+
configured knot bins, not an official IMD class.
|
| 8 |
+
|
| 9 |
+
The network is reached only through :class:`src.model_access.ModelAccess`.
|
| 10 |
+
Letterboxing happens before ``src.preprocessing.prepare_image``, which
|
| 11 |
+
resizes a square to the checkpoint size. Southern Hemisphere frames stay
|
| 12 |
+
unflipped via ``src.preprocessing.leave_unflipped``.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import math
|
| 19 |
+
import os
|
| 20 |
+
from dataclasses import dataclass
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
from src.config import image_sizes_match, parse_image_size
|
| 26 |
+
from src.model_access import ModelAccess
|
| 27 |
+
from src.schema import wind_to_imd5
|
| 28 |
+
|
| 29 |
+
# Shared with the web demo. cloudie.app re-exports these names.
|
| 30 |
+
NO_TRAINED_MODEL_BANNER = (
|
| 31 |
+
"No trained model yet. This page cannot produce estimates. "
|
| 32 |
+
"Not a forecast or warning system. "
|
| 33 |
+
"Best-track labels are noisy, and no survey or smoke number is a result of this project."
|
| 34 |
+
)
|
| 35 |
+
PAGE_LEAD = "Predict cyclone wind speed and intensity category from an infrared image."
|
| 36 |
+
CONFIDENCE_NOTE = (
|
| 37 |
+
"Confidence mixes the image gate, dropout spread, and a residual-quantile "
|
| 38 |
+
"width when one exists. It is uncalibrated until a held-out storm check exists. "
|
| 39 |
+
"It is not a forecast interval."
|
| 40 |
+
)
|
| 41 |
+
SCALE_NOTE = (
|
| 42 |
+
"Reported winds stay between 0 and 200 kt: below depression, depression, "
|
| 43 |
+
"cyclonic storm, severe, very severe, and extremely severe or super cyclonic storm. "
|
| 44 |
+
"Those names are this project's grouping, not an official IMD class."
|
| 45 |
+
)
|
| 46 |
+
GROUPING_LABEL = "Project grouping"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _section(config: dict, *keys: str):
|
| 50 |
+
cursor = config
|
| 51 |
+
walked: list[str] = []
|
| 52 |
+
for key in keys:
|
| 53 |
+
walked.append(key)
|
| 54 |
+
if not isinstance(cursor, dict) or key not in cursor:
|
| 55 |
+
raise ValueError(f"config {'.'.join(walked)} is required")
|
| 56 |
+
cursor = cursor[key]
|
| 57 |
+
return cursor
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _finite(raw, path: str) -> float:
|
| 61 |
+
try:
|
| 62 |
+
value = float(raw)
|
| 63 |
+
except (TypeError, ValueError) as exc:
|
| 64 |
+
raise ValueError(f"config {path} must be a number") from exc
|
| 65 |
+
if not math.isfinite(value):
|
| 66 |
+
raise ValueError(f"config {path} must be finite")
|
| 67 |
+
return value
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@dataclass(frozen=True)
|
| 71 |
+
class GateSettings:
|
| 72 |
+
"""Thresholds for the infrared-cyclone gate. All of them come from config."""
|
| 73 |
+
|
| 74 |
+
refusal: str
|
| 75 |
+
grayscale_tolerance: float
|
| 76 |
+
min_std: float
|
| 77 |
+
min_symmetry: float
|
| 78 |
+
min_cold_concentration: float
|
| 79 |
+
cold_radius_fraction: float
|
| 80 |
+
cold_tail_fraction: float
|
| 81 |
+
eye_radius_fraction: float
|
| 82 |
+
eyewall_outer_fraction: float
|
| 83 |
+
outer_inner_fraction: float
|
| 84 |
+
outer_outer_fraction: float
|
| 85 |
+
min_wall_contrast: float
|
| 86 |
+
radial_bins: int
|
| 87 |
+
cold_value: str
|
| 88 |
+
max_dropout_std_kt: float
|
| 89 |
+
concentration_reference: float
|
| 90 |
+
|
| 91 |
+
@staticmethod
|
| 92 |
+
def from_config(config: dict) -> GateSettings:
|
| 93 |
+
raw = _section(config, "predict", "gate")
|
| 94 |
+
settings = GateSettings(
|
| 95 |
+
refusal=str(raw["refusal"]).strip(),
|
| 96 |
+
grayscale_tolerance=_finite(raw["grayscale_tolerance"], "predict.gate.grayscale_tolerance"),
|
| 97 |
+
min_std=_finite(raw["min_std"], "predict.gate.min_std"),
|
| 98 |
+
min_symmetry=_finite(raw["min_symmetry"], "predict.gate.min_symmetry"),
|
| 99 |
+
min_cold_concentration=_finite(
|
| 100 |
+
raw["min_cold_concentration"], "predict.gate.min_cold_concentration"
|
| 101 |
+
),
|
| 102 |
+
cold_radius_fraction=_finite(
|
| 103 |
+
raw["cold_radius_fraction"], "predict.gate.cold_radius_fraction"
|
| 104 |
+
),
|
| 105 |
+
cold_tail_fraction=_finite(raw["cold_tail_fraction"], "predict.gate.cold_tail_fraction"),
|
| 106 |
+
eye_radius_fraction=_finite(raw["eye_radius_fraction"], "predict.gate.eye_radius_fraction"),
|
| 107 |
+
eyewall_outer_fraction=_finite(
|
| 108 |
+
raw["eyewall_outer_fraction"], "predict.gate.eyewall_outer_fraction"
|
| 109 |
+
),
|
| 110 |
+
outer_inner_fraction=_finite(raw["outer_inner_fraction"], "predict.gate.outer_inner_fraction"),
|
| 111 |
+
outer_outer_fraction=_finite(raw["outer_outer_fraction"], "predict.gate.outer_outer_fraction"),
|
| 112 |
+
min_wall_contrast=_finite(raw["min_wall_contrast"], "predict.gate.min_wall_contrast"),
|
| 113 |
+
radial_bins=int(raw["radial_bins"]),
|
| 114 |
+
cold_value=str(raw["cold_value"]).strip(),
|
| 115 |
+
max_dropout_std_kt=_finite(raw["max_dropout_std_kt"], "predict.gate.max_dropout_std_kt"),
|
| 116 |
+
concentration_reference=_finite(
|
| 117 |
+
raw["concentration_reference"], "predict.gate.concentration_reference"
|
| 118 |
+
),
|
| 119 |
+
)
|
| 120 |
+
if not settings.refusal:
|
| 121 |
+
raise ValueError("config predict.gate.refusal is empty")
|
| 122 |
+
if settings.cold_value not in {"auto", "low", "high"}:
|
| 123 |
+
raise ValueError("config predict.gate.cold_value must be auto, low, or high")
|
| 124 |
+
if settings.radial_bins < 2:
|
| 125 |
+
raise ValueError("config predict.gate.radial_bins must be at least 2")
|
| 126 |
+
if settings.concentration_reference <= 0:
|
| 127 |
+
raise ValueError("config predict.gate.concentration_reference must be positive")
|
| 128 |
+
if settings.max_dropout_std_kt <= 0:
|
| 129 |
+
raise ValueError("config predict.gate.max_dropout_std_kt must be positive")
|
| 130 |
+
radii = (
|
| 131 |
+
settings.eye_radius_fraction,
|
| 132 |
+
settings.eyewall_outer_fraction,
|
| 133 |
+
settings.outer_inner_fraction,
|
| 134 |
+
settings.outer_outer_fraction,
|
| 135 |
+
)
|
| 136 |
+
if not (0 < radii[0] < radii[1] < radii[2] < radii[3] <= 1):
|
| 137 |
+
raise ValueError("config predict.gate radii must increase and stay within (0, 1]")
|
| 138 |
+
if not 0 < settings.cold_radius_fraction <= 1:
|
| 139 |
+
raise ValueError("config predict.gate.cold_radius_fraction must be in (0, 1]")
|
| 140 |
+
if not 0 < settings.cold_tail_fraction < 0.5:
|
| 141 |
+
raise ValueError("config predict.gate.cold_tail_fraction must be in (0, 0.5)")
|
| 142 |
+
if settings.min_std < 0:
|
| 143 |
+
raise ValueError("config predict.gate.min_std must be >= 0")
|
| 144 |
+
return settings
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@dataclass(frozen=True)
|
| 148 |
+
class GateReport:
|
| 149 |
+
"""One frame's gate. ``score`` is 0 when the frame is refused."""
|
| 150 |
+
|
| 151 |
+
accepted: bool
|
| 152 |
+
reason: str
|
| 153 |
+
score: float
|
| 154 |
+
field: np.ndarray | None
|
| 155 |
+
symmetry: float | None = None
|
| 156 |
+
cold_concentration: float | None = None
|
| 157 |
+
wall_contrast: float | None = None
|
| 158 |
+
eye_contrast: float | None = None
|
| 159 |
+
polarity: str | None = None
|
| 160 |
+
|
| 161 |
+
def feature_map(self) -> dict[str, float]:
|
| 162 |
+
"""Scale-relative summaries. None of these are pixel counts."""
|
| 163 |
+
return {
|
| 164 |
+
"symmetry": 0.0 if self.symmetry is None else float(self.symmetry),
|
| 165 |
+
"cold_concentration": (
|
| 166 |
+
0.0 if self.cold_concentration is None else float(self.cold_concentration)
|
| 167 |
+
),
|
| 168 |
+
"wall_contrast": 0.0 if self.wall_contrast is None else float(self.wall_contrast),
|
| 169 |
+
"eye_contrast": 0.0 if self.eye_contrast is None else float(self.eye_contrast),
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class FrameGeometry:
|
| 174 |
+
"""Pad a frame to a square without stretching it.
|
| 175 |
+
|
| 176 |
+
``prepare_image`` then resizes that square to the checkpoint size.
|
| 177 |
+
A square input is returned unchanged, so the resize is the only resample.
|
| 178 |
+
"""
|
| 179 |
+
|
| 180 |
+
@staticmethod
|
| 181 |
+
def mode(config: dict) -> str:
|
| 182 |
+
mode = str(_section(config, "data", "resize")).strip()
|
| 183 |
+
if mode not in {"letterbox", "stretch"}:
|
| 184 |
+
raise ValueError("config data.resize must be letterbox or stretch")
|
| 185 |
+
return mode
|
| 186 |
+
|
| 187 |
+
@staticmethod
|
| 188 |
+
def pad_square(image: np.ndarray, pad: str) -> np.ndarray:
|
| 189 |
+
"""Return a square view of one channel. ``pad`` is ``median``."""
|
| 190 |
+
if pad != "median":
|
| 191 |
+
raise ValueError("config data.pad must be median")
|
| 192 |
+
array = np.asarray(image, dtype=np.float32)
|
| 193 |
+
if array.ndim != 2:
|
| 194 |
+
raise ValueError("letterbox expects one infrared channel")
|
| 195 |
+
height, width = array.shape
|
| 196 |
+
if height == width:
|
| 197 |
+
return array
|
| 198 |
+
side = max(height, width)
|
| 199 |
+
finite = array[np.isfinite(array)]
|
| 200 |
+
fill = float(np.median(finite)) if finite.size else 0.0
|
| 201 |
+
canvas = np.full((side, side), fill, dtype=np.float32)
|
| 202 |
+
top = (side - height) // 2
|
| 203 |
+
left = (side - width) // 2
|
| 204 |
+
canvas[top : top + height, left : left + width] = array
|
| 205 |
+
return canvas
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class CycloneImageGate:
|
| 209 |
+
"""Decide whether a frame is a plausible tropical-cyclone infrared image.
|
| 210 |
+
|
| 211 |
+
The checks are a single greyscale channel, a cold core relative to the
|
| 212 |
+
frame, and radial organization. A colour-enhanced RGB or RGBA frame is
|
| 213 |
+
refused before those checks. Radii are fractions of the half-width.
|
| 214 |
+
Model uncertainty is applied later by :meth:`uncertainty_reason`. A
|
| 215 |
+
refusal is not a wind speed.
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
@staticmethod
|
| 219 |
+
def uncertainty_reason(std_kt: float | None, settings: GateSettings) -> str | None:
|
| 220 |
+
"""Refuse when dropout spread exceeds the configured limit."""
|
| 221 |
+
if std_kt is None:
|
| 222 |
+
return None
|
| 223 |
+
if float(std_kt) > settings.max_dropout_std_kt:
|
| 224 |
+
return (
|
| 225 |
+
f"model uncertainty {float(std_kt):.1f} kt exceeds the configured "
|
| 226 |
+
f"limit of {settings.max_dropout_std_kt:.0f} kt"
|
| 227 |
+
)
|
| 228 |
+
return None
|
| 229 |
+
|
| 230 |
+
@staticmethod
|
| 231 |
+
def assess(image: np.ndarray, settings: GateSettings) -> GateReport:
|
| 232 |
+
planes, channel_reason = CycloneImageGate._planes(image, settings)
|
| 233 |
+
if channel_reason is not None:
|
| 234 |
+
return GateReport(False, channel_reason, 0.0, None)
|
| 235 |
+
field = np.mean(np.stack(planes, axis=0), axis=0).astype(np.float64)
|
| 236 |
+
finite = field[np.isfinite(field)]
|
| 237 |
+
if finite.size == 0:
|
| 238 |
+
return GateReport(False, "the frame has no finite pixels", 0.0, None)
|
| 239 |
+
spread = float(finite.std())
|
| 240 |
+
if spread < settings.min_std:
|
| 241 |
+
return GateReport(
|
| 242 |
+
False,
|
| 243 |
+
f"the frame is too flat to be an infrared cyclone (std {spread:.4f})",
|
| 244 |
+
0.0,
|
| 245 |
+
field,
|
| 246 |
+
)
|
| 247 |
+
candidates = CycloneImageGate._candidates(field, settings)
|
| 248 |
+
passing = [item for item in candidates if item[0]]
|
| 249 |
+
chosen = max(passing or candidates, key=lambda item: item[1])
|
| 250 |
+
accepted, score, reason, metrics, polarity = chosen
|
| 251 |
+
return GateReport(
|
| 252 |
+
accepted=accepted,
|
| 253 |
+
reason=reason,
|
| 254 |
+
score=score if accepted else 0.0,
|
| 255 |
+
field=field,
|
| 256 |
+
symmetry=metrics["symmetry"],
|
| 257 |
+
cold_concentration=metrics["cold_concentration"],
|
| 258 |
+
wall_contrast=metrics["wall_contrast"],
|
| 259 |
+
eye_contrast=metrics["eye_contrast"],
|
| 260 |
+
polarity=polarity,
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
@staticmethod
|
| 264 |
+
def _planes(image: np.ndarray, settings: GateSettings) -> tuple[list[np.ndarray], str | None]:
|
| 265 |
+
array = np.asarray(image)
|
| 266 |
+
if array.ndim == 2:
|
| 267 |
+
return [np.asarray(array, dtype=np.float64)], None
|
| 268 |
+
if array.ndim != 3:
|
| 269 |
+
return [], f"the array shape {array.shape} is not an infrared frame"
|
| 270 |
+
if array.shape[0] <= 4 and array.shape[1] > 4 and array.shape[2] > 4:
|
| 271 |
+
planes = [np.asarray(array[index], dtype=np.float64) for index in range(array.shape[0])]
|
| 272 |
+
elif array.shape[-1] <= 4 and array.shape[0] > 4 and array.shape[1] > 4:
|
| 273 |
+
planes = [np.asarray(array[..., index], dtype=np.float64) for index in range(array.shape[-1])]
|
| 274 |
+
else:
|
| 275 |
+
return [], f"the array shape {array.shape} is not an infrared frame"
|
| 276 |
+
if len(planes) == 1:
|
| 277 |
+
return planes, None
|
| 278 |
+
if len(planes) not in (3, 4):
|
| 279 |
+
return [], "the frame is not a single infrared channel"
|
| 280 |
+
# Four planes are RGB plus alpha. Alpha is not a colour channel.
|
| 281 |
+
colour = planes[:3]
|
| 282 |
+
reason = CycloneImageGate._colour_reason(colour, settings)
|
| 283 |
+
if reason is not None:
|
| 284 |
+
return [], reason
|
| 285 |
+
return colour, None
|
| 286 |
+
|
| 287 |
+
@staticmethod
|
| 288 |
+
def _colour_reason(planes: list[np.ndarray], settings: GateSettings) -> str | None:
|
| 289 |
+
"""Refuse a false-colour enhancement. Near-copies stay greyscale IR."""
|
| 290 |
+
mean = np.mean(np.stack(planes, axis=0), axis=0)
|
| 291 |
+
finite = mean[np.isfinite(mean)]
|
| 292 |
+
if finite.size == 0:
|
| 293 |
+
return "the frame has no finite pixels"
|
| 294 |
+
low, high = np.percentile(finite, [5, 95])
|
| 295 |
+
scale = max(float(high - low), 1e-6)
|
| 296 |
+
pair_gaps = [
|
| 297 |
+
float(np.mean(np.abs(planes[i] - planes[j])))
|
| 298 |
+
for i in range(3)
|
| 299 |
+
for j in range(i + 1, 3)
|
| 300 |
+
]
|
| 301 |
+
ratio = float(np.mean(pair_gaps)) / scale
|
| 302 |
+
if ratio > settings.grayscale_tolerance:
|
| 303 |
+
return (
|
| 304 |
+
"the frame is colour-enhanced rather than greyscale infrared "
|
| 305 |
+
f"(relative channel spread {ratio:.2f})"
|
| 306 |
+
)
|
| 307 |
+
return None
|
| 308 |
+
|
| 309 |
+
@staticmethod
|
| 310 |
+
def _candidates(field: np.ndarray, settings: GateSettings) -> list[tuple]:
|
| 311 |
+
if settings.cold_value == "low":
|
| 312 |
+
signed = [(field, "low")]
|
| 313 |
+
elif settings.cold_value == "high":
|
| 314 |
+
signed = [(-field, "high")]
|
| 315 |
+
else:
|
| 316 |
+
signed = [(field, "low"), (-field, "high")]
|
| 317 |
+
reports = []
|
| 318 |
+
for values, polarity in signed:
|
| 319 |
+
reports.append(CycloneImageGate._score_field(values, polarity, settings))
|
| 320 |
+
return reports
|
| 321 |
+
|
| 322 |
+
@staticmethod
|
| 323 |
+
def _score_field(field: np.ndarray, polarity: str, settings: GateSettings) -> tuple:
|
| 324 |
+
finite = np.isfinite(field)
|
| 325 |
+
values = field[finite]
|
| 326 |
+
low, high = np.percentile(values, [5, 95])
|
| 327 |
+
scale = max(float(high - low), 1e-6)
|
| 328 |
+
scaled = (field - float(np.median(values))) / scale
|
| 329 |
+
height, width = scaled.shape
|
| 330 |
+
yy, xx = np.mgrid[0:height, 0:width]
|
| 331 |
+
half = min(height, width) / 2.0
|
| 332 |
+
radius = np.hypot(yy - (height - 1) / 2.0, xx - (width - 1) / 2.0) / max(half, 1e-6)
|
| 333 |
+
symmetry = CycloneImageGate._symmetry(scaled, radius, finite, settings.radial_bins)
|
| 334 |
+
tail = float(np.percentile(scaled[finite], settings.cold_tail_fraction * 100.0))
|
| 335 |
+
cold = finite & (scaled <= tail)
|
| 336 |
+
core = radius <= settings.cold_radius_fraction
|
| 337 |
+
concentration = float(cold[core].sum() / max(int(cold.sum()), 1))
|
| 338 |
+
wall_mask = (radius > settings.eye_radius_fraction) & (
|
| 339 |
+
radius <= settings.eyewall_outer_fraction
|
| 340 |
+
)
|
| 341 |
+
outer_mask = (radius > settings.outer_inner_fraction) & (
|
| 342 |
+
radius <= settings.outer_outer_fraction
|
| 343 |
+
)
|
| 344 |
+
eye_mask = radius <= settings.eye_radius_fraction
|
| 345 |
+
wall_mean = CycloneImageGate._masked_mean(scaled, wall_mask & finite)
|
| 346 |
+
outer_mean = CycloneImageGate._masked_mean(scaled, outer_mask & finite)
|
| 347 |
+
eye_mean = CycloneImageGate._masked_mean(scaled, eye_mask & finite)
|
| 348 |
+
wall_contrast = (
|
| 349 |
+
None if wall_mean is None or outer_mean is None else outer_mean - wall_mean
|
| 350 |
+
)
|
| 351 |
+
eye_contrast = None if eye_mean is None or wall_mean is None else eye_mean - wall_mean
|
| 352 |
+
metrics = {
|
| 353 |
+
"symmetry": symmetry,
|
| 354 |
+
"cold_concentration": concentration,
|
| 355 |
+
"wall_contrast": wall_contrast,
|
| 356 |
+
"eye_contrast": eye_contrast,
|
| 357 |
+
}
|
| 358 |
+
failures: list[str] = []
|
| 359 |
+
if symmetry is None or symmetry < settings.min_symmetry:
|
| 360 |
+
shown = "missing" if symmetry is None else f"{symmetry:.2f}"
|
| 361 |
+
failures.append(f"radial symmetry {shown} is below {settings.min_symmetry:.2f}")
|
| 362 |
+
if concentration < settings.min_cold_concentration:
|
| 363 |
+
failures.append(
|
| 364 |
+
"cold-cloud concentration "
|
| 365 |
+
f"{concentration:.2f} is below {settings.min_cold_concentration:.2f}"
|
| 366 |
+
)
|
| 367 |
+
if wall_contrast is None or wall_contrast < settings.min_wall_contrast:
|
| 368 |
+
shown = "missing" if wall_contrast is None else f"{wall_contrast:.2f}"
|
| 369 |
+
failures.append(f"cold-core contrast {shown} is below {settings.min_wall_contrast:.2f}")
|
| 370 |
+
score = CycloneImageGate._score(symmetry, concentration, wall_contrast, settings)
|
| 371 |
+
if failures:
|
| 372 |
+
reason = "; ".join(failures) + f" ({polarity} values treated as cold)"
|
| 373 |
+
return False, score, reason, metrics, polarity
|
| 374 |
+
reason = (
|
| 375 |
+
"cold cloud is radially organized "
|
| 376 |
+
f"({polarity} values treated as cold)"
|
| 377 |
+
)
|
| 378 |
+
return True, score, reason, metrics, polarity
|
| 379 |
+
|
| 380 |
+
@staticmethod
|
| 381 |
+
def _symmetry(scaled, radius, finite, radial_bins: int) -> float | None:
|
| 382 |
+
inside = finite & (radius <= 1)
|
| 383 |
+
if int(inside.sum()) < 8:
|
| 384 |
+
return None
|
| 385 |
+
edges = np.linspace(0.0, 1.0, int(radial_bins) + 1)
|
| 386 |
+
residual = np.zeros(scaled.shape, dtype=np.float64)
|
| 387 |
+
for index in range(int(radial_bins)):
|
| 388 |
+
mask = inside & (radius >= edges[index]) & (radius < edges[index + 1])
|
| 389 |
+
if int(mask.sum()) == 0:
|
| 390 |
+
continue
|
| 391 |
+
residual[mask] = scaled[mask] - float(scaled[mask].mean())
|
| 392 |
+
variance = float(scaled[inside].var())
|
| 393 |
+
if variance <= 1e-8:
|
| 394 |
+
return 1.0
|
| 395 |
+
return float(1.0 - residual[inside].var() / variance)
|
| 396 |
+
|
| 397 |
+
@staticmethod
|
| 398 |
+
def _masked_mean(scaled, mask) -> float | None:
|
| 399 |
+
if int(mask.sum()) == 0:
|
| 400 |
+
return None
|
| 401 |
+
return float(scaled[mask].mean())
|
| 402 |
+
|
| 403 |
+
@staticmethod
|
| 404 |
+
def _score(symmetry, concentration, wall_contrast, settings: GateSettings) -> float:
|
| 405 |
+
if symmetry is None or wall_contrast is None:
|
| 406 |
+
return 0.0
|
| 407 |
+
return float(
|
| 408 |
+
np.clip(
|
| 409 |
+
min(
|
| 410 |
+
1.0,
|
| 411 |
+
max(float(symmetry), 0.0),
|
| 412 |
+
max(float(wall_contrast), 0.0),
|
| 413 |
+
max(float(concentration), 0.0) / settings.concentration_reference,
|
| 414 |
+
),
|
| 415 |
+
0.0,
|
| 416 |
+
1.0,
|
| 417 |
+
)
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
class ConfidenceScore:
|
| 422 |
+
"""Gate score, dropout spread, and residual quantiles when a checkpoint has them.
|
| 423 |
+
|
| 424 |
+
``src.evaluate`` stores a residual-quantile interval as the validation
|
| 425 |
+
quantile of ``|residual|``. That value is a half-width. The full width
|
| 426 |
+
used here is twice that half-width. A ``low_kt`` / ``high_kt`` pair is
|
| 427 |
+
the older full span and is used only when no evaluate levels are present.
|
| 428 |
+
|
| 429 |
+
The label stays ``uncalibrated`` unless a matching real-data run record
|
| 430 |
+
carries a coverage check or a held-out storm check whose quoted level
|
| 431 |
+
is ``within_tolerance``. This is not a prediction interval and it is
|
| 432 |
+
not an operational calibration claim.
|
| 433 |
+
"""
|
| 434 |
+
|
| 435 |
+
@staticmethod
|
| 436 |
+
def source(payload: dict, record: dict | None):
|
| 437 |
+
"""Quantile payload for the blend. The run record is the second choice."""
|
| 438 |
+
candidates = []
|
| 439 |
+
if isinstance(payload, dict):
|
| 440 |
+
candidates.append(payload.get("residual_quantiles"))
|
| 441 |
+
candidates.append(payload.get("uncertainty"))
|
| 442 |
+
if isinstance(record, dict):
|
| 443 |
+
candidates.append(record.get("residual_quantiles"))
|
| 444 |
+
candidates.append(record.get("uncertainty"))
|
| 445 |
+
for candidate in candidates:
|
| 446 |
+
if ConfidenceScore.interval_width(candidate) is not None:
|
| 447 |
+
return candidate
|
| 448 |
+
return None
|
| 449 |
+
|
| 450 |
+
@staticmethod
|
| 451 |
+
def interval_width(raw) -> float | None:
|
| 452 |
+
half = ConfidenceScore._half_width(raw)
|
| 453 |
+
if half is not None:
|
| 454 |
+
return 2.0 * half
|
| 455 |
+
if not isinstance(raw, dict) or "low_kt" not in raw or "high_kt" not in raw:
|
| 456 |
+
return None
|
| 457 |
+
low = _finite(raw["low_kt"], "residual_quantiles.low_kt")
|
| 458 |
+
high = _finite(raw["high_kt"], "residual_quantiles.high_kt")
|
| 459 |
+
if high < low:
|
| 460 |
+
return None
|
| 461 |
+
return high - low
|
| 462 |
+
|
| 463 |
+
@staticmethod
|
| 464 |
+
def _level_rows(raw) -> dict | None:
|
| 465 |
+
"""Rows from ``report['uncertainty']['residual_quantile']['levels']``."""
|
| 466 |
+
if not isinstance(raw, dict):
|
| 467 |
+
return None
|
| 468 |
+
uncertainty = raw.get("uncertainty")
|
| 469 |
+
if isinstance(uncertainty, dict):
|
| 470 |
+
found = ConfidenceScore._level_rows(uncertainty.get("residual_quantile"))
|
| 471 |
+
if found:
|
| 472 |
+
return found
|
| 473 |
+
for key in ("residual_quantile", "residual_quantiles"):
|
| 474 |
+
nested = raw.get(key)
|
| 475 |
+
if isinstance(nested, dict):
|
| 476 |
+
found = ConfidenceScore._level_rows(nested)
|
| 477 |
+
if found:
|
| 478 |
+
return found
|
| 479 |
+
levels = raw.get("levels")
|
| 480 |
+
if isinstance(levels, dict):
|
| 481 |
+
found = ConfidenceScore._level_rows(levels)
|
| 482 |
+
if found:
|
| 483 |
+
return found
|
| 484 |
+
rows = {
|
| 485 |
+
str(key): value
|
| 486 |
+
for key, value in raw.items()
|
| 487 |
+
if isinstance(value, dict) and "absolute_residual_quantile_kt" in value
|
| 488 |
+
}
|
| 489 |
+
return rows or None
|
| 490 |
+
|
| 491 |
+
@staticmethod
|
| 492 |
+
def _quantile_block(raw) -> dict | None:
|
| 493 |
+
"""The evaluate residual-quantile object, including its storm lists."""
|
| 494 |
+
if not isinstance(raw, dict):
|
| 495 |
+
return None
|
| 496 |
+
uncertainty = raw.get("uncertainty")
|
| 497 |
+
if isinstance(uncertainty, dict):
|
| 498 |
+
found = ConfidenceScore._quantile_block(uncertainty)
|
| 499 |
+
if found is not None:
|
| 500 |
+
return found
|
| 501 |
+
for key in ("residual_quantile", "residual_quantiles"):
|
| 502 |
+
nested = raw.get(key)
|
| 503 |
+
if isinstance(nested, dict):
|
| 504 |
+
found = ConfidenceScore._quantile_block(nested)
|
| 505 |
+
if found is not None:
|
| 506 |
+
return found
|
| 507 |
+
levels = raw.get("levels")
|
| 508 |
+
if isinstance(levels, dict) and ConfidenceScore._level_rows(levels):
|
| 509 |
+
return raw
|
| 510 |
+
if ConfidenceScore._level_rows(raw):
|
| 511 |
+
return raw
|
| 512 |
+
return None
|
| 513 |
+
|
| 514 |
+
@staticmethod
|
| 515 |
+
def _chosen_row(rows: dict) -> dict | None:
|
| 516 |
+
"""Highest nominal level. That is the interval this score quotes."""
|
| 517 |
+
chosen = None
|
| 518 |
+
nominal = None
|
| 519 |
+
for row in rows.values():
|
| 520 |
+
if not isinstance(row, dict):
|
| 521 |
+
continue
|
| 522 |
+
try:
|
| 523 |
+
level = float(row.get("nominal", 0.0))
|
| 524 |
+
half = float(row["absolute_residual_quantile_kt"])
|
| 525 |
+
except (TypeError, ValueError):
|
| 526 |
+
continue
|
| 527 |
+
if not math.isfinite(level) or not math.isfinite(half) or half < 0:
|
| 528 |
+
continue
|
| 529 |
+
if nominal is None or level > nominal:
|
| 530 |
+
nominal = level
|
| 531 |
+
chosen = row
|
| 532 |
+
return chosen
|
| 533 |
+
|
| 534 |
+
@staticmethod
|
| 535 |
+
def _half_width(raw) -> float | None:
|
| 536 |
+
rows = ConfidenceScore._level_rows(raw)
|
| 537 |
+
if not rows:
|
| 538 |
+
return None
|
| 539 |
+
chosen = ConfidenceScore._chosen_row(rows)
|
| 540 |
+
if chosen is None:
|
| 541 |
+
return None
|
| 542 |
+
return float(chosen["absolute_residual_quantile_kt"])
|
| 543 |
+
|
| 544 |
+
@staticmethod
|
| 545 |
+
def combine(
|
| 546 |
+
config: dict,
|
| 547 |
+
gate_score: float,
|
| 548 |
+
dropout_std: float | None,
|
| 549 |
+
residual_quantiles,
|
| 550 |
+
) -> float:
|
| 551 |
+
cfg = _section(config, "predict", "confidence")
|
| 552 |
+
weights = {
|
| 553 |
+
"gate": _finite(cfg["gate_weight"], "predict.confidence.gate_weight"),
|
| 554 |
+
"mc": _finite(cfg["mc_weight"], "predict.confidence.mc_weight"),
|
| 555 |
+
"interval": _finite(cfg["interval_weight"], "predict.confidence.interval_weight"),
|
| 556 |
+
}
|
| 557 |
+
if min(weights.values()) <= 0:
|
| 558 |
+
raise ValueError("config predict.confidence weights must be positive")
|
| 559 |
+
terms = [(weights["gate"], float(np.clip(gate_score, 0.0, 1.0)))]
|
| 560 |
+
if dropout_std is not None:
|
| 561 |
+
scale = _finite(cfg["mc_std_scale_kt"], "predict.confidence.mc_std_scale_kt")
|
| 562 |
+
if scale <= 0:
|
| 563 |
+
raise ValueError("config predict.confidence.mc_std_scale_kt must be positive")
|
| 564 |
+
terms.append((weights["mc"], 1.0 / (1.0 + float(dropout_std) / scale)))
|
| 565 |
+
width = ConfidenceScore.interval_width(residual_quantiles)
|
| 566 |
+
if width is not None:
|
| 567 |
+
scale = _finite(cfg["interval_scale_kt"], "predict.confidence.interval_scale_kt")
|
| 568 |
+
if scale <= 0:
|
| 569 |
+
raise ValueError("config predict.confidence.interval_scale_kt must be positive")
|
| 570 |
+
interval = float(np.clip(1.0 - width / scale, 0.0, 1.0))
|
| 571 |
+
terms.append((weights["interval"], interval))
|
| 572 |
+
total = sum(weight for weight, _value in terms)
|
| 573 |
+
score = sum(weight * value for weight, value in terms) / total
|
| 574 |
+
return float(np.clip(score, 0.0, 1.0))
|
| 575 |
+
|
| 576 |
+
@staticmethod
|
| 577 |
+
def status(config: dict, record: dict | None) -> str:
|
| 578 |
+
cfg = _section(config, "predict", "confidence")
|
| 579 |
+
uncalibrated = str(cfg["uncalibrated_label"]).strip()
|
| 580 |
+
recorded = str(cfg["coverage_label"]).strip()
|
| 581 |
+
if not isinstance(record, dict):
|
| 582 |
+
return uncalibrated
|
| 583 |
+
if ConfidenceScore._coverage_recorded(record):
|
| 584 |
+
return recorded
|
| 585 |
+
if ConfidenceScore._held_out_storm_check(record):
|
| 586 |
+
return recorded
|
| 587 |
+
return uncalibrated
|
| 588 |
+
|
| 589 |
+
@staticmethod
|
| 590 |
+
def _coverage_recorded(record: dict) -> bool:
|
| 591 |
+
check = record.get("coverage_check")
|
| 592 |
+
if not isinstance(check, dict) or check.get("real_data") is not True:
|
| 593 |
+
return False
|
| 594 |
+
try:
|
| 595 |
+
count = int(check["n"])
|
| 596 |
+
nominal = float(check["nominal"])
|
| 597 |
+
observed = float(check["observed"])
|
| 598 |
+
except (KeyError, TypeError, ValueError):
|
| 599 |
+
return False
|
| 600 |
+
return count >= 1 and math.isfinite(nominal) and math.isfinite(observed)
|
| 601 |
+
|
| 602 |
+
@staticmethod
|
| 603 |
+
def _held_out_storm_check(record: dict) -> bool:
|
| 604 |
+
"""True when evaluate scored residual quantiles on held-out storms.
|
| 605 |
+
|
| 606 |
+
Half-widths alone do not count. The block has to name test storms,
|
| 607 |
+
the quoted level has to be ``within_tolerance``, and the report
|
| 608 |
+
must not be synthetic. The label is still the coverage label, not
|
| 609 |
+
``calibrated``.
|
| 610 |
+
"""
|
| 611 |
+
block = ConfidenceScore._quantile_block(record)
|
| 612 |
+
if not isinstance(block, dict):
|
| 613 |
+
return False
|
| 614 |
+
if str(block.get("eval_split", "")).strip() != "test":
|
| 615 |
+
return False
|
| 616 |
+
storms = block.get("test_storms")
|
| 617 |
+
if not isinstance(storms, (list, tuple)) or not storms:
|
| 618 |
+
return False
|
| 619 |
+
if not all(str(storm).strip() for storm in storms):
|
| 620 |
+
return False
|
| 621 |
+
synthetic = record.get("synthetic", block.get("synthetic"))
|
| 622 |
+
if synthetic in {"yes", "mixed", True}:
|
| 623 |
+
return False
|
| 624 |
+
rows = ConfidenceScore._level_rows(block)
|
| 625 |
+
if not rows:
|
| 626 |
+
return False
|
| 627 |
+
chosen = ConfidenceScore._chosen_row(rows)
|
| 628 |
+
if chosen is None or str(chosen.get("status", "")).strip() != "within_tolerance":
|
| 629 |
+
return False
|
| 630 |
+
if chosen.get("eval_split") not in (None, "test"):
|
| 631 |
+
return False
|
| 632 |
+
try:
|
| 633 |
+
count = int(float(chosen["n"]))
|
| 634 |
+
except (KeyError, TypeError, ValueError):
|
| 635 |
+
return False
|
| 636 |
+
return count >= 1
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
class IntensityGrouping:
|
| 640 |
+
"""Project bins. The names are not an official IMD class."""
|
| 641 |
+
|
| 642 |
+
@staticmethod
|
| 643 |
+
def note(config: dict) -> str:
|
| 644 |
+
return str(_section(config, "data", "grouping_note")).strip()
|
| 645 |
+
|
| 646 |
+
@staticmethod
|
| 647 |
+
def code(wind_kt: float, edges: tuple[float, ...], names: tuple[str, ...]) -> str | None:
|
| 648 |
+
return wind_to_imd5(float(wind_kt), edges, names)
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
class RunRecord:
|
| 652 |
+
"""A checkpoint may be shown only when a real-data record matches it.
|
| 653 |
+
|
| 654 |
+
A synthetic checkpoint is always flagged. A checkpoint that claims to
|
| 655 |
+
be real and has no matching record produces no wind speed.
|
| 656 |
+
"""
|
| 657 |
+
|
| 658 |
+
@staticmethod
|
| 659 |
+
def load_match(config: dict, payload: dict) -> tuple[bool, dict | None]:
|
| 660 |
+
run_id = payload.get("run_id")
|
| 661 |
+
if run_id in (None, ""):
|
| 662 |
+
return False, None
|
| 663 |
+
run_id = str(run_id)
|
| 664 |
+
if "/" in run_id or "\\" in run_id or ".." in run_id:
|
| 665 |
+
return False, None
|
| 666 |
+
record = RunRecord._legacy_record(config, run_id)
|
| 667 |
+
if record is None:
|
| 668 |
+
record = RunRecord._run_directory_record(config, run_id)
|
| 669 |
+
if record is None:
|
| 670 |
+
record = RunRecord._active_directory_record(config, run_id)
|
| 671 |
+
if record is None:
|
| 672 |
+
return False, None
|
| 673 |
+
normalized = RunRecord._normalize(record, payload)
|
| 674 |
+
if str(normalized.get("run_id")) != run_id:
|
| 675 |
+
return False, None
|
| 676 |
+
if bool(normalized.get("is_synthetic", True)):
|
| 677 |
+
return False, None
|
| 678 |
+
if str(normalized.get("data_kind")) != "real":
|
| 679 |
+
return False, None
|
| 680 |
+
try:
|
| 681 |
+
same_model = str(normalized.get("model_name")) == str(payload.get("model_name"))
|
| 682 |
+
same_size = image_sizes_match(normalized.get("image_size"), payload.get("image_size"))
|
| 683 |
+
except (TypeError, ValueError):
|
| 684 |
+
return False, None
|
| 685 |
+
if not same_model or not same_size:
|
| 686 |
+
return False, None
|
| 687 |
+
return True, normalized
|
| 688 |
+
|
| 689 |
+
@staticmethod
|
| 690 |
+
def _read_json(path: Path) -> dict | None:
|
| 691 |
+
if not path.is_file():
|
| 692 |
+
return None
|
| 693 |
+
try:
|
| 694 |
+
record = json.loads(path.read_text(encoding="utf-8"))
|
| 695 |
+
except (OSError, json.JSONDecodeError, UnicodeError):
|
| 696 |
+
return None
|
| 697 |
+
if not isinstance(record, dict):
|
| 698 |
+
return None
|
| 699 |
+
return record
|
| 700 |
+
|
| 701 |
+
@staticmethod
|
| 702 |
+
def _legacy_record(config: dict, run_id: str) -> dict | None:
|
| 703 |
+
paths = config.get("paths")
|
| 704 |
+
if not isinstance(paths, dict) or "run_records" not in paths:
|
| 705 |
+
return None
|
| 706 |
+
return RunRecord._read_json(Path(paths["run_records"]) / f"{run_id}.json")
|
| 707 |
+
|
| 708 |
+
@staticmethod
|
| 709 |
+
def _run_directory_record(config: dict, run_id: str) -> dict | None:
|
| 710 |
+
"""``paths.runs/<run_id>/metrics.json`` from ``src.train.run_training``."""
|
| 711 |
+
paths = config.get("paths")
|
| 712 |
+
if not isinstance(paths, dict) or not paths.get("runs"):
|
| 713 |
+
return None
|
| 714 |
+
return RunRecord._read_json(Path(paths["runs"]) / run_id / "metrics.json")
|
| 715 |
+
|
| 716 |
+
@staticmethod
|
| 717 |
+
def _active_directory_record(config: dict, run_id: str) -> dict | None:
|
| 718 |
+
"""A Hub snapshot of one run directory, set in memory by :class:`RunCheckpoint`."""
|
| 719 |
+
paths = config.get("paths")
|
| 720 |
+
if not isinstance(paths, dict) or not paths.get("active_run_dir"):
|
| 721 |
+
return None
|
| 722 |
+
return RunRecord._read_json(Path(paths["active_run_dir"]) / "metrics.json")
|
| 723 |
+
|
| 724 |
+
@staticmethod
|
| 725 |
+
def _normalize(record: dict, payload: dict) -> dict:
|
| 726 |
+
normalized = dict(record)
|
| 727 |
+
if not normalized.get("model_name") and normalized.get("model"):
|
| 728 |
+
normalized["model_name"] = normalized.get("model")
|
| 729 |
+
if "image_size" not in normalized:
|
| 730 |
+
normalized["image_size"] = payload.get("image_size")
|
| 731 |
+
if not normalized.get("data_kind"):
|
| 732 |
+
dataset = str(normalized.get("dataset", "")).strip().lower()
|
| 733 |
+
real_run = (
|
| 734 |
+
dataset in {"nasa", "tcir"}
|
| 735 |
+
and normalized.get("is_synthetic") is False
|
| 736 |
+
and normalized.get("result") is True
|
| 737 |
+
)
|
| 738 |
+
if real_run:
|
| 739 |
+
normalized["data_kind"] = "real"
|
| 740 |
+
return normalized
|
| 741 |
+
|
| 742 |
+
@staticmethod
|
| 743 |
+
def _with_active(config: dict, directory: Path) -> dict:
|
| 744 |
+
prepared = dict(config)
|
| 745 |
+
prepared["paths"] = dict(config.get("paths") or {})
|
| 746 |
+
prepared["paths"]["active_run_dir"] = str(directory)
|
| 747 |
+
return prepared
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
class CoastalContext:
|
| 751 |
+
"""Nearest configured coastal reference points. Not a landfall forecast."""
|
| 752 |
+
|
| 753 |
+
@staticmethod
|
| 754 |
+
def describe(config: dict, latitude, longitude, metadata) -> tuple:
|
| 755 |
+
position = CoastalContext.position(config, latitude, longitude, metadata)
|
| 756 |
+
if position is None:
|
| 757 |
+
return None, None, None
|
| 758 |
+
lat, lon = position
|
| 759 |
+
count = int(_section(config, "predict", "coastal_count"))
|
| 760 |
+
if count < 1:
|
| 761 |
+
raise ValueError("config predict.coastal_count must be at least 1")
|
| 762 |
+
radius = _finite(_section(config, "predict", "earth_radius_km"), "predict.earth_radius_km")
|
| 763 |
+
places = _section(config, "predict", "coast")
|
| 764 |
+
if not isinstance(places, list) or not places:
|
| 765 |
+
raise ValueError("config predict.coast must list reference points")
|
| 766 |
+
ranked = sorted(
|
| 767 |
+
(
|
| 768 |
+
(
|
| 769 |
+
CoastalContext.distance_km(lat, lon, float(place["lat"]), float(place["lon"]), radius),
|
| 770 |
+
str(place["name"]),
|
| 771 |
+
)
|
| 772 |
+
for place in places
|
| 773 |
+
),
|
| 774 |
+
key=lambda item: item[0],
|
| 775 |
+
)
|
| 776 |
+
names = tuple(name for _distance, name in ranked[:count])
|
| 777 |
+
note = str(_section(config, "predict", "landfall_note")).strip()
|
| 778 |
+
reference = str(_section(config, "predict", "coast_reference_note")).strip()
|
| 779 |
+
return names, note, reference
|
| 780 |
+
|
| 781 |
+
@staticmethod
|
| 782 |
+
def position(config: dict, latitude, longitude, metadata) -> tuple[float, float] | None:
|
| 783 |
+
meta = metadata or {}
|
| 784 |
+
lat = latitude
|
| 785 |
+
lon = longitude
|
| 786 |
+
if lat is None:
|
| 787 |
+
for key in _section(config, "predict", "latitude_keys"):
|
| 788 |
+
if key in meta and meta[key] is not None:
|
| 789 |
+
lat = meta[key]
|
| 790 |
+
break
|
| 791 |
+
if lon is None:
|
| 792 |
+
for key in _section(config, "predict", "longitude_keys"):
|
| 793 |
+
if key in meta and meta[key] is not None:
|
| 794 |
+
lon = meta[key]
|
| 795 |
+
break
|
| 796 |
+
if lat is None and lon is None:
|
| 797 |
+
return None
|
| 798 |
+
if lat is None or lon is None:
|
| 799 |
+
raise ValueError("latitude and longitude must be supplied together")
|
| 800 |
+
lat_f = float(lat)
|
| 801 |
+
lon_f = float(lon)
|
| 802 |
+
if not (-90.0 <= lat_f <= 90.0 and -180.0 <= lon_f <= 180.0):
|
| 803 |
+
raise ValueError("latitude or longitude is outside the geographic range")
|
| 804 |
+
return lat_f, lon_f
|
| 805 |
+
|
| 806 |
+
@staticmethod
|
| 807 |
+
def distance_km(lat1: float, lon1: float, lat2: float, lon2: float, radius_km: float) -> float:
|
| 808 |
+
phi1, phi2 = math.radians(lat1), math.radians(lat2)
|
| 809 |
+
d_phi = math.radians(lat2 - lat1)
|
| 810 |
+
d_lon = math.radians(lon2 - lon1)
|
| 811 |
+
haversine = (
|
| 812 |
+
math.sin(d_phi / 2.0) ** 2
|
| 813 |
+
+ math.cos(phi1) * math.cos(phi2) * math.sin(d_lon / 2.0) ** 2
|
| 814 |
+
)
|
| 815 |
+
return 2.0 * radius_km * math.asin(min(1.0, math.sqrt(haversine)))
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
class CheckpointStore:
|
| 819 |
+
"""Load a ``.pt`` state dict or a ``.joblib`` estimator. No other suffix."""
|
| 820 |
+
|
| 821 |
+
@staticmethod
|
| 822 |
+
def load(path: Path) -> dict:
|
| 823 |
+
if path.suffix == ".joblib":
|
| 824 |
+
import joblib
|
| 825 |
+
|
| 826 |
+
payload = joblib.load(path)
|
| 827 |
+
if not isinstance(payload, dict) or "estimator" not in payload:
|
| 828 |
+
raise ValueError("joblib checkpoint must be a dict with an estimator")
|
| 829 |
+
loaded = dict(payload)
|
| 830 |
+
loaded["_kind"] = "sklearn"
|
| 831 |
+
return loaded
|
| 832 |
+
if path.suffix == ".pt":
|
| 833 |
+
import torch
|
| 834 |
+
|
| 835 |
+
try:
|
| 836 |
+
payload = torch.load(path, map_location="cpu", weights_only=False)
|
| 837 |
+
except TypeError:
|
| 838 |
+
payload = torch.load(path, map_location="cpu")
|
| 839 |
+
if not isinstance(payload, dict):
|
| 840 |
+
raise ValueError("torch checkpoint must be a dict")
|
| 841 |
+
loaded = dict(payload)
|
| 842 |
+
loaded["_kind"] = "torch"
|
| 843 |
+
return loaded
|
| 844 |
+
raise ValueError("checkpoint must be a .pt or .joblib file")
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
@dataclass(frozen=True)
|
| 848 |
+
class Estimate:
|
| 849 |
+
"""What ``predict_images`` turns into a :class:`cloudie.predict.Prediction`."""
|
| 850 |
+
|
| 851 |
+
outcome: str
|
| 852 |
+
banner: str
|
| 853 |
+
is_synthetic: bool
|
| 854 |
+
wind_kt: float | None = None
|
| 855 |
+
wind_kmh: float | None = None
|
| 856 |
+
dropout_std_kt: float | None = None
|
| 857 |
+
samples: tuple[float, ...] = ()
|
| 858 |
+
confidence: float | None = None
|
| 859 |
+
confidence_status: str | None = None
|
| 860 |
+
grouping_note: str | None = None
|
| 861 |
+
operational_disclaimer: str | None = None
|
| 862 |
+
coastal_heading: str | None = None
|
| 863 |
+
nearest_coastal_states: tuple[str, ...] | None = None
|
| 864 |
+
landfall_note: str | None = None
|
| 865 |
+
coast_reference_note: str | None = None
|
| 866 |
+
gate_reason: str | None = None
|
| 867 |
+
gate_score: float | None = None
|
| 868 |
+
matched_run: bool = False
|
| 869 |
+
outside_training: bool = False
|
| 870 |
+
wind_averaging: str | None = None
|
| 871 |
+
edges: tuple[float, ...] = ()
|
| 872 |
+
names: tuple[str, ...] = ()
|
| 873 |
+
honesty: str | None = None
|
| 874 |
+
|
| 875 |
+
|
| 876 |
+
class IntensityEstimate:
|
| 877 |
+
"""Run the gate, then the checkpoint, and refuse a wind when either fails.
|
| 878 |
+
|
| 879 |
+
This is not an operational forecast. Dropout spread and residual
|
| 880 |
+
quantiles are not a calibrated interval. Nearest coastal states are
|
| 881 |
+
context for a supplied position, not a landfall forecast.
|
| 882 |
+
"""
|
| 883 |
+
|
| 884 |
+
@staticmethod
|
| 885 |
+
def predict(
|
| 886 |
+
config: dict,
|
| 887 |
+
path: Path,
|
| 888 |
+
images: list[np.ndarray],
|
| 889 |
+
*,
|
| 890 |
+
hemisphere: str | None,
|
| 891 |
+
latitude,
|
| 892 |
+
longitude,
|
| 893 |
+
metadata,
|
| 894 |
+
) -> Estimate:
|
| 895 |
+
ctx = IntensityEstimate._context(config, latitude, longitude, metadata)
|
| 896 |
+
payload = CheckpointStore.load(path)
|
| 897 |
+
IntensityEstimate._check_identity(config, payload)
|
| 898 |
+
synthetic = bool(payload.get("is_synthetic"))
|
| 899 |
+
matched, record = RunRecord.load_match(config, payload)
|
| 900 |
+
if synthetic:
|
| 901 |
+
matched, record = False, None
|
| 902 |
+
expected = int(payload.get("n_frames", 1))
|
| 903 |
+
if len(images) != expected:
|
| 904 |
+
banner = (
|
| 905 |
+
f"This checkpoint expects {expected} infrared frames and received "
|
| 906 |
+
f"{len(images)}. There is no model output. This is not a forecast."
|
| 907 |
+
)
|
| 908 |
+
return Estimate("frame_count", banner, synthetic, matched_run=matched, **ctx)
|
| 909 |
+
frames = IntensityEstimate._unflipped(images, hemisphere)
|
| 910 |
+
missing = IntensityEstimate._missing_fraction(frames, float(payload["max_missing_fraction"]))
|
| 911 |
+
if missing is not None:
|
| 912 |
+
return Estimate("missing_pixels", "", synthetic, matched_run=matched, **ctx)
|
| 913 |
+
settings = GateSettings.from_config(config)
|
| 914 |
+
reports = [CycloneImageGate.assess(frame, settings) for frame in frames]
|
| 915 |
+
refused = next((report for report in reports if not report.accepted), None)
|
| 916 |
+
if refused is not None:
|
| 917 |
+
return Estimate(
|
| 918 |
+
"not_cyclone",
|
| 919 |
+
IntensityEstimate._gate_banner(settings, refused.reason),
|
| 920 |
+
synthetic,
|
| 921 |
+
gate_reason=refused.reason,
|
| 922 |
+
gate_score=refused.score,
|
| 923 |
+
matched_run=matched,
|
| 924 |
+
**ctx,
|
| 925 |
+
)
|
| 926 |
+
if not synthetic and not matched:
|
| 927 |
+
banner = str(_section(config, "predict", "no_run_record_refusal")).strip()
|
| 928 |
+
return Estimate("no_run_record", banner, synthetic, matched_run=False, **ctx)
|
| 929 |
+
prepared = IntensityEstimate._prepare(config, payload, reports)
|
| 930 |
+
wind_kt, samples, std_kt = IntensityEstimate._wind(config, payload, prepared, reports)
|
| 931 |
+
uncertain = CycloneImageGate.uncertainty_reason(std_kt, settings)
|
| 932 |
+
if uncertain is not None:
|
| 933 |
+
return Estimate(
|
| 934 |
+
"not_cyclone",
|
| 935 |
+
IntensityEstimate._gate_banner(settings, uncertain),
|
| 936 |
+
synthetic,
|
| 937 |
+
gate_reason=uncertain,
|
| 938 |
+
matched_run=matched,
|
| 939 |
+
**ctx,
|
| 940 |
+
)
|
| 941 |
+
edges = tuple(float(edge) for edge in payload.get("edges_kt", config["data"]["imd5_edges_kt"]))
|
| 942 |
+
names = tuple(str(name) for name in payload.get("class_names", config["data"]["imd5_names"]))
|
| 943 |
+
averaging = payload.get("wind_averaging")
|
| 944 |
+
averaging = None if averaging in (None, "") else str(averaging)
|
| 945 |
+
field_mean = IntensityEstimate._mean(reports)
|
| 946 |
+
width = _finite(_section(config, "predict", "training_mean_width"), "predict.training_mean_width")
|
| 947 |
+
scale = max(float(payload["norm_std"]), 1e-6)
|
| 948 |
+
outside = abs(field_mean - float(payload["norm_mean"])) > width * scale
|
| 949 |
+
low, high = (float(bound) for bound in config["data"]["plausible_wind_kt"])
|
| 950 |
+
if outside or not (low <= wind_kt <= high):
|
| 951 |
+
return Estimate(
|
| 952 |
+
"outside_range",
|
| 953 |
+
"",
|
| 954 |
+
synthetic,
|
| 955 |
+
outside_training=outside,
|
| 956 |
+
wind_averaging=averaging,
|
| 957 |
+
edges=edges,
|
| 958 |
+
names=names,
|
| 959 |
+
honesty=payload.get("honesty"),
|
| 960 |
+
matched_run=matched,
|
| 961 |
+
**ctx,
|
| 962 |
+
)
|
| 963 |
+
gate_score = min(report.score for report in reports)
|
| 964 |
+
quantiles = ConfidenceScore.source(payload, record if matched else None)
|
| 965 |
+
confidence = ConfidenceScore.combine(config, gate_score, std_kt, quantiles)
|
| 966 |
+
factor = _finite(_section(config, "data", "kt_to_kmh"), "data.kt_to_kmh")
|
| 967 |
+
if factor <= 0:
|
| 968 |
+
raise ValueError("config data.kt_to_kmh must be positive")
|
| 969 |
+
return Estimate(
|
| 970 |
+
"ok",
|
| 971 |
+
"",
|
| 972 |
+
synthetic,
|
| 973 |
+
wind_kt=float(wind_kt),
|
| 974 |
+
wind_kmh=float(wind_kt) * factor,
|
| 975 |
+
dropout_std_kt=None if std_kt is None else float(std_kt),
|
| 976 |
+
samples=tuple(float(value) for value in samples),
|
| 977 |
+
confidence=confidence,
|
| 978 |
+
confidence_status=ConfidenceScore.status(config, record if matched else None),
|
| 979 |
+
grouping_note=IntensityGrouping.note(config),
|
| 980 |
+
gate_score=gate_score,
|
| 981 |
+
matched_run=matched,
|
| 982 |
+
wind_averaging=averaging,
|
| 983 |
+
edges=edges,
|
| 984 |
+
names=names,
|
| 985 |
+
honesty=None if payload.get("honesty") is None else str(payload.get("honesty")),
|
| 986 |
+
**ctx,
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
@staticmethod
|
| 990 |
+
def _context(config: dict, latitude, longitude, metadata) -> dict:
|
| 991 |
+
states, note, reference = CoastalContext.describe(config, latitude, longitude, metadata)
|
| 992 |
+
return {
|
| 993 |
+
"operational_disclaimer": str(_section(config, "predict", "operational_disclaimer")).strip(),
|
| 994 |
+
"coastal_heading": str(_section(config, "predict", "coastal_heading")).strip(),
|
| 995 |
+
"nearest_coastal_states": states,
|
| 996 |
+
"landfall_note": note,
|
| 997 |
+
"coast_reference_note": reference,
|
| 998 |
+
}
|
| 999 |
+
|
| 1000 |
+
@staticmethod
|
| 1001 |
+
def _check_identity(config: dict, payload: dict) -> None:
|
| 1002 |
+
if str(config["model"].get("name", "simple_cnn")) != str(payload["model_name"]):
|
| 1003 |
+
raise ValueError("config model.name does not match the checkpoint")
|
| 1004 |
+
if not image_sizes_match(config["data"]["image_size"], payload["image_size"]):
|
| 1005 |
+
raise ValueError("config image_size does not match the checkpoint")
|
| 1006 |
+
if payload.get("hidden") is not None and int(config["model"].get("hidden", 16)) != int(
|
| 1007 |
+
payload["hidden"]
|
| 1008 |
+
):
|
| 1009 |
+
raise ValueError("config model.hidden does not match the checkpoint")
|
| 1010 |
+
if str(payload.get("norm_source_split")) != "train":
|
| 1011 |
+
raise ValueError("checkpoint normalization was not fit on train")
|
| 1012 |
+
|
| 1013 |
+
@staticmethod
|
| 1014 |
+
def _unflipped(images: list[np.ndarray], hemisphere: str | None) -> list[np.ndarray]:
|
| 1015 |
+
from src.preprocessing import leave_unflipped
|
| 1016 |
+
|
| 1017 |
+
return [leave_unflipped(image, hemisphere) for image in images]
|
| 1018 |
+
|
| 1019 |
+
@staticmethod
|
| 1020 |
+
def _missing_fraction(images: list[np.ndarray], limit: float) -> str | None:
|
| 1021 |
+
from src.preprocessing import as_channel_first, missing_fraction
|
| 1022 |
+
|
| 1023 |
+
for image in images:
|
| 1024 |
+
if missing_fraction(as_channel_first(image)) > limit:
|
| 1025 |
+
return "missing"
|
| 1026 |
+
return None
|
| 1027 |
+
|
| 1028 |
+
@staticmethod
|
| 1029 |
+
def _gate_banner(settings: GateSettings, reason: str) -> str:
|
| 1030 |
+
return (
|
| 1031 |
+
f"{settings.refusal}: {reason}. "
|
| 1032 |
+
"There is no wind speed. This is not a forecast."
|
| 1033 |
+
)
|
| 1034 |
+
|
| 1035 |
+
@staticmethod
|
| 1036 |
+
def _prepare(config: dict, payload: dict, reports: list[GateReport]) -> list[np.ndarray]:
|
| 1037 |
+
from src.preprocessing import norm_stats_from_checkpoint, prepare_image
|
| 1038 |
+
|
| 1039 |
+
mode = FrameGeometry.mode(config)
|
| 1040 |
+
pad = str(_section(config, "data", "pad")).strip()
|
| 1041 |
+
stats = norm_stats_from_checkpoint(payload)
|
| 1042 |
+
image_size = parse_image_size(payload["image_size"])
|
| 1043 |
+
limit = float(payload["max_missing_fraction"])
|
| 1044 |
+
prepared = []
|
| 1045 |
+
for report in reports:
|
| 1046 |
+
field = report.field if mode == "stretch" else FrameGeometry.pad_square(report.field, pad)
|
| 1047 |
+
prepared.append(prepare_image(field, image_size, stats, limit))
|
| 1048 |
+
return prepared
|
| 1049 |
+
|
| 1050 |
+
@staticmethod
|
| 1051 |
+
def _mean(reports: list[GateReport]) -> float:
|
| 1052 |
+
values = [np.asarray(report.field, dtype=np.float64) for report in reports]
|
| 1053 |
+
finite = [image[np.isfinite(image)] for image in values]
|
| 1054 |
+
finite = [image for image in finite if image.size]
|
| 1055 |
+
if not finite:
|
| 1056 |
+
raise ValueError("image has no finite pixels")
|
| 1057 |
+
return float(np.concatenate(finite).mean())
|
| 1058 |
+
|
| 1059 |
+
@staticmethod
|
| 1060 |
+
def _wind(config: dict, payload: dict, prepared: list[np.ndarray], reports: list[GateReport]):
|
| 1061 |
+
if payload["_kind"] == "sklearn":
|
| 1062 |
+
wind = IntensityEstimate._sklearn_wind(config, payload, reports[0])
|
| 1063 |
+
return wind, np.asarray([wind], dtype=np.float64), None
|
| 1064 |
+
return IntensityEstimate._torch_wind(config, payload, prepared)
|
| 1065 |
+
|
| 1066 |
+
@staticmethod
|
| 1067 |
+
def _sklearn_wind(config: dict, payload: dict, report: GateReport) -> float:
|
| 1068 |
+
expected = [str(name) for name in _section(config, "predict", "sklearn_features")]
|
| 1069 |
+
names = [str(name) for name in payload["feature_names"]]
|
| 1070 |
+
if names != expected:
|
| 1071 |
+
raise ValueError("joblib feature_names do not match predict.sklearn_features")
|
| 1072 |
+
estimator = payload["estimator"]
|
| 1073 |
+
if not hasattr(estimator, "predict"):
|
| 1074 |
+
raise ValueError("joblib checkpoint estimator has no predict")
|
| 1075 |
+
features = report.feature_map()
|
| 1076 |
+
vector = np.asarray([[features[name] for name in names]], dtype=np.float64)
|
| 1077 |
+
wind = float(np.asarray(estimator.predict(vector), dtype=np.float64).reshape(-1)[0])
|
| 1078 |
+
return wind
|
| 1079 |
+
|
| 1080 |
+
@staticmethod
|
| 1081 |
+
def _torch_wind(config: dict, payload: dict, prepared: list[np.ndarray]):
|
| 1082 |
+
import torch
|
| 1083 |
+
|
| 1084 |
+
count = int(_section(config, "model", "mc_samples"))
|
| 1085 |
+
if count < 1:
|
| 1086 |
+
raise ValueError("model.mc_samples must be at least 1")
|
| 1087 |
+
stack = np.stack(prepared, axis=0)
|
| 1088 |
+
tensor = torch.from_numpy(np.ascontiguousarray(stack))
|
| 1089 |
+
model_input = tensor if len(prepared) == 1 else tensor.unsqueeze(0)
|
| 1090 |
+
model = ModelAccess.build_net(config, size_head=bool(payload.get("size_head", False)))
|
| 1091 |
+
model.load_state_dict(payload["state_dict"])
|
| 1092 |
+
seed = int(config.get("project", {}).get("seed", 0))
|
| 1093 |
+
dropout = ModelAccess.mc_dropout()
|
| 1094 |
+
state = torch.get_rng_state()
|
| 1095 |
+
try:
|
| 1096 |
+
model.eval()
|
| 1097 |
+
with torch.no_grad():
|
| 1098 |
+
point = IntensityEstimate._as_wind(model(model_input))
|
| 1099 |
+
if count == 1:
|
| 1100 |
+
return point, np.asarray([point], dtype=np.float64), 0.0
|
| 1101 |
+
dropout.enable(model)
|
| 1102 |
+
torch.manual_seed(seed)
|
| 1103 |
+
draws = [
|
| 1104 |
+
IntensityEstimate._as_wind(model(model_input)) for _ in range(count)
|
| 1105 |
+
]
|
| 1106 |
+
samples = np.asarray(draws, dtype=np.float64)
|
| 1107 |
+
return point, samples, float(samples.std(ddof=1))
|
| 1108 |
+
finally:
|
| 1109 |
+
model.eval()
|
| 1110 |
+
torch.set_rng_state(state)
|
| 1111 |
+
|
| 1112 |
+
@staticmethod
|
| 1113 |
+
def _as_wind(output) -> float:
|
| 1114 |
+
wind = output[0] if isinstance(output, tuple) else output
|
| 1115 |
+
return float(wind.detach().cpu().reshape(-1)[0])
|
| 1116 |
+
|
| 1117 |
+
|
| 1118 |
+
class RunCheckpoint:
|
| 1119 |
+
"""Resolve a checkpoint from ``paths.runs/<run_id>/`` or a Hub mirror.
|
| 1120 |
+
|
| 1121 |
+
``src.train.run_training`` writes that directory: the checkpoint file
|
| 1122 |
+
named in ``paths.checkpoint_name``, plus ``metrics.json``. A model repo
|
| 1123 |
+
with those same relative paths is the Hub mirror. ``CLOUDIE_RUN_ID``
|
| 1124 |
+
overrides ``paths.run_id``. ``CLOUDIE_HF_MODEL_REPO`` overrides
|
| 1125 |
+
``paths.hf_model_repo``. ``CLOUDIE_CHECKPOINT`` is one local file for
|
| 1126 |
+
the synthetic software check.
|
| 1127 |
+
|
| 1128 |
+
A real checkpoint produces a wind only when its run record passes
|
| 1129 |
+
:meth:`ConfidenceScore._held_out_storm_check`. Until that record exists,
|
| 1130 |
+
this returns no wind. A synthetic file is flagged by ``is_synthetic``.
|
| 1131 |
+
"""
|
| 1132 |
+
|
| 1133 |
+
ENV_REPO = "CLOUDIE_HF_MODEL_REPO"
|
| 1134 |
+
ENV_RUN = "CLOUDIE_RUN_ID"
|
| 1135 |
+
ENV_FILE = "CLOUDIE_CHECKPOINT"
|
| 1136 |
+
MISSING = (
|
| 1137 |
+
"No checkpoint was found. There is no model output. This is not a forecast."
|
| 1138 |
+
)
|
| 1139 |
+
|
| 1140 |
+
@staticmethod
|
| 1141 |
+
def _optional(config: dict, env_name: str, key: str) -> str | None:
|
| 1142 |
+
raw = os.environ.get(env_name, "").strip()
|
| 1143 |
+
if not raw:
|
| 1144 |
+
value = (config.get("paths") or {}).get(key)
|
| 1145 |
+
raw = "" if value in (None, "null") else str(value).strip()
|
| 1146 |
+
if not raw or raw.lower() in {"none", "null"}:
|
| 1147 |
+
return None
|
| 1148 |
+
return raw
|
| 1149 |
+
|
| 1150 |
+
@staticmethod
|
| 1151 |
+
def repo_id(config: dict) -> str | None:
|
| 1152 |
+
raw = RunCheckpoint._optional(config, RunCheckpoint.ENV_REPO, "hf_model_repo")
|
| 1153 |
+
if raw is None:
|
| 1154 |
+
return None
|
| 1155 |
+
namespace, separator, name = raw.partition("/")
|
| 1156 |
+
allowed = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-")
|
| 1157 |
+
if (
|
| 1158 |
+
not separator
|
| 1159 |
+
or "/" in name
|
| 1160 |
+
or not namespace
|
| 1161 |
+
or not name
|
| 1162 |
+
or ".." in raw
|
| 1163 |
+
or any(char not in allowed for char in namespace + name)
|
| 1164 |
+
):
|
| 1165 |
+
raise ValueError("The Hugging Face model repo id must be namespace/name.")
|
| 1166 |
+
return raw
|
| 1167 |
+
|
| 1168 |
+
@staticmethod
|
| 1169 |
+
def run_id(config: dict) -> str | None:
|
| 1170 |
+
raw = RunCheckpoint._optional(config, RunCheckpoint.ENV_RUN, "run_id")
|
| 1171 |
+
if raw is None:
|
| 1172 |
+
return None
|
| 1173 |
+
if raw != Path(raw).name or ".." in raw:
|
| 1174 |
+
raise ValueError("paths.run_id must be a single directory name.")
|
| 1175 |
+
return raw
|
| 1176 |
+
|
| 1177 |
+
@staticmethod
|
| 1178 |
+
def download(repo_id: str, filename: str) -> Path:
|
| 1179 |
+
"""Fetch one file from a model repo. Tests replace this method."""
|
| 1180 |
+
if filename.startswith("/") or "\\" in filename or ".." in filename.split("/"):
|
| 1181 |
+
raise ValueError("The Hub filename must stay inside the repo.")
|
| 1182 |
+
message = (
|
| 1183 |
+
"The Hugging Face checkpoint could not be loaded. "
|
| 1184 |
+
"There is no model output. This is not a forecast."
|
| 1185 |
+
)
|
| 1186 |
+
try:
|
| 1187 |
+
from huggingface_hub import hf_hub_download
|
| 1188 |
+
except ImportError as exc:
|
| 1189 |
+
raise ValueError(message) from exc
|
| 1190 |
+
try:
|
| 1191 |
+
fetched = hf_hub_download(repo_id=repo_id, filename=filename, repo_type="model")
|
| 1192 |
+
except (KeyboardInterrupt, SystemExit):
|
| 1193 |
+
raise
|
| 1194 |
+
except Exception as exc:
|
| 1195 |
+
raise ValueError(message) from exc
|
| 1196 |
+
return Path(fetched)
|
| 1197 |
+
|
| 1198 |
+
@staticmethod
|
| 1199 |
+
def resolve(config: dict, root: Path | None = None) -> tuple[Path | None, dict]:
|
| 1200 |
+
"""Return the checkpoint and a config that can see its ``metrics.json``."""
|
| 1201 |
+
override = os.environ.get(RunCheckpoint.ENV_FILE, "").strip()
|
| 1202 |
+
if override:
|
| 1203 |
+
path = Path(override)
|
| 1204 |
+
prepared = RunRecord._with_active(config, path.parent) if path.is_file() else config
|
| 1205 |
+
return (path if path.is_file() else None), prepared
|
| 1206 |
+
base = root or Path()
|
| 1207 |
+
selected = RunCheckpoint.run_id(config)
|
| 1208 |
+
name = str(_section(config, "paths", "checkpoint_name"))
|
| 1209 |
+
if name != Path(name).name:
|
| 1210 |
+
raise ValueError("paths.checkpoint_name must be a file name, not a path.")
|
| 1211 |
+
if selected:
|
| 1212 |
+
directory = Path(_section(config, "paths", "runs")) / selected
|
| 1213 |
+
if not directory.is_absolute():
|
| 1214 |
+
directory = base / directory
|
| 1215 |
+
local = directory / name
|
| 1216 |
+
if local.is_file():
|
| 1217 |
+
return local, RunRecord._with_active(config, local.parent)
|
| 1218 |
+
repo = RunCheckpoint.repo_id(config)
|
| 1219 |
+
if repo is None:
|
| 1220 |
+
return None, config
|
| 1221 |
+
prefix = f"{selected}/" if selected else ""
|
| 1222 |
+
downloaded = RunCheckpoint.download(repo, f"{prefix}{name}")
|
| 1223 |
+
try:
|
| 1224 |
+
metrics = RunCheckpoint.download(repo, f"{prefix}metrics.json")
|
| 1225 |
+
except ValueError:
|
| 1226 |
+
metrics = None
|
| 1227 |
+
if metrics is None:
|
| 1228 |
+
return downloaded, config
|
| 1229 |
+
return downloaded, RunRecord._with_active(config, metrics.parent)
|
| 1230 |
+
|
| 1231 |
+
@staticmethod
|
| 1232 |
+
def held_out(config: dict, payload: dict) -> bool:
|
| 1233 |
+
matched, record = RunRecord.load_match(config, payload)
|
| 1234 |
+
if not matched or record is None:
|
| 1235 |
+
return False
|
| 1236 |
+
return bool(ConfidenceScore._held_out_storm_check(record))
|
| 1237 |
+
|
| 1238 |
+
@staticmethod
|
| 1239 |
+
def estimate(
|
| 1240 |
+
config: dict,
|
| 1241 |
+
images: list[np.ndarray],
|
| 1242 |
+
*,
|
| 1243 |
+
hemisphere: str | None = None,
|
| 1244 |
+
latitude=None,
|
| 1245 |
+
longitude=None,
|
| 1246 |
+
metadata=None,
|
| 1247 |
+
root: Path | None = None,
|
| 1248 |
+
path: Path | None = None,
|
| 1249 |
+
resolve: bool = True,
|
| 1250 |
+
) -> Estimate:
|
| 1251 |
+
"""Gate the frame, then load a run checkpoint when one is allowed to answer.
|
| 1252 |
+
|
| 1253 |
+
``path`` is an explicit file. ``resolve`` looks up ``paths.runs`` and
|
| 1254 |
+
the Hub mirror when ``path`` is omitted.
|
| 1255 |
+
"""
|
| 1256 |
+
try:
|
| 1257 |
+
ctx = IntensityEstimate._context(config, latitude, longitude, metadata)
|
| 1258 |
+
except ValueError:
|
| 1259 |
+
ctx = IntensityEstimate._context(config, None, None, None)
|
| 1260 |
+
settings = GateSettings.from_config(config)
|
| 1261 |
+
frames = IntensityEstimate._unflipped(images, hemisphere)
|
| 1262 |
+
reports = [CycloneImageGate.assess(frame, settings) for frame in frames]
|
| 1263 |
+
refused = next((report for report in reports if not report.accepted), None)
|
| 1264 |
+
if refused is not None:
|
| 1265 |
+
return Estimate(
|
| 1266 |
+
"not_cyclone",
|
| 1267 |
+
IntensityEstimate._gate_banner(settings, refused.reason),
|
| 1268 |
+
False,
|
| 1269 |
+
gate_reason=refused.reason,
|
| 1270 |
+
gate_score=refused.score,
|
| 1271 |
+
**ctx,
|
| 1272 |
+
)
|
| 1273 |
+
try:
|
| 1274 |
+
if path is not None:
|
| 1275 |
+
chosen = Path(path)
|
| 1276 |
+
if chosen.is_file():
|
| 1277 |
+
prepared = RunRecord._with_active(config, chosen.parent)
|
| 1278 |
+
else:
|
| 1279 |
+
chosen = None
|
| 1280 |
+
prepared = config
|
| 1281 |
+
elif resolve:
|
| 1282 |
+
chosen, prepared = RunCheckpoint.resolve(config, root)
|
| 1283 |
+
else:
|
| 1284 |
+
chosen, prepared = None, config
|
| 1285 |
+
except ValueError as exc:
|
| 1286 |
+
return Estimate("no_run_record", str(exc), False, **ctx)
|
| 1287 |
+
path = chosen
|
| 1288 |
+
if path is None:
|
| 1289 |
+
return Estimate("missing_checkpoint", RunCheckpoint.MISSING, False, **ctx)
|
| 1290 |
+
try:
|
| 1291 |
+
payload = CheckpointStore.load(path)
|
| 1292 |
+
except (OSError, ValueError) as exc:
|
| 1293 |
+
return Estimate("no_run_record", str(exc), False, **ctx)
|
| 1294 |
+
synthetic = bool(payload.get("is_synthetic"))
|
| 1295 |
+
if not synthetic and not RunCheckpoint.held_out(prepared, payload):
|
| 1296 |
+
matched, _record = RunRecord.load_match(prepared, payload)
|
| 1297 |
+
if matched:
|
| 1298 |
+
message = str(_section(prepared, "predict", "held_out_refusal")).strip()
|
| 1299 |
+
else:
|
| 1300 |
+
message = str(_section(prepared, "predict", "no_run_record_refusal")).strip()
|
| 1301 |
+
return Estimate("no_run_record", message, False, matched_run=matched, **ctx)
|
| 1302 |
+
try:
|
| 1303 |
+
return IntensityEstimate.predict(
|
| 1304 |
+
prepared,
|
| 1305 |
+
path,
|
| 1306 |
+
images,
|
| 1307 |
+
hemisphere=hemisphere,
|
| 1308 |
+
latitude=latitude,
|
| 1309 |
+
longitude=longitude,
|
| 1310 |
+
metadata=metadata,
|
| 1311 |
+
)
|
| 1312 |
+
except (OSError, ValueError) as exc:
|
| 1313 |
+
return Estimate("no_run_record", str(exc), synthetic, **ctx)
|
bundle/src/labels.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""IMD 3-minute wind target.
|
| 2 |
+
|
| 3 |
+
NASA and TCIR labels are 1-minute sustained winds. INCYDE labels are already
|
| 4 |
+
IMD 3-minute winds. The training target is ``wind_kt_3min``. Raw knots stay
|
| 5 |
+
on ``wind_speed_kt`` and ``wind_kt``.
|
| 6 |
+
|
| 7 |
+
The 1-minute to 3-minute factor is ``labels.wind_1min_to_3min`` (0.93 in the
|
| 8 |
+
YAML). It is a derived at-sea gust factor from WMO/TD-1555 Tables 1.1 and
|
| 9 |
+
1.2 (Harper, Kepert and Ginger 2010), not a WMO constant, and it is meant
|
| 10 |
+
for open water more than 20 km offshore. This module does not download a
|
| 11 |
+
coastline. A dataset with no land indicator is marked unknown.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import math
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pandas as pd
|
| 20 |
+
|
| 21 |
+
from src.schema import wind_averaging_seconds
|
| 22 |
+
|
| 23 |
+
# Citation for the default factor. The numeric factor itself lives in the YAML.
|
| 24 |
+
WIND_CONVERSION_NOTE = (
|
| 25 |
+
"0.93, derived from WMO/TD-1555 Tables 1.1 and 1.2, "
|
| 26 |
+
"at-sea exposure (not a WMO constant)"
|
| 27 |
+
)
|
| 28 |
+
HELD_RAW_NOTE = "held raw: near land, at-sea factor not applied"
|
| 29 |
+
NEAR_LAND_POLICIES = ("flag", "raw")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def conversion_note(factor: float) -> str:
|
| 33 |
+
"""Provenance string for a row whose 1-minute wind was multiplied.
|
| 34 |
+
|
| 35 |
+
The default factor of 0.93 uses the citation verbatim. Any other
|
| 36 |
+
configured factor keeps the same source and names that factor.
|
| 37 |
+
"""
|
| 38 |
+
if not math.isfinite(factor) or factor <= 0:
|
| 39 |
+
raise ValueError("wind factor must be a positive finite number")
|
| 40 |
+
if f"{float(factor):.2f}" == "0.93":
|
| 41 |
+
return WIND_CONVERSION_NOTE
|
| 42 |
+
return (
|
| 43 |
+
f"{float(factor):.2f}, derived from WMO/TD-1555 Tables 1.1 and 1.2, "
|
| 44 |
+
"at-sea exposure (not a WMO constant)"
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _blank(value: object) -> bool:
|
| 49 |
+
if value is None:
|
| 50 |
+
return True
|
| 51 |
+
try:
|
| 52 |
+
if pd.isna(value):
|
| 53 |
+
return True
|
| 54 |
+
except (TypeError, ValueError):
|
| 55 |
+
return False
|
| 56 |
+
return str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _flag(value: object) -> str:
|
| 60 |
+
"""``true``, ``false``, or ``unknown``."""
|
| 61 |
+
if isinstance(value, (bool, np.bool_)):
|
| 62 |
+
return "true" if bool(value) else "false"
|
| 63 |
+
if _blank(value):
|
| 64 |
+
return "unknown"
|
| 65 |
+
text = str(value).strip().lower()
|
| 66 |
+
if text in {"1", "true", "yes", "y", "t"}:
|
| 67 |
+
return "true"
|
| 68 |
+
if text in {"0", "false", "no", "n", "f"}:
|
| 69 |
+
return "false"
|
| 70 |
+
if text in {"unknown", "na", "n/a"}:
|
| 71 |
+
return "unknown"
|
| 72 |
+
raise ValueError(f"land indicator {value!r} is not true, false, or unknown")
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def near_land_status(frame: pd.DataFrame, open_water_km: float) -> pd.Series:
|
| 76 |
+
"""Per-row near-land status: ``true``, ``false``, or ``unknown``.
|
| 77 |
+
|
| 78 |
+
``distance_to_land_km`` is the quantitative indicator. Open water is
|
| 79 |
+
strictly farther than ``open_water_km`` (20 km in the YAML). A
|
| 80 |
+
``near_land`` or ``landfall`` column is used when there is no distance.
|
| 81 |
+
Latitude and longitude are not a land indicator. With none of those
|
| 82 |
+
columns the whole frame is unknown.
|
| 83 |
+
"""
|
| 84 |
+
if open_water_km < 0 or not math.isfinite(open_water_km):
|
| 85 |
+
raise ValueError("open_water_km must be a non-negative finite distance")
|
| 86 |
+
if "distance_to_land_km" in frame.columns:
|
| 87 |
+
distance = pd.to_numeric(frame["distance_to_land_km"], errors="coerce")
|
| 88 |
+
status = np.where(
|
| 89 |
+
distance.isna(),
|
| 90 |
+
"unknown",
|
| 91 |
+
np.where(distance > float(open_water_km), "false", "true"),
|
| 92 |
+
)
|
| 93 |
+
return pd.Series(status, index=frame.index, dtype=object)
|
| 94 |
+
if "near_land" in frame.columns:
|
| 95 |
+
return pd.Series(
|
| 96 |
+
[_flag(value) for value in frame["near_land"].tolist()],
|
| 97 |
+
index=frame.index,
|
| 98 |
+
dtype=object,
|
| 99 |
+
)
|
| 100 |
+
if "landfall" in frame.columns:
|
| 101 |
+
return pd.Series(
|
| 102 |
+
[_flag(value) for value in frame["landfall"].tolist()],
|
| 103 |
+
index=frame.index,
|
| 104 |
+
dtype=object,
|
| 105 |
+
)
|
| 106 |
+
return pd.Series("unknown", index=frame.index, dtype=object)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _raw_knots(frame: pd.DataFrame) -> pd.Series:
|
| 110 |
+
if "wind_speed_kt" not in frame.columns and "wind_kt" not in frame.columns:
|
| 111 |
+
raise ValueError("a wind row needs wind_speed_kt or wind_kt")
|
| 112 |
+
if "wind_speed_kt" in frame.columns and "wind_kt" in frame.columns:
|
| 113 |
+
left = pd.to_numeric(frame["wind_speed_kt"], errors="coerce")
|
| 114 |
+
right = pd.to_numeric(frame["wind_kt"], errors="coerce")
|
| 115 |
+
if not np.allclose(left.to_numpy(dtype=float), right.to_numpy(dtype=float), equal_nan=True):
|
| 116 |
+
raise ValueError("wind_kt and wind_speed_kt disagree; refusing to convert either")
|
| 117 |
+
return left
|
| 118 |
+
column = "wind_speed_kt" if "wind_speed_kt" in frame.columns else "wind_kt"
|
| 119 |
+
return pd.to_numeric(frame[column], errors="coerce")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def apply_wind_standard(
|
| 123 |
+
frame: pd.DataFrame,
|
| 124 |
+
*,
|
| 125 |
+
factor: float,
|
| 126 |
+
policy: str,
|
| 127 |
+
open_water_km: float,
|
| 128 |
+
) -> pd.DataFrame:
|
| 129 |
+
"""Add ``wind_kt_3min`` without overwriting the raw label.
|
| 130 |
+
|
| 131 |
+
3-minute rows, including INCYDE, pass through (``wind_kt_3min == wind_kt``).
|
| 132 |
+
1-minute rows are multiplied by ``factor`` unless ``policy`` is ``raw``
|
| 133 |
+
and the row is near land. ``flag`` (the default) still multiplies those
|
| 134 |
+
rows and sets ``conversion_exposure_flag`` true. Unknown exposure is
|
| 135 |
+
converted and the flag stays ``unknown``, so the at-sea factor is not
|
| 136 |
+
recorded as an open-water measurement.
|
| 137 |
+
"""
|
| 138 |
+
choice = str(policy).strip().lower()
|
| 139 |
+
if choice not in NEAR_LAND_POLICIES:
|
| 140 |
+
raise ValueError("labels.near_land_policy must be flag or raw")
|
| 141 |
+
note = conversion_note(factor)
|
| 142 |
+
if "wind_averaging" not in frame.columns:
|
| 143 |
+
raise ValueError("wind_averaging is required before the 3-minute target is added")
|
| 144 |
+
raw = _raw_knots(frame).to_numpy(dtype=float)
|
| 145 |
+
status = near_land_status(frame, open_water_km).tolist()
|
| 146 |
+
periods = [str(value).strip() for value in frame["wind_averaging"].tolist()]
|
| 147 |
+
target = np.empty(len(frame), dtype=float)
|
| 148 |
+
scale = np.empty(len(frame), dtype=float)
|
| 149 |
+
notes: list[str] = []
|
| 150 |
+
flags: list[str] = []
|
| 151 |
+
seconds: list[int | None] = []
|
| 152 |
+
for index, (period, land) in enumerate(zip(periods, status, strict=True)):
|
| 153 |
+
duration = wind_averaging_seconds(period)
|
| 154 |
+
seconds.append(duration)
|
| 155 |
+
if duration == 60:
|
| 156 |
+
hold = land == "true" and choice == "raw"
|
| 157 |
+
if hold:
|
| 158 |
+
target[index] = raw[index]
|
| 159 |
+
scale[index] = 1.0
|
| 160 |
+
notes.append(HELD_RAW_NOTE)
|
| 161 |
+
flags.append("true")
|
| 162 |
+
else:
|
| 163 |
+
target[index] = raw[index] * float(factor)
|
| 164 |
+
scale[index] = float(factor)
|
| 165 |
+
notes.append(note)
|
| 166 |
+
flags.append(land)
|
| 167 |
+
else:
|
| 168 |
+
target[index] = raw[index]
|
| 169 |
+
scale[index] = 1.0
|
| 170 |
+
notes.append("")
|
| 171 |
+
flags.append("")
|
| 172 |
+
out = frame.copy()
|
| 173 |
+
out["wind_speed_kt"] = raw
|
| 174 |
+
out["wind_kt"] = raw
|
| 175 |
+
out["wind_kt_3min"] = target
|
| 176 |
+
out["wind_kt_scale"] = scale
|
| 177 |
+
out["wind_conversion"] = notes
|
| 178 |
+
out["conversion_exposure_flag"] = flags
|
| 179 |
+
out["near_land"] = status
|
| 180 |
+
out["wind_averaging_s"] = pd.array(seconds, dtype="Int64")
|
| 181 |
+
return out
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def run_conversion_note(frame: pd.DataFrame) -> str | None:
|
| 185 |
+
"""The single conversion note on this frame, or null when nothing was scaled."""
|
| 186 |
+
if "wind_conversion" not in frame.columns or frame.empty:
|
| 187 |
+
return None
|
| 188 |
+
notes = []
|
| 189 |
+
for value in frame["wind_conversion"].tolist():
|
| 190 |
+
if _blank(value):
|
| 191 |
+
continue
|
| 192 |
+
text = str(value).strip()
|
| 193 |
+
if text.lower() in {"nan", "none", "null"}:
|
| 194 |
+
continue
|
| 195 |
+
notes.append(text)
|
| 196 |
+
notes = sorted(set(notes))
|
| 197 |
+
if not notes:
|
| 198 |
+
return None
|
| 199 |
+
if len(notes) == 1:
|
| 200 |
+
return notes[0]
|
| 201 |
+
return " | ".join(notes)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def back_converted_prediction(prediction: np.ndarray, scale: np.ndarray) -> np.ndarray:
|
| 205 |
+
"""Map a 3-minute prediction back to the raw label.
|
| 206 |
+
|
| 207 |
+
Converted 1-minute rows use ``prediction / factor``. Pass-through rows
|
| 208 |
+
have scale 1. Near-land rows held at the raw label also have scale 1.
|
| 209 |
+
"""
|
| 210 |
+
pred = np.asarray(prediction, dtype=np.float64).reshape(-1)
|
| 211 |
+
weights = np.asarray(scale, dtype=np.float64).reshape(-1)
|
| 212 |
+
if pred.shape != weights.shape:
|
| 213 |
+
raise ValueError("prediction and wind_kt_scale must have the same length")
|
| 214 |
+
if weights.size and (not np.isfinite(weights).all() or np.any(weights <= 0)):
|
| 215 |
+
raise ValueError("wind_kt_scale must be a positive finite multiplier")
|
| 216 |
+
return pred / weights
|
bundle/src/make_smoke_data.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synthetic images for software tests. These are not cyclones."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
# Project-class winds that stay inside the bin when a few knots are added.
|
| 12 |
+
CLASS_WINDS = (
|
| 13 |
+
("D_DD", 26.0),
|
| 14 |
+
("CS", 40.0),
|
| 15 |
+
("SCS", 55.0),
|
| 16 |
+
("VSCS", 75.0),
|
| 17 |
+
("ESCS_SUCS", 105.0),
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _synthetic_ir(size: int, wind_kt: float, rng: np.random.Generator) -> np.ndarray:
|
| 22 |
+
yy, xx = np.mgrid[0:size, 0:size]
|
| 23 |
+
radius = np.hypot(yy - size / 2, xx - size / 2)
|
| 24 |
+
cold_core = 220.0 - (wind_kt - 20.0) * 0.7 * np.exp(-(radius**2) / (2 * 8.0**2))
|
| 25 |
+
noise = rng.normal(0.0, 1.5, size=(size, size))
|
| 26 |
+
return (cold_core + noise).astype(np.float32)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _write_rows(root: Path, rows: list[dict[str, object]]) -> Path:
|
| 30 |
+
manifest = root / "manifest.csv"
|
| 31 |
+
pd.DataFrame(rows).to_csv(manifest, index=False)
|
| 32 |
+
return manifest
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def write_smoke(
|
| 36 |
+
root: Path,
|
| 37 |
+
n_storms: int = 8,
|
| 38 |
+
frames_per_storm: int = 4,
|
| 39 |
+
size: int = 64,
|
| 40 |
+
seed: int = 7,
|
| 41 |
+
) -> Path:
|
| 42 |
+
"""Write a manifest and ``.npy`` images.
|
| 43 |
+
|
| 44 |
+
Storm ``S06`` has frames in 2020 and 2021 so the year-holdout test can
|
| 45 |
+
prove that a boundary storm is not cut.
|
| 46 |
+
"""
|
| 47 |
+
rng = np.random.default_rng(seed)
|
| 48 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 49 |
+
image_dir = root / "images"
|
| 50 |
+
image_dir.mkdir(exist_ok=True)
|
| 51 |
+
rows: list[dict[str, object]] = []
|
| 52 |
+
for index in range(n_storms):
|
| 53 |
+
storm_id = f"S{index:02d}"
|
| 54 |
+
basin = "NIO" if index % 2 else "NA"
|
| 55 |
+
year = 2018 + (index % 4)
|
| 56 |
+
for time_index in range(frames_per_storm):
|
| 57 |
+
year_t = 2021 if index == 6 and time_index >= 2 else year
|
| 58 |
+
wind = float(np.clip(25 + index * 12 + time_index * 2, 20, 140))
|
| 59 |
+
relative = Path("images") / f"{storm_id}_{time_index:02d}.npy"
|
| 60 |
+
np.save(root / relative, _synthetic_ir(size, wind, rng))
|
| 61 |
+
rows.append(
|
| 62 |
+
{
|
| 63 |
+
"sample_id": f"{storm_id}_{time_index:02d}",
|
| 64 |
+
"image_path": relative.as_posix(),
|
| 65 |
+
"storm_id": storm_id,
|
| 66 |
+
"timestamp": f"{year_t}-06-01T{time_index:02d}:00:00Z",
|
| 67 |
+
"year": year_t,
|
| 68 |
+
"basin": basin,
|
| 69 |
+
"sensor": "synthetic",
|
| 70 |
+
"channel": "IR",
|
| 71 |
+
"wind_speed_kt": wind,
|
| 72 |
+
"wind_averaging": "synthetic",
|
| 73 |
+
"label_source": "smoke",
|
| 74 |
+
"is_synthetic": True,
|
| 75 |
+
}
|
| 76 |
+
)
|
| 77 |
+
return _write_rows(root, rows)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def write_balanced_smoke(
|
| 81 |
+
root: Path,
|
| 82 |
+
storms_per_class: int = 5,
|
| 83 |
+
frames_per_storm: int = 4,
|
| 84 |
+
size: int = 48,
|
| 85 |
+
seed: int = 7,
|
| 86 |
+
) -> Path:
|
| 87 |
+
"""One wind bin per storm, several storms per project class.
|
| 88 |
+
|
| 89 |
+
Used to exercise grouped classification splits. Still synthetic.
|
| 90 |
+
"""
|
| 91 |
+
if storms_per_class < 3:
|
| 92 |
+
raise ValueError("storms_per_class must be at least 3 for grouped folds")
|
| 93 |
+
rng = np.random.default_rng(seed)
|
| 94 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 95 |
+
image_dir = root / "images"
|
| 96 |
+
image_dir.mkdir(exist_ok=True)
|
| 97 |
+
rows: list[dict[str, object]] = []
|
| 98 |
+
for class_index, (_name, base_wind) in enumerate(CLASS_WINDS):
|
| 99 |
+
for storm_index in range(storms_per_class):
|
| 100 |
+
storm_id = f"C{class_index}{storm_index}"
|
| 101 |
+
basin = "NIO" if (class_index + storm_index) % 2 else "NA"
|
| 102 |
+
year = 2016 + ((class_index + storm_index) % 6)
|
| 103 |
+
for time_index in range(frames_per_storm):
|
| 104 |
+
wind = float(base_wind + time_index)
|
| 105 |
+
relative = Path("images") / f"{storm_id}_{time_index:02d}.npy"
|
| 106 |
+
np.save(root / relative, _synthetic_ir(size, wind, rng))
|
| 107 |
+
rows.append(
|
| 108 |
+
{
|
| 109 |
+
"sample_id": f"{storm_id}_{time_index:02d}",
|
| 110 |
+
"image_path": relative.as_posix(),
|
| 111 |
+
"storm_id": storm_id,
|
| 112 |
+
"timestamp": f"{year}-08-01T{time_index:02d}:00:00Z",
|
| 113 |
+
"year": year,
|
| 114 |
+
"basin": basin,
|
| 115 |
+
"sensor": "synthetic",
|
| 116 |
+
"channel": "IR",
|
| 117 |
+
"wind_speed_kt": wind,
|
| 118 |
+
"wind_averaging": "synthetic",
|
| 119 |
+
"label_source": "smoke",
|
| 120 |
+
"is_synthetic": True,
|
| 121 |
+
}
|
| 122 |
+
)
|
| 123 |
+
return _write_rows(root, rows)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _default_out() -> Path:
|
| 127 |
+
"""Directory that holds ``paths.manifest`` in the smoke config."""
|
| 128 |
+
from src.config import load_config
|
| 129 |
+
|
| 130 |
+
root = Path(__file__).resolve().parents[1]
|
| 131 |
+
manifest = Path(load_config(root / "config" / "config_smoke.yaml")["paths"]["manifest"])
|
| 132 |
+
return manifest.parent
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def main() -> None:
|
| 136 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 137 |
+
parser.add_argument("--out", type=Path, default=_default_out())
|
| 138 |
+
parser.add_argument(
|
| 139 |
+
"--profile",
|
| 140 |
+
choices=("span", "balanced"),
|
| 141 |
+
default="span",
|
| 142 |
+
help="span: year-boundary storm. balanced: several storms per class.",
|
| 143 |
+
)
|
| 144 |
+
args = parser.parse_args()
|
| 145 |
+
if args.profile == "balanced":
|
| 146 |
+
path = write_balanced_smoke(args.out)
|
| 147 |
+
else:
|
| 148 |
+
path = write_smoke(args.out)
|
| 149 |
+
print(f"Wrote synthetic manifest {path}. Not real cyclones. Do not report scores from it.")
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
if __name__ == "__main__":
|
| 153 |
+
main()
|
bundle/src/metrics.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Regression and classification metrics. No operational baseline is implied."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from sklearn.metrics import f1_score, recall_score
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def regression_metrics(y_true: np.ndarray, y_pred: np.ndarray) -> dict[str, float]:
|
| 11 |
+
truth = np.asarray(y_true, dtype=np.float64).ravel()
|
| 12 |
+
pred = np.asarray(y_pred, dtype=np.float64).ravel()
|
| 13 |
+
if truth.shape != pred.shape or truth.size == 0:
|
| 14 |
+
raise ValueError("y_true and y_pred must be non-empty and the same shape")
|
| 15 |
+
error = pred - truth
|
| 16 |
+
return {
|
| 17 |
+
"n": float(truth.size),
|
| 18 |
+
"mae_kt": float(np.mean(np.abs(error))),
|
| 19 |
+
"rmse_kt": float(np.sqrt(np.mean(error**2))),
|
| 20 |
+
"bias_kt": float(np.mean(error)),
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _as_seed(value: int, name: str) -> int:
|
| 25 |
+
if isinstance(value, bool) or not isinstance(value, (int, np.integer)):
|
| 26 |
+
raise ValueError(f"{name} must be an integer")
|
| 27 |
+
return int(value)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _storm_index(storm_ids: np.ndarray) -> list[np.ndarray]:
|
| 31 |
+
"""Row positions of each storm, in order of first appearance."""
|
| 32 |
+
order: list[str] = []
|
| 33 |
+
buckets: dict[str, list[int]] = {}
|
| 34 |
+
for index, storm in enumerate(np.asarray(storm_ids, dtype=object).ravel().tolist()):
|
| 35 |
+
if storm is None or pd.isna(storm):
|
| 36 |
+
raise ValueError("storm_ids must be present on every row")
|
| 37 |
+
key = str(storm)
|
| 38 |
+
if key not in buckets:
|
| 39 |
+
buckets[key] = []
|
| 40 |
+
order.append(key)
|
| 41 |
+
buckets[key].append(index)
|
| 42 |
+
return [np.asarray(buckets[key], dtype=np.int64) for key in order]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def storm_bootstrap_metrics(
|
| 46 |
+
y_true: np.ndarray,
|
| 47 |
+
y_pred: np.ndarray,
|
| 48 |
+
storm_ids: np.ndarray,
|
| 49 |
+
*,
|
| 50 |
+
n_resamples: int = 1000,
|
| 51 |
+
seed: int = 0,
|
| 52 |
+
ci_level: float = 0.95,
|
| 53 |
+
) -> dict[str, float | int | str]:
|
| 54 |
+
"""RMSE, MAE, and bias with a percentile interval that resamples storms.
|
| 55 |
+
|
| 56 |
+
Bias is prediction minus true wind. Each resample draws as many storm
|
| 57 |
+
IDs as there are storms, with replacement, and keeps every row of a
|
| 58 |
+
drawn storm. A storm drawn twice contributes its rows twice. Rows are
|
| 59 |
+
not drawn on their own. The point values are the full sample, not the
|
| 60 |
+
mean of the resamples. Storms are ordered by first appearance. The
|
| 61 |
+
generator is ``numpy.random.default_rng(seed)``.
|
| 62 |
+
"""
|
| 63 |
+
truth = np.asarray(y_true, dtype=np.float64).ravel()
|
| 64 |
+
pred = np.asarray(y_pred, dtype=np.float64).ravel()
|
| 65 |
+
if truth.shape != pred.shape or truth.size == 0:
|
| 66 |
+
raise ValueError("y_true and y_pred must be non-empty and the same shape")
|
| 67 |
+
if not np.isfinite(truth).all() or not np.isfinite(pred).all():
|
| 68 |
+
raise ValueError("y_true and y_pred must be finite")
|
| 69 |
+
ids = np.asarray(storm_ids, dtype=object).ravel()
|
| 70 |
+
if ids.size != truth.size:
|
| 71 |
+
raise ValueError("storm_ids must align with y_true")
|
| 72 |
+
groups = _storm_index(ids)
|
| 73 |
+
if not groups:
|
| 74 |
+
raise ValueError("storm_ids must align with y_true")
|
| 75 |
+
resamples = _as_seed(n_resamples, "n_resamples")
|
| 76 |
+
if resamples < 1:
|
| 77 |
+
raise ValueError("n_resamples must be at least 1")
|
| 78 |
+
seed_value = _as_seed(seed, "seed")
|
| 79 |
+
level = float(ci_level)
|
| 80 |
+
if not 0.0 < level < 1.0:
|
| 81 |
+
raise ValueError(f"ci_level must be between 0 and 1, got {level}")
|
| 82 |
+
point = regression_metrics(truth, pred)
|
| 83 |
+
error = pred - truth
|
| 84 |
+
n_per = np.asarray([group.size for group in groups], dtype=np.float64)
|
| 85 |
+
sum_abs = np.asarray([np.abs(error[group]).sum() for group in groups], dtype=np.float64)
|
| 86 |
+
sum_sq = np.asarray([(error[group] ** 2).sum() for group in groups], dtype=np.float64)
|
| 87 |
+
sum_err = np.asarray([error[group].sum() for group in groups], dtype=np.float64)
|
| 88 |
+
drawn = np.random.default_rng(seed_value).integers(0, len(groups), size=(resamples, len(groups)))
|
| 89 |
+
mae_s = np.empty(resamples, dtype=np.float64)
|
| 90 |
+
rmse_s = np.empty(resamples, dtype=np.float64)
|
| 91 |
+
bias_s = np.empty(resamples, dtype=np.float64)
|
| 92 |
+
for index, draw in enumerate(drawn):
|
| 93 |
+
counts = np.bincount(draw, minlength=len(groups)).astype(np.float64)
|
| 94 |
+
total = float(counts @ n_per)
|
| 95 |
+
mae_s[index] = float(counts @ sum_abs) / total
|
| 96 |
+
rmse_s[index] = float(np.sqrt((counts @ sum_sq) / total))
|
| 97 |
+
bias_s[index] = float(counts @ sum_err) / total
|
| 98 |
+
alpha = (1.0 - level) / 2.0
|
| 99 |
+
out: dict[str, float | int | str] = {
|
| 100 |
+
"n_rows": int(truth.size),
|
| 101 |
+
"n_storms": int(len(groups)),
|
| 102 |
+
"mae_kt": float(point["mae_kt"]),
|
| 103 |
+
"rmse_kt": float(point["rmse_kt"]),
|
| 104 |
+
"bias_kt": float(point["bias_kt"]),
|
| 105 |
+
"n_resamples": resamples,
|
| 106 |
+
"seed": seed_value,
|
| 107 |
+
"ci_level": level,
|
| 108 |
+
"resample": "storm_id",
|
| 109 |
+
}
|
| 110 |
+
for name, samples in (
|
| 111 |
+
("mae_kt", mae_s),
|
| 112 |
+
("rmse_kt", rmse_s),
|
| 113 |
+
("bias_kt", bias_s),
|
| 114 |
+
):
|
| 115 |
+
out[f"{name}_ci_low"] = float(np.quantile(samples, alpha, method="linear"))
|
| 116 |
+
out[f"{name}_ci_high"] = float(np.quantile(samples, 1.0 - alpha, method="linear"))
|
| 117 |
+
return out
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def metrics_by_class(
|
| 121 |
+
y_true: np.ndarray, y_pred: np.ndarray, classes: np.ndarray
|
| 122 |
+
) -> dict[str, dict[str, float]]:
|
| 123 |
+
truth = np.asarray(y_true, dtype=np.float64).ravel()
|
| 124 |
+
pred = np.asarray(y_pred, dtype=np.float64).ravel()
|
| 125 |
+
labels = np.asarray(classes)
|
| 126 |
+
if len(labels) != truth.size:
|
| 127 |
+
raise ValueError("classes must align with y_true")
|
| 128 |
+
out: dict[str, dict[str, float]] = {}
|
| 129 |
+
for name in pd.unique(labels):
|
| 130 |
+
if pd.isna(name):
|
| 131 |
+
continue
|
| 132 |
+
mask = labels == name
|
| 133 |
+
if np.asarray(mask).sum() == 0:
|
| 134 |
+
continue
|
| 135 |
+
out[str(name)] = regression_metrics(truth[mask], pred[mask])
|
| 136 |
+
return out
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def mean_baseline(y_train: np.ndarray, n_rows: int) -> np.ndarray:
|
| 140 |
+
"""Predict the training mean. Fit this on train storms only."""
|
| 141 |
+
return np.full(n_rows, float(np.mean(np.asarray(y_train, dtype=np.float64))))
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def classification_metrics(
|
| 145 |
+
y_true: np.ndarray,
|
| 146 |
+
y_pred: np.ndarray,
|
| 147 |
+
labels: tuple[str, ...],
|
| 148 |
+
) -> dict[str, float]:
|
| 149 |
+
"""Macro-F1 over classes present in ``y_true``, plus per-class recall.
|
| 150 |
+
|
| 151 |
+
Recall is NaN when the validation side has no samples of that class.
|
| 152 |
+
Accuracy is omitted on purpose: a single headline rate hides the rare
|
| 153 |
+
intense classes.
|
| 154 |
+
"""
|
| 155 |
+
truth = np.asarray(y_true).ravel()
|
| 156 |
+
pred = np.asarray(y_pred).ravel()
|
| 157 |
+
if truth.shape != pred.shape or truth.size == 0:
|
| 158 |
+
raise ValueError("y_true and y_pred must be non-empty and the same shape")
|
| 159 |
+
present = [label for label in labels if np.any(truth == label)]
|
| 160 |
+
if not present:
|
| 161 |
+
present = [str(value) for value in pd.unique(truth)]
|
| 162 |
+
macro = float(
|
| 163 |
+
f1_score(truth, pred, labels=present, average="macro", zero_division=0)
|
| 164 |
+
)
|
| 165 |
+
recalls = recall_score(
|
| 166 |
+
truth, pred, labels=list(labels), average=None, zero_division=0
|
| 167 |
+
)
|
| 168 |
+
out: dict[str, float] = {"n": float(truth.size), "macro_f1": macro}
|
| 169 |
+
for label, recall in zip(labels, recalls, strict=True):
|
| 170 |
+
if not np.any(truth == label):
|
| 171 |
+
out[f"recall_{label}"] = float("nan")
|
| 172 |
+
else:
|
| 173 |
+
out[f"recall_{label}"] = float(recall)
|
| 174 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model interfaces. Importing this module requires torch.
|
| 2 |
+
|
| 3 |
+
Spatial size is not fixed. The caller supplies the frame size (``data.image_size``
|
| 4 |
+
or a native infrared frame). Both regressors pool with ``AdaptiveAvgPool2d``
|
| 5 |
+
before the heads. ``pretrained=True`` downloads ImageNet weights and is refused
|
| 6 |
+
unless ``CLOUDIE_ALLOW_PRETRAINED=1``.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
from torch import nn
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class OptionalClassHead:
|
| 18 |
+
"""Project-class logits. Absent when the caller does not ask for them."""
|
| 19 |
+
|
| 20 |
+
@staticmethod
|
| 21 |
+
def build(feature_dim: int, n_classes: int | None) -> nn.Linear | None:
|
| 22 |
+
if n_classes is None:
|
| 23 |
+
return None
|
| 24 |
+
count = int(n_classes)
|
| 25 |
+
if count < 1:
|
| 26 |
+
raise ValueError("n_classes must be at least 1")
|
| 27 |
+
return nn.Linear(feature_dim, count)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class SimpleCNN(nn.Module):
|
| 31 |
+
"""Small regressor for smoke tests and a first real baseline.
|
| 32 |
+
|
| 33 |
+
The regression head predicts wind speed in knots. ``n_classes`` adds a
|
| 34 |
+
class head on the same pooled features. Dropout stays on the wind head.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
in_channels: int = 1,
|
| 40 |
+
dropout: float = 0.3,
|
| 41 |
+
n_classes: int | None = None,
|
| 42 |
+
) -> None:
|
| 43 |
+
super().__init__()
|
| 44 |
+
self.feature_dim = 64
|
| 45 |
+
self.features = nn.Sequential(
|
| 46 |
+
nn.Conv2d(in_channels, 16, 3, padding=1),
|
| 47 |
+
nn.ReLU(),
|
| 48 |
+
nn.MaxPool2d(2),
|
| 49 |
+
nn.Conv2d(16, 32, 3, padding=1),
|
| 50 |
+
nn.ReLU(),
|
| 51 |
+
nn.MaxPool2d(2),
|
| 52 |
+
nn.Conv2d(32, 64, 3, padding=1),
|
| 53 |
+
nn.ReLU(),
|
| 54 |
+
nn.AdaptiveAvgPool2d(1),
|
| 55 |
+
)
|
| 56 |
+
self.head = nn.Sequential(nn.Flatten(), nn.Dropout(dropout), nn.Linear(64, 1))
|
| 57 |
+
self.class_head = OptionalClassHead.build(self.feature_dim, n_classes)
|
| 58 |
+
|
| 59 |
+
def encode(self, inputs: torch.Tensor) -> torch.Tensor:
|
| 60 |
+
return self.features(inputs).flatten(1)
|
| 61 |
+
|
| 62 |
+
def forward(
|
| 63 |
+
self, inputs: torch.Tensor
|
| 64 |
+
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
| 65 |
+
features = self.encode(inputs)
|
| 66 |
+
wind = self.head(features)
|
| 67 |
+
if self.class_head is None:
|
| 68 |
+
return wind
|
| 69 |
+
return wind, self.class_head(features)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class ResNetRegressor(nn.Module):
|
| 73 |
+
"""ResNet-18 regressor. One-channel IR is repeated to three channels.
|
| 74 |
+
|
| 75 |
+
Repeating keeps the pretrained first convolution. Replacing it would
|
| 76 |
+
discard those weights. ImageNet pretraining is not a physical prior.
|
| 77 |
+
``pretrained=True`` downloads weights and must not run in CI unless
|
| 78 |
+
``CLOUDIE_ALLOW_PRETRAINED=1``. The regression head predicts wind speed
|
| 79 |
+
in knots. ``n_classes`` adds a class head on the same pooled features.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
def __init__(
|
| 83 |
+
self,
|
| 84 |
+
in_channels: int = 1,
|
| 85 |
+
pretrained: bool = False,
|
| 86 |
+
dropout: float = 0.2,
|
| 87 |
+
n_classes: int | None = None,
|
| 88 |
+
) -> None:
|
| 89 |
+
super().__init__()
|
| 90 |
+
if in_channels not in (1, 3):
|
| 91 |
+
raise ValueError(
|
| 92 |
+
"ResNet-18 keeps the 3-channel conv1. "
|
| 93 |
+
"Pass 1 channel to repeat it, or 3 channels."
|
| 94 |
+
)
|
| 95 |
+
weights = self.imagenet_weights(pretrained)
|
| 96 |
+
from torchvision.models import resnet18
|
| 97 |
+
|
| 98 |
+
backbone = resnet18(weights=weights)
|
| 99 |
+
if int(backbone.conv1.in_channels) != 3:
|
| 100 |
+
raise RuntimeError("pretrained conv1 must stay 3-channel")
|
| 101 |
+
# Adaptive pool, so a native frame and a resized frame share the head.
|
| 102 |
+
backbone.avgpool = nn.AdaptiveAvgPool2d(1)
|
| 103 |
+
in_features = backbone.fc.in_features
|
| 104 |
+
backbone.fc = nn.Identity()
|
| 105 |
+
self.backbone = backbone
|
| 106 |
+
self.feature_dim = in_features
|
| 107 |
+
self.repeat_to_rgb = in_channels == 1
|
| 108 |
+
self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(in_features, 1))
|
| 109 |
+
self.class_head = OptionalClassHead.build(self.feature_dim, n_classes)
|
| 110 |
+
|
| 111 |
+
@staticmethod
|
| 112 |
+
def imagenet_weights(pretrained: bool):
|
| 113 |
+
"""ImageNet weights, or None.
|
| 114 |
+
|
| 115 |
+
``weights=None`` builds the architecture without a download.
|
| 116 |
+
``pretrained=True`` asks for ``ResNet18_Weights.DEFAULT`` and is
|
| 117 |
+
refused unless ``CLOUDIE_ALLOW_PRETRAINED=1``.
|
| 118 |
+
"""
|
| 119 |
+
if not pretrained:
|
| 120 |
+
return None
|
| 121 |
+
if os.environ.get("CLOUDIE_ALLOW_PRETRAINED") != "1":
|
| 122 |
+
raise RuntimeError(
|
| 123 |
+
"pretrained: true downloads ImageNet weights and must not run in CI. "
|
| 124 |
+
"Set CLOUDIE_ALLOW_PRETRAINED=1 only for a local run that intends the download."
|
| 125 |
+
)
|
| 126 |
+
from torchvision.models import ResNet18_Weights
|
| 127 |
+
|
| 128 |
+
return ResNet18_Weights.DEFAULT
|
| 129 |
+
|
| 130 |
+
def encode(self, inputs: torch.Tensor) -> torch.Tensor:
|
| 131 |
+
if self.repeat_to_rgb and inputs.shape[1] == 1:
|
| 132 |
+
inputs = inputs.repeat(1, 3, 1, 1)
|
| 133 |
+
return self.backbone(inputs)
|
| 134 |
+
|
| 135 |
+
def forward(
|
| 136 |
+
self, inputs: torch.Tensor
|
| 137 |
+
) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
|
| 138 |
+
features = self.encode(inputs)
|
| 139 |
+
wind = self.head(features)
|
| 140 |
+
if self.class_head is None:
|
| 141 |
+
return wind
|
| 142 |
+
return wind, self.class_head(features)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class ConvLSTMCell(nn.Module):
|
| 146 |
+
"""One convolutional LSTM step. Hidden state stays on the image grid."""
|
| 147 |
+
|
| 148 |
+
def __init__(self, in_channels: int, hidden: int) -> None:
|
| 149 |
+
super().__init__()
|
| 150 |
+
self.hidden = hidden
|
| 151 |
+
self.gates = nn.Conv2d(in_channels + hidden, 4 * hidden, kernel_size=3, padding=1)
|
| 152 |
+
|
| 153 |
+
def forward(
|
| 154 |
+
self, inputs: torch.Tensor, state: tuple[torch.Tensor, torch.Tensor]
|
| 155 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 156 |
+
hidden, cell = state
|
| 157 |
+
input_gate, forget_gate, candidate, output_gate = self.gates(
|
| 158 |
+
torch.cat([inputs, hidden], dim=1)
|
| 159 |
+
).chunk(4, dim=1)
|
| 160 |
+
cell = torch.sigmoid(forget_gate) * cell + torch.sigmoid(input_gate) * torch.tanh(
|
| 161 |
+
candidate
|
| 162 |
+
)
|
| 163 |
+
hidden = torch.sigmoid(output_gate) * torch.tanh(cell)
|
| 164 |
+
return hidden, cell
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class ConvLSTMRegressor(nn.Module):
|
| 168 |
+
"""Four-frame ConvLSTM. The tensor is infrared imagery.
|
| 169 |
+
|
| 170 |
+
Best-track wind, R34, and radius of maximum wind are not inputs. The
|
| 171 |
+
training net attaches a size head to ``encode`` only after those labels
|
| 172 |
+
exist. This module does not flip Southern Hemisphere frames.
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
def __init__(
|
| 176 |
+
self,
|
| 177 |
+
in_channels: int = 1,
|
| 178 |
+
hidden: int = 16,
|
| 179 |
+
n_frames: int = 4,
|
| 180 |
+
dropout: float = 0.3,
|
| 181 |
+
) -> None:
|
| 182 |
+
super().__init__()
|
| 183 |
+
if n_frames != 4:
|
| 184 |
+
raise ValueError("ConvLSTM uses 4 frames")
|
| 185 |
+
if hidden < 1:
|
| 186 |
+
raise ValueError("hidden must be at least 1")
|
| 187 |
+
self.n_frames = n_frames
|
| 188 |
+
self.hidden = hidden
|
| 189 |
+
self.feature_dim = hidden
|
| 190 |
+
self.cell = ConvLSTMCell(in_channels, hidden)
|
| 191 |
+
self.pool = nn.AdaptiveAvgPool2d(1)
|
| 192 |
+
self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(hidden, 1))
|
| 193 |
+
|
| 194 |
+
def encode(self, inputs: torch.Tensor) -> torch.Tensor:
|
| 195 |
+
if inputs.ndim != 5:
|
| 196 |
+
raise ValueError(
|
| 197 |
+
"ConvLSTM expects (batch, 4, channels, height, width) infrared frames"
|
| 198 |
+
)
|
| 199 |
+
if int(inputs.shape[1]) != self.n_frames:
|
| 200 |
+
raise ValueError(
|
| 201 |
+
f"ConvLSTM expects {self.n_frames} frames, got {int(inputs.shape[1])}"
|
| 202 |
+
)
|
| 203 |
+
batch, _steps, _channels, height, width = inputs.shape
|
| 204 |
+
hidden = inputs.new_zeros(batch, self.hidden, height, width)
|
| 205 |
+
cell = inputs.new_zeros(batch, self.hidden, height, width)
|
| 206 |
+
for step in range(self.n_frames):
|
| 207 |
+
hidden, cell = self.cell(inputs[:, step], (hidden, cell))
|
| 208 |
+
return self.pool(hidden).flatten(1)
|
| 209 |
+
|
| 210 |
+
def forward(self, inputs: torch.Tensor) -> torch.Tensor:
|
| 211 |
+
return self.head(self.encode(inputs))
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class MCDropout:
|
| 215 |
+
"""Stochastic passes with BatchNorm frozen and Dropout left active.
|
| 216 |
+
|
| 217 |
+
The returned standard deviation is dropout noise. It is not a calibrated
|
| 218 |
+
prediction interval.
|
| 219 |
+
"""
|
| 220 |
+
|
| 221 |
+
@staticmethod
|
| 222 |
+
def enable(module: nn.Module) -> None:
|
| 223 |
+
"""Eval mode for the module, then train mode for Dropout only."""
|
| 224 |
+
module.eval()
|
| 225 |
+
for layer in module.modules():
|
| 226 |
+
if isinstance(layer, nn.Dropout):
|
| 227 |
+
layer.train()
|
| 228 |
+
|
| 229 |
+
@staticmethod
|
| 230 |
+
@torch.no_grad()
|
| 231 |
+
def predict(
|
| 232 |
+
module: nn.Module, inputs: torch.Tensor, n_samples: int
|
| 233 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 234 |
+
"""Mean and std over ``n_samples`` stochastic forwards.
|
| 235 |
+
|
| 236 |
+
``n_samples`` is ``model.mc_samples`` from config. A class-head tuple
|
| 237 |
+
contributes the wind-speed tensor only.
|
| 238 |
+
"""
|
| 239 |
+
if n_samples < 2:
|
| 240 |
+
raise ValueError("n_samples must be at least 2")
|
| 241 |
+
MCDropout.enable(module)
|
| 242 |
+
draws = []
|
| 243 |
+
for _ in range(n_samples):
|
| 244 |
+
output = module(inputs)
|
| 245 |
+
if isinstance(output, tuple):
|
| 246 |
+
output = output[0]
|
| 247 |
+
draws.append(output)
|
| 248 |
+
stacked = torch.stack(draws, dim=0)
|
| 249 |
+
return stacked.mean(dim=0), stacked.std(dim=0, unbiased=True)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def enable_mc_dropout(module: nn.Module) -> None:
|
| 253 |
+
"""Eval mode for BatchNorm, train mode for Dropout."""
|
| 254 |
+
MCDropout.enable(module)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
@torch.no_grad()
|
| 258 |
+
def mc_dropout_predict(
|
| 259 |
+
module: nn.Module, inputs: torch.Tensor, n_samples: int = 20
|
| 260 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 261 |
+
"""Return mean and std. This is not a calibrated prediction interval."""
|
| 262 |
+
return MCDropout.predict(module, inputs, n_samples)
|
bundle/src/model_access.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The only import point for the network and for MC-dropout.
|
| 2 |
+
|
| 3 |
+
``src.model.MCDropout`` is the class from the merged regressor work.
|
| 4 |
+
``src.train.build_net`` wraps that module and ``cloudie.train`` re-exports
|
| 5 |
+
it. This file does not copy either implementation.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ModelAccess:
|
| 12 |
+
"""Lazy imports so a gate check does not load torch."""
|
| 13 |
+
|
| 14 |
+
@staticmethod
|
| 15 |
+
def mc_dropout():
|
| 16 |
+
"""Return ``src.model.MCDropout``."""
|
| 17 |
+
from src.model import MCDropout
|
| 18 |
+
|
| 19 |
+
return MCDropout
|
| 20 |
+
|
| 21 |
+
@staticmethod
|
| 22 |
+
def build_net(config: dict, size_head: bool = False):
|
| 23 |
+
"""Return the training wrapper around the configured regressor."""
|
| 24 |
+
from src.train import build_net
|
| 25 |
+
|
| 26 |
+
return build_net(config, size_head=size_head)
|
bundle/src/nasa_tc.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build a Cloudie manifest from the NASA Tropical Storm Wind Speed dataset.
|
| 2 |
+
|
| 3 |
+
The main path is TorchGeo ``TropicalCyclone`` (Maskey et al. 2020,
|
| 4 |
+
https://doi.org/10.1109/JSTARS.2020.3011907). TorchGeo checks the files and
|
| 5 |
+
reads ``{training,test}_set_{features,labels}.csv``; images sit at
|
| 6 |
+
``<root>/<split>/<Image ID>.jpg``. A one-time download is
|
| 7 |
+
``TropicalCyclone(root, split, download=True)`` from the public Source
|
| 8 |
+
Cooperative blob. The copy tool and the mirror are named in
|
| 9 |
+
``docs/DATA_SOURCES.md``. The Hugging Face repo
|
| 10 |
+
``torchgeo/tropical_cyclone`` is only a mirror. CI never downloads either.
|
| 11 |
+
|
| 12 |
+
Images keep their native size. Nothing in this module resizes. Most frames
|
| 13 |
+
are 366 x 366, but the real train side also has 1093 x 1093 frames (stored
|
| 14 |
+
as grey in an RGB JPEG), which TorchGeo's own ``__getitem__`` bilinearly
|
| 15 |
+
resizes to 366. ``native_height``, ``native_width`` and ``orig_size`` are
|
| 16 |
+
recorded per row. An empirical check (scripted in the PR notes) found that a
|
| 17 |
+
1093 frame covers the same footprint as a 366 frame at about 3x the pixel
|
| 18 |
+
density: its spatial autocorrelation length is about 3.2x longer in pixels,
|
| 19 |
+
and after a 3x area average its texture and cold-cloud fraction match the
|
| 20 |
+
366 frames, while a 366 centre crop does not. ``to_working_grid`` therefore
|
| 21 |
+
area-averages to the 366 working grid, and ``working_resample`` marks which
|
| 22 |
+
rows need it. The manifest itself is never resampled.
|
| 23 |
+
|
| 24 |
+
Colour-enhanced frames (``npf_000``, ``npf_001``) are not grey IR. They are
|
| 25 |
+
dropped from the manifest and listed with a reason in an exclusions CSV next
|
| 26 |
+
to it.
|
| 27 |
+
|
| 28 |
+
The manifest never has a ``split`` column. The official side goes only to
|
| 29 |
+
``source_split``. ``src.splits.assign_storms`` writes ``split`` by storm.
|
| 30 |
+
|
| 31 |
+
Pixel values are an 8-bit rendering of IR brightness, not calibrated Kelvin.
|
| 32 |
+
Call them pixel stats until a calibration table exists.
|
| 33 |
+
|
| 34 |
+
Labels are HURDAT2 best-track maximum sustained winds in knots. HURDAT2 uses
|
| 35 |
+
1-minute sustained winds, so ``wind_averaging`` is ``1min``.
|
| 36 |
+
|
| 37 |
+
There is no distance-to-land join. ``storm_id`` is a 3-letter competition
|
| 38 |
+
identifier and the only time field is ``relative_time_s``, so an IBTrACS
|
| 39 |
+
match would be a guess. ``near_land`` stays unknown. See
|
| 40 |
+
``nasa_tc/audit/README.md``. Do not invent a mapping.
|
| 41 |
+
|
| 42 |
+
The competition's own train/test sides split frames, not storms: many test
|
| 43 |
+
storms also appear in train. ``source_split`` keeps that side for reference
|
| 44 |
+
only. Do not train on one side and score on the other. Use the storm-wise
|
| 45 |
+
splitter in ``src.splits`` on the union instead.
|
| 46 |
+
"""
|
| 47 |
+
|
| 48 |
+
from __future__ import annotations
|
| 49 |
+
|
| 50 |
+
import argparse
|
| 51 |
+
import json
|
| 52 |
+
from collections.abc import Callable
|
| 53 |
+
from pathlib import Path
|
| 54 |
+
|
| 55 |
+
import numpy as np
|
| 56 |
+
import pandas as pd
|
| 57 |
+
|
| 58 |
+
from src.schema import require_valid
|
| 59 |
+
|
| 60 |
+
WIND_AVERAGING = "1min"
|
| 61 |
+
LABEL_SOURCE = "nasa_tropical_storm_competition_hurdat2"
|
| 62 |
+
SPLITS = ("train", "test")
|
| 63 |
+
WORKING_SIZE = 366 # TorchGeo's grid and config data.image_size: native (PR #16)
|
| 64 |
+
# Known non-IR frames in this release. Frames detected as colour are excluded too.
|
| 65 |
+
KNOWN_EXCLUSIONS = {
|
| 66 |
+
"npf_000": "colour-enhanced render, not grey IR",
|
| 67 |
+
"npf_001": "colour-enhanced render, not grey IR",
|
| 68 |
+
}
|
| 69 |
+
EXCLUSION_COLUMNS = ["sample_id", "storm_id", "source_split", "reason"]
|
| 70 |
+
_FILE_STEM = {"train": "training_set", "test": "test_set"}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def torchgeo_tables(root: str | Path, split: str) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 74 |
+
"""Return TorchGeo's features and labels frames for one competition side.
|
| 75 |
+
|
| 76 |
+
Imports TorchGeo lazily so tests and the web app do not need it.
|
| 77 |
+
``download`` stays false: this reader never fetches imagery.
|
| 78 |
+
"""
|
| 79 |
+
import importlib
|
| 80 |
+
|
| 81 |
+
tropical = importlib.import_module("torchgeo.datasets")
|
| 82 |
+
dataset = tropical.TropicalCyclone(root=str(root), split=split, download=False)
|
| 83 |
+
return dataset.features, dataset.labels
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def csv_tables(root: str | Path, split: str) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 87 |
+
"""Read the same CSVs TorchGeo reads, without importing TorchGeo."""
|
| 88 |
+
stem = _FILE_STEM[split]
|
| 89 |
+
root = Path(root)
|
| 90 |
+
return (
|
| 91 |
+
pd.read_csv(root / f"{stem}_features.csv"),
|
| 92 |
+
pd.read_csv(root / f"{stem}_labels.csv"),
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def build_manifest(
|
| 97 |
+
root: str | Path,
|
| 98 |
+
manifest_dir: str | Path,
|
| 99 |
+
splits: tuple[str, ...] = SPLITS,
|
| 100 |
+
tables: Callable[[str | Path, str], tuple[pd.DataFrame, pd.DataFrame]] = torchgeo_tables,
|
| 101 |
+
check_images: bool = True,
|
| 102 |
+
keep_excluded: bool = False,
|
| 103 |
+
) -> pd.DataFrame:
|
| 104 |
+
"""Return a validated manifest. ``image_path`` is relative to ``manifest_dir``."""
|
| 105 |
+
root = Path(root).resolve()
|
| 106 |
+
manifest_dir = Path(manifest_dir).resolve()
|
| 107 |
+
frames = []
|
| 108 |
+
for split in splits:
|
| 109 |
+
if split not in _FILE_STEM:
|
| 110 |
+
raise ValueError(f"unknown split {split}")
|
| 111 |
+
features, labels = tables(root, split)
|
| 112 |
+
merged = features.merge(labels, on="Image ID", how="inner", validate="1:1")
|
| 113 |
+
if len(merged) != len(labels) or len(merged) != len(features):
|
| 114 |
+
raise ValueError(f"{split}: features and labels do not line up")
|
| 115 |
+
image_dir = root / split
|
| 116 |
+
paths = [image_dir / f"{image_id}.jpg" for image_id in merged["Image ID"]]
|
| 117 |
+
frames.append(
|
| 118 |
+
pd.DataFrame(
|
| 119 |
+
{
|
| 120 |
+
"sample_id": merged["Image ID"].astype(str),
|
| 121 |
+
"image_path": [_relative(path, manifest_dir) for path in paths],
|
| 122 |
+
"storm_id": merged["Storm ID"].astype(str),
|
| 123 |
+
"wind_speed_kt": pd.to_numeric(merged["Wind Speed"]),
|
| 124 |
+
"relative_time_s": pd.to_numeric(merged["Relative Time"]),
|
| 125 |
+
"ocean": merged["Ocean"].astype(int),
|
| 126 |
+
"basin": merged["Ocean"].map({1: "ATL", 2: "EPAC"}).fillna("unknown"),
|
| 127 |
+
"sensor": "GOES",
|
| 128 |
+
"channel": "IR",
|
| 129 |
+
"pixel_units": "8bit_uncalibrated",
|
| 130 |
+
"wind_averaging": WIND_AVERAGING,
|
| 131 |
+
"label_source": LABEL_SOURCE,
|
| 132 |
+
"center_source": "dataset_precentered",
|
| 133 |
+
"source_split": split,
|
| 134 |
+
"is_synthetic": False,
|
| 135 |
+
}
|
| 136 |
+
)
|
| 137 |
+
)
|
| 138 |
+
frame = pd.concat(frames, ignore_index=True)
|
| 139 |
+
if check_images:
|
| 140 |
+
frame = add_native_size(frame, manifest_dir)
|
| 141 |
+
if keep_excluded:
|
| 142 |
+
return frame
|
| 143 |
+
frame, _ = split_exclusions(frame)
|
| 144 |
+
return require_valid(frame)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def split_exclusions(frame: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 148 |
+
"""Return (kept, excluded). Excluded rows carry a ``reason``."""
|
| 149 |
+
reasons = frame["sample_id"].map(KNOWN_EXCLUSIONS)
|
| 150 |
+
if "grey_ir" in frame:
|
| 151 |
+
detected = ~frame["grey_ir"].astype(bool) & reasons.isna()
|
| 152 |
+
reasons = reasons.mask(detected, "channels differ, not grey IR")
|
| 153 |
+
drop = reasons.notna()
|
| 154 |
+
excluded = frame.loc[drop, ["sample_id", "storm_id", "source_split"]].assign(reason=reasons[drop])
|
| 155 |
+
return frame.loc[~drop].reset_index(drop=True), excluded.reset_index(drop=True)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def exclusions_for(frame: pd.DataFrame) -> pd.DataFrame:
|
| 159 |
+
"""Exclusions for a raw (pre-filter) frame, in the CSV column order."""
|
| 160 |
+
return split_exclusions(frame)[1][EXCLUSION_COLUMNS]
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _relative(path: Path, base: Path) -> str:
|
| 164 |
+
try:
|
| 165 |
+
return path.relative_to(base).as_posix()
|
| 166 |
+
except ValueError:
|
| 167 |
+
return path.as_posix()
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def add_native_size(frame: pd.DataFrame, manifest_dir: str | Path) -> pd.DataFrame:
|
| 171 |
+
"""Record native size and JPEG mode. Fails if any image is missing."""
|
| 172 |
+
from PIL import Image
|
| 173 |
+
|
| 174 |
+
manifest_dir = Path(manifest_dir)
|
| 175 |
+
heights, widths, modes, grey, missing = [], [], [], [], []
|
| 176 |
+
for image_path in frame["image_path"]:
|
| 177 |
+
path = Path(image_path)
|
| 178 |
+
path = path if path.is_absolute() else manifest_dir / path
|
| 179 |
+
if not path.is_file():
|
| 180 |
+
missing.append(str(path))
|
| 181 |
+
heights.append(-1)
|
| 182 |
+
widths.append(-1)
|
| 183 |
+
modes.append("")
|
| 184 |
+
grey.append(False)
|
| 185 |
+
continue
|
| 186 |
+
with Image.open(path) as image:
|
| 187 |
+
widths.append(image.width)
|
| 188 |
+
heights.append(image.height)
|
| 189 |
+
modes.append(image.mode)
|
| 190 |
+
grey.append(image.mode == "L" or _channels_identical(np.asarray(image)))
|
| 191 |
+
if missing:
|
| 192 |
+
raise FileNotFoundError(f"{len(missing)} images missing, first: {missing[:3]}")
|
| 193 |
+
out = frame.copy()
|
| 194 |
+
out["native_height"] = heights
|
| 195 |
+
out["native_width"] = widths
|
| 196 |
+
out["source_mode"] = modes
|
| 197 |
+
# False for colour-enhanced frames (npf_000/001 in this release). load_ir
|
| 198 |
+
# refuses them, so filter on this column before training.
|
| 199 |
+
out["grey_ir"] = grey
|
| 200 |
+
out["orig_size"] = [h if h == w else -1 for h, w in zip(heights, widths)]
|
| 201 |
+
if (out["orig_size"] < 0).any():
|
| 202 |
+
raise ValueError("non-square frame found; orig_size assumes square chips")
|
| 203 |
+
out["working_resample"] = np.where(out["orig_size"] == WORKING_SIZE, "none", "area_average")
|
| 204 |
+
return out
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def _channels_identical(array: np.ndarray) -> bool:
|
| 208 |
+
if array.ndim != 3:
|
| 209 |
+
return True
|
| 210 |
+
return bool(np.array_equal(array[..., 0], array[..., 1]) and np.array_equal(array[..., 0], array[..., 2]))
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def load_ir(path: str | Path) -> np.ndarray:
|
| 214 |
+
"""Read one frame as float32 at native size, single channel.
|
| 215 |
+
|
| 216 |
+
Three-channel JPEGs are accepted only when all channels match, so a
|
| 217 |
+
colour enhancement is never mistaken for IR.
|
| 218 |
+
"""
|
| 219 |
+
from PIL import Image
|
| 220 |
+
|
| 221 |
+
with Image.open(path) as image:
|
| 222 |
+
array = np.asarray(image)
|
| 223 |
+
if array.ndim == 3:
|
| 224 |
+
if not _channels_identical(array):
|
| 225 |
+
raise ValueError(f"{path}: channels differ, not a grey IR render")
|
| 226 |
+
array = array[..., 0]
|
| 227 |
+
return array.astype(np.float32)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def to_working_grid(array: np.ndarray, size: int = WORKING_SIZE) -> tuple[np.ndarray, bool]:
|
| 231 |
+
"""Area-average a frame onto the ``size`` grid. Returns (array, resampled).
|
| 232 |
+
|
| 233 |
+
Use only for frames that cover the same footprint (the 1093 frames do).
|
| 234 |
+
A frame already at ``size`` is returned unchanged.
|
| 235 |
+
"""
|
| 236 |
+
from PIL import Image
|
| 237 |
+
|
| 238 |
+
if array.shape == (size, size):
|
| 239 |
+
return array.astype(np.float32), False
|
| 240 |
+
if array.ndim != 2 or array.shape[0] != array.shape[1] or array.shape[0] < size:
|
| 241 |
+
raise ValueError(f"expected a square frame of at least {size}px, got {array.shape}")
|
| 242 |
+
image = Image.fromarray(array.astype(np.float32), mode="F")
|
| 243 |
+
return np.asarray(image.resize((size, size), resample=Image.BOX), dtype=np.float32), True
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def summarize(frame: pd.DataFrame) -> dict[str, object]:
|
| 247 |
+
by_side = {
|
| 248 |
+
side: {
|
| 249 |
+
"rows": int((frame["source_split"] == side).sum()),
|
| 250 |
+
"storms": int(frame.loc[frame["source_split"] == side, "storm_id"].nunique()),
|
| 251 |
+
}
|
| 252 |
+
for side in sorted(frame["source_split"].unique())
|
| 253 |
+
}
|
| 254 |
+
sides = [set(frame.loc[frame["source_split"] == side, "storm_id"]) for side in by_side]
|
| 255 |
+
shared = len(set.intersection(*sides)) if len(sides) > 1 else 0
|
| 256 |
+
return {
|
| 257 |
+
"rows": int(len(frame)),
|
| 258 |
+
"unique_storms": int(frame["storm_id"].nunique()),
|
| 259 |
+
"by_source_split": by_side,
|
| 260 |
+
"storms_on_both_source_sides": shared,
|
| 261 |
+
"wind_kt_min": float(frame["wind_speed_kt"].min()),
|
| 262 |
+
"wind_kt_max": float(frame["wind_speed_kt"].max()),
|
| 263 |
+
"wind_kt_mean": round(float(frame["wind_speed_kt"].mean()), 2),
|
| 264 |
+
"native_sizes": sorted(
|
| 265 |
+
{f"{h}x{w}" for h, w in zip(frame["native_height"], frame["native_width"])}
|
| 266 |
+
)
|
| 267 |
+
if "native_height" in frame
|
| 268 |
+
else [],
|
| 269 |
+
"source_modes": frame["source_mode"].value_counts().to_dict()
|
| 270 |
+
if "source_mode" in frame
|
| 271 |
+
else {},
|
| 272 |
+
"frames_not_grey_ir": sorted(frame.loc[~frame["grey_ir"], "sample_id"]) if "grey_ir" in frame else [],
|
| 273 |
+
"native_size_counts": {
|
| 274 |
+
f"{h}x{w}": int(n)
|
| 275 |
+
for (h, w), n in frame.groupby(["native_height", "native_width"]).size().items()
|
| 276 |
+
}
|
| 277 |
+
if "native_height" in frame
|
| 278 |
+
else {},
|
| 279 |
+
"orig_size_counts": {int(k): int(v) for k, v in frame["orig_size"].value_counts().items()}
|
| 280 |
+
if "orig_size" in frame
|
| 281 |
+
else {},
|
| 282 |
+
"frames_to_area_average_to_366": int((frame["working_resample"] == "area_average").sum())
|
| 283 |
+
if "working_resample" in frame
|
| 284 |
+
else 0,
|
| 285 |
+
"has_split_column": "split" in frame.columns,
|
| 286 |
+
"wind_averaging": sorted(frame["wind_averaging"].unique()),
|
| 287 |
+
"is_synthetic": bool(frame["is_synthetic"].any()),
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def save_sample_png(frame: pd.DataFrame, manifest_dir: str | Path, out: str | Path, index: int = 0) -> dict[str, object]:
|
| 292 |
+
import matplotlib
|
| 293 |
+
|
| 294 |
+
matplotlib.use("Agg")
|
| 295 |
+
import matplotlib.pyplot as plt
|
| 296 |
+
|
| 297 |
+
row = frame.iloc[index]
|
| 298 |
+
path = Path(row["image_path"])
|
| 299 |
+
path = path if path.is_absolute() else Path(manifest_dir) / path
|
| 300 |
+
image = load_ir(path)
|
| 301 |
+
fig, ax = plt.subplots(figsize=(4, 4))
|
| 302 |
+
ax.imshow(image, cmap="gray")
|
| 303 |
+
ax.set_title(f"{row['sample_id']} | {row['wind_speed_kt']:.0f} kt (1min) | NASA TC, real")
|
| 304 |
+
ax.axis("off")
|
| 305 |
+
Path(out).parent.mkdir(parents=True, exist_ok=True)
|
| 306 |
+
fig.savefig(out, dpi=100, bbox_inches="tight")
|
| 307 |
+
plt.close(fig)
|
| 308 |
+
return {"sample_id": row["sample_id"], "wind_speed_kt": float(row["wind_speed_kt"]), "shape": list(image.shape), "png": str(out)}
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def storm_split_check(frame: pd.DataFrame, strategy: str = "storm_wise", seed: int = 42) -> dict[str, object]:
|
| 312 |
+
"""Run the project splitter on the combined manifest and assert no storm leaks."""
|
| 313 |
+
from src.splits import assert_no_group_leakage, assign_storms
|
| 314 |
+
|
| 315 |
+
if "split" in frame.columns:
|
| 316 |
+
raise ValueError("manifest must not carry split; use source_split for the official side")
|
| 317 |
+
assigned = assign_storms(frame, strategy, seed=seed)
|
| 318 |
+
parts = [assigned.loc[assigned["split"] == name] for name in ("train", "val", "test")]
|
| 319 |
+
assert_no_group_leakage(*parts)
|
| 320 |
+
return {
|
| 321 |
+
"strategy": strategy,
|
| 322 |
+
"rows": {name: int(len(part)) for name, part in zip(("train", "val", "test"), parts)},
|
| 323 |
+
"storms": {name: int(part["storm_id"].nunique()) for name, part in zip(("train", "val", "test"), parts)},
|
| 324 |
+
"leakage": "none",
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def main() -> None:
|
| 329 |
+
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
| 330 |
+
parser.add_argument("--root", required=True, help="TorchGeo TropicalCyclone root")
|
| 331 |
+
parser.add_argument("--out", default="data/nasa_tc/manifest.csv")
|
| 332 |
+
parser.add_argument("--splits", nargs="+", default=list(SPLITS))
|
| 333 |
+
parser.add_argument("--reader", choices=["torchgeo", "csv"], default="torchgeo")
|
| 334 |
+
parser.add_argument("--summary", default="reports/nasa_tc_summary.json")
|
| 335 |
+
parser.add_argument("--sample-png", default="reports/nasa_tc_sample.png")
|
| 336 |
+
parser.add_argument("--exclusions", default=None, help="default: <manifest dir>/nasa_tc_exclusions.csv")
|
| 337 |
+
args = parser.parse_args()
|
| 338 |
+
|
| 339 |
+
out = Path(args.out)
|
| 340 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 341 |
+
tables = torchgeo_tables if args.reader == "torchgeo" else csv_tables
|
| 342 |
+
raw = build_manifest(args.root, out.parent, tuple(args.splits), tables, keep_excluded=True)
|
| 343 |
+
excluded = exclusions_for(raw)
|
| 344 |
+
frame = require_valid(split_exclusions(raw)[0])
|
| 345 |
+
exclusions_path = Path(args.exclusions) if args.exclusions else out.parent / "nasa_tc_exclusions.csv"
|
| 346 |
+
excluded.to_csv(exclusions_path, index=False)
|
| 347 |
+
frame.drop(columns=["imd5_class"]).to_csv(out, index=False)
|
| 348 |
+
summary = summarize(frame)
|
| 349 |
+
summary["excluded"] = {"count": int(len(excluded)), "sample_ids": excluded["sample_id"].tolist(), "file": str(exclusions_path)}
|
| 350 |
+
summary["storm_split_check"] = storm_split_check(frame)
|
| 351 |
+
summary["reader"] = args.reader
|
| 352 |
+
summary["manifest"] = str(out)
|
| 353 |
+
summary["sample"] = save_sample_png(frame, out.parent, args.sample_png)
|
| 354 |
+
Path(args.summary).parent.mkdir(parents=True, exist_ok=True)
|
| 355 |
+
Path(args.summary).write_text(json.dumps(summary, indent=2))
|
| 356 |
+
print(json.dumps(summary, indent=2))
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
if __name__ == "__main__":
|
| 360 |
+
main()
|
bundle/src/plots.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Comparison figures for classical baselines.
|
| 2 |
+
|
| 3 |
+
Figures are software artifacts. A title that includes a number is not a
|
| 4 |
+
result to quote, and these plots are not warnings.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
from src.schema import DEFAULT_NAMES
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _pyplot():
|
| 17 |
+
import matplotlib
|
| 18 |
+
|
| 19 |
+
matplotlib.use("Agg")
|
| 20 |
+
import matplotlib.pyplot as plt
|
| 21 |
+
|
| 22 |
+
return plt
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def save_confusion_matrix(
|
| 26 |
+
y_true: np.ndarray,
|
| 27 |
+
y_pred: np.ndarray,
|
| 28 |
+
path: str | Path,
|
| 29 |
+
title: str,
|
| 30 |
+
labels: tuple[str, ...] = DEFAULT_NAMES,
|
| 31 |
+
) -> Path:
|
| 32 |
+
"""Write a count matrix. Classes absent from both sides stay in the grid."""
|
| 33 |
+
plt = _pyplot()
|
| 34 |
+
truth = np.asarray(y_true).ravel()
|
| 35 |
+
pred = np.asarray(y_pred).ravel()
|
| 36 |
+
index = {label: position for position, label in enumerate(labels)}
|
| 37 |
+
counts = np.zeros((len(labels), len(labels)), dtype=int)
|
| 38 |
+
for actual, guess in zip(truth, pred, strict=True):
|
| 39 |
+
if actual not in index or guess not in index:
|
| 40 |
+
continue
|
| 41 |
+
counts[index[actual], index[guess]] += 1
|
| 42 |
+
figure, axis = plt.subplots(figsize=(6.2, 5.2))
|
| 43 |
+
image = axis.imshow(counts, cmap="Blues")
|
| 44 |
+
axis.set_xticks(range(len(labels)), labels, rotation=45, ha="right")
|
| 45 |
+
axis.set_yticks(range(len(labels)), labels)
|
| 46 |
+
axis.set_xlabel("Predicted class")
|
| 47 |
+
axis.set_ylabel("Best-track class (noisy label)")
|
| 48 |
+
axis.set_title(title)
|
| 49 |
+
for row in range(counts.shape[0]):
|
| 50 |
+
for col in range(counts.shape[1]):
|
| 51 |
+
axis.text(col, row, str(counts[row, col]), ha="center", va="center", fontsize=8)
|
| 52 |
+
figure.colorbar(image, ax=axis, fraction=0.046)
|
| 53 |
+
figure.tight_layout()
|
| 54 |
+
destination = Path(path)
|
| 55 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 56 |
+
figure.savefig(destination, dpi=100)
|
| 57 |
+
plt.close(figure)
|
| 58 |
+
return destination
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def save_feature_importance(
|
| 62 |
+
importances: dict[str, float],
|
| 63 |
+
path: str | Path,
|
| 64 |
+
title: str,
|
| 65 |
+
limit: int = 15,
|
| 66 |
+
) -> Path | None:
|
| 67 |
+
"""Horizontal bars for a train-only selection score. Empty input writes nothing."""
|
| 68 |
+
if not importances:
|
| 69 |
+
return None
|
| 70 |
+
plt = _pyplot()
|
| 71 |
+
ordered = sorted(importances.items(), key=lambda item: (item[1], item[0]))
|
| 72 |
+
ordered = ordered[-limit:]
|
| 73 |
+
labels = [name for name, _score in ordered]
|
| 74 |
+
scores = [score for _name, score in ordered]
|
| 75 |
+
figure, axis = plt.subplots(figsize=(7.0, 5.0))
|
| 76 |
+
axis.barh(labels, scores, color="#3d5a40")
|
| 77 |
+
axis.set_xlabel("Train-split selection score")
|
| 78 |
+
axis.set_title(title)
|
| 79 |
+
figure.tight_layout()
|
| 80 |
+
destination = Path(path)
|
| 81 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 82 |
+
figure.savefig(destination, dpi=100)
|
| 83 |
+
plt.close(figure)
|
| 84 |
+
return destination
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def save_regression_scatter(
|
| 88 |
+
y_true: np.ndarray,
|
| 89 |
+
y_pred: np.ndarray,
|
| 90 |
+
path: str | Path,
|
| 91 |
+
title: str,
|
| 92 |
+
) -> Path:
|
| 93 |
+
plt = _pyplot()
|
| 94 |
+
truth = np.asarray(y_true, dtype=np.float64).ravel()
|
| 95 |
+
pred = np.asarray(y_pred, dtype=np.float64).ravel()
|
| 96 |
+
figure, axis = plt.subplots(figsize=(5.2, 5.0))
|
| 97 |
+
axis.scatter(truth, pred, s=18, alpha=0.8, color="#1d3557")
|
| 98 |
+
low = float(min(truth.min(), pred.min()))
|
| 99 |
+
high = float(max(truth.max(), pred.max()))
|
| 100 |
+
axis.plot([low, high], [low, high], color="#9b2226", linewidth=1)
|
| 101 |
+
axis.set_xlabel("Label wind (kt)")
|
| 102 |
+
axis.set_ylabel("Predicted wind (kt)")
|
| 103 |
+
axis.set_title(title)
|
| 104 |
+
figure.tight_layout()
|
| 105 |
+
destination = Path(path)
|
| 106 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 107 |
+
figure.savefig(destination, dpi=100)
|
| 108 |
+
plt.close(figure)
|
| 109 |
+
return destination
|
bundle/src/preprocessing.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Image checks, resize, train-only normalization, and train-only augmentation.
|
| 2 |
+
|
| 3 |
+
Southern Hemisphere frames stay as stored. ``leave_unflipped`` records a
|
| 4 |
+
hemisphere label and does not mirror the array.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
from dataclasses import dataclass
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
from PIL import Image
|
| 13 |
+
|
| 14 |
+
from src.config import parse_image_size
|
| 15 |
+
from src.splits import LeakageError
|
| 16 |
+
|
| 17 |
+
# A missing-pixel fraction above this value fails closed. It does not warn.
|
| 18 |
+
MAX_MISSING_FRACTION = 0.30
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass(frozen=True)
|
| 22 |
+
class NormStats:
|
| 23 |
+
mean: float
|
| 24 |
+
std: float
|
| 25 |
+
source_split: str
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# Pixel units stay on the dataset that produced them. NASA chips are 8-bit
|
| 29 |
+
# counts. TCIR IR1 is brightness temperature in kelvin. They are never
|
| 30 |
+
# pooled into one mean and std. A later dataset gets its own entry.
|
| 31 |
+
PIXEL_KIND = {
|
| 32 |
+
"nasa": "uint8",
|
| 33 |
+
"tcir": "brightness_temperature_k",
|
| 34 |
+
"incyde": "jpeg_uncalibrated",
|
| 35 |
+
"smoke": "synthetic",
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def pixel_kind(dataset: str) -> str:
|
| 40 |
+
"""Unit label for one dataset. Unknown datasets stay unspecified."""
|
| 41 |
+
return PIXEL_KIND.get(str(dataset).strip().lower(), "unspecified")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def norm_by_dataset(dataset: str, stats: NormStats) -> dict:
|
| 45 |
+
"""One dataset's train-split stats. The map has that key only."""
|
| 46 |
+
if stats.source_split != "train":
|
| 47 |
+
raise LeakageError("normalization stats may be fit on the train split only")
|
| 48 |
+
name = str(dataset).strip().lower()
|
| 49 |
+
if not name:
|
| 50 |
+
raise ValueError("dataset name is required for normalization stats")
|
| 51 |
+
return {
|
| 52 |
+
name: {
|
| 53 |
+
"mean": float(stats.mean),
|
| 54 |
+
"std": float(stats.std),
|
| 55 |
+
"source_split": "train",
|
| 56 |
+
"pixel_kind": pixel_kind(name),
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def norm_stats_from_checkpoint(payload: dict) -> NormStats:
|
| 62 |
+
"""Stats for the checkpoint's own dataset. Mixed maps are refused.
|
| 63 |
+
|
| 64 |
+
A checkpoint written before per-dataset stats still uses ``norm_mean``
|
| 65 |
+
and ``norm_std``. A map with two datasets, or a key that is not the
|
| 66 |
+
checkpoint dataset, is not applied.
|
| 67 |
+
"""
|
| 68 |
+
grouped = payload.get("norm_by_dataset")
|
| 69 |
+
dataset = payload.get("dataset")
|
| 70 |
+
if isinstance(grouped, dict) and grouped:
|
| 71 |
+
if len(grouped) != 1:
|
| 72 |
+
raise ValueError(
|
| 73 |
+
"checkpoint mixes normalization stats across datasets; refusing to apply them"
|
| 74 |
+
)
|
| 75 |
+
name = None if dataset is None else str(dataset)
|
| 76 |
+
if name not in grouped:
|
| 77 |
+
raise ValueError(
|
| 78 |
+
"checkpoint norm_by_dataset does not match the checkpoint dataset; "
|
| 79 |
+
"refusing to mix normalization stats"
|
| 80 |
+
)
|
| 81 |
+
entry = grouped[name]
|
| 82 |
+
if str(entry.get("source_split")) != "train":
|
| 83 |
+
raise ValueError("checkpoint normalization was not fit on train")
|
| 84 |
+
return NormStats(
|
| 85 |
+
mean=float(entry["mean"]),
|
| 86 |
+
std=float(entry["std"]),
|
| 87 |
+
source_split="train",
|
| 88 |
+
)
|
| 89 |
+
if "norm_mean" not in payload or "norm_std" not in payload:
|
| 90 |
+
raise ValueError("checkpoint is missing normalization stats")
|
| 91 |
+
source = payload.get("norm_source_split")
|
| 92 |
+
if source is not None and str(source) != "train":
|
| 93 |
+
raise ValueError("checkpoint normalization was not fit on train")
|
| 94 |
+
return NormStats(
|
| 95 |
+
mean=float(payload["norm_mean"]),
|
| 96 |
+
std=float(payload["norm_std"]),
|
| 97 |
+
source_split="train",
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def as_channel_first(image: np.ndarray) -> np.ndarray:
|
| 102 |
+
array = np.asarray(image, dtype=np.float32)
|
| 103 |
+
if array.ndim == 2:
|
| 104 |
+
return array[None, ...]
|
| 105 |
+
if array.ndim != 3:
|
| 106 |
+
raise ValueError(f"expected a 2D or 3D image, got {array.shape}")
|
| 107 |
+
if array.shape[0] <= 4 and array.shape[1] > 4 and array.shape[2] > 4:
|
| 108 |
+
return array
|
| 109 |
+
if array.shape[-1] <= 4:
|
| 110 |
+
return np.moveaxis(array, -1, 0)
|
| 111 |
+
raise ValueError(f"cannot infer the channel axis for shape {array.shape}")
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def missing_fraction(image: np.ndarray) -> float:
|
| 115 |
+
return float((~np.isfinite(image)).mean())
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def fit_norm_stats(images: list[np.ndarray], source_split: str) -> NormStats:
|
| 119 |
+
"""Fit mean and std. Refuses anything other than the train split."""
|
| 120 |
+
if source_split != "train":
|
| 121 |
+
raise LeakageError("normalization stats may be fit on the train split only")
|
| 122 |
+
if not images:
|
| 123 |
+
raise ValueError("need at least one train image")
|
| 124 |
+
values = [np.asarray(image, dtype=np.float32) for image in images]
|
| 125 |
+
finite = np.concatenate([image[np.isfinite(image)].ravel() for image in values])
|
| 126 |
+
if finite.size == 0:
|
| 127 |
+
raise ValueError("train images have no finite pixels")
|
| 128 |
+
std = float(finite.std())
|
| 129 |
+
if std < 1e-6:
|
| 130 |
+
std = 1.0
|
| 131 |
+
return NormStats(mean=float(finite.mean()), std=std, source_split=source_split)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def stack_prepared(images: list[np.ndarray]) -> np.ndarray:
|
| 135 |
+
"""Stack chips that have already been prepared.
|
| 136 |
+
|
| 137 |
+
A native ``image_size`` does not resize, so every chip in the stack
|
| 138 |
+
must already share a height and width.
|
| 139 |
+
"""
|
| 140 |
+
if not images:
|
| 141 |
+
raise ValueError("no images to stack")
|
| 142 |
+
try:
|
| 143 |
+
return np.stack(images)
|
| 144 |
+
except ValueError as exc:
|
| 145 |
+
shapes = sorted({tuple(np.shape(image)) for image in images})
|
| 146 |
+
raise ValueError(
|
| 147 |
+
"prepared chips do not share a height and width "
|
| 148 |
+
f"{shapes}. A native image_size does not resize them onto one grid."
|
| 149 |
+
) from exc
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _resize(image: np.ndarray, size: int) -> np.ndarray:
|
| 153 |
+
channels = []
|
| 154 |
+
for channel in image:
|
| 155 |
+
picture = Image.fromarray(channel.astype(np.float32), mode="F")
|
| 156 |
+
picture = picture.resize((size, size), Image.Resampling.BILINEAR)
|
| 157 |
+
channels.append(np.asarray(picture, dtype=np.float32))
|
| 158 |
+
return np.stack(channels, axis=0)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def prepare_image(
|
| 162 |
+
image: np.ndarray,
|
| 163 |
+
image_size: int | str | None,
|
| 164 |
+
stats: NormStats | None,
|
| 165 |
+
max_missing_fraction: float = MAX_MISSING_FRACTION,
|
| 166 |
+
) -> np.ndarray:
|
| 167 |
+
"""Return ``(C, H, W)`` float32. Does not invent brightness temperature.
|
| 168 |
+
|
| 169 |
+
``image_size`` ``None`` or ``native`` keeps the chip's height and width.
|
| 170 |
+
An integer resizes to that square. ``max_missing_fraction`` is
|
| 171 |
+
``data.max_missing_fraction`` when the caller has a config.
|
| 172 |
+
A missing-pixel fraction above ``max_missing_fraction`` raises. Raw
|
| 173 |
+
digital numbers stay pixel values; this function does not name them Tb.
|
| 174 |
+
"""
|
| 175 |
+
array = as_channel_first(image)
|
| 176 |
+
fraction = missing_fraction(array)
|
| 177 |
+
if fraction > max_missing_fraction:
|
| 178 |
+
raise ValueError(
|
| 179 |
+
f"missing fraction {fraction:.2f} exceeds {max_missing_fraction:.2f}"
|
| 180 |
+
)
|
| 181 |
+
filled = array.copy()
|
| 182 |
+
for index in range(filled.shape[0]):
|
| 183 |
+
finite = np.isfinite(filled[index])
|
| 184 |
+
fill = float(np.median(filled[index][finite])) if finite.any() else 0.0
|
| 185 |
+
filled[index][~finite] = fill
|
| 186 |
+
side = parse_image_size(image_size)
|
| 187 |
+
output = filled if side is None else _resize(filled, side)
|
| 188 |
+
if stats is not None:
|
| 189 |
+
output = (output - stats.mean) / stats.std
|
| 190 |
+
return output
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def dn_to_brightness_temperature(dn: np.ndarray, gain: float, offset: float) -> np.ndarray:
|
| 194 |
+
"""Apply a caller-supplied calibration. This does not look up a sensor table."""
|
| 195 |
+
return np.asarray(dn, dtype=np.float32) * float(gain) + float(offset)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def leave_unflipped(image: np.ndarray, hemisphere: str | None = None) -> np.ndarray:
|
| 199 |
+
"""Use the frame as stored.
|
| 200 |
+
|
| 201 |
+
Southern Hemisphere TCIR imagery is not mirrored. ``hemisphere`` records
|
| 202 |
+
the caller's label and does not change the array.
|
| 203 |
+
"""
|
| 204 |
+
del hemisphere
|
| 205 |
+
return np.asarray(image)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def as_grey_plane(image: np.ndarray) -> np.ndarray:
|
| 209 |
+
"""One plane. Identical RGB channels collapse. Differing channels raise.
|
| 210 |
+
|
| 211 |
+
PIL JPEGs are often ``(H, W, C)`` even when every channel is the same
|
| 212 |
+
grey IR value. A leading singleton channel is accepted too.
|
| 213 |
+
"""
|
| 214 |
+
array = np.asarray(image, dtype=np.float32)
|
| 215 |
+
if array.ndim == 2:
|
| 216 |
+
return array
|
| 217 |
+
if array.ndim != 3:
|
| 218 |
+
raise ValueError(f"expected one grey plane, got {array.shape}")
|
| 219 |
+
channel_last = (
|
| 220 |
+
array.shape[-1] <= 4
|
| 221 |
+
and array.shape[0] > array.shape[-1]
|
| 222 |
+
and array.shape[1] > array.shape[-1]
|
| 223 |
+
)
|
| 224 |
+
channel_first = (
|
| 225 |
+
array.shape[0] <= 4
|
| 226 |
+
and array.shape[1] > array.shape[0]
|
| 227 |
+
and array.shape[2] > array.shape[0]
|
| 228 |
+
)
|
| 229 |
+
if channel_last:
|
| 230 |
+
count = int(array.shape[-1])
|
| 231 |
+
if count == 1 or all(np.array_equal(array[..., 0], array[..., index]) for index in range(1, count)):
|
| 232 |
+
return array[..., 0]
|
| 233 |
+
raise ValueError(f"expected grey IR, channels differ, shape {array.shape}")
|
| 234 |
+
if channel_first:
|
| 235 |
+
count = int(array.shape[0])
|
| 236 |
+
if count == 1 or all(np.array_equal(array[0], array[index]) for index in range(1, count)):
|
| 237 |
+
return array[0]
|
| 238 |
+
raise ValueError(f"expected grey IR, channels differ, shape {array.shape}")
|
| 239 |
+
raise ValueError(f"expected grey IR, got {array.shape}")
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def rotate_with_circular_mask(image: np.ndarray, angle_deg: float) -> np.ndarray:
|
| 243 |
+
"""Rotate about the centre and drop pixels outside the inscribed circle.
|
| 244 |
+
|
| 245 |
+
There is no flip. A square rotation otherwise paints the corners from
|
| 246 |
+
empty space, and those bars must not enter training. The disk of
|
| 247 |
+
diameter equal to the short side stays inside the original chip for
|
| 248 |
+
any angle, so the kept pixels are source pixels. Outside the disk the
|
| 249 |
+
values are NaN. Callers that already normalized fill those NaNs with 0.
|
| 250 |
+
Channel-last grey JPEGs are accepted and returned as one plane.
|
| 251 |
+
"""
|
| 252 |
+
plane = as_grey_plane(image)
|
| 253 |
+
finite = np.isfinite(plane)
|
| 254 |
+
filled = plane.copy()
|
| 255 |
+
filled[~finite] = 0.0
|
| 256 |
+
picture = Image.fromarray(filled, mode="F")
|
| 257 |
+
rotated = np.asarray(
|
| 258 |
+
picture.rotate(
|
| 259 |
+
float(angle_deg),
|
| 260 |
+
resample=Image.Resampling.BILINEAR,
|
| 261 |
+
fillcolor=0.0,
|
| 262 |
+
),
|
| 263 |
+
dtype=np.float32,
|
| 264 |
+
)
|
| 265 |
+
height, width = rotated.shape
|
| 266 |
+
yy, xx = np.ogrid[:height, :width]
|
| 267 |
+
center_y = (height - 1) / 2.0
|
| 268 |
+
center_x = (width - 1) / 2.0
|
| 269 |
+
radius = min(height, width) / 2.0
|
| 270 |
+
disk = (yy - center_y) ** 2 + (xx - center_x) ** 2 <= radius**2
|
| 271 |
+
out = rotated.copy()
|
| 272 |
+
out[~disk] = np.nan
|
| 273 |
+
return out
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def prepare_training_chip(
|
| 277 |
+
image: np.ndarray,
|
| 278 |
+
image_size: int | str | None,
|
| 279 |
+
angle: float | None,
|
| 280 |
+
stats: NormStats | None,
|
| 281 |
+
max_missing_fraction: float = MAX_MISSING_FRACTION,
|
| 282 |
+
) -> np.ndarray:
|
| 283 |
+
"""Prepare one training chip, then optionally rotate on that grid.
|
| 284 |
+
|
| 285 |
+
The missing-pixel gate sees the source image, before the circular mask.
|
| 286 |
+
A configured square resize happens first, so the mask is the inscribed
|
| 287 |
+
circle of the training grid (about a fifth of the square) and not the
|
| 288 |
+
corners of a wide native crop. Masked pixels are 0 after normalization,
|
| 289 |
+
which is the training mean, not a black bar.
|
| 290 |
+
"""
|
| 291 |
+
prepared = prepare_image(as_grey_plane(image), image_size, stats, max_missing_fraction)
|
| 292 |
+
if angle is None:
|
| 293 |
+
return prepared
|
| 294 |
+
masked = rotate_with_circular_mask(prepared, float(angle))
|
| 295 |
+
if masked.ndim == 2:
|
| 296 |
+
masked = masked[None, ...]
|
| 297 |
+
return np.where(np.isfinite(masked), masked, np.float32(0.0)).astype(np.float32)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def augment_image(image: np.ndarray, split: str, rng: np.random.Generator) -> np.ndarray:
|
| 301 |
+
"""Flip or rotate a train image. Refuses every other split.
|
| 302 |
+
|
| 303 |
+
Classical features do not call this. A later training loop may, and only
|
| 304 |
+
on rows whose split is ``train``.
|
| 305 |
+
"""
|
| 306 |
+
if split != "train":
|
| 307 |
+
raise LeakageError("augmentation is allowed on the train split only")
|
| 308 |
+
array = as_channel_first(image)
|
| 309 |
+
choice = int(rng.integers(0, 3))
|
| 310 |
+
if choice == 0:
|
| 311 |
+
return np.flip(array, axis=-1).copy()
|
| 312 |
+
if choice == 1:
|
| 313 |
+
return np.rot90(array, k=1, axes=(-2, -1)).copy()
|
| 314 |
+
return array.copy()
|
bundle/src/reproducibility.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Centralized seed helper for reproducible runs.
|
| 2 |
+
|
| 3 |
+
Sets Python, NumPy, and (when available) PyTorch random seeds in one call.
|
| 4 |
+
Training, baselines, and splits should call ``seed_everything`` before any
|
| 5 |
+
stochastic operation. This module does not import torch at module level so
|
| 6 |
+
that CPU-only installs still work.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import random
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def seed_everything(seed: int = 42) -> int:
|
| 18 |
+
"""Set Python, NumPy, and optional PyTorch seeds.
|
| 19 |
+
|
| 20 |
+
Returns the seed so callers can log it.
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
seed : int
|
| 25 |
+
Non-negative integer seed. The same value is forwarded to every
|
| 26 |
+
generator so a single config entry controls all randomness.
|
| 27 |
+
"""
|
| 28 |
+
if not isinstance(seed, int) or isinstance(seed, bool) or seed < 0:
|
| 29 |
+
raise ValueError(f"seed must be a non-negative integer, got {seed!r}")
|
| 30 |
+
|
| 31 |
+
random.seed(seed)
|
| 32 |
+
np.random.seed(seed)
|
| 33 |
+
os.environ["PYTHONHASHSEED"] = str(seed)
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
import torch
|
| 37 |
+
except ImportError:
|
| 38 |
+
pass
|
| 39 |
+
else:
|
| 40 |
+
torch.manual_seed(seed)
|
| 41 |
+
if torch.cuda.is_available():
|
| 42 |
+
torch.cuda.manual_seed_all(seed)
|
| 43 |
+
if hasattr(torch, "xpu") and torch.xpu.is_available():
|
| 44 |
+
torch.xpu.manual_seed(seed)
|
| 45 |
+
|
| 46 |
+
return seed
|
bundle/src/schema.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Manifest schema and row-level quality gates.
|
| 2 |
+
|
| 3 |
+
Required columns are ``sample_id``, ``image_path``, ``storm_id``, and
|
| 4 |
+
``wind_speed_kt``. ``require_valid`` raises ``SchemaError`` on a failed
|
| 5 |
+
gate. It does not warn and continue.
|
| 6 |
+
|
| 7 |
+
``wind_averaging`` must record one period for the whole manifest, such as
|
| 8 |
+
``1-min``, ``3-min``, or ``10-min``. Mixed or blank periods are rejected.
|
| 9 |
+
``is_synthetic`` must be an explicit true or false on every row so a
|
| 10 |
+
synthetic sample cannot be read as real.
|
| 11 |
+
|
| 12 |
+
Image statistics are pixel stats. This schema has no brightness-temperature
|
| 13 |
+
columns. Raw digital numbers are not named ``tb``. Those names are used
|
| 14 |
+
only after a brightness-temperature calibration table exists.
|
| 15 |
+
|
| 16 |
+
The 17/34/48/64/91 kt bins are this project's grouping, not official IMD
|
| 17 |
+
classes, and they are not a warning product. ``imd5_class`` stores that
|
| 18 |
+
project group.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
from dataclasses import dataclass
|
| 24 |
+
|
| 25 |
+
import pandas as pd
|
| 26 |
+
|
| 27 |
+
REQUIRED_COLUMNS = ("sample_id", "image_path", "storm_id", "wind_speed_kt")
|
| 28 |
+
FORBIDDEN_FEATURES = frozenset(
|
| 29 |
+
{"wind_speed_kt", "r34_nmi", "rmw_nmi", "imd5_class", "intensity_bin"}
|
| 30 |
+
)
|
| 31 |
+
# Project metric labels, not an IMD warning. Five names group D+DD and
|
| 32 |
+
# ESCS+SuCS. The edges 17/34/48/64/91 kt are this project's own grouping.
|
| 33 |
+
# IMD operational winds are 3-minute averages and are not these bins.
|
| 34 |
+
# NASA HURDAT2 labels are 1-minute winds; config data.wind_averaging is
|
| 35 |
+
# 1min for that dataset. Keep these tuples equal to data.imd5_edges_kt
|
| 36 |
+
# and data.imd5_names. The July 2024 IMD 3-minute sheet starts Extremely
|
| 37 |
+
# Severe at 90 kt, so 90 kt is VSCS here.
|
| 38 |
+
DEFAULT_EDGES_KT = (17.0, 34.0, 48.0, 64.0, 91.0)
|
| 39 |
+
DEFAULT_NAMES = ("D_DD", "CS", "SCS", "VSCS", "ESCS_SUCS")
|
| 40 |
+
DEFAULT_WIND_MIN_KT = 0.0
|
| 41 |
+
DEFAULT_WIND_MAX_KT = 200.0
|
| 42 |
+
|
| 43 |
+
_TRUE_TEXT = frozenset({"1", "true", "yes", "y", "t"})
|
| 44 |
+
_FALSE_TEXT = frozenset({"0", "false", "no", "n", "f"})
|
| 45 |
+
_MISSING_TEXT = frozenset({"", "nan", "none", "<na>", "nat", "null"})
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class SchemaError(ValueError):
|
| 49 |
+
"""A manifest failed a quality gate."""
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@dataclass(frozen=True)
|
| 53 |
+
class QualityReport:
|
| 54 |
+
n_rows: int
|
| 55 |
+
n_storms: int
|
| 56 |
+
errors: tuple[str, ...]
|
| 57 |
+
|
| 58 |
+
@property
|
| 59 |
+
def ok(self) -> bool:
|
| 60 |
+
return not self.errors
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def wind_to_imd5(
|
| 64 |
+
wind_kt: float,
|
| 65 |
+
edges: tuple[float, ...] = DEFAULT_EDGES_KT,
|
| 66 |
+
names: tuple[str, ...] = DEFAULT_NAMES,
|
| 67 |
+
) -> str | None:
|
| 68 |
+
"""Return this project's intensity group, or None below the lowest edge.
|
| 69 |
+
|
| 70 |
+
The names and edges are this project's grouping. They are not official IMD classes, IMD 3-minute categories, or a warning product.
|
| 71 |
+
"""
|
| 72 |
+
if len(edges) != len(names):
|
| 73 |
+
raise ValueError("edges and names must have the same length")
|
| 74 |
+
if pd.isna(wind_kt) or float(wind_kt) < edges[0]:
|
| 75 |
+
return None
|
| 76 |
+
value = float(wind_kt)
|
| 77 |
+
for lower, upper, name in zip(edges, edges[1:], names):
|
| 78 |
+
if lower <= value < upper:
|
| 79 |
+
return name
|
| 80 |
+
return names[-1]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _unpack_scalar(value: object) -> object:
|
| 84 |
+
"""Return a Python scalar when ``value`` is a numpy scalar."""
|
| 85 |
+
if isinstance(value, (str, bytes, bytearray, bool)):
|
| 86 |
+
return value
|
| 87 |
+
item = getattr(value, "item", None)
|
| 88 |
+
if not callable(item):
|
| 89 |
+
return value
|
| 90 |
+
try:
|
| 91 |
+
unpacked = item()
|
| 92 |
+
except (TypeError, ValueError):
|
| 93 |
+
return value
|
| 94 |
+
if type(unpacked) is type(value):
|
| 95 |
+
return value
|
| 96 |
+
return unpacked
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _is_missing(value: object) -> bool:
|
| 100 |
+
if value is None:
|
| 101 |
+
return True
|
| 102 |
+
try:
|
| 103 |
+
missing = pd.isna(value)
|
| 104 |
+
except (TypeError, ValueError):
|
| 105 |
+
return False
|
| 106 |
+
if missing is True:
|
| 107 |
+
return True
|
| 108 |
+
return False
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _sample_key(value: object) -> str:
|
| 112 |
+
if isinstance(value, bool):
|
| 113 |
+
return "True" if value else "False"
|
| 114 |
+
if _is_missing(value):
|
| 115 |
+
return ""
|
| 116 |
+
if isinstance(value, str):
|
| 117 |
+
return value.strip()
|
| 118 |
+
value = _unpack_scalar(value)
|
| 119 |
+
if isinstance(value, bool):
|
| 120 |
+
return "True" if value else "False"
|
| 121 |
+
if _is_missing(value):
|
| 122 |
+
return ""
|
| 123 |
+
if isinstance(value, str):
|
| 124 |
+
return value.strip()
|
| 125 |
+
if isinstance(value, int) and not isinstance(value, bool):
|
| 126 |
+
return str(value)
|
| 127 |
+
if isinstance(value, float):
|
| 128 |
+
if value != value:
|
| 129 |
+
return ""
|
| 130 |
+
if value.is_integer():
|
| 131 |
+
return str(int(value))
|
| 132 |
+
return str(value).strip()
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def parse_is_synthetic(value: object) -> bool:
|
| 136 |
+
"""Return an explicit synthetic flag. Ambiguous values raise.
|
| 137 |
+
|
| 138 |
+
Null, blank, and unrecognized values are not treated as real data.
|
| 139 |
+
"""
|
| 140 |
+
if isinstance(value, bool):
|
| 141 |
+
return value
|
| 142 |
+
if isinstance(value, str):
|
| 143 |
+
text = value.strip().lower()
|
| 144 |
+
if text in _TRUE_TEXT:
|
| 145 |
+
return True
|
| 146 |
+
if text in _FALSE_TEXT:
|
| 147 |
+
return False
|
| 148 |
+
if text in _MISSING_TEXT:
|
| 149 |
+
raise SchemaError("is_synthetic is null; synthetic rows must be explicit")
|
| 150 |
+
try:
|
| 151 |
+
number = float(text)
|
| 152 |
+
except ValueError:
|
| 153 |
+
raise SchemaError(
|
| 154 |
+
f"is_synthetic value {value!r} is not an explicit true or false"
|
| 155 |
+
) from None
|
| 156 |
+
return parse_is_synthetic(number)
|
| 157 |
+
value = _unpack_scalar(value)
|
| 158 |
+
if isinstance(value, bool):
|
| 159 |
+
return value
|
| 160 |
+
if _is_missing(value):
|
| 161 |
+
raise SchemaError("is_synthetic is null; synthetic rows must be explicit")
|
| 162 |
+
if isinstance(value, str):
|
| 163 |
+
return parse_is_synthetic(value)
|
| 164 |
+
if isinstance(value, int) and not isinstance(value, bool):
|
| 165 |
+
if value in (0, 1):
|
| 166 |
+
return bool(value)
|
| 167 |
+
raise SchemaError(
|
| 168 |
+
f"is_synthetic value {value!r} is not an explicit true or false"
|
| 169 |
+
)
|
| 170 |
+
if isinstance(value, float):
|
| 171 |
+
if value != value or value in (float("inf"), float("-inf")):
|
| 172 |
+
raise SchemaError("is_synthetic is null; synthetic rows must be explicit")
|
| 173 |
+
if value == 1.0:
|
| 174 |
+
return True
|
| 175 |
+
if value == 0.0:
|
| 176 |
+
return False
|
| 177 |
+
raise SchemaError(f"is_synthetic value {value!r} is not an explicit true or false")
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def recorded_wind_averaging(frame: pd.DataFrame) -> str:
|
| 181 |
+
"""Return the single averaging period recorded on this manifest.
|
| 182 |
+
|
| 183 |
+
The column is required. A blank row or two different periods raises.
|
| 184 |
+
"""
|
| 185 |
+
if "wind_averaging" not in frame.columns:
|
| 186 |
+
raise SchemaError(
|
| 187 |
+
"wind_averaging is required; record one period for the manifest "
|
| 188 |
+
"(for example 1-min, 3-min, or 10-min)"
|
| 189 |
+
)
|
| 190 |
+
if len(frame) == 0:
|
| 191 |
+
raise SchemaError(
|
| 192 |
+
"wind_averaging is required; record one period for the manifest"
|
| 193 |
+
)
|
| 194 |
+
periods: list[str] = []
|
| 195 |
+
for value in frame["wind_averaging"].tolist():
|
| 196 |
+
if isinstance(value, str):
|
| 197 |
+
text = value.strip()
|
| 198 |
+
elif _is_missing(value):
|
| 199 |
+
text = ""
|
| 200 |
+
else:
|
| 201 |
+
unpacked = _unpack_scalar(value)
|
| 202 |
+
if _is_missing(unpacked):
|
| 203 |
+
text = ""
|
| 204 |
+
else:
|
| 205 |
+
text = str(unpacked).strip()
|
| 206 |
+
if text.lower() in _MISSING_TEXT:
|
| 207 |
+
raise SchemaError(
|
| 208 |
+
"wind_averaging has nulls; record one period for every row"
|
| 209 |
+
)
|
| 210 |
+
periods.append(text)
|
| 211 |
+
unique = sorted(set(periods))
|
| 212 |
+
if len(unique) != 1:
|
| 213 |
+
raise SchemaError(
|
| 214 |
+
f"mixed wind_averaging periods {unique}; split or convert explicitly"
|
| 215 |
+
)
|
| 216 |
+
return unique[0]
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
# The label's duration in seconds. This is not a wind conversion factor.
|
| 220 |
+
_AVERAGING_SECONDS = {
|
| 221 |
+
"1min": 60,
|
| 222 |
+
"1-min": 60,
|
| 223 |
+
"1minute": 60,
|
| 224 |
+
"1-minute": 60,
|
| 225 |
+
"3min": 180,
|
| 226 |
+
"3-min": 180,
|
| 227 |
+
"3minute": 180,
|
| 228 |
+
"3-minute": 180,
|
| 229 |
+
"10min": 600,
|
| 230 |
+
"10-min": 600,
|
| 231 |
+
"10minute": 600,
|
| 232 |
+
"10-minute": 600,
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def wind_averaging_seconds(period: object) -> int | None:
|
| 237 |
+
"""Seconds for a 1, 3, or 10 minute label. Other labels have no duration.
|
| 238 |
+
|
| 239 |
+
``1min`` is 60, ``3-min`` is 180, and ``10min`` is 600. Synthetic and
|
| 240 |
+
unknown text stay null. This does not rescale a wind speed.
|
| 241 |
+
"""
|
| 242 |
+
if period is None:
|
| 243 |
+
return None
|
| 244 |
+
text = str(period).strip().lower().replace(" ", "").replace("_", "-")
|
| 245 |
+
if not text:
|
| 246 |
+
return None
|
| 247 |
+
return _AVERAGING_SECONDS.get(text)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def split_wind_averaging(frame: pd.DataFrame) -> dict[str, dict[str, list]]:
|
| 251 |
+
"""``wind_averaging`` and ``wind_averaging_s`` for train, val, and test.
|
| 252 |
+
|
| 253 |
+
Each split lists the set of labels on its rows. Seconds follow the
|
| 254 |
+
label. A label with no known duration stores null and is not converted.
|
| 255 |
+
"""
|
| 256 |
+
if "split" not in frame.columns:
|
| 257 |
+
raise SchemaError("split is required to record wind_averaging by split")
|
| 258 |
+
if "wind_averaging" not in frame.columns:
|
| 259 |
+
raise SchemaError("wind_averaging is required")
|
| 260 |
+
report: dict[str, dict[str, list]] = {}
|
| 261 |
+
for name in ("train", "val", "test"):
|
| 262 |
+
rows = frame.loc[frame["split"].astype(str) == name, "wind_averaging"]
|
| 263 |
+
labels = sorted({str(value).strip() for value in rows.tolist() if str(value).strip()})
|
| 264 |
+
report[name] = {
|
| 265 |
+
"wind_averaging": labels,
|
| 266 |
+
"wind_averaging_s": [wind_averaging_seconds(label) for label in labels],
|
| 267 |
+
}
|
| 268 |
+
return report
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _synthetic_flags(frame: pd.DataFrame) -> list[bool]:
|
| 272 |
+
if "is_synthetic" not in frame.columns:
|
| 273 |
+
raise SchemaError(
|
| 274 |
+
"is_synthetic is required so a synthetic row cannot be read as real"
|
| 275 |
+
)
|
| 276 |
+
return [parse_is_synthetic(value) for value in frame["is_synthetic"].tolist()]
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def validate_manifest(
|
| 280 |
+
frame: pd.DataFrame,
|
| 281 |
+
wind_min_kt: float = DEFAULT_WIND_MIN_KT,
|
| 282 |
+
wind_max_kt: float = DEFAULT_WIND_MAX_KT,
|
| 283 |
+
) -> QualityReport:
|
| 284 |
+
"""Collect quality-gate failures. Callers that load data use ``require_valid``."""
|
| 285 |
+
errors: list[str] = []
|
| 286 |
+
missing = [column for column in REQUIRED_COLUMNS if column not in frame.columns]
|
| 287 |
+
if missing:
|
| 288 |
+
return QualityReport(len(frame), 0, (f"missing required columns: {missing}",))
|
| 289 |
+
|
| 290 |
+
keys = frame["sample_id"].map(_sample_key)
|
| 291 |
+
null_id = frame["sample_id"].isna() | keys.eq("") | keys.str.lower().isin(_MISSING_TEXT)
|
| 292 |
+
if bool(null_id.any()):
|
| 293 |
+
errors.append("sample_id has nulls")
|
| 294 |
+
if bool(keys.duplicated().any()):
|
| 295 |
+
examples = keys.loc[keys.duplicated()].head(5).tolist()
|
| 296 |
+
errors.append(f"duplicate sample_id, examples: {examples}")
|
| 297 |
+
blank_storm = frame["storm_id"].astype(str).str.strip().str.len() == 0
|
| 298 |
+
if frame["storm_id"].isna().any() or blank_storm.any():
|
| 299 |
+
errors.append("storm_id has nulls")
|
| 300 |
+
if frame["image_path"].isna().any() or (
|
| 301 |
+
frame["image_path"].astype(str).str.strip().str.len() == 0
|
| 302 |
+
).any():
|
| 303 |
+
errors.append("image_path has nulls")
|
| 304 |
+
|
| 305 |
+
winds = pd.to_numeric(frame["wind_speed_kt"], errors="coerce")
|
| 306 |
+
if winds.isna().any():
|
| 307 |
+
errors.append("wind_speed_kt has non-numeric values")
|
| 308 |
+
else:
|
| 309 |
+
bad = (winds < wind_min_kt) | (winds > wind_max_kt)
|
| 310 |
+
if bad.any():
|
| 311 |
+
errors.append(
|
| 312 |
+
f"{int(bad.sum())} wind values outside [{wind_min_kt}, {wind_max_kt}] kt"
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
try:
|
| 316 |
+
recorded_wind_averaging(frame)
|
| 317 |
+
except SchemaError as exc:
|
| 318 |
+
errors.append(str(exc))
|
| 319 |
+
try:
|
| 320 |
+
_synthetic_flags(frame)
|
| 321 |
+
except SchemaError as exc:
|
| 322 |
+
errors.append(str(exc))
|
| 323 |
+
|
| 324 |
+
n_storms = int(frame["storm_id"].nunique(dropna=True))
|
| 325 |
+
return QualityReport(len(frame), n_storms, tuple(errors))
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def require_valid(frame: pd.DataFrame, **kwargs: float) -> pd.DataFrame:
|
| 329 |
+
"""Return a copy that passed every manifest gate. Raises on failure."""
|
| 330 |
+
report = validate_manifest(frame, **kwargs)
|
| 331 |
+
if not report.ok:
|
| 332 |
+
raise SchemaError("; ".join(report.errors))
|
| 333 |
+
out = frame.copy()
|
| 334 |
+
out["storm_id"] = out["storm_id"].astype(str).str.strip()
|
| 335 |
+
out["sample_id"] = out["sample_id"].map(_sample_key).astype(str)
|
| 336 |
+
out["image_path"] = out["image_path"].astype(str).str.strip()
|
| 337 |
+
out["wind_speed_kt"] = pd.to_numeric(out["wind_speed_kt"])
|
| 338 |
+
out["wind_averaging"] = recorded_wind_averaging(out)
|
| 339 |
+
out["is_synthetic"] = _synthetic_flags(out)
|
| 340 |
+
# Project grouping stored on imd5_class. Not an official IMD class code.
|
| 341 |
+
out["imd5_class"] = out["wind_speed_kt"].map(wind_to_imd5)
|
| 342 |
+
return out
|
bundle/src/sequences.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Four-frame windows inside one split.
|
| 2 |
+
|
| 3 |
+
The image tensor is infrared only. Wind, R34, and radius of maximum wind
|
| 4 |
+
may be read as targets for the last frame. They are not channels.
|
| 5 |
+
A previous-frame link that leaves the split cannot bring that frame in.
|
| 6 |
+
Southern Hemisphere frames are not flipped.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pandas as pd
|
| 15 |
+
|
| 16 |
+
from src.data_loader import load_image, resolve_image
|
| 17 |
+
from src.preprocessing import NormStats, leave_unflipped, prepare_image, stack_prepared
|
| 18 |
+
|
| 19 |
+
N_FRAMES = 4
|
| 20 |
+
SIZE_LABELS = ("r34_nmi", "rmw_nmi")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def size_targets_present(frame: pd.DataFrame) -> bool:
|
| 24 |
+
"""True when both size columns exist and one row has a finite pair.
|
| 25 |
+
|
| 26 |
+
All-null columns are not labels. The size head stays off until then.
|
| 27 |
+
"""
|
| 28 |
+
if any(column not in frame.columns for column in SIZE_LABELS):
|
| 29 |
+
return False
|
| 30 |
+
values = frame.loc[:, list(SIZE_LABELS)].apply(pd.to_numeric, errors="coerce")
|
| 31 |
+
finite_pair = np.isfinite(values.to_numpy(dtype=np.float64)).all(axis=1)
|
| 32 |
+
return bool(finite_pair.any())
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _prev_id(value: object) -> str | None:
|
| 36 |
+
if value is None:
|
| 37 |
+
return None
|
| 38 |
+
try:
|
| 39 |
+
if pd.isna(value):
|
| 40 |
+
return None
|
| 41 |
+
except (TypeError, ValueError):
|
| 42 |
+
return None
|
| 43 |
+
text = str(value).strip()
|
| 44 |
+
if text == "" or text.lower() in {"nan", "none", "<na>", "nat"}:
|
| 45 |
+
return None
|
| 46 |
+
return text
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _window_stays_in_split(
|
| 50 |
+
sample_ids: list[str], prev_ids: list[str | None], in_split: set[str]
|
| 51 |
+
) -> bool:
|
| 52 |
+
"""Reject a window whose previous-frame link leaves the split.
|
| 53 |
+
|
| 54 |
+
A link that was cleared is ignored. A link that is still set must name
|
| 55 |
+
the previous frame in this window, except at the first frame, where a
|
| 56 |
+
same-split predecessor may sit just outside a sliding window.
|
| 57 |
+
"""
|
| 58 |
+
for offset, _sample_id in enumerate(sample_ids):
|
| 59 |
+
prev = prev_ids[offset]
|
| 60 |
+
if prev is None:
|
| 61 |
+
continue
|
| 62 |
+
if prev not in in_split:
|
| 63 |
+
return False
|
| 64 |
+
if offset > 0 and prev != sample_ids[offset - 1]:
|
| 65 |
+
return False
|
| 66 |
+
return True
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def frame_windows(
|
| 70 |
+
frame: pd.DataFrame, split: str, n_frames: int = N_FRAMES
|
| 71 |
+
) -> list[list[str]]:
|
| 72 |
+
"""Sample ids of consecutive frames, one storm, one split.
|
| 73 |
+
|
| 74 |
+
``n_frames`` is 4. A link that points outside this split rejects the
|
| 75 |
+
window. A link that was cleared stays cleared and is not followed.
|
| 76 |
+
"""
|
| 77 |
+
if n_frames != N_FRAMES:
|
| 78 |
+
raise ValueError(f"ConvLSTM uses {N_FRAMES} frames")
|
| 79 |
+
if "split" not in frame.columns:
|
| 80 |
+
raise ValueError("frame is missing split")
|
| 81 |
+
rows = frame[frame["split"] == split]
|
| 82 |
+
if rows.empty:
|
| 83 |
+
return []
|
| 84 |
+
order = ["timestamp", "sample_id"] if "timestamp" in rows.columns else ["sample_id"]
|
| 85 |
+
in_split = set(rows["sample_id"].astype(str))
|
| 86 |
+
windows: list[list[str]] = []
|
| 87 |
+
for _storm_id, group in rows.groupby("storm_id", sort=False):
|
| 88 |
+
ordered = group.sort_values(order, kind="mergesort")
|
| 89 |
+
sample_ids = [str(value) for value in ordered["sample_id"].tolist()]
|
| 90 |
+
if "prev_sample_id" in ordered.columns:
|
| 91 |
+
prev_ids = [_prev_id(value) for value in ordered["prev_sample_id"].tolist()]
|
| 92 |
+
else:
|
| 93 |
+
prev_ids = [None] * len(sample_ids)
|
| 94 |
+
for start in range(0, len(sample_ids) - n_frames + 1):
|
| 95 |
+
chosen = sample_ids[start : start + n_frames]
|
| 96 |
+
prev = prev_ids[start : start + n_frames]
|
| 97 |
+
if _window_stays_in_split(chosen, prev, in_split):
|
| 98 |
+
windows.append(chosen)
|
| 99 |
+
return windows
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _row(indexed: pd.DataFrame, sample_id: str) -> pd.Series:
|
| 103 |
+
row = indexed.loc[sample_id]
|
| 104 |
+
if isinstance(row, pd.DataFrame):
|
| 105 |
+
return row.iloc[0]
|
| 106 |
+
return row
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _pair(row: pd.Series, column: str) -> float:
|
| 110 |
+
number = pd.to_numeric(pd.Series([row[column]]), errors="coerce").iloc[0]
|
| 111 |
+
if pd.isna(number):
|
| 112 |
+
return float("nan")
|
| 113 |
+
return float(number)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def stack_windows(
|
| 117 |
+
frame: pd.DataFrame,
|
| 118 |
+
manifest_path: str | Path,
|
| 119 |
+
split_name: str,
|
| 120 |
+
image_size: int | str | None,
|
| 121 |
+
stats: NormStats | None,
|
| 122 |
+
max_missing_fraction: float,
|
| 123 |
+
n_frames: int = N_FRAMES,
|
| 124 |
+
wind_column: str = "wind_speed_kt",
|
| 125 |
+
) -> tuple[np.ndarray, np.ndarray, list[str | None], np.ndarray | None]:
|
| 126 |
+
"""Return ``(N, 4, C, H, W)`` images and last-frame targets.
|
| 127 |
+
|
| 128 |
+
Size targets are returned only when :func:`size_targets_present` is true.
|
| 129 |
+
"""
|
| 130 |
+
windows = frame_windows(frame, split_name, n_frames)
|
| 131 |
+
if not windows:
|
| 132 |
+
raise ValueError(f"split {split_name} has no {n_frames}-frame windows")
|
| 133 |
+
indexed = frame.set_index(frame["sample_id"].astype(str), drop=False)
|
| 134 |
+
use_size = size_targets_present(frame)
|
| 135 |
+
images: list[np.ndarray] = []
|
| 136 |
+
winds: list[float] = []
|
| 137 |
+
labels: list[str | None] = []
|
| 138 |
+
sizes: list[list[float]] = []
|
| 139 |
+
for sample_ids in windows:
|
| 140 |
+
frames: list[np.ndarray] = []
|
| 141 |
+
for sample_id in sample_ids:
|
| 142 |
+
row = _row(indexed, sample_id)
|
| 143 |
+
array = load_image(resolve_image(manifest_path, str(row["image_path"])))
|
| 144 |
+
hemisphere = None
|
| 145 |
+
if "hemisphere" in frame.columns and not pd.isna(row["hemisphere"]):
|
| 146 |
+
hemisphere = str(row["hemisphere"])
|
| 147 |
+
frames.append(
|
| 148 |
+
prepare_image(
|
| 149 |
+
leave_unflipped(array, hemisphere),
|
| 150 |
+
image_size,
|
| 151 |
+
stats,
|
| 152 |
+
max_missing_fraction,
|
| 153 |
+
)
|
| 154 |
+
)
|
| 155 |
+
images.append(stack_prepared(frames))
|
| 156 |
+
last = _row(indexed, sample_ids[-1])
|
| 157 |
+
target_col = wind_column if wind_column in last and not pd.isna(last[wind_column]) else "wind_speed_kt"
|
| 158 |
+
winds.append(float(last[target_col]))
|
| 159 |
+
if "_class" in frame.columns and not pd.isna(last["_class"]):
|
| 160 |
+
labels.append(str(last["_class"]))
|
| 161 |
+
else:
|
| 162 |
+
labels.append(None)
|
| 163 |
+
if use_size:
|
| 164 |
+
sizes.append([_pair(last, "r34_nmi"), _pair(last, "rmw_nmi")])
|
| 165 |
+
size_array = np.asarray(sizes, dtype=np.float32) if use_size else None
|
| 166 |
+
return (
|
| 167 |
+
stack_prepared(images),
|
| 168 |
+
np.asarray(winds, dtype=np.float32),
|
| 169 |
+
labels,
|
| 170 |
+
size_array,
|
| 171 |
+
)
|
bundle/src/splits.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Storm-safe splits. Random frame splits are rejected.
|
| 2 |
+
|
| 3 |
+
``storm_ids_by_split`` returns the disjoint train, val, and test storm ids.
|
| 4 |
+
A later residual-quantile coverage check can reuse that map from an assigned
|
| 5 |
+
frame without assigning rows again.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import re
|
| 11 |
+
from collections.abc import Iterable
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pandas as pd
|
| 15 |
+
|
| 16 |
+
from src.schema import DEFAULT_NAMES, FORBIDDEN_FEATURES, wind_to_imd5
|
| 17 |
+
|
| 18 |
+
_CLASS_SEQUENCES = tuple(
|
| 19 |
+
tuple(part for part in re.split(r"[^a-z0-9]+", name.lower()) if part)
|
| 20 |
+
for name in DEFAULT_NAMES
|
| 21 |
+
)
|
| 22 |
+
_COMPACT_MARKERS = ("windspeed", "windkt", "r34", "rmw", "imd5", "intensity")
|
| 23 |
+
_LABEL_TOKENS = frozenset(
|
| 24 |
+
{"wind", "windspeed", "windkt", "r34", "rmw", "imd5", "intensity", "class"}
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class LeakageError(RuntimeError):
|
| 29 |
+
"""A split shares a storm across sides, or is a random frame split."""
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _name_tokens(name: str) -> list[str]:
|
| 33 |
+
return [part for part in re.split(r"[^a-z0-9]+", str(name).lower()) if part]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _contains_sequence(tokens: list[str], sequence: tuple[str, ...]) -> bool:
|
| 37 |
+
width = len(sequence)
|
| 38 |
+
if width == 0 or len(tokens) < width:
|
| 39 |
+
return False
|
| 40 |
+
return any(
|
| 41 |
+
tuple(tokens[index : index + width]) == sequence
|
| 42 |
+
for index in range(len(tokens) - width + 1)
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def is_forbidden_input(name: str) -> bool:
|
| 47 |
+
"""True for a label column or a name derived from wind, size, or class.
|
| 48 |
+
|
| 49 |
+
Image features such as ``pixel_mean`` and ``delta_pixel_mean`` stay allowed.
|
| 50 |
+
"""
|
| 51 |
+
text = str(name).strip().lower()
|
| 52 |
+
if text in {item.lower() for item in FORBIDDEN_FEATURES}:
|
| 53 |
+
return True
|
| 54 |
+
if text in {item.lower() for item in DEFAULT_NAMES}:
|
| 55 |
+
return True
|
| 56 |
+
tokens = _name_tokens(text)
|
| 57 |
+
if any(
|
| 58 |
+
token in _LABEL_TOKENS or token.startswith(("windspeed", "windkt", "r34", "rmw", "imd5"))
|
| 59 |
+
for token in tokens
|
| 60 |
+
):
|
| 61 |
+
return True
|
| 62 |
+
if any(_contains_sequence(tokens, sequence) for sequence in _CLASS_SEQUENCES):
|
| 63 |
+
return True
|
| 64 |
+
compact = "".join(tokens)
|
| 65 |
+
return any(marker in compact for marker in _COMPACT_MARKERS)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def forbidden_input_names(names: Iterable[str]) -> list[str]:
|
| 69 |
+
return sorted({str(name) for name in names if is_forbidden_input(str(name))})
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def assert_no_forbidden_inputs(names: Iterable[str], detail: str) -> None:
|
| 73 |
+
banned = forbidden_input_names(names)
|
| 74 |
+
if banned:
|
| 75 |
+
raise LeakageError(f"{detail}: {banned}")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def assert_no_group_leakage(*frames: pd.DataFrame, group_col: str = "storm_id") -> None:
|
| 79 |
+
seen: dict[str, int] = {}
|
| 80 |
+
for index, frame in enumerate(frames):
|
| 81 |
+
if frame.empty:
|
| 82 |
+
continue
|
| 83 |
+
for storm_id in frame[group_col].astype(str).unique():
|
| 84 |
+
if storm_id in seen:
|
| 85 |
+
raise LeakageError(
|
| 86 |
+
f"{group_col}={storm_id} is in split index {seen[storm_id]} and {index}"
|
| 87 |
+
)
|
| 88 |
+
seen[storm_id] = index
|
| 89 |
+
sample_ids: list[str] = []
|
| 90 |
+
for frame in frames:
|
| 91 |
+
if "sample_id" in frame.columns:
|
| 92 |
+
sample_ids.extend(frame["sample_id"].astype(str).tolist())
|
| 93 |
+
if len(sample_ids) != len(set(sample_ids)):
|
| 94 |
+
raise LeakageError("sample_id repeated across splits")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def storm_ids_by_split(frame: pd.DataFrame) -> dict[str, frozenset[str]]:
|
| 98 |
+
"""Return disjoint storm ids for ``train``, ``val``, and ``test``.
|
| 99 |
+
|
| 100 |
+
A later residual-quantile coverage check can take ``result["test"]``
|
| 101 |
+
from an assigned frame and score those storms without assigning rows again.
|
| 102 |
+
"""
|
| 103 |
+
if "storm_id" not in frame.columns or "split" not in frame.columns:
|
| 104 |
+
raise LeakageError("storm_id and split are required")
|
| 105 |
+
known = ("train", "val", "test")
|
| 106 |
+
labels = set(frame["split"].astype(str).unique())
|
| 107 |
+
unknown = labels - set(known)
|
| 108 |
+
if unknown:
|
| 109 |
+
raise LeakageError(f"unknown splits: {sorted(unknown)}")
|
| 110 |
+
parts = [frame.loc[frame["split"].astype(str) == name] for name in known]
|
| 111 |
+
assert_no_group_leakage(*parts)
|
| 112 |
+
return {
|
| 113 |
+
name: frozenset(part["storm_id"].astype(str))
|
| 114 |
+
for name, part in zip(known, parts, strict=True)
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _storm_table(frame: pd.DataFrame) -> pd.DataFrame:
|
| 119 |
+
rows: list[dict[str, object]] = []
|
| 120 |
+
for storm_id, group in frame.groupby("storm_id", sort=False):
|
| 121 |
+
if "year" in group.columns:
|
| 122 |
+
years = pd.to_numeric(group["year"], errors="coerce").dropna().astype(int)
|
| 123 |
+
else:
|
| 124 |
+
years = pd.Series(dtype=int)
|
| 125 |
+
basins = (
|
| 126 |
+
sorted(set(group["basin"].dropna().astype(str)))
|
| 127 |
+
if "basin" in group.columns
|
| 128 |
+
else []
|
| 129 |
+
)
|
| 130 |
+
median_wind = float(pd.to_numeric(group["wind_speed_kt"]).median())
|
| 131 |
+
rows.append(
|
| 132 |
+
{
|
| 133 |
+
"storm_id": str(storm_id),
|
| 134 |
+
"year_min": int(years.min()) if len(years) else pd.NA,
|
| 135 |
+
"year_max": int(years.max()) if len(years) else pd.NA,
|
| 136 |
+
"basins": basins,
|
| 137 |
+
"stratify": wind_to_imd5(median_wind) or "below",
|
| 138 |
+
}
|
| 139 |
+
)
|
| 140 |
+
return pd.DataFrame(rows)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _counts(n: int, test_fraction: float, val_fraction: float) -> tuple[int, int]:
|
| 144 |
+
if n < 3:
|
| 145 |
+
raise LeakageError("need at least 3 storms for train/val/test")
|
| 146 |
+
n_test = max(1, int(round(n * test_fraction)))
|
| 147 |
+
n_val = max(1, int(round((n - n_test) * val_fraction)))
|
| 148 |
+
if n - n_test - n_val < 1:
|
| 149 |
+
raise LeakageError("split fractions left no training storms")
|
| 150 |
+
return n_test, n_val
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _ordered_storms(table: pd.DataFrame, seed: int) -> list[str]:
|
| 154 |
+
"""Interleave intensity bins so a slice is approximately stratified."""
|
| 155 |
+
rng = np.random.default_rng(seed)
|
| 156 |
+
groups = [
|
| 157 |
+
list(rng.permutation(ids.to_numpy()))
|
| 158 |
+
for _, ids in table.groupby("stratify")["storm_id"]
|
| 159 |
+
]
|
| 160 |
+
ordered: list[str] = []
|
| 161 |
+
while any(groups):
|
| 162 |
+
for group in groups:
|
| 163 |
+
if group:
|
| 164 |
+
ordered.append(str(group.pop()))
|
| 165 |
+
return ordered
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _assignment_from_ids(
|
| 169 |
+
table: pd.DataFrame, test_ids: set[str], val_ids: set[str]
|
| 170 |
+
) -> dict[str, str]:
|
| 171 |
+
return {
|
| 172 |
+
sid: ("test" if sid in test_ids else "val" if sid in val_ids else "train")
|
| 173 |
+
for sid in table["storm_id"].astype(str)
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def assign_storms(
|
| 178 |
+
frame: pd.DataFrame,
|
| 179 |
+
strategy: str,
|
| 180 |
+
test_fraction: float = 0.2,
|
| 181 |
+
val_fraction: float = 0.2,
|
| 182 |
+
seed: int = 42,
|
| 183 |
+
holdout_years: list[int] | None = None,
|
| 184 |
+
holdout_basin: str | None = None,
|
| 185 |
+
) -> pd.DataFrame:
|
| 186 |
+
"""Return a copy with ``split`` in {train, val, test}. Storms are never cut."""
|
| 187 |
+
strategy = strategy.lower().strip()
|
| 188 |
+
if strategy in {"random", "frame", "shuffle", "random_frame"}:
|
| 189 |
+
raise LeakageError(
|
| 190 |
+
"random frame splits are forbidden; use storm_wise, chronological, or holdout_basin"
|
| 191 |
+
)
|
| 192 |
+
work = frame.copy()
|
| 193 |
+
work["storm_id"] = work["storm_id"].astype(str)
|
| 194 |
+
table = _storm_table(work)
|
| 195 |
+
holdout_years = list(holdout_years or [])
|
| 196 |
+
if strategy == "chronological":
|
| 197 |
+
if table["year_min"].isna().any():
|
| 198 |
+
missing = table.loc[table["year_min"].isna(), "storm_id"].tolist()
|
| 199 |
+
raise LeakageError(f"chronological split needs a year for every storm: {missing}")
|
| 200 |
+
if not holdout_years:
|
| 201 |
+
years = sorted(int(year) for year in table["year_min"].astype(int).unique())
|
| 202 |
+
n_hold = max(1, int(round(len(years) * test_fraction)))
|
| 203 |
+
holdout_years = years[-n_hold:]
|
| 204 |
+
held = {int(year) for year in holdout_years}
|
| 205 |
+
|
| 206 |
+
def touches_year(row: pd.Series) -> bool:
|
| 207 |
+
span = set(range(int(row.year_min), int(row.year_max) + 1))
|
| 208 |
+
return bool(span & held)
|
| 209 |
+
|
| 210 |
+
test_ids = set(table.loc[table.apply(touches_year, axis=1), "storm_id"].astype(str))
|
| 211 |
+
pool = table[~table["storm_id"].isin(test_ids)]
|
| 212 |
+
if pool.empty or not test_ids:
|
| 213 |
+
raise LeakageError("chronological split produced an empty side")
|
| 214 |
+
n_val = max(1, int(round(len(pool) * val_fraction)))
|
| 215 |
+
if n_val >= len(pool):
|
| 216 |
+
raise LeakageError("not enough non-holdout storms for train and val")
|
| 217 |
+
val_ids = set(_ordered_storms(pool, seed)[:n_val])
|
| 218 |
+
assignment = _assignment_from_ids(table, test_ids, val_ids)
|
| 219 |
+
elif strategy == "holdout_basin":
|
| 220 |
+
if not holdout_basin:
|
| 221 |
+
raise LeakageError("holdout_basin strategy requires holdout_basin")
|
| 222 |
+
test_ids = set(
|
| 223 |
+
table.loc[
|
| 224 |
+
table["basins"].map(lambda basins: holdout_basin in basins), "storm_id"
|
| 225 |
+
].astype(str)
|
| 226 |
+
)
|
| 227 |
+
pool = table[~table["storm_id"].isin(test_ids)]
|
| 228 |
+
if pool.empty or not test_ids:
|
| 229 |
+
raise LeakageError("holdout basin split produced an empty side")
|
| 230 |
+
n_val = max(1, int(round(len(pool) * val_fraction)))
|
| 231 |
+
if n_val >= len(pool):
|
| 232 |
+
raise LeakageError("not enough storms outside the holdout basin for train and val")
|
| 233 |
+
val_ids = set(_ordered_storms(pool, seed)[:n_val])
|
| 234 |
+
assignment = _assignment_from_ids(table, test_ids, val_ids)
|
| 235 |
+
elif strategy == "storm_wise":
|
| 236 |
+
ordered = _ordered_storms(table, seed)
|
| 237 |
+
n_test, n_val = _counts(len(ordered), test_fraction, val_fraction)
|
| 238 |
+
assignment = _assignment_from_ids(
|
| 239 |
+
table, set(ordered[:n_test]), set(ordered[n_test : n_test + n_val])
|
| 240 |
+
)
|
| 241 |
+
else:
|
| 242 |
+
raise LeakageError(f"unknown split strategy: {strategy}")
|
| 243 |
+
work["split"] = work["storm_id"].map(assignment)
|
| 244 |
+
if work["split"].isna().any():
|
| 245 |
+
raise LeakageError("some rows were not assigned a split")
|
| 246 |
+
parts = [work[work["split"] == name] for name in ("train", "val", "test")]
|
| 247 |
+
assert_no_group_leakage(*parts)
|
| 248 |
+
return work
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def observation_order(frame: pd.DataFrame) -> pd.Series:
|
| 252 |
+
"""Within-storm clock. Timestamp, else NASA ``relative_time_s``, else row order.
|
| 253 |
+
|
| 254 |
+
A missing value in the chosen clock falls back to row order so a partial
|
| 255 |
+
column cannot reorder the other rows. This is not a split.
|
| 256 |
+
"""
|
| 257 |
+
if "timestamp" in frame.columns:
|
| 258 |
+
parsed = pd.to_datetime(frame["timestamp"], errors="coerce", utc=True)
|
| 259 |
+
if not bool(parsed.isna().any()):
|
| 260 |
+
return pd.Series(parsed.to_numpy(), index=frame.index)
|
| 261 |
+
return frame["timestamp"].astype(str)
|
| 262 |
+
if "relative_time_s" in frame.columns:
|
| 263 |
+
values = pd.to_numeric(frame["relative_time_s"], errors="coerce")
|
| 264 |
+
if not bool(values.isna().any()):
|
| 265 |
+
return values
|
| 266 |
+
return pd.Series(np.arange(len(frame)), index=frame.index)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def add_previous_frame_id(frame: pd.DataFrame) -> pd.DataFrame:
|
| 270 |
+
"""Attach the previous sample inside the same storm, ordered by time.
|
| 271 |
+
|
| 272 |
+
The link is not yet split-safe. Call ``null_cross_split_links`` before
|
| 273 |
+
using it as a feature. NASA frames use ``relative_time_s`` when they
|
| 274 |
+
have no ``timestamp``.
|
| 275 |
+
"""
|
| 276 |
+
if "storm_id" not in frame.columns or "sample_id" not in frame.columns:
|
| 277 |
+
raise LeakageError("storm_id and sample_id are required")
|
| 278 |
+
out = frame.copy()
|
| 279 |
+
out["storm_id"] = out["storm_id"].astype(str)
|
| 280 |
+
out["sample_id"] = out["sample_id"].astype(str)
|
| 281 |
+
out = out.assign(_order=observation_order(out))
|
| 282 |
+
out = out.sort_values(["storm_id", "_order"], kind="mergesort")
|
| 283 |
+
out["prev_sample_id"] = out.groupby("storm_id", sort=False)["sample_id"].shift(1)
|
| 284 |
+
out = out.drop(columns=["_order"], errors="ignore")
|
| 285 |
+
return out.sort_index()
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def _sample_split_lookup(frame: pd.DataFrame) -> pd.Series:
|
| 289 |
+
"""Map sample id strings to the split of the first row with that id."""
|
| 290 |
+
temporary = frame.assign(_sid=frame["sample_id"].map(str))
|
| 291 |
+
temporary = temporary.drop_duplicates("_sid")
|
| 292 |
+
return temporary.set_index("_sid")["split"].astype(str)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
def null_cross_split_links(frame: pd.DataFrame) -> tuple[pd.DataFrame, int]:
|
| 296 |
+
"""Drop previous-frame ids that point outside the row's split.
|
| 297 |
+
|
| 298 |
+
Returns the frame and the number of links removed. Unknown previous ids
|
| 299 |
+
are removed as well; they can hide a filtered-out frame.
|
| 300 |
+
"""
|
| 301 |
+
if "split" not in frame.columns or "prev_sample_id" not in frame.columns:
|
| 302 |
+
raise LeakageError("split and prev_sample_id are required")
|
| 303 |
+
lookup = _sample_split_lookup(frame)
|
| 304 |
+
out = frame.copy()
|
| 305 |
+
dropped = 0
|
| 306 |
+
kept: list[object] = []
|
| 307 |
+
for prev, split in zip(out["prev_sample_id"], out["split"].astype(str), strict=True):
|
| 308 |
+
if pd.isna(prev):
|
| 309 |
+
kept.append(pd.NA)
|
| 310 |
+
continue
|
| 311 |
+
key = str(prev)
|
| 312 |
+
if key not in lookup.index or lookup.loc[key] != split:
|
| 313 |
+
kept.append(pd.NA)
|
| 314 |
+
dropped += 1
|
| 315 |
+
else:
|
| 316 |
+
kept.append(key)
|
| 317 |
+
out["prev_sample_id"] = kept
|
| 318 |
+
return out, dropped
|
bundle/src/tcir.py
ADDED
|
@@ -0,0 +1,591 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build a Cloudie manifest from TCIR HDF5 files, IR1 channel only.
|
| 2 |
+
|
| 3 |
+
TCIR (Chen, Chen and Lin, KDD 2018, https://doi.org/10.1145/3219819.3219926;
|
| 4 |
+
data https://github.com/BoyoChen/TCIR) ships two HDF5 files:
|
| 5 |
+
``TCIR-ATLN_EPAC_WPAC.h5`` and ``TCIR-CPAC_IO_SH.h5``. Each has
|
| 6 |
+
|
| 7 |
+
- ``matrix``: N x 201 x 201 x 4 float32. The README lists the channels in
|
| 8 |
+
the order IR1, WV, VIS, PMW, so IR1 is index 0 (``IR1_INDEX``). The file
|
| 9 |
+
has no channel attributes. On 512 random real frames per file, channel 0
|
| 10 |
+
has a median near 275 and is warmer than channel 1 (WV, median near 238)
|
| 11 |
+
in over 98% of frames, channel 2 is a 0 to 2.2 reflectance with many NaNs
|
| 12 |
+
(VIS at night) and channel 3 is a rain rate. That fits the README order.
|
| 13 |
+
IR1 comes from GridSat-B1, which stores brightness temperature in kelvin.
|
| 14 |
+
Reports still call these "pixel stats".
|
| 15 |
+
- ``info``: a pandas 0.15 "fixed" frame (data_set, ID, time, lon, lat, Vmax,
|
| 16 |
+
R35_4qAVG, MSLP). Current pandas cannot read it, so ``read_info`` decodes
|
| 17 |
+
it with h5py and a restricted unpickler that only rebuilds numpy arrays.
|
| 18 |
+
|
| 19 |
+
Only channel 0 is read (an h5py hyperslab, ``matrix[a:b, :, :, 0]``). Frames
|
| 20 |
+
keep their native 201 x 201 grid, centred on the best-track position, about
|
| 21 |
+
7/100 degree per pixel.
|
| 22 |
+
|
| 23 |
+
Labels. TCIR documents JTWC best tracks for WPAC and HURDAT2 for ATLN and
|
| 24 |
+
EPAC. Both are 1-minute sustained winds, so ``wind_averaging`` is ``1min``.
|
| 25 |
+
TCIR does not document the label source for CPAC, IO or SH. Those rows carry
|
| 26 |
+
``label_source_documented = False`` and an ``_inferred`` label source. A
|
| 27 |
+
cross-check against IBTrACS v04r01 (matched on time and a 0.6 degree
|
| 28 |
+
position window) found TCIR ``Vmax`` equal to ``USA_WIND`` on 99.8% of IO
|
| 29 |
+
and SH rows (JTWC, 1-minute) and on 92% of CPAC rows (99.5% within 5 kt;
|
| 30 |
+
HURDAT2/CPHC, 1-minute), while the 10-minute (BoM, RSMC La Reunion, Nadi)
|
| 31 |
+
and 3-minute (New Delhi) agency winds match 14-21% of the time. So
|
| 32 |
+
``wind_averaging`` is ``1min`` on every row.
|
| 33 |
+
|
| 34 |
+
Southern Hemisphere storms rotate clockwise. Nothing here flips an image by
|
| 35 |
+
default. ``hemisphere`` (N or S, from the row's latitude) is recorded per
|
| 36 |
+
row. ``flip_southern=True`` is an explicit opt-in that mirrors S frames
|
| 37 |
+
north-south when exporting and sets ``flipped = True`` on those rows.
|
| 38 |
+
|
| 39 |
+
Frames whose IR1 is all NaN, has a NaN fraction above
|
| 40 |
+
``max_missing_fraction`` (0.30, the preprocessing gate), or has any finite
|
| 41 |
+
value outside ``IR1_VALID_RANGE`` (150 to 340 K; the real files hold a few
|
| 42 |
+
frames with pixels down to 76 K or up to 348 K) are dropped and listed with a reason in an
|
| 43 |
+
exclusions CSV. Kept frames may still hold a few NaNs; ``ir1_nan_fraction``
|
| 44 |
+
records how many, and ``src.preprocessing`` fills them later.
|
| 45 |
+
|
| 46 |
+
TCIR has no official split inside these files, so the manifest has no
|
| 47 |
+
``source_split`` and never has ``split``. ``src.splits.assign_storms`` writes
|
| 48 |
+
``split`` by storm. MSLP and R35 are label-derived, so they stay out of the
|
| 49 |
+
manifest.
|
| 50 |
+
|
| 51 |
+
Distance to land is joined from ``tcir/audit/distance_to_land.csv`` on
|
| 52 |
+
``sample_id`` (``distance_to_land_km`` and ``near_land``). The training
|
| 53 |
+
path then applies ``labels.near_land_policy`` with ``labels.open_water_km``.
|
| 54 |
+
A sample the CSV does not list, and a listed row whose distance is blank,
|
| 55 |
+
stay unknown. The distance is not filled with 0. NASA is not in this file;
|
| 56 |
+
that loader has no join key (``nasa_tc/audit/README.md``).
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
from __future__ import annotations
|
| 60 |
+
|
| 61 |
+
import argparse
|
| 62 |
+
import io
|
| 63 |
+
import json
|
| 64 |
+
import pickle
|
| 65 |
+
from collections.abc import Iterator, Sequence
|
| 66 |
+
from pathlib import Path
|
| 67 |
+
|
| 68 |
+
import numpy as np
|
| 69 |
+
import pandas as pd
|
| 70 |
+
|
| 71 |
+
from src.schema import require_valid
|
| 72 |
+
|
| 73 |
+
CHANNELS = ("IR1", "WV", "VIS", "PMW") # order in the TCIR README
|
| 74 |
+
IR1_INDEX = 0
|
| 75 |
+
IMAGE_SIZE = 201
|
| 76 |
+
WIND_AVERAGING = "1min"
|
| 77 |
+
IR1_VALID_RANGE = (150.0, 340.0) # kelvin; colder or warmer than any plausible IR window value
|
| 78 |
+
MAX_MISSING_FRACTION = 0.30 # same gate as src.preprocessing
|
| 79 |
+
BLOCK = 256
|
| 80 |
+
_DISTANCE_COLUMNS = ("sample_id", "distance_to_land_km", "near_land")
|
| 81 |
+
DEFAULT_DISTANCE_CSV = Path(__file__).resolve().parents[1] / "tcir" / "audit" / "distance_to_land.csv"
|
| 82 |
+
|
| 83 |
+
# data_set -> (label source, documented by TCIR)
|
| 84 |
+
LABEL_SOURCES = {
|
| 85 |
+
"WPAC": ("jtwc_best_track", True),
|
| 86 |
+
"ATLN": ("hurdat2", True),
|
| 87 |
+
"EPAC": ("hurdat2", True),
|
| 88 |
+
# Not documented by TCIR; inferred from an IBTrACS v04r01 match (PR notes).
|
| 89 |
+
"CPAC": ("hurdat2_inferred", False),
|
| 90 |
+
"IO": ("jtwc_best_track_inferred", False),
|
| 91 |
+
"SH": ("jtwc_best_track_inferred", False),
|
| 92 |
+
}
|
| 93 |
+
EXCLUSION_COLUMNS = [
|
| 94 |
+
"sample_id",
|
| 95 |
+
"storm_id",
|
| 96 |
+
"basin",
|
| 97 |
+
"source_file",
|
| 98 |
+
"h5_index",
|
| 99 |
+
"ir1_nan_fraction",
|
| 100 |
+
"reason",
|
| 101 |
+
]
|
| 102 |
+
|
| 103 |
+
_ALLOWED_GLOBALS = {
|
| 104 |
+
("numpy.core.multiarray", "_reconstruct"),
|
| 105 |
+
("numpy._core.multiarray", "_reconstruct"),
|
| 106 |
+
("numpy.core.multiarray", "scalar"),
|
| 107 |
+
("numpy._core.multiarray", "scalar"),
|
| 108 |
+
("numpy", "ndarray"),
|
| 109 |
+
("numpy", "dtype"),
|
| 110 |
+
("_codecs", "encode"), # Python 3 protocol-2 pickles of byte strings
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class _NumpyOnlyUnpickler(pickle.Unpickler):
|
| 115 |
+
def find_class(self, module: str, name: str): # noqa: ANN201
|
| 116 |
+
if (module, name) not in _ALLOWED_GLOBALS:
|
| 117 |
+
raise pickle.UnpicklingError(f"refusing to load {module}.{name} from TCIR info")
|
| 118 |
+
target = "numpy._core.multiarray" if module.endswith(".multiarray") else module
|
| 119 |
+
import importlib
|
| 120 |
+
|
| 121 |
+
return getattr(importlib.import_module(target), name)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _text(value: object) -> str:
|
| 125 |
+
return value.decode() if isinstance(value, bytes) else str(value)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _block_values(dataset) -> np.ndarray: # noqa: ANN001
|
| 129 |
+
if dataset.dtype.kind in "fiub":
|
| 130 |
+
return dataset[()]
|
| 131 |
+
raw = dataset[0]
|
| 132 |
+
data = bytes(np.asarray(raw, dtype=np.uint8)) if not isinstance(raw, bytes) else raw
|
| 133 |
+
return _NumpyOnlyUnpickler(io.BytesIO(data), encoding="latin1").load()
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def read_info(path: str | Path) -> pd.DataFrame:
|
| 137 |
+
"""Decode the ``info`` frame with h5py. Adds ``h5_index`` (row in ``matrix``)."""
|
| 138 |
+
import h5py
|
| 139 |
+
|
| 140 |
+
with h5py.File(path, "r") as handle:
|
| 141 |
+
group = handle["info"]
|
| 142 |
+
order = [_text(name) for name in group["axis0"][()]]
|
| 143 |
+
n_rows = int(group["axis1"].shape[0])
|
| 144 |
+
columns: dict[str, np.ndarray] = {}
|
| 145 |
+
for block in range(int(group.attrs["nblocks"])):
|
| 146 |
+
items = [_text(name) for name in group[f"block{block}_items"][()]]
|
| 147 |
+
values = np.asarray(_block_values(group[f"block{block}_values"]))
|
| 148 |
+
if values.shape != (n_rows, len(items)):
|
| 149 |
+
raise ValueError(f"{path}: info block{block} has shape {values.shape}")
|
| 150 |
+
for position, item in enumerate(items):
|
| 151 |
+
columns[item] = values[:, position]
|
| 152 |
+
n_matrix = int(handle["matrix"].shape[0])
|
| 153 |
+
if n_matrix != n_rows:
|
| 154 |
+
raise ValueError(f"{path}: info has {n_rows} rows but matrix has {n_matrix}")
|
| 155 |
+
frame = pd.DataFrame({name: columns[name] for name in order})
|
| 156 |
+
for name in frame.columns:
|
| 157 |
+
if frame[name].dtype == object:
|
| 158 |
+
frame[name] = frame[name].map(_text)
|
| 159 |
+
frame["h5_index"] = np.arange(n_rows)
|
| 160 |
+
return frame
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def iter_ir1(path: str | Path, block: int = BLOCK) -> Iterator[tuple[int, np.ndarray]]:
|
| 164 |
+
"""Yield ``(start, frames)`` with frames shaped (k, 201, 201), IR1 only."""
|
| 165 |
+
import h5py
|
| 166 |
+
|
| 167 |
+
with h5py.File(path, "r") as handle:
|
| 168 |
+
matrix = handle["matrix"]
|
| 169 |
+
if matrix.ndim != 4 or matrix.shape[1:] != (IMAGE_SIZE, IMAGE_SIZE, len(CHANNELS)):
|
| 170 |
+
raise ValueError(f"{path}: matrix shape {matrix.shape}, expected N x 201 x 201 x 4")
|
| 171 |
+
for start in range(0, matrix.shape[0], block):
|
| 172 |
+
stop = min(start + block, matrix.shape[0])
|
| 173 |
+
yield start, np.asarray(matrix[start:stop, :, :, IR1_INDEX], dtype=np.float32)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def exclusion_reason(
|
| 177 |
+
frame: np.ndarray,
|
| 178 |
+
max_missing_fraction: float = MAX_MISSING_FRACTION,
|
| 179 |
+
valid_range: tuple[float, float] = IR1_VALID_RANGE,
|
| 180 |
+
) -> tuple[str | None, float]:
|
| 181 |
+
"""Return (reason or None, NaN fraction) for one IR1 frame."""
|
| 182 |
+
finite = np.isfinite(frame)
|
| 183 |
+
nan_fraction = float(1.0 - finite.mean())
|
| 184 |
+
if not finite.any():
|
| 185 |
+
return "ir1 all NaN", nan_fraction
|
| 186 |
+
if nan_fraction > max_missing_fraction:
|
| 187 |
+
return f"ir1 NaN fraction {nan_fraction:.3f} > {max_missing_fraction:.2f}", nan_fraction
|
| 188 |
+
values = frame[finite]
|
| 189 |
+
low, high = valid_range
|
| 190 |
+
if float(values.min()) < low or float(values.max()) > high:
|
| 191 |
+
return (
|
| 192 |
+
f"ir1 value outside [{low:g}, {high:g}] K "
|
| 193 |
+
f"(min {float(values.min()):.2f}, max {float(values.max()):.2f})",
|
| 194 |
+
nan_fraction,
|
| 195 |
+
)
|
| 196 |
+
return None, nan_fraction
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def hemisphere_of(lat: pd.Series) -> pd.Series:
|
| 200 |
+
return pd.Series(np.where(pd.to_numeric(lat) < 0, "S", "N"), index=lat.index)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _blank_distance(value: object) -> bool:
|
| 204 |
+
if value is None:
|
| 205 |
+
return True
|
| 206 |
+
try:
|
| 207 |
+
if pd.isna(value):
|
| 208 |
+
return True
|
| 209 |
+
except (TypeError, ValueError):
|
| 210 |
+
return False
|
| 211 |
+
return str(value).strip().lower() in {"", "nan", "none", "null", "<na>"}
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _near_land_token(value: object) -> str:
|
| 215 |
+
"""``true``, ``false``, or ``unknown``. A blank cell stays unknown."""
|
| 216 |
+
if isinstance(value, (bool, np.bool_)):
|
| 217 |
+
return "true" if bool(value) else "false"
|
| 218 |
+
if _blank_distance(value):
|
| 219 |
+
return "unknown"
|
| 220 |
+
text = str(value).strip().lower()
|
| 221 |
+
if text in {"1", "true", "yes", "y", "t"}:
|
| 222 |
+
return "true"
|
| 223 |
+
if text in {"0", "false", "no", "n", "f"}:
|
| 224 |
+
return "false"
|
| 225 |
+
if text in {"unknown", "na", "n/a"}:
|
| 226 |
+
return "unknown"
|
| 227 |
+
raise ValueError(f"near_land value {value!r} is not true, false, or unknown")
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _distance_km(value: object) -> float:
|
| 231 |
+
if _blank_distance(value):
|
| 232 |
+
return float("nan")
|
| 233 |
+
try:
|
| 234 |
+
number = float(value)
|
| 235 |
+
except (TypeError, ValueError) as exc:
|
| 236 |
+
raise ValueError(f"distance_to_land_km value {value!r} is not a distance") from exc
|
| 237 |
+
if not np.isfinite(number):
|
| 238 |
+
return float("nan")
|
| 239 |
+
return number
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def read_distance_to_land(path: str | Path | None = None) -> pd.DataFrame:
|
| 243 |
+
"""``sample_id``, ``distance_to_land_km``, and ``near_land`` from the audit CSV.
|
| 244 |
+
|
| 245 |
+
``path`` defaults to ``tcir/audit/distance_to_land.csv``. Blank distances
|
| 246 |
+
stay NaN. ``near_land`` stays ``unknown`` when the audit says so.
|
| 247 |
+
"""
|
| 248 |
+
csv_path = DEFAULT_DISTANCE_CSV if path in (None, "", "null") else Path(path)
|
| 249 |
+
if not csv_path.is_file():
|
| 250 |
+
raise FileNotFoundError(
|
| 251 |
+
f"TCIR distance table {csv_path} is missing. Nothing is downloaded."
|
| 252 |
+
)
|
| 253 |
+
table = pd.read_csv(csv_path)
|
| 254 |
+
table.columns = [str(column).strip() for column in table.columns]
|
| 255 |
+
missing = [column for column in _DISTANCE_COLUMNS if column not in table.columns]
|
| 256 |
+
if missing:
|
| 257 |
+
raise ValueError(f"distance_to_land.csv missing {missing}")
|
| 258 |
+
out = pd.DataFrame(
|
| 259 |
+
{
|
| 260 |
+
"sample_id": table["sample_id"].astype(str).str.strip(),
|
| 261 |
+
"distance_to_land_km": [_distance_km(value) for value in table["distance_to_land_km"].tolist()],
|
| 262 |
+
"near_land": [_near_land_token(value) for value in table["near_land"].tolist()],
|
| 263 |
+
}
|
| 264 |
+
)
|
| 265 |
+
if out["sample_id"].duplicated().any():
|
| 266 |
+
raise ValueError("distance_to_land.csv repeats a sample_id")
|
| 267 |
+
return out
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def attach_distance_to_land(
|
| 271 |
+
frame: pd.DataFrame, path: str | Path | None = None
|
| 272 |
+
) -> pd.DataFrame:
|
| 273 |
+
"""Left-join the audit distances onto ``sample_id``.
|
| 274 |
+
|
| 275 |
+
A sample that is not in the CSV, or a row whose distance is blank,
|
| 276 |
+
keeps a null distance and ``near_land`` ``unknown``. The null is not
|
| 277 |
+
replaced with 0 km or with ``false``.
|
| 278 |
+
"""
|
| 279 |
+
if "sample_id" not in frame.columns:
|
| 280 |
+
raise ValueError("TCIR distance join needs sample_id")
|
| 281 |
+
flags = read_distance_to_land(path)
|
| 282 |
+
lookup = flags.set_index("sample_id")
|
| 283 |
+
distance: list[float] = []
|
| 284 |
+
near: list[str] = []
|
| 285 |
+
for sample_id in frame["sample_id"].astype(str).tolist():
|
| 286 |
+
if sample_id not in lookup.index:
|
| 287 |
+
distance.append(float("nan"))
|
| 288 |
+
near.append("unknown")
|
| 289 |
+
continue
|
| 290 |
+
row = lookup.loc[sample_id]
|
| 291 |
+
if isinstance(row, pd.DataFrame):
|
| 292 |
+
raise ValueError(f"distance_to_land.csv repeats {sample_id}")
|
| 293 |
+
distance.append(_distance_km(row["distance_to_land_km"]))
|
| 294 |
+
near.append(_near_land_token(row["near_land"]))
|
| 295 |
+
out = frame.copy()
|
| 296 |
+
out["distance_to_land_km"] = np.asarray(distance, dtype=float)
|
| 297 |
+
out["near_land"] = near
|
| 298 |
+
return out
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def orient(
|
| 302 |
+
frame: np.ndarray, hemisphere: str, flip_southern: bool = False
|
| 303 |
+
) -> tuple[np.ndarray, bool]:
|
| 304 |
+
"""Return (frame, flipped). Only flips when ``flip_southern`` is set and the row is S."""
|
| 305 |
+
if flip_southern and hemisphere == "S":
|
| 306 |
+
return np.ascontiguousarray(frame[::-1, :]), True
|
| 307 |
+
return frame, False
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _rows(info: pd.DataFrame, source_file: str) -> pd.DataFrame:
|
| 311 |
+
unknown = sorted(set(info["data_set"]) - set(LABEL_SOURCES))
|
| 312 |
+
if unknown:
|
| 313 |
+
raise ValueError(f"unknown TCIR data_set values {unknown}")
|
| 314 |
+
stamp = pd.to_datetime(info["time"].astype(str), format="%Y%m%d%H", utc=True)
|
| 315 |
+
lon = pd.to_numeric(info["lon"]).astype(float)
|
| 316 |
+
rows = pd.DataFrame(
|
| 317 |
+
{
|
| 318 |
+
"sample_id": "tcir_" + info["ID"].astype(str) + "_" + info["time"].astype(str),
|
| 319 |
+
"storm_id": info["ID"].astype(str),
|
| 320 |
+
"timestamp": stamp.dt.strftime("%Y-%m-%dT%H:%M:%SZ"),
|
| 321 |
+
"year": stamp.dt.year.astype(int),
|
| 322 |
+
"wind_speed_kt": pd.to_numeric(info["Vmax"]).astype(float),
|
| 323 |
+
"basin": info["data_set"].astype(str),
|
| 324 |
+
"lat": pd.to_numeric(info["lat"]).astype(float),
|
| 325 |
+
"lon": ((lon + 180.0) % 360.0) - 180.0,
|
| 326 |
+
"hemisphere": hemisphere_of(info["lat"]),
|
| 327 |
+
"source": "tcir",
|
| 328 |
+
"source_file": source_file,
|
| 329 |
+
"h5_index": info["h5_index"].astype(int),
|
| 330 |
+
"sensor": "GridSat-B1",
|
| 331 |
+
"channel": "IR1",
|
| 332 |
+
"channel_index": IR1_INDEX,
|
| 333 |
+
"native_height": IMAGE_SIZE,
|
| 334 |
+
"native_width": IMAGE_SIZE,
|
| 335 |
+
"orig_size": IMAGE_SIZE,
|
| 336 |
+
"pixel_units": "kelvin_brightness_temperature",
|
| 337 |
+
"wind_averaging": WIND_AVERAGING,
|
| 338 |
+
"label_source": info["data_set"].map(lambda b: LABEL_SOURCES[b][0]),
|
| 339 |
+
"label_source_documented": info["data_set"].map(lambda b: LABEL_SOURCES[b][1]),
|
| 340 |
+
"center_source": "dataset_precentered",
|
| 341 |
+
"is_synthetic": False,
|
| 342 |
+
}
|
| 343 |
+
)
|
| 344 |
+
return rows
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
class _PixelStats:
|
| 348 |
+
def __init__(self) -> None:
|
| 349 |
+
self.count = 0
|
| 350 |
+
self.total = 0.0
|
| 351 |
+
self.total_sq = 0.0
|
| 352 |
+
self.low = np.inf
|
| 353 |
+
self.high = -np.inf
|
| 354 |
+
|
| 355 |
+
def add(self, frame: np.ndarray) -> None:
|
| 356 |
+
values = frame[np.isfinite(frame)].astype(np.float64)
|
| 357 |
+
if values.size:
|
| 358 |
+
self.count += int(values.size)
|
| 359 |
+
self.total += float(values.sum())
|
| 360 |
+
self.total_sq += float(np.square(values).sum())
|
| 361 |
+
self.low = min(self.low, float(values.min()))
|
| 362 |
+
self.high = max(self.high, float(values.max()))
|
| 363 |
+
|
| 364 |
+
def as_dict(self) -> dict[str, float | int]:
|
| 365 |
+
if not self.count:
|
| 366 |
+
return {"finite_pixels": 0}
|
| 367 |
+
mean = self.total / self.count
|
| 368 |
+
return {
|
| 369 |
+
"finite_pixels": self.count,
|
| 370 |
+
"min": round(self.low, 3),
|
| 371 |
+
"max": round(self.high, 3),
|
| 372 |
+
"mean": round(mean, 3),
|
| 373 |
+
"std": round(float(np.sqrt(max(self.total_sq / self.count - mean**2, 0.0))), 3),
|
| 374 |
+
}
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def build_manifest(
|
| 378 |
+
h5_paths: Sequence[str | Path],
|
| 379 |
+
manifest_dir: str | Path,
|
| 380 |
+
export: bool = True,
|
| 381 |
+
flip_southern: bool = False,
|
| 382 |
+
max_missing_fraction: float = MAX_MISSING_FRACTION,
|
| 383 |
+
block: int = BLOCK,
|
| 384 |
+
distance_csv: str | Path | None = None,
|
| 385 |
+
) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, object]]:
|
| 386 |
+
"""Return (manifest, exclusions, pixel stats).
|
| 387 |
+
|
| 388 |
+
With ``export`` each kept IR1 frame is saved as ``ir1/<sample_id>.npy``
|
| 389 |
+
under ``manifest_dir`` and ``image_path`` points there (relative), so
|
| 390 |
+
``src.data_loader`` can read it. Without ``export`` ``image_path`` is
|
| 391 |
+
``<file>#<h5_index>`` for reference only. ``distance_csv`` defaults to
|
| 392 |
+
the committed audit table and is joined on ``sample_id``.
|
| 393 |
+
"""
|
| 394 |
+
manifest_dir = Path(manifest_dir).resolve()
|
| 395 |
+
image_dir = manifest_dir / "ir1"
|
| 396 |
+
if export:
|
| 397 |
+
image_dir.mkdir(parents=True, exist_ok=True)
|
| 398 |
+
kept_parts, excluded_parts = [], []
|
| 399 |
+
stats = _PixelStats()
|
| 400 |
+
frames_with_nan = 0
|
| 401 |
+
for h5_path in h5_paths:
|
| 402 |
+
h5_path = Path(h5_path)
|
| 403 |
+
rows = _rows(read_info(h5_path), h5_path.name)
|
| 404 |
+
reasons: list[str | None] = [None] * len(rows)
|
| 405 |
+
nan_fractions = np.zeros(len(rows))
|
| 406 |
+
flipped = np.zeros(len(rows), dtype=bool)
|
| 407 |
+
winds = rows["wind_speed_kt"].to_numpy()
|
| 408 |
+
bad_wind = ~np.isfinite(winds) | (winds < 0)
|
| 409 |
+
for start, frames in iter_ir1(h5_path, block):
|
| 410 |
+
for offset, frame in enumerate(frames):
|
| 411 |
+
index = start + offset
|
| 412 |
+
reason, nan_fractions[index] = exclusion_reason(frame, max_missing_fraction)
|
| 413 |
+
if reason is None and bad_wind[index]:
|
| 414 |
+
reason = "wind missing or negative"
|
| 415 |
+
reasons[index] = reason
|
| 416 |
+
if reason is not None:
|
| 417 |
+
continue
|
| 418 |
+
stats.add(frame)
|
| 419 |
+
frames_with_nan += int(nan_fractions[index] > 0)
|
| 420 |
+
if export:
|
| 421 |
+
out, flipped[index] = orient(frame, rows.at[index, "hemisphere"], flip_southern)
|
| 422 |
+
np.save(image_dir / f"{rows.at[index, 'sample_id']}.npy", out.astype(np.float32))
|
| 423 |
+
rows["ir1_nan_fraction"] = np.round(nan_fractions, 5)
|
| 424 |
+
rows["flipped"] = flipped
|
| 425 |
+
rows["image_path"] = (
|
| 426 |
+
"ir1/" + rows["sample_id"] + ".npy"
|
| 427 |
+
if export
|
| 428 |
+
else rows["source_file"] + "#" + rows["h5_index"].astype(str)
|
| 429 |
+
)
|
| 430 |
+
drop = pd.Series([reason is not None for reason in reasons], index=rows.index)
|
| 431 |
+
excluded = rows.loc[drop].assign(reason=[r for r in reasons if r is not None])
|
| 432 |
+
kept_parts.append(rows.loc[~drop])
|
| 433 |
+
excluded_parts.append(excluded[EXCLUSION_COLUMNS])
|
| 434 |
+
manifest = pd.concat(kept_parts, ignore_index=True)
|
| 435 |
+
excluded = pd.concat(excluded_parts, ignore_index=True)
|
| 436 |
+
if "split" in manifest.columns or "source_split" in manifest.columns:
|
| 437 |
+
raise AssertionError("TCIR manifest must not carry split or source_split")
|
| 438 |
+
manifest = attach_distance_to_land(manifest, distance_csv)
|
| 439 |
+
manifest = require_valid(manifest)
|
| 440 |
+
pixel = stats.as_dict()
|
| 441 |
+
pixel["kept_frames_with_some_nan"] = frames_with_nan
|
| 442 |
+
return manifest, excluded, pixel
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def storm_split_check(
|
| 446 |
+
frame: pd.DataFrame, strategy: str = "storm_wise", seed: int = 42
|
| 447 |
+
) -> dict[str, object]:
|
| 448 |
+
"""Run the project splitter on the manifest and assert no storm leaks."""
|
| 449 |
+
from src.splits import assert_no_group_leakage, assign_storms
|
| 450 |
+
|
| 451 |
+
if "split" in frame.columns:
|
| 452 |
+
raise ValueError("manifest must not carry split")
|
| 453 |
+
assigned = assign_storms(frame, strategy, seed=seed)
|
| 454 |
+
names = ("train", "val", "test")
|
| 455 |
+
parts = [assigned.loc[assigned["split"] == name] for name in names]
|
| 456 |
+
assert_no_group_leakage(*parts)
|
| 457 |
+
return {
|
| 458 |
+
"strategy": strategy,
|
| 459 |
+
"rows": {name: int(len(part)) for name, part in zip(names, parts)},
|
| 460 |
+
"storms": {name: int(part["storm_id"].nunique()) for name, part in zip(names, parts)},
|
| 461 |
+
"leakage": "none",
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def _reason_kind(reason: str) -> str:
|
| 466 |
+
"""Strip per-frame numbers so reasons can be counted."""
|
| 467 |
+
if reason.startswith("ir1 NaN fraction"):
|
| 468 |
+
return f"ir1 NaN fraction > {MAX_MISSING_FRACTION:.2f}"
|
| 469 |
+
return reason.split(" (")[0]
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def summarize(
|
| 473 |
+
frame: pd.DataFrame, excluded: pd.DataFrame, pixel: dict[str, object]
|
| 474 |
+
) -> dict[str, object]:
|
| 475 |
+
def counts(column: str) -> dict[str, dict[str, int]]:
|
| 476 |
+
return {
|
| 477 |
+
str(key): {"rows": int(len(group)), "storms": int(group["storm_id"].nunique())}
|
| 478 |
+
for key, group in frame.groupby(column)
|
| 479 |
+
}
|
| 480 |
+
|
| 481 |
+
storm_hemispheres = frame.groupby("storm_id")["hemisphere"].nunique()
|
| 482 |
+
return {
|
| 483 |
+
"rows": int(len(frame)),
|
| 484 |
+
"unique_storms": int(frame["storm_id"].nunique()),
|
| 485 |
+
"by_basin": counts("basin"),
|
| 486 |
+
"by_hemisphere": counts("hemisphere"),
|
| 487 |
+
"by_source_file": counts("source_file"),
|
| 488 |
+
"storms_crossing_equator": sorted(storm_hemispheres[storm_hemispheres > 1].index.tolist()),
|
| 489 |
+
"basin_vs_hemisphere": {
|
| 490 |
+
f"{basin}/{hemi}": int(n)
|
| 491 |
+
for (basin, hemi), n in frame.groupby(["basin", "hemisphere"]).size().items()
|
| 492 |
+
},
|
| 493 |
+
"years": [int(frame["year"].min()), int(frame["year"].max())],
|
| 494 |
+
"wind_kt_min": float(frame["wind_speed_kt"].min()),
|
| 495 |
+
"wind_kt_max": float(frame["wind_speed_kt"].max()),
|
| 496 |
+
"wind_kt_mean": round(float(frame["wind_speed_kt"].mean()), 2),
|
| 497 |
+
"pixel_stats_ir1": pixel,
|
| 498 |
+
"flipped_rows": int(frame["flipped"].sum()),
|
| 499 |
+
"label_source_counts": frame["label_source"].value_counts().to_dict(),
|
| 500 |
+
"label_source_undocumented_rows": int((~frame["label_source_documented"].astype(bool)).sum()),
|
| 501 |
+
"wind_averaging": sorted(frame["wind_averaging"].unique()),
|
| 502 |
+
"native_sizes": sorted({f"{h}x{w}" for h, w in zip(frame["native_height"], frame["native_width"])}),
|
| 503 |
+
"has_split_column": "split" in frame.columns,
|
| 504 |
+
"has_source_split_column": "source_split" in frame.columns,
|
| 505 |
+
"is_synthetic": bool(frame["is_synthetic"].any()),
|
| 506 |
+
"excluded": {
|
| 507 |
+
"count": int(len(excluded)),
|
| 508 |
+
"by_reason": excluded["reason"].map(_reason_kind).value_counts().to_dict(),
|
| 509 |
+
"by_basin": excluded["basin"].value_counts().to_dict() if len(excluded) else {},
|
| 510 |
+
},
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def save_sample_png(
|
| 515 |
+
frame: pd.DataFrame, manifest_dir: str | Path, out: str | Path
|
| 516 |
+
) -> list[dict[str, object]]:
|
| 517 |
+
"""One N and one S frame side by side, as stored (no flip unless opted in)."""
|
| 518 |
+
import matplotlib
|
| 519 |
+
|
| 520 |
+
matplotlib.use("Agg")
|
| 521 |
+
import matplotlib.pyplot as plt
|
| 522 |
+
|
| 523 |
+
picks = []
|
| 524 |
+
for hemi in ("N", "S"):
|
| 525 |
+
subset = frame[frame["hemisphere"] == hemi]
|
| 526 |
+
if len(subset):
|
| 527 |
+
picks.append(subset.loc[subset["wind_speed_kt"].idxmax()])
|
| 528 |
+
fig, axes = plt.subplots(1, len(picks), figsize=(4.2 * len(picks), 4.4), squeeze=False)
|
| 529 |
+
info = []
|
| 530 |
+
for ax, row in zip(axes[0], picks):
|
| 531 |
+
image = np.load(Path(manifest_dir) / row["image_path"])
|
| 532 |
+
shown = ax.imshow(image, cmap="gray_r")
|
| 533 |
+
fig.colorbar(shown, ax=ax, fraction=0.046, label="IR1 pixel value")
|
| 534 |
+
ax.set_title(
|
| 535 |
+
f"{row['storm_id']} {row['timestamp'][:13]}Z {row['basin']}/{row['hemisphere']}\n"
|
| 536 |
+
f"{row['wind_speed_kt']:.0f} kt (1min) | flipped={bool(row['flipped'])} | TCIR real",
|
| 537 |
+
fontsize=8,
|
| 538 |
+
)
|
| 539 |
+
ax.axis("off")
|
| 540 |
+
info.append(
|
| 541 |
+
{
|
| 542 |
+
"sample_id": row["sample_id"],
|
| 543 |
+
"hemisphere": row["hemisphere"],
|
| 544 |
+
"wind_speed_kt": float(row["wind_speed_kt"]),
|
| 545 |
+
"shape": list(image.shape),
|
| 546 |
+
"flipped": bool(row["flipped"]),
|
| 547 |
+
}
|
| 548 |
+
)
|
| 549 |
+
Path(out).parent.mkdir(parents=True, exist_ok=True)
|
| 550 |
+
fig.savefig(out, dpi=100, bbox_inches="tight")
|
| 551 |
+
plt.close(fig)
|
| 552 |
+
return info
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def main() -> None:
|
| 556 |
+
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
| 557 |
+
parser.add_argument("--h5", nargs="+", required=True, help="TCIR .h5 files")
|
| 558 |
+
parser.add_argument("--out", default="data/tcir/manifest.csv")
|
| 559 |
+
parser.add_argument("--summary", default="reports/tcir_summary.json")
|
| 560 |
+
parser.add_argument("--sample-png", default="reports/tcir_sample.png")
|
| 561 |
+
parser.add_argument("--exclusions", default=None, help="default: <manifest dir>/tcir_exclusions.csv")
|
| 562 |
+
parser.add_argument("--no-export", action="store_true", help="do not write ir1/*.npy")
|
| 563 |
+
parser.add_argument(
|
| 564 |
+
"--flip-southern",
|
| 565 |
+
action="store_true",
|
| 566 |
+
help="opt in: mirror Southern Hemisphere frames north-south on export (default: no flip)",
|
| 567 |
+
)
|
| 568 |
+
args = parser.parse_args()
|
| 569 |
+
|
| 570 |
+
out = Path(args.out)
|
| 571 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 572 |
+
frame, excluded, pixel = build_manifest(
|
| 573 |
+
args.h5, out.parent, export=not args.no_export, flip_southern=args.flip_southern
|
| 574 |
+
)
|
| 575 |
+
exclusions_path = Path(args.exclusions) if args.exclusions else out.parent / "tcir_exclusions.csv"
|
| 576 |
+
excluded.to_csv(exclusions_path, index=False)
|
| 577 |
+
frame.drop(columns=["imd5_class"], errors="ignore").to_csv(out, index=False)
|
| 578 |
+
summary = summarize(frame, excluded, pixel)
|
| 579 |
+
summary["exclusions_file"] = str(exclusions_path)
|
| 580 |
+
summary["storm_split_check"] = storm_split_check(frame)
|
| 581 |
+
summary["flip_southern"] = bool(args.flip_southern)
|
| 582 |
+
summary["manifest"] = str(out)
|
| 583 |
+
if not args.no_export:
|
| 584 |
+
summary["sample"] = save_sample_png(frame, out.parent, args.sample_png)
|
| 585 |
+
Path(args.summary).parent.mkdir(parents=True, exist_ok=True)
|
| 586 |
+
Path(args.summary).write_text(json.dumps(summary, indent=2, default=str))
|
| 587 |
+
print(json.dumps(summary, indent=2, default=str))
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
if __name__ == "__main__":
|
| 591 |
+
main()
|
bundle/src/train.py
ADDED
|
@@ -0,0 +1,2356 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Training loop. A smoke fit only shows that the software runs.
|
| 2 |
+
|
| 3 |
+
Hyperparameters come from the YAML config. ``pretrained: true`` downloads
|
| 4 |
+
ImageNet weights and is refused unless ``CLOUDIE_ALLOW_PRETRAINED=1``.
|
| 5 |
+
The wind loss is weighted Smooth L1. The class loss is auxiliary. A size
|
| 6 |
+
term is added only when ``r34_nmi`` and ``rmw_nmi`` exist as labels, and
|
| 7 |
+
those columns are targets, not inputs. ``model.name: convlstm`` uses four
|
| 8 |
+
frames from the same storm and the same split.
|
| 9 |
+
|
| 10 |
+
``python -m src.train`` picks xpu, then cuda, then cpu. XPU and CUDA both
|
| 11 |
+
need ``CLOUDIE_ALLOW_GPU=1``. Normalization is fit per dataset on train
|
| 12 |
+
storms only. ``--init-from`` loads weights for a later dataset and refits
|
| 13 |
+
those stats. ``--resume`` continues the last finished epoch.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import copy
|
| 20 |
+
import hashlib
|
| 21 |
+
import json
|
| 22 |
+
import logging
|
| 23 |
+
import os
|
| 24 |
+
import random
|
| 25 |
+
import subprocess
|
| 26 |
+
import time
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
import pandas as pd
|
| 31 |
+
|
| 32 |
+
from src.config import checkpoint_path, load_config, parse_image_size
|
| 33 |
+
from src.data_loader import apply_frame_cache, load_image, load_manifest, resolve_image
|
| 34 |
+
from src.device import (
|
| 35 |
+
amp_policy_for,
|
| 36 |
+
autocast_context,
|
| 37 |
+
compare_model_parity,
|
| 38 |
+
make_grad_scaler,
|
| 39 |
+
peak_memory_bytes,
|
| 40 |
+
reset_peak_memory,
|
| 41 |
+
resolve_device,
|
| 42 |
+
seeded_parity_batch,
|
| 43 |
+
xpu_device_properties,
|
| 44 |
+
)
|
| 45 |
+
from src.labels import apply_wind_standard, back_converted_prediction, run_conversion_note
|
| 46 |
+
from src.preprocessing import (
|
| 47 |
+
NormStats,
|
| 48 |
+
fit_norm_stats,
|
| 49 |
+
norm_by_dataset,
|
| 50 |
+
prepare_image,
|
| 51 |
+
prepare_training_chip,
|
| 52 |
+
stack_prepared,
|
| 53 |
+
)
|
| 54 |
+
from src.schema import (
|
| 55 |
+
SchemaError,
|
| 56 |
+
parse_is_synthetic,
|
| 57 |
+
recorded_wind_averaging,
|
| 58 |
+
split_wind_averaging,
|
| 59 |
+
wind_averaging_seconds,
|
| 60 |
+
wind_to_imd5,
|
| 61 |
+
)
|
| 62 |
+
from src.sequences import N_FRAMES, _row, frame_windows, size_targets_present, stack_windows
|
| 63 |
+
from src.splits import (
|
| 64 |
+
LeakageError,
|
| 65 |
+
add_previous_frame_id,
|
| 66 |
+
assert_no_forbidden_inputs,
|
| 67 |
+
assign_storms,
|
| 68 |
+
null_cross_split_links,
|
| 69 |
+
storm_ids_by_split,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
SMOKE_BANNER = (
|
| 73 |
+
"Checkpoint was fit on synthetic smoke data. "
|
| 74 |
+
"Metrics from it are a software check. Do not report them as skill."
|
| 75 |
+
)
|
| 76 |
+
NOT_A_FORECAST = (
|
| 77 |
+
"This checkpoint is not a forecast or a warning. "
|
| 78 |
+
"Agreement with a best track is not ground truth."
|
| 79 |
+
)
|
| 80 |
+
class EarlyStopping:
|
| 81 |
+
"""Stop after ``patience`` validation checks without an improvement."""
|
| 82 |
+
|
| 83 |
+
def __init__(self, patience: int) -> None:
|
| 84 |
+
if patience < 1:
|
| 85 |
+
raise ValueError("patience must be at least 1")
|
| 86 |
+
self.patience = patience
|
| 87 |
+
self.best = float("inf")
|
| 88 |
+
self.waits = 0
|
| 89 |
+
self.best_state: dict | None = None
|
| 90 |
+
|
| 91 |
+
def update(self, metric: float, state: dict) -> bool:
|
| 92 |
+
"""Return True when training should stop. Lower metric is better."""
|
| 93 |
+
if metric < self.best:
|
| 94 |
+
self.best = float(metric)
|
| 95 |
+
self.waits = 0
|
| 96 |
+
self.best_state = copy.deepcopy(state)
|
| 97 |
+
return False
|
| 98 |
+
self.waits += 1
|
| 99 |
+
return self.waits >= self.patience
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def assert_model_inputs(names: list[str] | tuple[str, ...]) -> None:
|
| 103 |
+
"""Images are the model input. Wind, size, and class labels are not."""
|
| 104 |
+
assert_no_forbidden_inputs(names, "forbidden model inputs")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def class_sample_weights(
|
| 108 |
+
class_names: list[str | None], known: list[str]
|
| 109 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 110 |
+
"""Inverse-frequency weights fit on this list only.
|
| 111 |
+
|
| 112 |
+
``class_weight`` lines up with ``known``. A class that does not appear
|
| 113 |
+
gets weight 0. A row with no project class gets sample weight 1.
|
| 114 |
+
"""
|
| 115 |
+
counts = np.array(
|
| 116 |
+
[sum(name == item for item in class_names) for name in known], dtype=np.float64
|
| 117 |
+
)
|
| 118 |
+
present = counts > 0
|
| 119 |
+
class_weight = np.zeros(len(known), dtype=np.float64)
|
| 120 |
+
if present.any():
|
| 121 |
+
class_weight[present] = counts[present].sum() / (present.sum() * counts[present])
|
| 122 |
+
index = {name: position for position, name in enumerate(known)}
|
| 123 |
+
sample = np.ones(len(class_names), dtype=np.float64)
|
| 124 |
+
for row, name in enumerate(class_names):
|
| 125 |
+
if name in index and class_weight[index[name]] > 0:
|
| 126 |
+
sample[row] = class_weight[index[name]]
|
| 127 |
+
return sample, class_weight
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
LOSS_WEIGHTINGS = ("none", "inverse_freq", "sqrt_inverse_freq")
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def loss_weighting_mode(value: object) -> str:
|
| 134 |
+
"""``train.loss_weighting``. The default ``none`` leaves the wind loss unweighted."""
|
| 135 |
+
if value is None or (isinstance(value, str) and value.strip().lower() in {"", "null", "none"}):
|
| 136 |
+
return "none"
|
| 137 |
+
text = str(value).strip().lower()
|
| 138 |
+
if text not in LOSS_WEIGHTINGS:
|
| 139 |
+
raise ValueError("train.loss_weighting must be none, inverse_freq, or sqrt_inverse_freq")
|
| 140 |
+
return text
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def config_flag(value: object, name: str) -> bool:
|
| 144 |
+
"""YAML bool. Strings ``true`` and ``false`` are accepted. Anything else raises."""
|
| 145 |
+
if isinstance(value, (bool, np.bool_)):
|
| 146 |
+
return bool(value)
|
| 147 |
+
if value is None or (isinstance(value, str) and not value.strip()):
|
| 148 |
+
return False
|
| 149 |
+
text = str(value).strip().lower()
|
| 150 |
+
if text in {"1", "true", "yes", "y", "t"}:
|
| 151 |
+
return True
|
| 152 |
+
if text in {"0", "false", "no", "n", "f"}:
|
| 153 |
+
return False
|
| 154 |
+
raise ValueError(f"{name} must be true or false")
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def frequency_rows(frame: pd.DataFrame) -> tuple[pd.DataFrame, str]:
|
| 158 |
+
"""Rows that define intensity-bin frequencies.
|
| 159 |
+
|
| 160 |
+
Only the assigned train split is used. Synthetic copies are excluded
|
| 161 |
+
when that split also has original frames, so a ``rot_180`` duplicate
|
| 162 |
+
cannot change the weight. Val and test never contribute, including
|
| 163 |
+
under ``storm_cv`` (the val fold is already ``split == val``). A train
|
| 164 |
+
split whose every row is synthetic, which is the smoke manifest, uses
|
| 165 |
+
those rows because there is no original frame to count.
|
| 166 |
+
"""
|
| 167 |
+
if "split" not in frame.columns:
|
| 168 |
+
raise LeakageError("intensity weights need an assigned split")
|
| 169 |
+
train = frame.loc[frame["split"].astype(str) == "train"].copy()
|
| 170 |
+
if train.empty:
|
| 171 |
+
raise LeakageError("intensity weights need train rows")
|
| 172 |
+
note = "train originals; synthetic copies, val, and test are excluded"
|
| 173 |
+
if "is_synthetic" not in train.columns:
|
| 174 |
+
return train.reset_index(drop=True), note
|
| 175 |
+
flags = [parse_is_synthetic(value) for value in train["is_synthetic"].tolist()]
|
| 176 |
+
originals = train.loc[[not flag for flag in flags]]
|
| 177 |
+
if originals.empty:
|
| 178 |
+
return (
|
| 179 |
+
train.reset_index(drop=True),
|
| 180 |
+
"train rows; every train row is synthetic, so no original frame was excluded",
|
| 181 |
+
)
|
| 182 |
+
return originals.reset_index(drop=True), note
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _bin_weight_table(counts: dict[str, int], mode: str) -> dict[str, float | None]:
|
| 186 |
+
"""Per-bin weight. A bin with no train originals stays null.
|
| 187 |
+
|
| 188 |
+
``inverse_freq`` is ``n / (k * count)`` over bins that occur, the same
|
| 189 |
+
shape as the class weights above, so the count-weighted mean is 1.
|
| 190 |
+
``sqrt_inverse_freq`` is the square root of that weight. ``none`` is 1
|
| 191 |
+
on bins that occur and is not applied to the loss.
|
| 192 |
+
"""
|
| 193 |
+
choice = loss_weighting_mode(mode)
|
| 194 |
+
present = {name: int(count) for name, count in counts.items() if int(count) > 0}
|
| 195 |
+
total = float(sum(present.values()))
|
| 196 |
+
n_present = len(present)
|
| 197 |
+
weights: dict[str, float | None] = {}
|
| 198 |
+
for name, count in counts.items():
|
| 199 |
+
count = int(count)
|
| 200 |
+
if count <= 0:
|
| 201 |
+
weights[name] = None
|
| 202 |
+
continue
|
| 203 |
+
if choice == "none":
|
| 204 |
+
weights[name] = 1.0
|
| 205 |
+
continue
|
| 206 |
+
base = total / (n_present * float(count))
|
| 207 |
+
if choice == "inverse_freq":
|
| 208 |
+
weights[name] = float(base)
|
| 209 |
+
else:
|
| 210 |
+
weights[name] = float(np.sqrt(base))
|
| 211 |
+
return weights
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def intensity_balance(frame: pd.DataFrame, config: dict, wind_column: str) -> dict:
|
| 215 |
+
"""Train-only bin counts and the weights the run will record.
|
| 216 |
+
|
| 217 |
+
Sampling, when enabled, draws with the inverse-frequency weights so
|
| 218 |
+
each occurring bin has the same expected count. That table is separate
|
| 219 |
+
from ``sqrt_inverse_freq`` loss weights.
|
| 220 |
+
"""
|
| 221 |
+
train_cfg = config.get("train") if isinstance(config.get("train"), dict) else {}
|
| 222 |
+
mode = loss_weighting_mode(train_cfg.get("loss_weighting", "none"))
|
| 223 |
+
balanced = config_flag(train_cfg.get("balanced_sampling", False), "train.balanced_sampling")
|
| 224 |
+
rows, note = frequency_rows(frame)
|
| 225 |
+
names = [str(name) for name in config["data"]["imd5_names"]]
|
| 226 |
+
labels = project_labels(rows, config, wind_column)
|
| 227 |
+
counts = {name: 0 for name in names}
|
| 228 |
+
for label in labels:
|
| 229 |
+
if label in counts:
|
| 230 |
+
counts[label] += 1
|
| 231 |
+
return {
|
| 232 |
+
"loss_weighting": mode,
|
| 233 |
+
"balanced_sampling": balanced,
|
| 234 |
+
"source": note,
|
| 235 |
+
"split_strategy": str((config.get("split") or {}).get("strategy", "")),
|
| 236 |
+
"wind_column": str(wind_column),
|
| 237 |
+
"n_frequency_rows": int(len(rows)),
|
| 238 |
+
"n_below_lowest_edge": int(sum(label not in counts for label in labels)),
|
| 239 |
+
"counts": counts,
|
| 240 |
+
"weights": _bin_weight_table(counts, mode),
|
| 241 |
+
"sampling_weights": _bin_weight_table(counts, "inverse_freq") if balanced else None,
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def align_bin_weights(
|
| 246 |
+
labels: list, table: dict[str, float | None] | None, *, neutral: float = 1.0
|
| 247 |
+
) -> np.ndarray:
|
| 248 |
+
"""One weight per row. A missing bin, or a row below 17 kt, stays neutral."""
|
| 249 |
+
if table is None:
|
| 250 |
+
return np.ones(len(labels), dtype=np.float64)
|
| 251 |
+
out = np.empty(len(labels), dtype=np.float64)
|
| 252 |
+
for index, label in enumerate(labels):
|
| 253 |
+
weight = None if label is None else table.get(str(label))
|
| 254 |
+
out[index] = float(neutral if weight is None else weight)
|
| 255 |
+
return out
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def annotate_balance(frame: pd.DataFrame, balance: dict, config: dict) -> pd.DataFrame:
|
| 259 |
+
"""Record the project bin and the loss weight on every row.
|
| 260 |
+
|
| 261 |
+
Val and test stay at weight 1. They are not in the frequency table.
|
| 262 |
+
``none`` writes 1 on every row and the training loop does not weight
|
| 263 |
+
the loss.
|
| 264 |
+
"""
|
| 265 |
+
out = frame.copy()
|
| 266 |
+
labels = project_labels(out, config, str(balance["wind_column"]))
|
| 267 |
+
out["intensity_bin"] = ["" if label is None else str(label) for label in labels]
|
| 268 |
+
if balance["loss_weighting"] == "none":
|
| 269 |
+
out["loss_weight"] = np.ones(len(out), dtype=np.float64)
|
| 270 |
+
return out
|
| 271 |
+
weights = align_bin_weights(labels, balance["weights"])
|
| 272 |
+
train = out["split"].astype(str).eq("train").to_numpy()
|
| 273 |
+
applied = np.ones(len(out), dtype=np.float64)
|
| 274 |
+
applied[train] = weights[train]
|
| 275 |
+
out["loss_weight"] = applied
|
| 276 |
+
return out
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def balance_record(balance: dict) -> dict:
|
| 280 |
+
"""JSON-safe copy of the weight table for the run manifest."""
|
| 281 |
+
|
| 282 |
+
def _weights(table: dict | None) -> dict | None:
|
| 283 |
+
if table is None:
|
| 284 |
+
return None
|
| 285 |
+
return {str(name): None if value is None else float(value) for name, value in table.items()}
|
| 286 |
+
|
| 287 |
+
return {
|
| 288 |
+
"loss_weighting": balance["loss_weighting"],
|
| 289 |
+
"balanced_sampling": bool(balance["balanced_sampling"]),
|
| 290 |
+
"source": balance["source"],
|
| 291 |
+
"split_strategy": balance["split_strategy"],
|
| 292 |
+
"wind_column": balance["wind_column"],
|
| 293 |
+
"n_frequency_rows": int(balance["n_frequency_rows"]),
|
| 294 |
+
"n_below_lowest_edge": int(balance["n_below_lowest_edge"]),
|
| 295 |
+
"counts": {str(name): int(count) for name, count in balance["counts"].items()},
|
| 296 |
+
"weights": _weights(balance["weights"]),
|
| 297 |
+
"sampling_weights": _weights(balance["sampling_weights"]),
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def is_on_fix(value: object) -> bool:
|
| 302 |
+
"""True only when the flag is explicitly true. Unknown is not on-fix."""
|
| 303 |
+
if isinstance(value, (bool, np.bool_)):
|
| 304 |
+
return bool(value)
|
| 305 |
+
if value is None or value is pd.NA:
|
| 306 |
+
return False
|
| 307 |
+
try:
|
| 308 |
+
missing = pd.isna(value)
|
| 309 |
+
except (TypeError, ValueError):
|
| 310 |
+
missing = False
|
| 311 |
+
if isinstance(missing, (bool, np.bool_)) and bool(missing):
|
| 312 |
+
return False
|
| 313 |
+
return str(value).strip().lower() in {"1", "true", "yes", "y", "t"}
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def on_fix_metrics(
|
| 317 |
+
truth: np.ndarray, pred: np.ndarray, flags, config: dict
|
| 318 |
+
) -> dict:
|
| 319 |
+
"""Validation metrics on explicit on-fix rows. Unknown rows stay out."""
|
| 320 |
+
mask = np.asarray([is_on_fix(value) for value in list(flags)], dtype=bool)
|
| 321 |
+
truth_arr = np.asarray(truth, dtype=np.float64).reshape(-1)
|
| 322 |
+
pred_arr = np.asarray(pred, dtype=np.float64).reshape(-1)
|
| 323 |
+
if mask.shape[0] != truth_arr.shape[0] or pred_arr.shape[0] != truth_arr.shape[0]:
|
| 324 |
+
raise ValueError("on_fix flags must align with the validation rows")
|
| 325 |
+
return _score_split(truth_arr[mask], pred_arr[mask], config)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def project_labels(
|
| 329 |
+
frame: pd.DataFrame, config: dict, wind_column: str = "wind_speed_kt"
|
| 330 |
+
) -> list[str | None]:
|
| 331 |
+
"""Project class names, only when one wind-averaging period is recorded.
|
| 332 |
+
|
| 333 |
+
These names are the project's grouping, not official IMD classes.
|
| 334 |
+
A missing or mixed period raises instead of leaving the names blank.
|
| 335 |
+
``wind_column`` is the training target. INCYDE's own IMD class is the
|
| 336 |
+
``imd_class`` column, computed on the 3-minute label.
|
| 337 |
+
"""
|
| 338 |
+
recorded_wind_averaging(frame)
|
| 339 |
+
edges = tuple(float(edge) for edge in config["data"]["imd5_edges_kt"])
|
| 340 |
+
names = tuple(str(name) for name in config["data"]["imd5_names"])
|
| 341 |
+
return [
|
| 342 |
+
wind_to_imd5(float(wind), edges, names) for wind in frame[wind_column]
|
| 343 |
+
]
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def manifest_is_synthetic(frame: pd.DataFrame) -> bool:
|
| 347 |
+
"""True when any row is explicitly synthetic.
|
| 348 |
+
|
| 349 |
+
A missing column or a null flag raises. Null is not treated as real,
|
| 350 |
+
and one synthetic row keeps the whole manifest marked synthetic.
|
| 351 |
+
"""
|
| 352 |
+
if "is_synthetic" not in frame.columns:
|
| 353 |
+
raise SchemaError(
|
| 354 |
+
"is_synthetic is required so a synthetic row cannot be read as real"
|
| 355 |
+
)
|
| 356 |
+
flags = [parse_is_synthetic(value) for value in frame["is_synthetic"].tolist()]
|
| 357 |
+
return any(flags)
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
_TRAIN_KEYS = (
|
| 361 |
+
"batch_size",
|
| 362 |
+
"epochs",
|
| 363 |
+
"lr",
|
| 364 |
+
"weight_decay",
|
| 365 |
+
"patience",
|
| 366 |
+
"class_loss_weight",
|
| 367 |
+
"size_loss_weight",
|
| 368 |
+
"grad_accum_steps",
|
| 369 |
+
"num_workers",
|
| 370 |
+
"device_parity_tol",
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
LAST_CHECKPOINT = "last.pt"
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def _require_train_block(config: dict) -> dict:
|
| 377 |
+
train_cfg = config.get("train")
|
| 378 |
+
if not isinstance(train_cfg, dict):
|
| 379 |
+
raise ValueError("config train is required")
|
| 380 |
+
missing = [key for key in _TRAIN_KEYS if key not in train_cfg]
|
| 381 |
+
if missing:
|
| 382 |
+
raise ValueError(f"config train missing {missing}")
|
| 383 |
+
return train_cfg
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def assert_normalize(config: dict) -> None:
|
| 387 |
+
"""The deep path standardizes with train-split mean and std."""
|
| 388 |
+
mode = config["data"]["normalize"]
|
| 389 |
+
if str(mode) != "zscore":
|
| 390 |
+
raise ValueError("data.normalize must be zscore")
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def recorded_wind_period(frame: pd.DataFrame) -> str | None:
|
| 394 |
+
"""The single ``wind_averaging`` value on a manifest, if the column exists."""
|
| 395 |
+
if "wind_averaging" not in frame.columns:
|
| 396 |
+
return None
|
| 397 |
+
periods = sorted({str(value) for value in frame["wind_averaging"].dropna().unique()})
|
| 398 |
+
if len(periods) != 1:
|
| 399 |
+
return None
|
| 400 |
+
return periods[0]
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def assert_wind_averaging(config: dict, frame: pd.DataFrame) -> str | None:
|
| 404 |
+
"""Require ``data.wind_averaging`` and refuse a manifest that disagrees.
|
| 405 |
+
|
| 406 |
+
A manifest with no period column does not inherit the config value.
|
| 407 |
+
Project class names stay off until the column records one period.
|
| 408 |
+
"""
|
| 409 |
+
declared = config["data"]["wind_averaging"]
|
| 410 |
+
if declared is None or str(declared).strip() == "":
|
| 411 |
+
raise ValueError("config data.wind_averaging is required")
|
| 412 |
+
declared_text = str(declared)
|
| 413 |
+
observed = recorded_wind_period(frame)
|
| 414 |
+
if observed is not None and observed != declared_text:
|
| 415 |
+
raise ValueError(
|
| 416 |
+
f"manifest wind_averaging is {observed} but config data.wind_averaging "
|
| 417 |
+
f"is {declared_text}. Do not mix averaging periods."
|
| 418 |
+
)
|
| 419 |
+
return observed
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def split_frame(frame: pd.DataFrame, config: dict) -> pd.DataFrame:
|
| 423 |
+
split_cfg = config["split"]
|
| 424 |
+
holdout_years = split_cfg["holdout_years"] or []
|
| 425 |
+
holdout_basin = split_cfg["holdout_basin"] or None
|
| 426 |
+
assigned = assign_storms(
|
| 427 |
+
frame,
|
| 428 |
+
str(split_cfg["strategy"]),
|
| 429 |
+
test_fraction=float(split_cfg["test_fraction"]),
|
| 430 |
+
val_fraction=float(split_cfg["val_fraction"]),
|
| 431 |
+
seed=int(split_cfg["seed"]),
|
| 432 |
+
holdout_years=[int(year) for year in holdout_years],
|
| 433 |
+
holdout_basin=None if holdout_basin in (None, "null", "") else str(holdout_basin),
|
| 434 |
+
)
|
| 435 |
+
if "prev_sample_id" not in assigned.columns:
|
| 436 |
+
assigned = add_previous_frame_id(assigned)
|
| 437 |
+
assigned, _dropped = null_cross_split_links(assigned)
|
| 438 |
+
return assigned
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def stack_split(
|
| 442 |
+
frame: pd.DataFrame,
|
| 443 |
+
manifest_path: Path,
|
| 444 |
+
split_name: str,
|
| 445 |
+
image_size: int | str | None,
|
| 446 |
+
stats: NormStats | None,
|
| 447 |
+
max_missing_fraction: float,
|
| 448 |
+
) -> tuple[np.ndarray, np.ndarray, list[str | None]]:
|
| 449 |
+
rows = frame[frame["split"] == split_name].reset_index(drop=True)
|
| 450 |
+
if rows.empty:
|
| 451 |
+
raise ValueError(f"split {split_name} has no rows")
|
| 452 |
+
labels = [None if pd.isna(value) else str(value) for value in rows["_class"]]
|
| 453 |
+
images = []
|
| 454 |
+
winds = []
|
| 455 |
+
for row in rows.itertuples(index=False):
|
| 456 |
+
path = resolve_image(manifest_path, row.image_path)
|
| 457 |
+
images.append(
|
| 458 |
+
prepare_image(load_image(path), image_size, stats, max_missing_fraction)
|
| 459 |
+
)
|
| 460 |
+
winds.append(float(row.wind_speed_kt))
|
| 461 |
+
return stack_prepared(images), np.asarray(winds, dtype=np.float32), labels
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def _set_seed(seed: int) -> None:
|
| 465 |
+
random.seed(seed)
|
| 466 |
+
np.random.seed(seed)
|
| 467 |
+
torch = _torch()
|
| 468 |
+
torch.manual_seed(seed)
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
def _torch():
|
| 472 |
+
import torch
|
| 473 |
+
|
| 474 |
+
return torch
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def build_loader(
|
| 478 |
+
dataset, *, batch_size: int, shuffle: bool, num_workers: int, generator=None, sampler=None
|
| 479 |
+
):
|
| 480 |
+
"""DataLoader with ``persistent_workers`` whenever workers are used.
|
| 481 |
+
|
| 482 |
+
``num_workers`` comes from ``train.num_workers``. Zero workers load in
|
| 483 |
+
the parent process and do not set ``persistent_workers``. A balanced
|
| 484 |
+
sampler replaces shuffle. The sampler carries its own generator.
|
| 485 |
+
"""
|
| 486 |
+
from torch.utils.data import DataLoader
|
| 487 |
+
|
| 488 |
+
workers = int(num_workers)
|
| 489 |
+
if workers < 0:
|
| 490 |
+
raise ValueError("train.num_workers must be >= 0")
|
| 491 |
+
if sampler is not None and shuffle:
|
| 492 |
+
raise ValueError("balanced sampling does not also shuffle the loader")
|
| 493 |
+
kwargs = {
|
| 494 |
+
"batch_size": int(batch_size),
|
| 495 |
+
"shuffle": bool(shuffle) if sampler is None else False,
|
| 496 |
+
"num_workers": workers,
|
| 497 |
+
}
|
| 498 |
+
if sampler is not None:
|
| 499 |
+
kwargs["sampler"] = sampler
|
| 500 |
+
elif generator is not None:
|
| 501 |
+
kwargs["generator"] = generator
|
| 502 |
+
if workers > 0:
|
| 503 |
+
kwargs["persistent_workers"] = True
|
| 504 |
+
return DataLoader(dataset, **kwargs)
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def make_balanced_sampler(weights: np.ndarray, num_samples: int, seed: int):
|
| 508 |
+
"""Draw with replacement so every positive-weight bin can appear.
|
| 509 |
+
|
| 510 |
+
``num_samples`` is one epoch. Weights are the inverse-frequency table
|
| 511 |
+
from the train originals. A zero-sum table is refused.
|
| 512 |
+
"""
|
| 513 |
+
torch = _torch()
|
| 514 |
+
from torch.utils.data import WeightedRandomSampler
|
| 515 |
+
|
| 516 |
+
values = np.asarray(weights, dtype=np.float64).reshape(-1)
|
| 517 |
+
if values.size == 0 or not np.isfinite(values).all() or np.any(values < 0):
|
| 518 |
+
raise ValueError("balanced sampling weights must be finite and non-negative")
|
| 519 |
+
if float(values.sum()) <= 0:
|
| 520 |
+
raise ValueError("balanced sampling weights must have a positive sum")
|
| 521 |
+
generator = torch.Generator()
|
| 522 |
+
generator.manual_seed(int(seed))
|
| 523 |
+
return WeightedRandomSampler(
|
| 524 |
+
weights=torch.as_tensor(values, dtype=torch.double),
|
| 525 |
+
num_samples=int(num_samples),
|
| 526 |
+
replacement=True,
|
| 527 |
+
generator=generator,
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
class ArrayFrames:
|
| 532 |
+
"""In-memory frames. Module-level so Windows workers can unpickle it."""
|
| 533 |
+
|
| 534 |
+
def __init__(self, images, winds, labels, known: list[str], sample_weight, size=None) -> None:
|
| 535 |
+
torch = _torch()
|
| 536 |
+
index = {name: position for position, name in enumerate(known)}
|
| 537 |
+
class_index = [index.get(label, -1) if label is not None else -1 for label in labels]
|
| 538 |
+
self.images = torch.from_numpy(np.ascontiguousarray(images))
|
| 539 |
+
self.winds = torch.from_numpy(np.asarray(winds, dtype=np.float32)).view(-1, 1)
|
| 540 |
+
self.class_index = torch.tensor(class_index, dtype=torch.long)
|
| 541 |
+
self.sample_weight = torch.tensor(np.asarray(sample_weight), dtype=torch.float32)
|
| 542 |
+
self.size = None if size is None else torch.tensor(np.asarray(size), dtype=torch.float32)
|
| 543 |
+
|
| 544 |
+
def __len__(self) -> int:
|
| 545 |
+
return int(self.images.shape[0])
|
| 546 |
+
|
| 547 |
+
def __getitem__(self, item: int):
|
| 548 |
+
row = (
|
| 549 |
+
self.images[item],
|
| 550 |
+
self.winds[item],
|
| 551 |
+
self.class_index[item],
|
| 552 |
+
self.sample_weight[item],
|
| 553 |
+
)
|
| 554 |
+
if self.size is None:
|
| 555 |
+
return row
|
| 556 |
+
return row + (self.size[item],)
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
class PathFrames:
|
| 560 |
+
"""Load one frame per item so DataLoader workers stay on small files.
|
| 561 |
+
|
| 562 |
+
A cache path is an fp16 ``.npy``. A source path is whatever the
|
| 563 |
+
manifest already pointed at. Normalization uses the train-split stats
|
| 564 |
+
for this dataset only.
|
| 565 |
+
"""
|
| 566 |
+
|
| 567 |
+
def __init__(
|
| 568 |
+
self,
|
| 569 |
+
records: list[dict],
|
| 570 |
+
image_size: int | None,
|
| 571 |
+
mean: float | None,
|
| 572 |
+
std: float | None,
|
| 573 |
+
max_missing: float,
|
| 574 |
+
known: list[str],
|
| 575 |
+
) -> None:
|
| 576 |
+
self.records = list(records)
|
| 577 |
+
self.image_size = image_size
|
| 578 |
+
self.mean = None if mean is None else float(mean)
|
| 579 |
+
self.std = None if std is None else float(std)
|
| 580 |
+
self.max_missing = float(max_missing)
|
| 581 |
+
self.known = list(known)
|
| 582 |
+
self._index = {name: position for position, name in enumerate(known)}
|
| 583 |
+
|
| 584 |
+
def __len__(self) -> int:
|
| 585 |
+
return len(self.records)
|
| 586 |
+
|
| 587 |
+
def __getitem__(self, item: int):
|
| 588 |
+
torch = _torch()
|
| 589 |
+
row = self.records[item]
|
| 590 |
+
stats = None
|
| 591 |
+
if self.mean is not None and self.std is not None:
|
| 592 |
+
stats = NormStats(mean=self.mean, std=self.std, source_split="train")
|
| 593 |
+
image = load_image(row["path"])
|
| 594 |
+
angle = row.get("angle")
|
| 595 |
+
if angle is not None and pd.isna(angle):
|
| 596 |
+
angle = None
|
| 597 |
+
image = prepare_training_chip(image, self.image_size, angle, stats, self.max_missing)
|
| 598 |
+
label = row["label"]
|
| 599 |
+
class_index = self._index.get(label, -1) if label is not None else -1
|
| 600 |
+
return (
|
| 601 |
+
torch.from_numpy(np.ascontiguousarray(image)),
|
| 602 |
+
torch.tensor([float(row["wind"])], dtype=torch.float32),
|
| 603 |
+
torch.tensor(class_index, dtype=torch.long),
|
| 604 |
+
torch.tensor(float(row["weight"]), dtype=torch.float32),
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def uses_sequences(config: dict) -> bool:
|
| 609 |
+
return str(config["model"]["name"]) == "convlstm"
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
def train_size_head(frame: pd.DataFrame) -> bool:
|
| 613 |
+
"""Turn the size head on only when the train split has size labels."""
|
| 614 |
+
rows = frame[frame["split"] == "train"] if "split" in frame.columns else frame
|
| 615 |
+
return size_targets_present(rows)
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def model_n_frames(config: dict) -> int:
|
| 619 |
+
if not uses_sequences(config):
|
| 620 |
+
return 1
|
| 621 |
+
requested = int(config["model"]["n_frames"])
|
| 622 |
+
if requested != N_FRAMES:
|
| 623 |
+
raise ValueError(f"ConvLSTM uses {N_FRAMES} frames")
|
| 624 |
+
return requested
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def build_backbone(config: dict):
|
| 628 |
+
"""Build the image backbone. Refuses an ImageNet download by default."""
|
| 629 |
+
from src.model import ConvLSTMRegressor, ResNetRegressor, SimpleCNN
|
| 630 |
+
|
| 631 |
+
model_cfg = config["model"]
|
| 632 |
+
pretrained = bool(model_cfg["pretrained"])
|
| 633 |
+
if pretrained and os.environ.get("CLOUDIE_ALLOW_PRETRAINED") != "1":
|
| 634 |
+
raise RuntimeError(
|
| 635 |
+
"pretrained: true downloads ImageNet weights and must not run in CI. "
|
| 636 |
+
"Set CLOUDIE_ALLOW_PRETRAINED=1 only for a local run that intends the download."
|
| 637 |
+
)
|
| 638 |
+
name = str(model_cfg["name"])
|
| 639 |
+
dropout = float(model_cfg["dropout"])
|
| 640 |
+
channels = int(config["data"]["channels"])
|
| 641 |
+
if name == "simple_cnn":
|
| 642 |
+
return SimpleCNN(in_channels=channels, dropout=dropout)
|
| 643 |
+
if name == "resnet18":
|
| 644 |
+
return ResNetRegressor(in_channels=channels, pretrained=pretrained, dropout=dropout)
|
| 645 |
+
if name == "convlstm":
|
| 646 |
+
return ConvLSTMRegressor(
|
| 647 |
+
in_channels=channels,
|
| 648 |
+
hidden=int(model_cfg["hidden"]),
|
| 649 |
+
n_frames=model_n_frames(config),
|
| 650 |
+
dropout=dropout,
|
| 651 |
+
)
|
| 652 |
+
raise ValueError(f"unknown model {name}")
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
def build_net(config: dict, size_head: bool = False):
|
| 656 |
+
"""Wind and class heads. The size head exists only when labels do.
|
| 657 |
+
|
| 658 |
+
The size head reads image features. It does not take wind speed.
|
| 659 |
+
"""
|
| 660 |
+
torch = _torch()
|
| 661 |
+
from torch import nn
|
| 662 |
+
|
| 663 |
+
backbone = build_backbone(config)
|
| 664 |
+
n_classes = len(config["data"]["imd5_names"])
|
| 665 |
+
|
| 666 |
+
class _Net(nn.Module):
|
| 667 |
+
def __init__(self) -> None:
|
| 668 |
+
super().__init__()
|
| 669 |
+
self.backbone = backbone
|
| 670 |
+
self.class_head = nn.Linear(int(backbone.feature_dim), n_classes)
|
| 671 |
+
self.size_head = (
|
| 672 |
+
nn.Linear(int(backbone.feature_dim), 2) if size_head else None
|
| 673 |
+
)
|
| 674 |
+
|
| 675 |
+
def forward(self, inputs: torch.Tensor):
|
| 676 |
+
features = self.backbone.encode(inputs)
|
| 677 |
+
wind = self.backbone.head(features)
|
| 678 |
+
logits = self.class_head(features)
|
| 679 |
+
if self.size_head is None:
|
| 680 |
+
return wind, logits
|
| 681 |
+
return wind, logits, self.size_head(features)
|
| 682 |
+
|
| 683 |
+
return _Net()
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
def _wind_loss(prediction, target, sample_weight):
|
| 687 |
+
import torch.nn.functional as F
|
| 688 |
+
|
| 689 |
+
per_row = F.smooth_l1_loss(prediction.view(-1), target.view(-1), reduction="none")
|
| 690 |
+
if sample_weight is None:
|
| 691 |
+
return per_row.mean()
|
| 692 |
+
weight = sample_weight.view(-1)
|
| 693 |
+
return (per_row * weight).sum() / weight.sum().clamp_min(1e-8)
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
def batch_wind_loss(prediction, target, sample_weight, loss_weighting: str):
|
| 697 |
+
"""Smooth L1 for one batch.
|
| 698 |
+
|
| 699 |
+
``none`` is the unweighted mean, including when the rows carry a
|
| 700 |
+
weight column. Other modes use that column. The mean of the weighted
|
| 701 |
+
terms is divided by the weight sum, not by the row count.
|
| 702 |
+
"""
|
| 703 |
+
import torch.nn.functional as F
|
| 704 |
+
|
| 705 |
+
per_row = F.smooth_l1_loss(prediction.reshape(-1), target.reshape(-1), reduction="none")
|
| 706 |
+
if loss_weighting_mode(loss_weighting) == "none" or sample_weight is None:
|
| 707 |
+
return per_row.mean()
|
| 708 |
+
weight = sample_weight.reshape(-1)
|
| 709 |
+
return (per_row * weight).sum() / weight.sum().clamp_min(1e-8)
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
def _class_loss(logits, class_index, class_weight):
|
| 713 |
+
import torch.nn.functional as F
|
| 714 |
+
|
| 715 |
+
mask = class_index >= 0
|
| 716 |
+
if int(mask.sum()) == 0:
|
| 717 |
+
return logits.sum() * 0.0
|
| 718 |
+
return F.cross_entropy(logits[mask], class_index[mask], weight=class_weight)
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
def _size_loss(prediction, target):
|
| 722 |
+
"""Smooth L1 on finite R34 and RMW pairs. No term when none are finite."""
|
| 723 |
+
import torch
|
| 724 |
+
import torch.nn.functional as F
|
| 725 |
+
|
| 726 |
+
finite = torch.isfinite(target).all(dim=1)
|
| 727 |
+
if int(finite.sum()) == 0:
|
| 728 |
+
return prediction.sum() * 0.0
|
| 729 |
+
return F.smooth_l1_loss(prediction[finite], target[finite])
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
def _split_output(output):
|
| 733 |
+
if isinstance(output, tuple) and len(output) == 3:
|
| 734 |
+
return output[0], output[1], output[2]
|
| 735 |
+
wind, logits = output
|
| 736 |
+
return wind, logits, None
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
def _run_epoch(
|
| 740 |
+
model,
|
| 741 |
+
loader,
|
| 742 |
+
optimizer,
|
| 743 |
+
class_weight,
|
| 744 |
+
class_loss_weight: float,
|
| 745 |
+
train: bool,
|
| 746 |
+
size_loss_weight: float = 0.0,
|
| 747 |
+
grad_accum_steps: int = 1,
|
| 748 |
+
):
|
| 749 |
+
torch = _torch()
|
| 750 |
+
accum = int(grad_accum_steps)
|
| 751 |
+
if accum < 1:
|
| 752 |
+
raise ValueError("train.grad_accum_steps must be at least 1")
|
| 753 |
+
model.train(train)
|
| 754 |
+
total = 0.0
|
| 755 |
+
count = 0
|
| 756 |
+
pending = 0
|
| 757 |
+
if train:
|
| 758 |
+
optimizer.zero_grad(set_to_none=True)
|
| 759 |
+
for batch in loader:
|
| 760 |
+
images, winds, class_index, sample_weight = batch[0], batch[1], batch[2], batch[3]
|
| 761 |
+
size_target = batch[4] if len(batch) > 4 else None
|
| 762 |
+
with torch.set_grad_enabled(train):
|
| 763 |
+
wind_hat, logits, size_hat = _split_output(model(images))
|
| 764 |
+
monitor = _wind_loss(wind_hat, winds, None)
|
| 765 |
+
loss = _wind_loss(wind_hat, winds, sample_weight) if train else monitor
|
| 766 |
+
if train and class_loss_weight > 0:
|
| 767 |
+
loss = loss + class_loss_weight * _class_loss(logits, class_index, class_weight)
|
| 768 |
+
if (
|
| 769 |
+
train
|
| 770 |
+
and size_hat is not None
|
| 771 |
+
and size_target is not None
|
| 772 |
+
and size_loss_weight > 0
|
| 773 |
+
):
|
| 774 |
+
loss = loss + size_loss_weight * _size_loss(size_hat, size_target)
|
| 775 |
+
if train:
|
| 776 |
+
(loss / accum).backward()
|
| 777 |
+
pending += 1
|
| 778 |
+
if pending == accum:
|
| 779 |
+
optimizer.step()
|
| 780 |
+
optimizer.zero_grad(set_to_none=True)
|
| 781 |
+
pending = 0
|
| 782 |
+
batch_rows = int(images.shape[0])
|
| 783 |
+
total += float(monitor.detach()) * batch_rows
|
| 784 |
+
count += batch_rows
|
| 785 |
+
if train and pending:
|
| 786 |
+
optimizer.step()
|
| 787 |
+
optimizer.zero_grad(set_to_none=True)
|
| 788 |
+
if count == 0:
|
| 789 |
+
raise ValueError("loader produced no rows")
|
| 790 |
+
return total / count
|
| 791 |
+
|
| 792 |
+
|
| 793 |
+
def _dataset(
|
| 794 |
+
images,
|
| 795 |
+
winds,
|
| 796 |
+
labels,
|
| 797 |
+
known: list[str],
|
| 798 |
+
sample_weight: np.ndarray,
|
| 799 |
+
size: np.ndarray | None = None,
|
| 800 |
+
):
|
| 801 |
+
return ArrayFrames(images, winds, labels, known, sample_weight, size)
|
| 802 |
+
|
| 803 |
+
|
| 804 |
+
def _aligned_size(frame: pd.DataFrame, split_name: str) -> np.ndarray:
|
| 805 |
+
rows = frame[frame["split"] == split_name].reset_index(drop=True)
|
| 806 |
+
values = rows[["r34_nmi", "rmw_nmi"]].apply(pd.to_numeric, errors="coerce")
|
| 807 |
+
return values.to_numpy(dtype=np.float32)
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
def _load_examples(
|
| 811 |
+
config: dict,
|
| 812 |
+
frame: pd.DataFrame,
|
| 813 |
+
manifest: Path,
|
| 814 |
+
split_name: str,
|
| 815 |
+
stats: NormStats | None,
|
| 816 |
+
size_head: bool,
|
| 817 |
+
):
|
| 818 |
+
image_size = parse_image_size(config["data"]["image_size"])
|
| 819 |
+
max_missing = float(config["data"]["max_missing_fraction"])
|
| 820 |
+
wind_column = config.get("labels", {}).get("label_column", "wind_speed_kt")
|
| 821 |
+
if wind_column not in frame.columns:
|
| 822 |
+
wind_column = "wind_speed_kt"
|
| 823 |
+
if uses_sequences(config):
|
| 824 |
+
images, winds, labels, size = stack_windows(
|
| 825 |
+
frame,
|
| 826 |
+
manifest,
|
| 827 |
+
split_name,
|
| 828 |
+
image_size,
|
| 829 |
+
stats,
|
| 830 |
+
max_missing,
|
| 831 |
+
model_n_frames(config),
|
| 832 |
+
wind_column=wind_column,
|
| 833 |
+
)
|
| 834 |
+
return images, winds, labels, size if size_head else None
|
| 835 |
+
images, winds, labels = stack_split(
|
| 836 |
+
frame, manifest, split_name, image_size, stats, max_missing
|
| 837 |
+
)
|
| 838 |
+
size = _aligned_size(frame, split_name) if size_head else None
|
| 839 |
+
return images, winds, labels, size
|
| 840 |
+
|
| 841 |
+
|
| 842 |
+
def fit_split_normalization(
|
| 843 |
+
frame: pd.DataFrame, manifest: str | Path, config: dict
|
| 844 |
+
) -> NormStats:
|
| 845 |
+
"""Fit pixel mean and std on the train split only.
|
| 846 |
+
|
| 847 |
+
The images are the train split. ``data.image_size`` comes from config.
|
| 848 |
+
``native`` keeps each chip's height and width.
|
| 849 |
+
A later held-out coverage check reuses ``storm_ids_by_split`` and these
|
| 850 |
+
stored stats.
|
| 851 |
+
"""
|
| 852 |
+
groups = storm_ids_by_split(frame)
|
| 853 |
+
if not groups["train"]:
|
| 854 |
+
raise LeakageError("normalization stats may be fit on the train split only")
|
| 855 |
+
if uses_sequences(config):
|
| 856 |
+
raw_images, _winds, _labels, _size = _load_examples(
|
| 857 |
+
config, frame, Path(manifest), "train", None, False
|
| 858 |
+
)
|
| 859 |
+
norm_frames = [
|
| 860 |
+
raw_images[index, step]
|
| 861 |
+
for index in range(raw_images.shape[0])
|
| 862 |
+
for step in range(raw_images.shape[1])
|
| 863 |
+
]
|
| 864 |
+
return fit_norm_stats(norm_frames, "train")
|
| 865 |
+
|
| 866 |
+
image_size = parse_image_size(config["data"]["image_size"])
|
| 867 |
+
max_missing = float(config["data"]["max_missing_fraction"])
|
| 868 |
+
rows = frame[frame["split"] == "train"]
|
| 869 |
+
if rows.empty:
|
| 870 |
+
raise LeakageError("normalization stats may be fit on the train split only")
|
| 871 |
+
manifest_path = Path(manifest)
|
| 872 |
+
count = 0
|
| 873 |
+
total = 0.0
|
| 874 |
+
total_sq = 0.0
|
| 875 |
+
for row in rows.itertuples(index=False):
|
| 876 |
+
path = resolve_image(manifest_path, row.image_path)
|
| 877 |
+
img = prepare_image(load_image(path), image_size, None, max_missing)
|
| 878 |
+
finite = img[np.isfinite(img)]
|
| 879 |
+
if finite.size > 0:
|
| 880 |
+
finite64 = finite.astype(np.float64, copy=False)
|
| 881 |
+
count += int(finite64.size)
|
| 882 |
+
total += float(finite64.sum())
|
| 883 |
+
total_sq += float((finite64 * finite64).sum())
|
| 884 |
+
if count == 0:
|
| 885 |
+
raise ValueError("train images have no finite pixels")
|
| 886 |
+
mean = float(total / count)
|
| 887 |
+
var = max(0.0, float((total_sq / count) - (mean ** 2)))
|
| 888 |
+
std = float(np.sqrt(var))
|
| 889 |
+
if std < 1e-6:
|
| 890 |
+
std = 1.0
|
| 891 |
+
return NormStats(mean=mean, std=std, source_split="train")
|
| 892 |
+
|
| 893 |
+
|
| 894 |
+
def train(config: dict, manifest_path: str | Path | None = None) -> Path:
|
| 895 |
+
"""Fit on the train split and write the checkpoint named in ``paths``."""
|
| 896 |
+
assert_model_inputs(("image",))
|
| 897 |
+
train_cfg = _require_train_block(config)
|
| 898 |
+
assert_normalize(config)
|
| 899 |
+
manifest = Path(manifest_path or config["paths"]["manifest"])
|
| 900 |
+
frame = load_manifest(manifest)
|
| 901 |
+
wind_period = assert_wind_averaging(config, frame)
|
| 902 |
+
torch = _torch()
|
| 903 |
+
|
| 904 |
+
seed = int(config["project"]["seed"])
|
| 905 |
+
_set_seed(seed)
|
| 906 |
+
synthetic = manifest_is_synthetic(frame)
|
| 907 |
+
assigned = split_frame(frame, config)
|
| 908 |
+
assigned["_class"] = project_labels(assigned, config)
|
| 909 |
+
image_size = parse_image_size(config["data"]["image_size"])
|
| 910 |
+
max_missing = float(config["data"]["max_missing_fraction"])
|
| 911 |
+
# Size labels are a training-fold decision, same as class weights.
|
| 912 |
+
size_head = train_size_head(assigned)
|
| 913 |
+
n_frames = model_n_frames(config)
|
| 914 |
+
stats = fit_split_normalization(assigned, manifest, config)
|
| 915 |
+
train_images, train_winds, train_labels, train_size = _load_examples(
|
| 916 |
+
config, assigned, manifest, "train", stats, size_head
|
| 917 |
+
)
|
| 918 |
+
val_images, val_winds, val_labels, val_size = _load_examples(
|
| 919 |
+
config, assigned, manifest, "val", stats, size_head
|
| 920 |
+
)
|
| 921 |
+
known = [str(name) for name in config["data"]["imd5_names"]]
|
| 922 |
+
sample_weight, class_weight_np = class_sample_weights(train_labels, known)
|
| 923 |
+
# Validation uses weight 1. The class weights stay the train fold's.
|
| 924 |
+
val_weight = np.ones(len(val_labels), dtype=np.float64)
|
| 925 |
+
batch_size = int(train_cfg["batch_size"])
|
| 926 |
+
workers = int(train_cfg["num_workers"])
|
| 927 |
+
grad_accum_steps = int(train_cfg["grad_accum_steps"])
|
| 928 |
+
generator = torch.Generator()
|
| 929 |
+
generator.manual_seed(seed)
|
| 930 |
+
train_loader = build_loader(
|
| 931 |
+
_dataset(train_images, train_winds, train_labels, known, sample_weight, train_size),
|
| 932 |
+
batch_size=batch_size,
|
| 933 |
+
shuffle=True,
|
| 934 |
+
num_workers=workers,
|
| 935 |
+
generator=generator,
|
| 936 |
+
)
|
| 937 |
+
val_loader = build_loader(
|
| 938 |
+
_dataset(val_images, val_winds, val_labels, known, val_weight, val_size),
|
| 939 |
+
batch_size=batch_size,
|
| 940 |
+
shuffle=False,
|
| 941 |
+
num_workers=workers,
|
| 942 |
+
)
|
| 943 |
+
model = build_net(config, size_head=size_head)
|
| 944 |
+
optimizer = torch.optim.AdamW(
|
| 945 |
+
model.parameters(),
|
| 946 |
+
lr=float(train_cfg["lr"]),
|
| 947 |
+
weight_decay=float(train_cfg["weight_decay"]),
|
| 948 |
+
)
|
| 949 |
+
class_weight = torch.tensor(class_weight_np, dtype=torch.float32)
|
| 950 |
+
class_loss_weight = float(train_cfg["class_loss_weight"])
|
| 951 |
+
size_loss_weight = float(train_cfg["size_loss_weight"]) if size_head else 0.0
|
| 952 |
+
stopper = EarlyStopping(int(train_cfg["patience"]))
|
| 953 |
+
epochs = int(train_cfg["epochs"])
|
| 954 |
+
last_epoch = 0
|
| 955 |
+
for epoch in range(epochs):
|
| 956 |
+
last_epoch = epoch
|
| 957 |
+
_run_epoch(
|
| 958 |
+
model,
|
| 959 |
+
train_loader,
|
| 960 |
+
optimizer,
|
| 961 |
+
class_weight,
|
| 962 |
+
class_loss_weight,
|
| 963 |
+
True,
|
| 964 |
+
size_loss_weight,
|
| 965 |
+
grad_accum_steps,
|
| 966 |
+
)
|
| 967 |
+
val_loss = _run_epoch(
|
| 968 |
+
model,
|
| 969 |
+
val_loader,
|
| 970 |
+
optimizer,
|
| 971 |
+
class_weight,
|
| 972 |
+
class_loss_weight,
|
| 973 |
+
False,
|
| 974 |
+
size_loss_weight,
|
| 975 |
+
)
|
| 976 |
+
if not np.isfinite(val_loss):
|
| 977 |
+
raise RuntimeError("validation loss is not finite")
|
| 978 |
+
if stopper.update(val_loss, model.state_dict()):
|
| 979 |
+
break
|
| 980 |
+
if stopper.best_state is None:
|
| 981 |
+
raise RuntimeError("training produced no validation score")
|
| 982 |
+
model.load_state_dict(stopper.best_state)
|
| 983 |
+
checkpoint = checkpoint_path(config)
|
| 984 |
+
checkpoint.parent.mkdir(parents=True, exist_ok=True)
|
| 985 |
+
dataset_name = str(config["data"]["dataset"])
|
| 986 |
+
payload = {
|
| 987 |
+
"state_dict": {key: value.detach().cpu() for key, value in model.state_dict().items()},
|
| 988 |
+
"model_name": str(config["model"]["name"]),
|
| 989 |
+
"dropout": float(config["model"]["dropout"]),
|
| 990 |
+
"pretrained": False,
|
| 991 |
+
"in_channels": int(config["data"]["channels"]),
|
| 992 |
+
"n_classes": len(known),
|
| 993 |
+
"class_names": known,
|
| 994 |
+
"edges_kt": [float(edge) for edge in config["data"]["imd5_edges_kt"]],
|
| 995 |
+
"norm_mean": stats.mean,
|
| 996 |
+
"norm_std": stats.std,
|
| 997 |
+
"norm_source_split": stats.source_split,
|
| 998 |
+
"norm_by_dataset": norm_by_dataset(dataset_name, stats),
|
| 999 |
+
"dataset": dataset_name,
|
| 1000 |
+
"image_size": image_size,
|
| 1001 |
+
"max_missing_fraction": max_missing,
|
| 1002 |
+
"mean_baseline_kt": float(
|
| 1003 |
+
np.mean(
|
| 1004 |
+
assigned.loc[assigned["split"] == "train", "wind_speed_kt"].to_numpy(
|
| 1005 |
+
dtype=np.float64
|
| 1006 |
+
)
|
| 1007 |
+
)
|
| 1008 |
+
),
|
| 1009 |
+
"is_synthetic": synthetic,
|
| 1010 |
+
"wind_averaging": wind_period,
|
| 1011 |
+
"wind_averaging_s": wind_averaging_seconds(wind_period),
|
| 1012 |
+
"wind_averaging_by_split": split_wind_averaging(assigned),
|
| 1013 |
+
"split": {
|
| 1014 |
+
"strategy": str(config["split"]["strategy"]),
|
| 1015 |
+
"seed": int(config["split"]["seed"]),
|
| 1016 |
+
"test_fraction": float(config["split"]["test_fraction"]),
|
| 1017 |
+
"val_fraction": float(config["split"]["val_fraction"]),
|
| 1018 |
+
},
|
| 1019 |
+
"best_val_loss": stopper.best,
|
| 1020 |
+
"epoch": last_epoch,
|
| 1021 |
+
"present_as_forecast": False,
|
| 1022 |
+
"honesty": SMOKE_BANNER if synthetic else NOT_A_FORECAST,
|
| 1023 |
+
"n_frames": n_frames,
|
| 1024 |
+
"size_head": size_head,
|
| 1025 |
+
"hidden": int(config["model"]["hidden"]) if uses_sequences(config) else None,
|
| 1026 |
+
}
|
| 1027 |
+
torch.save(payload, checkpoint)
|
| 1028 |
+
if synthetic:
|
| 1029 |
+
print(SMOKE_BANNER)
|
| 1030 |
+
else:
|
| 1031 |
+
print(NOT_A_FORECAST)
|
| 1032 |
+
print(f"Wrote {checkpoint}")
|
| 1033 |
+
return checkpoint
|
| 1034 |
+
|
| 1035 |
+
|
| 1036 |
+
LOGGER = logging.getLogger("src.train")
|
| 1037 |
+
|
| 1038 |
+
# CLI names. simplecnn is the YAML name simple_cnn.
|
| 1039 |
+
_CLI_MODELS = {
|
| 1040 |
+
"simplecnn": "simple_cnn",
|
| 1041 |
+
"simple_cnn": "simple_cnn",
|
| 1042 |
+
"resnet18": "resnet18",
|
| 1043 |
+
"convlstm": "convlstm",
|
| 1044 |
+
}
|
| 1045 |
+
_DATASETS = ("nasa", "tcir", "incyde", "smoke")
|
| 1046 |
+
RUN_FILES = (
|
| 1047 |
+
"checkpoint",
|
| 1048 |
+
"resolved_config.yaml",
|
| 1049 |
+
"split_manifest.csv",
|
| 1050 |
+
"loss_curve.csv",
|
| 1051 |
+
"loss_curve.png",
|
| 1052 |
+
"metrics.json",
|
| 1053 |
+
)
|
| 1054 |
+
|
| 1055 |
+
|
| 1056 |
+
def canonical_model_name(name: str) -> str:
|
| 1057 |
+
"""Map the CLI model name onto ``model.name`` in the YAML."""
|
| 1058 |
+
key = str(name).strip().lower()
|
| 1059 |
+
if key not in _CLI_MODELS:
|
| 1060 |
+
raise ValueError("model must be simplecnn, resnet18, or convlstm")
|
| 1061 |
+
return _CLI_MODELS[key]
|
| 1062 |
+
|
| 1063 |
+
|
| 1064 |
+
def refuse_mixed_resolution(
|
| 1065 |
+
frame: pd.DataFrame, dataset: str, image_size: int | None = None
|
| 1066 |
+
) -> None:
|
| 1067 |
+
"""One dataset, one source resolution. NASA and TCIR stay in separate runs.
|
| 1068 |
+
|
| 1069 |
+
INCYDE crops are not one native size. A configured square resize is the
|
| 1070 |
+
training grid. ``native`` still refuses a mix.
|
| 1071 |
+
"""
|
| 1072 |
+
if frame.empty:
|
| 1073 |
+
raise ValueError(f"{dataset} frame has no rows")
|
| 1074 |
+
sizes: set[int] = set()
|
| 1075 |
+
if "orig_size" in frame.columns:
|
| 1076 |
+
sizes = {int(value) for value in frame["orig_size"].tolist()}
|
| 1077 |
+
elif {"native_height", "native_width"} <= set(frame.columns):
|
| 1078 |
+
sizes = {
|
| 1079 |
+
int(height) if int(height) == int(width) else -1
|
| 1080 |
+
for height, width in zip(frame["native_height"], frame["native_width"], strict=True)
|
| 1081 |
+
}
|
| 1082 |
+
if dataset == "incyde":
|
| 1083 |
+
if {"native_height", "native_width"} <= set(frame.columns):
|
| 1084 |
+
shapes = {
|
| 1085 |
+
(int(height), int(width))
|
| 1086 |
+
for height, width in zip(
|
| 1087 |
+
frame["native_height"], frame["native_width"], strict=True
|
| 1088 |
+
)
|
| 1089 |
+
}
|
| 1090 |
+
else:
|
| 1091 |
+
shapes = {(int(value), int(value)) for value in sizes}
|
| 1092 |
+
if len(shapes) > 1 and image_size is None:
|
| 1093 |
+
raise ValueError(
|
| 1094 |
+
"INCYDE frames mix native sizes "
|
| 1095 |
+
f"{sorted(shapes)} and data.image_size is native. "
|
| 1096 |
+
"Set a square image_size so corner bars are not a second grid."
|
| 1097 |
+
)
|
| 1098 |
+
return
|
| 1099 |
+
if len(sizes) > 1:
|
| 1100 |
+
raise ValueError(
|
| 1101 |
+
f"refusing a {dataset} batch that mixes resolutions {sorted(sizes)}. "
|
| 1102 |
+
"NASA and TCIR runs stay separate."
|
| 1103 |
+
)
|
| 1104 |
+
if dataset == "nasa" and sizes:
|
| 1105 |
+
from src.nasa_tc import WORKING_SIZE
|
| 1106 |
+
|
| 1107 |
+
if sizes != {int(WORKING_SIZE)}:
|
| 1108 |
+
raise ValueError(
|
| 1109 |
+
f"NASA phase 1 keeps only {int(WORKING_SIZE)}x{int(WORKING_SIZE)} frames, got {sorted(sizes)}"
|
| 1110 |
+
)
|
| 1111 |
+
if dataset == "tcir" and sizes:
|
| 1112 |
+
from src.tcir import IMAGE_SIZE
|
| 1113 |
+
|
| 1114 |
+
if sizes != {int(IMAGE_SIZE)}:
|
| 1115 |
+
raise ValueError(f"TCIR frames must stay {int(IMAGE_SIZE)}x{int(IMAGE_SIZE)}, got {sorted(sizes)}")
|
| 1116 |
+
|
| 1117 |
+
|
| 1118 |
+
def _log_excluded(dataset: str, count: int, detail: str) -> None:
|
| 1119 |
+
message = f"{dataset} excluded {int(count)} frames ({detail})"
|
| 1120 |
+
LOGGER.info(message)
|
| 1121 |
+
print(message)
|
| 1122 |
+
|
| 1123 |
+
|
| 1124 |
+
def _absolute_image_paths(frame: pd.DataFrame, base: Path) -> pd.DataFrame:
|
| 1125 |
+
out = frame.copy()
|
| 1126 |
+
paths: list[str] = []
|
| 1127 |
+
for image_path in out["image_path"].tolist():
|
| 1128 |
+
path = Path(str(image_path))
|
| 1129 |
+
if not path.is_absolute():
|
| 1130 |
+
path = base / path
|
| 1131 |
+
paths.append(path.resolve().as_posix())
|
| 1132 |
+
out["image_path"] = paths
|
| 1133 |
+
return out
|
| 1134 |
+
|
| 1135 |
+
|
| 1136 |
+
def load_nasa_frame(config: dict) -> tuple[pd.DataFrame, int]:
|
| 1137 |
+
"""NASA manifest for both official sides. ``source_split`` is not the split.
|
| 1138 |
+
|
| 1139 |
+
Phase 1 keeps ``orig_size`` 366 only. Colour frames and any other size
|
| 1140 |
+
are excluded, and the excluded count is logged. Nothing is downloaded.
|
| 1141 |
+
NASA has no IBTrACS join key, so ``near_land`` stays unknown. See
|
| 1142 |
+
``nasa_tc/audit/README.md``.
|
| 1143 |
+
"""
|
| 1144 |
+
from src.nasa_tc import WORKING_SIZE, build_manifest, csv_tables, exclusions_for, split_exclusions
|
| 1145 |
+
from src.schema import require_valid
|
| 1146 |
+
|
| 1147 |
+
root = Path(config["paths"]["nasa_root"])
|
| 1148 |
+
if not root.is_dir():
|
| 1149 |
+
raise FileNotFoundError(
|
| 1150 |
+
f"NASA root {root} is missing. Set paths.nasa_root in the YAML. "
|
| 1151 |
+
"This entrypoint does not download imagery."
|
| 1152 |
+
)
|
| 1153 |
+
raw = build_manifest(root, root, tables=csv_tables, keep_excluded=True)
|
| 1154 |
+
colour = exclusions_for(raw)
|
| 1155 |
+
kept, _dropped = split_exclusions(raw)
|
| 1156 |
+
if "orig_size" not in kept.columns:
|
| 1157 |
+
raise ValueError("NASA manifest is missing orig_size")
|
| 1158 |
+
if "split" in kept.columns:
|
| 1159 |
+
raise LeakageError("NASA manifest must not carry split; source_split holds the official side")
|
| 1160 |
+
size_ok = kept["orig_size"].astype(int) == int(WORKING_SIZE)
|
| 1161 |
+
size_excluded = int((~size_ok).sum())
|
| 1162 |
+
frame = require_valid(kept.loc[size_ok].reset_index(drop=True))
|
| 1163 |
+
excluded = int(len(colour)) + size_excluded
|
| 1164 |
+
_log_excluded(
|
| 1165 |
+
"nasa",
|
| 1166 |
+
excluded,
|
| 1167 |
+
f"{int(len(colour))} colour, {size_excluded} not {int(WORKING_SIZE)}x{int(WORKING_SIZE)}",
|
| 1168 |
+
)
|
| 1169 |
+
if "source_split" not in frame.columns:
|
| 1170 |
+
raise LeakageError("NASA manifest must keep the official side in source_split")
|
| 1171 |
+
refuse_mixed_resolution(frame, "nasa")
|
| 1172 |
+
return _absolute_image_paths(frame, root), excluded
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
def load_tcir_frame(config: dict) -> tuple[pd.DataFrame, int]:
|
| 1176 |
+
"""TCIR IR1 manifest. There is no official split inside the HDF5 files.
|
| 1177 |
+
|
| 1178 |
+
``assign_storms`` writes ``split``. Excluded IR1 frames are logged.
|
| 1179 |
+
This entrypoint does not download TCIR.
|
| 1180 |
+
"""
|
| 1181 |
+
from src.tcir import IMAGE_SIZE, build_manifest
|
| 1182 |
+
|
| 1183 |
+
files = config["paths"]["tcir_files"]
|
| 1184 |
+
if not isinstance(files, list) or not files:
|
| 1185 |
+
raise ValueError(
|
| 1186 |
+
"paths.tcir_files must list TCIR HDF5 paths. This entrypoint does not download TCIR."
|
| 1187 |
+
)
|
| 1188 |
+
manifest_dir = Path(config["paths"]["tcir_manifest_dir"])
|
| 1189 |
+
frame, excluded, _pixel = build_manifest(
|
| 1190 |
+
list(files), manifest_dir, export=True, flip_southern=False
|
| 1191 |
+
)
|
| 1192 |
+
if "split" in frame.columns or "source_split" in frame.columns:
|
| 1193 |
+
raise LeakageError(
|
| 1194 |
+
"TCIR has no official split. Keep any official label in source_split only, "
|
| 1195 |
+
"and let assign_storms write split."
|
| 1196 |
+
)
|
| 1197 |
+
refuse_mixed_resolution(frame, "tcir")
|
| 1198 |
+
sizes = {int(value) for value in frame["orig_size"].tolist()}
|
| 1199 |
+
if sizes != {int(IMAGE_SIZE)}:
|
| 1200 |
+
raise ValueError(f"TCIR frames must stay {int(IMAGE_SIZE)}x{int(IMAGE_SIZE)}, got {sorted(sizes)}")
|
| 1201 |
+
_log_excluded("tcir", int(len(excluded)), "IR1 gate")
|
| 1202 |
+
return _absolute_image_paths(frame, manifest_dir), int(len(excluded))
|
| 1203 |
+
|
| 1204 |
+
|
| 1205 |
+
def load_incyde_frame(config: dict) -> tuple[pd.DataFrame, int]:
|
| 1206 |
+
"""INCYDE manifest from a local extract. The audit CSVs name the split.
|
| 1207 |
+
|
| 1208 |
+
``rot_180`` copies stay on the source storm and in train only. Nothing
|
| 1209 |
+
is downloaded. ``on_fix``, ``distance_to_land_km``, and ``near_land``
|
| 1210 |
+
come from ``incyde/audit/frame_flags.csv``. Unknown audit cells stay
|
| 1211 |
+
unknown. The 3-minute label is not rescaled.
|
| 1212 |
+
"""
|
| 1213 |
+
from src.incyde import load_frame
|
| 1214 |
+
|
| 1215 |
+
frame, excluded = load_frame(config)
|
| 1216 |
+
if "source_split" in frame.columns:
|
| 1217 |
+
raise LeakageError("INCYDE must not carry an official source_split")
|
| 1218 |
+
refuse_mixed_resolution(frame, "incyde", parse_image_size(config["data"]["image_size"]))
|
| 1219 |
+
_log_excluded("incyde", int(excluded), "default_exclude, dropped augs, eval synthetics")
|
| 1220 |
+
return frame, int(excluded)
|
| 1221 |
+
|
| 1222 |
+
|
| 1223 |
+
def load_smoke_frame(config: dict) -> tuple[pd.DataFrame, int]:
|
| 1224 |
+
"""Synthetic manifest named by ``paths.manifest``. Not a result."""
|
| 1225 |
+
path = Path(config["paths"]["manifest"])
|
| 1226 |
+
if not path.is_file():
|
| 1227 |
+
raise FileNotFoundError(
|
| 1228 |
+
f"smoke manifest {path} is missing. Run python -m src.make_smoke_data. "
|
| 1229 |
+
"This entrypoint does not download imagery."
|
| 1230 |
+
)
|
| 1231 |
+
frame = load_manifest(path)
|
| 1232 |
+
if "split" in frame.columns:
|
| 1233 |
+
frame = frame.drop(columns=["split"])
|
| 1234 |
+
if "orig_size" in frame.columns or "native_height" in frame.columns:
|
| 1235 |
+
refuse_mixed_resolution(frame, "smoke")
|
| 1236 |
+
_log_excluded("smoke", 0, "synthetic manifest is already one size")
|
| 1237 |
+
return _absolute_image_paths(frame, path.parent), 0
|
| 1238 |
+
|
| 1239 |
+
|
| 1240 |
+
def training_wind_column(config: dict) -> str:
|
| 1241 |
+
"""Column the loss reads. The default in the YAML is ``wind_kt_3min``."""
|
| 1242 |
+
column = str(config["labels"]["label_column"]).strip()
|
| 1243 |
+
if column not in {"wind_kt_3min", "wind_speed_kt", "wind_kt"}:
|
| 1244 |
+
raise ValueError("labels.label_column must be wind_kt_3min, wind_speed_kt, or wind_kt")
|
| 1245 |
+
return column
|
| 1246 |
+
|
| 1247 |
+
|
| 1248 |
+
def apply_label_standard(frame: pd.DataFrame, config: dict) -> pd.DataFrame:
|
| 1249 |
+
"""Attach ``wind_kt_3min`` using the YAML factor. Raw knots stay put."""
|
| 1250 |
+
block = config["labels"]
|
| 1251 |
+
return apply_wind_standard(
|
| 1252 |
+
frame,
|
| 1253 |
+
factor=float(block["wind_1min_to_3min"]),
|
| 1254 |
+
policy=str(block["near_land_policy"]),
|
| 1255 |
+
open_water_km=float(block["open_water_km"]),
|
| 1256 |
+
)
|
| 1257 |
+
|
| 1258 |
+
|
| 1259 |
+
def load_training_frame(dataset: str, config: dict) -> tuple[pd.DataFrame, int]:
|
| 1260 |
+
"""Load one dataset. NASA and TCIR are never concatenated.
|
| 1261 |
+
|
| 1262 |
+
Every dataset then gets ``wind_kt_3min``. INCYDE passes through.
|
| 1263 |
+
NASA and TCIR 1-minute labels are multiplied by the configured factor.
|
| 1264 |
+
"""
|
| 1265 |
+
name = str(dataset).strip().lower()
|
| 1266 |
+
if name not in _DATASETS:
|
| 1267 |
+
raise ValueError(f"dataset must be one of {', '.join(_DATASETS)}")
|
| 1268 |
+
if name == "nasa":
|
| 1269 |
+
frame, excluded = load_nasa_frame(config)
|
| 1270 |
+
elif name == "tcir":
|
| 1271 |
+
frame, excluded = load_tcir_frame(config)
|
| 1272 |
+
elif name == "incyde":
|
| 1273 |
+
frame, excluded = load_incyde_frame(config)
|
| 1274 |
+
else:
|
| 1275 |
+
frame, excluded = load_smoke_frame(config)
|
| 1276 |
+
return apply_label_standard(frame, config), excluded
|
| 1277 |
+
|
| 1278 |
+
|
| 1279 |
+
def assign_project_split(frame: pd.DataFrame, config: dict) -> pd.DataFrame:
|
| 1280 |
+
"""Storm-wise split over the whole frame. ``source_split`` is not used.
|
| 1281 |
+
|
| 1282 |
+
A pre-existing ``split`` column is dropped. Official NASA sides stay in
|
| 1283 |
+
``source_split``. A storm that sits on both official sides gets one
|
| 1284 |
+
project split.
|
| 1285 |
+
"""
|
| 1286 |
+
work = frame.copy()
|
| 1287 |
+
if "split" in work.columns:
|
| 1288 |
+
work = work.drop(columns=["split"])
|
| 1289 |
+
assigned = split_frame(work, config)
|
| 1290 |
+
if "source_split" in assigned.columns:
|
| 1291 |
+
per_storm = assigned.groupby(assigned["storm_id"].astype(str))["split"].nunique()
|
| 1292 |
+
if bool((per_storm > 1).any()):
|
| 1293 |
+
raise LeakageError("source_split leaked into the project split and cut a storm")
|
| 1294 |
+
both = assigned.groupby(assigned["storm_id"].astype(str))["source_split"].nunique()
|
| 1295 |
+
shared = both[both > 1]
|
| 1296 |
+
for storm_id in shared.index:
|
| 1297 |
+
rows = assigned.loc[assigned["storm_id"].astype(str) == str(storm_id), "split"]
|
| 1298 |
+
if int(rows.nunique()) != 1:
|
| 1299 |
+
raise LeakageError(f"source_split leaked into the project split for {storm_id}")
|
| 1300 |
+
groups = storm_ids_by_split(assigned)
|
| 1301 |
+
if groups["train"] & groups["val"] or groups["train"] & groups["test"] or groups["val"] & groups["test"]:
|
| 1302 |
+
raise LeakageError("storm overlap across splits")
|
| 1303 |
+
return assigned
|
| 1304 |
+
|
| 1305 |
+
|
| 1306 |
+
def _move_batch(batch, device):
|
| 1307 |
+
images = batch[0].to(device)
|
| 1308 |
+
winds = batch[1].to(device)
|
| 1309 |
+
class_index = batch[2].to(device)
|
| 1310 |
+
sample_weight = batch[3].to(device)
|
| 1311 |
+
size_target = batch[4].to(device) if len(batch) > 4 else None
|
| 1312 |
+
return images, winds, class_index, sample_weight, size_target
|
| 1313 |
+
|
| 1314 |
+
|
| 1315 |
+
def _split_mae(model, loader, device, policy) -> float:
|
| 1316 |
+
"""Validation MAE in knots. Dropout is off. This is the early-stopping score."""
|
| 1317 |
+
torch = _torch()
|
| 1318 |
+
was_training = model.training
|
| 1319 |
+
model.eval()
|
| 1320 |
+
total = 0.0
|
| 1321 |
+
count = 0
|
| 1322 |
+
with torch.no_grad():
|
| 1323 |
+
for batch in loader:
|
| 1324 |
+
images, winds, _class_index, _sample_weight, _size = _move_batch(batch, device)
|
| 1325 |
+
with autocast_context(policy):
|
| 1326 |
+
wind_hat, _logits, _size_hat = _split_output(model(images))
|
| 1327 |
+
error = torch.abs(wind_hat.float().view(-1) - winds.float().view(-1))
|
| 1328 |
+
total += float(error.sum())
|
| 1329 |
+
count += int(images.shape[0])
|
| 1330 |
+
if was_training:
|
| 1331 |
+
model.train()
|
| 1332 |
+
if count == 0:
|
| 1333 |
+
raise ValueError("validation loader produced no rows")
|
| 1334 |
+
return total / count
|
| 1335 |
+
|
| 1336 |
+
|
| 1337 |
+
def _collect_predictions(model, loader, device, policy) -> tuple[np.ndarray, np.ndarray]:
|
| 1338 |
+
"""Point predictions with dropout off, aligned with the loader order."""
|
| 1339 |
+
torch = _torch()
|
| 1340 |
+
was_training = model.training
|
| 1341 |
+
model.eval()
|
| 1342 |
+
truths: list[np.ndarray] = []
|
| 1343 |
+
preds: list[np.ndarray] = []
|
| 1344 |
+
with torch.no_grad():
|
| 1345 |
+
for batch in loader:
|
| 1346 |
+
images, winds, _class_index, _sample_weight, _size = _move_batch(batch, device)
|
| 1347 |
+
with autocast_context(policy):
|
| 1348 |
+
wind_hat, _logits, _size_hat = _split_output(model(images))
|
| 1349 |
+
truths.append(winds.detach().float().cpu().numpy().reshape(-1))
|
| 1350 |
+
preds.append(wind_hat.detach().float().cpu().numpy().reshape(-1))
|
| 1351 |
+
if was_training:
|
| 1352 |
+
model.train()
|
| 1353 |
+
if not truths:
|
| 1354 |
+
raise ValueError("loader produced no rows")
|
| 1355 |
+
return np.concatenate(truths), np.concatenate(preds)
|
| 1356 |
+
|
| 1357 |
+
|
| 1358 |
+
def _apply_step(optimizer, scaler) -> None:
|
| 1359 |
+
if scaler is None:
|
| 1360 |
+
optimizer.step()
|
| 1361 |
+
else:
|
| 1362 |
+
scaler.step(optimizer)
|
| 1363 |
+
scaler.update()
|
| 1364 |
+
optimizer.zero_grad(set_to_none=True)
|
| 1365 |
+
|
| 1366 |
+
|
| 1367 |
+
def _optimizer_cpu_state(optimizer) -> dict:
|
| 1368 |
+
torch = _torch()
|
| 1369 |
+
blob = optimizer.state_dict()
|
| 1370 |
+
cpu_state: dict = {}
|
| 1371 |
+
for param_id, state in blob.get("state", {}).items():
|
| 1372 |
+
cpu_state[param_id] = {
|
| 1373 |
+
key: (value.detach().cpu() if torch.is_tensor(value) else value)
|
| 1374 |
+
for key, value in state.items()
|
| 1375 |
+
}
|
| 1376 |
+
blob["state"] = cpu_state
|
| 1377 |
+
return blob
|
| 1378 |
+
|
| 1379 |
+
|
| 1380 |
+
def _move_optimizer_to(optimizer, device) -> None:
|
| 1381 |
+
torch = _torch()
|
| 1382 |
+
for state in optimizer.state.values():
|
| 1383 |
+
for key, value in list(state.items()):
|
| 1384 |
+
if torch.is_tensor(value):
|
| 1385 |
+
state[key] = value.to(device)
|
| 1386 |
+
|
| 1387 |
+
|
| 1388 |
+
def _fit_run(
|
| 1389 |
+
model,
|
| 1390 |
+
train_loader,
|
| 1391 |
+
val_loader,
|
| 1392 |
+
train_cfg: dict,
|
| 1393 |
+
device,
|
| 1394 |
+
max_steps: int | None,
|
| 1395 |
+
*,
|
| 1396 |
+
start_epoch: int = 0,
|
| 1397 |
+
history: list | None = None,
|
| 1398 |
+
stopper: EarlyStopping | None = None,
|
| 1399 |
+
steps_done: int = 0,
|
| 1400 |
+
optimizer_state: dict | None = None,
|
| 1401 |
+
on_epoch_end=None,
|
| 1402 |
+
already_stopped: bool = False,
|
| 1403 |
+
loss_weighting: str = "none",
|
| 1404 |
+
):
|
| 1405 |
+
"""Smooth L1 on wind, AdamW, early stopping on validation MAE.
|
| 1406 |
+
|
| 1407 |
+
Gradient accumulation steps come from ``train.grad_accum_steps``.
|
| 1408 |
+
CUDA fp16 uses GradScaler. XPU bf16 and CPU fp32 do not. A checkpoint
|
| 1409 |
+
callback runs after every finished epoch so a sleep can resume there.
|
| 1410 |
+
``loss_weighting`` ``none`` keeps the unweighted mean.
|
| 1411 |
+
"""
|
| 1412 |
+
torch = _torch()
|
| 1413 |
+
|
| 1414 |
+
weighting = loss_weighting_mode(loss_weighting)
|
| 1415 |
+
policy = amp_policy_for(device)
|
| 1416 |
+
accum = int(train_cfg["grad_accum_steps"])
|
| 1417 |
+
if accum < 1:
|
| 1418 |
+
raise ValueError("train.grad_accum_steps must be at least 1")
|
| 1419 |
+
if max_steps is not None and int(max_steps) < 1:
|
| 1420 |
+
raise ValueError("max_steps must be at least 1")
|
| 1421 |
+
model.to(device)
|
| 1422 |
+
optimizer = torch.optim.AdamW(
|
| 1423 |
+
model.parameters(),
|
| 1424 |
+
lr=float(train_cfg["lr"]),
|
| 1425 |
+
weight_decay=float(train_cfg["weight_decay"]),
|
| 1426 |
+
)
|
| 1427 |
+
if optimizer_state is not None:
|
| 1428 |
+
optimizer.load_state_dict(optimizer_state)
|
| 1429 |
+
_move_optimizer_to(optimizer, device)
|
| 1430 |
+
scaler = make_grad_scaler(policy)
|
| 1431 |
+
epochs = int(train_cfg["epochs"])
|
| 1432 |
+
if stopper is None:
|
| 1433 |
+
stopper = EarlyStopping(int(train_cfg["patience"]))
|
| 1434 |
+
history = list(history or [])
|
| 1435 |
+
steps = int(steps_done)
|
| 1436 |
+
stopped_early = bool(already_stopped)
|
| 1437 |
+
reset_peak_memory(device)
|
| 1438 |
+
end_epoch = start_epoch if already_stopped else epochs
|
| 1439 |
+
for epoch in range(int(start_epoch), int(end_epoch)):
|
| 1440 |
+
epoch_start = time.time()
|
| 1441 |
+
model.train()
|
| 1442 |
+
_move_optimizer_to(optimizer, device)
|
| 1443 |
+
optimizer.zero_grad(set_to_none=True)
|
| 1444 |
+
total = 0.0
|
| 1445 |
+
count = 0
|
| 1446 |
+
pending = 0
|
| 1447 |
+
for batch in train_loader:
|
| 1448 |
+
if max_steps is not None and steps >= int(max_steps):
|
| 1449 |
+
break
|
| 1450 |
+
images, winds, _class_index, sample_weight, _size = _move_batch(batch, device)
|
| 1451 |
+
with autocast_context(policy):
|
| 1452 |
+
wind_hat, _logits, _size_hat = _split_output(model(images))
|
| 1453 |
+
loss = batch_wind_loss(wind_hat.float(), winds.float(), sample_weight, weighting)
|
| 1454 |
+
if scaler is None:
|
| 1455 |
+
(loss / accum).backward()
|
| 1456 |
+
else:
|
| 1457 |
+
scaler.scale(loss / accum).backward()
|
| 1458 |
+
pending += 1
|
| 1459 |
+
rows = int(images.shape[0])
|
| 1460 |
+
total += float(loss.detach()) * rows
|
| 1461 |
+
count += rows
|
| 1462 |
+
steps += 1
|
| 1463 |
+
if pending == accum:
|
| 1464 |
+
_apply_step(optimizer, scaler)
|
| 1465 |
+
pending = 0
|
| 1466 |
+
if pending:
|
| 1467 |
+
_apply_step(optimizer, scaler)
|
| 1468 |
+
if count == 0:
|
| 1469 |
+
break
|
| 1470 |
+
val_mae = _split_mae(model, val_loader, device, policy)
|
| 1471 |
+
if not np.isfinite(val_mae):
|
| 1472 |
+
raise RuntimeError("validation MAE is not finite")
|
| 1473 |
+
train_loss = total / count
|
| 1474 |
+
elapsed = time.time() - epoch_start
|
| 1475 |
+
print(
|
| 1476 |
+
f"epoch {epoch + 1}/{epochs} | train_loss={train_loss:.4f} | val_mae={float(val_mae):.2f} kt | elapsed={elapsed:.1f}s",
|
| 1477 |
+
flush=True,
|
| 1478 |
+
)
|
| 1479 |
+
history.append(
|
| 1480 |
+
{
|
| 1481 |
+
"epoch": epoch,
|
| 1482 |
+
"step": steps,
|
| 1483 |
+
"train_loss": train_loss,
|
| 1484 |
+
"val_mae": float(val_mae),
|
| 1485 |
+
}
|
| 1486 |
+
)
|
| 1487 |
+
state = {key: value.detach().cpu() for key, value in model.state_dict().items()}
|
| 1488 |
+
if stopper.update(float(val_mae), state):
|
| 1489 |
+
stopped_early = True
|
| 1490 |
+
if on_epoch_end is not None:
|
| 1491 |
+
on_epoch_end(
|
| 1492 |
+
epoch=epoch,
|
| 1493 |
+
model=model,
|
| 1494 |
+
optimizer=optimizer,
|
| 1495 |
+
history=history,
|
| 1496 |
+
stopper=stopper,
|
| 1497 |
+
steps=steps,
|
| 1498 |
+
stopped_early=stopped_early,
|
| 1499 |
+
)
|
| 1500 |
+
if stopped_early:
|
| 1501 |
+
break
|
| 1502 |
+
if max_steps is not None and steps >= int(max_steps):
|
| 1503 |
+
break
|
| 1504 |
+
if stopper.best_state is None:
|
| 1505 |
+
raise RuntimeError("training produced no validation score")
|
| 1506 |
+
model.load_state_dict(stopper.best_state)
|
| 1507 |
+
return model, history, stopped_early, float(stopper.best), peak_memory_bytes(device)
|
| 1508 |
+
|
| 1509 |
+
|
| 1510 |
+
def _config_hash(config: dict) -> str:
|
| 1511 |
+
payload = json.dumps(config, sort_keys=True, default=str)
|
| 1512 |
+
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
| 1513 |
+
|
| 1514 |
+
|
| 1515 |
+
def _write_loss_curve(history: list[dict], csv_path: Path, png_path: Path) -> None:
|
| 1516 |
+
import matplotlib
|
| 1517 |
+
|
| 1518 |
+
matplotlib.use("Agg", force=True)
|
| 1519 |
+
import matplotlib.pyplot as plt
|
| 1520 |
+
|
| 1521 |
+
table = pd.DataFrame(history)
|
| 1522 |
+
csv_path.parent.mkdir(parents=True, exist_ok=True)
|
| 1523 |
+
table.to_csv(csv_path, index=False)
|
| 1524 |
+
figure, axis = plt.subplots(figsize=(6.4, 4.0))
|
| 1525 |
+
axis.plot(table["epoch"], table["train_loss"], marker="o", label="train SmoothL1")
|
| 1526 |
+
axis.plot(table["epoch"], table["val_mae"], marker="o", label="val MAE (kt)")
|
| 1527 |
+
axis.set_xlabel("epoch")
|
| 1528 |
+
axis.set_ylabel("loss / MAE")
|
| 1529 |
+
axis.set_title("Training curve. Not a forecast.")
|
| 1530 |
+
axis.legend(frameon=False)
|
| 1531 |
+
figure.tight_layout()
|
| 1532 |
+
figure.savefig(png_path, dpi=100)
|
| 1533 |
+
plt.close(figure)
|
| 1534 |
+
|
| 1535 |
+
|
| 1536 |
+
def _score_split(truth: np.ndarray, pred: np.ndarray, config: dict) -> dict:
|
| 1537 |
+
"""MAE, RMSE, and bias from ``src.evaluate`` on one held-out split."""
|
| 1538 |
+
from src.evaluate import score_winds
|
| 1539 |
+
|
| 1540 |
+
edges = tuple(float(edge) for edge in config["data"]["imd5_edges_kt"])
|
| 1541 |
+
names = tuple(str(name) for name in config["data"]["imd5_names"])
|
| 1542 |
+
overall = score_winds(truth, pred, edges, names)["overall"]
|
| 1543 |
+
return {
|
| 1544 |
+
"n": overall["n"],
|
| 1545 |
+
"mae_kt": overall["mae_kt"],
|
| 1546 |
+
"rmse_kt": overall["rmse_kt"],
|
| 1547 |
+
"bias_kt": overall["bias_kt"],
|
| 1548 |
+
}
|
| 1549 |
+
|
| 1550 |
+
|
| 1551 |
+
def _run_id(dataset: str, model_name: str, config_digest: str) -> str:
|
| 1552 |
+
stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())
|
| 1553 |
+
return f"{dataset}-{model_name}-{stamp}-{time.time_ns()}-{config_digest[:8]}"
|
| 1554 |
+
|
| 1555 |
+
|
| 1556 |
+
def git_commit() -> str | None:
|
| 1557 |
+
"""HEAD of this checkout, or null when git is not available."""
|
| 1558 |
+
try:
|
| 1559 |
+
text = subprocess.check_output(
|
| 1560 |
+
["git", "rev-parse", "HEAD"],
|
| 1561 |
+
cwd=Path(__file__).resolve().parents[1],
|
| 1562 |
+
text=True,
|
| 1563 |
+
stderr=subprocess.DEVNULL,
|
| 1564 |
+
).strip()
|
| 1565 |
+
except (OSError, subprocess.CalledProcessError):
|
| 1566 |
+
return None
|
| 1567 |
+
return text or None
|
| 1568 |
+
|
| 1569 |
+
|
| 1570 |
+
def _file_sha256(path: Path) -> str:
|
| 1571 |
+
digest = hashlib.sha256()
|
| 1572 |
+
with Path(path).open("rb") as handle:
|
| 1573 |
+
for chunk in iter(lambda: handle.read(1 << 20), b""):
|
| 1574 |
+
digest.update(chunk)
|
| 1575 |
+
return digest.hexdigest()
|
| 1576 |
+
|
| 1577 |
+
|
| 1578 |
+
def _load_torch_payload(path: Path) -> dict:
|
| 1579 |
+
torch = _torch()
|
| 1580 |
+
if not path.is_file():
|
| 1581 |
+
raise FileNotFoundError(path)
|
| 1582 |
+
try:
|
| 1583 |
+
payload = torch.load(path, map_location="cpu", weights_only=False)
|
| 1584 |
+
except TypeError:
|
| 1585 |
+
payload = torch.load(path, map_location="cpu")
|
| 1586 |
+
if not isinstance(payload, dict):
|
| 1587 |
+
raise RuntimeError(f"{path} is not a checkpoint dict")
|
| 1588 |
+
return payload
|
| 1589 |
+
|
| 1590 |
+
|
| 1591 |
+
def _parent_periods(payload: dict) -> set[str]:
|
| 1592 |
+
periods: set[str] = set()
|
| 1593 |
+
grouped = payload.get("wind_averaging_by_split")
|
| 1594 |
+
if isinstance(grouped, dict):
|
| 1595 |
+
for entry in grouped.values():
|
| 1596 |
+
if isinstance(entry, dict):
|
| 1597 |
+
periods.update(str(value) for value in entry.get("wind_averaging", []))
|
| 1598 |
+
single = payload.get("wind_averaging")
|
| 1599 |
+
if single not in (None, ""):
|
| 1600 |
+
periods.add(str(single))
|
| 1601 |
+
return {value for value in periods if value and value.lower() != "none"}
|
| 1602 |
+
|
| 1603 |
+
|
| 1604 |
+
def load_init_weights(model, path: str | Path, config: dict) -> tuple[object, str, set[str], object]:
|
| 1605 |
+
"""Load weights only. Optimizer state is left untouched.
|
| 1606 |
+
|
| 1607 |
+
A different ``model_name`` or a state dict whose keys or shapes differ
|
| 1608 |
+
is refused. The returned hash is the file bytes, and the period set is
|
| 1609 |
+
whatever the parent run recorded.
|
| 1610 |
+
"""
|
| 1611 |
+
checkpoint = Path(path)
|
| 1612 |
+
payload = _load_torch_payload(checkpoint)
|
| 1613 |
+
if "state_dict" not in payload:
|
| 1614 |
+
raise RuntimeError(f"Refusing init-from: {checkpoint} has no state_dict")
|
| 1615 |
+
expected = str(config["model"]["name"])
|
| 1616 |
+
loaded_name = payload.get("model_name")
|
| 1617 |
+
if loaded_name is not None and str(loaded_name) != expected:
|
| 1618 |
+
raise RuntimeError(
|
| 1619 |
+
"Refusing init-from: architecture does not match "
|
| 1620 |
+
f"(checkpoint model {loaded_name}, training model {expected})"
|
| 1621 |
+
)
|
| 1622 |
+
incoming = payload["state_dict"]
|
| 1623 |
+
current = model.state_dict()
|
| 1624 |
+
if set(incoming) != set(current):
|
| 1625 |
+
missing = sorted(set(current) - set(incoming))[:8]
|
| 1626 |
+
extra = sorted(set(incoming) - set(current))[:8]
|
| 1627 |
+
raise RuntimeError(
|
| 1628 |
+
"Refusing init-from: architecture does not match "
|
| 1629 |
+
f"(missing {missing}, extra {extra})"
|
| 1630 |
+
)
|
| 1631 |
+
for key, tensor in current.items():
|
| 1632 |
+
if tuple(tensor.shape) != tuple(incoming[key].shape):
|
| 1633 |
+
raise RuntimeError(
|
| 1634 |
+
"Refusing init-from: architecture does not match at "
|
| 1635 |
+
f"{key}: {tuple(tensor.shape)} vs {tuple(incoming[key].shape)}"
|
| 1636 |
+
)
|
| 1637 |
+
model.load_state_dict({key: value.detach().cpu() for key, value in incoming.items()})
|
| 1638 |
+
run_id = payload.get("run_id")
|
| 1639 |
+
return run_id, _file_sha256(checkpoint), _parent_periods(payload), payload.get("label_column")
|
| 1640 |
+
|
| 1641 |
+
|
| 1642 |
+
def averaging_mismatch(
|
| 1643 |
+
parent_periods: set[str],
|
| 1644 |
+
current_periods: set[str],
|
| 1645 |
+
parent_label: object,
|
| 1646 |
+
current_label: object,
|
| 1647 |
+
) -> bool:
|
| 1648 |
+
"""True when raw averaging periods differ and the 3-minute target is not both sides.
|
| 1649 |
+
|
| 1650 |
+
A parent and a child that both train on ``wind_kt_3min`` already share
|
| 1651 |
+
the converted target, so a 1-minute pretrain and a 3-minute fine-tune
|
| 1652 |
+
do not set the mismatch flag. Forcing raw labels (``wind_speed_kt`` or
|
| 1653 |
+
``wind_kt``) on either side keeps the flag.
|
| 1654 |
+
"""
|
| 1655 |
+
if str(parent_label) == "wind_kt_3min" and str(current_label) == "wind_kt_3min":
|
| 1656 |
+
return False
|
| 1657 |
+
parent = {str(value) for value in parent_periods if str(value).strip()}
|
| 1658 |
+
current = {str(value) for value in current_periods if str(value).strip()}
|
| 1659 |
+
if not parent or not current or parent == current:
|
| 1660 |
+
return False
|
| 1661 |
+
return True
|
| 1662 |
+
|
| 1663 |
+
|
| 1664 |
+
def _warn_wind_mismatch(
|
| 1665 |
+
parent: set[str],
|
| 1666 |
+
current: set[str],
|
| 1667 |
+
parent_label: object,
|
| 1668 |
+
current_label: object,
|
| 1669 |
+
) -> bool:
|
| 1670 |
+
"""Loud warning when raw labels cross averaging periods."""
|
| 1671 |
+
if not averaging_mismatch(parent, current, parent_label, current_label):
|
| 1672 |
+
return False
|
| 1673 |
+
message = (
|
| 1674 |
+
"WARNING: wind_averaging mismatch. "
|
| 1675 |
+
f"Parent checkpoint records {sorted(parent)} and this dataset records {sorted(current)}. "
|
| 1676 |
+
"No conversion factor is applied."
|
| 1677 |
+
)
|
| 1678 |
+
LOGGER.warning(message)
|
| 1679 |
+
print(message)
|
| 1680 |
+
return True
|
| 1681 |
+
|
| 1682 |
+
|
| 1683 |
+
def assert_test_score_allowed(dataset: str, allow_final_test: bool) -> None:
|
| 1684 |
+
"""INCYDE test storms are not scored unless ``--allow-final-test`` is set.
|
| 1685 |
+
|
| 1686 |
+
That covers Bean's default split and ``year_holdout_2019``.
|
| 1687 |
+
"""
|
| 1688 |
+
if str(dataset).strip().lower() == "incyde" and not allow_final_test:
|
| 1689 |
+
raise RuntimeError(
|
| 1690 |
+
"refusing to score INCYDE test storms without --allow-final-test. "
|
| 1691 |
+
"This applies to the default storm split and to split year_holdout_2019."
|
| 1692 |
+
)
|
| 1693 |
+
|
| 1694 |
+
|
| 1695 |
+
def _path_records(
|
| 1696 |
+
frame: pd.DataFrame,
|
| 1697 |
+
manifest: Path,
|
| 1698 |
+
split_name: str,
|
| 1699 |
+
wind_column: str,
|
| 1700 |
+
angles: np.ndarray | None = None,
|
| 1701 |
+
weights: np.ndarray | None = None,
|
| 1702 |
+
) -> list[dict]:
|
| 1703 |
+
rows = frame[frame["split"] == split_name].reset_index(drop=True)
|
| 1704 |
+
if rows.empty:
|
| 1705 |
+
raise ValueError(f"split {split_name} has no rows")
|
| 1706 |
+
labels = [None if pd.isna(value) else str(value) for value in rows["_class"]]
|
| 1707 |
+
paths = [str(resolve_image(manifest, path)) for path in rows["image_path"].tolist()]
|
| 1708 |
+
winds = rows[wind_column].to_numpy(dtype=np.float64)
|
| 1709 |
+
raw = rows["wind_speed_kt"].to_numpy(dtype=np.float64)
|
| 1710 |
+
# wind_kt_scale maps a 3-minute prediction back to the raw label.
|
| 1711 |
+
# A run forced onto the raw column already predicts in raw knots.
|
| 1712 |
+
if wind_column == "wind_kt_3min" and "wind_kt_scale" in rows.columns:
|
| 1713 |
+
scale = rows["wind_kt_scale"].to_numpy(dtype=np.float64)
|
| 1714 |
+
else:
|
| 1715 |
+
scale = np.ones(len(rows), dtype=np.float64)
|
| 1716 |
+
if weights is None:
|
| 1717 |
+
row_weights = np.ones(len(rows), dtype=np.float64)
|
| 1718 |
+
else:
|
| 1719 |
+
row_weights = np.asarray(weights, dtype=np.float64).reshape(-1)
|
| 1720 |
+
if row_weights.shape[0] != len(rows):
|
| 1721 |
+
raise ValueError("loss weights must align with the split")
|
| 1722 |
+
if "on_fix" in rows.columns:
|
| 1723 |
+
on_fix_values = rows["on_fix"].tolist()
|
| 1724 |
+
else:
|
| 1725 |
+
on_fix_values = [None] * len(rows)
|
| 1726 |
+
records = []
|
| 1727 |
+
for index in range(len(rows)):
|
| 1728 |
+
angle = None if angles is None else float(angles[index])
|
| 1729 |
+
records.append(
|
| 1730 |
+
{
|
| 1731 |
+
"path": paths[index],
|
| 1732 |
+
"wind": float(winds[index]),
|
| 1733 |
+
"raw_wind": float(raw[index]),
|
| 1734 |
+
"scale": float(scale[index]),
|
| 1735 |
+
"label": labels[index],
|
| 1736 |
+
"weight": float(row_weights[index]),
|
| 1737 |
+
"on_fix": on_fix_values[index],
|
| 1738 |
+
"angle": angle,
|
| 1739 |
+
}
|
| 1740 |
+
)
|
| 1741 |
+
return records
|
| 1742 |
+
|
| 1743 |
+
|
| 1744 |
+
def training_angles(n_rows: int, seed: int, enabled: bool) -> np.ndarray | None:
|
| 1745 |
+
"""One seeded degree per train row. Val and test pass ``enabled`` false."""
|
| 1746 |
+
if not enabled or n_rows < 1:
|
| 1747 |
+
return None
|
| 1748 |
+
return np.random.default_rng(int(seed)).uniform(0.0, 360.0, size=int(n_rows))
|
| 1749 |
+
|
| 1750 |
+
|
| 1751 |
+
def _parity_side(config: dict, frame: pd.DataFrame) -> int:
|
| 1752 |
+
side = parse_image_size(config["data"]["image_size"])
|
| 1753 |
+
if side is not None:
|
| 1754 |
+
return int(side)
|
| 1755 |
+
if "orig_size" in frame.columns and len(frame):
|
| 1756 |
+
return int(frame["orig_size"].iloc[0])
|
| 1757 |
+
if "native_height" in frame.columns and len(frame):
|
| 1758 |
+
return int(frame["native_height"].iloc[0])
|
| 1759 |
+
raise ValueError("cannot infer the frame size for the device parity check")
|
| 1760 |
+
|
| 1761 |
+
|
| 1762 |
+
def _current_periods(report: dict) -> set[str]:
|
| 1763 |
+
periods: set[str] = set()
|
| 1764 |
+
for entry in report.values():
|
| 1765 |
+
periods.update(str(value) for value in entry["wind_averaging"])
|
| 1766 |
+
return periods
|
| 1767 |
+
|
| 1768 |
+
|
| 1769 |
+
def run_is_synthetic(dataset: str, frame: pd.DataFrame) -> bool:
|
| 1770 |
+
"""Smoke is synthetic. INCYDE aug copies do not mark a real run synthetic.
|
| 1771 |
+
|
| 1772 |
+
``manifest_is_synthetic`` stays true when any row is synthetic. A real
|
| 1773 |
+
INCYDE extract has original frames plus train-only ``rot_180`` copies.
|
| 1774 |
+
Those copies are flagged and the run is still a real-data run.
|
| 1775 |
+
"""
|
| 1776 |
+
if dataset == "smoke":
|
| 1777 |
+
return True
|
| 1778 |
+
if dataset == "incyde":
|
| 1779 |
+
flags = [parse_is_synthetic(value) for value in frame["is_synthetic"].tolist()]
|
| 1780 |
+
return not any(not flag for flag in flags)
|
| 1781 |
+
return manifest_is_synthetic(frame)
|
| 1782 |
+
|
| 1783 |
+
|
| 1784 |
+
def normalization_frame(frame: pd.DataFrame, dataset: str) -> pd.DataFrame:
|
| 1785 |
+
"""Train-split stats see original INCYDE frames, not ``rot_180`` copies."""
|
| 1786 |
+
if dataset != "incyde" or "is_synthetic" not in frame.columns:
|
| 1787 |
+
return frame
|
| 1788 |
+
flags = [parse_is_synthetic(value) for value in frame["is_synthetic"].tolist()]
|
| 1789 |
+
kept = frame.loc[[not flag for flag in flags]].reset_index(drop=True)
|
| 1790 |
+
if kept.empty or not bool((kept["split"].astype(str) == "train").any()):
|
| 1791 |
+
raise LeakageError("INCYDE normalization needs original train frames")
|
| 1792 |
+
return kept
|
| 1793 |
+
|
| 1794 |
+
|
| 1795 |
+
def run_training(
|
| 1796 |
+
config: dict,
|
| 1797 |
+
*,
|
| 1798 |
+
dataset: str | None = None,
|
| 1799 |
+
model: str | None = None,
|
| 1800 |
+
max_steps: int | None = None,
|
| 1801 |
+
device: str | None = None,
|
| 1802 |
+
resume: str | Path | None = None,
|
| 1803 |
+
init_from: str | Path | None = None,
|
| 1804 |
+
allow_final_test: bool = False,
|
| 1805 |
+
) -> Path:
|
| 1806 |
+
"""Fit one dataset and write the run record under ``paths.runs``.
|
| 1807 |
+
|
| 1808 |
+
``resume`` continues the last finished epoch in that run directory.
|
| 1809 |
+
``init_from`` copies weights from another run, refits normalization on
|
| 1810 |
+
this dataset's train storms, and does not load the optimizer.
|
| 1811 |
+
"""
|
| 1812 |
+
import yaml
|
| 1813 |
+
|
| 1814 |
+
if resume is not None and init_from is not None:
|
| 1815 |
+
raise ValueError("pass either --resume or --init-from, not both")
|
| 1816 |
+
assert_model_inputs(("image",))
|
| 1817 |
+
train_cfg = _require_train_block(config)
|
| 1818 |
+
assert_normalize(config)
|
| 1819 |
+
resolved = copy.deepcopy(config)
|
| 1820 |
+
saved = None
|
| 1821 |
+
if resume is not None:
|
| 1822 |
+
run_dir = Path(resume)
|
| 1823 |
+
saved = _load_torch_payload(run_dir / LAST_CHECKPOINT)
|
| 1824 |
+
if "state_dict" not in saved or "epoch" not in saved:
|
| 1825 |
+
raise RuntimeError(f"{run_dir / LAST_CHECKPOINT} is not a resume checkpoint")
|
| 1826 |
+
if dataset is not None:
|
| 1827 |
+
dataset_name = str(dataset).strip().lower()
|
| 1828 |
+
elif saved is not None:
|
| 1829 |
+
dataset_name = str(saved["dataset"]).strip().lower()
|
| 1830 |
+
else:
|
| 1831 |
+
dataset_name = str(resolved["data"]["dataset"]).strip().lower()
|
| 1832 |
+
if dataset_name not in _DATASETS:
|
| 1833 |
+
raise ValueError(f"dataset must be one of {', '.join(_DATASETS)}")
|
| 1834 |
+
if dataset_name == "incyde":
|
| 1835 |
+
resolved["data"]["wind_averaging"] = "3min"
|
| 1836 |
+
if saved is not None and str(saved["dataset"]) != dataset_name:
|
| 1837 |
+
raise RuntimeError(
|
| 1838 |
+
f"resume dataset is {saved['dataset']} but this command asked for {dataset_name}"
|
| 1839 |
+
)
|
| 1840 |
+
if model is not None:
|
| 1841 |
+
resolved["model"]["name"] = canonical_model_name(model)
|
| 1842 |
+
elif saved is not None:
|
| 1843 |
+
resolved["model"]["name"] = str(saved["model_name"])
|
| 1844 |
+
else:
|
| 1845 |
+
resolved["model"]["name"] = canonical_model_name(str(resolved["model"]["name"]))
|
| 1846 |
+
if resolved["model"]["name"] not in {"simple_cnn", "resnet18", "convlstm"}:
|
| 1847 |
+
raise ValueError("this entrypoint trains simplecnn, resnet18, or convlstm")
|
| 1848 |
+
if saved is not None and str(saved["model_name"]) != str(resolved["model"]["name"]):
|
| 1849 |
+
raise RuntimeError(
|
| 1850 |
+
"Refusing resume: architecture does not match "
|
| 1851 |
+
f"(checkpoint model {saved['model_name']}, training model {resolved['model']['name']})"
|
| 1852 |
+
)
|
| 1853 |
+
device_name = str(device if device is not None else resolved["train"]["device"])
|
| 1854 |
+
torch_device = resolve_device(device_name)
|
| 1855 |
+
policy = amp_policy_for(torch_device)
|
| 1856 |
+
if max_steps is None:
|
| 1857 |
+
max_steps = resolved["train"]["max_steps"]
|
| 1858 |
+
if max_steps is not None:
|
| 1859 |
+
max_steps = int(max_steps)
|
| 1860 |
+
resolved["data"]["dataset"] = dataset_name
|
| 1861 |
+
resolved["train"]["device"] = torch_device.type
|
| 1862 |
+
resolved["train"]["device_requested"] = device_name
|
| 1863 |
+
resolved["train"]["precision"] = policy.precision
|
| 1864 |
+
resolved["train"]["max_steps"] = max_steps
|
| 1865 |
+
digest = _config_hash(resolved)
|
| 1866 |
+
resolved["config_hash"] = digest
|
| 1867 |
+
print(f"device={torch_device.type} precision={policy.precision}")
|
| 1868 |
+
LOGGER.info("device=%s precision=%s", torch_device.type, policy.precision)
|
| 1869 |
+
|
| 1870 |
+
if saved is None:
|
| 1871 |
+
frame, n_excluded = load_training_frame(dataset_name, resolved)
|
| 1872 |
+
frame = apply_frame_cache(frame, dataset_name, resolved["paths"].get("frame_cache"))
|
| 1873 |
+
refuse_mixed_resolution(
|
| 1874 |
+
frame, dataset_name, parse_image_size(resolved["data"]["image_size"])
|
| 1875 |
+
)
|
| 1876 |
+
wind_period = assert_wind_averaging(resolved, frame)
|
| 1877 |
+
synthetic = run_is_synthetic(dataset_name, frame)
|
| 1878 |
+
seed = int(resolved["project"]["seed"])
|
| 1879 |
+
_set_seed(seed)
|
| 1880 |
+
wind_column = training_wind_column(resolved)
|
| 1881 |
+
if dataset_name == "incyde":
|
| 1882 |
+
assigned = frame.copy()
|
| 1883 |
+
else:
|
| 1884 |
+
assigned = assign_project_split(frame, resolved)
|
| 1885 |
+
assigned["_class"] = project_labels(assigned, resolved, wind_column)
|
| 1886 |
+
groups = storm_ids_by_split(assigned)
|
| 1887 |
+
if not groups["train"] or not groups["val"] or not groups["test"]:
|
| 1888 |
+
raise LeakageError("train, val, and test storms are all required")
|
| 1889 |
+
# Frequencies are the assigned train split, so storm_cv's val fold
|
| 1890 |
+
# and the sealed test storms are already out. The CSV records them.
|
| 1891 |
+
assigned = annotate_balance(
|
| 1892 |
+
assigned, intensity_balance(assigned, resolved, wind_column), resolved
|
| 1893 |
+
)
|
| 1894 |
+
run_id = _run_id(dataset_name, str(resolved["model"]["name"]), digest)
|
| 1895 |
+
run_dir = Path(resolved["paths"]["runs"]) / run_id
|
| 1896 |
+
run_dir.mkdir(parents=True, exist_ok=False)
|
| 1897 |
+
manifest_path = run_dir / "split_manifest.csv"
|
| 1898 |
+
assigned.drop(columns=["_class"], errors="ignore").to_csv(manifest_path, index=False)
|
| 1899 |
+
labeled = assigned.copy()
|
| 1900 |
+
labeled["_class"] = project_labels(labeled, resolved, wind_column)
|
| 1901 |
+
start_epoch = 0
|
| 1902 |
+
prior_history: list = []
|
| 1903 |
+
restored_stopper = None
|
| 1904 |
+
steps_done = 0
|
| 1905 |
+
optimizer_state = None
|
| 1906 |
+
already_stopped = False
|
| 1907 |
+
else:
|
| 1908 |
+
if not run_dir.is_dir():
|
| 1909 |
+
raise FileNotFoundError(run_dir)
|
| 1910 |
+
manifest_path = run_dir / "split_manifest.csv"
|
| 1911 |
+
labeled = load_manifest(manifest_path)
|
| 1912 |
+
wind_period = assert_wind_averaging(resolved, labeled)
|
| 1913 |
+
synthetic = run_is_synthetic(dataset_name, labeled)
|
| 1914 |
+
seed = int(saved.get("seed", resolved["project"]["seed"]))
|
| 1915 |
+
_set_seed(seed)
|
| 1916 |
+
wind_column = training_wind_column(resolved)
|
| 1917 |
+
labeled["_class"] = project_labels(labeled, resolved, wind_column)
|
| 1918 |
+
groups = storm_ids_by_split(labeled)
|
| 1919 |
+
if not groups["train"] or not groups["val"] or not groups["test"]:
|
| 1920 |
+
raise LeakageError("train, val, and test storms are all required")
|
| 1921 |
+
run_id = str(saved["run_id"])
|
| 1922 |
+
n_excluded = int(saved.get("n_excluded", 0))
|
| 1923 |
+
start_epoch = int(saved["epoch"]) + 1
|
| 1924 |
+
prior_history = list(saved.get("history") or [])
|
| 1925 |
+
restored_stopper = EarlyStopping(int(train_cfg["patience"]))
|
| 1926 |
+
restored_stopper.best = float(saved["best_metric"])
|
| 1927 |
+
restored_stopper.waits = int(saved["waits"])
|
| 1928 |
+
restored_stopper.best_state = saved["best_state"]
|
| 1929 |
+
steps_done = int(saved.get("steps", 0))
|
| 1930 |
+
optimizer_state = saved.get("optimizer_state_dict")
|
| 1931 |
+
already_stopped = bool(saved.get("stopped_early"))
|
| 1932 |
+
|
| 1933 |
+
size_head = False
|
| 1934 |
+
stats = fit_split_normalization(normalization_frame(labeled, dataset_name), manifest_path, resolved)
|
| 1935 |
+
if stats.source_split != "train":
|
| 1936 |
+
raise LeakageError("normalization stats may be fit on the train split only")
|
| 1937 |
+
dataset_stats = norm_by_dataset(dataset_name, stats)
|
| 1938 |
+
averaging = split_wind_averaging(labeled)
|
| 1939 |
+
known = [str(name) for name in resolved["data"]["imd5_names"]]
|
| 1940 |
+
image_size = parse_image_size(resolved["data"]["image_size"])
|
| 1941 |
+
max_missing = float(resolved["data"]["max_missing_fraction"])
|
| 1942 |
+
batch_size = int(train_cfg["batch_size"])
|
| 1943 |
+
workers = int(train_cfg["num_workers"])
|
| 1944 |
+
torch = _torch()
|
| 1945 |
+
generator = torch.Generator()
|
| 1946 |
+
generator.manual_seed(seed)
|
| 1947 |
+
balance = intensity_balance(labeled, resolved, wind_column)
|
| 1948 |
+
balance_payload = balance_record(balance)
|
| 1949 |
+
train_rows = labeled.loc[labeled["split"] == "train"].reset_index(drop=True)
|
| 1950 |
+
train_labels = [None if pd.isna(value) else str(value) for value in train_rows["_class"]]
|
| 1951 |
+
if balance["loss_weighting"] == "none":
|
| 1952 |
+
train_loss_weights = np.ones(len(train_rows), dtype=np.float64)
|
| 1953 |
+
else:
|
| 1954 |
+
train_loss_weights = align_bin_weights(train_labels, balance["weights"])
|
| 1955 |
+
if uses_sequences(resolved):
|
| 1956 |
+
train_images, train_winds, train_labels, train_size = _load_examples(
|
| 1957 |
+
resolved, labeled, manifest_path, "train", stats, size_head
|
| 1958 |
+
)
|
| 1959 |
+
val_images, val_winds, val_labels, val_size = _load_examples(
|
| 1960 |
+
resolved, labeled, manifest_path, "val", stats, size_head
|
| 1961 |
+
)
|
| 1962 |
+
if balance["loss_weighting"] == "none":
|
| 1963 |
+
train_loss_weights = np.ones(len(train_winds), dtype=np.float64)
|
| 1964 |
+
else:
|
| 1965 |
+
train_loss_weights = align_bin_weights(train_labels, balance["weights"])
|
| 1966 |
+
val_weight = np.ones(len(val_winds), dtype=np.float64)
|
| 1967 |
+
train_sampler = None
|
| 1968 |
+
shuffle_train = True
|
| 1969 |
+
if balance["balanced_sampling"]:
|
| 1970 |
+
train_sampler = make_balanced_sampler(
|
| 1971 |
+
align_bin_weights(train_labels, balance["sampling_weights"]),
|
| 1972 |
+
len(train_winds),
|
| 1973 |
+
seed,
|
| 1974 |
+
)
|
| 1975 |
+
shuffle_train = False
|
| 1976 |
+
train_loader = build_loader(
|
| 1977 |
+
_dataset(train_images, train_winds, train_labels, known, train_loss_weights, train_size),
|
| 1978 |
+
batch_size=batch_size,
|
| 1979 |
+
shuffle=shuffle_train,
|
| 1980 |
+
num_workers=workers,
|
| 1981 |
+
generator=None if train_sampler is not None else generator,
|
| 1982 |
+
sampler=train_sampler,
|
| 1983 |
+
)
|
| 1984 |
+
val_loader = build_loader(
|
| 1985 |
+
_dataset(val_images, val_winds, val_labels, known, val_weight, val_size),
|
| 1986 |
+
batch_size=batch_size,
|
| 1987 |
+
shuffle=False,
|
| 1988 |
+
num_workers=workers,
|
| 1989 |
+
)
|
| 1990 |
+
score_test = True
|
| 1991 |
+
test_refusal = None
|
| 1992 |
+
try:
|
| 1993 |
+
assert_test_score_allowed(dataset_name, allow_final_test)
|
| 1994 |
+
except RuntimeError as exc:
|
| 1995 |
+
score_test = False
|
| 1996 |
+
test_refusal = str(exc)
|
| 1997 |
+
test_records = None
|
| 1998 |
+
test_loader = None
|
| 1999 |
+
if score_test:
|
| 2000 |
+
try:
|
| 2001 |
+
test_images, test_winds, test_labels, test_size = _load_examples(
|
| 2002 |
+
resolved, labeled, manifest_path, "test", stats, size_head
|
| 2003 |
+
)
|
| 2004 |
+
test_weight = np.ones(len(test_winds), dtype=np.float64)
|
| 2005 |
+
test_loader = build_loader(
|
| 2006 |
+
_dataset(test_images, test_winds, test_labels, known, test_weight, test_size),
|
| 2007 |
+
batch_size=batch_size,
|
| 2008 |
+
shuffle=False,
|
| 2009 |
+
num_workers=workers,
|
| 2010 |
+
)
|
| 2011 |
+
except Exception as exc:
|
| 2012 |
+
score_test = False
|
| 2013 |
+
test_refusal = str(exc)
|
| 2014 |
+
else:
|
| 2015 |
+
train_count = int(len(train_rows))
|
| 2016 |
+
train_records = _path_records(
|
| 2017 |
+
labeled,
|
| 2018 |
+
manifest_path,
|
| 2019 |
+
"train",
|
| 2020 |
+
wind_column,
|
| 2021 |
+
training_angles(train_count, seed, dataset_name == "incyde"),
|
| 2022 |
+
train_loss_weights,
|
| 2023 |
+
)
|
| 2024 |
+
val_records = _path_records(labeled, manifest_path, "val", wind_column, None)
|
| 2025 |
+
train_sampler = None
|
| 2026 |
+
shuffle_train = True
|
| 2027 |
+
if balance["balanced_sampling"]:
|
| 2028 |
+
train_sampler = make_balanced_sampler(
|
| 2029 |
+
align_bin_weights(train_labels, balance["sampling_weights"]),
|
| 2030 |
+
len(train_rows),
|
| 2031 |
+
seed,
|
| 2032 |
+
)
|
| 2033 |
+
shuffle_train = False
|
| 2034 |
+
train_loader = build_loader(
|
| 2035 |
+
PathFrames(train_records, image_size, stats.mean, stats.std, max_missing, known),
|
| 2036 |
+
batch_size=batch_size,
|
| 2037 |
+
shuffle=shuffle_train,
|
| 2038 |
+
num_workers=workers,
|
| 2039 |
+
generator=None if train_sampler is not None else generator,
|
| 2040 |
+
sampler=train_sampler,
|
| 2041 |
+
)
|
| 2042 |
+
val_loader = build_loader(
|
| 2043 |
+
PathFrames(val_records, image_size, stats.mean, stats.std, max_missing, known),
|
| 2044 |
+
batch_size=batch_size,
|
| 2045 |
+
shuffle=False,
|
| 2046 |
+
num_workers=workers,
|
| 2047 |
+
)
|
| 2048 |
+
score_test = True
|
| 2049 |
+
test_refusal = None
|
| 2050 |
+
try:
|
| 2051 |
+
assert_test_score_allowed(dataset_name, allow_final_test)
|
| 2052 |
+
except RuntimeError as exc:
|
| 2053 |
+
score_test = False
|
| 2054 |
+
test_refusal = str(exc)
|
| 2055 |
+
test_records = None
|
| 2056 |
+
test_loader = None
|
| 2057 |
+
if score_test:
|
| 2058 |
+
test_records = _path_records(labeled, manifest_path, "test", wind_column, None)
|
| 2059 |
+
test_loader = build_loader(
|
| 2060 |
+
PathFrames(test_records, image_size, stats.mean, stats.std, max_missing, known),
|
| 2061 |
+
batch_size=batch_size,
|
| 2062 |
+
shuffle=False,
|
| 2063 |
+
num_workers=workers,
|
| 2064 |
+
)
|
| 2065 |
+
model = build_net(resolved, size_head=size_head)
|
| 2066 |
+
if not any(layer.__class__.__name__ == "Dropout" for layer in model.modules()):
|
| 2067 |
+
raise RuntimeError("MC-dropout needs a Dropout layer left in the network")
|
| 2068 |
+
parent_run_id = None
|
| 2069 |
+
parent_sha = None
|
| 2070 |
+
parent_periods: set[str] = set()
|
| 2071 |
+
parent_label = None
|
| 2072 |
+
if init_from is not None:
|
| 2073 |
+
parent_run_id, parent_sha, parent_periods, parent_label = load_init_weights(
|
| 2074 |
+
model, init_from, resolved
|
| 2075 |
+
)
|
| 2076 |
+
if saved is not None:
|
| 2077 |
+
model.load_state_dict(saved["state_dict"])
|
| 2078 |
+
label_column = wind_column
|
| 2079 |
+
mismatch = _warn_wind_mismatch(
|
| 2080 |
+
parent_periods, _current_periods(averaging), parent_label, label_column
|
| 2081 |
+
)
|
| 2082 |
+
parity = None
|
| 2083 |
+
if torch_device.type != "cpu":
|
| 2084 |
+
images, winds = seeded_parity_batch(
|
| 2085 |
+
min(2, batch_size),
|
| 2086 |
+
int(resolved["data"]["channels"]),
|
| 2087 |
+
_parity_side(resolved, labeled),
|
| 2088 |
+
seed=0,
|
| 2089 |
+
n_frames=model_n_frames(resolved),
|
| 2090 |
+
)
|
| 2091 |
+
parity = compare_model_parity(
|
| 2092 |
+
model,
|
| 2093 |
+
images,
|
| 2094 |
+
winds,
|
| 2095 |
+
torch_device,
|
| 2096 |
+
float(train_cfg["device_parity_tol"]),
|
| 2097 |
+
policy=policy,
|
| 2098 |
+
)
|
| 2099 |
+
|
| 2100 |
+
def _on_epoch_end(*, epoch, model, optimizer, history, stopper, steps, stopped_early) -> None:
|
| 2101 |
+
blob = {
|
| 2102 |
+
"state_dict": {key: value.detach().cpu() for key, value in model.state_dict().items()},
|
| 2103 |
+
"optimizer_state_dict": _optimizer_cpu_state(optimizer),
|
| 2104 |
+
"epoch": int(epoch),
|
| 2105 |
+
"history": list(history),
|
| 2106 |
+
"best_state": stopper.best_state,
|
| 2107 |
+
"best_metric": float(stopper.best),
|
| 2108 |
+
"waits": int(stopper.waits),
|
| 2109 |
+
"steps": int(steps),
|
| 2110 |
+
"stopped_early": bool(stopped_early),
|
| 2111 |
+
"run_id": run_id,
|
| 2112 |
+
"dataset": dataset_name,
|
| 2113 |
+
"model_name": str(resolved["model"]["name"]),
|
| 2114 |
+
"seed": seed,
|
| 2115 |
+
"n_excluded": int(n_excluded),
|
| 2116 |
+
}
|
| 2117 |
+
torch.save(blob, run_dir / LAST_CHECKPOINT)
|
| 2118 |
+
|
| 2119 |
+
model, history, stopped_early, best_val_mae, peak_bytes = _fit_run(
|
| 2120 |
+
model,
|
| 2121 |
+
train_loader,
|
| 2122 |
+
val_loader,
|
| 2123 |
+
train_cfg,
|
| 2124 |
+
torch_device,
|
| 2125 |
+
max_steps,
|
| 2126 |
+
start_epoch=start_epoch,
|
| 2127 |
+
history=prior_history,
|
| 2128 |
+
stopper=restored_stopper,
|
| 2129 |
+
steps_done=steps_done,
|
| 2130 |
+
optimizer_state=optimizer_state,
|
| 2131 |
+
on_epoch_end=_on_epoch_end,
|
| 2132 |
+
already_stopped=already_stopped,
|
| 2133 |
+
loss_weighting=balance["loss_weighting"],
|
| 2134 |
+
)
|
| 2135 |
+
if not history:
|
| 2136 |
+
raise RuntimeError("training produced no loss curve")
|
| 2137 |
+
val_truth, val_pred = _collect_predictions(model, val_loader, torch_device, policy)
|
| 2138 |
+
if uses_sequences(resolved):
|
| 2139 |
+
val_windows = frame_windows(labeled, "val", model_n_frames(resolved))
|
| 2140 |
+
indexed = labeled.set_index(labeled["sample_id"].astype(str), drop=False)
|
| 2141 |
+
last_rows = [_row(indexed, w[-1]) for w in val_windows]
|
| 2142 |
+
if wind_column == "wind_kt_3min" and "wind_kt_scale" in labeled.columns:
|
| 2143 |
+
val_scales = np.array([float(r.get("wind_kt_scale", 1.0)) for r in last_rows], dtype=np.float64)
|
| 2144 |
+
else:
|
| 2145 |
+
val_scales = np.ones(len(last_rows), dtype=np.float64)
|
| 2146 |
+
val_raw_truth = np.array([float(r["wind_speed_kt"]) for r in last_rows], dtype=np.float64)
|
| 2147 |
+
val_raw_pred = back_converted_prediction(val_pred, val_scales)
|
| 2148 |
+
else:
|
| 2149 |
+
val_raw_pred = back_converted_prediction(
|
| 2150 |
+
val_pred, np.array([row["scale"] for row in val_records], dtype=np.float64)
|
| 2151 |
+
)
|
| 2152 |
+
val_raw_truth = np.array([row["raw_wind"] for row in val_records], dtype=np.float64)
|
| 2153 |
+
if score_test and test_loader is not None:
|
| 2154 |
+
test_truth, test_pred = _collect_predictions(model, test_loader, torch_device, policy)
|
| 2155 |
+
if uses_sequences(resolved):
|
| 2156 |
+
test_windows = frame_windows(labeled, "test", model_n_frames(resolved))
|
| 2157 |
+
indexed = labeled.set_index(labeled["sample_id"].astype(str), drop=False)
|
| 2158 |
+
last_rows = [_row(indexed, w[-1]) for w in test_windows]
|
| 2159 |
+
if wind_column == "wind_kt_3min" and "wind_kt_scale" in labeled.columns:
|
| 2160 |
+
test_scales = np.array([float(r.get("wind_kt_scale", 1.0)) for r in last_rows], dtype=np.float64)
|
| 2161 |
+
else:
|
| 2162 |
+
test_scales = np.ones(len(last_rows), dtype=np.float64)
|
| 2163 |
+
test_raw_truth = np.array([float(r["wind_speed_kt"]) for r in last_rows], dtype=np.float64)
|
| 2164 |
+
test_raw_pred = back_converted_prediction(test_pred, test_scales)
|
| 2165 |
+
else:
|
| 2166 |
+
test_raw_pred = back_converted_prediction(
|
| 2167 |
+
test_pred, np.array([row["scale"] for row in test_records], dtype=np.float64)
|
| 2168 |
+
)
|
| 2169 |
+
test_raw_truth = np.array([row["raw_wind"] for row in test_records], dtype=np.float64)
|
| 2170 |
+
test_metrics = _score_split(test_truth, test_pred, resolved)
|
| 2171 |
+
test_raw_metrics = _score_split(test_raw_truth, test_raw_pred, resolved)
|
| 2172 |
+
else:
|
| 2173 |
+
test_metrics = {"scored": False, "reason": test_refusal}
|
| 2174 |
+
test_raw_metrics = {"scored": False, "reason": test_refusal}
|
| 2175 |
+
checkpoint_name = str(resolved["paths"]["checkpoint_name"])
|
| 2176 |
+
if not checkpoint_name or checkpoint_name != Path(checkpoint_name).name:
|
| 2177 |
+
raise ValueError("paths.checkpoint_name must be a file name, not a path")
|
| 2178 |
+
checkpoint = run_dir / checkpoint_name
|
| 2179 |
+
split_ids = {name: sorted(groups[name]) for name in ("train", "val", "test")}
|
| 2180 |
+
train_winds = labeled.loc[labeled["split"] == "train", wind_column].to_numpy(dtype=np.float64)
|
| 2181 |
+
conversion_note = run_conversion_note(labeled)
|
| 2182 |
+
properties = xpu_device_properties(torch_device)
|
| 2183 |
+
commit = git_commit()
|
| 2184 |
+
payload = {
|
| 2185 |
+
"state_dict": {key: value.detach().cpu() for key, value in model.state_dict().items()},
|
| 2186 |
+
"model_name": str(resolved["model"]["name"]),
|
| 2187 |
+
"dropout": float(resolved["model"]["dropout"]),
|
| 2188 |
+
"pretrained": False,
|
| 2189 |
+
"in_channels": int(resolved["data"]["channels"]),
|
| 2190 |
+
"n_classes": len(known),
|
| 2191 |
+
"class_names": known,
|
| 2192 |
+
"edges_kt": [float(edge) for edge in resolved["data"]["imd5_edges_kt"]],
|
| 2193 |
+
"norm_mean": stats.mean,
|
| 2194 |
+
"norm_std": stats.std,
|
| 2195 |
+
"norm_source_split": stats.source_split,
|
| 2196 |
+
"norm_by_dataset": dataset_stats,
|
| 2197 |
+
"image_size": image_size,
|
| 2198 |
+
"max_missing_fraction": max_missing,
|
| 2199 |
+
"mean_baseline_kt": float(np.mean(train_winds)),
|
| 2200 |
+
"is_synthetic": bool(synthetic),
|
| 2201 |
+
"wind_averaging": wind_period,
|
| 2202 |
+
"wind_averaging_s": wind_averaging_seconds(wind_period),
|
| 2203 |
+
"wind_averaging_by_split": averaging,
|
| 2204 |
+
"wind_averaging_mismatch": bool(mismatch),
|
| 2205 |
+
"label_column": label_column,
|
| 2206 |
+
"wind_conversion": conversion_note,
|
| 2207 |
+
"split": {
|
| 2208 |
+
"strategy": str(resolved["split"]["strategy"]),
|
| 2209 |
+
"seed": int(resolved["split"]["seed"]),
|
| 2210 |
+
"test_fraction": float(resolved["split"]["test_fraction"]),
|
| 2211 |
+
"val_fraction": float(resolved["split"]["val_fraction"]),
|
| 2212 |
+
},
|
| 2213 |
+
"split_storm_ids": split_ids,
|
| 2214 |
+
"best_val_loss": best_val_mae,
|
| 2215 |
+
"best_val_mae": best_val_mae,
|
| 2216 |
+
"epoch": int(history[-1]["epoch"]),
|
| 2217 |
+
"present_as_forecast": False,
|
| 2218 |
+
"honesty": SMOKE_BANNER if synthetic else NOT_A_FORECAST,
|
| 2219 |
+
"n_frames": model_n_frames(resolved) if uses_sequences(resolved) else 1,
|
| 2220 |
+
"size_head": size_head,
|
| 2221 |
+
"hidden": int(resolved["model"]["hidden"]) if uses_sequences(resolved) else None,
|
| 2222 |
+
"config_hash": digest,
|
| 2223 |
+
"seed": seed,
|
| 2224 |
+
"dataset": dataset_name,
|
| 2225 |
+
"run_id": run_id,
|
| 2226 |
+
"result": False if synthetic else True,
|
| 2227 |
+
"device": torch_device.type,
|
| 2228 |
+
"device_requested": device_name,
|
| 2229 |
+
"precision": policy.precision,
|
| 2230 |
+
"use_grad_scaler": bool(policy.use_grad_scaler),
|
| 2231 |
+
"grad_accum_steps": int(train_cfg["grad_accum_steps"]),
|
| 2232 |
+
"peak_memory_bytes": peak_bytes,
|
| 2233 |
+
"git_commit": commit,
|
| 2234 |
+
"parent_run_id": None if parent_run_id is None else str(parent_run_id),
|
| 2235 |
+
"parent_checkpoint_sha256": parent_sha,
|
| 2236 |
+
"xpu_device_properties": properties,
|
| 2237 |
+
"device_parity_ok": None if parity is None else bool(parity["ok"]),
|
| 2238 |
+
"device_parity_max_abs_diff": None if parity is None else parity["max_abs_diff"],
|
| 2239 |
+
"device_parity_output_max_abs": None if parity is None else parity["output_max_abs"],
|
| 2240 |
+
"device_parity_loss_max_abs": None if parity is None else parity["loss_max_abs"],
|
| 2241 |
+
"device_parity_tol": float(train_cfg["device_parity_tol"]),
|
| 2242 |
+
"intensity_balance": balance_payload,
|
| 2243 |
+
}
|
| 2244 |
+
torch.save(payload, checkpoint)
|
| 2245 |
+
(run_dir / "resolved_config.yaml").write_text(
|
| 2246 |
+
yaml.safe_dump(resolved, sort_keys=False), encoding="utf-8"
|
| 2247 |
+
)
|
| 2248 |
+
_write_loss_curve(history, run_dir / "loss_curve.csv", run_dir / "loss_curve.png")
|
| 2249 |
+
metrics = {
|
| 2250 |
+
"result": False if synthetic else True,
|
| 2251 |
+
"is_synthetic": bool(synthetic),
|
| 2252 |
+
"quote_as_result": "no",
|
| 2253 |
+
"present_as_forecast": False,
|
| 2254 |
+
"dataset": dataset_name,
|
| 2255 |
+
"model": str(resolved["model"]["name"]),
|
| 2256 |
+
"seed": seed,
|
| 2257 |
+
"config_hash": digest,
|
| 2258 |
+
"git_commit": commit,
|
| 2259 |
+
"resolved_config": "resolved_config.yaml",
|
| 2260 |
+
"run_id": run_id,
|
| 2261 |
+
"wind_averaging": wind_period,
|
| 2262 |
+
"wind_averaging_s": wind_averaging_seconds(wind_period),
|
| 2263 |
+
"wind_averaging_by_split": averaging,
|
| 2264 |
+
"wind_averaging_mismatch": bool(mismatch),
|
| 2265 |
+
"label_column": label_column,
|
| 2266 |
+
"wind_conversion": conversion_note,
|
| 2267 |
+
"parent_run_id": None if parent_run_id is None else str(parent_run_id),
|
| 2268 |
+
"parent_checkpoint_sha256": parent_sha,
|
| 2269 |
+
"n_excluded": int(n_excluded),
|
| 2270 |
+
"stopped_early": bool(stopped_early),
|
| 2271 |
+
"best_val_mae": best_val_mae,
|
| 2272 |
+
"epochs_ran": int(len(history)),
|
| 2273 |
+
"split_storm_ids": split_ids,
|
| 2274 |
+
"scored_by": "src.evaluate.score_winds",
|
| 2275 |
+
"val": _score_split(val_truth, val_pred, resolved),
|
| 2276 |
+
"val_raw": _score_split(val_raw_truth, val_raw_pred, resolved),
|
| 2277 |
+
"test": test_metrics,
|
| 2278 |
+
"test_raw": test_raw_metrics,
|
| 2279 |
+
"intensity_balance": balance_payload,
|
| 2280 |
+
"device": torch_device.type,
|
| 2281 |
+
"device_requested": device_name,
|
| 2282 |
+
"precision": policy.precision,
|
| 2283 |
+
"use_grad_scaler": bool(policy.use_grad_scaler),
|
| 2284 |
+
"grad_accum_steps": int(train_cfg["grad_accum_steps"]),
|
| 2285 |
+
"peak_memory_bytes": peak_bytes,
|
| 2286 |
+
"xpu_device_properties": properties,
|
| 2287 |
+
"device_parity_ok": None if parity is None else bool(parity["ok"]),
|
| 2288 |
+
"device_parity_max_abs_diff": None if parity is None else parity["max_abs_diff"],
|
| 2289 |
+
"device_parity_output_max_abs": None if parity is None else parity["output_max_abs"],
|
| 2290 |
+
"device_parity_loss_max_abs": None if parity is None else parity["loss_max_abs"],
|
| 2291 |
+
"device_parity_tol": float(train_cfg["device_parity_tol"]),
|
| 2292 |
+
"norm_by_dataset": dataset_stats,
|
| 2293 |
+
"note": SMOKE_BANNER if synthetic else NOT_A_FORECAST,
|
| 2294 |
+
}
|
| 2295 |
+
on_fix_only = False
|
| 2296 |
+
if dataset_name == "incyde":
|
| 2297 |
+
on_fix_only = config_flag(
|
| 2298 |
+
(resolved.get("incyde") or {}).get("on_fix_only_eval", False),
|
| 2299 |
+
"incyde.on_fix_only_eval",
|
| 2300 |
+
)
|
| 2301 |
+
if on_fix_only and "on_fix" not in labeled.columns:
|
| 2302 |
+
raise ValueError("incyde.on_fix_only_eval needs on_fix on the INCYDE rows")
|
| 2303 |
+
metrics["on_fix_only_eval"] = bool(on_fix_only)
|
| 2304 |
+
if on_fix_only:
|
| 2305 |
+
# Overall val and val_raw stay the full validation split. This block
|
| 2306 |
+
# is an extra slice. Unknown on_fix rows are not treated as on-fix.
|
| 2307 |
+
flags = [row.get("on_fix") for row in val_records]
|
| 2308 |
+
metrics["val_on_fix"] = on_fix_metrics(val_truth, val_pred, flags, resolved)
|
| 2309 |
+
metrics["val_raw_on_fix"] = on_fix_metrics(val_raw_truth, val_raw_pred, flags, resolved)
|
| 2310 |
+
if str(resolved["split"]["strategy"]).strip().lower() == "year_holdout_2019":
|
| 2311 |
+
from src.incyde import YEAR_HOLDOUT_NOTE
|
| 2312 |
+
|
| 2313 |
+
metrics["year_holdout_2019"] = YEAR_HOLDOUT_NOTE
|
| 2314 |
+
metrics["year_holdout_2019_indicative"] = True
|
| 2315 |
+
(run_dir / "metrics.json").write_text(json.dumps(metrics, indent=2) + "\n", encoding="utf-8")
|
| 2316 |
+
if synthetic:
|
| 2317 |
+
print(SMOKE_BANNER)
|
| 2318 |
+
else:
|
| 2319 |
+
print(NOT_A_FORECAST)
|
| 2320 |
+
print(f"Wrote run record {run_dir}")
|
| 2321 |
+
return run_dir
|
| 2322 |
+
|
| 2323 |
+
|
| 2324 |
+
def main(argv: list[str] | None = None) -> Path:
|
| 2325 |
+
"""``python -m src.train --config config/config.yaml``."""
|
| 2326 |
+
parser = argparse.ArgumentParser(
|
| 2327 |
+
description="Train a wind-speed model. Hyperparameters, paths, and seeds come from the YAML."
|
| 2328 |
+
)
|
| 2329 |
+
parser.add_argument("--config", type=Path, required=True)
|
| 2330 |
+
parser.add_argument("--dataset", choices=_DATASETS, default=None)
|
| 2331 |
+
parser.add_argument("--model", choices=("simplecnn", "resnet18", "convlstm"), default=None)
|
| 2332 |
+
parser.add_argument("--max-steps", type=int, default=None)
|
| 2333 |
+
parser.add_argument("--device", choices=("auto", "xpu", "cuda", "cpu"), default=None)
|
| 2334 |
+
parser.add_argument("--resume", type=Path, default=None)
|
| 2335 |
+
parser.add_argument("--init-from", type=Path, default=None)
|
| 2336 |
+
parser.add_argument(
|
| 2337 |
+
"--allow-final-test",
|
| 2338 |
+
action="store_true",
|
| 2339 |
+
help="Score INCYDE test storms. Without this flag the test split is withheld.",
|
| 2340 |
+
)
|
| 2341 |
+
args = parser.parse_args(argv)
|
| 2342 |
+
config = load_config(args.config)
|
| 2343 |
+
return run_training(
|
| 2344 |
+
config,
|
| 2345 |
+
dataset=args.dataset,
|
| 2346 |
+
model=args.model,
|
| 2347 |
+
max_steps=args.max_steps,
|
| 2348 |
+
device=args.device,
|
| 2349 |
+
resume=args.resume,
|
| 2350 |
+
init_from=args.init_from,
|
| 2351 |
+
allow_final_test=bool(args.allow_final_test),
|
| 2352 |
+
)
|
| 2353 |
+
|
| 2354 |
+
|
| 2355 |
+
if __name__ == "__main__":
|
| 2356 |
+
main()
|
bundle/src/verify_splits.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CLI that runs a 6-point data-leakage audit on the configured splits.
|
| 2 |
+
|
| 3 |
+
The six checks are:
|
| 4 |
+
|
| 5 |
+
1. storm_wise splits keep storms whole and disjoint.
|
| 6 |
+
2. chronological splits keep storms whole and disjoint.
|
| 7 |
+
3. holdout_basin splits keep storms whole and disjoint.
|
| 8 |
+
4. Random / frame / shuffle strategies raise ``LeakageError``.
|
| 9 |
+
5. No forbidden feature name leaks into the model matrix.
|
| 10 |
+
6. Cross-split previous-frame links are nulled.
|
| 11 |
+
|
| 12 |
+
Usage::
|
| 13 |
+
|
| 14 |
+
python -m src.verify_splits --config config/config_smoke.yaml
|
| 15 |
+
|
| 16 |
+
The exit code is 0 when all six checks pass. This module does not import
|
| 17 |
+
torch and does not download imagery.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import sys
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import pandas as pd
|
| 28 |
+
|
| 29 |
+
from src.config import load_config
|
| 30 |
+
from src.make_smoke_data import write_smoke
|
| 31 |
+
from src.schema import require_valid
|
| 32 |
+
from src.splits import (
|
| 33 |
+
LeakageError,
|
| 34 |
+
add_previous_frame_id,
|
| 35 |
+
assert_no_forbidden_inputs,
|
| 36 |
+
assign_storms,
|
| 37 |
+
null_cross_split_links,
|
| 38 |
+
storm_ids_by_split,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _build_smoke_frame(config: dict) -> pd.DataFrame:
|
| 43 |
+
"""Return a validated manifest from the smoke config's data path."""
|
| 44 |
+
manifest_path = Path(config["paths"]["manifest"])
|
| 45 |
+
if not manifest_path.exists():
|
| 46 |
+
# Generate smoke data on the fly so the audit is self-contained.
|
| 47 |
+
out_dir = manifest_path.parent
|
| 48 |
+
write_smoke(out_dir, seed=config.get("project", {}).get("seed", 7))
|
| 49 |
+
frame = pd.read_csv(manifest_path)
|
| 50 |
+
return require_valid(frame)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _assert_disjoint(assigned: pd.DataFrame) -> dict[str, frozenset[str]]:
|
| 54 |
+
"""Verify that storm-id sets across splits are disjoint."""
|
| 55 |
+
groups = storm_ids_by_split(assigned)
|
| 56 |
+
assert groups["train"], "train is empty"
|
| 57 |
+
assert groups["val"], "val is empty"
|
| 58 |
+
assert groups["test"], "test is empty"
|
| 59 |
+
assert groups["train"].isdisjoint(groups["val"]), "train ∩ val is non-empty"
|
| 60 |
+
assert groups["train"].isdisjoint(groups["test"]), "train ∩ test is non-empty"
|
| 61 |
+
assert groups["val"].isdisjoint(groups["test"]), "val ∩ test is non-empty"
|
| 62 |
+
# Every storm is in exactly one split.
|
| 63 |
+
counts = assigned.groupby(assigned["storm_id"].astype(str))["split"].nunique()
|
| 64 |
+
assert int(counts.max()) == 1, "a storm appears in more than one split"
|
| 65 |
+
return groups
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _run_strategy(frame: pd.DataFrame, strategy: str, config: dict) -> None:
|
| 69 |
+
"""Check that a strategy assigns splits correctly."""
|
| 70 |
+
split_cfg = dict(config.get("split", {}))
|
| 71 |
+
kwargs: dict = {
|
| 72 |
+
"test_fraction": float(split_cfg.get("test_fraction", 0.2)),
|
| 73 |
+
"val_fraction": float(split_cfg.get("val_fraction", 0.2)),
|
| 74 |
+
"seed": int(split_cfg.get("seed", 42)),
|
| 75 |
+
}
|
| 76 |
+
if strategy == "chronological":
|
| 77 |
+
holdout_years = [int(y) for y in (split_cfg.get("holdout_years") or [])]
|
| 78 |
+
if not holdout_years:
|
| 79 |
+
# Use at least one year for the audit.
|
| 80 |
+
if "year" in frame.columns:
|
| 81 |
+
years = sorted(frame["year"].dropna().unique())
|
| 82 |
+
holdout_years = [int(years[-1])] if years else [2021]
|
| 83 |
+
else:
|
| 84 |
+
holdout_years = [2021]
|
| 85 |
+
kwargs["holdout_years"] = holdout_years
|
| 86 |
+
if strategy == "holdout_basin":
|
| 87 |
+
holdout_basin = split_cfg.get("holdout_basin") or None
|
| 88 |
+
if not holdout_basin:
|
| 89 |
+
if "basin" in frame.columns:
|
| 90 |
+
basins = sorted(frame["basin"].dropna().unique())
|
| 91 |
+
holdout_basin = basins[0] if basins else "NIO"
|
| 92 |
+
else:
|
| 93 |
+
holdout_basin = "NIO"
|
| 94 |
+
kwargs["holdout_basin"] = holdout_basin
|
| 95 |
+
|
| 96 |
+
assigned = assign_storms(frame, strategy, **kwargs)
|
| 97 |
+
# Deterministic: same call same result.
|
| 98 |
+
again = assign_storms(frame, strategy, **kwargs)
|
| 99 |
+
assert assigned["split"].tolist() == again["split"].tolist(), (
|
| 100 |
+
f"{strategy}: non-deterministic assignment"
|
| 101 |
+
)
|
| 102 |
+
_assert_disjoint(assigned)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def audit(config: dict) -> list[str]:
|
| 106 |
+
"""Run the 6-point leakage audit. Returns a list of failure messages."""
|
| 107 |
+
frame = _build_smoke_frame(config)
|
| 108 |
+
failures: list[str] = []
|
| 109 |
+
|
| 110 |
+
# --- Check 1: storm_wise ---
|
| 111 |
+
try:
|
| 112 |
+
_run_strategy(frame, "storm_wise", config)
|
| 113 |
+
print(" [PASS] 1. storm_wise splits are disjoint")
|
| 114 |
+
except Exception as exc:
|
| 115 |
+
failures.append(f"1. storm_wise: {exc}")
|
| 116 |
+
print(f" [FAIL] 1. storm_wise: {exc}")
|
| 117 |
+
|
| 118 |
+
# --- Check 2: chronological ---
|
| 119 |
+
try:
|
| 120 |
+
_run_strategy(frame, "chronological", config)
|
| 121 |
+
print(" [PASS] 2. chronological splits are disjoint")
|
| 122 |
+
except Exception as exc:
|
| 123 |
+
failures.append(f"2. chronological: {exc}")
|
| 124 |
+
print(f" [FAIL] 2. chronological: {exc}")
|
| 125 |
+
|
| 126 |
+
# --- Check 3: holdout_basin ---
|
| 127 |
+
try:
|
| 128 |
+
_run_strategy(frame, "holdout_basin", config)
|
| 129 |
+
print(" [PASS] 3. holdout_basin splits are disjoint")
|
| 130 |
+
except Exception as exc:
|
| 131 |
+
failures.append(f"3. holdout_basin: {exc}")
|
| 132 |
+
print(f" [FAIL] 3. holdout_basin: {exc}")
|
| 133 |
+
|
| 134 |
+
# --- Check 4: random splits raise LeakageError ---
|
| 135 |
+
random_ok = True
|
| 136 |
+
for name in ("random", "frame", "shuffle", "random_frame"):
|
| 137 |
+
try:
|
| 138 |
+
assign_storms(frame, name)
|
| 139 |
+
failures.append(f"4. {name} did not raise LeakageError")
|
| 140 |
+
random_ok = False
|
| 141 |
+
except LeakageError:
|
| 142 |
+
pass
|
| 143 |
+
except Exception as exc:
|
| 144 |
+
failures.append(f"4. {name} raised unexpected {type(exc).__name__}: {exc}")
|
| 145 |
+
random_ok = False
|
| 146 |
+
if random_ok:
|
| 147 |
+
print(" [PASS] 4. Random splits raise LeakageError")
|
| 148 |
+
else:
|
| 149 |
+
print(" [FAIL] 4. Random splits did not all raise LeakageError")
|
| 150 |
+
|
| 151 |
+
# --- Check 5: no forbidden features in model matrix ---
|
| 152 |
+
try:
|
| 153 |
+
from src.features import FeatureSpec
|
| 154 |
+
|
| 155 |
+
feature_names = list(FeatureSpec().feature_names())
|
| 156 |
+
assert_no_forbidden_inputs(feature_names, "model features")
|
| 157 |
+
print(" [PASS] 5. No forbidden features in default feature set")
|
| 158 |
+
except LeakageError as exc:
|
| 159 |
+
failures.append(f"5. forbidden features: {exc}")
|
| 160 |
+
print(f" [FAIL] 5. {exc}")
|
| 161 |
+
except Exception as exc:
|
| 162 |
+
failures.append(f"5. feature check error: {exc}")
|
| 163 |
+
print(f" [FAIL] 5. {exc}")
|
| 164 |
+
|
| 165 |
+
# --- Check 6: cross-split links are nulled ---
|
| 166 |
+
try:
|
| 167 |
+
split_cfg = dict(config.get("split", {}))
|
| 168 |
+
assigned = assign_storms(
|
| 169 |
+
frame,
|
| 170 |
+
"storm_wise",
|
| 171 |
+
test_fraction=float(split_cfg.get("test_fraction", 0.2)),
|
| 172 |
+
val_fraction=float(split_cfg.get("val_fraction", 0.2)),
|
| 173 |
+
seed=int(split_cfg.get("seed", 42)),
|
| 174 |
+
)
|
| 175 |
+
linked = add_previous_frame_id(assigned)
|
| 176 |
+
linked["split"] = assigned.loc[linked.index, "split"]
|
| 177 |
+
# Artificially set a cross-split link.
|
| 178 |
+
train_ids = linked.loc[linked["split"] == "train", "sample_id"].tolist()
|
| 179 |
+
test_ids = linked.loc[linked["split"] == "test", "sample_id"].tolist()
|
| 180 |
+
if train_ids and test_ids:
|
| 181 |
+
dirty = linked.copy()
|
| 182 |
+
dirty.loc[dirty["sample_id"] == train_ids[0], "prev_sample_id"] = test_ids[0]
|
| 183 |
+
cleaned, dropped = null_cross_split_links(dirty)
|
| 184 |
+
assert dropped >= 1, "cross-split link was not removed"
|
| 185 |
+
assert pd.isna(
|
| 186 |
+
cleaned.loc[cleaned["sample_id"] == train_ids[0], "prev_sample_id"]
|
| 187 |
+
).all(), "cross-split link survived cleaning"
|
| 188 |
+
print(" [PASS] 6. Cross-split previous-frame links are nulled")
|
| 189 |
+
except Exception as exc:
|
| 190 |
+
failures.append(f"6. cross-split links: {exc}")
|
| 191 |
+
print(f" [FAIL] 6. {exc}")
|
| 192 |
+
|
| 193 |
+
return failures
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def main() -> None:
|
| 197 |
+
parser = argparse.ArgumentParser(
|
| 198 |
+
description="Run a 6-point data-leakage audit on the split strategy."
|
| 199 |
+
)
|
| 200 |
+
parser.add_argument(
|
| 201 |
+
"--config",
|
| 202 |
+
type=str,
|
| 203 |
+
default="config/config_smoke.yaml",
|
| 204 |
+
help="Path to YAML config file.",
|
| 205 |
+
)
|
| 206 |
+
args = parser.parse_args()
|
| 207 |
+
config = load_config(args.config)
|
| 208 |
+
print(f"Running 6-point leakage audit with {args.config}")
|
| 209 |
+
failures = audit(config)
|
| 210 |
+
if failures:
|
| 211 |
+
print(f"\n{len(failures)} check(s) failed:")
|
| 212 |
+
for msg in failures:
|
| 213 |
+
print(f" - {msg}")
|
| 214 |
+
sys.exit(1)
|
| 215 |
+
else:
|
| 216 |
+
print("\nAll 6 checks passed.")
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
if __name__ == "__main__":
|
| 220 |
+
main()
|
bundle/sync_bundle.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Copy the canonical project into a Hugging Face Space bundle.
|
| 2 |
+
|
| 3 |
+
The Space app imports ``src``. This script copies ``src/``, ``config/``,
|
| 4 |
+
and the bundled synthetic sample next to ``app.py`` so the Hub repo root
|
| 5 |
+
can import them. It does not train a model and it does not upload the bundle.
|
| 6 |
+
|
| 7 |
+
Run from a checkout, before the Hub upload::
|
| 8 |
+
|
| 9 |
+
python space/sync_bundle.py --out /tmp/cloudie-space
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import argparse
|
| 15 |
+
import shutil
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
DEFAULT_HF_MODEL_REPO = "Anlea/cloudie-weights"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class SpaceBundle:
|
| 23 |
+
"""Build the directory that is pushed to the Space repository."""
|
| 24 |
+
|
| 25 |
+
SPACE_FILES = ("app.py", "requirements.txt", "README.md", "sync_bundle.py")
|
| 26 |
+
PROJECT_TREES = ("src", "config")
|
| 27 |
+
SAMPLE = ("cloudie", "samples", "synthetic_ir.npy")
|
| 28 |
+
SKIP_NAMES = {
|
| 29 |
+
"__pycache__",
|
| 30 |
+
".pytest_cache",
|
| 31 |
+
".mypy_cache",
|
| 32 |
+
".ruff_cache",
|
| 33 |
+
"artifacts",
|
| 34 |
+
"data",
|
| 35 |
+
"reports",
|
| 36 |
+
".git",
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
@staticmethod
|
| 40 |
+
def repo_root() -> Path:
|
| 41 |
+
"""GitHub checkout that contains ``src/inference.py`` beside ``space/``."""
|
| 42 |
+
here = Path(__file__).resolve().parent
|
| 43 |
+
candidate = here.parent
|
| 44 |
+
if (candidate / "src" / "inference.py").is_file() and (here / "app.py").is_file():
|
| 45 |
+
return candidate
|
| 46 |
+
if (here / "src" / "inference.py").is_file():
|
| 47 |
+
return here
|
| 48 |
+
raise FileNotFoundError(
|
| 49 |
+
"src/inference.py was not found. Run this script from the Cloudie checkout."
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
@staticmethod
|
| 53 |
+
def ignore(directory: str, names: list[str]) -> set[str]:
|
| 54 |
+
"""Skip caches and local data. Keep ``cloudie/samples``."""
|
| 55 |
+
del directory
|
| 56 |
+
skipped = set()
|
| 57 |
+
for name in names:
|
| 58 |
+
if name in SpaceBundle.SKIP_NAMES or name.endswith((".pyc", ".pt", ".pth")):
|
| 59 |
+
skipped.add(name)
|
| 60 |
+
return skipped
|
| 61 |
+
|
| 62 |
+
@staticmethod
|
| 63 |
+
def build(destination: Path, repo_root: Path | None = None) -> Path:
|
| 64 |
+
"""Write a fresh bundle. Refuses to replace the checkout or its source trees."""
|
| 65 |
+
root = (repo_root or SpaceBundle.repo_root()).resolve()
|
| 66 |
+
destination = destination.resolve()
|
| 67 |
+
space_dir = root / "space"
|
| 68 |
+
if destination == root or destination in root.parents or destination == space_dir:
|
| 69 |
+
raise ValueError("Write the bundle to a new directory, for example space/bundle.")
|
| 70 |
+
for name in SpaceBundle.PROJECT_TREES:
|
| 71 |
+
tree = root / name
|
| 72 |
+
if destination == tree or tree in destination.parents or destination in tree.parents:
|
| 73 |
+
raise ValueError("The bundle destination must sit outside src, config, and cloudie.")
|
| 74 |
+
if destination.exists():
|
| 75 |
+
shutil.rmtree(destination)
|
| 76 |
+
destination.mkdir(parents=True)
|
| 77 |
+
for name in SpaceBundle.SPACE_FILES:
|
| 78 |
+
shutil.copy2(space_dir / name, destination / name)
|
| 79 |
+
for name in SpaceBundle.PROJECT_TREES:
|
| 80 |
+
shutil.copytree(root / name, destination / name, ignore=SpaceBundle.ignore)
|
| 81 |
+
sample = root.joinpath(*SpaceBundle.SAMPLE)
|
| 82 |
+
dest_sample = destination.joinpath(*SpaceBundle.SAMPLE)
|
| 83 |
+
dest_sample.parent.mkdir(parents=True, exist_ok=True)
|
| 84 |
+
shutil.copy2(sample, dest_sample)
|
| 85 |
+
return destination
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def main(argv: list[str] | None = None) -> int:
|
| 89 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 90 |
+
parser.add_argument(
|
| 91 |
+
"--out",
|
| 92 |
+
type=Path,
|
| 93 |
+
default=Path("space/bundle"),
|
| 94 |
+
help="Directory to write. Replaced when it already exists.",
|
| 95 |
+
)
|
| 96 |
+
args = parser.parse_args(argv)
|
| 97 |
+
built = SpaceBundle.build(args.out)
|
| 98 |
+
print(built)
|
| 99 |
+
return 0
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if __name__ == "__main__":
|
| 103 |
+
raise SystemExit(main())
|
requirements.txt
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
| 1 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 2 |
+
torch==2.9.1+cpu
|
| 3 |
+
torchvision==0.24.1+cpu
|
| 4 |
+
numpy>=1.24
|
| 5 |
+
pandas>=2.0
|
| 6 |
+
pyyaml>=6.0
|
| 7 |
+
pillow>=10.0
|
| 8 |
+
scikit-learn>=1.3
|