Add minimal raw-data preprocessing for MODIS-to-S2 inputs

#2
README.md CHANGED
@@ -16,6 +16,11 @@ This checkpoint reconstructs Sentinel-2 NDVI on a 20 m grid using prior Sentinel
16
 
17
  The package includes the weights, inference code, ten examples and reference predictions. The inputs are ready to use; no satellite downloads or HPC access are needed.
18
 
 
 
 
 
 
19
  ## Try an example
20
 
21
  Download and extract [demo_bundle.zip](demo_bundle.zip), then open a terminal in the extracted directory. Python 3.11 is the tested version.
 
16
 
17
  The package includes the weights, inference code, ten examples and reference predictions. The inputs are ready to use; no satellite downloads or HPC access are needed.
18
 
19
+ ## Prepare your own inputs
20
+
21
+ The [preprocessing guide](preprocessing/README.md) provides the code and input
22
+ manifest for assembling your own raw observations into `inputs.npz`.
23
+
24
  ## Try an example
25
 
26
  Download and extract [demo_bundle.zip](demo_bundle.zip), then open a terminal in the extracted directory. Python 3.11 is the tested version.
checksums.sha256 CHANGED
@@ -1,5 +1,5 @@
1
  89319f24748189ce911417c6360b1bc64e66aee829fa512c25cd6890db0efb3d INPUTS.md
2
- 6301ff38bdcfaa7991d6d0e4b4f6947a0503c38562bdcffb1bad41a3328bcfd5 README.md
3
  de013825dacd6a6fe7dc647b70df5ed09d0aaedb9fcc6db142e3150ae18806b7 config.json
4
  0891f673bc5084b4cb23b21b650b8dadeac28e3ab1ed182850dc7d157e393123 demo/france_south_x-1_y-1_2025-06-18/inputs.npz
5
  114397175f004e5c19d8bf0ce3ca17257970a223b1d9f9dde9a833c1661891a9 demo/france_south_x-1_y-1_2025-06-18/metadata.json
@@ -54,6 +54,15 @@ ae6c5cbb7a275307eb4dc089a097578aab9ff4a80b3089d85573a816e5a314b5 modis_s2/metri
54
  fc2bc891aa5166c77f5a3bb79056df8cd2f0f0b0f980321c11ad4dd565f73623 modis_s2/model.py
55
  b82790a69ccb1222c4444cd38c3a9590dbe2cc4e7143f6f18f311bcb86c9fb49 modis_s2/predict.py
56
  2f14524afc57401ef3688c06f298dd68ab2e2a60713c789aacbedcc574687845 normalization.json
 
 
 
 
 
 
 
 
 
57
  e29d8ae12aaa41f3826f5e69ea7ff96e6caa0ce123dc8ddd6623ab225356f772 provenance.json
58
  34d6a0b4b40d8746ff91dfc1b24d65d8b4f11f2df8d36e6b836169a450ba4fd0 reference_metrics.json
59
  c51817ea6c503800905143b16e5b0375ce3668ade15472da277642e9e78f64b1 requirements.txt
 
1
  89319f24748189ce911417c6360b1bc64e66aee829fa512c25cd6890db0efb3d INPUTS.md
2
+ 44a59f8099338268221af7fbe769fea5a04ac2a22ba1af7a28affe38fcbc9982 README.md
3
  de013825dacd6a6fe7dc647b70df5ed09d0aaedb9fcc6db142e3150ae18806b7 config.json
4
  0891f673bc5084b4cb23b21b650b8dadeac28e3ab1ed182850dc7d157e393123 demo/france_south_x-1_y-1_2025-06-18/inputs.npz
5
  114397175f004e5c19d8bf0ce3ca17257970a223b1d9f9dde9a833c1661891a9 demo/france_south_x-1_y-1_2025-06-18/metadata.json
 
54
  fc2bc891aa5166c77f5a3bb79056df8cd2f0f0b0f980321c11ad4dd565f73623 modis_s2/model.py
55
  b82790a69ccb1222c4444cd38c3a9590dbe2cc4e7143f6f18f311bcb86c9fb49 modis_s2/predict.py
56
  2f14524afc57401ef3688c06f298dd68ab2e2a60713c789aacbedcc574687845 normalization.json
57
+ 9cca6554c6940a3b6334cefec65cc2bb40beb88c0122723665696efe09dc4363 preprocessing/README.md
58
+ 0940f2e78ac1197f0350085da498ea793a3e2041de86b5634dd3ba2426f9dbf2 preprocessing/__init__.py
59
+ 68886242c4000fa2604ef044ace45e7721d03f4ee8be0517697718df475de9b1 preprocessing/assemble.py
60
+ 264365ab736a5094a66aafbfd7e493746c4f8e21cc55c315ca8de6f4bd9594ce preprocessing/fci.py
61
+ faaf89437be414b5b0faaa64b617f39ed750349c3012ec5259400644b7ddc881 preprocessing/legacy_sentinel.py
62
+ f21aeab2271f7d5be2ad606c4a6e10ab3bb8b42c5a86ff8d8d2a216fb7e96018 preprocessing/manifest.example.json
63
+ 9bfebde9813cb297d5a314ad6da1080fcb1433780e6b15a022194d27bfc2e7b9 preprocessing/raw.py
64
+ 07e524edc59c8d266ae46faa404922ce2896a14ef79c13df794a4670f3a5ea1b preprocessing/recipe.json
65
+ 1e3c130b1c863ed4b5bd92cca7860c08c84bf86c91d42fa5dfa5850c6702e179 preprocessing/requirements.txt
66
  e29d8ae12aaa41f3826f5e69ea7ff96e6caa0ce123dc8ddd6623ab225356f772 provenance.json
67
  34d6a0b4b40d8746ff91dfc1b24d65d8b4f11f2df8d36e6b836169a450ba4fd0 reference_metrics.json
68
  c51817ea6c503800905143b16e5b0375ce3668ade15472da277642e9e78f64b1 requirements.txt
