Skip to content

Commit

Permalink
Allow GMTDataArrayAccessor to work on sliced datacubes (GenericMappin…
Browse files Browse the repository at this point in the history
…gTools#1581)

If `grdinfo` can't read the source NetCDF file as it
is an n-dimensional datacube (instead of a 2D grid),
we fallback to setting the default gridline registration
and Cartesian grid type.

* Use with statement to ensure the grid is properly closed

So that the file can be deleted on Windows.

Co-authored-by: Will Schlitzer <[email protected]>
  • Loading branch information
2 people authored and Josh Sixsmith committed Dec 21, 2022
1 parent ca8fdf8 commit af68324
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pygmt/accessors.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def __init__(self, xarray_obj):
self._registration, self._gtype = map(
int, grdinfo(self._source, per_column="n", o="10,11").split()
)
except KeyError:
except (KeyError, ValueError):
self._registration = 0 # Default to Gridline registration
self._gtype = 0 # Default to Cartesian grid type

Expand Down
24 changes: 24 additions & 0 deletions pygmt/tests/test_accessor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""
Test the behaviour of the GMTDataArrayAccessor class.
"""
import os

import pytest
import xarray as xr
from pygmt import which
Expand Down Expand Up @@ -66,3 +68,25 @@ def test_accessor_set_non_boolean():

with pytest.raises(GMTInvalidInput):
grid.gmt.gtype = 2


def test_accessor_sliced_datacube():
"""
Check that a 2D grid which is sliced from an n-dimensional datacube works
with accessor methods.
This is a regression test for
https://github.com/GenericMappingTools/pygmt/issues/1578.
"""
try:
fname = which(
"https://github.com/pydata/xarray-data/raw/master/eraint_uvz.nc",
download="u",
)
with xr.open_dataset(fname) as dataset:
grid = dataset.sel(level=500, month=1, drop=True).z

assert grid.gmt.registration == 0 # gridline registration
assert grid.gmt.gtype == 0 # cartesian coordinate type
finally:
os.remove(fname)

0 comments on commit af68324

Please sign in to comment.