darts_acquisition
¶
Acquisition of data from various sources for the DARTS dataset.
download_admin_files
¶
Download the admin files for the regions.
Files will be stored under [admin_dir]/adm1.shp and [admin_dir]/adm2.shp.
Parameters:
Source code in darts-acquisition/src/darts_acquisition/admin.py
download_arcticdem
¶
download_arcticdem(
aoi: geopandas.GeoDataFrame,
data_dir: pathlib.Path | str,
resolution: darts_acquisition.arcticdem.RESOLUTIONS,
) -> None
Download ArcticDEM data for the specified area of interest.
This function downloads ArcticDEM elevation tiles from AWS S3 for the given area of interest and stores them in a local icechunk data store for efficient access.
Parameters:
-
aoi(geopandas.GeoDataFrame) –Area of interest for which to download ArcticDEM data. Can be in any CRS; will be reprojected to EPSG:3413 (ArcticDEM's native CRS).
-
data_dir(pathlib.Path | str) –Path to the icechunk data directory (must have .icechunk suffix). Must contain the resolution in the name (e.g., "arcticdem_2m.icechunk").
-
resolution(typing.Literal[2, 10, 32]) –The resolution of the ArcticDEM data in meters. Must match the resolution indicated in the data_dir name.
Note
This function automatically configures AWS access with unsigned requests to the public ArcticDEM S3 bucket. No AWS credentials are required.
Example
Download ArcticDEM for a study area:
import geopandas as gpd
from shapely.geometry import box
from darts_acquisition import download_arcticdem
# Define area of interest
aoi = gpd.GeoDataFrame(
geometry=[box(-50, 70, -49, 71)],
crs="EPSG:4326"
)
# Download 2m resolution ArcticDEM
download_arcticdem(
aoi=aoi,
data_dir="/data/arcticdem_2m.icechunk",
resolution=2
)
Source code in darts-acquisition/src/darts_acquisition/arcticdem.py
download_cdse_s2_sr_scene
¶
download_cdse_s2_sr_scene(
s2item: str | pystac.Item,
store: pathlib.Path,
bands_mapping: dict | typing.Literal["all"] = {
"B02_10m": "blue",
"B03_10m": "green",
"B04_10m": "red",
"B08_10m": "nir",
},
aws_profile_name: str = "default",
)
Download a Sentinel-2 scene from CDSE via STAC API and store it in the local data store.
This function downloads Sentinel-2 Level-2A surface reflectance data from the Copernicus Data Space Ecosystem (CDSE) and stores it locally in a compressed zarr store for efficient repeated access.
Parameters:
-
s2item(str | pystac.Item) –Sentinel-2 scene identifier (e.g., "S2A_MSIL2A_20230615T...") or a PySTAC Item object from a STAC search.
-
store(pathlib.Path) –Path to the local zarr store directory where the scene will be saved.
-
bands_mapping(dict | typing.Literal['all'], default:{'B02_10m': 'blue', 'B03_10m': 'green', 'B04_10m': 'red', 'B08_10m': 'nir'}) –Mapping of Sentinel-2 band names to custom band names. Keys should be CDSE band names (e.g., "B02_10m", "B03_10m"), values are the desired output names. Use "all" to load all optical bands and SCL. Defaults to {"B02_10m": "blue", "B03_10m": "green", "B04_10m": "red", "B08_10m": "nir"}.
-
aws_profile_name(str, default:'default') –AWS profile name for authentication with the Copernicus S3 bucket. Defaults to "default".
Note
- Requires Copernicus Data Space authentication. Use
darts_utils.copernicus.init_copernicus()to set up credentials before calling this function. - All bands are resampled to 10m resolution during download.
- Data is stored with zstd compression for efficient storage.
- The SCL (Scene Classification Layer) band is automatically included if not specified.
Example
Download Sentinel-2 scenes for a project:
from pathlib import Path
from darts_acquisition import download_cdse_s2_sr_scene
from darts_utils.copernicus import init_copernicus
# Setup authentication
init_copernicus(profile_name="default")
# Download scene with all bands
download_cdse_s2_sr_scene(
s2item="S2A_MSIL2A_20230615T123456_N0509_R012_T33UUP_20230615T145678",
store=Path("/data/s2_store"),
bands_mapping="all",
aws_profile_name="default"
)
Source code in darts-acquisition/src/darts_acquisition/s2/cdse_scene.py
download_gee_s2_sr_scene
¶
download_gee_s2_sr_scene(
s2item: str | ee.Image,
store: pathlib.Path,
bands_mapping: dict | typing.Literal["all"] = {
"B2": "blue",
"B3": "green",
"B4": "red",
"B8": "nir",
},
)
Download a Sentinel-2 scene from Google Earth Engine and store it in the local data store.
This function downloads Sentinel-2 Level-2A surface reflectance data from Google Earth Engine (GEE) and stores it locally in a compressed zarr store for efficient repeated access.
Parameters:
-
s2item(str | ee.Image) –Sentinel-2 scene identifier (e.g., "20230615T123456_20230615T123659_T33UUP") or an ee.Image object from the COPERNICUS/S2_SR collection.
-
store(pathlib.Path) –Path to the local zarr store directory where the scene will be saved.
-
bands_mapping(dict | typing.Literal['all'], default:{'B2': 'blue', 'B3': 'green', 'B4': 'red', 'B8': 'nir'}) –Mapping of Sentinel-2 band names to custom band names. Keys should be GEE band names (e.g., "B2", "B3"), values are the desired output names. Use "all" to load all optical bands and SCL. Defaults to {"B2": "blue", "B3": "green", "B4": "red", "B8": "nir"}.
Note
- Requires Google Earth Engine authentication. Use
ee.Initialize()before calling. - All bands are downloaded at 10m resolution.
- Data is stored with zstd compression for efficient storage.
- The SCL (Scene Classification Layer) band is automatically included if not specified.
Example
Download Sentinel-2 scenes from GEE:
Source code in darts-acquisition/src/darts_acquisition/s2/gee_scene.py
download_sentinel_2_grid
¶
Download the Sentinel 2 grid files.
Files will be stored under [grid_dir]/adm1.shp and [grid_dir]/...
Parameters:
Source code in darts-acquisition/src/darts_acquisition/s2/grid.py
download_tcvis
¶
Download TCVIS (Tasseled Cap trends) data for the specified area of interest.
This function downloads Tasseled Cap trend data from Google Earth Engine for the given area of interest and stores it in a local icechunk data store for efficient access.
Parameters:
-
aoi(geopandas.GeoDataFrame) –Area of interest for which to download TCVIS data. Can be in any CRS; will be reprojected to the TCVIS dataset's native CRS.
-
data_dir(pathlib.Path | str) –Path to the icechunk data directory (must have .icechunk suffix).
Note
Requires Google Earth Engine authentication to be set up before calling this function.
Use ee.Initialize() or ee.Authenticate() as needed.
Example
Download TCVIS for a study area:
Source code in darts-acquisition/src/darts_acquisition/tcvis.py
get_aoi_from_cdse_scene_ids
¶
Get the area of interest (AOI) as a GeoDataFrame from a list of Sentinel-2 scene IDs.
Parameters:
Returns:
-
geopandas.GeoDataFrame–gpd.GeoDataFrame: The AOI as a GeoDataFrame.
Raises:
-
ValueError–If no Sentinel-2 items are found for the given scene IDs.
Source code in darts-acquisition/src/darts_acquisition/s2/cdse_scene.py
get_aoi_from_gee_scene_ids
¶
Get the area of interest (AOI) as a GeoDataFrame from a list of Sentinel-2 scene IDs.
Parameters:
Returns:
-
geopandas.GeoDataFrame–gpd.GeoDataFrame: The AOI as a GeoDataFrame.
Raises:
-
ValueError–If no Sentinel-2 items are found for the given scene IDs.
Source code in darts-acquisition/src/darts_acquisition/s2/gee_scene.py
get_cdse_s2_sr_scene_ids_from_geodataframe
¶
get_cdse_s2_sr_scene_ids_from_geodataframe(
aoi: geopandas.GeoDataFrame | pathlib.Path | str,
start_date: str | None = None,
end_date: str | None = None,
max_cloud_cover: int | None = 10,
max_snow_cover: int | None = 10,
months: list[int] | None = None,
years: list[int] | None = None,
simplify_geometry: float
| typing.Literal[False] = False,
) -> dict[str, pystac.Item]
Search for Sentinel-2 scenes via STAC based on an area of interest (aoi).
Parameters:
-
aoi(geopandas.GeoDataFrame | pathlib.Path | str) –AOI as a GeoDataFrame or path to a shapefile. If a path is provided, it will be read using geopandas.
-
start_date(str, default:None) –Starting date in a format readable by pystac_client. If None, months and years parameters will be used for filtering if set. Defaults to None.
-
end_date(str, default:None) –Ending date in a format readable by pystac_client. If None, months and years parameters will be used for filtering if set. Defaults to None.
-
max_cloud_cover(int, default:10) –Maximum percentage of cloud cover. Defaults to 10.
-
max_snow_cover(int, default:10) –Maximum percentage of snow cover. Defaults to 10.
-
months(list[int] | None, default:None) –List of months (1-12) to filter the search. Only used if start_date and end_date are None. Defaults to None.
-
years(list[int] | None, default:None) –List of years to filter the search. Only used if start_date and end_date are None. Defaults to None.
-
simplify_geometry(float | typing.Literal[False], default:False) –If a float is provided, the geometry will be simplified using the
simplifymethod of geopandas. If False, no simplification will be done. This may become useful for large / weird AOIs which are too large for the STAC API. Defaults to False.
Returns:
Source code in darts-acquisition/src/darts_acquisition/s2/cdse_scene.py
get_cdse_s2_sr_scene_ids_from_tile_ids
¶
get_cdse_s2_sr_scene_ids_from_tile_ids(
tile_ids: list[str],
start_date: str | None = None,
end_date: str | None = None,
max_cloud_cover: int | None = 10,
max_snow_cover: int | None = 10,
months: list[int] | None = None,
years: list[int] | None = None,
) -> dict[str, pystac.Item]
Search for Sentinel-2 scenes via STAC based on a list of tile IDs.
Parameters:
-
tile_ids(list[str]) –List of MGRS tile IDs to search for.
-
start_date(str, default:None) –Starting date in a format readable by pystac_client. If None, months and years parameters will be used for filtering if set. Defaults to None.
-
end_date(str, default:None) –Ending date in a format readable by pystac_client. If None, months and years parameters will be used for filtering if set. Defaults to None.
-
max_cloud_cover(int, default:10) –Maximum percentage of cloud cover. Defaults to 10.
-
max_snow_cover(int, default:10) –Maximum percentage of snow cover. Defaults to 10.
-
months(list[int] | None, default:None) –List of months (1-12) to filter the search. Only used if start_date and end_date are None. Defaults to None.
-
years(list[int] | None, default:None) –List of years to filter the search. Only used if start_date and end_date are None. Defaults to None.
Returns:
Source code in darts-acquisition/src/darts_acquisition/s2/cdse_scene.py
get_gee_s2_sr_scene_ids_from_geodataframe
¶
get_gee_s2_sr_scene_ids_from_geodataframe(
aoi: geopandas.GeoDataFrame | pathlib.Path | str,
start_date: str | None = None,
end_date: str | None = None,
max_cloud_cover: int | None = 10,
max_snow_cover: int | None = 10,
) -> set[str]
Search for Sentinel-2 scenes via Earth Engine based on an aoi shapefile.
Parameters:
-
aoi(geopandas.GeoDataFrame | pathlib.Path | str) –AOI as a GeoDataFrame or path to a shapefile. If a path is provided, it will be read using geopandas.
-
start_date(str, default:None) –Starting date in a format readable by ee. If None, months and years parameters will be used for filtering if set. Defaults to None.
-
end_date(str, default:None) –Ending date in a format readable by ee. If None, months and years parameters will be used for filtering if set. Defaults to None.
-
max_cloud_cover(int, default:10) –Maximum percentage of cloud cover. Defaults to 10.
-
max_snow_cover(int, default:10) –Maximum percentage of snow cover. Defaults to 10.
Returns:
Source code in darts-acquisition/src/darts_acquisition/s2/gee_scene.py
get_gee_s2_sr_scene_ids_from_tile_ids
¶
get_gee_s2_sr_scene_ids_from_tile_ids(
tiles: list[str],
start_date: str | None = None,
end_date: str | None = None,
max_cloud_cover: int | None = 10,
max_snow_cover: int | None = 10,
) -> set[str]
Search for Sentinel-2 scenes via Earth Engine based on a list of tile IDs.
Parameters:
-
tiles(list[str]) –List of Sentinel-2 tile IDs.
-
start_date(str, default:None) –Starting date in a format readable by ee. If None, months and years parameters will be used for filtering if set. Defaults to None.
-
end_date(str, default:None) –Ending date in a format readable by ee. If None, months and years parameters will be used for filtering if set. Defaults to None.
-
max_cloud_cover(int, default:10) –Maximum percentage of cloud cover. Defaults to 10.
-
max_snow_cover(int, default:10) –Maximum percentage of snow cover. Defaults to 10.
Returns:
Source code in darts-acquisition/src/darts_acquisition/s2/gee_scene.py
get_planet_geometry
¶
Get the geometry of a Planet scene.
Parameters:
Returns:
-
odc.geo.Geometry–odc.geo.Geometry: The geometry of the Planet scene.
Raises:
-
FileNotFoundError–If no matching TIFF file is found in the specified path.
Source code in darts-acquisition/src/darts_acquisition/planet.py
load_arcticdem
¶
load_arcticdem(
geobox: odc.geo.geobox.GeoBox,
data_dir: pathlib.Path | str,
resolution: darts_acquisition.arcticdem.RESOLUTIONS,
buffer: int = 0,
offline: bool = False,
) -> xarray.Dataset
Load the ArcticDEM for the given geobox, fetch new data from the STAC server if necessary.
This function loads ArcticDEM elevation data from a local icechunk store. If offline=False,
missing data will be automatically downloaded from the AWS-hosted STAC server and stored
locally for future use. The loaded data is returned in the ArcticDEM's native CRS (EPSG:3413).
Parameters:
-
geobox(odc.geo.geobox.GeoBox) –The geobox for which the tile should be loaded. Must be in a meter-based CRS.
-
data_dir(pathlib.Path | str) –Path to the icechunk data directory (must have .icechunk suffix). This directory stores downloaded ArcticDEM data for faster consecutive access.
-
resolution(typing.Literal[2, 10, 32]) –The resolution of the ArcticDEM data in meters. Must match the resolution indicated in the data_dir name (e.g., "arcticdem_2m.icechunk").
-
buffer(int, default:0) –Buffer around the geobox in pixels. The buffer is applied in the ArcticDEM's native CRS (EPSG:3413) after reprojecting the input geobox. Useful for edge effect removal in terrain analysis. Defaults to 0.
-
offline(bool, default:False) –If True, only loads data already present in the local store without attempting any downloads. If False, missing data is downloaded from AWS. Defaults to False.
Returns:
-
xarray.Dataset–xr.Dataset: The ArcticDEM dataset with the following data variables: - dem (float32): Elevation values in meters, clipped to [-100, 3000] range - arcticdem_data_mask (uint8): Data validity mask (1=valid, 0=invalid)
The dataset is in the ArcticDEM's native CRS (EPSG:3413) with the buffer applied. It is NOT automatically reprojected to match the input geobox's CRS and resolution.
Note
The offline parameter controls data fetching behavior:
- When
offline=False: Usessmart_geocubesaccessor'sload()method which automatically downloads missing tiles from AWS and persists them to the icechunk store. - When
offline=True: Uses the accessor'sopen_xarray()method to open the existing store and crops it to the requested region. Raises an error if data is missing.
Warning
- The input geobox must be in a meter-based CRS.
- The data_dir must have an
.icechunksuffix and contain the resolution in the name. - The returned dataset is in EPSG:3413, not the input geobox's CRS.
Example
Load ArcticDEM with a buffer for terrain analysis:
from math import ceil, sqrt
from darts_acquisition import load_arcticdem
# Assume "optical" is a loaded Sentinel-2 dataset
arcticdem = load_arcticdem(
geobox=optical.odc.geobox,
data_dir="/data/arcticdem_2m.icechunk",
resolution=2,
buffer=ceil(128 / 2 * sqrt(2)), # Buffer for TPI with 128m radius
offline=False
)
# Reproject to match optical data's CRS and resolution
arcticdem = arcticdem.odc.reproject(optical.odc.geobox, resampling="cubic")
Source code in darts-acquisition/src/darts_acquisition/arcticdem.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | |
load_cdse_s2_sr_scene
¶
load_cdse_s2_sr_scene(
s2item: str | pystac.Item,
bands_mapping: dict | typing.Literal["all"] = {
"B02_10m": "blue",
"B03_10m": "green",
"B04_10m": "red",
"B08_10m": "nir",
},
store: pathlib.Path | None = None,
aws_profile_name: str = "default",
offline: bool = False,
output_dir_for_debug_geotiff: pathlib.Path
| None = None,
device: typing.Literal["cuda", "cpu"]
| int = darts_utils.cuda.DEFAULT_DEVICE,
) -> xarray.Dataset
Load a Sentinel-2 scene from CDSE, downloading from STAC API if necessary.
This function loads Sentinel-2 Level-2A surface reflectance data from the Copernicus Data Space Ecosystem (CDSE). If a local store is provided, the data is cached for efficient repeated access. The function handles quality masking, reflectance scaling, and optional GPU acceleration.
The download logic is basically as follows:
IF flag:raw-data-store THEN
IF exist_local THEN
open -> memory
ELIF online THEN
download -> memory
save
ELIF offline THEN
RAISE ERROR
ENDIF
ELIF online THEN
download -> memory
ELIF offline THEN
RAISE ERROR
ENDIF
Parameters:
-
s2item(str | pystac.Item) –Sentinel-2 scene identifier or PySTAC Item object.
-
bands_mapping(dict | typing.Literal['all'], default:{'B02_10m': 'blue', 'B03_10m': 'green', 'B04_10m': 'red', 'B08_10m': 'nir'}) –Mapping of Sentinel-2 band names to custom band names. Keys should be CDSE band names (e.g., "B02_10m"), values are output names. Use "all" to load all optical bands and SCL. Defaults to {"B02_10m": "blue", "B03_10m": "green", "B04_10m": "red", "B08_10m": "nir"}.
-
store(pathlib.Path | None, default:None) –Path to local zarr store for caching. If None, data is loaded directly without caching. Defaults to None.
-
aws_profile_name(str, default:'default') –AWS profile name for Copernicus S3 authentication. Defaults to "default".
-
offline(bool, default:False) –If True, only loads from local store without downloading. Requires
storeto be provided. If False, missing data is downloaded. Defaults to False. -
output_dir_for_debug_geotiff(pathlib.Path | None, default:None) –If provided, writes raw data as GeoTIFF files for debugging. Defaults to None.
-
device(typing.Literal['cuda', 'cpu'] | int, default:darts_utils.cuda.DEFAULT_DEVICE) –Device for processing (GPU or CPU). Defaults to DEFAULT_DEVICE.
Returns:
-
xarray.Dataset–xr.Dataset: Sentinel-2 dataset with the following data variables based on bands_mapping: - Optical bands (float32): Surface reflectance values [~-0.1 to ~1.0] Default bands: blue, green, red, nir Additional bands available: coastal, rededge071, rededge075, rededge078, nir08, nir09, swir16, swir22 Each has attributes: - long_name: "Sentinel-2 {Band}" - units: "Reflectance" - data_source: "Sentinel-2 L2A via Copernicus STAC API (sentinel-2-l2a)" - s2_scl (uint8): Scene Classification Layer Attributes: long_name, description of class values (0=NO_DATA, 1=SATURATED, etc.) - quality_data_mask (uint8): Derived quality mask - 0 = Invalid (no data, saturated, or defective) - 1 = Low quality (shadows, clouds, cirrus, snow/ice, water) - 2 = High quality (clear vegetation or non-vegetated land) - valid_data_mask (uint8): Binary validity mask (1=valid, 0=invalid)
Dataset attributes: - azimuth (float): Solar azimuth angle from view:azimuth - elevation (float): Solar elevation angle from view:sun_elevation - s2_tile_id (str): Scene identifier - tile_id (str): Scene identifier (same as s2_tile_id) - Plus additional STAC metadata fields
Note
The offline parameter controls data fetching:
- When offline=False: Automatically downloads missing data from CDSE and stores it
in the local zarr store (if store is provided).
- When offline=True: Only reads from the local store. Raises an error if data is
missing or if store is None.
Reflectance processing: - Raw DN values are scaled: (DN / 10000.0) - 0.1 - Pixels where SCL==0 or DN==0 are masked as NaN - This matches the data format from GEE and Planet loaders
Quality mask derivation from SCL: - Invalid (0): NO_DATA, SATURATED_OR_DEFECTIVE - Low quality (1): CAST_SHADOWS, CLOUD_SHADOWS, CLOUD_*, THIN_CIRRUS, SNOW/ICE, WATER - High quality (2): VEGETATION, NOT_VEGETATED
Example
Load scene with local caching:
from pathlib import Path
from darts_acquisition import load_cdse_s2_sr_scene
from darts_utils.copernicus import init_copernicus
# Setup authentication
init_copernicus(profile_name="default")
# Load with caching
s2_ds = load_cdse_s2_sr_scene(
s2item="S2A_MSIL2A_20230615T123456_N0509_R012_T33UUP_20230615T145678",
bands_mapping="all",
store=Path("/data/s2_store"),
offline=False # Download if not cached
)
# Compute NDVI
ndvi = (s2_ds.nir - s2_ds.red) / (s2_ds.nir + s2_ds.red)
# Filter to high quality pixels
s2_filtered = s2_ds.where(s2_ds.quality_data_mask == 2)
Source code in darts-acquisition/src/darts_acquisition/s2/cdse_scene.py
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | |
load_gee_s2_sr_scene
¶
load_gee_s2_sr_scene(
s2item: str | ee.Image,
bands_mapping: dict | typing.Literal["all"] = {
"B2": "blue",
"B3": "green",
"B4": "red",
"B8": "nir",
},
store: pathlib.Path | None = None,
offline: bool = False,
output_dir_for_debug_geotiff: pathlib.Path
| None = None,
device: typing.Literal["cuda", "cpu"]
| int = darts_utils.cuda.DEFAULT_DEVICE,
) -> xarray.Dataset
Load a Sentinel-2 scene from Google Earth Engine, downloading if necessary.
This function loads Sentinel-2 Level-2A surface reflectance data from Google Earth Engine. If a local store is provided, the data is cached for efficient repeated access. The function handles quality masking, reflectance scaling with time-dependent offsets, and optional GPU acceleration. It also handles NaN values in the data by masking them as invalid.
The download logic is basically as follows:
IF flag:raw-data-store THEN
IF exist_local THEN
open -> memory
ELIF online THEN
download -> memory
save
ELIF offline THEN
RAISE ERROR
ENDIF
ELIF online THEN
download -> memory
ELIF offline THEN
RAISE ERROR
ENDIF
Parameters:
-
s2item(str | ee.Image) –Sentinel-2 scene identifier or ee.Image object from COPERNICUS/S2_SR.
-
bands_mapping(dict | typing.Literal['all'], default:{'B2': 'blue', 'B3': 'green', 'B4': 'red', 'B8': 'nir'}) –Mapping of Sentinel-2 band names to custom band names. Keys should be GEE band names (e.g., "B2", "B3"), values are output names. Use "all" to load all optical bands and SCL. Defaults to {"B2": "blue", "B3": "green", "B4": "red", "B8": "nir"}.
-
store(pathlib.Path | None, default:None) –Path to local zarr store for caching. If None, data is loaded directly without caching. Defaults to None.
-
offline(bool, default:False) –If True, only loads from local store without downloading. Requires
storeto be provided. If False, missing data is downloaded. Defaults to False. -
output_dir_for_debug_geotiff(pathlib.Path | None, default:None) –If provided, writes raw data as GeoTIFF files for debugging. Defaults to None.
-
device(typing.Literal['cuda', 'cpu'] | int, default:darts_utils.cuda.DEFAULT_DEVICE) –Device for processing (GPU or CPU). Defaults to DEFAULT_DEVICE.
Returns:
-
xarray.Dataset–xr.Dataset: Sentinel-2 dataset with the following data variables based on bands_mapping: - Optical bands (float32): Surface reflectance values [~-0.1 to ~1.0 for newer scenes, ~0.0 to ~1.0 for scenes before 2022-01-25] Default bands: blue, green, red, nir Additional bands available: coastal, rededge071, rededge075, rededge078, nir08, nir09, swir16, swir22 Each has attributes: - long_name: "Sentinel 2 {Band}" - units: "Reflectance" - data_source: "Sentinel-2 L2A via Google Earth Engine (COPERNICUS/S2_SR)" - s2_scl (uint8): Scene Classification Layer Attributes: long_name, description of class values (0=NO_DATA, 1=SATURATED, etc.) - quality_data_mask (uint8): Derived quality mask - 0 = Invalid (no data, saturated, defective, or NaN values) - 1 = Low quality (shadows, clouds, cirrus, snow/ice, water) - 2 = High quality (clear vegetation or non-vegetated land) - valid_data_mask (uint8): Binary validity mask (1=valid, 0=invalid)
Dataset attributes: - azimuth (float): Solar azimuth angle from MEAN_SOLAR_AZIMUTH_ANGLE - elevation (float): Solar elevation angle from MEAN_SOLAR_ZENITH_ANGLE - s2_tile_id (str): Full PRODUCT_ID from GEE - tile_id (str): Scene identifier - time (str): Acquisition timestamp
Note
The offline parameter controls data fetching:
- When offline=False: Automatically downloads missing data from GEE and stores it
in the local zarr store (if store is provided).
- When offline=True: Only reads from the local store. Raises an error if data is
missing or if store is None.
Reflectance processing: - For scenes >= 2022-01-25: (DN / 10000.0) - 0.1 (processing baseline 04.00+) - For scenes < 2022-01-25: DN / 10000.0 (older processing baseline) - NaN values are filled with 0 and marked as invalid in quality_data_mask - Pixels where SCL is NaN are also masked as invalid
This function handles spatially random NaN values that can occur in GEE data by marking them as invalid and filling with 0 to prevent propagation in calculations.
Quality mask derivation from SCL: - Invalid (0): NO_DATA, SATURATED_OR_DEFECTIVE, or NaN values - Low quality (1): CAST_SHADOWS, CLOUD_SHADOWS, CLOUD_*, THIN_CIRRUS, SNOW/ICE, WATER - High quality (2): VEGETATION, NOT_VEGETATED
Example
Load scene with local caching:
import ee
from pathlib import Path
from darts_acquisition import load_gee_s2_sr_scene
# Initialize Earth Engine
ee.Initialize()
# Load with caching
s2_ds = load_gee_s2_sr_scene(
s2item="20230615T123456_20230615T123659_T33UUP",
bands_mapping="all",
store=Path("/data/s2_store"),
offline=False # Download if not cached
)
# Compute NDVI
ndvi = (s2_ds.nir - s2_ds.red) / (s2_ds.nir + s2_ds.red)
# Filter to high quality pixels
s2_filtered = s2_ds.where(s2_ds.quality_data_mask == 2)
Source code in darts-acquisition/src/darts_acquisition/s2/gee_scene.py
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | |
load_planet_masks
¶
Load quality and validity masks from a PlanetScope scene's UDM-2 data.
This function extracts data quality information from the PlanetScope Usable Data Mask (UDM-2) to create simplified quality masks for filtering and analysis.
Parameters:
-
fpath(str | pathlib.Path) –Path to the directory containing the PlanetScope scene data. Must contain _udm2.tif (or _udm2_clip.tif) file.
Returns:
-
xarray.Dataset–xr.Dataset: Dataset containing quality mask information with the following data variables: - quality_data_mask (uint8): Combined quality indicator * 0 = Invalid (no data) * 1 = Low quality (clouds, shadows, haze, snow, or other artifacts) * 2 = High quality (clear, usable data) Attributes: data_source="planet", long_name="Quality data mask", description="0 = Invalid, 1 = Low Quality, 2 = High Quality" - planet_udm (uint8): Raw UDM-2 bands (8 bands) Attributes: data_source="planet", long_name="Planet UDM", description="Usable Data Mask"
Raises:
-
FileNotFoundError–If the UDM-2 TIFF file is not found in the directory.
Note
Quality mask derivation logic: - Invalid: UDM band 8 (no data) is set - Low quality: Any of UDM bands 2-6 (clouds, shadows, haze, snow, or artifacts) is set - High quality: Neither invalid nor low quality
UDM-2 band definitions: 1. Clear - 2. Snow - 3. Shadow - 4. Light Haze - 5. Heavy Haze 6. Cloud - 7. Confidence - 8. No Data
Example
Load and apply quality masks:
from darts_acquisition import load_planet_scene, load_planet_masks
# Load scene and masks
scene = load_planet_scene("/data/planet/20230615_123045_1234")
masks = load_planet_masks("/data/planet/20230615_123045_1234")
# Filter to high quality pixels only
scene_filtered = scene.where(masks.quality_data_mask == 2)
# Count quality distribution
import numpy as np
unique, counts = np.unique(
masks.quality_data_mask.values,
return_counts=True
)
print(dict(zip(unique, counts)))
Source code in darts-acquisition/src/darts_acquisition/planet.py
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 | |
load_planet_scene
¶
Load a PlanetScope satellite scene from GeoTIFF files.
This function loads PlanetScope surface reflectance data (PSScene or PSOrthoTile) from a directory containing TIFF files and metadata. The scene type is automatically detected from the directory name format.
Parameters:
-
fpath(str | pathlib.Path) –Path to the directory containing the PlanetScope scene data. The directory must follow PlanetScope naming conventions: - Scene: YYYYMMDD_HHMMSS_NN_XXXX or YYYYMMDD_HHMMSS_XXXX - Orthotile: NNNNNNN_NNNNNNN_YYYY-MM-DD_XXXX Must contain _SR.tif (or _SR_clip.tif) and *_metadata.json files.
Returns:
-
xarray.Dataset–xr.Dataset: The loaded PlanetScope dataset with the following data variables: - blue (float32): Blue band surface reflectance [0-1] - green (float32): Green band surface reflectance [0-1] - red (float32): Red band surface reflectance [0-1] - nir (float32): Near-infrared band surface reflectance [0-1]
Each variable has attributes: - long_name: "PLANET {Band}" - units: "Reflectance" - data_source: "planet" - planet_type: "scene" or "orthotile"
Dataset-level attributes: - azimuth (float): Solar azimuth angle in degrees - elevation (float): Solar elevation angle in degrees - tile_id (str): Unique identifier for the scene - planet_scene_id (str): Scene identifier (for scenes) or scene portion (for orthotiles) - planet_orthotile_id (str): Orthotile identifier (only for orthotiles)
Raises:
-
FileNotFoundError–If required TIFF or metadata files are not found in the directory.
Note
- Input DN values are divided by 10000 to convert to reflectance [0-1].
- The scene type (PSScene vs PSOrthoTile) is automatically detected from the directory name.
- Solar geometry is extracted from the metadata JSON file.
Example
Load a PlanetScope scene:
from darts_acquisition import load_planet_scene
# Load scene data
planet_ds = load_planet_scene("/data/planet/20230615_123045_1234")
# Access bands
ndvi = (planet_ds.nir - planet_ds.red) / (planet_ds.nir + planet_ds.red)
# Check solar geometry
print(f"Solar azimuth: {planet_ds.azimuth}")
print(f"Solar elevation: {planet_ds.elevation}")
Source code in darts-acquisition/src/darts_acquisition/planet.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | |
load_tcvis
¶
load_tcvis(
geobox: odc.geo.geobox.GeoBox,
data_dir: pathlib.Path | str,
buffer: int = 0,
offline: bool = False,
) -> xarray.Dataset
Load TCVIS (Tasseled Cap trends) for the given geobox, fetch new data from GEE if necessary.
This function loads Tasseled Cap trend data from a local icechunk store. If offline=False,
missing data will be automatically downloaded from Google Earth Engine and stored locally.
The data contains temporal trends in brightness, greenness, and wetness derived from
Landsat imagery.
Parameters:
-
geobox(odc.geo.geobox.GeoBox) –The geobox for which to load the data. Can be in any CRS.
-
data_dir(pathlib.Path | str) –Path to the icechunk data directory (must have .icechunk suffix). This directory stores downloaded TCVIS data for faster consecutive access.
-
buffer(int, default:0) –Buffer around the geobox in pixels. The buffer is applied in the TCVIS dataset's native CRS after reprojecting the input geobox. Defaults to 0.
-
offline(bool, default:False) –If True, only loads data already present in the local store without attempting any downloads. If False, missing data is downloaded from GEE. Defaults to False.
Returns:
-
xarray.Dataset–xr.Dataset: The TCVIS dataset with the following data variables: - tc_brightness (float): Temporal trend in Tasseled Cap brightness component - tc_greenness (float): Temporal trend in Tasseled Cap greenness component - tc_wetness (float): Temporal trend in Tasseled Cap wetness component
The dataset is in the TCVIS native CRS with the buffer applied. It is NOT automatically reprojected to match the input geobox's CRS.
Note
The offline parameter controls data fetching behavior:
- When
offline=False: Usessmart_geocubesaccessor'sload()method which automatically downloads missing tiles from GEE and persists them to the icechunk store. - When
offline=True: Uses the accessor'sopen_xarray()method to open the existing store and crops it to the requested region. Raises an error if data is missing.
Variable naming: The original TCB_slope, TCG_slope, and TCW_slope variables are renamed to follow DARTS conventions (tc_brightness, tc_greenness, tc_wetness).
Example
Load TCVIS data aligned with optical imagery:
from darts_acquisition import load_tcvis
# Assume "optical" is a loaded Sentinel-2 dataset
tcvis = load_tcvis(
geobox=optical.odc.geobox,
data_dir="/data/tcvis.icechunk",
buffer=0,
offline=False
)
# Reproject to match optical data's CRS and resolution
tcvis = tcvis.odc.reproject(optical.odc.geobox, resampling="cubic")
Source code in darts-acquisition/src/darts_acquisition/tcvis.py
match_cdse_s2_sr_scene_ids_from_geodataframe
¶
match_cdse_s2_sr_scene_ids_from_geodataframe(
aoi: geopandas.GeoDataFrame,
day_range: int = 60,
max_cloud_cover: int = 20,
min_intersects: float = 0.7,
simplify_geometry: float
| typing.Literal[False] = False,
save_scores: pathlib.Path | None = None,
) -> dict[int, pystac.Item | None]
Match items from a GeoDataFrame with Sentinel-2 items from the STAC API based on a date range.
Parameters:
-
aoi(geopandas.GeoDataFrame) –The area of interest as a GeoDataFrame.
-
day_range(int, default:60) –The number of days before and after the date to search for. Defaults to 60.
-
max_cloud_cover(int, default:20) –The maximum cloud cover percentage. Defaults to 20.
-
min_intersects(float, default:0.7) –The minimum intersection area ratio to consider a match. Defaults to 0.7.
-
simplify_geometry(float | typing.Literal[False], default:False) –If a float is provided, the geometry will be simplified using the
simplifymethod of geopandas. If False, no simplification will be done. This may become useful for large / weird AOIs which are too large for the STAC API. Defaults to False. -
save_scores(pathlib.Path | None, default:None) –If provided, the scores will be saved to this path as a Parquet file.
Raises:
-
ValueError–If the 'date' column is not present or not of type datetime.
Returns:
-
dict[int, pystac.Item | None]–dict[int, Item | None]: A dictionary mapping each row to its best matching Sentinel-2 item. The keys are the indices of the rows in the GeoDataFrame, and the values are the matching Sentinel-2 items. If no matching item is found, the value will be None.
Source code in darts-acquisition/src/darts_acquisition/s2/cdse_scene.py
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 | |
parse_planet_type
¶
Parse the type of Planet data from the directory path.
Parameters:
Returns:
Raises:
-
ValueError–If the Planet data type cannot be parsed from the file path.
Source code in darts-acquisition/src/darts_acquisition/planet.py
search_cdse_s2_sr
¶
search_cdse_s2_sr(
intersects=None,
tiles: list[str] | None = None,
start_date: str | None = None,
end_date: str | None = None,
max_cloud_cover: int | None = 10,
max_snow_cover: int | None = 10,
months: list[int] | None = None,
years: list[int] | None = None,
) -> dict[str, pystac.Item]
Search for Sentinel-2 scenes via STAC based on an area of interest (intersects) and date range.
Note
start_date and end_date will be concatted with a / to form a date range.
Read more about the date format here: https://pystac-client.readthedocs.io/en/stable/api.html#pystac_client.Client.search
Parameters:
-
intersects(any, default:None) –The geometry object to search for Sentinel-2 tiles. Can be anything implementing the
__geo_interface__protocol, such as a GeoDataFrame or a shapely geometry. If None, and tiles is also None, the search will be performed globally. If set and tiles is also set, will be ignored. -
tiles(list[str] | None, default:None) –List of MGRS tile IDs to filter the search. If set, ignores intersects parameter. Defaults to None.
-
start_date(str, default:None) –Starting date in a format readable by pystac_client. If None, months and years parameters will be used for filtering if set. Defaults to None.
-
end_date(str, default:None) –Ending date in a format readable by pystac_client. If None, months and years parameters will be used for filtering if set. Defaults to None.
-
max_cloud_cover(int, default:10) –Maximum percentage of cloud cover. Defaults to 10.
-
max_snow_cover(int, default:10) –Maximum percentage of snow cover. Defaults to 10.
-
months(list[int] | None, default:None) –List of months (1-12) to filter the search. Only used if start_date and end_date are None. Defaults to None.
-
years(list[int] | None, default:None) –List of years to filter the search. Only used if start_date and end_date are None. Defaults to None.
Returns:
-
dict[str, pystac.Item]–dict[str, Item]: A dictionary of found Sentinel-2 items as values and the s2id as keys.
Source code in darts-acquisition/src/darts_acquisition/s2/cdse_scene.py
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 | |