Files
planet/backend/app/services/earth_clouds_fx.py
T
rayd1o 30b44ec00d
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.84.2
2026-12-05 01:56:03 +08:00

323 lines
13 KiB
Python

"""GeoColor daytime visible compositing and DIS optical flow synthesis for cloud maps."""
from __future__ import annotations
import gc
import io
import math
from datetime import UTC, datetime
from typing import Any, Iterator, Sequence
import cv2
import numpy as np
from PIL import Image
def _longitude_weight_vector(width: int, sub_lon_deg: float) -> np.ndarray:
lons = ((np.arange(width, dtype=np.float32) + 0.5) / float(width)) * 360.0 - 180.0
delta = np.abs(((lons - float(sub_lon_deg) + 180.0) % 360.0) - 180.0)
sigma = 46.0
weights = np.exp(-0.5 * (delta / sigma) ** 2).astype(np.float32)
weights[delta > 74.0] = 0.0
return weights
def _decode_rgba_resized(payload_bytes: bytes, width: int, height: int) -> np.ndarray:
with Image.open(io.BytesIO(payload_bytes)) as img:
converted = img.convert("RGBA")
if converted.size != (width, height):
converted = converted.resize((width, height), Image.Resampling.BILINEAR)
return np.asarray(converted, dtype=np.uint8)
def decode_visual_payloads(
visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]],
width: int,
height: int,
) -> list[tuple[dict[str, Any], np.ndarray]]:
"""Decode and resize visible satellite payloads once so density & GeoColor share buffers."""
return list(_iter_decoded_visuals(visual_payloads, width, height))
def _iter_decoded_visuals(
visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]],
width: int,
height: int,
) -> Iterator[tuple[dict[str, Any], np.ndarray]]:
"""Yield one decoded RGBA visual frame at a time to bound peak heap usage."""
for sat, payload in visual_payloads:
if isinstance(payload, np.ndarray):
if payload.shape[:2] == (height, width) and payload.shape[2] == 4:
yield sat, payload
continue
try:
rgba = _decode_rgba_resized(payload, width, height)
yield sat, rgba
except Exception:
continue
def _rgba_channels_and_luma(
rgba: np.ndarray,
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
red = rgba[:, :, 0]
green = rgba[:, :, 1]
blue = rgba[:, :, 2]
alpha = rgba[:, :, 3]
luma = (
0.299 * red.astype(np.float32)
+ 0.587 * green.astype(np.float32)
+ 0.114 * blue.astype(np.float32)
)
return red, green, blue, alpha, luma
def _solar_cosine_grid(width: int, height: int, now_utc: datetime) -> tuple[np.ndarray, np.ndarray]:
"""Return `(cos_sza_2d, lats_deg_1d)` on the equirectangular cloud grid."""
utc = now_utc.astimezone(UTC) if now_utc.tzinfo else now_utc.replace(tzinfo=UTC)
doy = utc.timetuple().tm_yday
decl = math.radians(-23.44 * math.cos(2.0 * math.pi * (doy + 10) / 365.0))
utc_hour = utc.hour + utc.minute / 60.0 + utc.second / 3600.0
subsolar_lon = (12.0 - utc_hour) * 15.0
lats_deg = (90.0 - ((np.arange(height, dtype=np.float32) + 0.5) / float(height)) * 180.0)
lons_deg = (((np.arange(width, dtype=np.float32) + 0.5) / float(width)) * 360.0 - 180.0)
lat_rad = np.deg2rad(lats_deg)[:, None]
ha_rad = np.deg2rad(lons_deg - subsolar_lon)[None, :]
cos_sza = (
np.sin(lat_rad) * math.sin(decl)
+ np.cos(lat_rad) * math.cos(decl) * np.cos(ha_rad)
).astype(np.float32)
return cos_sza, lats_deg
def fuse_daytime_visible_into_density(
density_u8: np.ndarray,
temp_c: np.ndarray,
visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]],
*,
width: int,
height: int,
now_utc: datetime | None = None,
) -> np.ndarray:
"""Recover warm daytime low clouds (stratocumulus) from sunlit visible channels."""
if not visual_payloads or density_u8.shape != (height, width) or temp_c.shape != (height, width):
return density_u8
cos_sza, lats_deg = _solar_cosine_grid(width, height, now_utc or datetime.now(UTC))
polar_w = np.clip((76.0 - np.abs(lats_deg)) / 12.0, 0.0, 1.0).astype(np.float32)[:, None]
day_weight = (np.clip((cos_sza - 0.12) / 0.24, 0.0, 1.0) * polar_w).astype(np.float32)
if not np.any(day_weight > 0.01):
return density_u8
cos_safe = np.clip(cos_sza, 0.30, 1.0)
safe_temp = np.where(np.isfinite(temp_c), temp_c, 15.0).astype(np.float32)
# Band-pass gate: peaks on -2C..+16C warm low clouds while suppressing hot deserts (>+24C) and sub-zero snow (<-8C).
warm_low_cloud_gate = (
np.clip((24.0 - safe_temp) / 12.0, 0.0, 1.0)
* np.clip((safe_temp + 8.0) / 10.0, 0.0, 1.0)
).astype(np.float32)
vis_accum = np.zeros((height, width), dtype=np.float32)
weight_accum = np.zeros((height, width), dtype=np.float32)
for sat, rgba in _iter_decoded_visuals(visual_payloads, width, height):
r_u8, g_u8, b_u8, alpha_u8, luma = _rgba_channels_and_luma(rgba)
not_clipped = ~(
(r_u8 >= 254)
& (g_u8 >= 254)
& (b_u8 >= 254)
& (safe_temp > -10.0)
)
valid = (alpha_u8 > 12) & (luma > 8.0) & not_clipped
if not np.any(valid):
continue
max_u8 = np.maximum(np.maximum(r_u8, g_u8), b_u8)
min_u8 = np.minimum(np.minimum(r_u8, g_u8), b_u8)
chroma = (max_u8 - min_u8).astype(np.float32) / 255.0
is_color = float(np.nanpercentile(chroma[valid], 95)) > 0.08
if is_color:
albedo = min_u8.astype(np.float32) / cos_safe
whiteness = np.clip(1.0 - chroma / 0.36, 0.0, 1.0)
sat_cloud = np.clip((albedo - 85.0) / 135.0, 0.0, 1.0) * whiteness * warm_low_cloud_gate
else:
albedo = luma / cos_safe
sat_cloud = np.clip((albedo - 88.0) / 132.0, 0.0, 1.0) * warm_low_cloud_gate
lon_w = _longitude_weight_vector(width, float(sat.get("sub_lon", 0.0)))
pix_w = np.where(valid, lon_w[None, :], 0.0)
vis_accum += sat_cloud * pix_w
weight_accum += pix_w
del rgba, luma, chroma, sat_cloud, pix_w
covered = weight_accum > 0.0
if not np.any(covered):
return density_u8
vis_cloud = np.zeros((height, width), dtype=np.float32)
vis_cloud[covered] = vis_accum[covered] / weight_accum[covered]
vis_cloud *= day_weight
vis_u8 = np.clip(np.round(vis_cloud * 255.0), 0, 255).astype(np.uint8)
vis_u8 = cv2.GaussianBlur(vis_u8, (3, 3), 0.6)
return np.maximum(density_u8, vis_u8)
def synthesize_geocolor_visual_webp(
visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]],
density_u8: np.ndarray,
*,
width: int,
height: int,
) -> bytes | None:
"""Composite daytime GeoColor/Visible satellite WMS tiles into an RGBA WebP overlay."""
if not visual_payloads or density_u8.shape != (height, width):
return None
rgb_accum = np.zeros((height, width, 3), dtype=np.float32)
weight_accum = np.zeros((height, width), dtype=np.float32)
valid_sources = 0
for sat, rgba in _iter_decoded_visuals(visual_payloads, width, height):
r_u8, g_u8, b_u8, alpha_u8, luma = _rgba_channels_and_luma(rgba)
# EUMETView/GIBS return opaque black over night hemispheres or pure-white clipped wedges.
# Mask out dark night pixels and non-dense pure-white [255,255,255] fill artifacts.
not_clipped = ~(
(r_u8 >= 254)
& (g_u8 >= 254)
& (b_u8 >= 254)
& (density_u8 < 180)
)
valid = (alpha_u8 > 12) & (luma > 22.0) & not_clipped
if not np.any(valid):
continue
lon_w = _longitude_weight_vector(width, float(sat.get("sub_lon", 0.0)))
# Emphasize cloud-rich pixels from daytime channels so dark ocean reflectance doesn't darken clouds.
pix_w = np.where(valid, lon_w[None, :], 0.0)
for ch in range(3):
rgb_accum[:, :, ch] += rgba[:, :, ch].astype(np.float32) * pix_w
weight_accum += pix_w
valid_sources += 1
del rgba, luma, pix_w
if valid_sources == 0 or not np.any(weight_accum > 0.0):
return None
covered = weight_accum > 0.0
comp_rgb = np.full((height, width, 3), 238.0, dtype=np.float32)
comp_rgb[covered] = rgb_accum[covered] / weight_accum[covered, None]
# Purify cloud colors toward clean sunlight white so underlying dark land/ocean never tints thin clouds green/brown
density_f = density_u8.astype(np.float32) / 255.0
comp_luma = (
0.299 * comp_rgb[:, :, 0] + 0.587 * comp_rgb[:, :, 1] + 0.114 * comp_rgb[:, :, 2]
)
daylight_factor = np.where(
covered,
np.clip((comp_luma - 28.0) / 140.0, 0.0, 1.0),
0.0,
).astype(np.float32)
fallback_tone = np.clip(212.0 + density_f * 43.0, 0.0, 255.0)
for ch in range(3):
blended = comp_rgb[:, :, ch] * daylight_factor + fallback_tone * (1.0 - daylight_factor)
comp_rgb[:, :, ch] = blended * 0.65 + fallback_tone * 0.35
out_rgba = np.empty((height, width, 4), dtype=np.uint8)
out_rgba[:, :, :3] = np.clip(np.round(comp_rgb), 0, 255).astype(np.uint8)
# Alpha encodes visible daylight availability multiplied by cloud density.
vis_alpha = np.clip(np.round(density_f * (0.35 + 0.65 * daylight_factor) * 255.0), 0, 255).astype(np.uint8)
out_rgba[:, :, 3] = vis_alpha
img = Image.fromarray(out_rgba, mode="RGBA")
buf = io.BytesIO()
img.save(buf, format="WEBP", quality=86, method=1)
return buf.getvalue()
def compute_dis_optical_flow_webp(
prev_density_u8: np.ndarray,
curr_density_u8: np.ndarray,
*,
flow_width: int = 512,
flow_height: int = 256,
) -> tuple[bytes, float] | None:
"""Compute dense DIS optical flow between consecutive cloud density frames.
Returns `(webp_bytes, max_uv)` where pixels encode normalized UV displacement:
- `R = round((du / max_uv * 0.5 + 0.5) * 255)`
- `G = round((dv / max_uv * 0.5 + 0.5) * 255)`
Using OpenCV's inverted-V orientation converted directly to WebGL UV delta (`v` positive up).
"""
if prev_density_u8 is None or curr_density_u8 is None:
return None
if prev_density_u8.size == 0 or curr_density_u8.size == 0:
return None
prev_small = cv2.resize(prev_density_u8, (flow_width, flow_height), interpolation=cv2.INTER_AREA)
curr_small = cv2.resize(curr_density_u8, (flow_width, flow_height), interpolation=cv2.INTER_AREA)
dis = cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_MEDIUM)
flow_px = dis.calc(prev_small, curr_small, None)
if flow_px is None or flow_px.shape[:2] != (flow_height, flow_width):
return None
# Smooth vector field slightly so advection warps stay coherent without blockiness
flow_px = cv2.GaussianBlur(flow_px, (7, 7), 1.6)
# Convert pixel displacement to normalized equirectangular UV displacement.
# Flip Y sign because image rows increase downward while equirectangular V increases upward in Three.js Canvas/Image unless flipY=true.
# Three.js default Texture.flipY=true puts row 0 (North) at v=1 and row H-1 (South) at v=0, so positive image dy (southward) corresponds to negative dv.
du = flow_px[:, :, 0].astype(np.float32) / float(flow_width)
dv = -flow_px[:, :, 1].astype(np.float32) / float(flow_height)
# Suppress tiny noisy vectors in clear sky regions
max_uv = float(max(np.percentile(np.maximum(np.abs(du), np.abs(dv)), 99.5), 1e-4))
max_uv = min(max_uv, 0.08)
u_norm = np.clip(du / max_uv, -1.0, 1.0) * 0.5 + 0.5
v_norm = np.clip(dv / max_uv, -1.0, 1.0) * 0.5 + 0.5
rgb = np.empty((flow_height, flow_width, 3), dtype=np.uint8)
rgb[:, :, 0] = np.clip(np.round(u_norm * 255.0), 0, 255).astype(np.uint8)
rgb[:, :, 1] = np.clip(np.round(v_norm * 255.0), 0, 255).astype(np.uint8)
rgb[:, :, 2] = 128
img = Image.fromarray(rgb, mode="RGB")
buf = io.BytesIO()
img.save(buf, format="WEBP", quality=92, method=1)
return buf.getvalue(), round(float(max_uv), 6)
def fuse_and_synthesize_visual_layers(
density_u8: np.ndarray,
temp_c: np.ndarray,
visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]],
*,
width: int,
height: int,
now_utc: datetime | None = None,
) -> tuple[np.ndarray, bytes | None]:
"""Stream visible payloads one at a time for low-cloud density fusion and GeoColor WebP."""
if not visual_payloads:
return density_u8, None
fused_density = fuse_daytime_visible_into_density(
density_u8,
temp_c,
visual_payloads,
width=width,
height=height,
now_utc=now_utc,
)
gc.collect()
visual_webp_bytes = synthesize_geocolor_visual_webp(
visual_payloads,
fused_density,
width=width,
height=height,
)
gc.collect()
return fused_density, visual_webp_bytes