-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Use narwhals as dataframe-agnostic backend
#7964
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
base: main
Are you sure you want to change the base?
Changes from all commits
f7e4b20
0bcb631
edc1fe7
86a7b05
d32abc8
8a10ba3
f65ad77
a5da840
3553f00
ff7af55
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,23 +11,25 @@ | |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| import importlib | ||
| import io | ||
| import typing | ||
| import urllib.request | ||
|
|
||
| from collections.abc import Sequence | ||
| from copy import copy | ||
| from functools import singledispatch | ||
| from typing import Union, cast | ||
|
|
||
| import narwhals as nw | ||
| import numpy as np | ||
| import pandas as pd | ||
| import pytensor | ||
| import pytensor.tensor as pt | ||
| import xarray as xr | ||
|
|
||
| from narwhals.typing import IntoFrameT, IntoSeriesT | ||
| from pytensor.compile import SharedVariable | ||
| from pytensor.compile.builders import OpFromGraph | ||
| from pytensor.compile.sharedvalue import SharedVariable | ||
| from pytensor.graph.basic import Variable | ||
| from pytensor.raise_op import Assert | ||
| from pytensor.tensor.random.basic import IntegersRV | ||
|
|
@@ -161,65 +163,174 @@ def Minibatch(variable: TensorVariable, *variables: TensorVariable, batch_size: | |
| return mb_tensors if len(variables) else mb_tensors[0] | ||
|
|
||
|
|
||
| def _handle_none_dims( | ||
| dims: Sequence[str | None] | None, ndim: int | ||
| ) -> Sequence[str | None] | Sequence[None]: | ||
| if dims is None: | ||
| return [None] * ndim | ||
| else: | ||
| return dims | ||
|
|
||
|
|
||
| @singledispatch | ||
| def determine_coords( | ||
| model, | ||
| value: pd.DataFrame | pd.Series | xr.DataArray, | ||
| dims: Sequence[str] | None = None, | ||
| value: typing.Any, | ||
| model: "Model", | ||
| dims: Sequence[str | None] | None = None, | ||
| coords: dict[str, Sequence | np.ndarray] | None = None, | ||
| ) -> tuple[dict[str, Sequence | np.ndarray], Sequence[str] | Sequence[None]]: | ||
| ) -> tuple[dict[str, Sequence | np.ndarray], Sequence[str | None] | Sequence[None]]: | ||
| """Determine coordinate values from data or the model (via ``dims``).""" | ||
| raise NotImplementedError( | ||
| f"Cannot determine coordinates for data of type {type(value)}, please provide `coords` explicitly or " | ||
| f"convert the data to a supported type" | ||
| ) | ||
|
|
||
|
|
||
| @determine_coords.register(np.ndarray) | ||
| def determine_array_coords( | ||
| value: np.ndarray, | ||
| model: "Model", | ||
| dims: Sequence[str] | None = None, | ||
| coords: dict[str, Sequence | np.ndarray] | None = None, | ||
| ) -> tuple[dict[str, Sequence | np.ndarray], Sequence[str | None] | Sequence[None]]: | ||
| if coords is None: | ||
| coords = {} | ||
|
|
||
| dim_name = None | ||
| # If value is a df or a series, we interpret the index as coords: | ||
| if hasattr(value, "index"): | ||
| if dims is not None: | ||
| dim_name = dims[0] | ||
| if dim_name is None and value.index.name is not None: | ||
| dim_name = value.index.name | ||
| if dim_name is not None: | ||
| coords[dim_name] = value.index | ||
|
|
||
| # If value is a df, we also interpret the columns as coords: | ||
| if hasattr(value, "columns"): | ||
| if dims is not None: | ||
| dim_name = dims[1] | ||
| if dim_name is None and value.columns.name is not None: | ||
| dim_name = value.columns.name | ||
| if dim_name is not None: | ||
| coords[dim_name] = value.columns | ||
|
|
||
| if isinstance(value, xr.DataArray): | ||
| if dims is not None: | ||
| for dim in dims: | ||
| dim_name = dim | ||
| # str is applied because dim entries may be None | ||
| coords[str(dim_name)] = cast(xr.DataArray, value[dim]).to_numpy() | ||
|
|
||
| if isinstance(value, np.ndarray) and dims is not None: | ||
| if len(dims) != value.ndim: | ||
| raise ShapeError( | ||
| "Invalid data shape. The rank of the dataset must match the length of `dims`.", | ||
| actual=value.shape, | ||
| expected=value.ndim, | ||
| ) | ||
| for size, dim in zip(value.shape, dims): | ||
| coord = model.coords.get(dim, None) | ||
| if coord is None and dim is not None: | ||
| coords[dim] = range(size) | ||
| if dims is None: | ||
| return coords, _handle_none_dims(dims, value.ndim) | ||
|
|
||
| if len(dims) != value.ndim: | ||
| raise ShapeError( | ||
| "Invalid data shape. The rank of the dataset must match the length of `dims`.", | ||
| actual=value.shape, | ||
| expected=len(value.shape), | ||
| ) | ||
|
|
||
| for size, dim in zip(value.shape, dims): | ||
| coord = model.coords.get(dim, None) | ||
| if coord is None and dim is not None: | ||
| coords[dim] = range(size) | ||
|
|
||
| return coords, _handle_none_dims(dims, value.ndim) | ||
|
|
||
|
|
||
| @determine_coords.register(xr.DataArray) | ||
| def determine_xarray_coords( | ||
| value: xr.DataArray, | ||
| model: "Model", | ||
| dims: Sequence[str | None] | None = None, | ||
| coords: dict[str, Sequence | np.ndarray] | None = None, | ||
| ) -> tuple[dict[str, Sequence | np.ndarray], Sequence[str | None] | Sequence[None]]: | ||
| if coords is None: | ||
| coords = {} | ||
|
|
||
| if dims is None: | ||
| # TODO: Also determine dim names from the index | ||
| new_dims: Sequence[str] | Sequence[None] = [None] * np.ndim(value) | ||
| else: | ||
| new_dims = dims | ||
| return coords, new_dims | ||
| return coords, _handle_none_dims(dims, value.ndim) | ||
|
|
||
| for dim in dims: | ||
| dim_name = dim | ||
| # str is applied because dim entries may be None | ||
| coords[str(dim_name)] = cast(xr.DataArray, value[dim]).to_numpy() | ||
|
|
||
| return coords, _handle_none_dims(dims, value.ndim) | ||
|
|
||
|
|
||
| def _dataframe_agnostic_coords( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe we can add a simple test for this function?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I added a test for this. The new test revealed that my code for inferring an "index column" in the dataframe based on the left-most dim was broken. I was trying to do was to allow for an "index column" in backends with no index (Polars). So if your dims were Frankly though I kind of hate this feature, it's too magical. Just force people to write out their coords. |
||
| value: IntoFrameT | IntoSeriesT, | ||
| model: "Model", | ||
| ndim_in: int = 2, | ||
| dims: Sequence[str | None] | None = None, | ||
| coords: dict[str, Sequence | np.ndarray] | None = None, | ||
| ) -> tuple[dict[str, Sequence | np.ndarray], Sequence[str | None] | Sequence[None]]: | ||
| if coords is None: | ||
| coords = {} | ||
|
|
||
| value = nw.from_native(value, allow_series=ndim_in == 1) # type: ignore[call-overload] | ||
| if isinstance(value, nw.LazyFrame): | ||
| value = value.collect() | ||
|
|
||
| if dims is None: | ||
| return coords, _handle_none_dims(dims, ndim_in) | ||
|
|
||
| index = nw.maybe_get_index(value) # type: ignore[arg-type] | ||
|
|
||
| if len(dims) != ndim_in: | ||
| raise ShapeError( | ||
| "Invalid data shape. The rank of the dataset must match the length of `dims`.", | ||
| actual=value.shape, # type: ignore[union-attr] | ||
| expected=len(dims), | ||
| ) | ||
|
|
||
| index_dim = dims[0] | ||
| if index_dim is not None: | ||
| if index is not None: | ||
| coords[index_dim] = tuple(index) | ||
| elif index_dim in model.coords: | ||
| coords[index_dim] = model.coords[index_dim] # type: ignore[assignment] | ||
| else: | ||
| raise ValueError( | ||
| f"Dimension '{index_dim}' not found in DataFrame index or model coordinates. Cannot infer " | ||
| "index coordinates." | ||
| ) | ||
|
|
||
| if len(dims) > 1: | ||
| column_dim = dims[1] | ||
| if column_dim is not None: | ||
| coords[column_dim] = value.columns # type: ignore[union-attr] | ||
|
|
||
| return coords, _handle_none_dims(dims, ndim_in) | ||
|
|
||
|
|
||
| def _series_agnostic_coords( | ||
| value: IntoSeriesT, | ||
| model: "Model", | ||
| dims: Sequence[str | None] | None = None, | ||
| coords: dict[str, Sequence | np.ndarray] | None = None, | ||
| ) -> tuple[dict[str, Sequence | np.ndarray], Sequence[str | None] | Sequence[None]]: | ||
| return _dataframe_agnostic_coords( | ||
| value, | ||
| ndim_in=1, | ||
| model=model, | ||
| dims=dims, | ||
| coords=coords, | ||
| ) | ||
|
|
||
|
|
||
| def _register_dataframe_backend(library_name: str): | ||
| try: | ||
| library = importlib.import_module(library_name) | ||
|
|
||
| @determine_coords.register(library.Series) | ||
| def determine_series_coords( | ||
| value: IntoSeriesT, | ||
| model: "Model", | ||
| dims: Sequence[str] | None = None, | ||
| coords: dict[str, Sequence | np.ndarray] | None = None, | ||
| ) -> tuple[dict[str, Sequence | np.ndarray], Sequence[str | None] | Sequence[None]]: | ||
| return _series_agnostic_coords(value, model=model, dims=dims, coords=coords) | ||
|
|
||
| @determine_coords.register(library.DataFrame) | ||
| def determine_dataframe_coords( | ||
| value: IntoFrameT, | ||
| model: "Model", | ||
| dims: Sequence[str] | None = None, | ||
| coords: dict[str, Sequence | np.ndarray] | None = None, | ||
| ) -> tuple[dict[str, Sequence | np.ndarray], Sequence[str | None] | Sequence[None]]: | ||
| return _dataframe_agnostic_coords(value, model=model, dims=dims, coords=coords) | ||
|
|
||
| except ImportError: | ||
jessegrabowski marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| # Dataframe backends are optional | ||
| pass | ||
|
|
||
|
|
||
| _register_dataframe_backend("pandas") | ||
| _register_dataframe_backend("polars") | ||
| _register_dataframe_backend("dask.dataframe") | ||
|
|
||
|
|
||
| def Data( | ||
| name: str, | ||
| value, | ||
| value: IntoFrameT | IntoSeriesT | xr.DataArray | np.ndarray, | ||
| *, | ||
| dims: Sequence[str] | None = None, | ||
| coords: dict[str, Sequence | np.ndarray] | None = None, | ||
|
|
@@ -248,11 +359,11 @@ def Data( | |
| ---------- | ||
| name : str | ||
| The name for this variable. | ||
| value : array_like or pandas.Series, pandas.Dataframe | ||
| value : array_like or Narwhals-compatible Series or DataFrame | ||
jessegrabowski marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| A value to associate with this variable. | ||
| dims : str, tuple of str or tuple of None, optional | ||
| Dimension names of the random variables (as opposed to the shapes of these | ||
| random variables). Use this when ``value`` is a pandas Series or DataFrame. The | ||
| random variables). Use this when ``value`` is a Series or DataFrame. The | ||
| ``dims`` will then be the name of the Series / DataFrame's columns. See ArviZ | ||
| documentation for more information about dimensions and coordinates: | ||
| :ref:`arviz:quickstart`. | ||
|
|
@@ -265,6 +376,9 @@ def Data( | |
| infer_dims_and_coords : bool, default=False | ||
| If True, the ``Data`` container will try to infer what the coordinates | ||
| and dimension names should be if there is an index in ``value``. | ||
| model : pymc.Model, optional | ||
| Model to which to add the data variable. If not specified, the data variable | ||
| will be added to the model on the context stack. | ||
| **kwargs : dict, optional | ||
| Extra arguments passed to :func:`pytensor.shared`. | ||
|
|
||
|
|
@@ -333,9 +447,9 @@ def Data( | |
| expected=x.ndim, | ||
| ) | ||
|
|
||
| new_dims: Sequence[str] | Sequence[None] | None | ||
| new_dims: Sequence[str | None] | Sequence[None] | None | ||
| if infer_dims_and_coords: | ||
| coords, new_dims = determine_coords(model, value, dims) | ||
| coords, new_dims = determine_coords(value, model, dims) | ||
| else: | ||
| new_dims = dims | ||
|
|
||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.