preprocessing/README.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Raw observations to `inputs.npz`
2
+
3
+ This folder contains the preprocessing for the released MODIS-to-Sentinel-2
4
+ model. It produces normalized input arrays; use the repository's existing
5
+ `normalization.json` unchanged. Tensor definitions are in [INPUTS.md](../INPUTS.md).
6
+
7
+ ## Usage
8
+
9
+ From the repository root, with Python 3.11:
10
+
11
+ ```bash
12
+ python -m pip install -r preprocessing/requirements.txt
13
+ cp preprocessing/manifest.example.json scene.json
14
+ # Edit scene.json for your grid, acquisition IDs/times and local source paths.
15
+ python -m preprocessing.raw --manifest scene.json \
16
+ --aligned-output work/scene --output work/scene/inputs.npz
17
+ ```
18
+
19
+ The output directory contains `inputs.npz` and its georeferencing `metadata.json`.
20
+ It must be a new directory. The example manifest documents a complete input
21
+ configuration; the referenced data files are not included. `recipe.json`
22
+ documents the fixed preprocessing conventions used by the model.
23
+
24
+ ## Sources in the manifest
25
+
26
+ - **S1:** georeferenced RTC VV/VH rasters in **linear power**, with observation
27
+ timestamps and processing metadata. The code converts positive power to dB
28
+ once and applies the released training normalization.
29
+ - **S2:** native L2A DN rasters for B01, B02, B03, B04, B05, B06, B07, B08,
30
+ B8A, B09, B11, B12 and SCL. Supply the original product metadata XML using
31
+ `product_metadata_xml`, or its authoritative BOA quantification/offsets in
32
+ `radiometry`. Keep cloudy observations: SCL and measurement masks are separate.
33
+ - **MODIS:** exact target-day MOD09GQ and matching MOD09GA Collection 061 HDF4
34
+ products, with the same tile/date/production. Their common numeric/QA support
35
+ preserves the released model's paired 250m/500m input recipe.
36
+ - **MTG:** archived native FCI `vis_06`/`vis_08` patches, one NPZ per candidate,
37
+ with keys `vis_06`, `vis_08`, `origin`. `origin` is the native full-disk
38
+ `[row0, col0]` shared by both bands. Preserve the archive's units and row
39
+ orientation. For each observation provide the three nearest available
40
+ source grids in their original rank order. The code performs geostationary
41
+ mapping, bilinear sampling, support checks, scaling and five-slot padding.
42
+ - **Land cover:** georeferenced MCD12Q1 `LC_Type1` categorical raster, preserving
43
+ its native grid and nodata. The original archive's year was not verified.
44
+
45
+ All paths are relative to the manifest. Its `geometry` specifies the actual
46
+ 256 x 256, north-up, 20m output grid; do not infer a footprint from array size.
47
+ The reader accepts explicitly selected source assets. Catalogue search,
48
+ downloads, and the upstream FCI L1C-to-archive conversion are outside this entry
49
+ point. No source imagery is overwritten.
50
+
51
+ Select prior S2 products from the same MGRS tile, one per date, in chronological
52
+ order. Exclude the target and target-day S2. Prior S1 must have a common known
53
+ orbit direction/relative orbit and cover the footprint. The newer original
54
+ cohort requested eight S2 dates and up to six S1 dates, with at least two S1;
55
+ preserve the actual committed history when reproducing an existing scene.
56
+
57
+ ## Already aligned observations
58
+
59
+ If the native products have already been assembled into the original aligned
60
+ `sentinel.npz` (or legacy `conditioning.npz`), `context.npz` and
61
+ `paired_modis.npz`, together with their `metadata.json`:
62
+
63
+ ```bash
64
+ python -m preprocessing.assemble --scene-dir aligned_scene \
65
+ --output aligned_scene/inputs.npz
66
+ ```
67
+
68
+ The released input assembly reads no target image. It uses original product
69
+ timestamps, a cutoff at midnight ending the target UTC day, and train-only
70
+ normalization. Do not normalize the output again. This preserves retrospective
71
+ input conventions; it does not certify historical real-time product availability.
preprocessing/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Preprocessing for the published MODIS250 v1 checkpoint."""
preprocessing/assemble.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Assemble exact released inputs from committed, spatially aligned observations."""
2
+ from pathlib import Path
3
+ import argparse,json
4
+ import numpy as np
5
+ from .legacy_sentinel import predictors,sha,parse,cutoff
6
+
7
+ def assemble(scene_dir,normalization,modis_pair=None,no_modis=False):
8
+ scene_dir=Path(scene_dir);meta_path=scene_dir/'metadata.json';meta=json.loads(meta_path.read_text())
9
+ if meta['geometry']['shape'] != [256,256]:raise ValueError('This checkpoint requires 256x256 at 20m')
10
+ transform=meta['geometry']['transform']
11
+ if not np.allclose([transform[0],transform[1],transform[3],transform[4]],[20,0,0,-20],atol=1e-9,rtol=0):raise ValueError('Use the original north-up 20m scene grid')
12
+ stats=json.loads(Path(normalization).read_text())
13
+ # Keep the production functions' floating-point order, S1 float64 logarithm,
14
+ # radiometry, masks, SCL one-hot encoding, calendar and last-clear anchor.
15
+ p,_,_=predictors({'folder':str(scene_dir),'metadata_sha256':sha(meta_path)},stats)
16
+ p.pop('modis')
17
+ for key in ['s2_quality','s2_quality_valid']:p[key]=p[key].astype(bool).astype(np.float32)
18
+ with np.load(scene_dir/'context.npz',allow_pickle=False) as z:
19
+ geo=z['geo'][-5:].copy();ages=z['geo_age'][-5:].copy();times=z['geo_times'][-5:].copy();land=z['landcover'].copy()
20
+ if land.ndim==2:
21
+ valid=z['landcover_valid'].astype(bool)
22
+ land=np.concatenate([(land==np.arange(1,18)[:,None,None])&valid,valid[None]],axis=0)
23
+ assert geo.shape==(5,3,256,256) and land.shape==(18,256,256) and ages.shape==(5,)
24
+ for index,stamp in enumerate(times):
25
+ if stamp:
26
+ observed=parse(str(stamp));assert str(stamp)[:10]==meta['date'] and observed<cutoff(meta['date'])
27
+ assert abs(float(ages[index])-(cutoff(meta['date'])-observed).total_seconds()/86400)<1e-4
28
+ else:assert not geo[index].any()
29
+ p={key:value[None] for key,value in p.items()}
30
+ p['geo']=geo[None];p['geo_age']=ages[None];p['mtg_age']=p['geo_age'].copy()
31
+ same=np.zeros((1,39,256,256),np.float32);same[:,6:21]=p['geo'].reshape(1,15,256,256);same[:,21:]=land.astype(bool)
32
+ if no_modis:
33
+ if modis_pair is not None:raise ValueError('Choose a MODIS pair or explicitly missing MODIS, not both')
34
+ else:
35
+ path=Path(modis_pair) if modis_pair else scene_dir/'paired_modis.npz'
36
+ with np.load(path,allow_pickle=False) as z:
37
+ common=z['common_20m_mask'].astype(bool);values=np.stack([z['reflectance_500'],z['reflectance_250']])
38
+ assert common.shape==(256,256) and values.shape==(2,2,256,256)
39
+ assert np.isfinite(values).all() and not values[...,~common].any()
40
+ same[0,:2]=np.clip(values/.5,-1,3)[1];same[0,2:6]=common
41
+ p['same_day']=same
42
+ for key,value in p.items():
43
+ assert value.dtype==(np.bool_ if key in ['s1_mask','s2_mask'] else np.float32),(key,value.dtype)
44
+ assert np.isfinite(value).all(),key
45
+ return p,meta
46
+
47
+ def write(path,arrays):
48
+ path=Path(path);path.parent.mkdir(parents=True,exist_ok=True);temp=path.with_name(path.name+'.partial.npz')
49
+ np.savez_compressed(temp,**arrays);temp.replace(path)
50
+ with np.load(path,allow_pickle=False) as stored:
51
+ assert set(stored.files)==set(arrays)
52
+ for key,value in arrays.items():assert stored[key].dtype==value.dtype and np.array_equal(stored[key],value),key
53
+
54
+ def main():
55
+ ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--scene-dir',type=Path,required=True);ap.add_argument('--normalization',type=Path,default=Path(__file__).resolve().parents[1]/'normalization.json');ap.add_argument('--modis-pair',type=Path);ap.add_argument('--no-modis',action='store_true');ap.add_argument('--output',type=Path,required=True);args=ap.parse_args()
56
+ arrays,meta=assemble(args.scene_dir,args.normalization,args.modis_pair,args.no_modis);write(args.output,arrays)
57
+ provenance={'id':meta['id'],'date':meta['date'],'target_time':meta['target_time'],'geometry':meta['geometry'],'normalization_sha256':sha(args.normalization),'source_metadata_sha256':sha(args.scene_dir/'metadata.json'),'inputs_sha256':sha(args.output),'keys':{k:{'shape':list(v.shape),'dtype':str(v.dtype)} for k,v in arrays.items()},'training_or_target_labels_read':False,'augmentation':False}
58
+ args.output.with_suffix('.metadata.json').write_text(json.dumps(provenance,indent=2)+'\n');print('Wrote',args.output,'with',len(arrays),'input arrays')
59
+ if __name__=='__main__':main()
preprocessing/fci.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verbatim geometry/sampling functions from the producer environment."""
2
+ from typing import Tuple
3
+ import warnings
4
+ import numpy as np
5
+ from pyproj import CRS,Transformer
6
+ from scipy.ndimage import map_coordinates
7
+
8
+ class FCIGeometry:
9
+ """MTG FCI full-disk geostationary geometry (EUMETSAT ICD-SBV-0064).
10
+
11
+ Scan order note
12
+ ---------------
13
+ The FCI L1C product (as read by satpy) stores rows south→north: row 0 is
14
+ the southernmost line of the visible disk. The satpy pyresample area
15
+ therefore has a *negative* pixel_size_y (y_ll = north edge, y_ur = south
16
+ edge in the area_extent tuple).
17
+
18
+ Consequence for row mapping
19
+ ---------------------------
20
+ Given a geostationary y coordinate (positive = northward, standard PROJ
21
+ convention), the full-disk pixel row is:
22
+
23
+ row = (y_geos - Y_SOUTH) / SCALE_Y - 0.5
24
+
25
+ where Y_SOUTH is the *geographic* y value of the south edge of the disk
26
+ (a negative number in standard geos coordinates).
27
+ """
28
+
29
+ FULL_DISK_PX: int = 11136
30
+
31
+ # Projection semi-axes from the official CRS
32
+ A_METERS: float = 6_378_169.0 # semi-major axis
33
+ B_METERS: float = 6_356_583.8 # semi-minor axis
34
+ H_METERS: float = 35_785_831.0 # satellite altitude above ellipsoid
35
+ LON_0_DEG: float = 0.0
36
+
37
+ # Full-disk extent from areas.yaml (EUMETSAT ICD values)
38
+ # X_WEST / X_EAST : western / eastern edge x in geos metres
39
+ # Y_NORTH / Y_SOUTH: northern / southern edge y in geos metres
40
+ # (Y_SOUTH is negative because south of the equator)
41
+ X_WEST: float = -5_571_248.412732527
42
+ X_EAST: float = 5_566_247.740968115
43
+ Y_NORTH: float = 5_571_248.412732527
44
+ Y_SOUTH: float = -5_566_247.740968115
45
+
46
+ SCALE_X: float = (X_EAST - X_WEST) / FULL_DISK_PX # m per pixel (col)
47
+ SCALE_Y: float = (Y_NORTH - Y_SOUTH) / FULL_DISK_PX # m per pixel (row)
48
+
49
+ CRS_PROJ_STRING: str = (
50
+ "+proj=geos +lon_0=0 +h=35785831 "
51
+ "+a=6378169 +b=6356583.8 +units=m"
52
+ )
53
+
54
+ @classmethod
55
+ def crs(cls) -> CRS:
56
+ return CRS.from_proj4(cls.CRS_PROJ_STRING)
57
+
58
+ def _latlon_to_fci_px(
59
+ lat: np.ndarray, lon: np.ndarray,
60
+ fci_patch_row0: int,
61
+ fci_patch_col0: int,
62
+ fci_patch_h: int = 128,
63
+ fci_patch_w: int = 128,
64
+ ) -> Tuple[np.ndarray, np.ndarray]:
65
+ """
66
+ Map (lat, lon) → fractional pixel coordinates inside the FCI patch.
67
+
68
+ Parameters
69
+ ----------
70
+ lat, lon : ndarray (H_out × W_out)
71
+ fci_patch_row0, fci_patch_col0 : int
72
+ Top-left corner of the extracted FCI patch in full-disk pixel coords.
73
+ (Row 0 = north edge of full disk.)
74
+ fci_patch_h, fci_patch_w : int
75
+ Size of the FCI patch (default 128×128).
76
+
77
+ Returns
78
+ -------
79
+ frac_row, frac_col : ndarray (H_out × W_out)
80
+ Fractional index into the FCI patch; NaN where outside or over the
81
+ Earth limb (geostationary projection is undefined beyond the disk).
82
+ """
83
+ geo = FCIGeometry
84
+ t = Transformer.from_crs(
85
+ CRS.from_epsg(4326),
86
+ CRS.from_proj4(geo.CRS_PROJ_STRING),
87
+ always_xy=True,
88
+ )
89
+ with warnings.catch_warnings():
90
+ warnings.simplefilter("ignore")
91
+ x_geos, y_geos = t.transform(lon, lat)
92
+
93
+ # Over-the-limb pixels become ±inf or nan from pyproj
94
+ limb_mask = ~np.isfinite(x_geos) | ~np.isfinite(y_geos)
95
+
96
+ # Convert geostationary metres → full-disk pixel index (0-based, float)
97
+ # Column: x increases eastward, col increases eastward
98
+ # Row: FCI scans south→north so row 0 = south edge; y increases northward
99
+ col_full = (x_geos - geo.X_WEST) / geo.SCALE_X - 0.5
100
+ row_full = (y_geos - geo.Y_SOUTH) / geo.SCALE_Y - 0.5
101
+
102
+ # Convert to patch-local fractional index
103
+ frac_col = col_full - fci_patch_col0
104
+ frac_row = row_full - fci_patch_row0
105
+
106
+ # Mask out-of-bounds and limb.
107
+ # For bilinear interpolation (order=1), scipy.map_coordinates returns NaN
108
+ # if the fractional index is strictly > size-1 (it would need to sample the
109
+ # out-of-bounds neighbour pixel). The safe range is exactly [0, size-1].
110
+ outside = (
111
+ limb_mask
112
+ | (frac_row < 0) | (frac_row > fci_patch_h - 1)
113
+ | (frac_col < 0) | (frac_col > fci_patch_w - 1)
114
+ )
115
+ frac_row[outside] = np.nan
116
+ frac_col[outside] = np.nan
117
+
118
+ return frac_row, frac_col
119
+
120
+ def _sample_array(
121
+ source: np.ndarray,
122
+ frac_row: np.ndarray,
123
+ frac_col: np.ndarray,
124
+ order: int = 1,
125
+ fill_value: float = np.nan,
126
+ ) -> np.ndarray:
127
+ """
128
+ Bilinear (order=1) sampling of *source* at fractional indices.
129
+
130
+ NaN coordinates produce fill_value in the output.
131
+ The output dtype is float32 regardless of the input dtype.
132
+ """
133
+ out = np.full(frac_row.shape, fill_value, dtype=np.float32)
134
+ valid = np.isfinite(frac_row) & np.isfinite(frac_col)
135
+ if not valid.any():
136
+ return out
137
+
138
+ out[valid] = map_coordinates(
139
+ source.astype(np.float32),
140
+ [frac_row[valid], frac_col[valid]],
141
+ order=order,
142
+ mode="constant",
143
+ cval=fill_value,
144
+ prefilter=False,
145
+ )
146
+ return out
preprocessing/legacy_sentinel.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Verbatim frozen Sentinel predictor functions; no training code."""
2
+ from pathlib import Path
3
+ from datetime import datetime,timedelta,timezone
4
+ import json,hashlib
5
+ import numpy as np
6
+ BANDS=['B01', 'B02', 'B03', 'B04', 'B05', 'B06', 'B07', 'B08', 'B8A', 'B09', 'B11', 'B12']
7
+
8
+ def load(path):
9
+ return json.loads(Path(path).read_text())
10
+
11
+ def sha(path):
12
+ result = hashlib.sha256()
13
+ with Path(path).open('rb') as stream:
14
+ for block in iter(lambda: stream.read(8 * 1024**2), b''):
15
+ result.update(block)
16
+ return result.hexdigest()
17
+
18
+ def parse(value):
19
+ return datetime.fromisoformat(value.replace('Z', '+00:00'))
20
+
21
+ def cutoff(day):
22
+ return parse(day + 'T00:00:00Z') + timedelta(days=1)
23
+
24
+ def read_sentinel(row):
25
+ folder = Path(row['folder'])
26
+ meta = load(folder/'metadata.json')
27
+ assert sha(folder/'metadata.json') == row['metadata_sha256'], 'Source changed after freeze'
28
+ assert meta['target_definition'] == 'NDVI_B8A_B04_20m'
29
+ assert meta['s2_band_order'] == BANDS and meta['s1_band_order'] == ['vv','vh']
30
+ filename = 'sentinel.npz' if meta.get('format') == 'same_day_observations_v1' else 'conditioning.npz'
31
+ with np.load(folder/filename, allow_pickle=False) as z:
32
+ a = {k:z[k] for k in z.files if k.startswith(('s1_','s2_'))}
33
+ target = parse(meta['target_time'])
34
+ limit = cutoff(meta['date'])
35
+ assert target < limit
36
+ for sensor, name, channels in [('s1','s1_source_values',2),('s2','s2_reflectance',12)]:
37
+ history = [h for h in meta['history'] if h['sensor'] == sensor.upper()]
38
+ value = a[name].astype(np.float32)
39
+ valid = a[sensor+'_valid'].astype(bool) & np.isfinite(value)
40
+ ages = a[sensor+'_days_before_target'].astype(np.float32)
41
+ assert value.shape == valid.shape == (len(history),channels,256,256)
42
+ expected = np.array([(target-parse(h['time'])).total_seconds()/86400 for h in history])
43
+ assert np.allclose(ages,expected,atol=1e-4) and np.all(ages > 0)
44
+ for h in history:
45
+ assert h['id'] != meta['target_item'] and parse(h['time']) < target
46
+ if sensor == 's2':
47
+ assert parse(h['time']).date() < target.date(), 'Same-day S2 forbidden'
48
+ produced = (h.get('radiometry',{}).get('generation_time') if sensor=='s2'
49
+ else h.get('properties',{}).get('s1:processing_datetime'))
50
+ assert not produced or parse(produced) < limit
51
+ if sensor == 's1':
52
+ valid &= value > 0
53
+ value = (10*np.log10(np.where(valid,value,1).astype(np.float64))).astype(np.float32)
54
+ a[sensor] = np.where(valid,value,0)
55
+ a[sensor+'_mask'] = valid
56
+ a[sensor+'_age'] = ages
57
+ scl, scm = a['s2_scl'], a['s2_scl_valid'].astype(bool)
58
+ assert scl.shape == scm.shape == (len(a['s2']),256,256)
59
+ a['s2_quality'] = np.stack([(scl==i)&scm for i in range(12)],axis=1).astype(np.float32)
60
+ a['s2_quality_valid'] = scm[:,None].astype(np.float32)
61
+ return a, meta
62
+
63
+ def predictors(row, stats):
64
+ """Only Sentinel observations, date and train-only constants enter here."""
65
+ a,meta=read_sentinel(row)
66
+ ages=a['s2_age']; red=a['s2'][:,3]; nir=a['s2'][:,8]
67
+ clear=a['s2_quality'][:,[4,5,6]].sum(1)>0
68
+ good=clear&a['s2_mask'][:,3]&a['s2_mask'][:,8]&(red>=0)&(nir>=0)&(red+nir>1e-6)
69
+ ndvi=np.divide(nir-red,nir+red,out=np.zeros_like(red),where=good)
70
+ last=np.full((256,256),stats['training_target_mean'],np.float32)
71
+ last_age=np.zeros_like(last); taken=np.zeros_like(last,bool)
72
+ for i in np.argsort(ages,kind='stable'):
73
+ use=good[i]&~taken
74
+ last[use]=ndvi[i][use]; last_age[use]=ages[i]/30; taken|=good[i]
75
+ anchor=np.stack([last,taken,last_age]).astype(np.float32)
76
+ target=parse(meta['target_time'])
77
+ phase=2*np.pi*((target.timetuple().tm_yday-1)+target.hour/24)/365.25
78
+ calendar=np.broadcast_to(np.array([np.sin(phase),np.cos(phase),0],np.float32)[:,None,None],(3,256,256)).copy()
79
+ p={k:a[k] for k in ('s1','s1_mask','s1_age','s2','s2_mask','s2_age','s2_quality','s2_quality_valid')}
80
+ for sensor in ('s1','s2'):
81
+ mean=np.array(stats[sensor]['mean'],np.float32)[None,:,None,None]
82
+ std=np.array(stats[sensor]['std'],np.float32)[None,:,None,None]
83
+ p[sensor]=np.where(p[sensor+'_mask'],(p[sensor]-mean)/std,0).astype(np.float32)
84
+ p.update(anchor=anchor,calendar=calendar,modis=np.zeros((7,256,256),np.float32),
85
+ cutoff_offset=np.array([(cutoff(meta['date'])-target).total_seconds()/86400],np.float32))
86
+ return p,last[None],taken[None]
preprocessing/manifest.example.json ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "id": "hungary_central_x-1_y-1_2025-06-02",
3
+ "date": "2025-06-02",
4
+ "target_time": "2025-06-02T09:40:51.025000Z",
5
+ "target_item": "S2C_MSIL2A_20250602T094051_R036_T34TDS_20250602T132716",
6
+ "geometry": {
7
+ "crs": "EPSG:32634",
8
+ "transform": [
9
+ 20,
10
+ 0,
11
+ 409414.68790106743,
12
+ 0,
13
+ -20,
14
+ 5196209.347746108
15
+ ],
16
+ "shape": [
17
+ 256,
18
+ 256
19
+ ]
20
+ },
21
+ "history": [
22
+ {
23
+ "sensor": "S1",
24
+ "id": "S1C_IW_GRDH_1SDV_20250428T163320_20250428T163345_002096_rtc",
25
+ "time": "2025-04-28T16:33:32.520318Z",
26
+ "assets": {
27
+ "vv": "raw/sentinel/S1C_IW_GRDH_1SDV_20250428T163320_20250428T163345_002096_rtc/vv.tif",
28
+ "vh": "raw/sentinel/S1C_IW_GRDH_1SDV_20250428T163320_20250428T163345_002096_rtc/vh.tif"
29
+ },
30
+ "properties": {
31
+ "sat:orbit_state": "ascending",
32
+ "sat:relative_orbit": 175,
33
+ "s1:processing_datetime": "2025-04-28T17:13:10.000000Z"
34
+ }
35
+ },
36
+ {
37
+ "sensor": "S1",
38
+ "id": "S1A_IW_GRDH_1SDV_20250504T163419_20250504T163444_059047_rtc",
39
+ "time": "2025-05-04T16:34:31.635254Z",
40
+ "assets": {
41
+ "vv": "raw/sentinel/S1A_IW_GRDH_1SDV_20250504T163419_20250504T163444_059047_rtc/vv.tif",
42
+ "vh": "raw/sentinel/S1A_IW_GRDH_1SDV_20250504T163419_20250504T163444_059047_rtc/vh.tif"
43
+ },
44
+ "properties": {
45
+ "sat:orbit_state": "ascending",
46
+ "sat:relative_orbit": 175,
47
+ "s1:processing_datetime": "2025-05-04T17:20:07.000000Z"
48
+ }
49
+ },
50
+ {
51
+ "sensor": "S1",
52
+ "id": "S1C_IW_GRDH_1SDV_20250510T163320_20250510T163345_002271_rtc",
53
+ "time": "2025-05-10T16:33:33.055971Z",
54
+ "assets": {
55
+ "vv": "raw/sentinel/S1C_IW_GRDH_1SDV_20250510T163320_20250510T163345_002271_rtc/vv.tif",
56
+ "vh": "raw/sentinel/S1C_IW_GRDH_1SDV_20250510T163320_20250510T163345_002271_rtc/vh.tif"
57
+ },
58
+ "properties": {
59
+ "sat:orbit_state": "ascending",
60
+ "sat:relative_orbit": 175,
61
+ "s1:processing_datetime": "2025-05-10T17:35:12.000000Z"
62
+ }
63
+ },
64
+ {
65
+ "sensor": "S1",
66
+ "id": "S1A_IW_GRDH_1SDV_20250516T163418_20250516T163443_059222_07594D_rtc",
67
+ "time": "2025-05-16T16:34:31.277375Z",
68
+ "assets": {
69
+ "vv": "raw/sentinel/S1A_IW_GRDH_1SDV_20250516T163418_20250516T163443_059222_07594D_rtc/vv.tif",
70
+ "vh": "raw/sentinel/S1A_IW_GRDH_1SDV_20250516T163418_20250516T163443_059222_07594D_rtc/vh.tif"
71
+ },
72
+ "properties": {
73
+ "sat:orbit_state": "ascending",
74
+ "sat:relative_orbit": 175
75
+ }
76
+ },
77
+ {
78
+ "sensor": "S1",
79
+ "id": "S1C_IW_GRDH_1SDV_20250522T163321_20250522T163346_002446_rtc",
80
+ "time": "2025-05-22T16:33:34.252875Z",
81
+ "assets": {
82
+ "vv": "raw/sentinel/S1C_IW_GRDH_1SDV_20250522T163321_20250522T163346_002446_rtc/vv.tif",
83
+ "vh": "raw/sentinel/S1C_IW_GRDH_1SDV_20250522T163321_20250522T163346_002446_rtc/vh.tif"
84
+ },
85
+ "properties": {
86
+ "sat:orbit_state": "ascending",
87
+ "sat:relative_orbit": 175,
88
+ "s1:processing_datetime": "2025-05-22T17:50:32.000000Z"
89
+ }
90
+ },
91
+ {
92
+ "sensor": "S1",
93
+ "id": "S1A_IW_GRDH_1SDV_20250528T163418_20250528T163443_059397_075F64_rtc",
94
+ "time": "2025-05-28T16:34:30.884823Z",
95
+ "assets": {
96
+ "vv": "raw/sentinel/S1A_IW_GRDH_1SDV_20250528T163418_20250528T163443_059397_075F64_rtc/vv.tif",
97
+ "vh": "raw/sentinel/S1A_IW_GRDH_1SDV_20250528T163418_20250528T163443_059397_075F64_rtc/vh.tif"
98
+ },
99
+ "properties": {
100
+ "sat:orbit_state": "ascending",
101
+ "sat:relative_orbit": 175
102
+ }
103
+ },
104
+ {
105
+ "sensor": "S2",
106
+ "id": "S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917",
107
+ "time": "2025-05-05T09:40:41.024000Z",
108
+ "assets": {
109
+ "B01": "raw/sentinel/S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917/B01.tif",
110
+ "B02": "raw/sentinel/S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917/B02.tif",
111
+ "B03": "raw/sentinel/S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917/B03.tif",
112
+ "B04": "raw/sentinel/S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917/B04.tif",
113
+ "B05": "raw/sentinel/S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917/B05.tif",
114
+ "B06": "raw/sentinel/S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917/B06.tif",
115
+ "B07": "raw/sentinel/S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917/B07.tif",
116
+ "B08": "raw/sentinel/S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917/B08.tif",
117
+ "B8A": "raw/sentinel/S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917/B8A.tif",
118
+ "B09": "raw/sentinel/S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917/B09.tif",
119
+ "B11": "raw/sentinel/S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917/B11.tif",
120
+ "B12": "raw/sentinel/S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917/B12.tif",
121
+ "SCL": "raw/sentinel/S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917/SCL.tif"
122
+ },
123
+ "product_metadata_xml": "raw/sentinel/S2A_MSIL2A_20250505T094041_R036_T34TDS_20250506T015917/product-metadata.xml"
124
+ },
125
+ {
126
+ "sensor": "S2",
127
+ "id": "S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702",
128
+ "time": "2025-05-08T09:40:29.024000Z",
129
+ "assets": {
130
+ "B01": "raw/sentinel/S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702/B01.tif",
131
+ "B02": "raw/sentinel/S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702/B02.tif",
132
+ "B03": "raw/sentinel/S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702/B03.tif",
133
+ "B04": "raw/sentinel/S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702/B04.tif",
134
+ "B05": "raw/sentinel/S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702/B05.tif",
135
+ "B06": "raw/sentinel/S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702/B06.tif",
136
+ "B07": "raw/sentinel/S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702/B07.tif",
137
+ "B08": "raw/sentinel/S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702/B08.tif",
138
+ "B8A": "raw/sentinel/S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702/B8A.tif",
139
+ "B09": "raw/sentinel/S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702/B09.tif",
140
+ "B11": "raw/sentinel/S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702/B11.tif",
141
+ "B12": "raw/sentinel/S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702/B12.tif",
142
+ "SCL": "raw/sentinel/S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702/SCL.tif"
143
+ },
144
+ "product_metadata_xml": "raw/sentinel/S2B_MSIL2A_20250508T094029_R036_T34TDS_20250508T115702/product-metadata.xml"
145
+ },
146
+ {
147
+ "sensor": "S2",
148
+ "id": "S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412",
149
+ "time": "2025-05-13T09:40:51.025000Z",
150
+ "assets": {
151
+ "B01": "raw/sentinel/S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412/B01.tif",
152
+ "B02": "raw/sentinel/S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412/B02.tif",
153
+ "B03": "raw/sentinel/S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412/B03.tif",
154
+ "B04": "raw/sentinel/S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412/B04.tif",
155
+ "B05": "raw/sentinel/S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412/B05.tif",
156
+ "B06": "raw/sentinel/S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412/B06.tif",
157
+ "B07": "raw/sentinel/S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412/B07.tif",
158
+ "B08": "raw/sentinel/S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412/B08.tif",
159
+ "B8A": "raw/sentinel/S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412/B8A.tif",
160
+ "B09": "raw/sentinel/S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412/B09.tif",
161
+ "B11": "raw/sentinel/S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412/B11.tif",
162
+ "B12": "raw/sentinel/S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412/B12.tif",
163
+ "SCL": "raw/sentinel/S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412/SCL.tif"
164
+ },
165
+ "product_metadata_xml": "raw/sentinel/S2C_MSIL2A_20250513T094051_R036_T34TDS_20250513T122412/product-metadata.xml"
166
+ },
167
+ {
168
+ "sensor": "S2",
169
+ "id": "S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414",
170
+ "time": "2025-05-15T09:41:21.024000Z",
171
+ "assets": {
172
+ "B01": "raw/sentinel/S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414/B01.tif",
173
+ "B02": "raw/sentinel/S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414/B02.tif",
174
+ "B03": "raw/sentinel/S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414/B03.tif",
175
+ "B04": "raw/sentinel/S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414/B04.tif",
176
+ "B05": "raw/sentinel/S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414/B05.tif",
177
+ "B06": "raw/sentinel/S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414/B06.tif",
178
+ "B07": "raw/sentinel/S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414/B07.tif",
179
+ "B08": "raw/sentinel/S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414/B08.tif",
180
+ "B8A": "raw/sentinel/S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414/B8A.tif",
181
+ "B09": "raw/sentinel/S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414/B09.tif",
182
+ "B11": "raw/sentinel/S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414/B11.tif",
183
+ "B12": "raw/sentinel/S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414/B12.tif",
184
+ "SCL": "raw/sentinel/S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414/SCL.tif"
185
+ },
186
+ "product_metadata_xml": "raw/sentinel/S2A_MSIL2A_20250515T094121_R036_T34TDS_20250515T120414/product-metadata.xml"
187
+ },
188
+ {
189
+ "sensor": "S2",
190
+ "id": "S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812",
191
+ "time": "2025-05-18T09:40:29.024000Z",
192
+ "assets": {
193
+ "B01": "raw/sentinel/S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812/B01.tif",
194
+ "B02": "raw/sentinel/S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812/B02.tif",
195
+ "B03": "raw/sentinel/S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812/B03.tif",
196
+ "B04": "raw/sentinel/S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812/B04.tif",
197
+ "B05": "raw/sentinel/S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812/B05.tif",
198
+ "B06": "raw/sentinel/S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812/B06.tif",
199
+ "B07": "raw/sentinel/S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812/B07.tif",
200
+ "B08": "raw/sentinel/S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812/B08.tif",
201
+ "B8A": "raw/sentinel/S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812/B8A.tif",
202
+ "B09": "raw/sentinel/S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812/B09.tif",
203
+ "B11": "raw/sentinel/S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812/B11.tif",
204
+ "B12": "raw/sentinel/S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812/B12.tif",
205
+ "SCL": "raw/sentinel/S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812/SCL.tif"
206
+ },
207
+ "product_metadata_xml": "raw/sentinel/S2B_MSIL2A_20250518T094029_R036_T34TDS_20250518T115812/product-metadata.xml"
208
+ },
209
+ {
210
+ "sensor": "S2",
211
+ "id": "S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908",
212
+ "time": "2025-05-23T09:40:51.025000Z",
213
+ "assets": {
214
+ "B01": "raw/sentinel/S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908/B01.tif",
215
+ "B02": "raw/sentinel/S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908/B02.tif",
216
+ "B03": "raw/sentinel/S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908/B03.tif",
217
+ "B04": "raw/sentinel/S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908/B04.tif",
218
+ "B05": "raw/sentinel/S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908/B05.tif",
219
+ "B06": "raw/sentinel/S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908/B06.tif",
220
+ "B07": "raw/sentinel/S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908/B07.tif",
221
+ "B08": "raw/sentinel/S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908/B08.tif",
222
+ "B8A": "raw/sentinel/S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908/B8A.tif",
223
+ "B09": "raw/sentinel/S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908/B09.tif",
224
+ "B11": "raw/sentinel/S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908/B11.tif",
225
+ "B12": "raw/sentinel/S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908/B12.tif",
226
+ "SCL": "raw/sentinel/S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908/SCL.tif"
227
+ },
228
+ "product_metadata_xml": "raw/sentinel/S2C_MSIL2A_20250523T094051_R036_T34TDS_20250523T122908/product-metadata.xml"
229
+ },
230
+ {
231
+ "sensor": "S2",
232
+ "id": "S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714",
233
+ "time": "2025-05-25T09:40:51.024000Z",
234
+ "assets": {
235
+ "B01": "raw/sentinel/S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714/B01.tif",
236
+ "B02": "raw/sentinel/S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714/B02.tif",
237
+ "B03": "raw/sentinel/S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714/B03.tif",
238
+ "B04": "raw/sentinel/S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714/B04.tif",
239
+ "B05": "raw/sentinel/S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714/B05.tif",
240
+ "B06": "raw/sentinel/S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714/B06.tif",
241
+ "B07": "raw/sentinel/S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714/B07.tif",
242
+ "B08": "raw/sentinel/S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714/B08.tif",
243
+ "B8A": "raw/sentinel/S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714/B8A.tif",
244
+ "B09": "raw/sentinel/S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714/B09.tif",
245
+ "B11": "raw/sentinel/S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714/B11.tif",
246
+ "B12": "raw/sentinel/S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714/B12.tif",
247
+ "SCL": "raw/sentinel/S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714/SCL.tif"
248
+ },
249
+ "product_metadata_xml": "raw/sentinel/S2A_MSIL2A_20250525T094051_R036_T34TDS_20250525T120714/product-metadata.xml"
250
+ },
251
+ {
252
+ "sensor": "S2",
253
+ "id": "S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349",
254
+ "time": "2025-05-28T09:40:29.024000Z",
255
+ "assets": {
256
+ "B01": "raw/sentinel/S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349/B01.tif",
257
+ "B02": "raw/sentinel/S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349/B02.tif",
258
+ "B03": "raw/sentinel/S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349/B03.tif",
259
+ "B04": "raw/sentinel/S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349/B04.tif",
260
+ "B05": "raw/sentinel/S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349/B05.tif",
261
+ "B06": "raw/sentinel/S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349/B06.tif",
262
+ "B07": "raw/sentinel/S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349/B07.tif",
263
+ "B08": "raw/sentinel/S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349/B08.tif",
264
+ "B8A": "raw/sentinel/S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349/B8A.tif",
265
+ "B09": "raw/sentinel/S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349/B09.tif",
266
+ "B11": "raw/sentinel/S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349/B11.tif",
267
+ "B12": "raw/sentinel/S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349/B12.tif",
268
+ "SCL": "raw/sentinel/S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349/SCL.tif"
269
+ },
270
+ "product_metadata_xml": "raw/sentinel/S2B_MSIL2A_20250528T094029_R036_T34TDS_20250528T115349/product-metadata.xml"
271
+ }
272
+ ],
273
+ "modis": {
274
+ "gq": "raw/modis/MOD09GQ.A2025153.h19v04.061.2025157154133.hdf",
275
+ "ga": "raw/modis/MOD09GA.A2025153.h19v04.061.2025157154133.hdf"
276
+ },
277
+ "mtg": [
278
+ {
279
+ "time": "2025-06-02T10:00:00+00:00",
280
+ "candidates": [
281
+ {
282
+ "patch_npz": "raw/mtg/2025-06-02T100000_52U_15R.npz"
283
+ },
284
+ {
285
+ "patch_npz": "raw/mtg/2025-06-02T100000_53U_15R.npz"
286
+ },
287
+ {
288
+ "patch_npz": "raw/mtg/2025-06-02T100000_52U_16R.npz"
289
+ }
290
+ ]
291
+ },
292
+ {
293
+ "time": "2025-06-02T11:00:00+00:00",
294
+ "candidates": [
295
+ {
296
+ "patch_npz": "raw/mtg/2025-06-02T110000_52U_15R.npz"
297
+ },
298
+ {
299
+ "patch_npz": "raw/mtg/2025-06-02T110000_53U_15R.npz"
300
+ },
301
+ {
302
+ "patch_npz": "raw/mtg/2025-06-02T110000_52U_16R.npz"
303
+ }
304
+ ]
305
+ },
306
+ {
307
+ "time": "2025-06-02T12:00:00+00:00",
308
+ "candidates": [
309
+ {
310
+ "patch_npz": "raw/mtg/2025-06-02T120000_52U_15R.npz"
311
+ },
312
+ {
313
+ "patch_npz": "raw/mtg/2025-06-02T120000_53U_15R.npz"
314
+ },
315
+ {
316
+ "patch_npz": "raw/mtg/2025-06-02T120000_52U_16R.npz"
317
+ }
318
+ ]
319
+ },
320
+ {
321
+ "time": "2025-06-02T13:00:00+00:00",
322
+ "candidates": [
323
+ {
324
+ "patch_npz": "raw/mtg/2025-06-02T130000_52U_15R.npz"
325
+ },
326
+ {
327
+ "patch_npz": "raw/mtg/2025-06-02T130000_53U_15R.npz"
328
+ },
329
+ {
330
+ "patch_npz": "raw/mtg/2025-06-02T130000_52U_16R.npz"
331
+ }
332
+ ]
333
+ },
334
+ {
335
+ "time": "2025-06-02T14:00:00+00:00",
336
+ "candidates": [
337
+ {
338
+ "patch_npz": "raw/mtg/2025-06-02T140000_52U_15R.npz"
339
+ },
340
+ {
341
+ "patch_npz": "raw/mtg/2025-06-02T140000_53U_15R.npz"
342
+ },
343
+ {
344
+ "patch_npz": "raw/mtg/2025-06-02T140000_52U_16R.npz"
345
+ }
346
+ ]
347
+ }
348
+ ],
349
+ "landcover": {
350
+ "path": "raw/landcover.tif"
351
+ }
352
+ }
preprocessing/raw.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Local raw assets -> aligned observations -> released MODIS250 input tensors.
2
+
3
+ Pass explicitly selected acquisitions and exact geometry in a JSON manifest.
4
+ This module performs no catalogue search or alternative-source selection.
5
+ """
6
+ from pathlib import Path
7
+ from datetime import timedelta
8
+ import argparse,hashlib,json,re,xml.etree.ElementTree as ET
9
+ import numpy as np
10
+ from affine import Affine
11
+ from pyproj import Transformer
12
+ import rasterio
13
+ from rasterio.vrt import WarpedVRT
14
+ from rasterio.enums import Resampling
15
+ from .legacy_sentinel import BANDS,parse,cutoff,sha
16
+ from .assemble import assemble,write
17
+ from .fci import _latlon_to_fci_px,_sample_array
18
+
19
+ FULL=['B01','B02','B03','B04','B05','B06','B07','B08','B8A','B09','B10','B11','B12']
20
+ RED,NIR='sur_refl_b01_1','sur_refl_b02_1'
21
+
22
+ def read_band(path,band,geometry):
23
+ mode=Resampling.average if band in ['B02','B03','B04','B08'] else Resampling.nearest
24
+ with rasterio.open(str(path)) as source:
25
+ with WarpedVRT(source,crs=geometry['crs'],transform=Affine(*geometry['transform']),width=256,height=256,resampling=mode,**({'dtype':'float32'} if mode==Resampling.average else {})) as vrt:
26
+ a=vrt.read(1,masked=True)
27
+ return a.filled(0),(~np.ma.getmaskarray(a))&np.isfinite(a.filled(0))
28
+
29
+ def radiometry_xml(path):
30
+ raw=Path(path).read_bytes();root=ET.fromstring(raw);offsets={};quantification=None;generation=None
31
+ for node in root.iter():
32
+ tag=node.tag.rsplit('}',1)[-1]
33
+ if tag=='BOA_QUANTIFICATION_VALUE':quantification=float(node.text)
34
+ if tag=='BOA_ADD_OFFSET':offsets[node.attrib['band_id']]=float(node.text)
35
+ if tag=='GENERATION_TIME':generation=node.text
36
+ if not quantification or not offsets:raise ValueError('Authoritative S2 BOA quantification and offsets are required')
37
+ return dict(quantification=quantification,offsets=offsets,generation_time=generation,xml_sha256=hashlib.sha256(raw).hexdigest())
38
+
39
+ def optical(acquisition,geometry,resolve):
40
+ radiometry=radiometry_xml(resolve(acquisition['product_metadata_xml'])) if 'product_metadata_xml' in acquisition else acquisition['radiometry']
41
+ values=[];masks=[]
42
+ for band in BANDS:
43
+ a,valid=read_band(resolve(acquisition['assets'][band]),band,geometry);valid &= (a!=0)&np.isfinite(a)
44
+ v=(a.astype(np.float32)+radiometry['offsets'][str(FULL.index(band))])/radiometry['quantification']
45
+ values.append(np.where(valid,v,0));masks.append(valid)
46
+ scl,valid=read_band(resolve(acquisition['assets']['SCL']),'SCL',geometry)
47
+ return np.stack(values),np.stack(masks),scl,valid,radiometry
48
+
49
+ def grid_metadata(hdf,name):
50
+ text=''.join(str(v).rstrip('\x00') for k,v in hdf.attributes().items() if k.startswith('StructMetadata'))
51
+ match=re.search(r'GROUP=GRID_\d+\s+GridName="'+re.escape(name)+r'"(.*?)END_GROUP=GRID_\d+',text,re.S)
52
+ if not match:raise ValueError('Missing original HDF grid: '+name)
53
+ block=match.group(1);width=int(re.search(r'XDim=(\d+)',block)[1]);height=int(re.search(r'YDim=(\d+)',block)[1])
54
+ pair=lambda key:tuple(map(float,re.search(key+r'=\(([^)]+)\)',block)[1].split(',')))
55
+ left,top=pair('UpperLeftPointMtrs');right,bottom=pair('LowerRightMtrs');radius=pair('ProjParams')[0]
56
+ return Affine((right-left)/width,0,left,0,(bottom-top)/height,top),(height,width),f'+proj=sinu +R={radius} +units=m +no_defs'
57
+
58
+ def crop(hdf,field,window):
59
+ r0,r1,c0,c1=window;ds=hdf.select(field)
60
+ try:return ds[r0:r1,c0:c1],ds.attributes()
61
+ finally:ds.endaccess()
62
+
63
+ def window(rr,cc):return int(rr.min()),int(rr.max()+1),int(cc.min()),int(cc.max()+1)
64
+
65
+ def strict_mask(qa,nobs):
66
+ clear=(qa!=65535)&(nobs>0)&((qa&3)==0)&(((qa>>8)&3)==0)
67
+ for bit in [2,10,12,13,15]:clear &= ((qa>>bit)&1)==0
68
+ return clear
69
+
70
+ def reflectance(hdf,rr,cc,window_):
71
+ valid=np.ones(rr.shape,bool);values=[]
72
+ for band in [RED,NIR]:
73
+ a,attrs=crop(hdf,band,window_);a=a[rr,cc];lo,hi=attrs['valid_range'];valid &= (a!=attrs['_FillValue'])&(a>=lo)&(a<=hi)
74
+ values.append((a.astype(np.float32)-float(attrs.get('add_offset',0)))*float(attrs['scale_factor']))
75
+ return np.stack(values),valid
76
+
77
+ def modis_pair(gq_path,ga_path,geometry):
78
+ from pyhdf.SD import SD,SDC
79
+ gq=SD(str(gq_path),SDC.READ);ga=SD(str(ga_path),SDC.READ)
80
+ try:
81
+ native,shape,crs=grid_metadata(gq,'MODIS_Grid_2D');assert shape==(4800,4800)
82
+ row,col=np.indices((256,256));x,y=Affine(*geometry['transform'])*(col+.5,row+.5);x,y=Transformer.from_crs(geometry['crs'],crs,always_xy=True).transform(x,y)
83
+ c,r=(~native)*(x,y);rr,cc=np.floor(r).astype(int),np.floor(c).astype(int)
84
+ assert ((rr>=0)&(rr<4800)&(cc>=0)&(cc<4800)).all(),'Use one containing MODIS tile'
85
+ w=window(rr,cc);local_r,local_c=rr-w[0],cc-w[2]
86
+ # QA is first mapped to each native GQ pixel centre, then to output pixels.
87
+ gy,gx=np.indices((w[1]-w[0],w[3]-w[2]));ix,iy=native*(gx+w[2]+.5,gy+w[0]+.5)
88
+ qa_grid,qa_shape,qa_crs=grid_metadata(ga,'MODIS_Grid_1km_2D');assert qa_shape==(1200,1200) and qa_crs==crs
89
+ qc,qr=(~qa_grid)*(ix,iy);qr,qc=np.floor(qr).astype(int),np.floor(qc).astype(int);assert ((qr>=0)&(qr<1200)&(qc>=0)&(qc<1200)).all()
90
+ qw=window(qr,qc);state,_=crop(ga,'state_1km_1',qw);nobsqa,_=crop(ga,'num_observations_1km',qw);clear=strict_mask(state[qr-qw[0],qc-qw[2]].astype(np.uint16),nobsqa[qr-qw[0],qc-qw[2]])[local_r,local_c]
91
+ r250,valid250=reflectance(gq,local_r,local_c,w);q250,_=crop(gq,'QC_250m_1',w);nobs,_=crop(gq,'num_observations',w);q250=q250[local_r,local_c].astype(np.uint16)
92
+ good250=valid250&(nobs[local_r,local_c]>0)&(r250[0]>=0)&(r250[1]>=0)&(r250.sum(0)>1e-6)&((q250&3)==0)&(((q250>>4)&255)==0)&clear
93
+ grid500,shape500,crs500=grid_metadata(ga,'MODIS_Grid_500m_2D');assert shape500==(2400,2400) and crs500==crs
94
+ c,r=(~grid500)*(x,y);rr,cc=np.floor(r).astype(int),np.floor(c).astype(int);assert ((rr>=0)&(rr<2400)&(cc>=0)&(cc<2400)).all();w=window(rr,cc);rr,cc=rr-w[0],cc-w[2]
95
+ r500,valid500=reflectance(ga,rr,cc,w);q500,_=crop(ga,'QC_500m_1',w);q500=q500[rr,cc]
96
+ common=good250&valid500&clear&((q500&3)==0)&(((q500>>2)&255)==0)
97
+ return dict(reflectance_250=np.where(common,r250,0),reflectance_500=np.where(common,r500,0),common_20m_mask=common)
98
+ finally:gq.end();ga.end()
99
+
100
+ def context(manifest,geometry,resolve):
101
+ r,c=np.indices((256,256),dtype=np.float64);x,y=Affine(*geometry['transform'])*(c+.5,r+.5);lon,lat=Transformer.from_crs(geometry['crs'],4326,always_xy=True).transform(x,y)
102
+ geo=np.zeros((5,3,256,256),np.float32);ages=np.zeros(5,np.float32);times=np.full(5,'',dtype='U40');slot=0;seen=set()
103
+ for observation in sorted(manifest['mtg'],key=lambda v:parse(v['time'])):
104
+ stamp=observation['time'];observed=parse(stamp);assert stamp[:10]==manifest['date'] and observed<cutoff(manifest['date'])
105
+ if observed in seen:raise ValueError('Duplicate MTG observation timestamp')
106
+ seen.add(observed);best=None
107
+ candidates=observation['candidates']
108
+ if len(candidates)>3:raise ValueError('Supply the three nearest source grids in the frozen rank order')
109
+ for candidate in candidates:
110
+ with np.load(resolve(candidate['patch_npz']),allow_pickle=False) as z:
111
+ origin=z['origin'] if 'origin' in z else [candidate['origin_row'],candidate['origin_col']]
112
+ rr,cc=_latlon_to_fci_px(lat,lon,int(origin[0]),int(origin[1]));a=np.stack([_sample_array(z[b].astype(np.float32),rr,cc) for b in ['vis_06','vis_08']])
113
+ valid=np.isfinite(a)&(a>=2);support=valid.all(0).mean()
114
+ if best is None or support>best[0]:best=(support,a,valid)
115
+ if support>.99:break
116
+ if best is None or best[0]<.1:continue
117
+ _,a,valid=best;values=np.where(valid,a,0).astype(np.float32);geo[slot,:2]=np.clip(values/100,0,3)*valid;geo[slot,2]=valid.all(0);ages[slot]=(cutoff(manifest['date'])-observed).total_seconds()/86400;times[slot]=stamp;slot+=1
118
+ if slot==5:break
119
+ lc,lcv=read_band(resolve(manifest['landcover']['path']),'LC_Type1',geometry);lcv &= np.isin(lc,np.arange(1,18))
120
+ return dict(geo=geo,geo_age=ages,geo_times=times,landcover=lc,landcover_valid=lcv)
121
+
122
+ def prepare(manifest_path,destination):
123
+ manifest_path=Path(manifest_path);m=json.loads(manifest_path.read_text());destination=Path(destination);destination.mkdir(parents=True,exist_ok=False)
124
+ def resolve(path):return path if '://' in path else str((manifest_path.parent/Path(path)).resolve())
125
+ geometry=m['geometry'];assert geometry['shape']==[256,256];target=parse(m['target_time']);assert target.date().isoformat()==m['date'];arrays={};history=[]
126
+ for sensor in ['S1','S2']:
127
+ observations=[v for v in m['history'] if v['sensor']==sensor];assert observations,'Supply actual prior observations, including cloudy S2'
128
+ values=[];valids=[];scls=[];sclvalid=[];ages=[]
129
+ for item in observations:
130
+ stamp=parse(item['time']);assert stamp<target and item['id']!=m['target_item']
131
+ record={k:item[k] for k in ['sensor','id','time']}
132
+ if sensor=='S2':
133
+ assert stamp.date()<target.date();value,valid,scl,scm,rad=optical(item,geometry,resolve);scls.append(scl);sclvalid.append(scm);record['radiometry']=rad
134
+ assert not rad.get('generation_time') or parse(rad['generation_time'])<cutoff(m['date'])
135
+ else:
136
+ channels=[read_band(resolve(item['assets'][band]),band,geometry) for band in ['vv','vh']];value=np.stack([v[0] for v in channels]).astype(np.float32);valid=np.stack([v[1] for v in channels])&np.isfinite(value)&(value>0);value=np.where(valid,value,0);record['properties']=item.get('properties',{});produced=record['properties'].get('s1:processing_datetime');assert not produced or parse(produced)<cutoff(m['date'])
137
+ values.append(value);valids.append(valid);ages.append((target-stamp).total_seconds()/86400);history.append(record)
138
+ name=sensor.lower();arrays[name+('_source_values' if sensor=='S1' else '_reflectance')]=np.stack(values);arrays[name+'_valid']=np.stack(valids);arrays[name+'_days_before_target']=np.asarray(ages,np.float32)
139
+ if sensor=='S2':arrays.update(s2_scl=np.stack(scls),s2_scl_valid=np.stack(sclvalid))
140
+ write(destination/'sentinel.npz',arrays);write(destination/'context.npz',context(m,geometry,resolve))
141
+ modis=m['modis'];gq,ga=Path(resolve(modis['gq'])),Path(resolve(modis['ga']));assert gq.name.split('.')[1:]==ga.name.split('.')[1:],'Use the same date, tile, collection and production of GQ and GA';assert gq.name.split('.')[1]==target.strftime('A%Y%j')
142
+ write(destination/'paired_modis.npz',modis_pair(gq,ga,geometry))
143
+ meta={k:m[k] for k in ['id','date','target_time','target_item','geometry']};meta.update(history=history,s1_band_order=['vv','vh'],s2_band_order=BANDS,target_definition='NDVI_B8A_B04_20m',format='same_day_observations_v1',modis_gq=gq.name,modis_ga=ga.name,strict_operational_replay_qualified=False,sha256={n:sha(destination/n) for n in ['sentinel.npz','context.npz','paired_modis.npz']})
144
+ (destination/'metadata.json').write_text(json.dumps(meta,indent=2)+'\n');return destination
145
+
146
+ def main():
147
+ ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--manifest',type=Path,required=True);ap.add_argument('--aligned-output',type=Path,required=True);ap.add_argument('--output',type=Path,required=True);ap.add_argument('--normalization',type=Path,default=Path(__file__).resolve().parents[1]/'normalization.json');args=ap.parse_args();prepare(args.manifest,args.aligned_output);arrays,_=assemble(args.aligned_output,args.normalization);write(args.output,arrays);print('Prepared raw assets and wrote',args.output)
148
+ if __name__=='__main__':main()
preprocessing/recipe.json ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "release": "modis250_v1",
3
+ "output_grid": {
4
+ "shape": [
5
+ 256,
6
+ 256
7
+ ],
8
+ "spacing_m": 20,
9
+ "crs_and_affine": "Explicit per-scene geometry; no inferred tile bounding box"
10
+ },
11
+ "s1": {
12
+ "source": "Sentinel-1 RTC linear power",
13
+ "bands": [
14
+ "vv",
15
+ "vh"
16
+ ],
17
+ "resampling": "nearest",
18
+ "validity": "Source mask, finite, positive",
19
+ "transform": "10*log10 in float64, cast to float32; once only",
20
+ "normalization": "Released normalization.json; invalid values zero after normalization"
21
+ },
22
+ "s2": {
23
+ "source": "Sentinel-2 L2A DN plus authoritative BOA metadata",
24
+ "bands": [
25
+ "B01",
26
+ "B02",
27
+ "B03",
28
+ "B04",
29
+ "B05",
30
+ "B06",
31
+ "B07",
32
+ "B08",
33
+ "B8A",
34
+ "B09",
35
+ "B11",
36
+ "B12"
37
+ ],
38
+ "average_resampling": [
39
+ "B02",
40
+ "B03",
41
+ "B04",
42
+ "B08"
43
+ ],
44
+ "nearest_resampling": "All other bands and SCL",
45
+ "radiometry": "(DN + BOA_ADD_OFFSET) / BOA_QUANTIFICATION_VALUE; zero DN invalid",
46
+ "cloud_policy": "Keep cloudy reflectance; supply SCL one-hot classes 0..11 and SCL validity separately",
47
+ "history": "Use explicitly selected prior products in stored order; target and target-day S2 excluded"
48
+ },
49
+ "anchor": {
50
+ "clear_scl": [
51
+ 4,
52
+ 5,
53
+ 6
54
+ ],
55
+ "ndvi": "(B8A-B04)/(B8A+B04)",
56
+ "selection": "Most recent usable clear pixel; stable sort by exact age",
57
+ "missing": "training_target_mean; support=0; age=0",
58
+ "age_scale_days": 30
59
+ },
60
+ "modis": {
61
+ "products": [
62
+ "Terra MOD09GQ Collection061 red/NIR",
63
+ "Matched MOD09GA Collection061 for common 500m/250m support"
64
+ ],
65
+ "mapping": "Target pixel centres to native sinusoidal cells by floor; native 1km QA mapped via GQ pixel centres",
66
+ "qa": "Strict state_1km/num_observations + ideal QC250 + ideal QC500 + native numeric validity",
67
+ "reflectance_scaling": "clip(reflectance/0.5, -1, 3)",
68
+ "validity_channels": "Four copies of common_20m_mask",
69
+ "missing": "Zero reflectance and validity",
70
+ "smoothing": "None in this published MODIS250 input recipe",
71
+ "model_internal_age_days": 0.5
72
+ },
73
+ "mtg": {
74
+ "bands": [
75
+ "vis_06",
76
+ "vis_08"
77
+ ],
78
+ "source": "Native FCI patch arrays with full-disk patch origins; numeric units as stored in original archive",
79
+ "mapping": "Original eumetsearch0.1.3 FCI geostationary inverse mapping, bilinear sampling",
80
+ "selection": "First five chronological eligible target-day frames; best support among the supplied three nearest source grids in fixed rank order",
81
+ "validity": "finite and >=2, frame retained if both-band support >=10%; this is numeric support, not a cloud mask",
82
+ "scaling": "clip(value/100,0,3), separate per-band invalid zeroing, joint validity as channel3",
83
+ "padding": "Zero data, zero ages, empty timestamps"
84
+ },
85
+ "landcover": {
86
+ "product": "MCD12Q1 LC_Type1",
87
+ "channels": "Classes1..17 one-hot plus validity",
88
+ "source_year": "Not independently verified for the original source archive; no annual-year claim"
89
+ },
90
+ "same_day_channels": {
91
+ "0:2": "MODIS red/NIR",
92
+ "2:6": "4 common MODIS support copies",
93
+ "6:21": "5 MTG frames x3 channels",
94
+ "21:38": "17 landcover class indicators",
95
+ "38": "landcover validity"
96
+ },
97
+ "time": {
98
+ "sentinel_reference": "Original S2 product/datake-start timestamp, not a pixel clock",
99
+ "sentinel_ages": "Days before target_time",
100
+ "cutoff": "Midnight ending the target UTC day",
101
+ "cutoff_offset": "Days from target_time to cutoff; added to Sentinel ages internally by model",
102
+ "mtg_reference": "Days before cutoff",
103
+ "calendar": "2*pi*((doy-1)+hour/24)/365.25; sin,cos,0",
104
+ "availability": "Retrospective reconstruction; input product production can be later than nominal cutoff; not certified real-time availability"
105
+ }
106
+ }
preprocessing/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ numpy==2.4.6
2
+ scipy==1.17.1
3
+ rasterio==1.4.4
4
+ pyproj==3.7.2
5
+ affine==3.0.1
6
+ pyhdf==0.11.7