hail-ml-prediction-map / build_static_data.py
wcui0613's picture
Cluster-only display (s1>=0.3) + on-map 5-min time slider; smaller data
899567f verified
Raw History Blame Contribute Delete
2.62 kB
"""Convert yearly hail prediction .npz files into small per-day JSON files.
Source: hail_climo_YYYY.npz with arrays timestamp, lat, lon, s1_prob, s2_pred.
Output: data/index.json and data/<year>/<date>.json for a static web viewer.
"""
from pathlib import Path
import json
import re
import numpy as np
SOURCE_DIR = Path("/Users/wenjun/Downloads/outputs")
OUTPUT_DIR = Path(__file__).parent / "data"
# Keep only detected hail clusters: S1 flags a hail cluster when s1_prob >= 0.3,
# and only those clusters are passed to S2 for size classification.
MIN_PROB = 0.3
def year_of(path: Path) -> str:
match = re.search(r"(\d{4})", path.stem)
if not match:
raise ValueError(f"No year found in {path.name}")
return match.group(1)
def build() -> None:
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
index: dict[str, list[str]] = {}
for source in sorted(SOURCE_DIR.glob("hail_climo_*.npz")):
year = year_of(source)
with np.load(source, allow_pickle=True) as dataset:
timestamp = np.asarray(dataset["timestamp"]).astype(str)
lat = np.asarray(dataset["lat"], dtype=np.float32)
lon = np.asarray(dataset["lon"], dtype=np.float32)
s1 = np.asarray(dataset["s1_prob"], dtype=np.float32)
s2 = np.asarray(dataset["s2_pred"], dtype=np.int8)
date = np.array([value[:10] for value in timestamp])
time_of_day = np.array([value[11:19] for value in timestamp])
keep = (s1 >= MIN_PROB) | (s2 >= 1)
lat, lon, s1, s2 = lat[keep], lon[keep], s1[keep], s2[keep]
date, time_of_day = date[keep], time_of_day[keep]
year_dir = OUTPUT_DIR / year
year_dir.mkdir(parents=True, exist_ok=True)
unique_dates = sorted(np.unique(date).tolist())
index[year] = unique_dates
for day in unique_dates:
mask = date == day
payload = {
"lat": [round(float(v), 3) for v in lat[mask]],
"lon": [round(float(v), 3) for v in lon[mask]],
"s1": [round(float(v), 3) for v in s1[mask]],
"s2": [int(v) for v in s2[mask]],
"t": time_of_day[mask].tolist(),
}
with (year_dir / f"{day}.json").open("w") as handle:
json.dump(payload, handle, separators=(",", ":"))
print(f"{year}: {len(unique_dates)} days written")
with (OUTPUT_DIR / "index.json").open("w") as handle:
json.dump(index, handle, separators=(",", ":"))
print(f"index.json written with {len(index)} years")
if __name__ == "__main__":
build()