Skip to content

Commit

Permalink
Fix warnings about not creating indexes when using .rename()
Browse files Browse the repository at this point in the history
xarray behaviour changed, see pydata/xarray#6999
and links from there.
  • Loading branch information
johnomotani committed Jan 20, 2023
1 parent a39b729 commit 8422b9b
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
11 changes: 6 additions & 5 deletions xbout/geometries.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
_set_attrs_on_all_vars,
_set_as_coord,
_1d_coord_from_spacing,
_maybe_rename_dimension,
)

REGISTERED_GEOMETRIES = {}
Expand Down Expand Up @@ -386,12 +387,12 @@ def add_toroidal_geometry_coords(ds, *, coordinates=None, grid=None):
],
)

if "t" in ds.dims:
if coordinates["t"] != "t":
# Rename 't' if user requested it
ds = ds.rename(t=coordinates["t"])
ds = _maybe_rename_dimension(ds, "t", coordinates["t"])

# Change names of dimensions to Orthogonal Toroidal ones
ds = ds.rename(y=coordinates["y"])
ds = _maybe_rename_dimension(ds, "y", coordinates["y"])

# TODO automatically make this coordinate 1D in simplified cases?
ds = ds.rename(psixy=coordinates["x"])
Expand All @@ -407,7 +408,7 @@ def add_toroidal_geometry_coords(ds, *, coordinates=None, grid=None):

# If full data (not just grid file) then toroidal dim will be present
if "z" in ds.dims:
ds = ds.rename(z=coordinates["z"])
ds = _maybe_rename_dimension(ds, "z", coordinates["z"])

# Record which dimension 'z' was renamed to.
ds.metadata["bout_zdim"] = coordinates["z"]
Expand Down Expand Up @@ -482,7 +483,7 @@ def add_s_alpha_geometry_coords(ds, *, coordinates=None, grid=None):
ds["r"] = ds["hthe"].isel({ycoord: 0}).squeeze(drop=True)
ds["r"].attrs["units"] = "m"
ds = ds.set_coords("r")
ds = ds.rename(x="r")
ds = ds.swap_dims(x="r")
ds.metadata["bout_xdim"] = "r"

if hthe_from_grid:
Expand Down
11 changes: 11 additions & 0 deletions xbout/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -880,3 +880,14 @@ def _set_as_coord(ds, name):
except ValueError:
pass
return ds


def _maybe_rename_dimension(ds, old_name, new_name):
if old_name in ds.dims and new_name != old_name:
# Rename dimension
ds = ds.swap_dims({old_name: new_name})
if old_name in ds:
# Rename coordinate if it exists
ds = ds.rename({old_name: new_name})

return ds

0 comments on commit 8422b9b

Please sign in to comment.