forked from linkong/planet
736 lines
25 KiB
Python
736 lines
25 KiB
Python
"""NOAA NCEP GFS 10m global wind field collector, storage, analytics, and point query engine."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import csv
|
|
from datetime import UTC, datetime
|
|
import io
|
|
import json
|
|
import math
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
from typing import Any
|
|
from uuid import uuid4
|
|
|
|
import cv2
|
|
import httpx
|
|
import numpy as np
|
|
from pydantic import BaseModel, Field
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.data_sources import get_data_sources_config
|
|
from app.core.logging import get_logger
|
|
from app.core.time import to_iso8601_utc
|
|
from app.models.datasource import DataSource
|
|
from app.models.datasource_config import DataSourceConfig
|
|
|
|
logger = get_logger(__name__, service="earth_wind")
|
|
|
|
REPO_ROOT = Path(__file__).resolve().parents[3]
|
|
WIND_DATA_DIR = REPO_ROOT / "data" / "earth-wind"
|
|
DEFAULT_GFS_ERDDAP_URL = "https://pae-paha.pacioos.hawaii.edu/erddap/griddap/ncep_global.csv0"
|
|
VERSION_PATTERN = re.compile(r"^[A-Za-z0-9._-]{4,64}$")
|
|
_WIND_WRITE_LOCK = asyncio.Lock()
|
|
|
|
EARTH_CIRCUMFERENCE_KM = 40075.017
|
|
|
|
# Reuse consistent maritime / aviation meteorological zones for global posture rollups
|
|
WIND_REGIONS: tuple[dict[str, Any], ...] = (
|
|
{
|
|
"key": "west_pacific",
|
|
"name": "西北太平洋",
|
|
"name_en": "Western North Pacific",
|
|
"lat_min": 5.0,
|
|
"lat_max": 35.0,
|
|
"lon_min": 120.0,
|
|
"lon_max": 165.0,
|
|
},
|
|
{
|
|
"key": "east_asia_coast",
|
|
"name": "东亚沿海",
|
|
"name_en": "East Asia Coastal Corridor",
|
|
"lat_min": 18.0,
|
|
"lat_max": 42.0,
|
|
"lon_min": 105.0,
|
|
"lon_max": 135.0,
|
|
},
|
|
{
|
|
"key": "south_china_sea",
|
|
"name": "南海海域",
|
|
"name_en": "South China Sea",
|
|
"lat_min": 3.0,
|
|
"lat_max": 23.0,
|
|
"lon_min": 105.0,
|
|
"lon_max": 122.0,
|
|
},
|
|
{
|
|
"key": "indian_ocean",
|
|
"name": "印度洋航道",
|
|
"name_en": "Indian Ocean Corridor",
|
|
"lat_min": -20.0,
|
|
"lat_max": 20.0,
|
|
"lon_min": 50.0,
|
|
"lon_max": 98.0,
|
|
},
|
|
{
|
|
"key": "arabian_red_sea",
|
|
"name": "阿拉伯海与红海",
|
|
"name_en": "Arabian & Red Sea",
|
|
"lat_min": 10.0,
|
|
"lat_max": 30.0,
|
|
"lon_min": 32.0,
|
|
"lon_max": 68.0,
|
|
},
|
|
{
|
|
"key": "north_pacific",
|
|
"name": "北太平洋航线",
|
|
"name_en": "North Pacific Corridor",
|
|
"lat_min": 30.0,
|
|
"lat_max": 58.0,
|
|
"lon_min": 140.0,
|
|
"lon_max": -125.0,
|
|
},
|
|
{
|
|
"key": "gulf_caribbean",
|
|
"name": "墨西哥湾与加勒比",
|
|
"name_en": "Gulf & Caribbean",
|
|
"lat_min": 10.0,
|
|
"lat_max": 32.0,
|
|
"lon_min": -98.0,
|
|
"lon_max": -60.0,
|
|
},
|
|
{
|
|
"key": "north_atlantic",
|
|
"name": "北大西洋航道",
|
|
"name_en": "North Atlantic Corridor",
|
|
"lat_min": 35.0,
|
|
"lat_max": 62.0,
|
|
"lon_min": -60.0,
|
|
"lon_max": -10.0,
|
|
},
|
|
)
|
|
|
|
|
|
class WindFieldConfig(BaseModel):
|
|
grid_step_deg: float = Field(default=2.0, ge=1.0, le=5.0)
|
|
gale_threshold_ms: float = Field(default=17.2, ge=10.0, le=35.0)
|
|
request_timeout_seconds: int = Field(default=25, ge=5, le=60)
|
|
max_history_runs: int = Field(default=12, ge=2, le=48)
|
|
|
|
|
|
DEFAULT_WIND_CONFIG = WindFieldConfig()
|
|
|
|
|
|
def _wind_dir() -> Path:
|
|
return WIND_DATA_DIR
|
|
|
|
|
|
def _manifest_path() -> Path:
|
|
return _wind_dir() / "manifest.json"
|
|
|
|
|
|
def _grids_dir() -> Path:
|
|
return _wind_dir() / "grids"
|
|
|
|
|
|
def _ensure_wind_dirs() -> None:
|
|
_grids_dir().mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
def _atomic_write_bytes(path: Path, content: bytes) -> None:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp_path = path.with_name(f".{path.name}.{uuid4().hex[:8]}.tmp")
|
|
try:
|
|
tmp_path.write_bytes(content)
|
|
os.replace(tmp_path, path)
|
|
finally:
|
|
if tmp_path.exists():
|
|
try:
|
|
tmp_path.unlink()
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def _atomic_write_json(path: Path, payload: Any) -> None:
|
|
encoded = json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8")
|
|
_atomic_write_bytes(path, encoded)
|
|
|
|
|
|
def _read_manifest() -> dict[str, Any]:
|
|
path = _manifest_path()
|
|
if not path.exists():
|
|
return {"latest_version": None, "updated_at": None, "runs": []}
|
|
try:
|
|
parsed = json.loads(path.read_text(encoding="utf-8"))
|
|
if isinstance(parsed, dict) and isinstance(parsed.get("runs"), list):
|
|
return parsed
|
|
except Exception:
|
|
pass
|
|
return {"latest_version": None, "updated_at": None, "runs": []}
|
|
|
|
|
|
def _wind_vector_to_bearing_deg(u_ms: float, v_ms: float) -> float:
|
|
"""Meteorological heading TO which wind blows (0=N, 90=E, 180=S, 270=W)."""
|
|
return (math.degrees(math.atan2(u_ms, v_ms)) + 360.0) % 360.0
|
|
|
|
|
|
def _bearing_to_cardinal(deg: float) -> str:
|
|
dirs = ("N", "NE", "E", "SE", "S", "SW", "W", "NW")
|
|
idx = int(round((deg % 360.0) / 45.0)) % 8
|
|
return dirs[idx]
|
|
|
|
|
|
def _speed_to_beaufort(speed_ms: float) -> int:
|
|
thresholds = (0.3, 1.6, 3.4, 5.5, 8.0, 10.8, 13.9, 17.2, 20.8, 24.5, 28.5, 32.7)
|
|
for force, limit in enumerate(thresholds):
|
|
if speed_ms < limit:
|
|
return force
|
|
return 12
|
|
|
|
|
|
def _match_region_name(lat: float, lon: float) -> tuple[str, str]:
|
|
wrapped = ((float(lon) + 180.0) % 360.0) - 180.0
|
|
for reg in WIND_REGIONS:
|
|
if not (reg["lat_min"] <= lat <= reg["lat_max"]):
|
|
continue
|
|
lon_min, lon_max = reg["lon_min"], reg["lon_max"]
|
|
if lon_min <= lon_max:
|
|
in_lon = lon_min <= wrapped <= lon_max
|
|
else:
|
|
in_lon = wrapped >= lon_min or wrapped <= lon_max
|
|
if in_lon:
|
|
return reg["name"], reg["name_en"]
|
|
return "公海全球风场", "Global High Seas"
|
|
|
|
|
|
async def read_wind_configuration(db: AsyncSession | None = None) -> dict[str, Any]:
|
|
endpoint = DEFAULT_GFS_ERDDAP_URL
|
|
raw_cfg: dict[str, Any] = {}
|
|
if db is not None and hasattr(db, "execute"):
|
|
try:
|
|
row = (
|
|
await db.execute(
|
|
select(DataSourceConfig).where(DataSourceConfig.name == "global_wind_gfs")
|
|
)
|
|
).scalar_one_or_none()
|
|
if row is not None:
|
|
if row.endpoint:
|
|
endpoint = str(row.endpoint).strip()
|
|
if isinstance(row.config, dict):
|
|
raw_cfg = dict(row.config)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
yaml_url = await get_data_sources_config().get_url("global_wind_gfs", db)
|
|
if yaml_url:
|
|
endpoint = yaml_url
|
|
except Exception:
|
|
pass
|
|
|
|
try:
|
|
validated = WindFieldConfig.model_validate(raw_cfg)
|
|
except Exception:
|
|
validated = DEFAULT_WIND_CONFIG
|
|
return {
|
|
"endpoint": endpoint,
|
|
"config": validated.model_dump(mode="json"),
|
|
}
|
|
|
|
|
|
def parse_erddap_csv0_wind(csv_text: str) -> dict[str, Any]:
|
|
"""Parse PacIOOS ERDDAP `ncep_global.csv0` `ugrd10m,vgrd10m` into `[-180..180]` grids."""
|
|
rows: list[tuple[float, float, float, float]] = []
|
|
forecast_time: str | None = None
|
|
|
|
reader = csv.reader(io.StringIO(csv_text))
|
|
for line in reader:
|
|
if len(line) < 5:
|
|
continue
|
|
t_raw, lat_s, lon_s, u_s, v_s = line[0].strip(), line[1].strip(), line[2].strip(), line[3].strip(), line[4].strip()
|
|
if t_raw.lower() == "time" or lat_s.lower() == "latitude":
|
|
continue
|
|
try:
|
|
lat = float(lat_s)
|
|
lon_raw = float(lon_s)
|
|
u_val = float(u_s)
|
|
v_val = float(v_s)
|
|
except ValueError:
|
|
continue
|
|
if not (math.isfinite(lat) and math.isfinite(lon_raw) and math.isfinite(u_val) and math.isfinite(v_val)):
|
|
continue
|
|
if forecast_time is None and t_raw:
|
|
forecast_time = t_raw
|
|
# Shift 0..360 longitude to [-180, 180)
|
|
lon_norm = ((lon_raw + 180.0) % 360.0) - 180.0
|
|
rows.append((round(lat, 3), round(lon_norm, 3), u_val, v_val))
|
|
|
|
if not rows:
|
|
raise RuntimeError("GFS wind ERDDAP payload contained zero valid grid samples")
|
|
|
|
lats = sorted({item[0] for item in rows})
|
|
lons = sorted({item[1] for item in rows})
|
|
lat_idx = {val: i for i, val in enumerate(lats)}
|
|
lon_idx = {val: i for i, val in enumerate(lons)}
|
|
|
|
height = len(lats)
|
|
width = len(lons)
|
|
u_grid = np.zeros((height, width), dtype=np.float32)
|
|
v_grid = np.zeros((height, width), dtype=np.float32)
|
|
|
|
for lat, lon, u_val, v_val in rows:
|
|
u_grid[lat_idx[lat], lon_idx[lon]] = u_val
|
|
v_grid[lat_idx[lat], lon_idx[lon]] = v_val
|
|
|
|
return {
|
|
"forecast_time": forecast_time,
|
|
"lats": np.asarray(lats, dtype=np.float32),
|
|
"lons": np.asarray(lons, dtype=np.float32),
|
|
"u": u_grid,
|
|
"v": v_grid,
|
|
}
|
|
|
|
|
|
def analyze_wind_grid(
|
|
parsed: dict[str, Any],
|
|
*,
|
|
config: WindFieldConfig,
|
|
) -> dict[str, Any]:
|
|
lats = parsed["lats"]
|
|
lons = parsed["lons"]
|
|
u_grid = parsed["u"]
|
|
v_grid = parsed["v"]
|
|
speed = np.sqrt(u_grid * u_grid + v_grid * v_grid).astype(np.float32)
|
|
|
|
lat_weights = np.maximum(np.cos(np.deg2rad(lats)), 0.05).astype(np.float32)[:, None]
|
|
weight_sum = float(np.sum(lat_weights) * speed.shape[1])
|
|
|
|
mean_speed = float(np.sum(speed * lat_weights) / max(weight_sum, 1e-6))
|
|
max_speed = float(np.max(speed))
|
|
gale_mask = speed >= float(config.gale_threshold_ms)
|
|
gale_cov_pct = float(np.sum(gale_mask.astype(np.float32) * lat_weights) / max(weight_sum, 1e-6) * 100.0)
|
|
|
|
# Identify coherent gale/storm cores via connected components
|
|
gale_u8 = (gale_mask.astype(np.uint8) * 255)
|
|
num_labels, labels, stats, _centroids = cv2.connectedComponentsWithStats(gale_u8, connectivity=8)
|
|
dlat = abs(float(lats[1] - lats[0])) if len(lats) > 1 else config.grid_step_deg
|
|
dlon = abs(float(lons[1] - lons[0])) if len(lons) > 1 else config.grid_step_deg
|
|
|
|
storm_cores: list[dict[str, Any]] = []
|
|
for label_id in range(1, num_labels):
|
|
pixel_count = int(stats[label_id, cv2.CC_STAT_AREA])
|
|
if pixel_count < 3:
|
|
continue
|
|
comp_mask = labels == label_id
|
|
comp_lats = lats[np.where(comp_mask)[0]]
|
|
comp_lons = lons[np.where(comp_mask)[1]]
|
|
center_lat = float(np.mean(comp_lats))
|
|
center_lon = float(np.mean(comp_lons))
|
|
comp_speeds = speed[comp_mask]
|
|
peak_ms = float(np.max(comp_speeds))
|
|
avg_ms = float(np.mean(comp_speeds))
|
|
cell_area = (
|
|
(dlat / 360.0) * EARTH_CIRCUMFERENCE_KM
|
|
* ((dlon / 360.0) * EARTH_CIRCUMFERENCE_KM * max(math.cos(math.radians(center_lat)), 0.1))
|
|
)
|
|
area_km2 = round(pixel_count * cell_area)
|
|
region_zh, region_en = _match_region_name(center_lat, center_lon)
|
|
storm_cores.append(
|
|
{
|
|
"id": f"gale-{label_id}",
|
|
"lat": round(center_lat, 2),
|
|
"lon": round(center_lon, 2),
|
|
"max_speed_ms": round(peak_ms, 1),
|
|
"mean_speed_ms": round(avg_ms, 1),
|
|
"beaufort": _speed_to_beaufort(peak_ms),
|
|
"area_km2": area_km2,
|
|
"region": region_zh,
|
|
"region_en": region_en,
|
|
"severity": "storm" if peak_ms >= 24.5 else "gale",
|
|
}
|
|
)
|
|
storm_cores.sort(key=lambda item: item["max_speed_ms"], reverse=True)
|
|
storm_cores = storm_cores[:24]
|
|
|
|
region_summaries: list[dict[str, Any]] = []
|
|
for reg in WIND_REGIONS:
|
|
lat_mask = (lats >= reg["lat_min"]) & (lats <= reg["lat_max"])
|
|
if reg["lon_min"] <= reg["lon_max"]:
|
|
lon_mask = (lons >= reg["lon_min"]) & (lons <= reg["lon_max"])
|
|
else:
|
|
lon_mask = (lons >= reg["lon_min"]) | (lons <= reg["lon_max"])
|
|
sub_mask = np.outer(lat_mask, lon_mask)
|
|
if not np.any(sub_mask):
|
|
continue
|
|
sub_speed = speed[sub_mask]
|
|
sub_u = u_grid[sub_mask]
|
|
sub_v = v_grid[sub_mask]
|
|
mean_reg = float(np.mean(sub_speed))
|
|
max_reg = float(np.max(sub_speed))
|
|
gale_reg = float(np.mean(sub_speed >= float(config.gale_threshold_ms)) * 100.0)
|
|
dom_u = float(np.mean(sub_u))
|
|
dom_v = float(np.mean(sub_v))
|
|
dom_deg = _wind_vector_to_bearing_deg(dom_u, dom_v)
|
|
posture = "gale_warning" if gale_reg >= 12.0 or max_reg >= 20.8 else ("breezy" if mean_reg >= 10.8 else "moderate")
|
|
region_summaries.append(
|
|
{
|
|
"key": reg["key"],
|
|
"name": reg["name"],
|
|
"name_en": reg["name_en"],
|
|
"mean_speed_ms": round(mean_reg, 1),
|
|
"max_speed_ms": round(max_reg, 1),
|
|
"gale_coverage_pct": round(gale_reg, 1),
|
|
"dominant_direction_deg": round(dom_deg, 1),
|
|
"dominant_cardinal": _bearing_to_cardinal(dom_deg),
|
|
"posture": posture,
|
|
}
|
|
)
|
|
|
|
return {
|
|
"global_summary": {
|
|
"mean_speed_ms": round(mean_speed, 2),
|
|
"max_speed_ms": round(max_speed, 2),
|
|
"gale_coverage_pct": round(gale_cov_pct, 2),
|
|
"storm_core_count": len(storm_cores),
|
|
"grid_width": int(u_grid.shape[1]),
|
|
"grid_height": int(u_grid.shape[0]),
|
|
"step_deg": round(float(config.grid_step_deg), 2),
|
|
"forecast_time": parsed.get("forecast_time"),
|
|
},
|
|
"regions": region_summaries,
|
|
"storm_cores": storm_cores,
|
|
}
|
|
|
|
|
|
def _remove_wind_run_files(version: str) -> int:
|
|
if not VERSION_PATTERN.match(version):
|
|
return 0
|
|
target = _grids_dir() / f"{version}.npz"
|
|
if target.exists():
|
|
try:
|
|
target.unlink()
|
|
return 1
|
|
except OSError:
|
|
pass
|
|
return 0
|
|
|
|
|
|
def prune_wind_artifacts(max_runs: int = 12) -> int:
|
|
if not _wind_dir().exists():
|
|
return 0
|
|
manifest = _read_manifest()
|
|
runs = manifest.get("runs", [])
|
|
kept = runs[: max(1, int(max_runs))]
|
|
kept_versions = {str(item.get("version")) for item in kept if item.get("version")}
|
|
removed = 0
|
|
for item in runs[max(1, int(max_runs)) :]:
|
|
ver = str(item.get("version") or "")
|
|
if ver:
|
|
removed += _remove_wind_run_files(ver)
|
|
if _grids_dir().exists():
|
|
for file_path in _grids_dir().iterdir():
|
|
if file_path.name.startswith(".") or file_path.stem not in kept_versions:
|
|
try:
|
|
file_path.unlink()
|
|
removed += 1
|
|
except OSError:
|
|
pass
|
|
if len(kept) != len(runs):
|
|
_atomic_write_json(
|
|
_manifest_path(),
|
|
{
|
|
"latest_version": kept[0].get("version") if kept else None,
|
|
"updated_at": manifest.get("updated_at"),
|
|
"runs": kept,
|
|
},
|
|
)
|
|
return removed
|
|
|
|
|
|
def clear_all_wind_artifacts() -> int:
|
|
removed = 0
|
|
if _grids_dir().exists():
|
|
for file_path in _grids_dir().iterdir():
|
|
if file_path.is_file():
|
|
try:
|
|
file_path.unlink()
|
|
removed += 1
|
|
except OSError:
|
|
pass
|
|
manifest_file = _manifest_path()
|
|
if manifest_file.exists():
|
|
try:
|
|
manifest_file.unlink()
|
|
removed += 1
|
|
except OSError:
|
|
pass
|
|
return removed
|
|
|
|
|
|
def _save_wind_run_sync(
|
|
*,
|
|
version: str,
|
|
captured_at: str,
|
|
parsed: dict[str, Any],
|
|
analysis: dict[str, Any],
|
|
max_history_runs: int,
|
|
) -> dict[str, Any]:
|
|
_ensure_wind_dirs()
|
|
grid_path = _grids_dir() / f"{version}.npz"
|
|
tmp_path = grid_path.with_name(f".{version}.{uuid4().hex[:8]}.npz")
|
|
try:
|
|
np.savez_compressed(
|
|
tmp_path,
|
|
lats=parsed["lats"],
|
|
lons=parsed["lons"],
|
|
u=parsed["u"],
|
|
v=parsed["v"],
|
|
)
|
|
os.replace(tmp_path, grid_path)
|
|
finally:
|
|
if tmp_path.exists():
|
|
try:
|
|
tmp_path.unlink()
|
|
except OSError:
|
|
pass
|
|
|
|
entry = {
|
|
"version": version,
|
|
"captured_at": captured_at,
|
|
"forecast_time": parsed.get("forecast_time"),
|
|
"source": "global_wind_gfs",
|
|
"grid_url": f"/api/v1/earth/wind/grid/{version}",
|
|
"file_size_bytes": grid_path.stat().st_size if grid_path.exists() else 0,
|
|
"global_summary": analysis["global_summary"],
|
|
"regions": analysis["regions"],
|
|
"storm_cores": analysis["storm_cores"],
|
|
}
|
|
|
|
manifest = _read_manifest()
|
|
runs = [item for item in manifest.get("runs", []) if item.get("version") != version]
|
|
runs.insert(0, entry)
|
|
kept_runs = runs[: max(1, int(max_history_runs))]
|
|
dropped = [str(item.get("version") or "") for item in runs[max(1, int(max_history_runs)) :]]
|
|
_atomic_write_json(
|
|
_manifest_path(),
|
|
{
|
|
"latest_version": version,
|
|
"updated_at": captured_at,
|
|
"runs": kept_runs,
|
|
},
|
|
)
|
|
for old_ver in dropped:
|
|
_remove_wind_run_files(old_ver)
|
|
return entry
|
|
|
|
|
|
async def collect_latest_wind_grid(db: AsyncSession | None = None) -> dict[str, Any]:
|
|
env = await read_wind_configuration(db)
|
|
config = WindFieldConfig.model_validate(env["config"])
|
|
endpoint = str(env["endpoint"] or DEFAULT_GFS_ERDDAP_URL).rstrip("/")
|
|
stride = max(1, int(round(float(config.grid_step_deg) * 2.0)))
|
|
query_url = (
|
|
f"{endpoint}?ugrd10m[(last)][(-90):{stride}:(90)][(0):{stride}:(359.5)],"
|
|
f"vgrd10m[(last)][(-90):{stride}:(90)][(0):{stride}:(359.5)]"
|
|
)
|
|
timeout = httpx.Timeout(float(config.request_timeout_seconds))
|
|
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthWindCollector)"}
|
|
|
|
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client:
|
|
response = await client.get(query_url)
|
|
response.raise_for_status()
|
|
csv_text = response.text
|
|
|
|
parsed = await asyncio.to_thread(parse_erddap_csv0_wind, csv_text)
|
|
analysis = await asyncio.to_thread(analyze_wind_grid, parsed, config=config)
|
|
|
|
now_utc = datetime.now(UTC)
|
|
version = now_utc.strftime("%Y%m%dT%H%M%SZ")
|
|
captured_at = to_iso8601_utc(now_utc) or now_utc.isoformat()
|
|
|
|
async with _WIND_WRITE_LOCK:
|
|
entry = await asyncio.to_thread(
|
|
_save_wind_run_sync,
|
|
version=version,
|
|
captured_at=captured_at,
|
|
parsed=parsed,
|
|
analysis=analysis,
|
|
max_history_runs=config.max_history_runs,
|
|
)
|
|
|
|
return {
|
|
"run": entry,
|
|
"global_summary": analysis["global_summary"],
|
|
"regions": analysis["regions"],
|
|
"storm_cores": analysis["storm_cores"],
|
|
"config": config.model_dump(mode="json"),
|
|
}
|
|
|
|
|
|
def _load_wind_npz(version: str) -> dict[str, np.ndarray] | None:
|
|
if not VERSION_PATTERN.match(version):
|
|
return None
|
|
path = (_grids_dir() / f"{version}.npz").resolve()
|
|
root = _grids_dir().resolve()
|
|
if path.parent != root or not path.exists():
|
|
return None
|
|
with np.load(path, allow_pickle=False) as archive:
|
|
return {
|
|
"lats": archive["lats"].copy(),
|
|
"lons": archive["lons"].copy(),
|
|
"u": archive["u"].copy(),
|
|
"v": archive["v"].copy(),
|
|
}
|
|
|
|
|
|
async def get_wind_runtime_meta(db: AsyncSession | None = None) -> dict[str, Any]:
|
|
ds_active = True
|
|
if db is not None and hasattr(db, "execute"):
|
|
try:
|
|
row = (
|
|
await db.execute(select(DataSource).where(DataSource.source == "global_wind_gfs"))
|
|
).scalar_one_or_none()
|
|
if row is not None:
|
|
ds_active = bool(row.is_active)
|
|
except Exception:
|
|
pass
|
|
|
|
manifest = _read_manifest()
|
|
runs = manifest.get("runs", [])
|
|
latest = runs[0] if runs else None
|
|
latest_version = str(latest.get("version")) if isinstance(latest, dict) and latest.get("version") else None
|
|
exists = bool(latest_version and (_grids_dir() / f"{latest_version}.npz").exists())
|
|
|
|
available = bool(ds_active and exists)
|
|
return {
|
|
"available": available,
|
|
"is_active": ds_active,
|
|
"version": latest_version if exists else None,
|
|
"captured_at": latest.get("captured_at") if exists and latest else None,
|
|
"forecast_time": latest.get("forecast_time") if exists and latest else None,
|
|
"grid_url": f"/api/v1/earth/wind/grid/{latest_version}" if available else None,
|
|
"global_summary": (latest.get("global_summary") or {}) if exists and latest else {},
|
|
"regions": (latest.get("regions") or []) if exists and latest else [],
|
|
"storm_cores": (latest.get("storm_cores") or []) if exists and latest else [],
|
|
"has_data": exists,
|
|
}
|
|
|
|
|
|
def read_wind_grid_payload(version: str) -> dict[str, Any] | None:
|
|
manifest = _read_manifest()
|
|
entry = next(
|
|
(item for item in manifest.get("runs", []) if item.get("version") == version),
|
|
None,
|
|
)
|
|
arrays = _load_wind_npz(version)
|
|
if arrays is None:
|
|
return None
|
|
lats = arrays["lats"]
|
|
lons = arrays["lons"]
|
|
u = arrays["u"]
|
|
v = arrays["v"]
|
|
speed = np.sqrt(u * u + v * v)
|
|
return {
|
|
"version": version,
|
|
"captured_at": entry.get("captured_at") if entry else None,
|
|
"forecast_time": entry.get("forecast_time") if entry else None,
|
|
"width": int(u.shape[1]),
|
|
"height": int(u.shape[0]),
|
|
"lat_min": float(lats[0]),
|
|
"lat_max": float(lats[-1]),
|
|
"lon_min": float(lons[0]),
|
|
"lon_max": float(lons[-1]),
|
|
"max_speed_ms": round(float(np.max(speed)), 2),
|
|
"u": [round(float(val), 2) for val in u.ravel().tolist()],
|
|
"v": [round(float(val), 2) for val in v.ravel().tolist()],
|
|
}
|
|
|
|
|
|
async def query_wind_point(
|
|
lat: float,
|
|
lon: float,
|
|
db: AsyncSession | None = None,
|
|
) -> dict[str, Any]:
|
|
env = await read_wind_configuration(db)
|
|
config = WindFieldConfig.model_validate(env["config"])
|
|
manifest = _read_manifest()
|
|
runs = manifest.get("runs", [])
|
|
latest = runs[0] if runs else None
|
|
version = str(latest.get("version") or "") if isinstance(latest, dict) else ""
|
|
arrays = _load_wind_npz(version) if version else None
|
|
if arrays is None:
|
|
return {
|
|
"available": False,
|
|
"latitude": round(float(lat), 4),
|
|
"longitude": round(float(lon), 4),
|
|
"u_ms": None,
|
|
"v_ms": None,
|
|
"speed_ms": None,
|
|
"direction_deg": None,
|
|
"direction_cardinal": None,
|
|
"beaufort": None,
|
|
}
|
|
|
|
lats = arrays["lats"]
|
|
lons = arrays["lons"]
|
|
u_arr = arrays["u"]
|
|
v_arr = arrays["v"]
|
|
|
|
clamped_lat = max(float(lats[0]), min(float(lats[-1]), float(lat)))
|
|
wrapped_lon = ((float(lon) + 180.0) % 360.0) - 180.0
|
|
|
|
# Bilinear interpolation across grid
|
|
lat_pos = float(np.interp(clamped_lat, lats, np.arange(len(lats), dtype=np.float32)))
|
|
lon_pos = float(np.interp(wrapped_lon, lons, np.arange(len(lons), dtype=np.float32)))
|
|
r0 = min(int(math.floor(lat_pos)), len(lats) - 1)
|
|
r1 = min(r0 + 1, len(lats) - 1)
|
|
c0 = min(int(math.floor(lon_pos)), len(lons) - 1)
|
|
c1 = min(c0 + 1, len(lons) - 1)
|
|
dr = lat_pos - r0
|
|
dc = lon_pos - c0
|
|
|
|
def _bilerp(grid: np.ndarray) -> float:
|
|
top = float(grid[r0, c0]) * (1.0 - dc) + float(grid[r0, c1]) * dc
|
|
bot = float(grid[r1, c0]) * (1.0 - dc) + float(grid[r1, c1]) * dc
|
|
return top * (1.0 - dr) + bot * dr
|
|
|
|
u_val = _bilerp(u_arr)
|
|
v_val = _bilerp(v_arr)
|
|
speed = math.hypot(u_val, v_val)
|
|
bearing = _wind_vector_to_bearing_deg(u_val, v_val)
|
|
region_zh, region_en = _match_region_name(lat, lon)
|
|
|
|
return {
|
|
"available": True,
|
|
"latitude": round(float(lat), 4),
|
|
"longitude": round(float(lon), 4),
|
|
"u_ms": round(u_val, 2),
|
|
"v_ms": round(v_val, 2),
|
|
"speed_ms": round(speed, 2),
|
|
"direction_deg": round(bearing, 1),
|
|
"direction_cardinal": _bearing_to_cardinal(bearing),
|
|
"beaufort": _speed_to_beaufort(speed),
|
|
"is_gale": speed >= float(config.gale_threshold_ms),
|
|
"region": region_zh,
|
|
"region_en": region_en,
|
|
"version": version,
|
|
"captured_at": latest.get("captured_at") if latest else None,
|
|
"forecast_time": latest.get("forecast_time") if latest else None,
|
|
}
|
|
|
|
|
|
async def get_wind_analysis_summary(db: AsyncSession | None = None) -> dict[str, Any]:
|
|
meta = await get_wind_runtime_meta(db)
|
|
return {
|
|
"available": meta["available"],
|
|
"is_active": meta["is_active"],
|
|
"version": meta["version"],
|
|
"captured_at": meta["captured_at"],
|
|
"forecast_time": meta["forecast_time"],
|
|
"global_summary": meta["global_summary"],
|
|
"regions": meta["regions"],
|
|
"storm_cores": meta["storm_cores"],
|
|
}
|