ingest: Planetary Computer L2A with baseline packing; --bbox selection
Browse files
modules/segmentation/supervised/datasets.py
CHANGED
|
@@ -35,8 +35,9 @@ def find_labels(raw: Path = DATA / "raw") -> pd.DataFrame:
|
|
| 35 |
a label with its image, `processed/images/{scene}.tif`.
|
| 36 |
|
| 37 |
Returns:
|
| 38 |
-
One row per file: `scene` (`{lon}_{lat}-{yyyymmdd}`), `
|
| 39 |
-
`variant` (composite rule or expert id, empty
|
|
|
|
| 40 |
"""
|
| 41 |
rows = []
|
| 42 |
for source, folder in SOURCES.items():
|
|
@@ -48,6 +49,8 @@ def find_labels(raw: Path = DATA / "raw") -> pd.DataFrame:
|
|
| 48 |
rows.append(
|
| 49 |
{
|
| 50 |
"scene": f"{lon}_{lat}-{day}",
|
|
|
|
|
|
|
| 51 |
"date": pd.Timestamp(day),
|
| 52 |
"source": source,
|
| 53 |
"variant": variant,
|
|
|
|
| 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():
|
|
|
|
| 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,
|
scripts/ingest_dynamic_world.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 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 |
|
| 5 |
Run from the workspace root.
|
| 6 |
|
|
@@ -20,35 +21,34 @@ import xarray as xr
|
|
| 20 |
from tqdm import tqdm
|
| 21 |
|
| 22 |
import geosave # noqa: F401 registers the .gs accessors
|
|
|
|
| 23 |
from geosave.geodata import io, stac
|
| 24 |
from geosave.geodata.stac import StacClient, StacQuery
|
| 25 |
|
| 26 |
from modules.segmentation.supervised.datasets import DATA, SOURCES, find_labels
|
| 27 |
|
| 28 |
-
#
|
| 29 |
-
|
| 30 |
-
COLLECTION = "sentinel-2-c1-l2a"
|
| 31 |
|
| 32 |
# The 10 m and 20 m bands the Dynamic World model reads (Brown et al., 2022).
|
| 33 |
-
BANDS = [
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
"
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
"
|
| 43 |
-
"swir22",
|
| 44 |
-
]
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
def find_scenes(sources: list[str]) -> pd.DataFrame:
|
| 48 |
-
"""Return one label row per scene the chosen sources annotate."""
|
| 49 |
labels = find_labels()
|
| 50 |
labels = labels[labels["source"].isin(sources)]
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
# Every label of a scene shares its grid, so the first one places the image.
|
| 53 |
return labels.drop_duplicates("scene")
|
| 54 |
|
|
@@ -63,6 +63,22 @@ def search_items(
|
|
| 63 |
return client.search_items(query)
|
| 64 |
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
def load_image(client: StacClient, label_path: Path, date: pd.Timestamp) -> xr.Dataset:
|
| 67 |
"""Load the label day's acquisition onto the label's grid.
|
| 68 |
|
|
@@ -70,20 +86,25 @@ def load_image(client: StacClient, label_path: Path, date: pd.Timestamp) -> xr.D
|
|
| 70 |
"""
|
| 71 |
label = io.open_geotiff(label_path, chunks=None)
|
| 72 |
items = search_items(client, label, date)
|
|
|
|
| 73 |
|
| 74 |
image = stac.load_dataset(
|
| 75 |
items,
|
| 76 |
label.gs.geobox,
|
| 77 |
bands=BANDS,
|
| 78 |
resampling="bilinear",
|
|
|
|
|
|
|
| 79 |
chunks=None,
|
|
|
|
| 80 |
)
|
| 81 |
|
| 82 |
# The label annotates one acquisition; several would be a different image per tile.
|
| 83 |
if image.sizes["time"] != 1:
|
| 84 |
raise ValueError(f"expected one acquisition on {date:%Y-%m-%d}, found {image.sizes['time']}")
|
| 85 |
|
| 86 |
-
|
|
|
|
| 87 |
|
| 88 |
|
| 89 |
def write_image(image: xr.Dataset, path: Path) -> None:
|
|
@@ -130,16 +151,17 @@ def download_scenes(
|
|
| 130 |
|
| 131 |
def main(
|
| 132 |
source: list[str] = list(SOURCES),
|
|
|
|
| 133 |
out: Path = DATA / "processed",
|
| 134 |
threads: int = 4,
|
| 135 |
) -> None:
|
| 136 |
"""Download images for the scenes the chosen label sources annotate."""
|
| 137 |
-
scenes = find_scenes(source)
|
| 138 |
|
| 139 |
folder = out / "images"
|
| 140 |
folder.mkdir(parents=True, exist_ok=True)
|
| 141 |
|
| 142 |
-
client = StacClient.
|
| 143 |
failures = download_scenes(client, scenes, folder, threads)
|
| 144 |
|
| 145 |
table = pd.DataFrame(failures, columns=["scene", "error"])
|
|
|
|
| 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 |
|
|
|
|
| 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_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 |
|
|
|
|
| 63 |
return client.search_items(query)
|
| 64 |
|
| 65 |
|
| 66 |
+
def read_packing(items: list[pystac.Item]) -> attrs.CFPacking:
|
| 67 |
+
"""Read how the items' digital numbers decode to reflectance.
|
| 68 |
+
|
| 69 |
+
Processing baseline 04.00 added a -1000 DN offset. Tiles of different
|
| 70 |
+
baselines decode differently, so one image must not mosaic them.
|
| 71 |
+
"""
|
| 72 |
+
baselines = set()
|
| 73 |
+
for item in items:
|
| 74 |
+
baselines.add(item.properties["s2:processing_baseline"])
|
| 75 |
+
if len(baselines) != 1:
|
| 76 |
+
raise ValueError(f"tiles mix processing baselines {sorted(baselines)}")
|
| 77 |
+
|
| 78 |
+
offset = -0.1 if float(baselines.pop()) >= 4 else 0.0
|
| 79 |
+
return attrs.CFPacking(scale_factor=1e-4, add_offset=offset, fill_value=0)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
def load_image(client: StacClient, label_path: Path, date: pd.Timestamp) -> xr.Dataset:
|
| 83 |
"""Load the label day's acquisition onto the label's grid.
|
| 84 |
|
|
|
|
| 86 |
"""
|
| 87 |
label = io.open_geotiff(label_path, chunks=None)
|
| 88 |
items = search_items(client, label, date)
|
| 89 |
+
packing = read_packing(items)
|
| 90 |
|
| 91 |
image = stac.load_dataset(
|
| 92 |
items,
|
| 93 |
label.gs.geobox,
|
| 94 |
bands=BANDS,
|
| 95 |
resampling="bilinear",
|
| 96 |
+
dtype="uint16",
|
| 97 |
+
nodata=0,
|
| 98 |
chunks=None,
|
| 99 |
+
patch_url=client.patch_url,
|
| 100 |
)
|
| 101 |
|
| 102 |
# The label annotates one acquisition; several would be a different image per tile.
|
| 103 |
if image.sizes["time"] != 1:
|
| 104 |
raise ValueError(f"expected one acquisition on {date:%Y-%m-%d}, found {image.sizes['time']}")
|
| 105 |
|
| 106 |
+
image = image.isel(time=0)
|
| 107 |
+
return image.gs.write_packing(packing)
|
| 108 |
|
| 109 |
|
| 110 |
def write_image(image: xr.Dataset, path: Path) -> None:
|
|
|
|
| 151 |
|
| 152 |
def main(
|
| 153 |
source: list[str] = list(SOURCES),
|
| 154 |
+
bbox: str | None = None,
|
| 155 |
out: Path = DATA / "processed",
|
| 156 |
threads: int = 4,
|
| 157 |
) -> None:
|
| 158 |
"""Download images for the scenes the chosen label sources annotate."""
|
| 159 |
+
scenes = find_scenes(source, bbox)
|
| 160 |
|
| 161 |
folder = out / "images"
|
| 162 |
folder.mkdir(parents=True, exist_ok=True)
|
| 163 |
|
| 164 |
+
client = StacClient.planetary_computer()
|
| 165 |
failures = download_scenes(client, scenes, folder, threads)
|
| 166 |
|
| 167 |
table = pd.DataFrame(failures, columns=["scene", "error"])
|