-
Notifications
You must be signed in to change notification settings - Fork 21
Initial minimal working Cubed example for "map-reduce" #352
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
cb16e2a
Initial minimal working Cubed example for "map-reduce"
tomwhite ccae0d6
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 3375f28
Fix misspelled `aggegrate_func`
tomwhite abdc032
Update flox/core.py
tomwhite c740817
Expand to ALL_FUNCS
tomwhite bed1bcf
Use `_finalize_results` directly
tomwhite ca04f8a
Add test for nan values
tomwhite 4dd2158
Removed unused dtype from test
tomwhite dafaddb
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] ee0e597
Move example notebook to a gist https://gist.github.com/tomwhite/2d63…
tomwhite ef6b1fa
Add CubedArray type
tomwhite b0f7c68
Add Cubed to CI
tomwhite 1018620
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 2e80dc2
Make mypy happy
tomwhite 5b27ebc
Make mypy happy (again)
tomwhite File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,6 +6,7 @@ dependencies: | |
- cachey | ||
- cftime | ||
- codecov | ||
- cubed>=0.14.2 | ||
- dask-core | ||
- pandas | ||
- numpy>=1.22 | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -38,7 +38,9 @@ | |
) | ||
from .cache import memoize | ||
from .xrutils import ( | ||
is_chunked_array, | ||
is_duck_array, | ||
is_duck_cubed_array, | ||
is_duck_dask_array, | ||
isnull, | ||
module_available, | ||
|
@@ -63,10 +65,11 @@ | |
except (ModuleNotFoundError, ImportError): | ||
Unpack: Any # type: ignore[no-redef] | ||
|
||
import cubed.Array as CubedArray | ||
import dask.array.Array as DaskArray | ||
from dask.typing import Graph | ||
|
||
T_DuckArray = Union[np.ndarray, DaskArray] # Any ? | ||
T_DuckArray = Union[np.ndarray, DaskArray, CubedArray] # Any ? | ||
T_By = T_DuckArray | ||
T_Bys = tuple[T_By, ...] | ||
T_ExpectIndex = pd.Index | ||
|
@@ -95,7 +98,7 @@ | |
|
||
|
||
IntermediateDict = dict[Union[str, Callable], Any] | ||
FinalResultsDict = dict[str, Union["DaskArray", np.ndarray]] | ||
FinalResultsDict = dict[str, Union["DaskArray", "CubedArray", np.ndarray]] | ||
FactorProps = namedtuple("FactorProps", "offset_group nan_sentinel nanmask") | ||
|
||
# This dummy axis is inserted using np.expand_dims | ||
|
@@ -1718,6 +1721,109 @@ def dask_groupby_agg( | |
return (result, groups) | ||
|
||
|
||
def cubed_groupby_agg( | ||
array: CubedArray, | ||
by: T_By, | ||
agg: Aggregation, | ||
expected_groups: pd.Index | None, | ||
axis: T_Axes = (), | ||
fill_value: Any = None, | ||
method: T_Method = "map-reduce", | ||
reindex: bool = False, | ||
engine: T_Engine = "numpy", | ||
sort: bool = True, | ||
chunks_cohorts=None, | ||
) -> tuple[CubedArray, tuple[np.ndarray | CubedArray]]: | ||
import cubed | ||
import cubed.core.groupby | ||
|
||
# I think _tree_reduce expects this | ||
assert isinstance(axis, Sequence) | ||
assert all(ax >= 0 for ax in axis) | ||
|
||
inds = tuple(range(array.ndim)) | ||
|
||
by_input = by | ||
|
||
# Unifying chunks is necessary for argreductions. | ||
# We need to rechunk before zipping up with the index | ||
# let's always do it anyway | ||
if not is_chunked_array(by): | ||
# chunk numpy arrays like the input array | ||
chunks = tuple(array.chunks[ax] if by.shape[ax] != 1 else (1,) for ax in range(-by.ndim, 0)) | ||
|
||
by = cubed.from_array(by, chunks=chunks, spec=array.spec) | ||
_, (array, by) = cubed.core.unify_chunks(array, inds, by, inds[-by.ndim :]) | ||
|
||
# Cubed's groupby_reduction handles the generation of "intermediates", and the | ||
# "map-reduce" combination step, so we don't have to do that here. | ||
# Only the equivalent of "_simple_combine" is supported, there is no | ||
# support for "_grouped_combine". | ||
labels_are_unknown = is_chunked_array(by_input) and expected_groups is None | ||
do_simple_combine = not _is_arg_reduction(agg) and not labels_are_unknown | ||
|
||
assert do_simple_combine | ||
assert method == "map-reduce" | ||
assert expected_groups is not None | ||
assert reindex is True | ||
assert len(axis) == 1 # one axis/grouping | ||
|
||
def _groupby_func(a, by, axis, intermediate_dtype, num_groups): | ||
blockwise_method = partial( | ||
_get_chunk_reduction(agg.reduction_type), | ||
func=agg.chunk, | ||
fill_value=agg.fill_value["intermediate"], | ||
dtype=agg.dtype["intermediate"], | ||
reindex=reindex, | ||
user_dtype=agg.dtype["user"], | ||
axis=axis, | ||
expected_groups=expected_groups, | ||
engine=engine, | ||
sort=sort, | ||
) | ||
out = blockwise_method(a, by) | ||
# Convert dict to one that cubed understands, dropping groups since they are | ||
# known, and the same for every block. | ||
dcherian marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return {f"f{idx}": intermediate for idx, intermediate in enumerate(out["intermediates"])} | ||
dcherian marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def _groupby_combine(a, axis, dummy_axis, dtype, keepdims): | ||
# this is similar to _simple_combine, except the dummy axis and concatenation is handled by cubed | ||
# only combine over the dummy axis, to preserve grouping along 'axis' | ||
dtype = dict(dtype) | ||
out = {} | ||
for idx, combine in enumerate(agg.simple_combine): | ||
field = f"f{idx}" | ||
out[field] = combine(a[field], axis=dummy_axis, keepdims=keepdims) | ||
return out | ||
|
||
def _groupby_aggregate(a): | ||
# Convert cubed dict to one that _finalize_results works with | ||
results = {"groups": expected_groups, "intermediates": a.values()} | ||
out = _finalize_results(results, agg, axis, expected_groups, fill_value, reindex) | ||
return out[agg.name] | ||
|
||
# convert list of dtypes to a structured dtype for cubed | ||
intermediate_dtype = [(f"f{i}", dtype) for i, dtype in enumerate(agg.dtype["intermediate"])] | ||
dtype = agg.dtype["final"] | ||
num_groups = len(expected_groups) | ||
|
||
result = cubed.core.groupby.groupby_reduction( | ||
array, | ||
by, | ||
func=_groupby_func, | ||
combine_func=_groupby_combine, | ||
aggregate_func=_groupby_aggregate, | ||
axis=axis, | ||
intermediate_dtype=intermediate_dtype, | ||
dtype=dtype, | ||
num_groups=num_groups, | ||
) | ||
|
||
groups = (expected_groups.to_numpy(),) | ||
|
||
return (result, groups) | ||
|
||
|
||
def _collapse_blocks_along_axes(reduced: DaskArray, axis: T_Axes, group_chunks) -> DaskArray: | ||
import dask.array | ||
from dask.highlevelgraph import HighLevelGraph | ||
|
@@ -2240,6 +2346,7 @@ def groupby_reduce( | |
nax = len(axis_) | ||
|
||
has_dask = is_duck_dask_array(array) or is_duck_dask_array(by_) | ||
has_cubed = is_duck_cubed_array(array) or is_duck_cubed_array(by_) | ||
|
||
if _is_first_last_reduction(func): | ||
if has_dask and nax != 1: | ||
|
@@ -2302,7 +2409,30 @@ def groupby_reduce( | |
kwargs["engine"] = _choose_engine(by_, agg) if engine is None else engine | ||
|
||
groups: tuple[np.ndarray | DaskArray, ...] | ||
if not has_dask: | ||
if has_cubed: | ||
if method is None: | ||
method = "map-reduce" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Will also need a There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah, not sure where that would go exactly. |
||
|
||
if method != "map-reduce": | ||
raise NotImplementedError( | ||
"Reduction for Cubed arrays is only implemented for method 'map-reduce'." | ||
) | ||
|
||
partial_agg = partial(cubed_groupby_agg, **kwargs) | ||
|
||
result, groups = partial_agg( | ||
array, | ||
by_, | ||
expected_groups=expected_, | ||
agg=agg, | ||
reindex=reindex, | ||
method=method, | ||
sort=sort, | ||
) | ||
|
||
return (result, groups) | ||
|
||
elif not has_dask: | ||
results = _reduce_blockwise( | ||
array, by_, agg, expected_groups=expected_, reindex=reindex, sort=sort, **kwargs | ||
) | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -121,6 +121,7 @@ module=[ | |
"asv_runner.*", | ||
"cachey", | ||
"cftime", | ||
"cubed.*", | ||
"dask.*", | ||
"importlib_metadata", | ||
"numba", | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.