Skip to content
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

Add cf conventions helper #31

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions pvxarray/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import xarray as xr

from pvxarray import rectilinear, structured
from pvxarray.cf import get_cf_names


class _LocIndexer:
Expand Down Expand Up @@ -51,6 +52,15 @@ def mesh(
order: Optional[str] = None,
component: Optional[str] = None,
) -> pv.DataSet:
if (3 - (x, y, z).count(None)) < 1:
try:
x, y, z, _ = get_cf_names(self._obj)
except ImportError: # pragma: no cover
pass
if (3 - (x, y, z).count(None)) < 1:
raise ValueError(
"You must specify at least one dimension as X, Y, or Z or install `cf_xarray`."
)
ndim = 0
if x is not None:
_x = self._get_array(x)
Expand Down
13 changes: 13 additions & 0 deletions pvxarray/cf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
def get_cf_names(da):
"""Use `cf_xarray` to get the names of the X, Y, and Z arrays."""
try:
import cf_xarray # noqa

axes = da.cf.axes
except (AttributeError, ImportError): # pragma: no cover
raise ImportError("Please install `cf_xarray` to use CF conventions.")
x = axes.get("X", [None])[0]
y = axes.get("Y", [None])[0]
z = axes.get("Z", [None])[0]
Comment on lines +9 to +11
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This just feels wrong

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that is quite ugly.

Alternatives are

x = da.axes["X"][0] if "X" in da.cf else None

or in _get_array:

# if cf_xarray exists
return da.cf[key]  # this falls back to usually xarray stuff if "key" is not interpretable using cf conventions

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great! thank you for the suggestions

t = axes.get("T", [None])[0]
return x, y, z, t
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ netcdf4
pytest
pytest-cov
rioxarray
cf_xarray
5 changes: 5 additions & 0 deletions tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ def test_report():
assert pvxarray.Report()


def test_no_cf_and_no_names(sample):
with pytest.raises(ValueError):
sample[dict(t=0)].pyvista.mesh()


def test_bad_key(sample):
with pytest.raises(KeyError):
sample[dict(t=0)].pyvista.mesh(x="foo")
Expand Down
17 changes: 17 additions & 0 deletions tests/test_cf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import numpy as np
import xarray as xr


def test_air_temperature():
ds = xr.tutorial.load_dataset("air_temperature")
da = ds.air[dict(time=0)]

mesh = da.pyvista.mesh() # No X,Y,Z specified, so should try cf_xarray
assert mesh
assert mesh.n_points == 1325
assert "air" in mesh.point_data

assert np.array_equal(mesh["air"], da.values.ravel())
assert np.may_share_memory(mesh["air"], da.values.ravel())
assert np.array_equal(mesh.x, da.lon)
assert np.array_equal(mesh.y, da.lat)