|
38 | 38 | )
|
39 | 39 | from .cache import memoize
|
40 | 40 | from .xrutils import (
|
| 41 | + is_chunked_array, |
41 | 42 | is_duck_array,
|
| 43 | + is_duck_cubed_array, |
42 | 44 | is_duck_dask_array,
|
43 | 45 | isnull,
|
44 | 46 | module_available,
|
|
63 | 65 | except (ModuleNotFoundError, ImportError):
|
64 | 66 | Unpack: Any # type: ignore[no-redef]
|
65 | 67 |
|
| 68 | + import cubed.Array as CubedArray |
66 | 69 | import dask.array.Array as DaskArray
|
67 | 70 | from dask.typing import Graph
|
68 | 71 |
|
69 |
| - T_DuckArray = Union[np.ndarray, DaskArray] # Any ? |
| 72 | + T_DuckArray = Union[np.ndarray, DaskArray, CubedArray] # Any ? |
70 | 73 | T_By = T_DuckArray
|
71 | 74 | T_Bys = tuple[T_By, ...]
|
72 | 75 | T_ExpectIndex = pd.Index
|
|
95 | 98 |
|
96 | 99 |
|
97 | 100 | IntermediateDict = dict[Union[str, Callable], Any]
|
98 |
| -FinalResultsDict = dict[str, Union["DaskArray", np.ndarray]] |
| 101 | +FinalResultsDict = dict[str, Union["DaskArray", "CubedArray", np.ndarray]] |
99 | 102 | FactorProps = namedtuple("FactorProps", "offset_group nan_sentinel nanmask")
|
100 | 103 |
|
101 | 104 | # This dummy axis is inserted using np.expand_dims
|
@@ -1718,6 +1721,109 @@ def dask_groupby_agg(
|
1718 | 1721 | return (result, groups)
|
1719 | 1722 |
|
1720 | 1723 |
|
| 1724 | +def cubed_groupby_agg( |
| 1725 | + array: CubedArray, |
| 1726 | + by: T_By, |
| 1727 | + agg: Aggregation, |
| 1728 | + expected_groups: pd.Index | None, |
| 1729 | + axis: T_Axes = (), |
| 1730 | + fill_value: Any = None, |
| 1731 | + method: T_Method = "map-reduce", |
| 1732 | + reindex: bool = False, |
| 1733 | + engine: T_Engine = "numpy", |
| 1734 | + sort: bool = True, |
| 1735 | + chunks_cohorts=None, |
| 1736 | +) -> tuple[CubedArray, tuple[np.ndarray | CubedArray]]: |
| 1737 | + import cubed |
| 1738 | + import cubed.core.groupby |
| 1739 | + |
| 1740 | + # I think _tree_reduce expects this |
| 1741 | + assert isinstance(axis, Sequence) |
| 1742 | + assert all(ax >= 0 for ax in axis) |
| 1743 | + |
| 1744 | + inds = tuple(range(array.ndim)) |
| 1745 | + |
| 1746 | + by_input = by |
| 1747 | + |
| 1748 | + # Unifying chunks is necessary for argreductions. |
| 1749 | + # We need to rechunk before zipping up with the index |
| 1750 | + # let's always do it anyway |
| 1751 | + if not is_chunked_array(by): |
| 1752 | + # chunk numpy arrays like the input array |
| 1753 | + chunks = tuple(array.chunks[ax] if by.shape[ax] != 1 else (1,) for ax in range(-by.ndim, 0)) |
| 1754 | + |
| 1755 | + by = cubed.from_array(by, chunks=chunks, spec=array.spec) |
| 1756 | + _, (array, by) = cubed.core.unify_chunks(array, inds, by, inds[-by.ndim :]) |
| 1757 | + |
| 1758 | + # Cubed's groupby_reduction handles the generation of "intermediates", and the |
| 1759 | + # "map-reduce" combination step, so we don't have to do that here. |
| 1760 | + # Only the equivalent of "_simple_combine" is supported, there is no |
| 1761 | + # support for "_grouped_combine". |
| 1762 | + labels_are_unknown = is_chunked_array(by_input) and expected_groups is None |
| 1763 | + do_simple_combine = not _is_arg_reduction(agg) and not labels_are_unknown |
| 1764 | + |
| 1765 | + assert do_simple_combine |
| 1766 | + assert method == "map-reduce" |
| 1767 | + assert expected_groups is not None |
| 1768 | + assert reindex is True |
| 1769 | + assert len(axis) == 1 # one axis/grouping |
| 1770 | + |
| 1771 | + def _groupby_func(a, by, axis, intermediate_dtype, num_groups): |
| 1772 | + blockwise_method = partial( |
| 1773 | + _get_chunk_reduction(agg.reduction_type), |
| 1774 | + func=agg.chunk, |
| 1775 | + fill_value=agg.fill_value["intermediate"], |
| 1776 | + dtype=agg.dtype["intermediate"], |
| 1777 | + reindex=reindex, |
| 1778 | + user_dtype=agg.dtype["user"], |
| 1779 | + axis=axis, |
| 1780 | + expected_groups=expected_groups, |
| 1781 | + engine=engine, |
| 1782 | + sort=sort, |
| 1783 | + ) |
| 1784 | + out = blockwise_method(a, by) |
| 1785 | + # Convert dict to one that cubed understands, dropping groups since they are |
| 1786 | + # known, and the same for every block. |
| 1787 | + return {f"f{idx}": intermediate for idx, intermediate in enumerate(out["intermediates"])} |
| 1788 | + |
| 1789 | + def _groupby_combine(a, axis, dummy_axis, dtype, keepdims): |
| 1790 | + # this is similar to _simple_combine, except the dummy axis and concatenation is handled by cubed |
| 1791 | + # only combine over the dummy axis, to preserve grouping along 'axis' |
| 1792 | + dtype = dict(dtype) |
| 1793 | + out = {} |
| 1794 | + for idx, combine in enumerate(agg.simple_combine): |
| 1795 | + field = f"f{idx}" |
| 1796 | + out[field] = combine(a[field], axis=dummy_axis, keepdims=keepdims) |
| 1797 | + return out |
| 1798 | + |
| 1799 | + def _groupby_aggregate(a): |
| 1800 | + # Convert cubed dict to one that _finalize_results works with |
| 1801 | + results = {"groups": expected_groups, "intermediates": a.values()} |
| 1802 | + out = _finalize_results(results, agg, axis, expected_groups, fill_value, reindex) |
| 1803 | + return out[agg.name] |
| 1804 | + |
| 1805 | + # convert list of dtypes to a structured dtype for cubed |
| 1806 | + intermediate_dtype = [(f"f{i}", dtype) for i, dtype in enumerate(agg.dtype["intermediate"])] |
| 1807 | + dtype = agg.dtype["final"] |
| 1808 | + num_groups = len(expected_groups) |
| 1809 | + |
| 1810 | + result = cubed.core.groupby.groupby_reduction( |
| 1811 | + array, |
| 1812 | + by, |
| 1813 | + func=_groupby_func, |
| 1814 | + combine_func=_groupby_combine, |
| 1815 | + aggregate_func=_groupby_aggregate, |
| 1816 | + axis=axis, |
| 1817 | + intermediate_dtype=intermediate_dtype, |
| 1818 | + dtype=dtype, |
| 1819 | + num_groups=num_groups, |
| 1820 | + ) |
| 1821 | + |
| 1822 | + groups = (expected_groups.to_numpy(),) |
| 1823 | + |
| 1824 | + return (result, groups) |
| 1825 | + |
| 1826 | + |
1721 | 1827 | def _collapse_blocks_along_axes(reduced: DaskArray, axis: T_Axes, group_chunks) -> DaskArray:
|
1722 | 1828 | import dask.array
|
1723 | 1829 | from dask.highlevelgraph import HighLevelGraph
|
@@ -2240,6 +2346,7 @@ def groupby_reduce(
|
2240 | 2346 | nax = len(axis_)
|
2241 | 2347 |
|
2242 | 2348 | has_dask = is_duck_dask_array(array) or is_duck_dask_array(by_)
|
| 2349 | + has_cubed = is_duck_cubed_array(array) or is_duck_cubed_array(by_) |
2243 | 2350 |
|
2244 | 2351 | if _is_first_last_reduction(func):
|
2245 | 2352 | if has_dask and nax != 1:
|
@@ -2302,7 +2409,30 @@ def groupby_reduce(
|
2302 | 2409 | kwargs["engine"] = _choose_engine(by_, agg) if engine is None else engine
|
2303 | 2410 |
|
2304 | 2411 | groups: tuple[np.ndarray | DaskArray, ...]
|
2305 |
| - if not has_dask: |
| 2412 | + if has_cubed: |
| 2413 | + if method is None: |
| 2414 | + method = "map-reduce" |
| 2415 | + |
| 2416 | + if method != "map-reduce": |
| 2417 | + raise NotImplementedError( |
| 2418 | + "Reduction for Cubed arrays is only implemented for method 'map-reduce'." |
| 2419 | + ) |
| 2420 | + |
| 2421 | + partial_agg = partial(cubed_groupby_agg, **kwargs) |
| 2422 | + |
| 2423 | + result, groups = partial_agg( |
| 2424 | + array, |
| 2425 | + by_, |
| 2426 | + expected_groups=expected_, |
| 2427 | + agg=agg, |
| 2428 | + reindex=reindex, |
| 2429 | + method=method, |
| 2430 | + sort=sort, |
| 2431 | + ) |
| 2432 | + |
| 2433 | + return (result, groups) |
| 2434 | + |
| 2435 | + elif not has_dask: |
2306 | 2436 | results = _reduce_blockwise(
|
2307 | 2437 | array, by_, agg, expected_groups=expected_, reindex=reindex, sort=sort, **kwargs
|
2308 | 2438 | )
|
|
0 commit comments