-
Notifications
You must be signed in to change notification settings - Fork 387
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1980 from AdeelH/xarray_source_config
Add `XarraySourceConfig` to allow specifying an `XarraySource` from STAC Items
- Loading branch information
Showing
8 changed files
with
218 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
54 changes: 54 additions & 0 deletions
54
rastervision_core/rastervision/core/data/raster_source/stac_config.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
from typing import TYPE_CHECKING, List, Optional | ||
|
||
from rastervision.pipeline.config import (Config, Field, register_config) | ||
from rastervision.pipeline.file_system.utils import file_to_json | ||
|
||
if TYPE_CHECKING: | ||
from pystac import Item, ItemCollection | ||
|
||
|
||
@register_config('stac_item') | ||
class STACItemConfig(Config): | ||
"""Specify a raster via a STAC Item.""" | ||
|
||
uri: str = Field(..., description='URI to a JSON-serialized STAC Item.') | ||
assets: Optional[List[str]] = Field( | ||
None, | ||
description= | ||
'Subset of assets to use. This should be a list of asset keys') | ||
|
||
def build(self) -> 'Item': | ||
from pystac import Item | ||
|
||
item = Item.from_dict(file_to_json(self.uri)) | ||
if self.assets is not None: | ||
item = subset_assets(item, self.assets) | ||
return item | ||
|
||
|
||
@register_config('stac_item_collection') | ||
class STACItemCollectionConfig(Config): | ||
"""Specify a raster via a STAC ItemCollection.""" | ||
|
||
uri: str = Field( | ||
..., description='URI to a JSON-serialized STAC ItemCollection.') | ||
assets: Optional[List[str]] = Field( | ||
None, | ||
description= | ||
'Subset of assets to use. This should be a list of asset keys') | ||
|
||
def build(self) -> 'ItemCollection': | ||
from pystac import ItemCollection | ||
|
||
items = ItemCollection.from_dict(file_to_json(self.uri)) | ||
if self.assets is not None: | ||
items = [subset_assets(item, self.assets) for item in items] | ||
items = ItemCollection(items) | ||
return items | ||
|
||
|
||
def subset_assets(item: 'Item', assets: List[str]) -> 'Item': | ||
"""Subset the assets in a STAC Item.""" | ||
src_assets = item.assets | ||
item.assets = {k: src_assets[k] for k in assets} | ||
return item |
76 changes: 76 additions & 0 deletions
76
rastervision_core/rastervision/core/data/raster_source/xarray_source_config.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
from typing import Optional, Tuple, Union | ||
import logging | ||
|
||
from rastervision.pipeline.config import Field, register_config | ||
from rastervision.core.box import Box | ||
from rastervision.core.data.raster_source.raster_source_config import ( | ||
RasterSourceConfig) | ||
from rastervision.core.data.crs_transformer import RasterioCRSTransformer | ||
from rastervision.core.data.raster_source.stac_config import ( | ||
STACItemConfig, STACItemCollectionConfig) | ||
from rastervision.core.data.raster_source.xarray_source import (XarraySource) | ||
|
||
log = logging.getLogger(__name__) | ||
|
||
|
||
@register_config('xarray_source') | ||
class XarraySourceConfig(RasterSourceConfig): | ||
"""Configure an :class:`.XarraySource`.""" | ||
|
||
stac: Union[STACItemConfig, STACItemCollectionConfig] = Field( | ||
..., | ||
description='STAC Item or ItemCollection to build the DataArray from.') | ||
allow_streaming: bool = Field( | ||
True, | ||
description='If False, load the entire DataArray into memory. ' | ||
'Defaults to True.') | ||
bbox_map_coords: Optional[Tuple[float, float, float, float]] = Field( | ||
None, | ||
description='Optional user-specified bbox in EPSG:4326 coords of the ' | ||
'form (ymin, xmin, ymax, xmax). Useful for cropping the raster source ' | ||
'so that only part of the raster is read from. This is ignored if ' | ||
'bbox is also specified. Defaults to None.') | ||
temporal: bool = Field( | ||
False, description='Whether the data is a time-series.') | ||
|
||
def build(self, | ||
tmp_dir: Optional[str] = None, | ||
use_transformers: bool = True) -> XarraySource: | ||
import stackstac | ||
|
||
item_or_item_collection = self.stac.build() | ||
data_array = stackstac.stack(item_or_item_collection) | ||
|
||
if not self.temporal and 'time' in data_array.dims: | ||
if len(data_array.time) > 1: | ||
raise ValueError('temporal=False but len(data_array.time) > 1') | ||
data_array = data_array.isel(time=0) | ||
|
||
if not self.allow_streaming: | ||
from humanize import naturalsize | ||
log.info('Loading the full DataArray into memory ' | ||
f'({naturalsize(data_array.nbytes)}).') | ||
data_array.load() | ||
|
||
crs_transformer = RasterioCRSTransformer( | ||
transform=data_array.transform, image_crs=data_array.crs) | ||
raster_transformers = ([rt.build() for rt in self.transformers] | ||
if use_transformers else []) | ||
|
||
if self.bbox is not None: | ||
log.info('Using bbox and ignoring bbox_map_coords.') | ||
bbox = Box(*self.bbox) | ||
elif self.bbox_map_coords is not None: | ||
bbox_map_coords = Box(*self.bbox_map_coords) | ||
bbox = crs_transformer.map_to_pixel(bbox_map_coords).normalize() | ||
else: | ||
bbox = None | ||
|
||
raster_source = XarraySource( | ||
data_array, | ||
crs_transformer=crs_transformer, | ||
raster_transformers=raster_transformers, | ||
channel_order=self.channel_order, | ||
bbox=bbox, | ||
temporal=self.temporal) | ||
return raster_source |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import unittest | ||
|
||
from pystac import Item, ItemCollection | ||
|
||
from rastervision.core.data.raster_source import (STACItemConfig, | ||
STACItemCollectionConfig) | ||
|
||
from tests import data_file_path | ||
|
||
|
||
class TestSTACItemConfig(unittest.TestCase): | ||
def test_build(self): | ||
uri = data_file_path('stac/item.json') | ||
cfg = STACItemConfig(uri=uri, assets=['red']) | ||
item = cfg.build() | ||
self.assertIsInstance(item, Item) | ||
self.assertEqual(len(item.assets), 1) | ||
self.assertIn('red', item.assets) | ||
|
||
|
||
class TestSTACItemCollectionConfig(unittest.TestCase): | ||
def test_build(self): | ||
uri = data_file_path('stac/item_collection.json') | ||
cfg = STACItemCollectionConfig(uri=uri, assets=['red']) | ||
items = cfg.build() | ||
self.assertIsInstance(items, ItemCollection) | ||
self.assertEqual(len(items), 3) | ||
for item in items: | ||
self.assertEqual(len(item.assets), 1) | ||
self.assertIn('red', item.assets) | ||
|
||
|
||
if __name__ == '__main__': | ||
unittest.main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
Large diffs are not rendered by default.
Oops, something went wrong.