refactor: changed project structure
Browse files- .env.example +0 -8
- .gitignore +1 -0
- EXPERIMENT.md +0 -23
- README.md +144 -17
- configs/dinov3_s_dpt.yaml +171 -0
- configs/small_cnn_unet.yaml +169 -0
- main.py +6 -3
- modules/segmentation/supervised/__init__.py +0 -0
- modules/segmentation/supervised/data.py +0 -94
- modules/segmentation/supervised/datasets.py +0 -83
- modules/segmentation/supervised/module.py +0 -138
- modules/{segmentation → supervised}/__init__.py +0 -0
- modules/supervised/data.py +129 -0
- modules/supervised/datasets.py +115 -0
- modules/supervised/module.py +190 -0
- project.yaml +2 -0
- requirements.txt +1 -3
- scripts/download_dynamic_world.py +0 -106
- scripts/ingest_dynamic_world.py +0 -197
- scripts/publish.py +83 -0
- tests/conftest.py +0 -8
- tests/test_data_workflow.py +333 -0
.env.example
DELETED
|
@@ -1,8 +0,0 @@
|
|
| 1 |
-
# This file is part of the Copernicus Data Space Ecosystem (CDSE).
|
| 2 |
-
GDAL_HTTP_TCP_KEEPALIVE=YES
|
| 3 |
-
AWS_S3_ENDPOINT=eodata.dataspace.copernicus.eu
|
| 4 |
-
AWS_ACCESS_KEY_ID=changethis
|
| 5 |
-
AWS_SECRET_ACCESS_KEY=changethis
|
| 6 |
-
AWS_HTTPS=YES
|
| 7 |
-
AWS_VIRTUAL_HOSTING=FALSE
|
| 8 |
-
GDAL_HTTP_UNSAFESSL=YES
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.gitignore
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
.env
|
| 2 |
data/
|
| 3 |
artifacts/
|
|
|
|
| 4 |
*.ckpt
|
| 5 |
__pycache__/
|
| 6 |
*.pyc
|
|
|
|
| 1 |
.env
|
| 2 |
data/
|
| 3 |
artifacts/
|
| 4 |
+
release/
|
| 5 |
*.ckpt
|
| 6 |
__pycache__/
|
| 7 |
*.pyc
|
EXPERIMENT.md
DELETED
|
@@ -1,23 +0,0 @@
|
|
| 1 |
-
# Experiment requirements
|
| 2 |
-
|
| 3 |
-
Publish a size ladder of segmentation models and measure speed against accuracy.
|
| 4 |
-
|
| 5 |
-
| Stage | Runs | Varies |
|
| 6 |
-
| --- | --- | --- |
|
| 7 |
-
| 0 baseline | DINOv3 S/16 (lvd1689m) + DPT, RGB | proves the pipeline |
|
| 8 |
-
| 1 encoders | DINOv3 S/B/L lvd1689m and L sat493m (RGB); Prithvi-EO-2.0 300/600 (6 bands), 300-TL (+time/location); Clay v1.5 L (10 bands) | encoder, bands |
|
| 9 |
-
| 2 ablations on the best | UNet vs DPT; augmentation none/flip/rotate; CutMix; OHEM; experts only vs + non-expert | one thing each |
|
| 10 |
-
|
| 11 |
-
Excluded: DINOv3 7B and huge-plus (cost), `qkvb` variants and Prithvi v1 (redundant).
|
| 12 |
-
|
| 13 |
-
Training uses paired random crops; validation and test score whole scenes
|
| 14 |
-
(510², test 512²) padded to the encoder's patch multiple, so evaluation needs no
|
| 15 |
-
chip merging. Each encoder must be checked to accept the padded scene size.
|
| 16 |
-
|
| 17 |
-
Source memberships overlap (shared scene ids between experts, non-experts,
|
| 18 |
-
validation and test). Resolve evaluation membership and the validation
|
| 19 |
-
composite before claiming generalization or picking a best model.
|
| 20 |
-
|
| 21 |
-
EDA is auditable: one question per section, visible calculations, plain
|
| 22 |
-
DataFrames, direct GeoSave plot/explore calls. Its band statistics set
|
| 23 |
-
normalization.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
|
@@ -1,35 +1,162 @@
|
|
| 1 |
-
# Dynamic World segmentation
|
| 2 |
|
| 3 |
-
|
| 4 |
-
annotations paired with Sentinel-2 L2A imagery, comparing speed and accuracy.
|
| 5 |
-
Training runs through GeoSave's LightningCLI (`main.py`).
|
| 6 |
|
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 30 |
Human annotations: Dynamic World Project, National Geographic Society with
|
| 31 |
Google and the World Resources Institute, CC-BY-4.0.
|
| 32 |
[Annotations](https://doi.pangaea.de/10.1594/PANGAEA.933475) ·
|
| 33 |
-
[Test set](https://zenodo.org/records/4766508) ·
|
| 34 |
[Paper](https://doi.org/10.1038/s41597-022-01307-4).
|
| 35 |
Imagery: Copernicus Sentinel-2 data terms apply.
|
|
|
|
| 1 |
+
# Dynamic World land-cover segmentation
|
| 2 |
|
| 3 |
+
This project owns one data preparation workflow and one AI task:
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
- **Data:** pair Dynamic World human annotations with Sentinel-2 L2A imagery
|
| 6 |
+
on the labels' grid. The independent `data/` repository owns preparation,
|
| 7 |
+
provenance, splits and exploratory analysis.
|
| 8 |
+
- **AI task:** semantic segmentation into nine Dynamic World land-cover classes.
|
| 9 |
+
Compare model accuracy and inference speed, then release the selected model
|
| 10 |
+
with its georeferenced prediction pipeline.
|
| 11 |
+
- **Method:** supervised learning. Encoder/decoder choices are experiments
|
| 12 |
+
within this task, configured in `configs/`.
|
| 13 |
|
| 14 |
+
Training runs through GeoSave's LightningCLI (`main.py`). Each project has one
|
| 15 |
+
AI task; additional methods for that task belong in `modules/<method>/`.
|
| 16 |
+
|
| 17 |
+
Three repos, one job each:
|
| 18 |
+
|
| 19 |
+
| Repo | Holds |
|
| 20 |
| --- | --- |
|
| 21 |
+
| [`fatmur/dynamicworld`](https://huggingface.co/fatmur/dynamicworld) (this one) | experiment code and configs |
|
| 22 |
+
| [`datasets/fatmur/dynamicworld`](https://huggingface.co/datasets/fatmur/dynamicworld) | label releases, image and label pairs, the scripts and notebook that make them |
|
| 23 |
+
| `fatmur/dynamicworld-<model>`, such as [`fatmur/dynamicworld-small-cnn`](https://huggingface.co/fatmur/dynamicworld-small-cnn) | one released model each: weights, pipeline, model card |
|
| 24 |
+
|
| 25 |
+
## Layout
|
| 26 |
+
|
| 27 |
+
```text
|
| 28 |
+
project.yaml AI task and data directory
|
| 29 |
+
main.py LightningCLI entry point
|
| 30 |
+
configs/ one self-contained file per experiment
|
| 31 |
+
├── small_cnn_unet.yaml small CNN on RGB, CPU
|
| 32 |
+
└── dinov3_s_dpt.yaml DINOv3 S/16 + DPT on RGB, GPU; not trained yet
|
| 33 |
+
modules/supervised/
|
| 34 |
+
├── datasets.py SceneDataset: image GeoTIFF + label GeoTIFF -> Sample
|
| 35 |
+
├── data.py Sample, DataModule: batches, crops and augments
|
| 36 |
+
└── module.py Module: trains on crops, validates on whole scenes
|
| 37 |
+
scripts/
|
| 38 |
+
└── publish.py checkpoint -> Hub repo; optional local export
|
| 39 |
+
data/ data repo: EDA, raw releases and prepared pairs
|
| 40 |
+
artifacts/ TensorBoard runs, configs and checkpoints
|
| 41 |
+
release/ optional local model exports
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
The task is plain semantic segmentation: a sample is one 510×510 px image
|
| 45 |
+
and its original annotation on the same grid, paired through the annotation catalogue.
|
| 46 |
+
|
| 47 |
+
```text
|
| 48 |
+
data/processed/scene.parquet ─▶ explicit split/source selection
|
| 49 |
+
└─ image_path + label_path ─▶ SceneDataset ─▶ DataModule ─▶ Module
|
| 50 |
+
```
|
| 51 |
|
| 52 |
+
A config records the data selection, label scheme and model settings. Two
|
| 53 |
+
settings are shared with the release, and `publish.py` copies both into it,
|
| 54 |
+
so inference prepares and chips a raster exactly as training and validation
|
| 55 |
+
did. The run config also freezes `label_scheme`: original annotation codes are
|
| 56 |
+
remapped only by `SceneDataset`, and publication uses the same class names and
|
| 57 |
+
colors rather than an independently selected target:
|
| 58 |
+
|
| 59 |
+
| Config | Used in training by | In the release |
|
| 60 |
+
| --- | --- | --- |
|
| 61 |
+
| `data.train.init_args.preprocessor` (GeoSave's `dense`) | `SceneDataset`, on every image | the pipeline's preprocessor |
|
| 62 |
+
| `model.chip_size`, `chip_stride`, `chip_mode`, `merge_window`, `chip_batch_size` | `Module.predict_chips`, in validation | the pipeline's `dense` predictor |
|
| 63 |
|
| 64 |
## Commands
|
| 65 |
|
| 66 |
```bash
|
| 67 |
+
hf download fatmur/dynamicworld --type dataset --local-dir data
|
| 68 |
+
|
| 69 |
+
python main.py fit --config configs/small_cnn_unet.yaml
|
| 70 |
+
|
| 71 |
+
python -m scripts.publish fatmur/dynamicworld-small-cnn \
|
| 72 |
+
artifacts/small_cnn_unet/version_0/checkpoints/<name>.ckpt
|
| 73 |
+
|
| 74 |
+
# Optional local copy alongside direct Hub publication:
|
| 75 |
+
# add --out release/dynamicworld-small-cnn
|
| 76 |
+
```
|
| 77 |
+
|
| 78 |
+
```python
|
| 79 |
+
import xarray as xr
|
| 80 |
+
|
| 81 |
+
import geosave as gs
|
| 82 |
+
from geosave.ml import load_pipeline
|
| 83 |
+
|
| 84 |
+
pipeline = load_pipeline("fatmur/dynamicworld-small-cnn")
|
| 85 |
+
image = gs.open_raster("data/processed/image/train/<scene>.tif")
|
| 86 |
+
product = pipeline.predict(xr.DataTree.from_dict({"image": image}))
|
| 87 |
+
```
|
| 88 |
+
|
| 89 |
+
The data repo's `eda.ipynb` explains the original tables, annotation sources,
|
| 90 |
+
voting rules and scene overlap. It assigns splits, copies labels unchanged and
|
| 91 |
+
writes `processed/label.parquet`. Ingestion discovers source STAC Items, acquires
|
| 92 |
+
each selected scene once and writes `processed/scene.parquet`, including paths,
|
| 93 |
+
biome metadata, geometry and diagnostics for pending, successful and failed scenes.
|
| 94 |
+
Training selects expert rows explicitly and remaps original codes only in memory.
|
| 95 |
+
The test dataset selects the supplied consensus composites. The notebook displays intermediate tables and uses GeoSave for raster plots.
|
| 96 |
+
|
| 97 |
+
After selecting a checkpoint using development validation, run final evaluation:
|
| 98 |
+
|
| 99 |
+
```bash
|
| 100 |
+
python main.py test --config configs/small_cnn_unet.yaml --ckpt_path <checkpoint>
|
| 101 |
```
|
| 102 |
|
| 103 |
+
This scores only the ingested test subset. Acquire the complete 409-scene cohort
|
| 104 |
+
before reporting a full benchmark result. Test metrics never select checkpoints.
|
| 105 |
+
|
| 106 |
+
## Run outputs and releases
|
| 107 |
+
|
| 108 |
+
TensorBoard owns each run directory, `artifacts/<model_name>/version_N/`.
|
| 109 |
+
Lightning saves `config.yaml`, `hparams.yaml`, event logs and `checkpoints/`
|
| 110 |
+
there. Leave `ModelCheckpoint.dirpath` unset so checkpoints follow the logger.
|
| 111 |
+
`last.ckpt` resumes training; the best-scoring checkpoint is selected by
|
| 112 |
+
`val_iou_macro`. The legacy top-level `checkpoints/last.ckpt` is retained as
|
| 113 |
+
an existing training result, but is not the destination of current configs.
|
| 114 |
+
|
| 115 |
+
`python -m scripts.publish` reconstructs the pipeline and calls the native
|
| 116 |
+
Hugging Face `push_to_hub` API. Each released model has its own Hub repository.
|
| 117 |
+
A local export is optional and belongs under `release/`, outside run artifacts.
|
| 118 |
+
|
| 119 |
+
## Experiment plan
|
| 120 |
+
|
| 121 |
+
Publish a size ladder of segmentation models and measure speed against accuracy.
|
| 122 |
+
|
| 123 |
+
| Stage | Runs | Varies |
|
| 124 |
+
| --- | --- | --- |
|
| 125 |
+
| 0 pipeline | small CNN + UNet, RGB (`small_cnn_unet.yaml`) | proves data → training → release |
|
| 126 |
+
| 1 baseline | DINOv3 S/16 (lvd1689m) + DPT, RGB (`dinov3_s_dpt.yaml`) | first pretrained encoder |
|
| 127 |
+
| 2 encoders | DINOv3 S/B/L lvd1689m and L sat493m (RGB); Prithvi-EO-2.0 300/600 (6 bands); Clay v1.5 L (10 bands) | encoder, bands |
|
| 128 |
+
| 3 ablations on the best | UNet vs DPT; augmentation none/flip/rotate; experts only vs + non-expert | one thing each |
|
| 129 |
+
|
| 130 |
+
A stage gets its config when it is run; only stages 0 and 1 have one now.
|
| 131 |
+
|
| 132 |
+
Training draws one random 256 px crop per scene and epoch. Validation scores
|
| 133 |
+
whole 510 px scenes, predicted chip by chip and merged with the release's
|
| 134 |
+
predictor settings.
|
| 135 |
+
|
| 136 |
+
### Evaluation scope and limits
|
| 137 |
+
|
| 138 |
+
- EDA prepares the full dataset. Ingestion optionally limits the number of unique
|
| 139 |
+
scenes with `--limit`; `data/README.md` records the earlier 300-scene study.
|
| 140 |
+
- All 409 published evaluation locations belong to test. Our seed-0 80/20
|
| 141 |
+
expert-location development split is a project choice, not a verified original
|
| 142 |
+
paper assignment. Overlapping held-out footprints are excluded from training.
|
| 143 |
+
- The global baseline trains on expert and non-expert labels across all biomes.
|
| 144 |
+
Val stays expert-only; test uses consensus. Training uses completed imagery,
|
| 145 |
+
so full-dataset training requires complete ingestion. Regional fine-tuning can
|
| 146 |
+
follow later. Our L2A inputs differ from the paper's L1C inputs.
|
| 147 |
+
- The earlier checkpoint and normalization statistics used a different cohort.
|
| 148 |
+
Current configs mark their statistics as historical. Recompute training-only
|
| 149 |
+
normalization and train a new run before claiming results for the new sample.
|
| 150 |
+
- Earlier models selected using the consensus cohort cannot retrospectively
|
| 151 |
+
claim it as unseen test data. Old per-split folders are retained as history;
|
| 152 |
+
current configs read only `scene.parquet`.
|
| 153 |
+
- Existing run configs without `label_scheme` need their actual training
|
| 154 |
+
taxonomy recorded explicitly before using the updated publisher.
|
| 155 |
+
|
| 156 |
## Sources
|
| 157 |
|
| 158 |
Human annotations: Dynamic World Project, National Geographic Society with
|
| 159 |
Google and the World Resources Institute, CC-BY-4.0.
|
| 160 |
[Annotations](https://doi.pangaea.de/10.1594/PANGAEA.933475) ·
|
|
|
|
| 161 |
[Paper](https://doi.org/10.1038/s41597-022-01307-4).
|
| 162 |
Imagery: Copernicus Sentinel-2 data terms apply.
|
configs/dinov3_s_dpt.yaml
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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elerator: gpu
|
| 10 |
+
max_epochs: 100
|
| 11 |
+
check_val_every_n_epoch: 5
|
| 12 |
+
log_every_n_steps: 1
|
| 13 |
+
|
| 14 |
+
callbacks:
|
| 15 |
+
- class_path: lightning.pytorch.callbacks.ModelCheckpoint
|
| 16 |
+
init_args:
|
| 17 |
+
monitor: val_iou_macro
|
| 18 |
+
mode: max
|
| 19 |
+
save_top_k: 1
|
| 20 |
+
save_last: true
|
| 21 |
+
filename: "{epoch:02d}-{val_iou_macro:.4f}"
|
| 22 |
+
- class_path: lightning.pytorch.callbacks.LearningRateMonitor
|
| 23 |
+
init_args:
|
| 24 |
+
logging_interval: epoch
|
| 25 |
+
|
| 26 |
+
model:
|
| 27 |
+
encoder:
|
| 28 |
+
name: dinov3
|
| 29 |
+
init_args:
|
| 30 |
+
model_name: vit_small_patch16_dinov3.lvd1689m
|
| 31 |
+
pretrained: true
|
| 32 |
+
in_channels: 3
|
| 33 |
+
input_size: 256
|
| 34 |
+
|
| 35 |
+
decoder:
|
| 36 |
+
name: dpt
|
| 37 |
+
|
| 38 |
+
head:
|
| 39 |
+
name: segmentation
|
| 40 |
+
init_args:
|
| 41 |
+
num_classes: 9
|
| 42 |
+
ignore_index: 255
|
| 43 |
+
|
| 44 |
+
criterion:
|
| 45 |
+
name: cross_entropy
|
| 46 |
+
init_args:
|
| 47 |
+
ignore_index: 255
|
| 48 |
+
|
| 49 |
+
# A pretrained encoder learns ten times slower than the new decoder and head.
|
| 50 |
+
optimizer:
|
| 51 |
+
name: adamw
|
| 52 |
+
init_args:
|
| 53 |
+
lr: 0.0005
|
| 54 |
+
weight_decay: 0.01
|
| 55 |
+
|
| 56 |
+
encoder_lr: 0.00005
|
| 57 |
+
|
| 58 |
+
lr_scheduler:
|
| 59 |
+
name: cosine_annealing
|
| 60 |
+
init_args:
|
| 61 |
+
T_max: 100
|
| 62 |
+
|
| 63 |
+
metrics:
|
| 64 |
+
- iou.macro
|
| 65 |
+
- f1.macro
|
| 66 |
+
|
| 67 |
+
# Validation chips; publish.py gives the release's predictor the same settings.
|
| 68 |
+
chip_size: 256
|
| 69 |
+
chip_stride: 192
|
| 70 |
+
chip_mode: reflect
|
| 71 |
+
merge_window: hann
|
| 72 |
+
chip_batch_size: 8
|
| 73 |
+
|
| 74 |
+
data:
|
| 75 |
+
train:
|
| 76 |
+
class_path: modules.supervised.datasets.SceneDataset
|
| 77 |
+
init_args:
|
| 78 |
+
table: data/processed/scene.parquet
|
| 79 |
+
split: train
|
| 80 |
+
source_groups: [experts, non_expert]
|
| 81 |
+
label_scheme: &label_scheme
|
| 82 |
+
ignore_index: 255
|
| 83 |
+
remap:
|
| 84 |
+
0: 255
|
| 85 |
+
1: 0
|
| 86 |
+
2: 1
|
| 87 |
+
3: 2
|
| 88 |
+
4: 3
|
| 89 |
+
5: 4
|
| 90 |
+
6: 5
|
| 91 |
+
7: 6
|
| 92 |
+
8: 7
|
| 93 |
+
9: 8
|
| 94 |
+
10: 255
|
| 95 |
+
classes:
|
| 96 |
+
- water
|
| 97 |
+
- trees
|
| 98 |
+
- grass
|
| 99 |
+
- flooded_vegetation
|
| 100 |
+
- crops
|
| 101 |
+
- shrub_and_scrub
|
| 102 |
+
- built
|
| 103 |
+
- bare
|
| 104 |
+
- snow_and_ice
|
| 105 |
+
colors:
|
| 106 |
+
- '#419bdf'
|
| 107 |
+
- '#397d49'
|
| 108 |
+
- '#88b053'
|
| 109 |
+
- '#7a87c6'
|
| 110 |
+
- '#e49635'
|
| 111 |
+
- '#dfc35a'
|
| 112 |
+
- '#c4281b'
|
| 113 |
+
- '#a59b8f'
|
| 114 |
+
- '#b39fe1'
|
| 115 |
+
|
| 116 |
+
preprocessor: &preprocessor
|
| 117 |
+
name: dense
|
| 118 |
+
init_args:
|
| 119 |
+
bands: [B04, B03, B02]
|
| 120 |
+
decode: true
|
| 121 |
+
fill: 0.0
|
| 122 |
+
# Historical normalization; recompute on the current training cohort
|
| 123 |
+
mean: [0.0577, 0.0692, 0.0487]
|
| 124 |
+
std: [0.0623, 0.0564, 0.0585]
|
| 125 |
+
name: image
|
| 126 |
+
ignore_index: 255
|
| 127 |
+
|
| 128 |
+
val:
|
| 129 |
+
class_path: modules.supervised.datasets.SceneDataset
|
| 130 |
+
init_args:
|
| 131 |
+
table: data/processed/scene.parquet
|
| 132 |
+
split: val
|
| 133 |
+
source_groups: [experts]
|
| 134 |
+
label_scheme: *label_scheme
|
| 135 |
+
preprocessor: *preprocessor
|
| 136 |
+
ignore_index: 255
|
| 137 |
+
|
| 138 |
+
test:
|
| 139 |
+
class_path: modules.supervised.datasets.SceneDataset
|
| 140 |
+
init_args:
|
| 141 |
+
table: data/processed/scene.parquet
|
| 142 |
+
split: test
|
| 143 |
+
source_groups: [expert_composites]
|
| 144 |
+
voting_rule: consensus
|
| 145 |
+
label_scheme: *label_scheme
|
| 146 |
+
preprocessor: *preprocessor
|
| 147 |
+
ignore_index: 255
|
| 148 |
+
|
| 149 |
+
# One random crop per scene and epoch; mirrors and quarter turns, since
|
| 150 |
+
# land cover has no preferred direction.
|
| 151 |
+
|
| 152 |
+
augmentations:
|
| 153 |
+
- name: RandomCrop
|
| 154 |
+
init_args:
|
| 155 |
+
size: [256, 256]
|
| 156 |
+
- name: RandomHorizontalFlip
|
| 157 |
+
init_args:
|
| 158 |
+
p: 0.5
|
| 159 |
+
- name: RandomVerticalFlip
|
| 160 |
+
init_args:
|
| 161 |
+
p: 0.5
|
| 162 |
+
- name: RandomRotation90
|
| 163 |
+
init_args:
|
| 164 |
+
times: [1, 3]
|
| 165 |
+
p: 0.75
|
| 166 |
+
|
| 167 |
+
crop_size: 256
|
| 168 |
+
ignore_index: 255
|
| 169 |
+
batch_size: 8
|
| 170 |
+
eval_batch_size: 3
|
| 171 |
+
num_workers: 4
|
configs/small_cnn_unet.yaml
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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aml
|
| 3 |
+
|
| 4 |
+
seed_everything: 0
|
| 5 |
+
|
| 6 |
+
model_name: small_cnn_unet
|
| 7 |
+
|
| 8 |
+
trainer:
|
| 9 |
+
accelerator: cpu
|
| 10 |
+
max_epochs: 100
|
| 11 |
+
check_val_every_n_epoch: 5
|
| 12 |
+
log_every_n_steps: 1
|
| 13 |
+
|
| 14 |
+
callbacks:
|
| 15 |
+
- class_path: lightning.pytorch.callbacks.ModelCheckpoint
|
| 16 |
+
init_args:
|
| 17 |
+
monitor: val_iou_macro
|
| 18 |
+
mode: max
|
| 19 |
+
save_top_k: 1
|
| 20 |
+
save_last: true
|
| 21 |
+
filename: "{epoch:02d}-{val_iou_macro:.4f}"
|
| 22 |
+
- class_path: lightning.pytorch.callbacks.LearningRateMonitor
|
| 23 |
+
init_args:
|
| 24 |
+
logging_interval: epoch
|
| 25 |
+
|
| 26 |
+
model:
|
| 27 |
+
encoder:
|
| 28 |
+
name: small_cnn
|
| 29 |
+
init_args:
|
| 30 |
+
in_channels: 3
|
| 31 |
+
input_size: 256
|
| 32 |
+
|
| 33 |
+
decoder:
|
| 34 |
+
name: unet
|
| 35 |
+
|
| 36 |
+
head:
|
| 37 |
+
name: segmentation
|
| 38 |
+
init_args:
|
| 39 |
+
num_classes: 9
|
| 40 |
+
ignore_index: 255
|
| 41 |
+
|
| 42 |
+
criterion:
|
| 43 |
+
name: cross_entropy
|
| 44 |
+
init_args:
|
| 45 |
+
ignore_index: 255
|
| 46 |
+
|
| 47 |
+
# Trained from scratch: one rate for every stage.
|
| 48 |
+
optimizer:
|
| 49 |
+
name: adamw
|
| 50 |
+
init_args:
|
| 51 |
+
lr: 0.001
|
| 52 |
+
weight_decay: 0.01
|
| 53 |
+
|
| 54 |
+
encoder_lr: 0.001
|
| 55 |
+
|
| 56 |
+
lr_scheduler:
|
| 57 |
+
name: cosine_annealing
|
| 58 |
+
init_args:
|
| 59 |
+
T_max: 100
|
| 60 |
+
|
| 61 |
+
metrics:
|
| 62 |
+
- iou.macro
|
| 63 |
+
- f1.macro
|
| 64 |
+
|
| 65 |
+
# Validation chips; publish.py gives the release's predictor the same settings.
|
| 66 |
+
chip_size: 256
|
| 67 |
+
chip_stride: 192
|
| 68 |
+
chip_mode: reflect
|
| 69 |
+
merge_window: hann
|
| 70 |
+
chip_batch_size: 8
|
| 71 |
+
|
| 72 |
+
data:
|
| 73 |
+
train:
|
| 74 |
+
class_path: modules.supervised.datasets.SceneDataset
|
| 75 |
+
init_args:
|
| 76 |
+
table: data/processed/scene.parquet
|
| 77 |
+
split: train
|
| 78 |
+
source_groups: [experts, non_expert]
|
| 79 |
+
label_scheme: &label_scheme
|
| 80 |
+
ignore_index: 255
|
| 81 |
+
remap:
|
| 82 |
+
0: 255
|
| 83 |
+
1: 0
|
| 84 |
+
2: 1
|
| 85 |
+
3: 2
|
| 86 |
+
4: 3
|
| 87 |
+
5: 4
|
| 88 |
+
6: 5
|
| 89 |
+
7: 6
|
| 90 |
+
8: 7
|
| 91 |
+
9: 8
|
| 92 |
+
10: 255
|
| 93 |
+
classes:
|
| 94 |
+
- water
|
| 95 |
+
- trees
|
| 96 |
+
- grass
|
| 97 |
+
- flooded_vegetation
|
| 98 |
+
- crops
|
| 99 |
+
- shrub_and_scrub
|
| 100 |
+
- built
|
| 101 |
+
- bare
|
| 102 |
+
- snow_and_ice
|
| 103 |
+
colors:
|
| 104 |
+
- '#419bdf'
|
| 105 |
+
- '#397d49'
|
| 106 |
+
- '#88b053'
|
| 107 |
+
- '#7a87c6'
|
| 108 |
+
- '#e49635'
|
| 109 |
+
- '#dfc35a'
|
| 110 |
+
- '#c4281b'
|
| 111 |
+
- '#a59b8f'
|
| 112 |
+
- '#b39fe1'
|
| 113 |
+
|
| 114 |
+
preprocessor: &preprocessor
|
| 115 |
+
name: dense
|
| 116 |
+
init_args:
|
| 117 |
+
bands: [B04, B03, B02]
|
| 118 |
+
decode: true
|
| 119 |
+
fill: 0.0
|
| 120 |
+
# Historical normalization; recompute on the current training cohort
|
| 121 |
+
mean: [0.0577, 0.0692, 0.0487]
|
| 122 |
+
std: [0.0623, 0.0564, 0.0585]
|
| 123 |
+
name: image
|
| 124 |
+
ignore_index: 255
|
| 125 |
+
|
| 126 |
+
val:
|
| 127 |
+
class_path: modules.supervised.datasets.SceneDataset
|
| 128 |
+
init_args:
|
| 129 |
+
table: data/processed/scene.parquet
|
| 130 |
+
split: val
|
| 131 |
+
source_groups: [experts]
|
| 132 |
+
label_scheme: *label_scheme
|
| 133 |
+
preprocessor: *preprocessor
|
| 134 |
+
ignore_index: 255
|
| 135 |
+
|
| 136 |
+
test:
|
| 137 |
+
class_path: modules.supervised.datasets.SceneDataset
|
| 138 |
+
init_args:
|
| 139 |
+
table: data/processed/scene.parquet
|
| 140 |
+
split: test
|
| 141 |
+
source_groups: [expert_composites]
|
| 142 |
+
voting_rule: consensus
|
| 143 |
+
label_scheme: *label_scheme
|
| 144 |
+
preprocessor: *preprocessor
|
| 145 |
+
ignore_index: 255
|
| 146 |
+
|
| 147 |
+
# One random crop per scene and epoch; mirrors and quarter turns, since
|
| 148 |
+
# land cover has no preferred direction.
|
| 149 |
+
|
| 150 |
+
augmentations:
|
| 151 |
+
- name: RandomCrop
|
| 152 |
+
init_args:
|
| 153 |
+
size: [256, 256]
|
| 154 |
+
- name: RandomHorizontalFlip
|
| 155 |
+
init_args:
|
| 156 |
+
p: 0.5
|
| 157 |
+
- name: RandomVerticalFlip
|
| 158 |
+
init_args:
|
| 159 |
+
p: 0.5
|
| 160 |
+
- name: RandomRotation90
|
| 161 |
+
init_args:
|
| 162 |
+
times: [1, 3]
|
| 163 |
+
p: 0.75
|
| 164 |
+
|
| 165 |
+
crop_size: 256
|
| 166 |
+
ignore_index: 255
|
| 167 |
+
batch_size: 8
|
| 168 |
+
eval_batch_size: 3
|
| 169 |
+
num_workers: 4
|
main.py
CHANGED
|
@@ -1,8 +1,11 @@
|
|
| 1 |
-
"""Run
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
from geosave.ml.cli import GeosaveCLI
|
| 4 |
-
from modules.
|
| 5 |
-
from modules.
|
| 6 |
|
| 7 |
if __name__ == "__main__":
|
| 8 |
GeosaveCLI(
|
|
|
|
| 1 |
+
"""Run one experiment configuration through GeoSave's LightningCLI.
|
| 2 |
+
|
| 3 |
+
python main.py fit --config configs/small_cnn_unet.yaml
|
| 4 |
+
"""
|
| 5 |
|
| 6 |
from geosave.ml.cli import GeosaveCLI
|
| 7 |
+
from modules.supervised.data import DataModule
|
| 8 |
+
from modules.supervised.module import Module
|
| 9 |
|
| 10 |
if __name__ == "__main__":
|
| 11 |
GeosaveCLI(
|
modules/segmentation/supervised/__init__.py
DELETED
|
File without changes
|
modules/segmentation/supervised/data.py
DELETED
|
@@ -1,94 +0,0 @@
|
|
| 1 |
-
"""Batch segmentation samples, augment paired pixels, then normalize."""
|
| 2 |
-
|
| 3 |
-
from lightning import LightningDataModule
|
| 4 |
-
from torch.utils.data import DataLoader
|
| 5 |
-
|
| 6 |
-
from geosave.ml.transforms import ImageAugmenter, CutMix
|
| 7 |
-
|
| 8 |
-
from .datasets import DynamicWorld, read_target
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
class DataModule(LightningDataModule):
|
| 12 |
-
"""Configure bands, normalization and augmentation for training.
|
| 13 |
-
|
| 14 |
-
Encoder context (time, location) returns with the Sample design, read from
|
| 15 |
-
each sample's crs, transform and time rather than per-encoder flags.
|
| 16 |
-
"""
|
| 17 |
-
|
| 18 |
-
def __init__(
|
| 19 |
-
self,
|
| 20 |
-
bands: list[str],
|
| 21 |
-
mean: list[float] | None = None,
|
| 22 |
-
std: list[float] | None = None,
|
| 23 |
-
size: int = 256,
|
| 24 |
-
target: str = "dynamic_world",
|
| 25 |
-
cutmix: float = 0.0,
|
| 26 |
-
batch_size: int = 8,
|
| 27 |
-
num_workers: int = 0,
|
| 28 |
-
augmentations: list[dict] | None = None,
|
| 29 |
-
):
|
| 30 |
-
super().__init__()
|
| 31 |
-
self.save_hyperparameters()
|
| 32 |
-
|
| 33 |
-
if (mean is None) != (std is None):
|
| 34 |
-
raise ValueError("Supply both mean and std for normalization")
|
| 35 |
-
|
| 36 |
-
self.datasets = {}
|
| 37 |
-
self.ignore_index = read_target(target)["ignore_index"]
|
| 38 |
-
self.augmenter = ImageAugmenter(augmentations or [], size)
|
| 39 |
-
self.cutmix = CutMix(cutmix)
|
| 40 |
-
|
| 41 |
-
def setup(self, stage: str | None = None):
|
| 42 |
-
splits = {
|
| 43 |
-
None: ("train", "val", "test"),
|
| 44 |
-
"fit": ("train", "val"),
|
| 45 |
-
"validate": ("val",),
|
| 46 |
-
"test": ("test",),
|
| 47 |
-
}
|
| 48 |
-
for split in splits[stage]:
|
| 49 |
-
self.datasets[split] = DynamicWorld(
|
| 50 |
-
split,
|
| 51 |
-
bands=self.hparams.bands,
|
| 52 |
-
size=self.hparams.size,
|
| 53 |
-
target=self.hparams.target,
|
| 54 |
-
)
|
| 55 |
-
|
| 56 |
-
def _loader(self, split, shuffle=False):
|
| 57 |
-
workers = self.hparams.num_workers
|
| 58 |
-
|
| 59 |
-
return DataLoader(
|
| 60 |
-
self.datasets[split],
|
| 61 |
-
batch_size=self.hparams.batch_size,
|
| 62 |
-
shuffle=shuffle,
|
| 63 |
-
num_workers=workers,
|
| 64 |
-
persistent_workers=workers > 0,
|
| 65 |
-
multiprocessing_context="spawn" if workers else None,
|
| 66 |
-
)
|
| 67 |
-
|
| 68 |
-
def train_dataloader(self):
|
| 69 |
-
return self._loader("train", shuffle=True)
|
| 70 |
-
|
| 71 |
-
def val_dataloader(self):
|
| 72 |
-
return self._loader("val")
|
| 73 |
-
|
| 74 |
-
def test_dataloader(self):
|
| 75 |
-
return self._loader("test")
|
| 76 |
-
|
| 77 |
-
def on_after_batch_transfer(self, batch, dataloader_idx):
|
| 78 |
-
image, target = batch["image"], batch["target"]
|
| 79 |
-
|
| 80 |
-
if self.trainer is not None and self.trainer.training:
|
| 81 |
-
# Reserve zero for ignored labels and borders introduced by rotation.
|
| 82 |
-
mask = (target + 1).masked_fill(target == self.ignore_index, 0).float()
|
| 83 |
-
image, mask = self.augmenter(image, mask, data_keys=["input", "mask"])
|
| 84 |
-
target = mask.round().long() - 1
|
| 85 |
-
target = target.masked_fill(target < 0, self.ignore_index)
|
| 86 |
-
image, target = self.cutmix(image, target)
|
| 87 |
-
|
| 88 |
-
# Normalize after augmentation.
|
| 89 |
-
if self.hparams.mean is not None:
|
| 90 |
-
mean = image.new_tensor(self.hparams.mean)[:, None, None]
|
| 91 |
-
std = image.new_tensor(self.hparams.std)[:, None, None]
|
| 92 |
-
image = (image - mean) / std
|
| 93 |
-
|
| 94 |
-
return {**batch, "image": image, "target": target}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
modules/segmentation/supervised/datasets.py
DELETED
|
@@ -1,83 +0,0 @@
|
|
| 1 |
-
"""Dynamic World scenes as segmentation samples; stubbed until the Sample design settles."""
|
| 2 |
-
|
| 3 |
-
import re
|
| 4 |
-
from pathlib import Path
|
| 5 |
-
from typing import Literal
|
| 6 |
-
|
| 7 |
-
import pandas as pd
|
| 8 |
-
import yaml
|
| 9 |
-
from torch.utils.data import Dataset
|
| 10 |
-
|
| 11 |
-
DATA = Path(__file__).resolve().parents[3] / "data"
|
| 12 |
-
|
| 13 |
-
# Where each label source sits under data/raw. The Zenodo test files repeat the
|
| 14 |
-
# consensus composite and are not a source.
|
| 15 |
-
SOURCES = {
|
| 16 |
-
"experts": "experts",
|
| 17 |
-
"non_expert": "non_expert",
|
| 18 |
-
"individual_experts": "validation/validation_set/individual_experts",
|
| 19 |
-
"expert_composites": "validation/validation_set/expert_composites",
|
| 20 |
-
}
|
| 21 |
-
|
| 22 |
-
# dw_{lon}_{lat}-{yyyymmdd}[_{variant}].tif; variant is a composite rule or expert id.
|
| 23 |
-
LABEL_NAME = re.compile(r"^dw_(-?\d+\.\d+)_(-?\d+\.\d+)-(\d{8})_?(.*)$")
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
def read_target(name: str) -> dict:
|
| 27 |
-
"""Read one training target (remap, classes, colors) from data/labels.yaml."""
|
| 28 |
-
return yaml.safe_load((DATA / "labels.yaml").read_text())[name]
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
def find_labels(raw: Path = DATA / "raw") -> pd.DataFrame:
|
| 32 |
-
"""List every label file with the scene it annotates.
|
| 33 |
-
|
| 34 |
-
Every label of one scene shares that scene's grid, so the scene key pairs
|
| 35 |
-
a label with its image, `processed/images/{scene}.tif`.
|
| 36 |
-
|
| 37 |
-
Returns:
|
| 38 |
-
One row per file: `scene` (`{lon}_{lat}-{yyyymmdd}`), its `lon`, `lat`
|
| 39 |
-
and `date`, `source`, `variant` (composite rule or expert id, empty
|
| 40 |
-
otherwise) and `path`.
|
| 41 |
-
"""
|
| 42 |
-
rows = []
|
| 43 |
-
for source, folder in SOURCES.items():
|
| 44 |
-
for path in sorted((raw / folder).rglob("*.tif")):
|
| 45 |
-
match = LABEL_NAME.match(path.stem)
|
| 46 |
-
if match is None:
|
| 47 |
-
raise ValueError(f"unexpected label name: {path}")
|
| 48 |
-
lon, lat, day, variant = match.groups()
|
| 49 |
-
rows.append(
|
| 50 |
-
{
|
| 51 |
-
"scene": f"{lon}_{lat}-{day}",
|
| 52 |
-
"lon": float(lon),
|
| 53 |
-
"lat": float(lat),
|
| 54 |
-
"date": pd.Timestamp(day),
|
| 55 |
-
"source": source,
|
| 56 |
-
"variant": variant,
|
| 57 |
-
"path": path,
|
| 58 |
-
}
|
| 59 |
-
)
|
| 60 |
-
return pd.DataFrame(rows)
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
class DynamicWorld(Dataset):
|
| 64 |
-
"""Paired image/label scenes from the prepared catalog.
|
| 65 |
-
|
| 66 |
-
Stub: waits on the ingest rewrite (new catalog) and the Sample design
|
| 67 |
-
(pixels + crs + transform + time; train random crops, whole-scene eval).
|
| 68 |
-
"""
|
| 69 |
-
|
| 70 |
-
def __init__(
|
| 71 |
-
self,
|
| 72 |
-
split: Literal["train", "val", "test"],
|
| 73 |
-
bands: list[str],
|
| 74 |
-
size: int = 256,
|
| 75 |
-
target: str = "dynamic_world",
|
| 76 |
-
):
|
| 77 |
-
raise NotImplementedError("DynamicWorld waits on the new catalog and Sample design")
|
| 78 |
-
|
| 79 |
-
def __len__(self) -> int:
|
| 80 |
-
raise NotImplementedError
|
| 81 |
-
|
| 82 |
-
def __getitem__(self, index: int) -> dict:
|
| 83 |
-
raise NotImplementedError
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
modules/segmentation/supervised/module.py
DELETED
|
@@ -1,138 +0,0 @@
|
|
| 1 |
-
"""Project-owned supervised recipe using GeoSave's training builders."""
|
| 2 |
-
|
| 3 |
-
from copy import deepcopy
|
| 4 |
-
|
| 5 |
-
import torch
|
| 6 |
-
from lightning import LightningModule
|
| 7 |
-
from torchmetrics import MeanMetric
|
| 8 |
-
|
| 9 |
-
from geosave.ml.builders import build_criterion, build_optimizer, build_scheduler
|
| 10 |
-
from geosave.ml.metrics import MulticlassMetrics
|
| 11 |
-
from geosave.model import build_model
|
| 12 |
-
|
| 13 |
-
from .datasets import read_target
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
class Module(LightningModule):
|
| 17 |
-
"""Train a configured model on flat image, context, and target batches."""
|
| 18 |
-
|
| 19 |
-
def __init__(
|
| 20 |
-
self,
|
| 21 |
-
model_chain: dict,
|
| 22 |
-
target: str = "dynamic_world",
|
| 23 |
-
criterion: dict | None = None,
|
| 24 |
-
optimizer: dict | None = None,
|
| 25 |
-
lr_scheduler: dict | None = None,
|
| 26 |
-
metrics: list[str] | None = None,
|
| 27 |
-
policy: dict | None = None,
|
| 28 |
-
):
|
| 29 |
-
super().__init__()
|
| 30 |
-
policy = read_target(target) if policy is None else deepcopy(policy)
|
| 31 |
-
criterion = deepcopy(criterion or {"name": "cross_entropy"})
|
| 32 |
-
optimizer = optimizer or {"name": "adamw", "init_args": {"lr": 1e-3}}
|
| 33 |
-
metrics = metrics or ["iou.macro.per_class", "f1.macro"]
|
| 34 |
-
self.save_hyperparameters()
|
| 35 |
-
self.policy = policy
|
| 36 |
-
self.ignore_index = policy["ignore_index"]
|
| 37 |
-
self.num_classes = len(policy["classes"])
|
| 38 |
-
|
| 39 |
-
# Loss and metrics share the Dataset's ignored label value.
|
| 40 |
-
options = criterion.setdefault("init_args", {})
|
| 41 |
-
options["ignore_index"] = self.ignore_index
|
| 42 |
-
self.criterion = build_criterion(criterion)
|
| 43 |
-
|
| 44 |
-
def configure_model(self):
|
| 45 |
-
"""Build the chain and metrics in Lightning's model construction hook."""
|
| 46 |
-
if hasattr(self, "model"):
|
| 47 |
-
return
|
| 48 |
-
self.model = build_model(deepcopy(self.hparams.model_chain))
|
| 49 |
-
last = list(self.hparams.model_chain)[-1]
|
| 50 |
-
if self.model.get_submodule(last).num_classes != self.num_classes:
|
| 51 |
-
raise ValueError("head num_classes must match the label policy")
|
| 52 |
-
metrics = MulticlassMetrics(
|
| 53 |
-
self.num_classes,
|
| 54 |
-
ignore_index=self.ignore_index,
|
| 55 |
-
labels=self.policy["classes"],
|
| 56 |
-
metrics=self.hparams.metrics,
|
| 57 |
-
)
|
| 58 |
-
self.train_metrics = metrics.clone(prefix="train_")
|
| 59 |
-
self.val_metrics = metrics.clone(prefix="val_")
|
| 60 |
-
self.test_metrics = metrics.clone(prefix="test_")
|
| 61 |
-
self.train_loss = MeanMetric()
|
| 62 |
-
self.val_loss = MeanMetric()
|
| 63 |
-
self.test_loss = MeanMetric()
|
| 64 |
-
|
| 65 |
-
def configure_optimizers(self):
|
| 66 |
-
optimizer = build_optimizer(self.hparams.optimizer, self.model)
|
| 67 |
-
if self.hparams.lr_scheduler is None:
|
| 68 |
-
return optimizer
|
| 69 |
-
return {
|
| 70 |
-
"optimizer": optimizer,
|
| 71 |
-
"lr_scheduler": build_scheduler(self.hparams.lr_scheduler, optimizer),
|
| 72 |
-
}
|
| 73 |
-
|
| 74 |
-
def forward(self, **inputs):
|
| 75 |
-
return self.model(**inputs)
|
| 76 |
-
|
| 77 |
-
def on_load_checkpoint(self, checkpoint):
|
| 78 |
-
if checkpoint["hyper_parameters"]["policy"] != self.policy:
|
| 79 |
-
raise ValueError("Cannot resume with a different target policy")
|
| 80 |
-
|
| 81 |
-
def setup(self, stage):
|
| 82 |
-
if self.trainer.world_size != 1:
|
| 83 |
-
raise ValueError("These experiments support one training device")
|
| 84 |
-
for dataset in self.trainer.datamodule.datasets.values():
|
| 85 |
-
if dataset.policy != self.policy:
|
| 86 |
-
raise ValueError("Dataset and model target policies differ")
|
| 87 |
-
|
| 88 |
-
def _step(self, batch, stage):
|
| 89 |
-
target = batch["target"]
|
| 90 |
-
count = target.ne(self.ignore_index).sum()
|
| 91 |
-
if count == 0:
|
| 92 |
-
# Skip optimization too: AdamW would otherwise decay parameters.
|
| 93 |
-
return None
|
| 94 |
-
inputs = {name: value for name, value in batch.items() if name != "target"}
|
| 95 |
-
logits = self(**inputs)
|
| 96 |
-
loss = self.criterion(logits, target)
|
| 97 |
-
if getattr(self.criterion, "reduction", None) == "sum":
|
| 98 |
-
loss = loss / count
|
| 99 |
-
|
| 100 |
-
# Weight epoch loss by usable pixels, so padded windows do not dominate.
|
| 101 |
-
getattr(self, f"{stage}_metrics").update(logits, target)
|
| 102 |
-
getattr(self, f"{stage}_loss").update(loss.detach(), weight=count)
|
| 103 |
-
return loss
|
| 104 |
-
|
| 105 |
-
def _log_epoch(self, stage):
|
| 106 |
-
metrics = getattr(self, f"{stage}_metrics")
|
| 107 |
-
average = getattr(self, f"{stage}_loss")
|
| 108 |
-
loss = average.compute()
|
| 109 |
-
if not torch.isfinite(loss):
|
| 110 |
-
raise ValueError(f"{stage} epoch has no usable labels or a nonfinite loss")
|
| 111 |
-
self.log(f"{stage}_loss", loss, on_epoch=True)
|
| 112 |
-
for name, value in metrics.compute().items():
|
| 113 |
-
self.log(name, value, on_epoch=True, prog_bar=name == "val_iou_macro")
|
| 114 |
-
with torch.inference_mode(False):
|
| 115 |
-
metrics.reset()
|
| 116 |
-
average.reset()
|
| 117 |
-
|
| 118 |
-
def training_step(self, batch, batch_idx):
|
| 119 |
-
return self._step(batch, "train")
|
| 120 |
-
|
| 121 |
-
def validation_step(self, batch, batch_idx):
|
| 122 |
-
return self._step(batch, "val")
|
| 123 |
-
|
| 124 |
-
def test_step(self, batch, batch_idx):
|
| 125 |
-
return self._step(batch, "test")
|
| 126 |
-
|
| 127 |
-
def predict_step(self, batch, batch_idx):
|
| 128 |
-
inputs = {name: value for name, value in batch.items() if name != "target"}
|
| 129 |
-
return self(**inputs)
|
| 130 |
-
|
| 131 |
-
def on_train_epoch_end(self):
|
| 132 |
-
self._log_epoch("train")
|
| 133 |
-
|
| 134 |
-
def on_validation_epoch_end(self):
|
| 135 |
-
self._log_epoch("val")
|
| 136 |
-
|
| 137 |
-
def on_test_epoch_end(self):
|
| 138 |
-
self._log_epoch("test")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The sample this method trains on, and the DataModule that batches it."""
|
| 2 |
+
|
| 3 |
+
from typing import Any, TypedDict
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from lightning import LightningDataModule
|
| 7 |
+
from torch.utils.data import DataLoader, Dataset
|
| 8 |
+
|
| 9 |
+
from geosave.ml.transforms import ImageAugmenter
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Sample(TypedDict):
|
| 13 |
+
"""One whole scene, as `SceneDataset` returns it.
|
| 14 |
+
|
| 15 |
+
A collated batch holds the same keys with a leading batch axis.
|
| 16 |
+
|
| 17 |
+
Attributes:
|
| 18 |
+
image: float32 `(band, y, x)` pixels as the preprocessor prepared them.
|
| 19 |
+
target: int64 `(y, x)` class ids, `ignore_index` where unknown.
|
| 20 |
+
transform: float64 `(6,)` affine coefficients of the scene's grid.
|
| 21 |
+
crs: int64 EPSG code of the scene's grid.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
image: torch.Tensor
|
| 25 |
+
target: torch.Tensor
|
| 26 |
+
transform: torch.Tensor
|
| 27 |
+
crs: torch.Tensor
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class DataModule(LightningDataModule):
|
| 31 |
+
"""Batch whole scenes; crop and augment training batches on the device.
|
| 32 |
+
|
| 33 |
+
Scenes are 510 x 510 px, so they batch whole. A training batch is cut to
|
| 34 |
+
`crop_size` and augmented by the Kornia steps of `augmentations`, image
|
| 35 |
+
and target together. Validation batches stay whole scenes, which the
|
| 36 |
+
Module predicts chip by chip as a release does.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
train: Training dataset returning a `Sample` per scene.
|
| 40 |
+
val: Validation dataset returning a `Sample` per scene.
|
| 41 |
+
test: Optional final evaluation dataset, unused during fit.
|
| 42 |
+
augmentations: Kornia augmentations by `name` and `init_args`, run in
|
| 43 |
+
order on training batches. List `RandomCrop` first.
|
| 44 |
+
crop_size: Height and width in pixels `RandomCrop` cuts.
|
| 45 |
+
ignore_index: Label a target pixel takes where an augmentation
|
| 46 |
+
invented it; the datasets' and the Module's `ignore_index`.
|
| 47 |
+
batch_size: Training scenes per batch.
|
| 48 |
+
eval_batch_size: Validation scenes per batch.
|
| 49 |
+
num_workers: DataLoader worker processes.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def __init__(
|
| 53 |
+
self,
|
| 54 |
+
train: Dataset,
|
| 55 |
+
val: Dataset,
|
| 56 |
+
augmentations: list[dict[str, Any]],
|
| 57 |
+
crop_size: int,
|
| 58 |
+
ignore_index: int,
|
| 59 |
+
batch_size: int,
|
| 60 |
+
eval_batch_size: int,
|
| 61 |
+
num_workers: int,
|
| 62 |
+
test: Dataset | None = None,
|
| 63 |
+
) -> None:
|
| 64 |
+
super().__init__()
|
| 65 |
+
self.train_dataset = train
|
| 66 |
+
self.val_dataset = val
|
| 67 |
+
self.test_dataset = test
|
| 68 |
+
self.augmenter = ImageAugmenter(augmentations, crop_size)
|
| 69 |
+
self.ignore_index = ignore_index
|
| 70 |
+
self.batch_size = batch_size
|
| 71 |
+
self.eval_batch_size = eval_batch_size
|
| 72 |
+
self.num_workers = num_workers
|
| 73 |
+
|
| 74 |
+
def train_dataloader(self) -> DataLoader:
|
| 75 |
+
"""Return shuffled batches of whole training scenes."""
|
| 76 |
+
return DataLoader(
|
| 77 |
+
self.train_dataset,
|
| 78 |
+
batch_size=self.batch_size,
|
| 79 |
+
shuffle=True,
|
| 80 |
+
drop_last=True,
|
| 81 |
+
num_workers=self.num_workers,
|
| 82 |
+
persistent_workers=self.num_workers > 0,
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
def val_dataloader(self) -> DataLoader:
|
| 86 |
+
"""Return batches of whole validation scenes, in order."""
|
| 87 |
+
return DataLoader(
|
| 88 |
+
self.val_dataset,
|
| 89 |
+
batch_size=self.eval_batch_size,
|
| 90 |
+
shuffle=False,
|
| 91 |
+
num_workers=self.num_workers,
|
| 92 |
+
persistent_workers=self.num_workers > 0,
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
def test_dataloader(self) -> DataLoader:
|
| 96 |
+
"""Read the held-out evaluation cohort only for an explicit test run."""
|
| 97 |
+
if self.test_dataset is None:
|
| 98 |
+
raise ValueError("configure a test dataset before running test")
|
| 99 |
+
return DataLoader(
|
| 100 |
+
self.test_dataset,
|
| 101 |
+
batch_size=self.eval_batch_size,
|
| 102 |
+
shuffle=False,
|
| 103 |
+
num_workers=self.num_workers,
|
| 104 |
+
persistent_workers=self.num_workers > 0,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
def on_after_batch_transfer(self, batch: Sample, dataloader_idx: int) -> Sample:
|
| 108 |
+
"""Crop and augment a training batch; leave every other batch as it is."""
|
| 109 |
+
if self.trainer is None or not self.trainer.training:
|
| 110 |
+
return batch
|
| 111 |
+
|
| 112 |
+
image = batch["image"]
|
| 113 |
+
target = batch["target"]
|
| 114 |
+
|
| 115 |
+
# Kornia fills the pixels an augmentation invents with zero, so class
|
| 116 |
+
# ids move up by one and zero means "unknown" while augmenting.
|
| 117 |
+
shifted = (target + 1).masked_fill(target == self.ignore_index, 0).float()
|
| 118 |
+
image, shifted = self.augmenter(image, shifted, data_keys=["input", "mask"])
|
| 119 |
+
target = shifted.round().long() - 1
|
| 120 |
+
target = target.masked_fill(target < 0, self.ignore_index)
|
| 121 |
+
|
| 122 |
+
# The crop moved the pixels without moving `transform`: the grid of a
|
| 123 |
+
# training batch is no longer exact, and training does not read it.
|
| 124 |
+
return {
|
| 125 |
+
"image": image,
|
| 126 |
+
"target": target,
|
| 127 |
+
"transform": batch["transform"],
|
| 128 |
+
"crs": batch["crs"],
|
| 129 |
+
}
|
modules/supervised/datasets.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read Dynamic World scenes: one image GeoTIFF and its label GeoTIFF per sample."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
import geopandas as gpd
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
import xarray as xr
|
| 10 |
+
from torch.utils.data import Dataset
|
| 11 |
+
|
| 12 |
+
import geosave as gs
|
| 13 |
+
from geosave.ml.factory import BuildSpec
|
| 14 |
+
from geosave.ml.processing.raster.preprocessing.base import PREPROCESSORS
|
| 15 |
+
|
| 16 |
+
from .data import Sample
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class SceneDataset(Dataset[Sample]):
|
| 20 |
+
"""Read one whole scene and its class labels per index.
|
| 21 |
+
|
| 22 |
+
Selection is explicit in the annotation catalogue. Multiple annotations may
|
| 23 |
+
share one image; each returned sample uses its own original label file.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
table: Ingestion GeoParquet; paths resolve relative to this file.
|
| 27 |
+
split: train, val or test.
|
| 28 |
+
source_groups: Annotation sources to include, e.g. experts and non_expert.
|
| 29 |
+
preprocessor: Native preprocessing component specification.
|
| 30 |
+
ignore_index: In-memory ignored target value.
|
| 31 |
+
label_scheme: Original-code remapping and class metadata.
|
| 32 |
+
voting_rule: Composite to select; None selects individual annotations.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
table: str,
|
| 38 |
+
split: str,
|
| 39 |
+
source_groups: list[str],
|
| 40 |
+
preprocessor: BuildSpec,
|
| 41 |
+
ignore_index: int,
|
| 42 |
+
label_scheme: dict[str, Any],
|
| 43 |
+
voting_rule: str | None = None,
|
| 44 |
+
) -> None:
|
| 45 |
+
root = Path(table).parent
|
| 46 |
+
scenes_df = gpd.read_parquet(table)
|
| 47 |
+
selected_df = scenes_df.loc[
|
| 48 |
+
(scenes_df["split"] == split)
|
| 49 |
+
& scenes_df["source_group"].isin(source_groups)
|
| 50 |
+
& (scenes_df["status"] == "written")
|
| 51 |
+
]
|
| 52 |
+
if voting_rule is None:
|
| 53 |
+
selected_df = selected_df.loc[selected_df["voting_rule"].isna()]
|
| 54 |
+
else:
|
| 55 |
+
selected_df = selected_df.loc[selected_df["voting_rule"] == voting_rule]
|
| 56 |
+
|
| 57 |
+
if selected_df.empty:
|
| 58 |
+
raise ValueError(
|
| 59 |
+
f"no completed annotations for {split}/{source_groups}/{voting_rule}"
|
| 60 |
+
)
|
| 61 |
+
duplicate_columns = (
|
| 62 |
+
["scene_id", "source_group"] if split == "train" else ["scene_id"]
|
| 63 |
+
)
|
| 64 |
+
if selected_df.duplicated(duplicate_columns).any():
|
| 65 |
+
raise ValueError("select one annotation per scene and training source")
|
| 66 |
+
|
| 67 |
+
self.images = [root / path for path in selected_df.image_path]
|
| 68 |
+
self.labels = [root / path for path in selected_df.label_path]
|
| 69 |
+
|
| 70 |
+
self.preprocessor = PREPROCESSORS.build(preprocessor)
|
| 71 |
+
self.ignore_index = ignore_index
|
| 72 |
+
self.label_scheme = label_scheme
|
| 73 |
+
if label_scheme["ignore_index"] != ignore_index:
|
| 74 |
+
raise ValueError("label scheme and loss must use the same ignore_index")
|
| 75 |
+
self.class_of_code = np.full(256, ignore_index, dtype="int64")
|
| 76 |
+
for code, class_id in label_scheme["remap"].items():
|
| 77 |
+
self.class_of_code[int(code)] = class_id
|
| 78 |
+
|
| 79 |
+
def __len__(self) -> int:
|
| 80 |
+
"""Return the number of scenes."""
|
| 81 |
+
return len(self.images)
|
| 82 |
+
|
| 83 |
+
def __getitem__(self, index: int) -> Sample:
|
| 84 |
+
"""Read one scene as tensors.
|
| 85 |
+
|
| 86 |
+
Raises:
|
| 87 |
+
ValueError: The label is not one band on the image grid, or has
|
| 88 |
+
values outside the original annotation codes 0–10.
|
| 89 |
+
"""
|
| 90 |
+
with (
|
| 91 |
+
gs.open_raster(self.images[index]) as image,
|
| 92 |
+
gs.open_raster(self.labels[index]) as label,
|
| 93 |
+
):
|
| 94 |
+
rasters = xr.DataTree.from_dict({"image": image})
|
| 95 |
+
prepared = self.preprocessor(rasters)["image"].to_dataset()
|
| 96 |
+
|
| 97 |
+
if len(label.data_vars) != 1:
|
| 98 |
+
raise ValueError("expected one original annotation band")
|
| 99 |
+
codes = next(iter(label.data_vars.values())).values
|
| 100 |
+
if label.gs.geobox != prepared.gs.geobox:
|
| 101 |
+
raise ValueError(f"{self.labels[index]} is not on its image's grid")
|
| 102 |
+
if not np.isin(codes, np.arange(11)).all():
|
| 103 |
+
raise ValueError(
|
| 104 |
+
f"{self.labels[index]} is not original annotation codes 0–10"
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
sample = prepared.gs.to_tensor("image", dtype="float32", grid=True)
|
| 108 |
+
target = torch.from_numpy(self.class_of_code[codes.astype("uint8")])
|
| 109 |
+
|
| 110 |
+
return {
|
| 111 |
+
"image": sample["image"],
|
| 112 |
+
"target": target,
|
| 113 |
+
"transform": sample["transform"],
|
| 114 |
+
"crs": sample["crs"],
|
| 115 |
+
}
|
modules/supervised/module.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Supervised segmentation: train on crops, validate on whole scenes."""
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from lightning import LightningModule
|
| 5 |
+
from torch.utils.data import default_collate
|
| 6 |
+
|
| 7 |
+
from geosave.geodata.sampling import ChipMode, MergeWindow, TensorChipper, TensorMerger
|
| 8 |
+
from geosave.ml import build_model
|
| 9 |
+
from geosave.ml.builders.criterion import CRITERIA
|
| 10 |
+
from geosave.ml.builders.optimizer import OPTIMIZERS
|
| 11 |
+
from geosave.ml.builders.scheduler import SCHEDULERS
|
| 12 |
+
from geosave.ml.factory import BuildSpec
|
| 13 |
+
from geosave.ml.metrics import MulticlassMetrics
|
| 14 |
+
|
| 15 |
+
from .data import Sample
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Module(LightningModule):
|
| 19 |
+
"""Train on random crops; score validation on whole scenes, chip by chip.
|
| 20 |
+
|
| 21 |
+
Every argument is required, so a config states the whole experiment.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
encoder: Encoder stage by registered `name` with `init_args`.
|
| 25 |
+
decoder: Decoder stage by registered `name` with `init_args`.
|
| 26 |
+
head: Head stage by registered `name` with `init_args`; its
|
| 27 |
+
`num_classes` is the class count of loss and metrics.
|
| 28 |
+
ignore_index: Target value left out of loss and metrics.
|
| 29 |
+
criterion: Loss by `name` with `init_args`; its `ignore_index` must
|
| 30 |
+
equal `ignore_index`.
|
| 31 |
+
optimizer: Optimizer by `name` with `init_args`; its `lr` is the
|
| 32 |
+
decoder's and the head's learning rate.
|
| 33 |
+
encoder_lr: Learning rate of the encoder.
|
| 34 |
+
lr_scheduler: Scheduler by `name` with `init_args`, stepped once an epoch.
|
| 35 |
+
metrics: Metric names, such as `iou.macro`.
|
| 36 |
+
chip_size: Height and width in pixels of a validation chip; the
|
| 37 |
+
model's input size.
|
| 38 |
+
chip_stride: Pixels between validation chip starts.
|
| 39 |
+
chip_mode: How validation chips meet a scene's edge.
|
| 40 |
+
merge_window: Taper weighting each chip where validation chips overlap.
|
| 41 |
+
chip_batch_size: Validation chips predicted at once.
|
| 42 |
+
|
| 43 |
+
Raises:
|
| 44 |
+
ValueError: The criterion ignores another value than `ignore_index`.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
*,
|
| 50 |
+
encoder: BuildSpec,
|
| 51 |
+
decoder: BuildSpec,
|
| 52 |
+
head: BuildSpec,
|
| 53 |
+
ignore_index: int,
|
| 54 |
+
criterion: BuildSpec,
|
| 55 |
+
optimizer: BuildSpec,
|
| 56 |
+
encoder_lr: float,
|
| 57 |
+
lr_scheduler: BuildSpec,
|
| 58 |
+
metrics: list[str],
|
| 59 |
+
chip_size: int,
|
| 60 |
+
chip_stride: int,
|
| 61 |
+
chip_mode: ChipMode,
|
| 62 |
+
merge_window: MergeWindow,
|
| 63 |
+
chip_batch_size: int,
|
| 64 |
+
) -> None:
|
| 65 |
+
super().__init__()
|
| 66 |
+
self.save_hyperparameters()
|
| 67 |
+
|
| 68 |
+
if criterion.init_args["ignore_index"] != ignore_index:
|
| 69 |
+
raise ValueError("criterion init_args.ignore_index must equal ignore_index")
|
| 70 |
+
|
| 71 |
+
self.ignore_index = ignore_index
|
| 72 |
+
self.optimizer_spec = optimizer
|
| 73 |
+
self.encoder_lr = encoder_lr
|
| 74 |
+
self.scheduler_spec = lr_scheduler
|
| 75 |
+
self.chip_size = chip_size
|
| 76 |
+
self.chip_stride = chip_stride
|
| 77 |
+
self.chip_mode: ChipMode = chip_mode
|
| 78 |
+
self.merge_window: MergeWindow = merge_window
|
| 79 |
+
self.chip_batch_size = chip_batch_size
|
| 80 |
+
|
| 81 |
+
self.model = build_model({"encoder": encoder, "decoder": decoder, "head": head})
|
| 82 |
+
self.criterion = CRITERIA.build(criterion)
|
| 83 |
+
|
| 84 |
+
num_classes = self.model.head.num_classes
|
| 85 |
+
self.train_metrics = MulticlassMetrics(
|
| 86 |
+
num_classes, ignore_index=ignore_index, metrics=metrics
|
| 87 |
+
).clone(prefix="train_")
|
| 88 |
+
self.val_metrics = MulticlassMetrics(
|
| 89 |
+
num_classes, ignore_index=ignore_index, metrics=metrics
|
| 90 |
+
).clone(prefix="val_")
|
| 91 |
+
|
| 92 |
+
self.test_metrics = MulticlassMetrics(
|
| 93 |
+
num_classes, ignore_index=ignore_index, metrics=metrics
|
| 94 |
+
).clone(prefix="test_")
|
| 95 |
+
|
| 96 |
+
def configure_optimizers(self) -> dict:
|
| 97 |
+
"""Return the optimizer over three parameter groups and its scheduler."""
|
| 98 |
+
# The encoder takes its own rate; the decoder and the head take the optimizer's.
|
| 99 |
+
parameter_groups = [
|
| 100 |
+
{"params": self.model.encoder.parameters(), "lr": self.encoder_lr},
|
| 101 |
+
{"params": self.model.decoder.parameters()},
|
| 102 |
+
{"params": self.model.head.parameters()},
|
| 103 |
+
]
|
| 104 |
+
optimizer = OPTIMIZERS.build(self.optimizer_spec, parameter_groups)
|
| 105 |
+
scheduler = SCHEDULERS.build(self.scheduler_spec, optimizer)
|
| 106 |
+
|
| 107 |
+
return {
|
| 108 |
+
"optimizer": optimizer,
|
| 109 |
+
"lr_scheduler": {"scheduler": scheduler, "interval": "epoch"},
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
def forward(self, image: torch.Tensor) -> torch.Tensor:
|
| 113 |
+
"""Return logits shaped `(batch, class, y, x)` for an image batch."""
|
| 114 |
+
return self.model(image=image)
|
| 115 |
+
|
| 116 |
+
def predict_chips(self, batch: Sample) -> torch.Tensor:
|
| 117 |
+
"""Predict whole scenes chip by chip and merge the chips' logits.
|
| 118 |
+
|
| 119 |
+
The scenes are cut into chips of `chip_size` every `chip_stride`
|
| 120 |
+
pixels, each chip is predicted alone, and overlapping logits are
|
| 121 |
+
averaged under `merge_window`: what a release's predictor does with
|
| 122 |
+
the same settings.
|
| 123 |
+
|
| 124 |
+
Args:
|
| 125 |
+
batch: Whole scenes on one grid shape, with their `transform` and `crs`.
|
| 126 |
+
|
| 127 |
+
Returns:
|
| 128 |
+
Logits shaped `(batch, class, y, x)` on the scenes' grid.
|
| 129 |
+
"""
|
| 130 |
+
chipper = TensorChipper(
|
| 131 |
+
batch,
|
| 132 |
+
pixels=["image"],
|
| 133 |
+
size=self.chip_size,
|
| 134 |
+
stride=self.chip_stride,
|
| 135 |
+
mode=self.chip_mode,
|
| 136 |
+
)
|
| 137 |
+
merger = TensorMerger(chipper.layout, window=self.merge_window)
|
| 138 |
+
|
| 139 |
+
for start in range(0, len(chipper), self.chip_batch_size):
|
| 140 |
+
stop = min(start + self.chip_batch_size, len(chipper))
|
| 141 |
+
|
| 142 |
+
chips = []
|
| 143 |
+
for index in range(start, stop):
|
| 144 |
+
chips.append(chipper[index])
|
| 145 |
+
chips = default_collate(chips)
|
| 146 |
+
|
| 147 |
+
chip_logits = self(chips["image"])
|
| 148 |
+
for index, logits in zip(range(start, stop), chip_logits, strict=True):
|
| 149 |
+
merger.add(index, logits)
|
| 150 |
+
|
| 151 |
+
return merger.merge()
|
| 152 |
+
|
| 153 |
+
def training_step(self, batch: Sample, batch_idx: int) -> torch.Tensor:
|
| 154 |
+
"""Return the loss of a batch of crops and log it with the metrics."""
|
| 155 |
+
target = batch["target"]
|
| 156 |
+
logits = self(batch["image"])
|
| 157 |
+
|
| 158 |
+
if target.ne(self.ignore_index).any():
|
| 159 |
+
loss = self.criterion(logits, target)
|
| 160 |
+
self.train_metrics.update(logits, target)
|
| 161 |
+
else:
|
| 162 |
+
# Cross entropy over no known pixel is NaN; such a batch trains nothing.
|
| 163 |
+
loss = logits.sum() * 0
|
| 164 |
+
|
| 165 |
+
self.log("train_loss", loss, on_epoch=True, prog_bar=True)
|
| 166 |
+
self.log_dict(self.train_metrics, on_step=False, on_epoch=True)
|
| 167 |
+
|
| 168 |
+
return loss
|
| 169 |
+
|
| 170 |
+
def validation_step(self, batch: Sample, batch_idx: int) -> None:
|
| 171 |
+
"""Score the merged logits of whole scenes and log loss and metrics."""
|
| 172 |
+
target = batch["target"]
|
| 173 |
+
logits = self.predict_chips(batch)
|
| 174 |
+
|
| 175 |
+
loss = self.criterion(logits, target)
|
| 176 |
+
self.val_metrics.update(logits, target)
|
| 177 |
+
|
| 178 |
+
self.log("val_loss", loss, on_epoch=True, prog_bar=True, batch_size=len(target))
|
| 179 |
+
self.log_dict(self.val_metrics, on_step=False, on_epoch=True)
|
| 180 |
+
|
| 181 |
+
def test_step(self, batch: Sample, batch_idx: int) -> None:
|
| 182 |
+
"""Score final held-out scenes independently of validation metrics."""
|
| 183 |
+
target = batch["target"]
|
| 184 |
+
logits = self.predict_chips(batch)
|
| 185 |
+
|
| 186 |
+
loss = self.criterion(logits, target)
|
| 187 |
+
self.test_metrics.update(logits, target)
|
| 188 |
+
|
| 189 |
+
self.log("test_loss", loss, on_epoch=True, batch_size=len(target))
|
| 190 |
+
self.log_dict(self.test_metrics, on_step=False, on_epoch=True)
|
project.yaml
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
task: segmentation
|
| 2 |
+
data: data
|
requirements.txt
CHANGED
|
@@ -2,6 +2,4 @@
|
|
| 2 |
-e ../..[ml]
|
| 3 |
tensorboard
|
| 4 |
typer
|
| 5 |
-
|
| 6 |
-
tqdm
|
| 7 |
-
openpyxl
|
|
|
|
| 2 |
-e ../..[ml]
|
| 3 |
tensorboard
|
| 4 |
typer
|
| 5 |
+
pyyaml
|
|
|
|
|
|
scripts/download_dynamic_world.py
DELETED
|
@@ -1,106 +0,0 @@
|
|
| 1 |
-
"""Download every Dynamic World label release.
|
| 2 |
-
|
| 3 |
-
uv run python workspace/dynamicworld/scripts/download_dynamic_world.py
|
| 4 |
-
|
| 5 |
-
writes workspace/dynamicworld/data/raw/<subset>/; a subset already downloaded
|
| 6 |
-
is skipped. Each label is extracted straight from the remote archive, so the
|
| 7 |
-
test release's model probabilities, 3.9 of its 3.9 GB, are never fetched.
|
| 8 |
-
"""
|
| 9 |
-
|
| 10 |
-
import time
|
| 11 |
-
from tempfile import TemporaryDirectory
|
| 12 |
-
|
| 13 |
-
import requests
|
| 14 |
-
from pathlib import Path
|
| 15 |
-
from zipfile import ZipFile, ZipInfo
|
| 16 |
-
|
| 17 |
-
import fsspec
|
| 18 |
-
import typer
|
| 19 |
-
from aiohttp import ClientResponseError
|
| 20 |
-
from tqdm import tqdm
|
| 21 |
-
|
| 22 |
-
PANGAEA = "https://download.pangaea.de/dataset/933475/files"
|
| 23 |
-
URLS = {
|
| 24 |
-
"experts": f"{PANGAEA}/Experts_tiles.zip",
|
| 25 |
-
"non_expert": f"{PANGAEA}/Non_expert_tiles.zip",
|
| 26 |
-
"validation": f"{PANGAEA}/validation_set_tiles.zip",
|
| 27 |
-
"test": "https://zenodo.org/records/4766508/files/dw_test.zip?download=1",
|
| 28 |
-
}
|
| 29 |
-
RAW = Path(__file__).resolve().parents[1] / "data" / "raw"
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
def extract(files: ZipFile, member: ZipInfo, folder: Path) -> None:
|
| 33 |
-
"""Extract one member, waiting out the server's rate limit as it asks."""
|
| 34 |
-
while True:
|
| 35 |
-
try:
|
| 36 |
-
files.extract(member, folder)
|
| 37 |
-
return
|
| 38 |
-
except ClientResponseError as error:
|
| 39 |
-
# Zenodo allows 133 requests a minute and names the wait itself.
|
| 40 |
-
if error.status != 429 or error.headers is None:
|
| 41 |
-
raise
|
| 42 |
-
time.sleep(int(error.headers.get("Retry-After", 60)))
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
def download(url: str, folder: Path) -> None:
|
| 46 |
-
"""Download annotation archives; range-read only the probability-heavy test ZIP."""
|
| 47 |
-
partial = folder.with_suffix(".partial")
|
| 48 |
-
with TemporaryDirectory(dir=folder.parent) as temporary:
|
| 49 |
-
if "dw_test.zip" in url:
|
| 50 |
-
remote = fsspec.filesystem("https").open(url, block_size=2**16)
|
| 51 |
-
else:
|
| 52 |
-
archive = Path(temporary) / "labels.zip"
|
| 53 |
-
with requests.get(url, stream=True, timeout=120) as response:
|
| 54 |
-
response.raise_for_status()
|
| 55 |
-
with archive.open("wb") as output:
|
| 56 |
-
for chunk in response.iter_content(2**20):
|
| 57 |
-
output.write(chunk)
|
| 58 |
-
remote = archive.open("rb")
|
| 59 |
-
with remote, ZipFile(remote) as files:
|
| 60 |
-
members = []
|
| 61 |
-
for member in files.infolist():
|
| 62 |
-
if member.is_dir() or member.filename.startswith("__MACOSX"):
|
| 63 |
-
continue
|
| 64 |
-
if Path(member.filename).name.startswith("probs_"):
|
| 65 |
-
continue
|
| 66 |
-
members.append(member)
|
| 67 |
-
for member in tqdm(members, desc=folder.name, unit="file"):
|
| 68 |
-
extract(files, member, partial)
|
| 69 |
-
partial.rename(folder)
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
def download_metadata(raw: Path) -> None:
|
| 73 |
-
"""Fetch the separately published training workbook and source README."""
|
| 74 |
-
for name in ("v1_dw_tile_metadata_for_public_release.xlsx", "README.txt"):
|
| 75 |
-
path = raw / name
|
| 76 |
-
if path.exists():
|
| 77 |
-
continue
|
| 78 |
-
|
| 79 |
-
partial = path.with_suffix(path.suffix + ".partial")
|
| 80 |
-
with requests.get(f"{PANGAEA}/{name}", stream=True, timeout=120) as response:
|
| 81 |
-
response.raise_for_status()
|
| 82 |
-
with partial.open("wb") as output:
|
| 83 |
-
for chunk in response.iter_content(2**20):
|
| 84 |
-
output.write(chunk)
|
| 85 |
-
|
| 86 |
-
partial.replace(path)
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
def main(raw: Path = RAW, subset: str | None = None) -> None:
|
| 90 |
-
"""Download all releases, or one named subset, into RAW."""
|
| 91 |
-
if subset is not None and subset not in URLS:
|
| 92 |
-
raise typer.BadParameter(f"choose one of {', '.join(URLS)}")
|
| 93 |
-
raw.mkdir(parents=True, exist_ok=True)
|
| 94 |
-
download_metadata(raw)
|
| 95 |
-
|
| 96 |
-
urls = URLS if subset is None else {subset: URLS[subset]}
|
| 97 |
-
for name, url in urls.items():
|
| 98 |
-
folder = raw / name
|
| 99 |
-
if folder.exists():
|
| 100 |
-
print(f"already downloaded: {folder}")
|
| 101 |
-
continue
|
| 102 |
-
download(url, folder)
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
if __name__ == "__main__":
|
| 106 |
-
typer.run(main)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
scripts/ingest_dynamic_world.py
DELETED
|
@@ -1,197 +0,0 @@
|
|
| 1 |
-
"""Download the Sentinel-2 L2A image of every labelled Dynamic World scene.
|
| 2 |
-
|
| 3 |
-
uv run python -m scripts.ingest_dynamic_world --source experts --source expert_composites
|
| 4 |
-
uv run python -m scripts.ingest_dynamic_world --source experts --source expert_composites --bbox 95,-11,141,6
|
| 5 |
-
|
| 6 |
-
Run from the workspace root.
|
| 7 |
-
|
| 8 |
-
label file ──▶ search the label's day ──▶ load onto the label's grid ──▶ images/{scene}.tif
|
| 9 |
-
|
| 10 |
-
All labels of one scene share its grid, so one image serves every label of it.
|
| 11 |
-
Existing images are skipped, so a rerun downloads only what is missing.
|
| 12 |
-
"""
|
| 13 |
-
|
| 14 |
-
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 15 |
-
from pathlib import Path
|
| 16 |
-
|
| 17 |
-
import pandas as pd
|
| 18 |
-
import pystac
|
| 19 |
-
import typer
|
| 20 |
-
import xarray as xr
|
| 21 |
-
from tqdm import tqdm
|
| 22 |
-
|
| 23 |
-
import geosave # noqa: F401 registers the .gs accessors
|
| 24 |
-
import geosave.geodata.attrs as attrs
|
| 25 |
-
from geosave.geodata import io, stac
|
| 26 |
-
from geosave.geodata.stac import StacClient, StacQuery
|
| 27 |
-
|
| 28 |
-
from modules.segmentation.supervised.datasets import DATA, SOURCES, find_labels
|
| 29 |
-
|
| 30 |
-
# Planetary Computer's L2A; its STAC states no scale or offset (see read_esa_packing).
|
| 31 |
-
COLLECTION = "sentinel-2-l2a"
|
| 32 |
-
|
| 33 |
-
# The 10 m and 20 m bands the Dynamic World model reads (Brown et al., 2022).
|
| 34 |
-
BANDS = ["B02", "B03", "B04", "B05", "B06", "B07", "B08", "B8A", "B11", "B12"]
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def find_scenes(sources: list[str], bbox: str | None) -> pd.DataFrame:
|
| 38 |
-
"""Return one label row per scene the chosen sources annotate.
|
| 39 |
-
|
| 40 |
-
Args:
|
| 41 |
-
sources: Label sources, keys of `SOURCES`.
|
| 42 |
-
bbox: "west,south,east,north" in degrees, or None for every scene.
|
| 43 |
-
"""
|
| 44 |
-
labels = find_labels()
|
| 45 |
-
labels = labels[labels["source"].isin(sources)]
|
| 46 |
-
|
| 47 |
-
if bbox is not None:
|
| 48 |
-
west, south, east, north = [float(value) for value in bbox.split(",")]
|
| 49 |
-
inside = labels["lon"].between(west, east) & labels["lat"].between(south, north)
|
| 50 |
-
labels = labels[inside]
|
| 51 |
-
|
| 52 |
-
# Every label of a scene shares its grid, so the first one places the image.
|
| 53 |
-
return labels.drop_duplicates("scene")
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
def search_items(
|
| 57 |
-
client: StacClient, label: xr.Dataset, date: pd.Timestamp
|
| 58 |
-
) -> list[pystac.Item]:
|
| 59 |
-
"""Find the acquisitions covering the label on its day."""
|
| 60 |
-
region = label.gs.region.replace(timespan=f"{date:%Y-%m-%d}")
|
| 61 |
-
query = StacQuery(collections=[COLLECTION]).set_region(region)
|
| 62 |
-
|
| 63 |
-
return client.search_items(query)
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
def drop_superseded(items: list[pystac.Item]) -> list[pystac.Item]:
|
| 67 |
-
"""Keep only the newest processing of each tile acquisition.
|
| 68 |
-
|
| 69 |
-
Planetary Computer lists an acquisition once per ESA processing, e.g. the
|
| 70 |
-
2020 original (baseline 02.12) and the 2023 reprocessing (05.00). Their
|
| 71 |
-
ids differ only in the last field, the processing time. ODC would fuse
|
| 72 |
-
both as one observation, so the first listed would silently win.
|
| 73 |
-
"""
|
| 74 |
-
newest = {}
|
| 75 |
-
for item in items:
|
| 76 |
-
acquisition, processed = item.id.rsplit("_", 1)
|
| 77 |
-
if acquisition not in newest or processed > newest[acquisition][0]:
|
| 78 |
-
newest[acquisition] = (processed, item)
|
| 79 |
-
|
| 80 |
-
kept = []
|
| 81 |
-
for _, item in newest.values():
|
| 82 |
-
kept.append(item)
|
| 83 |
-
return kept
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
def read_esa_packing(items: list[pystac.Item]) -> attrs.CFPacking:
|
| 87 |
-
"""Derive reflectance decoding from ESA's product format and processing baseline.
|
| 88 |
-
|
| 89 |
-
Planetary Computer's STAC states no scale or offset, only the ESA
|
| 90 |
-
processing baseline (`s2:processing_baseline`, the `N0500` of a product
|
| 91 |
-
name). ESA: reflectance = (DN + BOA_ADD_OFFSET) / 10000, where
|
| 92 |
-
BOA_ADD_OFFSET is -1000 from baseline 04.00 and 0 before
|
| 93 |
-
(https://forum.step.esa.int/t/35431). Tiles of different baselines
|
| 94 |
-
decode differently, so one image must not mosaic them.
|
| 95 |
-
"""
|
| 96 |
-
baselines = set()
|
| 97 |
-
for item in items:
|
| 98 |
-
baselines.add(item.properties["s2:processing_baseline"])
|
| 99 |
-
if len(baselines) != 1:
|
| 100 |
-
raise ValueError(f"tiles mix processing baselines {sorted(baselines)}")
|
| 101 |
-
|
| 102 |
-
offset = -0.1 if float(baselines.pop()) >= 4 else 0.0
|
| 103 |
-
return attrs.CFPacking(scale_factor=1e-4, add_offset=offset, fill_value=0)
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
def load_image(client: StacClient, label_path: Path, date: pd.Timestamp) -> xr.Dataset:
|
| 107 |
-
"""Load the label day's acquisition onto the label's grid.
|
| 108 |
-
|
| 109 |
-
Neighbouring tiles of one pass are mosaicked into one image.
|
| 110 |
-
"""
|
| 111 |
-
label = io.open_geotiff(label_path, chunks=None)
|
| 112 |
-
items = drop_superseded(search_items(client, label, date))
|
| 113 |
-
packing = read_esa_packing(items)
|
| 114 |
-
|
| 115 |
-
image = stac.load_dataset(
|
| 116 |
-
items,
|
| 117 |
-
label.gs.geobox,
|
| 118 |
-
bands=BANDS,
|
| 119 |
-
resampling="bilinear",
|
| 120 |
-
dtype="uint16",
|
| 121 |
-
nodata=0,
|
| 122 |
-
chunks=None,
|
| 123 |
-
patch_url=client.patch_url,
|
| 124 |
-
)
|
| 125 |
-
|
| 126 |
-
# The label annotates one acquisition; several would be a different image per tile.
|
| 127 |
-
if image.sizes["time"] != 1:
|
| 128 |
-
raise ValueError(f"expected one acquisition on {date:%Y-%m-%d}, found {image.sizes['time']}")
|
| 129 |
-
|
| 130 |
-
image = image.isel(time=0)
|
| 131 |
-
return image.gs.write_packing(packing)
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
def write_image(image: xr.Dataset, path: Path) -> None:
|
| 135 |
-
"""Write the image as a COG, renaming it into place only once it is complete.
|
| 136 |
-
|
| 137 |
-
A rerun skips existing files, so a half-written one must never sit at `path`.
|
| 138 |
-
"""
|
| 139 |
-
partial = path.with_suffix(".partial.tif")
|
| 140 |
-
io.write_cog(image, partial, overwrite=True)
|
| 141 |
-
partial.replace(path)
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
def download_scene(client: StacClient, scene: pd.Series, folder: Path) -> None:
|
| 145 |
-
"""Load and write one scene's image."""
|
| 146 |
-
image = load_image(client, scene["path"], scene["date"])
|
| 147 |
-
write_image(image, folder / f"{scene['scene']}.tif")
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
def download_scenes(
|
| 151 |
-
client: StacClient, scenes: pd.DataFrame, folder: Path, threads: int
|
| 152 |
-
) -> list[tuple[str, str]]:
|
| 153 |
-
"""Download every scene not yet in `folder`, several at a time.
|
| 154 |
-
|
| 155 |
-
Returns:
|
| 156 |
-
(scene, error) for each scene that failed.
|
| 157 |
-
"""
|
| 158 |
-
failures = []
|
| 159 |
-
with ThreadPoolExecutor(threads) as pool:
|
| 160 |
-
futures = {}
|
| 161 |
-
for _, scene in scenes.iterrows():
|
| 162 |
-
if (folder / f"{scene['scene']}.tif").exists():
|
| 163 |
-
continue
|
| 164 |
-
future = pool.submit(download_scene, client, scene, folder)
|
| 165 |
-
futures[future] = scene["scene"]
|
| 166 |
-
|
| 167 |
-
for future in tqdm(as_completed(futures), total=len(futures), unit="scene"):
|
| 168 |
-
try:
|
| 169 |
-
future.result()
|
| 170 |
-
except Exception as error:
|
| 171 |
-
failures.append((futures[future], repr(error)))
|
| 172 |
-
|
| 173 |
-
return failures
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
def main(
|
| 177 |
-
source: list[str] = list(SOURCES),
|
| 178 |
-
bbox: str | None = None,
|
| 179 |
-
out: Path = DATA / "processed",
|
| 180 |
-
threads: int = 4,
|
| 181 |
-
) -> None:
|
| 182 |
-
"""Download images for the scenes the chosen label sources annotate."""
|
| 183 |
-
scenes = find_scenes(source, bbox)
|
| 184 |
-
|
| 185 |
-
folder = out / "images"
|
| 186 |
-
folder.mkdir(parents=True, exist_ok=True)
|
| 187 |
-
|
| 188 |
-
client = StacClient.planetary_computer()
|
| 189 |
-
failures = download_scenes(client, scenes, folder, threads)
|
| 190 |
-
|
| 191 |
-
table = pd.DataFrame(failures, columns=["scene", "error"])
|
| 192 |
-
table.to_csv(out / "failures.csv", index=False)
|
| 193 |
-
print(f"{len(scenes)} scenes; {len(failures)} failed, listed in failures.csv")
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
if __name__ == "__main__":
|
| 197 |
-
typer.run(main)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Publish a checkpoint and its inference pipeline to a Hugging Face model repo.
|
| 2 |
+
|
| 3 |
+
python -m scripts.publish fatmur/dynamicworld-small-cnn \
|
| 4 |
+
artifacts/small_cnn_unet/version_0/checkpoints/last.ckpt
|
| 5 |
+
|
| 6 |
+
Add --out release/dynamicworld-small-cnn to retain a local export.
|
| 7 |
+
The run's config.yaml supplies preprocessing; the checkpoint supplies the
|
| 8 |
+
weights and validation chip settings; the run config also freezes its label scheme.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import typer
|
| 14 |
+
import yaml
|
| 15 |
+
|
| 16 |
+
from geosave.ml import RasterPipeline
|
| 17 |
+
from geosave.ml.factory import BuildSpec
|
| 18 |
+
from geosave.ml.processing.raster.ingestion.sentinel2 import Sentinel2Ingestor
|
| 19 |
+
from geosave.ml.processing.raster.postprocessing.dense import SegmentationPostprocessor
|
| 20 |
+
from geosave.ml.processing.raster.prediction.dense import DensePredictor
|
| 21 |
+
from geosave.ml.processing.raster.preprocessing.base import PREPROCESSORS
|
| 22 |
+
from geosave.ml.release import ChainModel
|
| 23 |
+
from modules.supervised.module import Module
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def main(
|
| 27 |
+
repo_id: str,
|
| 28 |
+
checkpoint: Path,
|
| 29 |
+
out: Path | None = typer.Option(None, help="Optional local release directory."),
|
| 30 |
+
) -> None:
|
| 31 |
+
"""Publish to repo_id; optionally keep the same release locally."""
|
| 32 |
+
# Lightning writes a run's resolved config beside its checkpoints folder.
|
| 33 |
+
run = checkpoint.parent.parent
|
| 34 |
+
config = yaml.safe_load((run / "config.yaml").read_text())
|
| 35 |
+
labels = config["data"]["train"]["init_args"]["label_scheme"]
|
| 36 |
+
val_labels = config["data"]["val"]["init_args"]["label_scheme"]
|
| 37 |
+
if labels != val_labels:
|
| 38 |
+
raise ValueError("training and validation label schemes differ")
|
| 39 |
+
|
| 40 |
+
module = Module.load_from_checkpoint(checkpoint, map_location="cpu")
|
| 41 |
+
module.eval()
|
| 42 |
+
if module.model.head.num_classes != len(labels["classes"]):
|
| 43 |
+
raise ValueError("checkpoint head does not match the run label scheme")
|
| 44 |
+
|
| 45 |
+
preprocessor_spec = config["data"]["train"]["init_args"]["preprocessor"]
|
| 46 |
+
preprocessor = PREPROCESSORS.build(BuildSpec.model_validate(preprocessor_spec))
|
| 47 |
+
|
| 48 |
+
# The release chips and merges a raster as validation chipped the scenes.
|
| 49 |
+
predictor = DensePredictor(
|
| 50 |
+
size=module.chip_size,
|
| 51 |
+
stride=module.chip_stride,
|
| 52 |
+
mode=module.chip_mode,
|
| 53 |
+
window=module.merge_window,
|
| 54 |
+
batch_size=module.chip_batch_size,
|
| 55 |
+
context=[],
|
| 56 |
+
nodes=None,
|
| 57 |
+
)
|
| 58 |
+
postprocessor = SegmentationPostprocessor(
|
| 59 |
+
classes=labels["classes"], colors=labels["colors"], mask=None
|
| 60 |
+
)
|
| 61 |
+
# The images were ingested at 10 m under the node the preprocessor reads.
|
| 62 |
+
ingestor = Sentinel2Ingestor(
|
| 63 |
+
bands=preprocessor.bands, resolution=10.0, name=preprocessor.name
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
pipeline = RasterPipeline(
|
| 67 |
+
module.model,
|
| 68 |
+
preprocessor=preprocessor,
|
| 69 |
+
predictor=predictor,
|
| 70 |
+
postprocessor=postprocessor,
|
| 71 |
+
ingestor=ingestor,
|
| 72 |
+
)
|
| 73 |
+
release = ChainModel.from_pipeline(pipeline)
|
| 74 |
+
if out is not None:
|
| 75 |
+
release.save_pretrained(out)
|
| 76 |
+
print(f"Saved local release to {out}")
|
| 77 |
+
|
| 78 |
+
commit = release.push_to_hub(repo_id)
|
| 79 |
+
print(f"Released {repo_id} at {commit.oid}")
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
if __name__ == "__main__":
|
| 83 |
+
typer.run(main)
|
tests/conftest.py
DELETED
|
@@ -1,8 +0,0 @@
|
|
| 1 |
-
"""Import project modules without installing the consumer workspace."""
|
| 2 |
-
|
| 3 |
-
from pathlib import Path
|
| 4 |
-
import sys
|
| 5 |
-
|
| 6 |
-
WORKSPACE = Path(__file__).resolve().parents[1]
|
| 7 |
-
sys.path.insert(0, str(WORKSPACE))
|
| 8 |
-
sys.path.insert(0, str(WORKSPACE / "scripts"))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tests/test_data_workflow.py
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Original labels remain unchanged through ingestion and training reads."""
|
| 2 |
+
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from types import SimpleNamespace
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
+
import pytest
|
| 9 |
+
import rasterio
|
| 10 |
+
from rasterio.transform import from_origin
|
| 11 |
+
import yaml
|
| 12 |
+
|
| 13 |
+
from geosave.ml.factory import BuildSpec
|
| 14 |
+
from modules.supervised.datasets import SceneDataset
|
| 15 |
+
from data.scripts import ingest_scenes
|
| 16 |
+
import geopandas as gpd
|
| 17 |
+
import json
|
| 18 |
+
from shapely.geometry import box
|
| 19 |
+
|
| 20 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@pytest.mark.parametrize(
|
| 24 |
+
"scheme_name,expected",
|
| 25 |
+
[
|
| 26 |
+
("dynamic_world", [255, *range(9), 255]),
|
| 27 |
+
("land_cover", [255, *range(8), 255, 255]),
|
| 28 |
+
],
|
| 29 |
+
)
|
| 30 |
+
@pytest.mark.parametrize("sources", [["experts"], ["experts", "non_expert"]])
|
| 31 |
+
def test_original_codes_are_remapped_only_in_memory(
|
| 32 |
+
tmp_path, scheme_name, expected, sources
|
| 33 |
+
):
|
| 34 |
+
labels = tmp_path / "labels"
|
| 35 |
+
images = tmp_path / "images"
|
| 36 |
+
labels.mkdir()
|
| 37 |
+
images.mkdir()
|
| 38 |
+
options = dict(
|
| 39 |
+
driver="GTiff",
|
| 40 |
+
width=11,
|
| 41 |
+
height=1,
|
| 42 |
+
count=1,
|
| 43 |
+
crs="EPSG:32649",
|
| 44 |
+
transform=from_origin(500000, 10000, 10, 10),
|
| 45 |
+
)
|
| 46 |
+
with rasterio.open(labels / "scene.tif", "w", dtype="uint8", **options) as dst:
|
| 47 |
+
dst.write(np.arange(11, dtype="uint8")[None], 1)
|
| 48 |
+
with rasterio.open(images / "scene.tif", "w", dtype="uint16", **options) as dst:
|
| 49 |
+
dst.write(np.ones((1, 11), dtype="uint16"), 1)
|
| 50 |
+
dst.set_band_description(1, "red")
|
| 51 |
+
original_bytes = (labels / "scene.tif").read_bytes()
|
| 52 |
+
scheme = yaml.safe_load((ROOT / "data/labels.yaml").read_text())[scheme_name]
|
| 53 |
+
table = tmp_path / "scene.parquet"
|
| 54 |
+
gpd.GeoDataFrame(
|
| 55 |
+
{
|
| 56 |
+
"scene_id": ["scene"],
|
| 57 |
+
"split": ["train"],
|
| 58 |
+
"source_group": ["experts"],
|
| 59 |
+
"voting_rule": [None],
|
| 60 |
+
"status": ["written"],
|
| 61 |
+
"image_path": ["images/scene.tif"],
|
| 62 |
+
"label_path": ["labels/scene.tif"],
|
| 63 |
+
},
|
| 64 |
+
geometry=[box(0, 0, 1, 1)],
|
| 65 |
+
crs="EPSG:4326",
|
| 66 |
+
).to_parquet(table)
|
| 67 |
+
# Include only requested training sources; held-out rows never enter training.
|
| 68 |
+
records = gpd.read_parquet(table)
|
| 69 |
+
non_expert = records.assign(source_group="non_expert")
|
| 70 |
+
held_out = records.assign(split="test")
|
| 71 |
+
pd.concat([records, non_expert, held_out], ignore_index=True).to_parquet(table)
|
| 72 |
+
dataset = SceneDataset(
|
| 73 |
+
str(table),
|
| 74 |
+
"train",
|
| 75 |
+
sources,
|
| 76 |
+
BuildSpec(
|
| 77 |
+
name="dense",
|
| 78 |
+
init_args={
|
| 79 |
+
"bands": ["band_1"],
|
| 80 |
+
"decode": False,
|
| 81 |
+
"fill": 0.0,
|
| 82 |
+
"mean": [0.0],
|
| 83 |
+
"std": [1.0],
|
| 84 |
+
"name": "image",
|
| 85 |
+
},
|
| 86 |
+
),
|
| 87 |
+
255,
|
| 88 |
+
scheme,
|
| 89 |
+
)
|
| 90 |
+
assert len(dataset) == len(sources)
|
| 91 |
+
assert all(path.name == "scene.tif" for path in dataset.images)
|
| 92 |
+
sample = dataset[0]
|
| 93 |
+
assert sample["target"].tolist() == [expected]
|
| 94 |
+
assert sample["image"].shape == (1, 1, 11)
|
| 95 |
+
assert (labels / "scene.tif").read_bytes() == original_bytes
|
| 96 |
+
with rasterio.open(labels / "scene.tif") as src:
|
| 97 |
+
assert src.nodata is None
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def test_missing_acquisition_reports_search_failure(tmp_path, monkeypatch):
|
| 101 |
+
annotations_df = gpd.GeoDataFrame(
|
| 102 |
+
{
|
| 103 |
+
"scene_id": ["missing", "unselected"],
|
| 104 |
+
"date": [pd.Timestamp("2019-01-01")] * 2,
|
| 105 |
+
"label_path": ["missing.tif", None],
|
| 106 |
+
"image_path": ["image/train/missing.tif", None],
|
| 107 |
+
},
|
| 108 |
+
geometry=[box(0, 0, 1, 1), box(1, 1, 2, 2)],
|
| 109 |
+
crs="EPSG:4326",
|
| 110 |
+
)
|
| 111 |
+
labels = tmp_path / "label.parquet"
|
| 112 |
+
annotations_df.to_parquet(labels)
|
| 113 |
+
ingestor = SimpleNamespace(search_items=lambda region: [])
|
| 114 |
+
monkeypatch.setattr(ingest_scenes, "Sentinel2Ingestor", lambda bands: ingestor)
|
| 115 |
+
|
| 116 |
+
with pytest.raises(ingest_scenes.typer.Exit):
|
| 117 |
+
ingest_scenes.main(labels)
|
| 118 |
+
|
| 119 |
+
scenes_df = gpd.read_parquet(tmp_path / "scene.parquet").set_index("scene_id")
|
| 120 |
+
assert scenes_df.at["missing", "status"] == "failed"
|
| 121 |
+
assert scenes_df.at["missing", "stage"] == "search"
|
| 122 |
+
assert scenes_df.at["missing", "source_items"] == "[]"
|
| 123 |
+
assert "no Sentinel-2 L2A Items" in scenes_df.at["missing", "error"]
|
| 124 |
+
assert scenes_df.at["unselected", "status"] == "pending"
|
| 125 |
+
assert scenes_df.image_path.isna().all()
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
@pytest.mark.parametrize("baseline,offset", [("02.12", 0.0), ("05.00", -0.1)])
|
| 129 |
+
def test_parquet_dates_paths_and_original_labels_survive_ingestion(
|
| 130 |
+
tmp_path, monkeypatch, baseline, offset
|
| 131 |
+
):
|
| 132 |
+
from datetime import datetime, timezone
|
| 133 |
+
|
| 134 |
+
import geopandas as gpd
|
| 135 |
+
import pystac
|
| 136 |
+
import geosave as gs
|
| 137 |
+
|
| 138 |
+
label = tmp_path / "annotation-without-a-date.tif"
|
| 139 |
+
asset = tmp_path / "source.tif"
|
| 140 |
+
options = dict(
|
| 141 |
+
driver="GTiff",
|
| 142 |
+
width=4,
|
| 143 |
+
height=4,
|
| 144 |
+
count=1,
|
| 145 |
+
dtype="uint16",
|
| 146 |
+
crs="EPSG:32649",
|
| 147 |
+
transform=from_origin(500000, 10000, 10, 10),
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
for path in [label, asset]:
|
| 151 |
+
with rasterio.open(path, "w", **options) as dst:
|
| 152 |
+
dst.write(np.full((4, 4), 2, dtype="uint16"), 1)
|
| 153 |
+
|
| 154 |
+
with gs.open_raster(label) as original:
|
| 155 |
+
footprint = original.gs.geobox.extent.to_crs("EPSG:4326").geom
|
| 156 |
+
|
| 157 |
+
item = pystac.Item(
|
| 158 |
+
"local",
|
| 159 |
+
footprint.__geo_interface__,
|
| 160 |
+
list(footprint.bounds),
|
| 161 |
+
datetime(2020, 1, 1, tzinfo=timezone.utc),
|
| 162 |
+
{"s2:processing_baseline": baseline},
|
| 163 |
+
)
|
| 164 |
+
item.add_asset(
|
| 165 |
+
"red",
|
| 166 |
+
pystac.Asset(str(asset), media_type=pystac.MediaType.GEOTIFF, roles=["data"]),
|
| 167 |
+
)
|
| 168 |
+
ingestor = ingest_scenes.Sentinel2Ingestor(["red"])
|
| 169 |
+
ingestor.__dict__["client"] = SimpleNamespace(patch_url=None)
|
| 170 |
+
monkeypatch.setattr(ingest_scenes, "Sentinel2Ingestor", lambda bands: ingestor)
|
| 171 |
+
monkeypatch.setattr(ingest_scenes, "BANDS", ["red"])
|
| 172 |
+
|
| 173 |
+
frame = gpd.GeoDataFrame(
|
| 174 |
+
{
|
| 175 |
+
"scene_id": ["scene"],
|
| 176 |
+
"annotation_id": ["expert/scene"],
|
| 177 |
+
"split": ["train"],
|
| 178 |
+
"date": [pd.Timestamp("2020-01-01")],
|
| 179 |
+
"label_path": [label.name],
|
| 180 |
+
"image_path": ["image/train/paired.tif"],
|
| 181 |
+
"biome": [1],
|
| 182 |
+
},
|
| 183 |
+
geometry=[footprint],
|
| 184 |
+
crs="EPSG:4326",
|
| 185 |
+
)
|
| 186 |
+
# A second annotation uses the same pixels and must share the acquisition.
|
| 187 |
+
second = frame.copy()
|
| 188 |
+
second["annotation_id"] = "non_expert/scene"
|
| 189 |
+
frame = pd.concat([frame, second], ignore_index=True)
|
| 190 |
+
table = tmp_path / "label.parquet"
|
| 191 |
+
frame.to_parquet(table, index=False)
|
| 192 |
+
label_before, table_before = label.read_bytes(), table.read_bytes()
|
| 193 |
+
|
| 194 |
+
# Overlapping Items with an identical datetime must load as one observation.
|
| 195 |
+
overlapping = item.clone()
|
| 196 |
+
overlapping.id = "overlapping"
|
| 197 |
+
calls = []
|
| 198 |
+
|
| 199 |
+
def search(region):
|
| 200 |
+
calls.append(region)
|
| 201 |
+
return [item, overlapping]
|
| 202 |
+
|
| 203 |
+
ingestor.search_items = search
|
| 204 |
+
ingest_scenes.main(table, threads=1)
|
| 205 |
+
assert len(calls) == 1
|
| 206 |
+
saved = gpd.read_parquet(tmp_path / "scene.parquet")
|
| 207 |
+
assert len(saved) == 2
|
| 208 |
+
assert saved.image_path.nunique() == 1
|
| 209 |
+
assert json.loads(saved.source_items.iloc[0])[0] == json.loads(
|
| 210 |
+
json.dumps(item.to_dict())
|
| 211 |
+
)
|
| 212 |
+
assert len(json.loads(saved.source_items.iloc[0])) == 2
|
| 213 |
+
provenance = saved.source_items.tolist()
|
| 214 |
+
|
| 215 |
+
with gs.open_raster(tmp_path / "image/train/paired.tif") as image:
|
| 216 |
+
np.testing.assert_array_equal(image.red.values, np.full((4, 4), 2))
|
| 217 |
+
assert image.red.attrs["scale_factor"] == 1e-4
|
| 218 |
+
assert image.red.attrs.get("add_offset", 0.0) == offset
|
| 219 |
+
grid = image.gs.geobox
|
| 220 |
+
|
| 221 |
+
# Search-based ingestion and replay of saved Items must have the same result.
|
| 222 |
+
import xarray as xr
|
| 223 |
+
|
| 224 |
+
direct = ingestor.ingest_grid(grid, pd.Timestamp("2020-01-01"))
|
| 225 |
+
replayed = ingestor.ingest_grid(
|
| 226 |
+
grid, pd.Timestamp("2020-01-01"), items=[item, overlapping]
|
| 227 |
+
)
|
| 228 |
+
xr.testing.assert_identical(direct, replayed)
|
| 229 |
+
assert direct.red.attrs["scale_factor"] == 1e-4
|
| 230 |
+
assert direct.red.attrs.get("add_offset", 0.0) == offset
|
| 231 |
+
assert label.read_bytes() == label_before
|
| 232 |
+
assert table.read_bytes() == table_before
|
| 233 |
+
|
| 234 |
+
def unexpected_search(region):
|
| 235 |
+
raise AssertionError("completed imagery must not be searched again")
|
| 236 |
+
|
| 237 |
+
ingestor.search_items = unexpected_search
|
| 238 |
+
ingest_scenes.main(table, threads=1)
|
| 239 |
+
assert label.read_bytes() == label_before
|
| 240 |
+
assert table.read_bytes() == table_before
|
| 241 |
+
|
| 242 |
+
resumed = gpd.read_parquet(tmp_path / "scene.parquet")
|
| 243 |
+
assert resumed.source_items.tolist() == provenance
|
| 244 |
+
assert resumed.status.tolist() == ["written", "written"]
|
| 245 |
+
|
| 246 |
+
# A load failure must retain the original Items for a search-free retry.
|
| 247 |
+
(tmp_path / "image/train/paired.tif").unlink()
|
| 248 |
+
real_load = ingestor.ingest_grid
|
| 249 |
+
|
| 250 |
+
def broken_load(*args, **kwargs):
|
| 251 |
+
raise ValueError("overlap reproduction")
|
| 252 |
+
|
| 253 |
+
monkeypatch.setattr(ingestor, "ingest_grid", broken_load)
|
| 254 |
+
with pytest.raises(ingest_scenes.typer.Exit):
|
| 255 |
+
ingest_scenes.main(table, threads=1)
|
| 256 |
+
failed = gpd.read_parquet(tmp_path / "scene.parquet")
|
| 257 |
+
assert failed.stage.tolist() == ["load", "load"]
|
| 258 |
+
assert failed.image_path.isna().all()
|
| 259 |
+
assert failed.source_items.tolist() == provenance
|
| 260 |
+
assert failed.error.str.contains("overlap reproduction").all()
|
| 261 |
+
|
| 262 |
+
monkeypatch.setattr(ingestor, "ingest_grid", real_load)
|
| 263 |
+
ingest_scenes.main(table, threads=1)
|
| 264 |
+
assert gpd.read_parquet(tmp_path / "scene.parquet").status.eq("written").all()
|
| 265 |
+
|
| 266 |
+
# A partial COG must never be exposed as a completed image or lose provenance.
|
| 267 |
+
(tmp_path / "image/train/paired.tif").unlink()
|
| 268 |
+
|
| 269 |
+
def interrupted_write(image, path, **kwargs):
|
| 270 |
+
path.write_bytes(b"incomplete raster")
|
| 271 |
+
raise OSError("write interrupted")
|
| 272 |
+
|
| 273 |
+
with monkeypatch.context() as patch:
|
| 274 |
+
patch.setattr(ingest_scenes.io, "write_cog", interrupted_write)
|
| 275 |
+
with pytest.raises(ingest_scenes.typer.Exit):
|
| 276 |
+
ingest_scenes.main(table, threads=1)
|
| 277 |
+
|
| 278 |
+
failed_df = gpd.read_parquet(tmp_path / "scene.parquet")
|
| 279 |
+
assert failed_df.status.eq("failed").all()
|
| 280 |
+
assert failed_df.stage.eq("write").all()
|
| 281 |
+
assert failed_df.image_path.isna().all()
|
| 282 |
+
assert failed_df.source_items.tolist() == provenance
|
| 283 |
+
assert not list((tmp_path / "image/train").glob("*.tif"))
|
| 284 |
+
|
| 285 |
+
ingest_scenes.main(table, threads=1)
|
| 286 |
+
assert gpd.read_parquet(tmp_path / "scene.parquet").status.eq("written").all()
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
@pytest.mark.parametrize("limit,expected_searches", [(1, 1), (None, 2)])
|
| 290 |
+
def test_ingestion_limit_preserves_full_annotation_table(
|
| 291 |
+
tmp_path, monkeypatch, limit, expected_searches
|
| 292 |
+
):
|
| 293 |
+
annotations_df = gpd.GeoDataFrame(
|
| 294 |
+
{
|
| 295 |
+
"scene_id": ["a", "a", "b"],
|
| 296 |
+
"date": [pd.Timestamp("2020-01-01")] * 3,
|
| 297 |
+
"label_path": [
|
| 298 |
+
"label/train/expert/a.tif",
|
| 299 |
+
"label/train/non-expert/a.tif",
|
| 300 |
+
"label/test/b.tif",
|
| 301 |
+
],
|
| 302 |
+
"image_path": [
|
| 303 |
+
"image/train/a.tif",
|
| 304 |
+
"image/train/a.tif",
|
| 305 |
+
"image/test/b.tif",
|
| 306 |
+
],
|
| 307 |
+
},
|
| 308 |
+
geometry=[box(0, 0, 1, 1)] * 3,
|
| 309 |
+
crs="EPSG:4326",
|
| 310 |
+
)
|
| 311 |
+
labels = tmp_path / "label.parquet"
|
| 312 |
+
annotations_df.to_parquet(labels)
|
| 313 |
+
original = labels.read_bytes()
|
| 314 |
+
searched = []
|
| 315 |
+
|
| 316 |
+
def search(region):
|
| 317 |
+
searched.append(region)
|
| 318 |
+
return []
|
| 319 |
+
|
| 320 |
+
ingestor = SimpleNamespace(search_items=search)
|
| 321 |
+
monkeypatch.setattr(ingest_scenes, "Sentinel2Ingestor", lambda bands: ingestor)
|
| 322 |
+
with pytest.raises(ingest_scenes.typer.Exit):
|
| 323 |
+
ingest_scenes.main(labels, limit=limit)
|
| 324 |
+
|
| 325 |
+
scenes_df = gpd.read_parquet(tmp_path / "scene.parquet")
|
| 326 |
+
assert len(searched) == expected_searches
|
| 327 |
+
assert len(scenes_df) == 3
|
| 328 |
+
assert scenes_df.status.tolist() == [
|
| 329 |
+
"failed",
|
| 330 |
+
"failed",
|
| 331 |
+
"pending" if limit else "failed",
|
| 332 |
+
]
|
| 333 |
+
assert labels.read_bytes() == original
|