{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 216
Expand file tree
/
Copy pathprepare_data.py
More file actions
378 lines (310 loc) · 12.7 KB
/
Copy pathprepare_data.py
File metadata and controls
378 lines (310 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
"""
Data preparation script for ClimateVision forest segmentation.
Two modes:
--mode synthetic Generate fractal-noise synthetic Sentinel-2 patches (no data required)
--mode gee Download real Sentinel-2 L2A tiles via Google Earth Engine
Usage:
# Quick start — 2 000 synthetic patches, default 70/15/15 split:
python scripts/prepare_data.py --mode synthetic --n-patches 2000 --out data/processed
# Fewer patches for a fast smoke test:
python scripts/prepare_data.py --mode synthetic --n-patches 200 --out data/processed
# Real data via GEE (requires authenticated `earthengine-api`):
python scripts/prepare_data.py --mode gee \\
--bbox 2.3 48.8 2.5 49.0 \\
--start 2022-01-01 --end 2023-12-31 \\
--out data/processed
"""
from __future__ import annotations
import argparse
import logging
import sys
from pathlib import Path
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%H:%M:%S",
)
logger = logging.getLogger(__name__)
PROJECT_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(PROJECT_ROOT / "src"))
# ---------------------------------------------------------------------------
# Synthetic mode
# ---------------------------------------------------------------------------
def generate_synthetic(
n_patches: int,
out_dir: Path,
patch_size: int,
train_ratio: float,
val_ratio: float,
) -> None:
"""Delegate entirely to the built-in synthetic generator."""
try:
from climatevision.data.synthetic import generate_synthetic_dataset
except ImportError as exc:
logger.error("Cannot import climatevision package: %s", exc)
logger.error("Run `pip install -e .` from the project root first.")
sys.exit(1)
test_ratio = max(0.0, 1.0 - train_ratio - val_ratio)
n_train = int(n_patches * train_ratio)
n_val = int(n_patches * val_ratio)
n_test = max(0, n_patches - n_train - n_val)
logger.info(
"Generating %d synthetic patches "
"(train=%d / val=%d / test=%d) patch_size=%d",
n_patches, n_train, n_val, n_test, patch_size,
)
generate_synthetic_dataset(
output_dir=out_dir,
n_train=n_train,
n_val=n_val,
n_test=n_test,
patch_size=patch_size,
)
logger.info("Dataset written to %s", out_dir)
# ---------------------------------------------------------------------------
# GEE mode
# ---------------------------------------------------------------------------
def download_gee(
bbox: tuple[float, float, float, float],
start: str,
end: str,
out_dir: Path,
patch_size: int,
max_patches: int,
train_ratio: float,
val_ratio: float,
cloud_threshold: float,
) -> None:
try:
import ee
except ImportError:
logger.error("earthengine-api not installed. Run: pip install earthengine-api")
sys.exit(1)
try:
import os
svc_account = os.getenv("GEE_SERVICE_ACCOUNT")
key_file = os.getenv("GEE_SERVICE_ACCOUNT_KEY")
project = os.getenv("GEE_PROJECT_ID")
if key_file and not os.path.isabs(key_file):
key_file = str(PROJECT_ROOT / key_file)
if svc_account and key_file and os.path.exists(key_file):
credentials = ee.ServiceAccountCredentials(svc_account, key_file)
ee.Initialize(credentials)
elif project:
ee.Initialize(project=project)
else:
ee.Initialize()
except Exception as exc:
logger.error("GEE auth failed: %s", exc)
logger.error("Run: earthengine authenticate")
sys.exit(1)
try:
import rasterio
import numpy as np
except ImportError:
logger.error("rasterio not installed. Run: pip install rasterio")
sys.exit(1)
import random, urllib.request, tempfile, os
west, south, east, north = bbox
# GEE download size limit is 48 MB per request.
# At 100 m resolution, a 0.25° tile is ~278x278 px × 5 bands × 4 bytes ≈ 1.5 MB — safe.
# 100 m is standard for regional forest classification.
TILE_DEG = 0.25
SCALE_M = 100
# Build tile grid
tiles = []
lat = south
while lat < north:
lon = west
while lon < east:
tiles.append((
round(lon, 6),
round(lat, 6),
round(min(lon + TILE_DEG, east), 6),
round(min(lat + TILE_DEG, north), 6),
))
lon += TILE_DEG
lat += TILE_DEG
logger.info("Downloading %d tiles (%.2f° each, scale=%dm)…", len(tiles), TILE_DEG, SCALE_M)
patches: list[tuple[np.ndarray, np.ndarray]] = []
# Minimal rasterio profile for writing plain GeoTIFF patches
base_profile = {
"driver": "GTiff",
"crs": "EPSG:4326",
"transform": rasterio.transform.from_bounds(west, south, east, north, patch_size, patch_size),
}
for ti, (tw, ts, te, tn) in enumerate(tiles):
if len(patches) >= max_patches:
break
tile_region = ee.Geometry.Rectangle([tw, ts, te, tn])
collection = (
ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED")
.filterBounds(tile_region)
.filterDate(start, end)
.filter(ee.Filter.lt("CLOUDY_PIXEL_PERCENTAGE", cloud_threshold * 100))
.select(["B4", "B3", "B2", "B8"])
)
dw = (
ee.ImageCollection("GOOGLE/DYNAMICWORLD/V1")
.filterBounds(tile_region)
.filterDate(start, end)
.select("label")
.mode()
)
forest_mask = dw.eq(1).rename("forest")
try:
image = collection.median().clip(tile_region)
combined = image.addBands(forest_mask)
url = combined.getDownloadURL({
"region": tile_region,
"scale": SCALE_M,
"format": "GEO_TIFF",
})
tmp = tempfile.mktemp(suffix=".tif")
urllib.request.urlretrieve(url, tmp)
with rasterio.open(tmp) as src:
full = src.read() # (5, H, W)
os.unlink(tmp)
if full.shape[0] < 5:
continue
image_data = full[:4].astype(np.float32)
mask_data = (full[4] > 0).astype(np.uint8)
_, H, W = image_data.shape
for y in range(0, H - patch_size + 1, patch_size):
for x in range(0, W - patch_size + 1, patch_size):
if len(patches) >= max_patches:
break
patches.append((
image_data[:, y:y + patch_size, x:x + patch_size],
mask_data[ y:y + patch_size, x:x + patch_size],
))
if len(patches) >= max_patches:
break
logger.info(" tile %d/%d → %d patches so far", ti + 1, len(tiles), len(patches))
except Exception as exc:
logger.warning(" tile %d/%d skipped: %s", ti + 1, len(tiles), exc)
continue
if not patches:
logger.error("No patches extracted — check GEE credentials and bbox")
sys.exit(1)
logger.info("Extracted %d patches total", len(patches))
# Shuffle + split
random.seed(42)
random.shuffle(patches)
n = len(patches)
n_train = int(n * train_ratio)
n_val = int(n * val_ratio)
splits = {
"train": patches[:n_train],
"val": patches[n_train:n_train + n_val],
"test": patches[n_train + n_val:],
}
for split, split_patches in splits.items():
(out_dir / split / "images").mkdir(parents=True, exist_ok=True)
(out_dir / split / "masks").mkdir(parents=True, exist_ok=True)
for idx, (img_patch, mask_patch) in enumerate(split_patches):
stem = f"patch_{idx:05d}"
img_profile = {**base_profile, "count": 4, "dtype": "float32",
"height": patch_size, "width": patch_size}
with rasterio.open(out_dir / split / "images" / f"{stem}.tif", "w", **img_profile) as dst:
dst.write(img_patch)
msk_profile = {**base_profile, "count": 1, "dtype": "uint8",
"height": patch_size, "width": patch_size}
with rasterio.open(out_dir / split / "masks" / f"{stem}.tif", "w", **msk_profile) as dst:
dst.write(mask_patch[np.newaxis])
logger.info(" %s: %d patches", split, len(split_patches))
logger.info("Dataset written to %s", out_dir)
# ---------------------------------------------------------------------------
# Normaliser fitting
# ---------------------------------------------------------------------------
def fit_normalizer(data_dir: Path, out_path: Path) -> None:
"""Compute per-band mean/std on the training set and save to JSON."""
try:
from climatevision.data.preprocessing import Sentinel2Normalizer
except ImportError as exc:
logger.warning("Could not fit normalizer: %s", exc)
return
import glob
import rasterio
tifs = sorted(glob.glob(str(data_dir / "train" / "images" / "*.tif")))
if not tifs:
logger.warning("No training images found — skipping normalizer fit")
return
logger.info("Fitting normalizer on %d training images…", len(tifs))
arrays = []
for p in tifs:
with rasterio.open(p) as src:
arrays.append(src.read().astype("float32"))
norm = Sentinel2Normalizer()
norm.fit(arrays)
norm.save(out_path)
logger.info("Normalizer stats saved to %s", out_path)
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(
description="Prepare dataset for ClimateVision training",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
p.add_argument("--mode", choices=["synthetic", "gee"], default="synthetic")
p.add_argument("--out", type=Path, default=Path("data/processed"),
help="Output directory (created if needed)")
# Synthetic options
p.add_argument("--n-patches", type=int, default=2000,
help="[synthetic] Total number of patches to generate")
p.add_argument("--patch-size", type=int, default=256,
help="Spatial size of each patch in pixels")
# GEE options
p.add_argument("--bbox", type=float, nargs=4, metavar=("W", "S", "E", "N"),
help="[gee] Bounding box: west south east north")
p.add_argument("--start", type=str, default="2022-01-01",
help="[gee] Start date YYYY-MM-DD")
p.add_argument("--end", type=str, default="2023-12-31",
help="[gee] End date YYYY-MM-DD")
p.add_argument("--max-patches", type=int, default=5000,
help="[gee] Maximum patches to extract from download")
p.add_argument("--cloud-threshold", type=float, default=0.2,
help="[gee] Max cloud fraction (0–1)")
# Split ratios
p.add_argument("--train-ratio", type=float, default=0.70)
p.add_argument("--val-ratio", type=float, default=0.15)
# Normalizer
p.add_argument("--fit-normalizer", action="store_true",
help="Fit per-band stats on training set after generation")
p.add_argument("--normalizer-out", type=Path, default=None,
help="Where to write normalizer JSON (default: <out>/normalizer.json)")
return p.parse_args()
def main() -> None:
args = parse_args()
if args.train_ratio + args.val_ratio > 1.0:
logger.error("--train-ratio + --val-ratio must be ≤ 1.0")
sys.exit(1)
if args.mode == "synthetic":
generate_synthetic(
n_patches=args.n_patches,
out_dir=args.out,
patch_size=args.patch_size,
train_ratio=args.train_ratio,
val_ratio=args.val_ratio,
)
else:
if not args.bbox:
logger.error("--bbox W S E N is required for --mode gee")
sys.exit(1)
download_gee(
bbox=tuple(args.bbox), # type: ignore[arg-type]
start=args.start,
end=args.end,
out_dir=args.out,
patch_size=args.patch_size,
max_patches=args.max_patches,
train_ratio=args.train_ratio,
val_ratio=args.val_ratio,
cloud_threshold=args.cloud_threshold,
)
if args.fit_normalizer:
norm_out = args.normalizer_out or (args.out / "normalizer.json")
fit_normalizer(args.out, norm_out)
if __name__ == "__main__":
main()
You can’t perform that action at this time.
