Skip to content

Commit

Permalink
Extend geojson dataset to support more file types
Browse files Browse the repository at this point in the history
Signed-off-by: Harm Matthias Harms <[email protected]>
  • Loading branch information
harm-matthias-harms committed Aug 22, 2024
1 parent 97eac73 commit 42ae4a2
Show file tree
Hide file tree
Showing 5 changed files with 140 additions and 408 deletions.
5 changes: 1 addition & 4 deletions kedro-datasets/RELEASE.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
# Upcoming Release
## Major features and improvements

- Added the following new datasets:
| Type | Description | Location |
| ---- | ----------- | -------- |
| `geopandas.ParquetDataset` | A dataset for loading and saving geopandas dataframe. | `kedro_datasets.geopandas` |
- Add `file_format` to `geopandas.GeoJSONDataSet` to support parquet and feather file formats.

## Bug fixes and other changes
## Breaking Changes
Expand Down
56 changes: 49 additions & 7 deletions kedro-datasets/kedro_datasets/geopandas/geojson_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
underlying functionality is supported by geopandas, so it supports all
allowed geopandas (pandas) options for loading and saving geosjon files.
"""

from __future__ import annotations

import copy
Expand All @@ -18,6 +19,8 @@
get_protocol_and_path,
)

NON_FILE_SYSTEM_TARGETS = ["postgis"]


class GeoJSONDataset(
AbstractVersionedDataset[
Expand All @@ -41,7 +44,7 @@ class GeoJSONDataset(
... {"col1": [1, 2], "col2": [4, 5], "col3": [5, 6]},
... geometry=[Point(1, 1), Point(2, 4)],
... )
>>> dataset = GeoJSONDataset(filepath=tmp_path / "test.geojson", save_args=None)
>>> dataset = GeoJSONDataset(filepath=tmp_path / "test.geojson")
>>> dataset.save(data)
>>> reloaded = dataset.load()
>>>
Expand All @@ -50,12 +53,13 @@ class GeoJSONDataset(
"""

DEFAULT_LOAD_ARGS: dict[str, Any] = {}
DEFAULT_SAVE_ARGS = {"driver": "GeoJSON"}
DEFAULT_SAVE_ARGS: dict[str, Any] = {}

def __init__( # noqa: PLR0913
self,
*,
filepath: str,
file_format: str = "file",
load_args: dict[str, Any] | None = None,
save_args: dict[str, Any] | None = None,
version: Version | None = None,
Expand All @@ -72,6 +76,11 @@ def __init__( # noqa: PLR0913
`s3://`. If prefix is not provided `file` protocol (local filesystem) will be used.
The prefix should be any protocol supported by ``fsspec``.
Note: `http(s)` doesn't support versioning.
file_format: String which is used to match the appropriate load/save method on a best
effort basis. For example if 'parquet' is passed in the `geopandas.read_parquet` and
`geopandas.DataFrame.to_parquet` will be identified. An error will be raised unless
at least one matching `read_{file_format}` or `to_{file_format}` method is
identified. Defaults to 'file'.
load_args: GeoPandas options for loading GeoJSON files.
Here you can find all available arguments:
https://geopandas.org/en/stable/docs/reference/api/geopandas.read_file.html
Expand All @@ -94,6 +103,9 @@ def __init__( # noqa: PLR0913
metadata: Any arbitrary metadata.
This is ignored by Kedro, but may be consumed by users or external plugins.
"""

self._file_format = file_format.lower()

_fs_args = copy.deepcopy(fs_args) or {}
_fs_open_args_load = _fs_args.pop("open_args_load", {})
_fs_open_args_save = _fs_args.pop("open_args_save", {})
Expand Down Expand Up @@ -126,16 +138,45 @@ def __init__( # noqa: PLR0913
self._fs_open_args_load = _fs_open_args_load
self._fs_open_args_save = _fs_open_args_save

def _ensure_file_system_target(self) -> None:
# Fail fast if provided a known non-filesystem target
if self._file_format in NON_FILE_SYSTEM_TARGETS:
raise DatasetError(
f"Cannot create a dataset of file_format '{self._file_format}' as it "
f"does not support a filepath target/source."
)

def _load(self) -> gpd.GeoDataFrame | dict[str, gpd.GeoDataFrame]:
self._ensure_file_system_target()

load_path = get_filepath_str(self._get_load_path(), self._protocol)
with self._fs.open(load_path, **self._fs_open_args_load) as fs_file:
return gpd.read_file(fs_file, **self._load_args)
load_method = getattr(gpd, f"read_{self._file_format}", None)
if load_method:
with self._fs.open(load_path, **self._fs_open_args_load) as fs_file:
return load_method(fs_file, **self._load_args)
raise DatasetError(
f"Unable to retrieve 'geopandas.read_{self._file_format}' method, please ensure that your "
"'file_format' parameter has been defined correctly as per the GeoPandas API "
"https://geopandas.org/en/stable/docs/reference/io.html"
)

def _save(self, data: gpd.GeoDataFrame) -> None:
self._ensure_file_system_target()

save_path = get_filepath_str(self._get_save_path(), self._protocol)
with self._fs.open(save_path, **self._fs_open_args_save) as fs_file:
data.to_file(fs_file, **self._save_args)
self.invalidate_cache()
save_method = getattr(data, f"to_{self._file_format}", None)
if save_method:
with self._fs.open(save_path, **self._fs_open_args_save) as fs_file:
# KEY ASSUMPTION - first argument is path/buffer/io
save_method(fs_file, **self._save_args)
self.invalidate_cache()
else:
raise DatasetError(
f"Unable to retrieve 'geopandas.DataFrame.to_{self._file_format}' method, please "
"ensure that your 'file_format' parameter has been defined correctly as "
"per the GeoPandas API "
"https://geopandas.org/en/stable/docs/reference/io.html"
)

def _exists(self) -> bool:
try:
Expand All @@ -147,6 +188,7 @@ def _exists(self) -> bool:
def _describe(self) -> dict[str, Any]:
return {
"filepath": self._filepath,
"file_format": self._file_format,
"protocol": self._protocol,
"load_args": self._load_args,
"save_args": self._save_args,
Expand Down
162 changes: 0 additions & 162 deletions kedro-datasets/kedro_datasets/geopandas/parquet_dataset.py

This file was deleted.

Loading

0 comments on commit 42ae4a2

Please sign in to comment.