Files
planet/backend/app/services/earth_clouds.py
T

1827 lines
67 KiB
Python

"""Real-time global satellite IR cloud map engine, storage, and spatial analytics."""
from __future__ import annotations
import asyncio
from datetime import UTC, datetime
import hashlib
import io
import json
import math
import os
from pathlib import Path
import re
from time import perf_counter
from typing import Any
from urllib.parse import urlparse
from uuid import uuid4
import cv2
import httpx
import numpy as np
from PIL import Image
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import select
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.core.request_context import get_request_id
from app.core.time import to_iso8601_utc
from app.models.collected_data import CollectedData
from app.models.datasource import DataSource
from app.models.system_log import AuditLog
from app.models.system_setting import SystemSetting
from app.models.user import User
from app.models.vessel import VesselPosition
logger = get_logger(__name__, service="earth_clouds")
REPO_ROOT = Path(__file__).resolve().parents[3]
CLOUD_DATA_DIR = REPO_ROOT / "data" / "earth-clouds"
CLOUD_CONFIG_CATEGORY = "earth_cloud_map"
DEFAULT_STATIC_CLOUD_URL = "./assets/earth_clouds_2048.png"
ANALYSIS_GRID_WIDTH = 720
ANALYSIS_GRID_HEIGHT = 360
VERSION_PATTERN = re.compile(r"^[A-Za-z0-9._-]{4,64}$")
NASA_GIBS_WMS_URL = "https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi"
EUMETVIEW_WMS_URL = "https://view.eumetsat.int/geoserver/wms"
MATTEASON_BASE_URL = "https://clouds.matteason.co.uk/images"
SATELLITE_SOURCES: tuple[dict[str, Any], ...] = (
{
"id": "himawari",
"label": "Himawari-9 (JMA)",
"provider": "gibs",
"url": NASA_GIBS_WMS_URL,
"layer": "Himawari_AHI_Band13_Clean_Infrared",
"visual_layer": "Himawari_AHI_Band3_Red_Visible_1km",
"sub_lon": 140.7,
},
{
"id": "goes_east",
"label": "GOES-East (NOAA)",
"provider": "gibs",
"url": NASA_GIBS_WMS_URL,
"layer": "GOES-East_ABI_Band13_Clean_Infrared",
"visual_layer": "GOES-East_ABI_GeoColor",
"sub_lon": -75.2,
},
{
"id": "goes_west",
"label": "GOES-West (NOAA)",
"provider": "gibs",
"url": NASA_GIBS_WMS_URL,
"layer": "GOES-West_ABI_Band13_Clean_Infrared",
"visual_layer": "GOES-West_ABI_GeoColor",
"sub_lon": -137.2,
},
{
"id": "msg_fes",
"label": "Meteosat 0° (EUMETSAT)",
"provider": "eumetview",
"url": EUMETVIEW_WMS_URL,
"layer": "msg_fes:ir108",
"visual_layer": "msg_fes:rgb_naturalenhncd",
"sub_lon": 0.0,
},
{
"id": "msg_iodc",
"label": "Meteosat IODC (EUMETSAT)",
"provider": "eumetview",
"url": EUMETVIEW_WMS_URL,
"layer": "msg_iodc:ir108",
"visual_layer": "msg_iodc:rgb_naturalenhncd",
"sub_lon": 45.5,
},
)
# Official GIBS Clean_Longwave_Infrared_Window_Band.xml non-grayscale palette entries:
# (R, G, B, midpoint Brightness Temperature in Celsius).
GIBS_BAND13_COLOR_LUT: tuple[tuple[int, int, int, float], ...] = (
(127, 0, 127, -90.6),
(140, 13, 135, -89.6),
(153, 25, 142, -88.6),
(165, 38, 150, -87.6),
(178, 51, 157, -86.6),
(191, 64, 165, -85.6),
(204, 76, 173, -84.6),
(217, 89, 180, -83.6),
(229, 102, 188, -82.6),
(242, 114, 195, -81.6),
(255, 127, 203, -80.6),
(26, 0, 0, -69.6),
(51, 0, 0, -68.6),
(77, 0, 0, -67.6),
(102, 0, 0, -66.6),
(128, 0, 0, -65.6),
(153, 0, 0, -64.6),
(179, 0, 0, -63.6),
(204, 0, 0, -62.6),
(230, 0, 0, -61.6),
(255, 0, 0, -60.6),
(255, 26, 0, -59.6),
(255, 51, 0, -58.6),
(255, 77, 0, -57.6),
(255, 102, 0, -56.6),
(255, 128, 0, -55.6),
(255, 153, 0, -54.6),
(255, 179, 0, -53.6),
(255, 204, 0, -52.6),
(255, 230, 0, -51.6),
(255, 255, 0, -50.6),
(230, 255, 0, -49.6),
(204, 255, 0, -48.6),
(179, 255, 0, -47.6),
(153, 255, 0, -46.6),
(128, 255, 0, -45.6),
(102, 255, 0, -44.6),
(77, 255, 0, -43.6),
(51, 255, 0, -42.6),
(26, 255, 0, -41.6),
(0, 255, 0, -40.6),
(0, 234, 10, -39.6),
(0, 212, 19, -38.6),
(0, 191, 29, -37.6),
(0, 170, 38, -36.6),
(0, 149, 48, -35.6),
(0, 128, 58, -34.6),
(0, 106, 67, -33.6),
(0, 85, 77, -32.6),
(0, 64, 86, -31.6),
(0, 42, 96, -30.85),
(0, 21, 105, -30.35),
(0, 0, 115, -29.85),
(0, 0, 125, -29.35),
(0, 13, 122, -28.85),
(0, 26, 129, -28.35),
(0, 38, 136, -27.85),
(0, 51, 143, -27.35),
(0, 64, 150, -26.85),
(0, 76, 157, -26.35),
(0, 89, 164, -25.85),
(0, 102, 171, -25.35),
(0, 115, 178, -24.85),
(0, 128, 185, -24.35),
(0, 140, 192, -23.85),
(0, 153, 199, -23.35),
(0, 166, 206, -22.85),
(0, 178, 213, -22.35),
(0, 191, 220, -21.85),
(0, 204, 227, -21.35),
(0, 217, 234, -20.85),
(0, 230, 241, -20.35),
(0, 242, 248, -19.85),
(0, 255, 255, -19.35),
)
FOCUS_REGIONS: tuple[dict[str, Any], ...] = (
{
"key": "east_asia_scs",
"name": "东亚与南海",
"name_en": "East Asia & South China Sea",
"lat_min": 10.0,
"lat_max": 42.0,
"lon_min": 100.0,
"lon_max": 135.0,
},
{
"key": "malacca_maritime",
"name": "马六甲与印尼航道",
"name_en": "Malacca & Maritime SE Asia",
"lat_min": -8.0,
"lat_max": 12.0,
"lon_min": 92.0,
"lon_max": 122.0,
},
{
"key": "west_pacific_typhoon",
"name": "西北太平洋台风带",
"name_en": "Western Pacific Typhoon Belt",
"lat_min": 5.0,
"lat_max": 35.0,
"lon_min": 120.0,
"lon_max": 165.0,
},
{
"key": "red_sea_suez",
"name": "红海与苏伊士走廊",
"name_en": "Red Sea & Suez Corridor",
"lat_min": 10.0,
"lat_max": 33.0,
"lon_min": 30.0,
"lon_max": 50.0,
},
{
"key": "western_europe",
"name": "欧洲西部",
"name_en": "Western Europe",
"lat_min": 36.0,
"lat_max": 60.0,
"lon_min": -12.0,
"lon_max": 22.0,
},
{
"key": "north_america_east",
"name": "北美东海岸",
"name_en": "North America East Coast",
"lat_min": 24.0,
"lat_max": 50.0,
"lon_min": -85.0,
"lon_max": -60.0,
},
{
"key": "north_america_west",
"name": "北美西海岸",
"name_en": "North America West Coast",
"lat_min": 24.0,
"lat_max": 52.0,
"lon_min": -135.0,
"lon_max": -112.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,
},
)
_GIBS_3D_LUT: np.ndarray | None = None
_CLOUD_WRITE_LOCK = asyncio.Lock()
class CloudMapRevisionConflictError(RuntimeError):
"""Raised when saving cloud map configuration with a stale revision."""
class CloudMapConfig(BaseModel):
enabled: bool = True
primary_source: str = Field(default="multi_sat_ir")
fallback_source: str = Field(default="matteason_live")
resolution: str = Field(default="4096x2048")
ir_threshold: int = Field(default=22, ge=0, le=80)
contrast_gamma: float = Field(default=0.88, ge=0.5, le=2.0)
convective_threshold: int = Field(default=82, ge=45, le=96)
min_cluster_area_km2: int = Field(default=35000, ge=5000, le=500000)
polar_feather_enabled: bool = True
max_history_frames: int = Field(default=24, ge=4, le=48)
timelapse_enabled: bool = True
show_convective_markers: bool = False
default_opacity: float = Field(default=0.38, ge=0.1, le=0.8)
request_timeout_seconds: int = Field(default=45, ge=5, le=60)
geocolor_enabled: bool = True
relief_shading_strength: float = Field(default=0.45, ge=0.0, le=1.0)
optical_flow_enabled: bool = True
@field_validator("primary_source")
@classmethod
def validate_primary_source(cls, value: str) -> str:
normalized = str(value or "multi_sat_ir").strip().lower()
if normalized not in {"multi_sat_ir", "matteason_live"}:
raise ValueError("primary_source must be 'multi_sat_ir' or 'matteason_live'")
return normalized
@field_validator("fallback_source")
@classmethod
def validate_fallback_source(cls, value: str) -> str:
normalized = str(value or "matteason_live").strip().lower()
if normalized not in {"matteason_live", "static"}:
raise ValueError("fallback_source must be 'matteason_live' or 'static'")
return normalized
@field_validator("resolution")
@classmethod
def validate_resolution(cls, value: str) -> str:
normalized = str(value or "4096x2048").strip().lower()
if normalized not in {"2048x1024", "4096x2048"}:
raise ValueError("resolution must be '2048x1024' or '4096x2048'")
return normalized
DEFAULT_CLOUD_CONFIG = CloudMapConfig()
DEFAULT_CLOUD_REVISION = hashlib.sha256(
DEFAULT_CLOUD_CONFIG.model_dump_json().encode("utf-8")
).hexdigest()[:16]
def _default_envelope() -> dict[str, Any]:
return {
"config": DEFAULT_CLOUD_CONFIG.model_dump(mode="json"),
"revision": DEFAULT_CLOUD_REVISION,
"is_default": True,
}
def _get_data_dir() -> Path:
return CLOUD_DATA_DIR
def _manifest_path() -> Path:
return _get_data_dir() / "manifest.json"
def _frames_dir() -> Path:
return _get_data_dir() / "frames"
def _grids_dir() -> Path:
return _get_data_dir() / "grids"
def _temps_dir() -> Path:
return _get_data_dir() / "temps"
def _ensure_dirs() -> None:
_frames_dir().mkdir(parents=True, exist_ok=True)
_grids_dir().mkdir(parents=True, exist_ok=True)
_temps_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")
tmp_path.write_bytes(content)
os.replace(tmp_path, path)
def _atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
raw = json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8")
_atomic_write_bytes(path, raw)
def _read_manifest() -> dict[str, Any]:
path = _manifest_path()
if not path.exists():
return {"latest_version": None, "updated_at": None, "frames": []}
try:
data = json.loads(path.read_text(encoding="utf-8"))
except Exception:
return {"latest_version": None, "updated_at": None, "frames": []}
if not isinstance(data, dict):
return {"latest_version": None, "updated_at": None, "frames": []}
frames = data.get("frames")
return {
"latest_version": data.get("latest_version"),
"updated_at": data.get("updated_at"),
"frames": [item for item in frames if isinstance(item, dict)] if isinstance(frames, list) else [],
}
def parse_resolution(resolution: str) -> tuple[int, int]:
return (4096, 2048) if resolution == "4096x2048" else (2048, 1024)
def _get_gibs_3d_lut() -> np.ndarray:
"""Build a quantized 5-bit/channel RGB -> Brightness Temperature (°C) lookup table."""
global _GIBS_3D_LUT
if _GIBS_3D_LUT is not None:
return _GIBS_3D_LUT
palette_rgb = np.array([[r, g, b] for r, g, b, _ in GIBS_BAND13_COLOR_LUT], dtype=np.int32)
palette_temp = np.array([temp for _, _, _, temp in GIBS_BAND13_COLOR_LUT], dtype=np.float32)
levels = np.arange(32, dtype=np.int32) * 8 + 4
rr, gg, bb = np.meshgrid(levels, levels, levels, indexing="ij")
grid_rgb = np.stack([rr, gg, bb], axis=-1).reshape(-1, 3)
diff = grid_rgb[:, None, :] - palette_rgb[None, :, :]
dist_sq = np.sum(diff * diff, axis=-1)
nearest_idx = np.argmin(dist_sq, axis=1)
_GIBS_3D_LUT = palette_temp[nearest_idx].reshape(32, 32, 32)
return _GIBS_3D_LUT
def _disambiguate_dvorak_cold_gray(
valid: np.ndarray,
gray: np.ndarray,
chroma: np.ndarray,
temp_c: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
"""Recover Dvorak cold gray/white cloud cores enclosed by <= -52°C convective rings.
Also masks pure-white GOES/GIBS missing scan-band stripes outside convective rings
so they never become bogus -91.5°C storm clusters. Runs purely vectorized in C/NumPy
to avoid tens of thousands of Python per-component calls holding the GIL.
"""
updated_valid = valid.copy()
result = temp_c.copy()
cold_ring = updated_valid & (chroma >= 12) & (result <= -52.0)
if np.any(cold_ring):
near_cold_ring = (
cv2.dilate(cold_ring.astype(np.uint8), np.ones((7, 7), dtype=np.uint8), iterations=1) > 0
)
else:
near_cold_ring = np.zeros_like(updated_valid, dtype=bool)
white_stripe = updated_valid & (chroma < 8) & (gray >= 245) & ~near_cold_ring
if np.any(white_stripe):
updated_valid[white_stripe] = False
if not np.any(cold_ring):
return result, updated_valid
height, width = updated_valid.shape
max_hole_pixels = max(512, int(height * width * 0.015))
not_ring = (~cold_ring).astype(np.uint8)
num_labels, labels, stats, _ = cv2.connectedComponentsWithStats(not_ring, connectivity=8)
if num_labels <= 1:
return result, updated_valid
areas = stats[:, cv2.CC_STAT_AREA]
lefts = stats[:, cv2.CC_STAT_LEFT]
tops = stats[:, cv2.CC_STAT_TOP]
widths = stats[:, cv2.CC_STAT_WIDTH]
heights = stats[:, cv2.CC_STAT_HEIGHT]
touches_edge = (
(lefts == 0)
| (tops == 0)
| (lefts + widths >= width)
| (tops + heights >= height)
)
touches_invalid = np.zeros(num_labels, dtype=bool)
if np.any(~updated_valid):
touches_invalid[np.unique(labels[~updated_valid])] = True
is_hole = (areas > 0) & (areas <= max_hole_pixels) & ~touches_edge & ~touches_invalid
is_hole[0] = False
if np.any(is_hole):
dvorak_core = is_hole[labels] & updated_valid & (chroma < 12)
if np.any(dvorak_core):
sub_gray = gray[dvorak_core]
result[dvorak_core] = -70.1 - (np.clip(sub_gray, 0.0, 230.0) / 230.0) * 10.0
ultra_wrap = dvorak_core & (gray >= 248)
if np.any(ultra_wrap):
result[ultra_wrap] = -91.5
return result, updated_valid
def decode_gibs_band13_to_temp_and_valid(rgba_arr: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Invert GIBS Band13 Clean IR RGBA pixels into Brightness Temperature (°C) and valid mask."""
rgb = rgba_arr[:, :, :3].astype(np.int32)
alpha = rgba_arr[:, :, 3]
valid = alpha > 12
r_ch = rgb[:, :, 0]
g_ch = rgb[:, :, 1]
b_ch = rgb[:, :, 2]
chroma = np.maximum(np.maximum(r_ch, g_ch), b_ch) - np.minimum(np.minimum(r_ch, g_ch), b_ch)
gray = ((r_ch + g_ch + b_ch) // 3).astype(np.float32)
temp_c = 57.3 - (np.clip(gray, 0.0, 197.0) / 197.0) * 76.4
color_mask = valid & (chroma >= 12)
if np.any(color_mask):
lut = _get_gibs_3d_lut()
temp_c[color_mask] = lut[
r_ch[color_mask] >> 3,
g_ch[color_mask] >> 3,
b_ch[color_mask] >> 3,
]
temp_c, valid = _disambiguate_dvorak_cold_gray(valid, gray, chroma, temp_c)
temp_c[~valid] = np.nan
return temp_c.astype(np.float32), valid
def decode_eumetview_ir_to_temp_and_valid(rgba_arr: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Convert EUMETView grayscale IR10.8 image into approximate Brightness Temperature (°C)."""
alpha = rgba_arr[:, :, 3]
valid = alpha > 12
gray = np.mean(rgba_arr[:, :, :3].astype(np.float32), axis=2)
# EUMETView IR108 is 8-bit inverted brightness (warm dark ~1 -> +42°C, cold bright 255 -> -76°C).
temp_c = 42.0 - (gray / 255.0) * 118.0
temp_c[~valid] = np.nan
return temp_c.astype(np.float32), valid
def temperature_to_density(
temp_c: np.ndarray,
*,
ir_threshold: int,
contrast_gamma: float,
) -> np.ndarray:
"""Map physical Brightness Temperature (°C) monotonically to 0..255 cloud density."""
# ir_threshold 0..80 maps clear-sky cutoff from +26°C down to -18°C (22 -> +13.9°C).
clear_cutoff_c = 26.0 - (float(ir_threshold) / 100.0) * 55.0
dense_cloud_c = -55.0
span = max(18.0, clear_cutoff_c - dense_cloud_c)
normalized = np.clip((clear_cutoff_c - temp_c) / span, 0.0, 1.0)
normalized = np.where(np.isnan(temp_c), 0.0, normalized)
if abs(contrast_gamma - 1.0) > 1e-3:
normalized = np.power(normalized, float(contrast_gamma))
return np.clip(np.round(normalized * 255.0), 0, 255).astype(np.uint8)
def _compute_satellite_longitude_weights(width: int, sub_lon: float) -> np.ndarray:
lons = np.linspace(-180.0, 180.0, width, endpoint=False, dtype=np.float32) + (180.0 / width)
delta_rad = np.deg2rad(((lons - sub_lon + 180.0) % 360.0) - 180.0)
cos_val = np.cos(delta_rad)
# Favor near-nadir pixels cleanly while preserving thin feathering near disk edges.
return np.power(np.maximum(0.0, cos_val - 0.12), 1.5) + 0.005
def _apply_polar_and_seam_smoothing(
density_u8: np.ndarray,
*,
polar_feather_enabled: bool,
) -> np.ndarray:
height, width = density_u8.shape
out = density_u8.astype(np.float32)
if polar_feather_enabled:
lats = np.linspace(90.0, -90.0, height, endpoint=False, dtype=np.float32) - (90.0 / height)
abs_lat = np.abs(lats)
# Smooth taper from 62° to 80° to soften geostationary limb cutoff near poles.
t = np.clip((abs_lat - 62.0) / 18.0, 0.0, 1.0)
polar_weight = 1.0 - (t * t * (3.0 - 2.0 * t)) * 0.92
out *= polar_weight[:, None]
# Subtle seam blend across ±180° dateline (first & last 4 columns).
seam_w = 4
if width > seam_w * 2:
left = out[:, :seam_w].copy()
right = out[:, -seam_w:].copy()
avg = 0.5 * (left + np.flip(right, axis=1))
alpha = np.linspace(0.5, 0.0, seam_w, dtype=np.float32)[None, :]
out[:, :seam_w] = left * (1.0 - alpha) + avg * alpha
out[:, -seam_w:] = right * (1.0 - np.flip(alpha, axis=1)) + np.flip(avg, axis=1) * np.flip(alpha, axis=1)
return np.clip(np.round(out), 0, 255).astype(np.uint8)
def _decode_image_bytes(raw: bytes, width: int, height: int) -> np.ndarray:
with Image.open(io.BytesIO(raw)) as img:
rgba = img.convert("RGBA")
if rgba.size != (width, height):
rgba = rgba.resize((width, height), Image.Resampling.BILINEAR)
return np.array(rgba, dtype=np.uint8)
def _bound_cv_threads() -> None:
try:
cv2.setNumThreads(min(2, os.cpu_count() or 1))
except Exception:
pass
def synthesize_multi_sat_ir(
satellite_payloads: list[tuple[dict[str, Any], bytes]],
*,
config: CloudMapConfig,
) -> tuple[np.ndarray, np.ndarray, list[str]]:
"""Composite multiple geostationary satellite IR PNGs into global density & temp grids."""
_bound_cv_threads()
width, height = parse_resolution(config.resolution)
temp_accum = np.zeros((height, width), dtype=np.float32)
weight_accum = np.zeros((height, width), dtype=np.float32)
active_satellites: list[str] = []
for sat, payload_bytes in satellite_payloads:
rgba_arr = _decode_image_bytes(payload_bytes, width, height)
if sat["provider"] == "gibs":
sat_temp, valid = decode_gibs_band13_to_temp_and_valid(rgba_arr)
else:
sat_temp, valid = decode_eumetview_ir_to_temp_and_valid(rgba_arr)
if not np.any(valid):
continue
lon_weights = _compute_satellite_longitude_weights(width, float(sat["sub_lon"]))
pixel_weight = np.where(valid, lon_weights[None, :], 0.0)
safe_temp = np.where(valid, sat_temp, 0.0)
temp_accum += safe_temp * pixel_weight
weight_accum += pixel_weight
active_satellites.append(str(sat["id"]))
if not active_satellites or not np.any(weight_accum > 0.0):
raise RuntimeError("No valid geostationary IR satellite frames could be decoded")
covered = weight_accum > 0.0
composite_temp = np.full((height, width), np.nan, dtype=np.float32)
composite_temp[covered] = temp_accum[covered] / weight_accum[covered]
density = temperature_to_density(
composite_temp,
ir_threshold=config.ir_threshold,
contrast_gamma=config.contrast_gamma,
)
# Light edge-preserving denoise to soften WMS resampling quantization.
density = cv2.GaussianBlur(density, (3, 3), 0.6)
density = _apply_polar_and_seam_smoothing(
density,
polar_feather_enabled=config.polar_feather_enabled,
)
return density, composite_temp, active_satellites
def decode_matteason_cloud_bytes(
payload_bytes: bytes,
*,
config: CloudMapConfig,
) -> tuple[np.ndarray, np.ndarray]:
"""Normalize Matt Eason equirectangular cloud texture into global density & approx temp."""
width, height = parse_resolution(config.resolution)
rgba_arr = _decode_image_bytes(payload_bytes, width, height)
rgb_mean = np.mean(rgba_arr[:, :, :3].astype(np.float32), axis=2)
alpha = rgba_arr[:, :, 3].astype(np.float32)
raw_density = np.minimum(rgb_mean, alpha) / 255.0
cutoff = max(0.0, min(0.6, config.ir_threshold / 180.0))
scaled = np.clip((raw_density - cutoff) / max(0.25, 1.0 - cutoff), 0.0, 1.0)
if abs(config.contrast_gamma - 1.0) > 1e-3:
scaled = np.power(scaled, float(config.contrast_gamma))
density = np.clip(np.round(scaled * 255.0), 0, 255).astype(np.uint8)
approx_temp = (20.0 - (density.astype(np.float32) / 255.0) * 90.0).astype(np.float32)
return density, approx_temp
def _encode_cloud_webp(density_u8: np.ndarray) -> bytes:
"""Encode density field as RGBA WebP compatible with Three.js cloud shader & HTML preview."""
rgba = np.empty((density_u8.shape[0], density_u8.shape[1], 4), dtype=np.uint8)
rgba[:, :, 0] = density_u8
rgba[:, :, 1] = density_u8
rgba[:, :, 2] = density_u8
rgba[:, :, 3] = density_u8
img = Image.fromarray(rgba, mode="RGBA")
buf = io.BytesIO()
img.save(buf, format="WEBP", quality=88, method=1)
return buf.getvalue()
def _lat_lon_to_grid_indices(lat: float, lon: float) -> tuple[int, int]:
clamped_lat = max(-89.999, min(89.999, float(lat)))
wrapped_lon = ((float(lon) + 180.0) % 360.0) - 180.0
row = int(max(0, min(ANALYSIS_GRID_HEIGHT - 1, math.floor((90.0 - clamped_lat) / 0.5))))
col = int(max(0, min(ANALYSIS_GRID_WIDTH - 1, math.floor((wrapped_lon + 180.0) / 0.5))))
return row, col
def _classify_cloud_density(density_pct: float, convective_threshold: int) -> str:
if density_pct >= float(convective_threshold):
return "convective"
if density_pct >= 55.0:
return "overcast"
if density_pct >= 20.0:
return "partly_cloudy"
return "clear"
def _match_region_name(lat: float, lon: float) -> tuple[str, str]:
for region in FOCUS_REGIONS:
if (
region["lat_min"] <= lat <= region["lat_max"]
and region["lon_min"] <= lon <= region["lon_max"]
):
return str(region["name"]), str(region["name_en"])
if -23.5 <= lat <= 23.5:
return "热带海域/陆区", "Tropics"
if lat > 23.5:
return "北半球中高纬", "Northern Mid-High Latitudes"
return "南半球中高纬", "Southern Mid-High Latitudes"
def analyze_cloud_density_grid(
density_u8: np.ndarray,
temp_c: np.ndarray,
*,
config: CloudMapConfig,
previous_snapshot: dict[str, Any] | None = None,
previous_regions: dict[str, float] | None = None,
) -> dict[str, Any]:
"""Downsample density/temperature fields and compute regional & convective analytics."""
_bound_cv_threads()
grid_density = cv2.resize(
density_u8,
(ANALYSIS_GRID_WIDTH, ANALYSIS_GRID_HEIGHT),
interpolation=cv2.INTER_AREA,
)
temp_filled = np.where(np.isnan(temp_c), 25.0, temp_c).astype(np.float32)
grid_temp = cv2.resize(
temp_filled,
(ANALYSIS_GRID_WIDTH, ANALYSIS_GRID_HEIGHT),
interpolation=cv2.INTER_AREA,
)
density_pct = (grid_density.astype(np.float32) / 255.0) * 100.0
lat_centers = 90.0 - (np.arange(ANALYSIS_GRID_HEIGHT, dtype=np.float32) + 0.5) * 0.5
lon_centers = -180.0 + (np.arange(ANALYSIS_GRID_WIDTH, dtype=np.float32) + 0.5) * 0.5
lat_weights = np.cos(np.deg2rad(lat_centers)).clip(min=0.01)[:, None]
def _weighted_stats(mask_rows: np.ndarray | None = None) -> tuple[float, float, float]:
sub_d = density_pct if mask_rows is None else density_pct[mask_rows]
sub_w = np.broadcast_to(lat_weights, density_pct.shape)
if mask_rows is not None:
sub_w = sub_w[mask_rows]
w_sum = float(np.sum(sub_w)) or 1.0
mean_cover = float(np.sum(sub_d * sub_w) / w_sum)
overcast_ratio = float(np.sum((sub_d >= 55.0) * sub_w) / w_sum) * 100.0
conv_ratio = float(np.sum((sub_d >= float(config.convective_threshold)) * sub_w) / w_sum) * 100.0
return round(mean_cover, 2), round(overcast_ratio, 2), round(conv_ratio, 2)
global_mean, global_overcast, global_conv = _weighted_stats()
north_mean, _, _ = _weighted_stats(lat_centers >= 0.0)
south_mean, _, _ = _weighted_stats(lat_centers < 0.0)
tropics_mean, _, _ = _weighted_stats((lat_centers >= -23.5) & (lat_centers <= 23.5))
prev_global = None
if isinstance(previous_snapshot, dict):
try:
prev_global = float(previous_snapshot.get("global_cloud_cover_pct"))
except (TypeError, ValueError):
prev_global = None
region_summaries: list[dict[str, Any]] = []
for region in FOCUS_REGIONS:
row_mask = (lat_centers >= region["lat_min"]) & (lat_centers <= region["lat_max"])
col_mask = (lon_centers >= region["lon_min"]) & (lon_centers <= region["lon_max"])
sub_d = density_pct[np.ix_(row_mask, col_mask)]
sub_t = grid_temp[np.ix_(row_mask, col_mask)]
sub_w = np.broadcast_to(lat_weights[row_mask], sub_d.shape)
w_sum = float(np.sum(sub_w)) or 1.0
mean_cover = round(float(np.sum(sub_d * sub_w) / w_sum), 2)
overcast_pct = round(float(np.sum((sub_d >= 55.0) * sub_w) / w_sum) * 100.0, 2)
conv_pct = round(
float(np.sum((sub_d >= float(config.convective_threshold)) * sub_w) / w_sum) * 100.0, 2
)
min_temp = round(float(np.min(sub_t)), 1) if sub_t.size else None
prev_val = (previous_regions or {}).get(region["key"])
delta_pct = round(mean_cover - prev_val, 2) if prev_val is not None else None
region_summaries.append(
{
"key": region["key"],
"name": region["name"],
"name_en": region["name_en"],
"center_lat": round((region["lat_min"] + region["lat_max"]) * 0.5, 2),
"center_lon": round((region["lon_min"] + region["lon_max"]) * 0.5, 2),
"cloud_cover_pct": mean_cover,
"overcast_coverage_pct": overcast_pct,
"convective_coverage_pct": conv_pct,
"min_brightness_temp_c": min_temp,
"delta_pct": delta_pct,
}
)
# Extract convective / cyclone candidate clusters via connected components.
conv_mask = (density_pct >= float(config.convective_threshold)).astype(np.uint8)
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(conv_mask, connectivity=8)
# 0.5° x 0.5° cell area at equator ≈ (111.32 * 0.5)^2 ≈ 3098 km²
cell_area_eq_km2 = (111.32 * 0.5) ** 2
clusters: list[dict[str, Any]] = []
if num_labels > 1:
label_areas = stats[1:, cv2.CC_STAT_AREA]
candidate_indices = np.flatnonzero(label_areas >= 3) + 1
if candidate_indices.size > 200:
order = np.argsort(stats[candidate_indices, cv2.CC_STAT_AREA])[::-1][:200]
candidate_indices = candidate_indices[order]
else:
candidate_indices = np.empty((0,), dtype=np.int32)
for label_id in candidate_indices.tolist():
x = int(stats[label_id, cv2.CC_STAT_LEFT])
y = int(stats[label_id, cv2.CC_STAT_TOP])
w = int(stats[label_id, cv2.CC_STAT_WIDTH])
h = int(stats[label_id, cv2.CC_STAT_HEIGHT])
sub_mask = labels[y : y + h, x : x + w] == label_id
sub_lat_weights = lat_weights[y : y + h]
area_km2 = round(float(np.sum(sub_mask * sub_lat_weights)) * cell_area_eq_km2, 0)
if area_km2 < float(config.min_cluster_area_km2):
continue
cx, cy = centroids[label_id]
center_lon = round(-180.0 + (float(cx) + 0.5) * 0.5, 2)
center_lat = round(90.0 - (float(cy) + 0.5) * 0.5, 2)
peak_intensity = round(float(np.max(density_pct[y : y + h, x : x + w][sub_mask])), 1)
min_temp_c = round(float(np.min(grid_temp[y : y + h, x : x + w][sub_mask])), 1)
region_zh, region_en = _match_region_name(center_lat, center_lon)
clusters.append(
{
"cluster_id": f"conv-{len(clusters) + 1}",
"latitude": center_lat,
"longitude": center_lon,
"area_km2": int(area_km2),
"peak_intensity": peak_intensity,
"min_brightness_temp_c": min_temp_c,
"region": region_zh,
"region_en": region_en,
"bbox": {
"lon_min": round(-180.0 + x * 0.5, 2),
"lon_max": round(-180.0 + (x + w) * 0.5, 2),
"lat_max": round(90.0 - y * 0.5, 2),
"lat_min": round(90.0 - (y + h) * 0.5, 2),
},
}
)
clusters.sort(key=lambda item: (item["area_km2"], item["peak_intensity"]), reverse=True)
clusters = clusters[:25]
for idx, item in enumerate(clusters, start=1):
item["cluster_id"] = f"conv-{idx}"
global_min_temp = round(float(np.min(grid_temp)), 1) if grid_temp.size else None
return {
"grid_density": grid_density,
"grid_temp_i8": np.clip(np.round(grid_temp), -120, 80).astype(np.int8),
"global_summary": {
"global_cloud_cover_pct": global_mean,
"global_overcast_pct": global_overcast,
"global_convective_pct": global_conv,
"northern_hemisphere_pct": north_mean,
"southern_hemisphere_pct": south_mean,
"tropics_pct": tropics_mean,
"delta_pct": round(global_mean - prev_global, 2) if prev_global is not None else None,
"convective_cluster_count": len(clusters),
"min_brightness_temp_c": global_min_temp,
},
"regions": region_summaries,
"convective_clusters": clusters,
}
def _wms_getmap_params(layer: str, width: int, height: int) -> dict[str, str]:
return {
"SERVICE": "WMS",
"REQUEST": "GetMap",
"VERSION": "1.1.1",
"LAYERS": layer,
"STYLES": "",
"FORMAT": "image/png",
"TRANSPARENT": "true",
"SRS": "EPSG:4326",
"BBOX": "-180,-90,180,90",
"WIDTH": str(width),
"HEIGHT": str(height),
}
async def _fetch_multi_sat_payloads(
config: CloudMapConfig,
*,
layer_field: str = "layer",
) -> list[tuple[dict[str, Any], bytes]]:
width, height = parse_resolution(config.resolution)
timeout = httpx.Timeout(float(config.request_timeout_seconds))
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthCloudCollector)"}
async def _get_one(client: httpx.AsyncClient, sat: dict[str, Any]) -> tuple[dict[str, Any], bytes] | None:
layer_name = str(sat.get(layer_field) or "").strip()
if not layer_name:
return None
params = _wms_getmap_params(layer_name, width, height)
try:
response = await client.get(str(sat["url"]), params=params)
response.raise_for_status()
content_type = str(response.headers.get("content-type") or "").lower()
if not content_type.startswith("image/"):
logger.warning_event(
"Cloud satellite WMS returned non-image content",
event="earth.cloud_map.wms_invalid_content_type",
context={"satellite": sat["id"], "layer": layer_name, "content_type": content_type},
)
return None
return sat, response.content
except Exception as exc:
logger.warning_event(
"Cloud satellite WMS request failed",
event="earth.cloud_map.wms_fetch_failed",
context={"satellite": sat["id"], "layer": layer_name, "error": str(exc)},
)
return None
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client:
semaphore = asyncio.Semaphore(5)
async def _limited_get(sat: dict[str, Any]) -> tuple[dict[str, Any], bytes] | None:
async with semaphore:
return await _get_one(client, sat)
results = await asyncio.gather(*(_limited_get(sat) for sat in SATELLITE_SOURCES))
return [item for item in results if item is not None]
async def _fetch_matteason_bytes(config: CloudMapConfig) -> bytes:
size_path = "4096x2048" if config.resolution == "4096x2048" else "2048x1024"
url = f"{MATTEASON_BASE_URL}/{size_path}/clouds-alpha.png"
timeout = httpx.Timeout(float(config.request_timeout_seconds))
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthCloudCollector)"}
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client:
response = await client.get(url)
response.raise_for_status()
content_type = str(response.headers.get("content-type") or "").lower()
if not content_type.startswith("image/"):
raise RuntimeError(f"Unexpected Matt Eason content-type: {content_type}")
return response.content
def _flows_dir() -> Path:
return _get_data_dir() / "flows"
def _save_frame_artifacts_sync(
*,
version: str,
captured_at: str,
source_used: str,
satellites: list[str],
degraded: bool,
config: CloudMapConfig,
webp_bytes: bytes,
visual_webp_bytes: bytes | None = None,
flow_webp_bytes: bytes | None = None,
flow_prev_version: str | None = None,
flow_max_uv: float = 0.0,
grid_density: np.ndarray,
grid_temp_i8: np.ndarray,
global_summary: dict[str, Any],
regions: list[dict[str, Any]],
clusters: list[dict[str, Any]],
) -> dict[str, Any]:
_ensure_dirs()
_flows_dir().mkdir(parents=True, exist_ok=True)
frame_path = _frames_dir() / f"{version}.webp"
visual_path = _frames_dir() / f"{version}_vis.webp"
flow_path = _flows_dir() / f"{version}.webp"
grid_path = _grids_dir() / f"{version}.bin"
temp_path = _temps_dir() / f"{version}.bin"
_atomic_write_bytes(frame_path, webp_bytes)
if visual_webp_bytes:
_atomic_write_bytes(visual_path, visual_webp_bytes)
if flow_webp_bytes:
_atomic_write_bytes(flow_path, flow_webp_bytes)
_atomic_write_bytes(grid_path, grid_density.tobytes())
_atomic_write_bytes(temp_path, grid_temp_i8.tobytes())
sha256 = hashlib.sha256(webp_bytes).hexdigest()
frame_entry = {
"version": version,
"captured_at": captured_at,
"source": source_used,
"satellites": satellites,
"degraded": degraded,
"resolution": config.resolution,
"file_size_bytes": len(webp_bytes),
"sha256": sha256,
"image_url": f"/api/v1/earth/clouds/frames/{version}",
"visual_url": f"/api/v1/earth/clouds/frames/{version}/visual" if visual_webp_bytes else None,
"flow_url": f"/api/v1/earth/clouds/flows/{version}" if flow_webp_bytes else None,
"flow_prev_version": flow_prev_version if flow_webp_bytes else None,
"flow_max_uv": float(flow_max_uv) if flow_webp_bytes else 0.0,
"global_summary": global_summary,
"regions": regions,
"convective_clusters": clusters,
}
manifest = _read_manifest()
frames = [item for item in manifest.get("frames", []) if item.get("version") != version]
frames.insert(0, frame_entry)
kept_frames = frames[: config.max_history_frames]
dropped_versions = {
str(item.get("version"))
for item in frames[config.max_history_frames :]
if item.get("version")
}
_atomic_write_json(
_manifest_path(),
{
"latest_version": version,
"updated_at": captured_at,
"frames": kept_frames,
},
)
for old_version in dropped_versions:
_remove_version_files(old_version)
return frame_entry
def _remove_version_files(version: str) -> int:
if not VERSION_PATTERN.match(version):
return 0
removed = 0
for target in (
_frames_dir() / f"{version}.webp",
_frames_dir() / f"{version}_vis.webp",
_flows_dir() / f"{version}.webp",
_grids_dir() / f"{version}.bin",
_temps_dir() / f"{version}.bin",
):
if target.exists():
try:
target.unlink()
removed += 1
except OSError:
pass
return removed
def prune_cloud_map_artifacts(max_frames: int = 24) -> int:
"""Prune stale cloud frame/grid/flow artifacts beyond retention limit and orphaned temp files."""
if not _get_data_dir().exists():
return 0
manifest = _read_manifest()
frames = manifest.get("frames", [])
kept = frames[: max(1, int(max_frames))]
kept_versions = {str(item.get("version")) for item in kept if item.get("version")}
removed = 0
for item in frames[max(1, int(max_frames)) :]:
ver = str(item.get("version") or "")
if ver:
removed += _remove_version_files(ver)
for directory in (_frames_dir(), _flows_dir(), _grids_dir(), _temps_dir()):
if not directory.exists():
continue
for file_path in directory.iterdir():
base_stem = file_path.stem.removesuffix("_vis")
if file_path.name.startswith(".") or base_stem not in kept_versions:
try:
file_path.unlink()
removed += 1
except OSError:
pass
if len(kept) != len(frames):
_atomic_write_json(
_manifest_path(),
{
"latest_version": kept[0].get("version") if kept else None,
"updated_at": manifest.get("updated_at"),
"frames": kept,
},
)
return removed
def clear_all_cloud_map_artifacts() -> int:
"""Remove all persisted cloud frame images, visual/flow maps, grids, and manifest."""
removed = 0
for directory in (_frames_dir(), _flows_dir(), _grids_dir(), _temps_dir()):
if not directory.exists():
continue
for file_path in directory.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
async def read_cloud_map_configuration(db: AsyncSession | None) -> dict[str, Any]:
if db is None or not callable(getattr(db, "execute", None)):
return _default_envelope()
result = await db.execute(
select(SystemSetting).where(SystemSetting.category == CLOUD_CONFIG_CATEGORY)
)
record = result.scalar_one_or_none()
if not record or not isinstance(record.payload, dict):
return _default_envelope()
payload = dict(record.payload)
try:
validated = CloudMapConfig.model_validate(payload.get("config") or {})
except Exception:
validated = DEFAULT_CLOUD_CONFIG
return {
"config": validated.model_dump(mode="json"),
"revision": str(payload.get("revision") or DEFAULT_CLOUD_REVISION),
"is_default": bool(payload.get("is_default", False)),
}
async def save_cloud_map_configuration(
db: AsyncSession,
*,
revision: str,
config: CloudMapConfig,
actor: User,
reset: bool = False,
) -> dict[str, Any]:
dialect_name = ""
try:
bind = db.get_bind()
dialect_name = str(getattr(getattr(bind, "dialect", None), "name", "") or "").lower()
except Exception:
dialect_name = ""
if dialect_name == "postgresql":
await db.execute(
pg_insert(SystemSetting)
.values(category=CLOUD_CONFIG_CATEGORY, payload=_default_envelope())
.on_conflict_do_nothing(index_elements=[SystemSetting.category])
)
record = (
await db.execute(
select(SystemSetting)
.where(SystemSetting.category == CLOUD_CONFIG_CATEGORY)
.with_for_update()
)
).scalar_one()
else:
record = (
await db.execute(
select(SystemSetting).where(SystemSetting.category == CLOUD_CONFIG_CATEGORY)
)
).scalar_one_or_none()
if record is None:
record = SystemSetting(category=CLOUD_CONFIG_CATEGORY, payload=_default_envelope())
db.add(record)
current_revision = str((record.payload or {}).get("revision") or DEFAULT_CLOUD_REVISION)
if current_revision != revision:
await db.rollback()
raise CloudMapRevisionConflictError("Configuration changed by another editor. Reload and retry.")
envelope = (
_default_envelope()
if reset
else {
"config": config.model_dump(mode="json"),
"revision": uuid4().hex[:16],
"is_default": False,
}
)
before = dict(record.payload or {})
if reset:
if getattr(record, "id", None) is not None:
await db.delete(record)
else:
record.payload = envelope
db.add(
AuditLog(
actor_id=actor.id,
actor_name=actor.username,
action="earth_cloud_map.reset" if reset else "earth_cloud_map.update",
target_type="system_setting",
target_id=CLOUD_CONFIG_CATEGORY,
result="success",
request_id=get_request_id(),
details={"before": before, "after": envelope},
)
)
await db.commit()
return envelope
async def collect_latest_cloud_frame(
db: AsyncSession | None = None,
*,
override_config: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Fetch, composite, analyze, and persist one live satellite cloud frame."""
envelope = await read_cloud_map_configuration(db)
merged_cfg = {**envelope["config"], **(override_config or {})}
config = CloudMapConfig.model_validate(merged_cfg)
manifest = _read_manifest()
prev_frames = manifest.get("frames", [])
prev_entry = prev_frames[0] if prev_frames else None
prev_snapshot = prev_entry.get("global_summary") if isinstance(prev_entry, dict) else None
prev_regions: dict[str, float] = {}
if isinstance(prev_entry, dict) and isinstance(prev_entry.get("regions"), list):
for item in prev_entry["regions"]:
if isinstance(item, dict) and item.get("key") is not None:
try:
prev_regions[str(item["key"])] = float(item["cloud_cover_pct"])
except (TypeError, ValueError):
pass
density: np.ndarray | None = None
temp_c: np.ndarray | None = None
visual_payloads: list[tuple[dict[str, Any], bytes]] = []
source_used = config.primary_source
satellites: list[str] = []
degraded = False
if config.primary_source == "multi_sat_ir":
if config.geocolor_enabled:
payloads, visual_payloads = await asyncio.gather(
_fetch_multi_sat_payloads(config, layer_field="layer"),
_fetch_multi_sat_payloads(config, layer_field="visual_layer"),
)
else:
payloads = await _fetch_multi_sat_payloads(config, layer_field="layer")
if payloads:
density, temp_c, satellites = await asyncio.to_thread(
synthesize_multi_sat_ir,
payloads,
config=config,
)
if len(satellites) < len(SATELLITE_SOURCES):
degraded = True
elif config.fallback_source == "matteason_live":
raw = await _fetch_matteason_bytes(config)
density, temp_c = await asyncio.to_thread(
decode_matteason_cloud_bytes,
raw,
config=config,
)
source_used = "matteason_live"
satellites = ["eumetsat_nasa_mosaic"]
degraded = True
else:
raw = await _fetch_matteason_bytes(config)
density, temp_c = await asyncio.to_thread(
decode_matteason_cloud_bytes,
raw,
config=config,
)
source_used = "matteason_live"
satellites = ["eumetsat_nasa_mosaic"]
if density is None or temp_c is None:
raise RuntimeError("Failed to fetch cloud imagery from all configured upstream sources")
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()
def _finalize() -> tuple[dict[str, Any], dict[str, Any]]:
from app.services.earth_clouds_fx import (
compute_dis_optical_flow_webp,
decode_visual_payloads,
fuse_daytime_visible_into_density,
synthesize_geocolor_visual_webp,
)
width, height = parse_resolution(config.resolution)
decoded_visuals = (
decode_visual_payloads(visual_payloads, width, height)
if (config.geocolor_enabled and visual_payloads)
else []
)
fused_density = (
fuse_daytime_visible_into_density(
density,
temp_c,
decoded_visuals,
width=width,
height=height,
now_utc=now_utc,
)
if decoded_visuals
else density
)
analysis = analyze_cloud_density_grid(
fused_density,
temp_c,
config=config,
previous_snapshot=prev_snapshot,
previous_regions=prev_regions,
)
webp_bytes = _encode_cloud_webp(fused_density)
visual_webp_bytes = (
synthesize_geocolor_visual_webp(
decoded_visuals,
fused_density,
width=width,
height=height,
)
if decoded_visuals
else None
)
flow_webp_bytes: bytes | None = None
flow_prev_version: str | None = None
flow_max_uv = 0.0
if config.optical_flow_enabled and isinstance(prev_entry, dict) and prev_entry.get("version"):
prev_ver = str(prev_entry["version"])
prev_frame_file = _frames_dir() / f"{prev_ver}.webp"
if prev_ver != version and prev_frame_file.exists():
try:
prev_rgba = _decode_image_bytes(prev_frame_file.read_bytes(), width, height)
prev_density = prev_rgba[:, :, 3]
flow_res = compute_dis_optical_flow_webp(prev_density, fused_density)
if flow_res is not None:
flow_webp_bytes, flow_max_uv = flow_res
flow_prev_version = prev_ver
except Exception as exc:
logger.warning_event(
"Cloud optical flow calculation failed",
event="earth.cloud_map.optical_flow_failed",
context={"prev_version": prev_ver, "error": str(exc)},
)
entry = _save_frame_artifacts_sync(
version=version,
captured_at=captured_at,
source_used=source_used,
satellites=satellites,
degraded=degraded,
config=config,
webp_bytes=webp_bytes,
visual_webp_bytes=visual_webp_bytes,
flow_webp_bytes=flow_webp_bytes,
flow_prev_version=flow_prev_version,
flow_max_uv=flow_max_uv,
grid_density=analysis["grid_density"],
grid_temp_i8=analysis["grid_temp_i8"],
global_summary=analysis["global_summary"],
regions=analysis["regions"],
clusters=analysis["convective_clusters"],
)
return entry, analysis
async with _CLOUD_WRITE_LOCK:
frame_entry, analysis = await asyncio.to_thread(_finalize)
return {
"frame": frame_entry,
"global_summary": analysis["global_summary"],
"regions": analysis["regions"],
"convective_clusters": analysis["convective_clusters"],
"config": config.model_dump(mode="json"),
}
def _summarize_storage() -> dict[str, Any]:
total_bytes = 0
file_count = 0
for directory in (_frames_dir(), _flows_dir(), _grids_dir(), _temps_dir()):
if not directory.exists():
continue
for file_path in directory.iterdir():
if file_path.is_file():
file_count += 1
try:
total_bytes += file_path.stat().st_size
except OSError:
pass
return {
"file_count": file_count,
"total_bytes": total_bytes,
"total_mb": round(total_bytes / (1024 * 1024), 2),
}
async def get_cloud_map_runtime_meta(db: AsyncSession | None = None) -> dict[str, Any]:
envelope = await read_cloud_map_configuration(db)
config = CloudMapConfig.model_validate(envelope["config"])
manifest = _read_manifest()
frames = manifest.get("frames", [])
latest = frames[0] if frames else None
latest_version = str(latest.get("version")) if isinstance(latest, dict) and latest.get("version") else None
frame_exists = bool(
latest_version
and VERSION_PATTERN.match(latest_version)
and (_frames_dir() / f"{latest_version}.webp").exists()
)
if not config.enabled:
mode = "static"
image_url = DEFAULT_STATIC_CLOUD_URL
elif frame_exists and latest is not None:
mode = "realtime"
image_url = f"/api/v1/earth/clouds/frames/{latest_version}"
else:
mode = "fallback_static"
image_url = DEFAULT_STATIC_CLOUD_URL
visual_exists = bool(
frame_exists
and config.geocolor_enabled
and (_frames_dir() / f"{latest_version}_vis.webp").exists()
)
flow_exists = bool(
frame_exists
and config.optical_flow_enabled
and (_flows_dir() / f"{latest_version}.webp").exists()
)
hd_tiles_available = False
if db is not None and hasattr(db, "execute"):
try:
hd_row = (
await db.execute(select(DataSource.is_active).where(DataSource.source == "cloud_hd_tiles"))
).scalar_one_or_none()
hd_tiles_available = bool(hd_row)
except Exception:
hd_tiles_available = False
history_frames = [
{
"version": item.get("version"),
"captured_at": item.get("captured_at"),
"source": item.get("source"),
"satellites": item.get("satellites") or [],
"degraded": bool(item.get("degraded", False)),
"resolution": item.get("resolution"),
"file_size_bytes": item.get("file_size_bytes"),
"image_url": item.get("image_url"),
"visual_url": (
f"/api/v1/earth/clouds/frames/{item.get('version')}/visual"
if (_frames_dir() / f"{item.get('version')}_vis.webp").exists()
else None
),
"flow_url": (
f"/api/v1/earth/clouds/flows/{item.get('version')}"
if (_flows_dir() / f"{item.get('version')}.webp").exists()
else None
),
"flow_prev_version": item.get("flow_prev_version"),
"flow_max_uv": float(item.get("flow_max_uv") or 0.0),
"global_summary": item.get("global_summary") or {},
}
for item in frames
if isinstance(item, dict)
and item.get("version")
and (_frames_dir() / f"{item.get('version')}.webp").exists()
]
return {
"enabled": config.enabled,
"mode": mode,
"degraded": bool(latest.get("degraded", False)) if (frame_exists and latest) else (config.enabled),
"source": latest.get("source") if (frame_exists and latest) else "static",
"satellites": (latest.get("satellites") or []) if (frame_exists and latest) else [],
"captured_at": latest.get("captured_at") if (frame_exists and latest) else None,
"version": latest_version if frame_exists else None,
"image_url": image_url,
"visual_url": f"/api/v1/earth/clouds/frames/{latest_version}/visual" if visual_exists else None,
"flow_url": f"/api/v1/earth/clouds/flows/{latest_version}" if flow_exists else None,
"flow_prev_version": latest.get("flow_prev_version") if (flow_exists and latest) else None,
"flow_max_uv": float(latest.get("flow_max_uv") or 0.0) if (flow_exists and latest) else 0.0,
"geocolor_enabled": config.geocolor_enabled,
"relief_shading_strength": config.relief_shading_strength,
"optical_flow_enabled": config.optical_flow_enabled,
"hd_tiles_available": hd_tiles_available,
"default_opacity": config.default_opacity,
"timelapse_enabled": config.timelapse_enabled,
"show_convective_markers": config.show_convective_markers,
"convective_threshold": config.convective_threshold,
"frames": history_frames,
"summary": (latest.get("global_summary") or {}) if (frame_exists and latest) else {},
"regions": (latest.get("regions") or []) if (frame_exists and latest) else [],
"convective_clusters": (latest.get("convective_clusters") or []) if (frame_exists and latest) else [],
"storage_stats": _summarize_storage(),
}
def read_cloud_frame_bytes(version: str) -> bytes | None:
if not VERSION_PATTERN.match(version):
return None
target = (_frames_dir() / f"{version}.webp").resolve()
frames_root = _frames_dir().resolve()
if target.parent != frames_root or not target.exists():
return None
return target.read_bytes()
def read_cloud_visual_frame_bytes(version: str) -> bytes | None:
if not VERSION_PATTERN.match(version):
return None
target = (_frames_dir() / f"{version}_vis.webp").resolve()
frames_root = _frames_dir().resolve()
if target.parent != frames_root or not target.exists():
return None
return target.read_bytes()
def read_cloud_flow_bytes(version: str) -> bytes | None:
if not VERSION_PATTERN.match(version):
return None
target = (_flows_dir() / f"{version}.webp").resolve()
flows_root = _flows_dir().resolve()
if target.parent != flows_root or not target.exists():
return None
return target.read_bytes()
def _load_latest_analysis_grids() -> tuple[dict[str, Any] | None, np.ndarray | None, np.ndarray | None]:
manifest = _read_manifest()
frames = manifest.get("frames", [])
if not frames:
return None, None, None
latest = frames[0]
version = str(latest.get("version") or "")
if not VERSION_PATTERN.match(version):
return None, None, None
grid_file = _grids_dir() / f"{version}.bin"
if not grid_file.exists():
return None, None, None
raw = grid_file.read_bytes()
expected = ANALYSIS_GRID_WIDTH * ANALYSIS_GRID_HEIGHT
if len(raw) != expected:
return None, None, None
density = np.frombuffer(raw, dtype=np.uint8).reshape((ANALYSIS_GRID_HEIGHT, ANALYSIS_GRID_WIDTH))
temp_file = _temps_dir() / f"{version}.bin"
temp_i8 = None
if temp_file.exists():
t_raw = temp_file.read_bytes()
if len(t_raw) == expected:
temp_i8 = np.frombuffer(t_raw, dtype=np.int8).reshape(
(ANALYSIS_GRID_HEIGHT, ANALYSIS_GRID_WIDTH)
)
return latest, density, temp_i8
async def query_cloud_point(
lat: float,
lon: float,
db: AsyncSession | None = None,
) -> dict[str, Any]:
envelope = await read_cloud_map_configuration(db)
config = CloudMapConfig.model_validate(envelope["config"])
latest, density_grid, temp_grid = _load_latest_analysis_grids()
if latest is None or density_grid is None:
return {
"available": False,
"latitude": round(float(lat), 4),
"longitude": round(float(lon), 4),
"cloud_cover_pct": None,
"classification": "unavailable",
"brightness_temp_c": None,
"captured_at": None,
}
row, col = _lat_lon_to_grid_indices(lat, lon)
pct = round(float(density_grid[row, col]) / 255.0 * 100.0, 1)
temp_val = int(temp_grid[row, col]) if temp_grid is not None else None
region_zh, region_en = _match_region_name(lat, lon)
return {
"available": True,
"latitude": round(float(lat), 4),
"longitude": round(float(lon), 4),
"cloud_cover_pct": pct,
"classification": _classify_cloud_density(pct, config.convective_threshold),
"brightness_temp_c": temp_val,
"region": region_zh,
"region_en": region_en,
"version": latest.get("version"),
"captured_at": latest.get("captured_at"),
"source": latest.get("source"),
}
async def get_cloud_analysis_summary(db: AsyncSession | None = None) -> dict[str, Any]:
meta = await get_cloud_map_runtime_meta(db)
return {
"available": meta["mode"] == "realtime",
"mode": meta["mode"],
"degraded": meta["degraded"],
"version": meta["version"],
"captured_at": meta["captured_at"],
"source": meta["source"],
"satellites": meta["satellites"],
"global_summary": meta["summary"],
"regions": meta["regions"],
"convective_clusters": meta["convective_clusters"],
}
async def _load_asset_candidates(db: AsyncSession, domain: str) -> list[dict[str, Any]]:
from app.api.v1.visualization import (
_build_compute_centers_geojson,
_build_landing_points_geojson,
_build_satellites_geojson,
)
from app.core.collected_data_fields import get_record_field
candidates: list[dict[str, Any]] = []
if domain == "vessels":
rows = (
await db.execute(
select(VesselPosition)
.where(
VesselPosition.latitude.is_not(None),
VesselPosition.longitude.is_not(None),
)
.order_by(VesselPosition.received_at.desc())
.limit(2000)
)
).scalars().all()
for row in rows:
candidates.append(
{
"id": str(row.mmsi),
"name": row.name or f"MMSI {row.mmsi}",
"entity_type": "vessel",
"latitude": float(row.latitude),
"longitude": float(row.longitude),
"extra": {"sog": row.sog, "vessel_type": row.vessel_type_name},
}
)
return candidates
fc: dict[str, Any] = {}
if domain == "cables":
fc = await _build_landing_points_geojson(db)
elif domain == "compute_centers":
fc = await _build_compute_centers_geojson(limit=1500, db=db)
else:
fc = await _build_satellites_geojson(limit=1000, db=db)
for feat in fc.get("features") or []:
geom = feat.get("geometry") or {}
coords = geom.get("coordinates")
if not isinstance(coords, (list, tuple)) or len(coords) < 2:
continue
try:
lon_val = float(coords[0])
lat_val = float(coords[1])
except (TypeError, ValueError):
continue
props = feat.get("properties") or {}
candidates.append(
{
"id": str(props.get("id") or props.get("source_id") or props.get("norad_id") or props.get("name") or ""),
"name": str(props.get("name") or props.get("title") or "Asset"),
"entity_type": str(props.get("type") or props.get("category") or domain),
"latitude": lat_val,
"longitude": lon_val,
"extra": {
k: props[k]
for k in ("country", "city", "constellation", "cable_count")
if props.get(k) is not None
},
}
)
if not candidates and domain in {"cables", "compute_centers"}:
# Lightweight fallback when visualization geojson helpers have empty sources
rows = (
await db.execute(
select(CollectedData)
.where(
CollectedData.is_current.is_(True),
CollectedData.deleted_at.is_(None),
)
.limit(1500)
)
).scalars().all()
for row in rows:
lat_val = get_record_field(row, "latitude")
lon_val = get_record_field(row, "longitude")
if not isinstance(lat_val, (int, float)) or not isinstance(lon_val, (int, float)):
continue
candidates.append(
{
"id": str(row.source_id or row.id),
"name": row.name or row.title or f"Record #{row.id}",
"entity_type": str(row.data_type or domain),
"latitude": float(lat_val),
"longitude": float(lon_val),
"extra": {"country": get_record_field(row, "country")},
}
)
return candidates
async def correlate_cloud_with_assets(
db: AsyncSession,
*,
domain: str,
min_density: float = 55.0,
limit: int = 25,
) -> dict[str, Any]:
"""Cross-reference current cloud density grid against spatial assets in DB."""
normalized_domain = str(domain or "").strip().lower()
if normalized_domain not in {"vessels", "cables", "compute_centers", "satellites"}:
raise ValueError("domain must be one of: vessels, cables, compute_centers, satellites")
latest, density_grid, temp_grid = _load_latest_analysis_grids()
if latest is None or density_grid is None:
return {
"available": False,
"domain": normalized_domain,
"min_density": min_density,
"captured_at": None,
"total_checked": 0,
"affected_count": 0,
"items": [],
}
candidates = await _load_asset_candidates(db, normalized_domain)
affected: list[dict[str, Any]] = []
for item in candidates:
row_idx, col_idx = _lat_lon_to_grid_indices(item["latitude"], item["longitude"])
pct = round(float(density_grid[row_idx, col_idx]) / 255.0 * 100.0, 1)
if pct < min_density:
continue
temp_val = int(temp_grid[row_idx, col_idx]) if temp_grid is not None else None
region_zh, _ = _match_region_name(item["latitude"], item["longitude"])
affected.append(
{
**item,
"cloud_cover_pct": pct,
"brightness_temp_c": temp_val,
"region": region_zh,
}
)
affected.sort(key=lambda entry: entry["cloud_cover_pct"], reverse=True)
bounded_limit = max(1, min(int(limit), 100))
return {
"available": True,
"domain": normalized_domain,
"min_density": min_density,
"version": latest.get("version"),
"captured_at": latest.get("captured_at"),
"total_checked": len(candidates),
"affected_count": len(affected),
"items": affected[:bounded_limit],
}
async def test_cloud_map_source(source_id: str, timeout_seconds: int = 15) -> dict[str, Any]:
"""Probe upstream cloud source using GET with tiny image size (GIBS rejects HEAD)."""
normalized = str(source_id or "multi_sat_ir").strip().lower()
if normalized not in {"multi_sat_ir", "matteason_live"}:
raise ValueError("source_id must be 'multi_sat_ir' or 'matteason_live'")
timeout = httpx.Timeout(float(max(5, min(timeout_seconds, 45))))
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthCloudProbe)"}
started = perf_counter()
if normalized == "matteason_live":
probe_url = f"{MATTEASON_BASE_URL}/2048x1024/clouds-alpha.png"
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client:
async with client.stream("GET", probe_url) as resp:
resp.raise_for_status()
content_type = str(resp.headers.get("content-type") or "").lower()
if not content_type.startswith("image/"):
raise RuntimeError(f"Unexpected content-type: {content_type}")
return {
"source_id": normalized,
"ok": True,
"latency_ms": round((perf_counter() - started) * 1000, 1),
"satellites": [{"id": "matteason_live", "ok": True}],
}
async def _probe_sat(client: httpx.AsyncClient, sat: dict[str, Any]) -> dict[str, Any]:
t0 = perf_counter()
params = _wms_getmap_params(str(sat["layer"]), 64, 32)
try:
resp = await client.get(str(sat["url"]), params=params)
resp.raise_for_status()
ct = str(resp.headers.get("content-type") or "").lower()
if not ct.startswith("image/"):
return {"id": sat["id"], "label": sat["label"], "ok": False, "error": f"content-type={ct}"}
return {
"id": sat["id"],
"label": sat["label"],
"ok": True,
"latency_ms": round((perf_counter() - t0) * 1000, 1),
}
except Exception as exc:
return {"id": sat["id"], "label": sat["label"], "ok": False, "error": str(exc)}
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client:
sat_results = await asyncio.gather(*(_probe_sat(client, sat) for sat in SATELLITE_SOURCES))
ok_count = sum(1 for item in sat_results if item["ok"])
return {
"source_id": normalized,
"ok": ok_count > 0,
"reachable_count": ok_count,
"total_count": len(SATELLITE_SOURCES),
"latency_ms": round((perf_counter() - started) * 1000, 1),
"satellites": sat_results,
}
async def get_cloud_datasource_summary(db: AsyncSession) -> dict[str, Any] | None:
ds = (
await db.execute(select(DataSource).where(DataSource.source == "global_cloud_map"))
).scalar_one_or_none()
if ds is None:
return None
return {
"id": ds.id,
"source": ds.source,
"name": ds.name,
"is_active": ds.is_active,
"frequency_minutes": ds.frequency_minutes,
"last_run_at": to_iso8601_utc(ds.last_run_at),
"next_run_at": to_iso8601_utc(ds.next_run_at),
"last_status": ds.last_status,
}
def validate_whitelisted_cloud_url(url: str) -> str:
parsed = urlparse(str(url or "").strip())
allowed_hosts = {"gibs.earthdata.nasa.gov", "view.eumetsat.int", "clouds.matteason.co.uk"}
if parsed.scheme != "https" or (parsed.hostname or "").lower() not in allowed_hosts:
raise ValueError("Cloud URL must target a whitelisted meteorological HTTPS host")
return url