44from typing import Any , Callable , Dict , Hashable , Iterable , List , Mapping , Union
55
66import anytree
7+ from xarray import DataArray , Dataset , merge
78from xarray .core import dtypes , utils
8- from xarray .core .arithmetic import DatasetArithmetic
9- from xarray .core .combine import merge
10- from xarray .core .common import DataWithCoords
11- from xarray .core .dataarray import DataArray
12- from xarray .core .dataset import Dataset
13- from xarray .core .ops import NAN_CUM_METHODS , NAN_REDUCE_METHODS , REDUCE_METHODS
149from xarray .core .variable import Variable
1510
1611from .mapping import map_over_subtree
12+ from .ops import (
13+ DataTreeArithmeticMixin ,
14+ MappedDatasetMethodsMixin ,
15+ MappedDataWithCoords ,
16+ )
1717from .treenode import PathType , TreeNode , _init_single_treenode
1818
1919"""
20- The structure of a populated Datatree looks roughly like this:
21-
22- DataTree("root name")
23- |-- DataNode("weather")
24- | | Variable("wind_speed")
25- | | Variable("pressure")
26- | |-- DataNode("temperature")
27- | | Variable("sea_surface_temperature")
28- | | Variable("dew_point_temperature")
29- |-- DataNode("satellite image")
30- | | Variable("true_colour")
31- | |-- DataNode("infrared")
32- | | Variable("near_infrared")
33- | | Variable("far_infrared")
34- |-- DataNode("topography")
35- | |-- DataNode("elevation")
36- | | Variable("height_above_sea_level")
37- |-- DataNode("population")
38-
39-
4020DEVELOPERS' NOTE
4121----------------
4222The idea of this module is to create a `DataTree` class which inherits the tree structure from TreeNode, and also copies
4323the entire API of `xarray.Dataset`, but with certain methods decorated to instead map the dataset function over every
4424node in the tree. As this API is copied without directly subclassing `xarray.Dataset` we instead create various Mixin
45- classes which each define part of `xarray.Dataset`'s extensive API.
25+ classes (in ops.py) which each define part of `xarray.Dataset`'s extensive API.
4626
4727Some of these methods must be wrapped to map over all nodes in the subtree. Others are fine to inherit unaltered
4828(normally because they (a) only call dataset properties and (b) don't return a dataset that should be nested into a new
@@ -56,6 +36,8 @@ class DatasetPropertiesMixin:
5636 # TODO a neater way of setting all of these?
5737 # We wouldn't need this at all if we inherited directly from Dataset...
5838
39+ # TODO we could also just not define these at all, and require users to call e.g. dt.ds.dims ...
40+
5941 @property
6042 def dims (self ):
6143 if self .has_data :
@@ -159,202 +141,12 @@ def imag(self):
159141 chunks .__doc__ = Dataset .chunks .__doc__
160142
161143
162- _MAPPED_DOCSTRING_ADDENDUM = textwrap .fill (
163- "This method was copied from xarray.Dataset, but has been altered to "
164- "call the method on the Datasets stored in every node of the subtree. "
165- "See the `map_over_subtree` function for more details." ,
166- width = 117 ,
167- )
168-
169- # TODO equals, broadcast_equals etc.
170- # TODO do dask-related private methods need to be exposed?
171- _DATASET_DASK_METHODS_TO_MAP = [
172- "load" ,
173- "compute" ,
174- "persist" ,
175- "unify_chunks" ,
176- "chunk" ,
177- "map_blocks" ,
178- ]
179- _DATASET_METHODS_TO_MAP = [
180- "copy" ,
181- "as_numpy" ,
182- "__copy__" ,
183- "__deepcopy__" ,
184- "set_coords" ,
185- "reset_coords" ,
186- "info" ,
187- "isel" ,
188- "sel" ,
189- "head" ,
190- "tail" ,
191- "thin" ,
192- "broadcast_like" ,
193- "reindex_like" ,
194- "reindex" ,
195- "interp" ,
196- "interp_like" ,
197- "rename" ,
198- "rename_dims" ,
199- "rename_vars" ,
200- "swap_dims" ,
201- "expand_dims" ,
202- "set_index" ,
203- "reset_index" ,
204- "reorder_levels" ,
205- "stack" ,
206- "unstack" ,
207- "update" ,
208- "merge" ,
209- "drop_vars" ,
210- "drop_sel" ,
211- "drop_isel" ,
212- "drop_dims" ,
213- "transpose" ,
214- "dropna" ,
215- "fillna" ,
216- "interpolate_na" ,
217- "ffill" ,
218- "bfill" ,
219- "combine_first" ,
220- "reduce" ,
221- "map" ,
222- "assign" ,
223- "diff" ,
224- "shift" ,
225- "roll" ,
226- "sortby" ,
227- "quantile" ,
228- "rank" ,
229- "differentiate" ,
230- "integrate" ,
231- "cumulative_integrate" ,
232- "filter_by_attrs" ,
233- "polyfit" ,
234- "pad" ,
235- "idxmin" ,
236- "idxmax" ,
237- "argmin" ,
238- "argmax" ,
239- "query" ,
240- "curvefit" ,
241- ]
242- # TODO unsure if these are called by external functions or not?
243- _DATASET_OPS_TO_MAP = ["_unary_op" , "_binary_op" , "_inplace_binary_op" ]
244- _ALL_DATASET_METHODS_TO_MAP = (
245- _DATASET_DASK_METHODS_TO_MAP + _DATASET_METHODS_TO_MAP + _DATASET_OPS_TO_MAP
246- )
247-
248- _DATA_WITH_COORDS_METHODS_TO_MAP = [
249- "squeeze" ,
250- "clip" ,
251- "assign_coords" ,
252- "where" ,
253- "close" ,
254- "isnull" ,
255- "notnull" ,
256- "isin" ,
257- "astype" ,
258- ]
259-
260- # TODO NUM_BINARY_OPS apparently aren't defined on DatasetArithmetic, and don't appear to be injected anywhere...
261- _ARITHMETIC_METHODS_TO_MAP = (
262- REDUCE_METHODS + NAN_REDUCE_METHODS + NAN_CUM_METHODS + ["__array_ufunc__" ]
263- )
264-
265-
266- def _wrap_then_attach_to_cls (
267- target_cls_dict , source_cls , methods_to_set , wrap_func = None
268- ):
269- """
270- Attach given methods on a class, and optionally wrap each method first. (i.e. with map_over_subtree)
271-
272- Result is like having written this in the classes' definition:
273- ```
274- @wrap_func
275- def method_name(self, *args, **kwargs):
276- return self.method(*args, **kwargs)
277- ```
278-
279- Every method attached here needs to have a return value of Dataset or DataArray in order to construct a new tree.
280-
281- Parameters
282- ----------
283- target_cls_dict : MappingProxy
284- The __dict__ attribute of the class which we want the methods to be added to. (The __dict__ attribute can also
285- be accessed by calling vars() from within that classes' definition.) This will be updated by this function.
286- source_cls : class
287- Class object from which we want to copy methods (and optionally wrap them). Should be the actual class object
288- (or instance), not just the __dict__.
289- methods_to_set : Iterable[Tuple[str, callable]]
290- The method names and definitions supplied as a list of (method_name_string, method) pairs.
291- This format matches the output of inspect.getmembers().
292- wrap_func : callable, optional
293- Function to decorate each method with. Must have the same return type as the method.
294- """
295- for method_name in methods_to_set :
296- orig_method = getattr (source_cls , method_name )
297- wrapped_method = (
298- wrap_func (orig_method ) if wrap_func is not None else orig_method
299- )
300- target_cls_dict [method_name ] = wrapped_method
301-
302- if wrap_func is map_over_subtree :
303- # Add a paragraph to the method's docstring explaining how it's been mapped
304- orig_method_docstring = orig_method .__doc__
305- if orig_method_docstring is not None :
306- if "\n " in orig_method_docstring :
307- new_method_docstring = orig_method_docstring .replace (
308- "\n " , _MAPPED_DOCSTRING_ADDENDUM , 1
309- )
310- else :
311- new_method_docstring = (
312- orig_method_docstring + f"\n \n { _MAPPED_DOCSTRING_ADDENDUM } "
313- )
314- setattr (target_cls_dict [method_name ], "__doc__" , new_method_docstring )
315-
316-
317- class MappedDatasetMethodsMixin :
318- """
319- Mixin to add Dataset methods like .mean(), but wrapped to map over all nodes in the subtree.
320- """
321-
322- __slots__ = ()
323- _wrap_then_attach_to_cls (
324- vars (), Dataset , _ALL_DATASET_METHODS_TO_MAP , wrap_func = map_over_subtree
325- )
326-
327-
328- class MappedDataWithCoords (DataWithCoords ):
329- # TODO add mapped versions of groupby, weighted, rolling, rolling_exp, coarsen, resample
330- # TODO re-implement AttrsAccessMixin stuff so that it includes access to child nodes
331- _wrap_then_attach_to_cls (
332- vars (),
333- DataWithCoords ,
334- _DATA_WITH_COORDS_METHODS_TO_MAP ,
335- wrap_func = map_over_subtree ,
336- )
337-
338-
339- class DataTreeArithmetic (DatasetArithmetic ):
340- """
341- Mixin to add Dataset methods like __add__ and .mean().
342- """
343-
344- _wrap_then_attach_to_cls (
345- vars (),
346- DatasetArithmetic ,
347- _ARITHMETIC_METHODS_TO_MAP ,
348- wrap_func = map_over_subtree ,
349- )
350-
351-
352144class DataTree (
353145 TreeNode ,
354146 DatasetPropertiesMixin ,
355147 MappedDatasetMethodsMixin ,
356148 MappedDataWithCoords ,
357- DataTreeArithmetic ,
149+ DataTreeArithmeticMixin ,
358150):
359151 """
360152 A tree-like hierarchical collection of xarray objects.
@@ -858,7 +650,7 @@ def to_netcdf(
858650
859651 def to_zarr (self , store , mode : str = "w" , encoding = None , ** kwargs ):
860652 """
861- Write datatree contents to a netCDF file .
653+ Write datatree contents to a Zarr store .
862654
863655 Parameters
864656 ---------
@@ -875,7 +667,7 @@ def to_zarr(self, store, mode: str = "w", encoding=None, **kwargs):
875667 ``{"root/set1": {"my_variable": {"dtype": "int16", "scale_factor": 0.1}, ...}, ...}``.
876668 See ``xarray.Dataset.to_zarr`` for available options.
877669 kwargs :
878- Addional keyword arguments to be passed to ``xarray.Dataset.to_zarr``
670+ Additional keyword arguments to be passed to ``xarray.Dataset.to_zarr``
879671 """
880672 from .io import _datatree_to_zarr
881673
0 commit comments