-
Notifications
You must be signed in to change notification settings - Fork 22
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Split kerchunk reader up #261
Merged
Merged
Changes from 21 commits
Commits
Show all changes
29 commits
Select commit
Hold shift + click to select a range
89ff49a
standardize zarr v3 and dmrpp readers behind dedicated open_virtual_d…
TomNicholas 8d6c42a
refactor hdf5 reader behind open_virtual_dataset function
TomNicholas eb7444e
refactor netcdf3
TomNicholas bb39907
refactor tiff
TomNicholas 97fc588
refactor fits
TomNicholas 2e197e2
refactored so create VirtualBackends
TomNicholas f29d2ff
restore backend.py, but keep readers/common.py
TomNicholas 5a8b18e
oops I deleted a file
TomNicholas 84330f0
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 0e2fa71
standardize open_virtual_dataset method signature, and raise NotImple…
TomNicholas 996d81a
fix bug with zarr reader
TomNicholas bf71ae3
remove todo
TomNicholas 79477a9
Merge branch 'split_kerchunk_reader' of https://github.com/TomNichola…
TomNicholas fc2f3bc
make open_virtual_dataset a staticmethod
TomNicholas d955e1a
try to fix mypy error about importing DataTree from versions of xarra…
TomNicholas 4c5a2bb
mypy
TomNicholas e592933
sanitize drop_variables and loadable_variables
TomNicholas 6a2179e
implement drop_variables for kerchunk reader
TomNicholas 74a6b6c
sanitize drmpp args
TomNicholas 6bafd5b
pass all arguments to kerchunk reader
TomNicholas b41e5d8
coerce kerchunk refs to our types
TomNicholas bf78b84
make sure all readers are passed the same set of args
TomNicholas 0ae7437
Merge branch 'main' into split_kerchunk_reader
TomNicholas 180a0fd
fix bad merge, and refactor determine_chunk_grid_shape a bit
TomNicholas 8b987c6
Merge branch 'split_kerchunk_reader' of https://github.com/TomNichola…
TomNicholas edf0372
ensure decode_times is passed to each reader
TomNicholas 55d152d
remove match case statement in favour of mapping
TomNicholas f6c75da
ensure optional dependencies aren't imported
TomNicholas 7995b1c
release note
TomNicholas File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
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,195 @@ | ||
import os | ||
import warnings | ||
from abc import ABC | ||
from collections.abc import Iterable, Mapping, MutableMapping | ||
from io import BufferedIOBase | ||
from typing import ( | ||
TYPE_CHECKING, | ||
Any, | ||
Hashable, | ||
Optional, | ||
cast, | ||
) | ||
|
||
import xarray as xr | ||
from xarray import Dataset | ||
from xarray.backends import AbstractDataStore, BackendArray | ||
from xarray.core.indexes import Index, PandasIndex | ||
from xarray.core.variable import IndexVariable, Variable | ||
|
||
from virtualizarr.manifests import ManifestArray | ||
from virtualizarr.utils import _FsspecFSFromFilepath | ||
|
||
XArrayOpenT = str | os.PathLike[Any] | BufferedIOBase | AbstractDataStore | ||
|
||
if TYPE_CHECKING: | ||
try: | ||
from xarray import DataTree # type: ignore[attr-defined] | ||
except ImportError: | ||
DataTree = Any | ||
|
||
|
||
class ManifestBackendArray(ManifestArray, BackendArray): | ||
"""Using this prevents xarray from wrapping the KerchunkArray in ExplicitIndexingAdapter etc.""" | ||
|
||
... | ||
|
||
|
||
def open_loadable_vars_and_indexes( | ||
filepath: str, | ||
loadable_variables, | ||
reader_options, | ||
drop_variables, | ||
indexes, | ||
group, | ||
decode_times, | ||
) -> tuple[Mapping[str, Variable], Mapping[str, Index]]: | ||
""" | ||
Open selected variables and indexes using xarray. | ||
|
||
Relies on xr.open_dataset and its auto-detection of filetypes to find the correct installed backend. | ||
""" | ||
|
||
# TODO get rid of this if? | ||
if indexes is None or len(loadable_variables) > 0: | ||
# TODO we are reading a bunch of stuff we know we won't need here, e.g. all of the data variables... | ||
# TODO it would also be nice if we could somehow consolidate this with the reading of the kerchunk references | ||
# TODO really we probably want a dedicated xarray backend that iterates over all variables only once | ||
fpath = _FsspecFSFromFilepath( | ||
filepath=filepath, reader_options=reader_options | ||
).open_file() | ||
|
||
# fpath can be `Any` thanks to fsspec.filesystem(...).open() returning Any. | ||
# We'll (hopefully safely) cast it to what xarray is expecting, but this might let errors through. | ||
|
||
ds = xr.open_dataset( | ||
cast(XArrayOpenT, fpath), | ||
drop_variables=drop_variables, | ||
group=group, | ||
decode_times=decode_times, | ||
) | ||
|
||
if indexes is None: | ||
warnings.warn( | ||
"Specifying `indexes=None` will create in-memory pandas indexes for each 1D coordinate, but concatenation of ManifestArrays backed by pandas indexes is not yet supported (see issue #18)." | ||
"You almost certainly want to pass `indexes={}` to `open_virtual_dataset` instead." | ||
) | ||
|
||
# add default indexes by reading data from file | ||
indexes = {name: index for name, index in ds.xindexes.items()} | ||
elif indexes != {}: | ||
# TODO allow manual specification of index objects | ||
raise NotImplementedError() | ||
else: | ||
indexes = dict(**indexes) # for type hinting: to allow mutation | ||
|
||
# TODO we should drop these earlier by using drop_variables | ||
loadable_vars = { | ||
str(name): var | ||
for name, var in ds.variables.items() | ||
if name in loadable_variables | ||
} | ||
|
||
# if we only read the indexes we can just close the file right away as nothing is lazy | ||
if loadable_vars == {}: | ||
ds.close() | ||
else: | ||
loadable_vars = {} | ||
indexes = {} | ||
|
||
return loadable_vars, indexes | ||
|
||
|
||
def construct_virtual_dataset( | ||
virtual_vars, | ||
loadable_vars, | ||
indexes, | ||
coord_names, | ||
attrs, | ||
) -> Dataset: | ||
"""Construct a virtual Datset from consistuent parts.""" | ||
|
||
vars = {**virtual_vars, **loadable_vars} | ||
|
||
data_vars, coords = separate_coords(vars, indexes, coord_names) | ||
|
||
vds = xr.Dataset( | ||
data_vars, | ||
coords=coords, | ||
# indexes={}, # TODO should be added in a later version of xarray | ||
attrs=attrs, | ||
) | ||
|
||
# TODO we should probably also use vds.set_close() to tell xarray how to close the file we opened | ||
|
||
return vds | ||
|
||
|
||
def separate_coords( | ||
vars: Mapping[str, xr.Variable], | ||
indexes: MutableMapping[str, Index], | ||
coord_names: Iterable[str] | None = None, | ||
) -> tuple[dict[str, xr.Variable], xr.Coordinates]: | ||
""" | ||
Try to generate a set of coordinates that won't cause xarray to automatically build a pandas.Index for the 1D coordinates. | ||
|
||
Currently requires this function as a workaround unless xarray PR #8124 is merged. | ||
|
||
Will also preserve any loaded variables and indexes it is passed. | ||
""" | ||
|
||
if coord_names is None: | ||
coord_names = [] | ||
|
||
# split data and coordinate variables (promote dimension coordinates) | ||
data_vars = {} | ||
coord_vars: dict[ | ||
str, tuple[Hashable, Any, dict[Any, Any], dict[Any, Any]] | xr.Variable | ||
] = {} | ||
for name, var in vars.items(): | ||
if name in coord_names or var.dims == (name,): | ||
# use workaround to avoid creating IndexVariables described here https://github.com/pydata/xarray/pull/8107#discussion_r1311214263 | ||
if len(var.dims) == 1: | ||
dim1d, *_ = var.dims | ||
coord_vars[name] = (dim1d, var.data, var.attrs, var.encoding) | ||
|
||
if isinstance(var, IndexVariable): | ||
# unless variable actually already is a loaded IndexVariable, | ||
# in which case we need to keep it and add the corresponding indexes explicitly | ||
coord_vars[str(name)] = var | ||
# TODO this seems suspect - will it handle datetimes? | ||
indexes[name] = PandasIndex(var, dim1d) | ||
else: | ||
coord_vars[name] = var | ||
else: | ||
data_vars[name] = var | ||
|
||
coords = xr.Coordinates(coord_vars, indexes=indexes) | ||
|
||
return data_vars, coords | ||
|
||
|
||
class VirtualBackend(ABC): | ||
@staticmethod | ||
def open_virtual_dataset( | ||
filepath: str, | ||
group: str | None = None, | ||
drop_variables: Iterable[str] | None = None, | ||
loadable_variables: Iterable[str] | None = None, | ||
decode_times: bool | None = None, | ||
indexes: Mapping[str, Index] | None = None, | ||
reader_options: Optional[dict] = None, | ||
) -> Dataset: | ||
raise NotImplementedError() | ||
|
||
@staticmethod | ||
def open_virtual_datatree( | ||
path: str, | ||
group: str | None = None, | ||
drop_variables: Iterable[str] | None = None, | ||
loadable_variables: Iterable[str] | None = None, | ||
decode_times: bool | None = None, | ||
indexes: Mapping[str, Index] | None = None, | ||
reader_options: Optional[dict] = None, | ||
) -> "DataTree": | ||
raise NotImplementedError() |
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
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure that a
@staticmethod
is the best way to do this but for now it's just an internal implementation detail. The important thing is that theopen_virtual_dataset
function signature gets standardized by this approach.