Skip to content

Commit

Permalink
Rename inherited -> inherit in DataTree.to_dataset (pydata#9615)
Browse files Browse the repository at this point in the history
* Rename inherited -> inherit in DataTree.to_dataset

* fixed one missed instance of kwarg from pydata#9602

---------

Co-authored-by: Tom Nicholas <[email protected]>
  • Loading branch information
shoyer and TomNicholas authored Oct 13, 2024
1 parent e407d65 commit 93b4859
Show file tree
Hide file tree
Showing 10 changed files with 45 additions and 45 deletions.
4 changes: 2 additions & 2 deletions doc/getting-started-guide/quick-overview.rst
Original file line number Diff line number Diff line change
Expand Up @@ -307,11 +307,11 @@ We can get a copy of the :py:class:`~xarray.Dataset` including the inherited coo
ds_inherited = dt["simulation/coarse"].to_dataset()
ds_inherited
And you can get a copy of just the node local values of :py:class:`~xarray.Dataset` by setting the ``inherited`` keyword to ``False``:
And you can get a copy of just the node local values of :py:class:`~xarray.Dataset` by setting the ``inherit`` keyword to ``False``:

.. ipython:: python
ds_node_local = dt["simulation/coarse"].to_dataset(inherited=False)
ds_node_local = dt["simulation/coarse"].to_dataset(inherit=False)
ds_node_local
.. note::
Expand Down
4 changes: 2 additions & 2 deletions doc/user-guide/data-structures.rst
Original file line number Diff line number Diff line change
Expand Up @@ -792,13 +792,13 @@ automatically includes coordinates from higher levels (e.g., ``time`` and
dt2["/weather/temperature"].dataset
Similarly, when you retrieve a Dataset through :py:func:`~xarray.DataTree.to_dataset` , the inherited coordinates are
included by default unless you exclude them with the ``inherited`` flag:
included by default unless you exclude them with the ``inherit`` flag:

.. ipython:: python
dt2["/weather/temperature"].to_dataset()
dt2["/weather/temperature"].to_dataset(inherited=False)
dt2["/weather/temperature"].to_dataset(inherit=False)
.. _coordinates:
Expand Down
4 changes: 2 additions & 2 deletions xarray/core/coordinates.py
Original file line number Diff line number Diff line change
Expand Up @@ -849,14 +849,14 @@ def _update_coords(
from xarray.core.datatree import check_alignment

# create updated node (`.to_dataset` makes a copy so this doesn't modify in-place)
node_ds = self._data.to_dataset(inherited=False)
node_ds = self._data.to_dataset(inherit=False)
node_ds.coords._update_coords(coords, indexes)

# check consistency *before* modifying anything in-place
# TODO can we clean up the signature of check_alignment to make this less awkward?
if self._data.parent is not None:
parent_ds = self._data.parent._to_dataset_view(
inherited=True, rebuild_dims=False
inherit=True, rebuild_dims=False
)
else:
parent_ds = None
Expand Down
38 changes: 19 additions & 19 deletions xarray/core/datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def check_alignment(

for child_name, child in children.items():
child_path = str(NodePath(path) / child_name)
child_ds = child.to_dataset(inherited=False)
child_ds = child.to_dataset(inherit=False)
check_alignment(child_path, child_ds, base_ds, child.children)


Expand Down Expand Up @@ -507,8 +507,8 @@ def _pre_attach(self: DataTree, parent: DataTree, name: str) -> None:
f"parent {parent.name} already contains a variable named {name}"
)
path = str(NodePath(parent.path) / name)
node_ds = self.to_dataset(inherited=False)
parent_ds = parent._to_dataset_view(rebuild_dims=False, inherited=True)
node_ds = self.to_dataset(inherit=False)
parent_ds = parent._to_dataset_view(rebuild_dims=False, inherit=True)
check_alignment(path, node_ds, parent_ds, self.children)
_deduplicate_inherited_coordinates(self, parent)

Expand All @@ -533,14 +533,14 @@ def _dims(self) -> ChainMap[Hashable, int]:
def _indexes(self) -> ChainMap[Hashable, Index]:
return ChainMap(self._node_indexes, *(p._node_indexes for p in self.parents))

def _to_dataset_view(self, rebuild_dims: bool, inherited: bool) -> DatasetView:
coord_vars = self._coord_variables if inherited else self._node_coord_variables
def _to_dataset_view(self, rebuild_dims: bool, inherit: bool) -> DatasetView:
coord_vars = self._coord_variables if inherit else self._node_coord_variables
variables = dict(self._data_variables)
variables |= coord_vars
if rebuild_dims:
dims = calculate_dimensions(variables)
elif inherited:
# Note: rebuild_dims=False with inherited=True can create
elif inherit:
# Note: rebuild_dims=False with inherit=True can create
# technically invalid Dataset objects because it still includes
# dimensions that are only defined on parent data variables
# (i.e. not present on any parent coordinate variables).
Expand All @@ -552,7 +552,7 @@ def _to_dataset_view(self, rebuild_dims: bool, inherited: bool) -> DatasetView:
# ... "/b": xr.Dataset(),
# ... }
# ... )
# >>> ds = tree["b"]._to_dataset_view(rebuild_dims=False, inherited=True)
# >>> ds = tree["b"]._to_dataset_view(rebuild_dims=False, inherit=True)
# >>> ds
# <xarray.DatasetView> Size: 0B
# Dimensions: (x: 2)
Expand All @@ -576,7 +576,7 @@ def _to_dataset_view(self, rebuild_dims: bool, inherited: bool) -> DatasetView:
coord_names=set(self._coord_variables),
dims=dims,
attrs=self._attrs,
indexes=dict(self._indexes if inherited else self._node_indexes),
indexes=dict(self._indexes if inherit else self._node_indexes),
encoding=self._encoding,
close=None,
)
Expand All @@ -595,7 +595,7 @@ def dataset(self) -> DatasetView:
--------
DataTree.to_dataset
"""
return self._to_dataset_view(rebuild_dims=True, inherited=True)
return self._to_dataset_view(rebuild_dims=True, inherit=True)

@dataset.setter
def dataset(self, data: Dataset | None = None) -> None:
Expand All @@ -606,30 +606,30 @@ def dataset(self, data: Dataset | None = None) -> None:
# xarray-contrib/datatree
ds = dataset

def to_dataset(self, inherited: bool = True) -> Dataset:
def to_dataset(self, inherit: bool = True) -> Dataset:
"""
Return the data in this node as a new xarray.Dataset object.
Parameters
----------
inherited : bool, optional
inherit : bool, optional
If False, only include coordinates and indexes defined at the level
of this DataTree node, excluding any inherited coordinates and indexes.
See Also
--------
DataTree.dataset
"""
coord_vars = self._coord_variables if inherited else self._node_coord_variables
coord_vars = self._coord_variables if inherit else self._node_coord_variables
variables = dict(self._data_variables)
variables |= coord_vars
dims = calculate_dimensions(variables) if inherited else dict(self._node_dims)
dims = calculate_dimensions(variables) if inherit else dict(self._node_dims)
return Dataset._construct_direct(
variables,
set(coord_vars),
dims,
None if self._attrs is None else dict(self._attrs),
dict(self._indexes if inherited else self._node_indexes),
dict(self._indexes if inherit else self._node_indexes),
None if self._encoding is None else dict(self._encoding),
self._close,
)
Expand Down Expand Up @@ -798,7 +798,7 @@ def _replace_node(
children: dict[str, DataTree] | Default = _default,
) -> None:

ds = self.to_dataset(inherited=False) if data is _default else data
ds = self.to_dataset(inherit=False) if data is _default else data

if children is _default:
children = self._children
Expand All @@ -808,7 +808,7 @@ def _replace_node(
raise ValueError(f"node already contains a variable named {child_name}")

parent_ds = (
self.parent._to_dataset_view(rebuild_dims=False, inherited=True)
self.parent._to_dataset_view(rebuild_dims=False, inherit=True)
if self.parent is not None
else None
)
Expand All @@ -830,7 +830,7 @@ def _copy_node(

new_node = super()._copy_node()

data = self._to_dataset_view(rebuild_dims=False, inherited=False)
data = self._to_dataset_view(rebuild_dims=False, inherit=False)
if deep:
data = data.copy(deep=True)
new_node._set_node_data(data)
Expand Down Expand Up @@ -1000,7 +1000,7 @@ def update(
raise TypeError(f"Type {type(v)} cannot be assigned to a DataTree")

vars_merge_result = dataset_update_method(
self.to_dataset(inherited=False), new_variables
self.to_dataset(inherit=False), new_variables
)
data = Dataset._construct_direct(**vars_merge_result._asdict())

Expand Down
4 changes: 2 additions & 2 deletions xarray/core/datatree_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def _datatree_to_netcdf(
unlimited_dims = {}

for node in dt.subtree:
ds = node.to_dataset(inherited=False)
ds = node.to_dataset(inherit=False)
group_path = node.path
if ds is None:
_create_empty_netcdf_group(filepath, group_path, mode, engine)
Expand Down Expand Up @@ -151,7 +151,7 @@ def _datatree_to_zarr(
)

for node in dt.subtree:
ds = node.to_dataset(inherited=False)
ds = node.to_dataset(inherit=False)
group_path = node.path
if ds is None:
_create_empty_zarr_group(store, group_path, mode)
Expand Down
2 changes: 1 addition & 1 deletion xarray/core/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -1102,7 +1102,7 @@ def _datatree_node_repr(node: DataTree, show_inherited: bool) -> str:
summary.append(f"{dims_start}({dims_values})")

if node._node_coord_variables:
node_coords = node.to_dataset(inherited=False).coords
node_coords = node.to_dataset(inherit=False).coords
summary.append(coords_repr(node_coords, col_width=col_width, max_rows=max_rows))

if show_inherited and inherited_coords:
Expand Down
2 changes: 1 addition & 1 deletion xarray/core/formatting_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ def summarize_datatree_children(children: Mapping[str, DataTree]) -> str:
def datatree_node_repr(group_title: str, dt: DataTree) -> str:
header_components = [f"<div class='xr-obj-type'>{escape(group_title)}</div>"]

ds = dt._to_dataset_view(rebuild_dims=False, inherited=True)
ds = dt._to_dataset_view(rebuild_dims=False, inherit=True)

sections = [
children_section(dt.children),
Expand Down
4 changes: 2 additions & 2 deletions xarray/tests/test_backends_datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ def test_to_netcdf_inherited_coords(self, tmpdir):
roundtrip_dt = open_datatree(filepath, engine=self.engine)
assert_equal(original_dt, roundtrip_dt)
subtree = cast(DataTree, roundtrip_dt["/sub"])
assert "x" not in subtree.to_dataset(inherited=False).coords
assert "x" not in subtree.to_dataset(inherit=False).coords

def test_netcdf_encoding(self, tmpdir, simple_datatree):
filepath = tmpdir / "test.nc"
Expand Down Expand Up @@ -320,7 +320,7 @@ def test_to_zarr_inherited_coords(self, tmpdir):
roundtrip_dt = open_datatree(filepath, engine="zarr")
assert_equal(original_dt, roundtrip_dt)
subtree = cast(DataTree, roundtrip_dt["/sub"])
assert "x" not in subtree.to_dataset(inherited=False).coords
assert "x" not in subtree.to_dataset(inherit=False).coords

def test_open_groups_round_trip(self, tmpdir, simple_datatree) -> None:
"""Test `open_groups` opens a zarr store with the `simple_datatree` structure."""
Expand Down
26 changes: 13 additions & 13 deletions xarray/tests/test_datatree.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,12 +222,12 @@ def test_to_dataset_inherited(self):
tree = DataTree.from_dict({"/": base, "/sub": sub})
subtree = typing.cast(DataTree, tree["sub"])

assert_identical(tree.to_dataset(inherited=False), base)
assert_identical(subtree.to_dataset(inherited=False), sub)
assert_identical(tree.to_dataset(inherit=False), base)
assert_identical(subtree.to_dataset(inherit=False), sub)

sub_and_base = xr.Dataset(coords={"a": [1], "c": [3]}) # no "b"
assert_identical(tree.to_dataset(inherited=True), base)
assert_identical(subtree.to_dataset(inherited=True), sub_and_base)
assert_identical(tree.to_dataset(inherit=True), base)
assert_identical(subtree.to_dataset(inherit=True), sub_and_base)


class TestVariablesChildrenNameCollisions:
Expand Down Expand Up @@ -368,8 +368,8 @@ def test_update_inherited_coords(self):
# DataTree.identical() currently does not require that non-inherited
# coordinates are defined identically, so we need to check this
# explicitly
actual_node = actual.children["b"].to_dataset(inherited=False)
expected_node = expected.children["b"].to_dataset(inherited=False)
actual_node = actual.children["b"].to_dataset(inherit=False)
expected_node = expected.children["b"].to_dataset(inherit=False)
assert_identical(actual_node, expected_node)


Expand Down Expand Up @@ -414,7 +414,7 @@ def test_copy_coord_inheritance(self) -> None:
{"/": xr.Dataset(coords={"x": [0, 1]}), "/c": DataTree()}
)
tree2 = tree.copy()
node_ds = tree2.children["c"].to_dataset(inherited=False)
node_ds = tree2.children["c"].to_dataset(inherit=False)
assert_identical(node_ds, xr.Dataset())

def test_deepcopy(self, create_test_datatree):
Expand Down Expand Up @@ -1267,8 +1267,8 @@ def test_inherited_dims(self):
assert dt.c.sizes == {"x": 2, "y": 3}
# dataset objects created from nodes should not
assert dt.b.dataset.sizes == {"y": 1}
assert dt.b.to_dataset(inherited=True).sizes == {"y": 1}
assert dt.b.to_dataset(inherited=False).sizes == {"y": 1}
assert dt.b.to_dataset(inherit=True).sizes == {"y": 1}
assert dt.b.to_dataset(inherit=False).sizes == {"y": 1}

def test_inherited_coords_index(self):
dt = DataTree.from_dict(
Expand Down Expand Up @@ -1306,12 +1306,12 @@ def test_inherited_coords_with_index_are_deduplicated(self):
"/b": xr.Dataset(coords={"x": [1, 2]}),
}
)
child_dataset = dt.children["b"].to_dataset(inherited=False)
child_dataset = dt.children["b"].to_dataset(inherit=False)
expected = xr.Dataset()
assert_identical(child_dataset, expected)

dt["/c"] = xr.Dataset({"foo": ("x", [4, 5])}, coords={"x": [1, 2]})
child_dataset = dt.children["c"].to_dataset(inherited=False)
child_dataset = dt.children["c"].to_dataset(inherit=False)
expected = xr.Dataset({"foo": ("x", [4, 5])})
assert_identical(child_dataset, expected)

Expand All @@ -1324,7 +1324,7 @@ def test_deduplicated_after_setitem(self):
}
)
dt["b/x"] = dt["x"]
child_dataset = dt.children["b"].to_dataset(inherited=False)
child_dataset = dt.children["b"].to_dataset(inherit=False)
expected = xr.Dataset()
assert_identical(child_dataset, expected)

Expand Down Expand Up @@ -1786,7 +1786,7 @@ def test_arithmetic_inherited_coords(self):
tree["/foo"] = DataTree(xr.Dataset({"bar": ("x", [4, 5, 6])}))
actual: DataTree = 2 * tree # type: ignore[assignment,operator]

actual_dataset = actual.children["foo"].to_dataset(inherited=False)
actual_dataset = actual.children["foo"].to_dataset(inherit=False)
assert "x" not in actual_dataset.coords

expected = tree.copy()
Expand Down
2 changes: 1 addition & 1 deletion xarray/tests/test_datatree_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ def test_inherited_coordinates_with_index(self):
assert isinstance(actual, xr.DataTree)
assert_identical(tree, actual)

actual_child = actual.children["child"].to_dataset(inherited=False)
actual_child = actual.children["child"].to_dataset(inherit=False)
assert_identical(actual_child, child)


Expand Down

0 comments on commit 93b4859

Please sign in to comment.