-
-
Notifications
You must be signed in to change notification settings - Fork 34
Add XArraySQLSource for N-dimensional scientific data #1741
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
Merged
Merged
Changes from 1 commit
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
39eea3a
Add XArraySQLSource for N-dimensional scientific data
ghostiee-11 dce1606
Address review feedback: simplify code, add GRIB support and 2D coord…
ghostiee-11 5a91c7c
Merge origin/main, resolve pyproject.toml conflict
ghostiee-11 f2a3162
Fix isort: add blank line between stdlib imports in test file
ghostiee-11 9ed53cd
Address review: drop postgres dialect, add from_dataset, trim deps
ghostiee-11 f549d86
Address review: reduce nesting, prefer netcdf4 for HDF5, add xarray-g…
ghostiee-11 ad250ff
Remove H5 engine detection, drop h5netcdf dep, add xarray-grib extra
ghostiee-11 fd3a25a
Lazy-load xarray imports per review (philippjfr)
ghostiee-11 ebcac86
Move XARRAY_ENGINES and _detect_engine into class per review
ghostiee-11 71040e0
Move _detect_engine after __init__ per review feedback
ghostiee-11 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
This file contains hidden or 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 hidden or 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 |
|---|---|---|
| @@ -1 +1,6 @@ | ||
| from .base import * | ||
|
|
||
| try: | ||
| from .xarray_sql import XArraySQLSource # noqa: F401 | ||
| except ImportError: | ||
| pass |
This file contains hidden or 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,316 @@ | ||||
| """ | ||||
| XArraySQLSource -- SQL-backed xarray source for Lumen. | ||||
|
|
||||
| Uses xarray-sql (Apache DataFusion) to provide SQL query capabilities | ||||
| over N-dimensional xarray datasets. Each data variable in the dataset | ||||
| is exposed as a separate SQL table with coordinate columns. | ||||
| """ | ||||
|
|
||||
| from __future__ import annotations | ||||
|
|
||||
| import math | ||||
|
|
||||
| from pathlib import Path | ||||
| from typing import Any, ClassVar | ||||
|
|
||||
| import param | ||||
|
|
||||
| from ..transforms.sql import SQLFilter | ||||
| from .base import BaseSQLSource, cached | ||||
|
|
||||
| try: | ||||
| import xarray as xr | ||||
|
|
||||
| from xarray_sql import XarrayContext | ||||
| XARRAY_AVAILABLE = True | ||||
| except ImportError: | ||||
| XARRAY_AVAILABLE = False | ||||
|
|
||||
| # Map file extensions to xarray engines | ||||
| XARRAY_ENGINES = { | ||||
| ".nc": "netcdf4", | ||||
| ".nc4": "netcdf4", | ||||
| ".netcdf": "netcdf4", | ||||
| ".h5": "h5netcdf", | ||||
| ".hdf5": "h5netcdf", | ||||
| ".he5": "h5netcdf", | ||||
| ".zarr": "zarr", | ||||
| ".grib": "cfgrib", | ||||
| ".grib2": "cfgrib", | ||||
| ".grb": "cfgrib", | ||||
| ".grb2": "cfgrib", | ||||
| } | ||||
|
|
||||
|
|
||||
| def _detect_engine(path: str) -> str | None: | ||||
| """Detect xarray engine from file extension.""" | ||||
| suffix = Path(path).suffix.lower() | ||||
| return XARRAY_ENGINES.get(suffix) | ||||
|
ahuang11 marked this conversation as resolved.
Outdated
|
||||
|
|
||||
|
|
||||
| class XArraySQLSource(BaseSQLSource): | ||||
| """ | ||||
| SQL-queryable xarray data source for Lumen. | ||||
|
|
||||
| Wraps xarray datasets with Apache DataFusion (via xarray-sql) to | ||||
| provide full SQL query support. Each data variable in the dataset | ||||
| is exposed as a separate SQL table with coordinate columns. | ||||
|
|
||||
| To use this source, install the optional xarray dependencies:: | ||||
|
|
||||
| pip install lumen[xarray] | ||||
|
|
||||
| Parameters | ||||
| ---------- | ||||
| uri : str | ||||
| Path or URL to a NetCDF/Zarr/HDF5/GRIB file. | ||||
| engine : str or None | ||||
| xarray engine to use. Auto-detected from file extension if None. | ||||
| chunks : dict or str or None | ||||
| Chunking specification for dask-backed lazy loading. | ||||
| Use 'auto' for automatic chunking, or a dict like {'time': 100}. | ||||
| open_kwargs : dict | ||||
| Additional keyword arguments passed to xr.open_dataset(). | ||||
| variables : list or None | ||||
| Subset of data variables to expose. None means all variables. | ||||
|
|
||||
| Examples | ||||
| -------- | ||||
| >>> source = XArraySQLSource(uri="air_temperature.nc") | ||||
| >>> source.get_tables() | ||||
| ['air'] | ||||
| >>> df = source.execute("SELECT lat, lon, AVG(air) FROM air GROUP BY lat, lon") | ||||
| >>> schema = source.get_schema("air") | ||||
| """ | ||||
|
|
||||
| source_type: ClassVar[str | None] = "xarray" | ||||
|
|
||||
| dialect = "postgres" | ||||
|
|
||||
| uri = param.String(default=None, allow_None=True, doc=""" | ||||
| Path or URL to the xarray-compatible data file. | ||||
| Supports NetCDF (.nc), Zarr (.zarr), HDF5 (.h5), GRIB (.grib).""") | ||||
|
|
||||
| engine = param.String(default=None, allow_None=True, doc=""" | ||||
| xarray backend engine. Auto-detected from file extension if None. | ||||
| Options: netcdf4, h5netcdf, zarr, cfgrib.""") | ||||
|
|
||||
| chunks = param.Parameter(default="auto", doc=""" | ||||
| Dask chunk specification for lazy loading. | ||||
| Use 'auto', a dict like {'time': 100}, or None for eager loading.""") | ||||
|
|
||||
| open_kwargs = param.Dict(default={}, doc=""" | ||||
| Additional keyword arguments for xr.open_dataset().""") | ||||
|
|
||||
| variables = param.List(default=None, allow_None=True, doc=""" | ||||
| Subset of data variables to expose as tables. | ||||
| None means all variables are exposed.""") | ||||
|
|
||||
| tables = param.ClassSelector(class_=(list, dict), default=None, allow_None=True, doc=""" | ||||
| List or dict of tables. Populated automatically from dataset variables. | ||||
| When a dict, maps logical table names to SQL expressions.""") | ||||
|
|
||||
| sql_expr = param.String(default='SELECT * FROM {table}', doc=""" | ||||
| The SQL expression template for table queries.""") | ||||
|
|
||||
| def __init__(self, _dataset=None, _ctx=None, **params): | ||||
| if not XARRAY_AVAILABLE: | ||||
| raise ImportError( | ||||
| "xarray and xarray-sql are required for XArraySQLSource. " | ||||
| "Install them with: pip install lumen[xarray]" | ||||
| ) | ||||
| super().__init__(**params) | ||||
| self._dataset = _dataset | ||||
|
||||
| self._dataset = _dataset |
ahuang11 marked this conversation as resolved.
ghostiee-11 marked this conversation as resolved.
Outdated
ghostiee-11 marked this conversation as resolved.
ghostiee-11 marked this conversation as resolved.
ahuang11 marked this conversation as resolved.
Outdated
ahuang11 marked this conversation as resolved.
ahuang11 marked this conversation as resolved.
ahuang11 marked this conversation as resolved.
Outdated
ahuang11 marked this conversation as resolved.
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.
Uh oh!
There was an error while loading. Please reload this page.