riccardode's picture frankaisabell's picture
Add minimal raw-data preprocessing for MODIS-to-S2 inputs (#2)
33dd50b
Raw History Blame Contribute Delete
5.07 kB
"""Verbatim geometry/sampling functions from the producer environment."""
from typing import Tuple
import warnings
import numpy as np
from pyproj import CRS,Transformer
from scipy.ndimage import map_coordinates
class FCIGeometry:
"""MTG FCI full-disk geostationary geometry (EUMETSAT ICD-SBV-0064).
Scan order note
---------------
The FCI L1C product (as read by satpy) stores rows south→north: row 0 is
the southernmost line of the visible disk. The satpy pyresample area
therefore has a *negative* pixel_size_y (y_ll = north edge, y_ur = south
edge in the area_extent tuple).
Consequence for row mapping
---------------------------
Given a geostationary y coordinate (positive = northward, standard PROJ
convention), the full-disk pixel row is:
row = (y_geos - Y_SOUTH) / SCALE_Y - 0.5
where Y_SOUTH is the *geographic* y value of the south edge of the disk
(a negative number in standard geos coordinates).
"""
FULL_DISK_PX: int = 11136
# Projection semi-axes from the official CRS
A_METERS: float = 6_378_169.0 # semi-major axis
B_METERS: float = 6_356_583.8 # semi-minor axis
H_METERS: float = 35_785_831.0 # satellite altitude above ellipsoid
LON_0_DEG: float = 0.0
# Full-disk extent from areas.yaml (EUMETSAT ICD values)
# X_WEST / X_EAST : western / eastern edge x in geos metres
# Y_NORTH / Y_SOUTH: northern / southern edge y in geos metres
# (Y_SOUTH is negative because south of the equator)
X_WEST: float = -5_571_248.412732527
X_EAST: float = 5_566_247.740968115
Y_NORTH: float = 5_571_248.412732527
Y_SOUTH: float = -5_566_247.740968115
SCALE_X: float = (X_EAST - X_WEST) / FULL_DISK_PX # m per pixel (col)
SCALE_Y: float = (Y_NORTH - Y_SOUTH) / FULL_DISK_PX # m per pixel (row)
CRS_PROJ_STRING: str = (
"+proj=geos +lon_0=0 +h=35785831 "
"+a=6378169 +b=6356583.8 +units=m"
)
@classmethod
def crs(cls) -> CRS:
return CRS.from_proj4(cls.CRS_PROJ_STRING)
def _latlon_to_fci_px(
lat: np.ndarray, lon: np.ndarray,
fci_patch_row0: int,
fci_patch_col0: int,
fci_patch_h: int = 128,
fci_patch_w: int = 128,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Map (lat, lon) → fractional pixel coordinates inside the FCI patch.
Parameters
----------
lat, lon : ndarray (H_out × W_out)
fci_patch_row0, fci_patch_col0 : int
Top-left corner of the extracted FCI patch in full-disk pixel coords.
(Row 0 = north edge of full disk.)
fci_patch_h, fci_patch_w : int
Size of the FCI patch (default 128×128).
Returns
-------
frac_row, frac_col : ndarray (H_out × W_out)
Fractional index into the FCI patch; NaN where outside or over the
Earth limb (geostationary projection is undefined beyond the disk).
"""
geo = FCIGeometry
t = Transformer.from_crs(
CRS.from_epsg(4326),
CRS.from_proj4(geo.CRS_PROJ_STRING),
always_xy=True,
)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
x_geos, y_geos = t.transform(lon, lat)
# Over-the-limb pixels become ±inf or nan from pyproj
limb_mask = ~np.isfinite(x_geos) | ~np.isfinite(y_geos)
# Convert geostationary metres → full-disk pixel index (0-based, float)
# Column: x increases eastward, col increases eastward
# Row: FCI scans south→north so row 0 = south edge; y increases northward
col_full = (x_geos - geo.X_WEST) / geo.SCALE_X - 0.5
row_full = (y_geos - geo.Y_SOUTH) / geo.SCALE_Y - 0.5
# Convert to patch-local fractional index
frac_col = col_full - fci_patch_col0
frac_row = row_full - fci_patch_row0
# Mask out-of-bounds and limb.
# For bilinear interpolation (order=1), scipy.map_coordinates returns NaN
# if the fractional index is strictly > size-1 (it would need to sample the
# out-of-bounds neighbour pixel). The safe range is exactly [0, size-1].
outside = (
limb_mask
| (frac_row < 0) | (frac_row > fci_patch_h - 1)
| (frac_col < 0) | (frac_col > fci_patch_w - 1)
)
frac_row[outside] = np.nan
frac_col[outside] = np.nan
return frac_row, frac_col
def _sample_array(
source: np.ndarray,
frac_row: np.ndarray,
frac_col: np.ndarray,
order: int = 1,
fill_value: float = np.nan,
) -> np.ndarray:
"""
Bilinear (order=1) sampling of *source* at fractional indices.
NaN coordinates produce fill_value in the output.
The output dtype is float32 regardless of the input dtype.
"""
out = np.full(frac_row.shape, fill_value, dtype=np.float32)
valid = np.isfinite(frac_row) & np.isfinite(frac_col)
if not valid.any():
return out
out[valid] = map_coordinates(
source.astype(np.float32),
[frac_row[valid], frac_col[valid]],
order=order,
mode="constant",
cval=fill_value,
prefilter=False,
)
return out