Skip to content

Feature/groupby reductions multiple levels - #1692

Merged
mrocklin merged 17 commits into
dask:masterfrom
chmp:feature/groupby-reductions-multiple-levels
Nov 7, 2016
Merged

mrocklin merged 17 commits into
dask:masterfrom
chmp:feature/groupby-reductions-multiple-levels

Conversation

@chmp

@chmp chmp commented Oct 23, 2016

Copy link
Copy Markdown
Contributor

While working on #1678, I found that the aggregates std, var, nunique for df.groupby(...) do not with multiple groupby columns. Further, grouping of multiple series that are transformations of columns is not supported.

Tests that fail with dask master for these cases are attached.

@chmp

chmp commented Oct 23, 2016

Copy link
Copy Markdown
Contributor Author

The rebase to master has some strange interaction with my code. I'll investigate.

Comment thread dask/dataframe/tests/test_groupby.py Outdated
call(ddf.groupby([ddf['a'], ddf['b']])['c'], agg_func))

assert_eq(call(pdf.groupby([pdf['a'] > 2, pdf['b'] > 1])['c'], agg_func),
call(ddf.groupby([ddf['a'] > 2, ddf['b'] > 1])['c'], agg_func))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be nice to extend one of the existing tests to include multi-series groupers. For example you could add new groupers to the for loop in test_split_apply_combine_on_series.

@chmp chmp Oct 23, 2016 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea. Once I figure out the reasons for the segfaults, I will adapt the existing tests.

@chmp

chmp commented Oct 23, 2016

Copy link
Copy Markdown
Contributor Author

Ok, at first blush the segfaulting seems to be a little bit more complicated. There has to be some kind of race condition introduced in my code. If I use the synchronous scheduler, everything seems to run (at least locally). Specifically, there is no segfault, if the last test looks like:

    with dask.set_options(get=dask.async.get_sync):
        assert_eq(call(pdf.groupby([pdf['a'] > 2, pdf['b'] > 1])['c'], agg_func),
                  call(ddf.groupby([ddf['a'] > 2, ddf['b'] > 1])['c'], agg_func))

As a meta question: I cannot run travis without updating the PR, or can I?

@mrocklin

Copy link
Copy Markdown
Member

I suspect that you only have the ability to restart tests if you own the repository. You might be able to do this if you were to open a PR to your own fork.

When I run into a segfault I usually try to distill it down to a small example and then share it with others. If possible I try to remove dask.dataframe from the example and see if I can reproduce with just Pandas and threads. If so then I kick it over to them as an issue and they can usually handle it fairly quickly.

@chmp

chmp commented Oct 23, 2016 •

Copy link
Copy Markdown
Contributor Author

Sorry, With my local test setup (python version and dependency versions), I could not reproduce this issue at first. However, @sinhrks was so kind to give a pointer how to setup travis with my fork. The next PR will be extensively tested with travis first.

Thanks for the debugging hint. Luckily, it was a bug in my code, that was easy to find by tracing the execution flow. However, there still seems to a possible segfault when passing a dask series directly to pandas.DataFrame.groupby. I'll try to find a minimal example open an issue.

@jcrist

jcrist commented Oct 24, 2016

Copy link
Copy Markdown
Member

However, there still seems to a possible segfault when passing a dask series directly to pandas.DataFrame.groupby. I'll try to find a minimal example open an issue.

The segfault was also found here: #1616 (comment).

@mrocklin

Copy link
Copy Markdown
Member

What is the status on this?

@chmp

chmp commented Oct 25, 2016

Copy link
Copy Markdown
Contributor Author

You mean the PR? I'm somewhat swamped at the moment. The implementation should be pretty feature complete, but I'd like to extend the tests. In particular, along the lines of your suggestion. Furthermore, I'd like to extend the tests in the direction of grouped series. I somehow overlooked that series can be grouped. Maybe this PR already fixes parts of the series-aggregate problem I stumbled upon in #1678 .

@mrocklin

Copy link
Copy Markdown
Member

OK, good to know. Don't mean to apply pressure. I mostly asked to see if things are blocking on lack of review.

@chmp

chmp commented Oct 25, 2016 •

Copy link
Copy Markdown
Contributor Author

I extended the tests and ran of course into a couple of problems. In particular related to groupby(...).apply(...). While it was not my original goal, my changes also extended the range of groupby arguments for which apply will work. Sadly, lists of series are not supported.

Further, I have yet to get unique for a series working, when a list is passed to groupby(...).

Finally, for python3.4, the name attribute of the mean series created by dask is None. This is related to the pandas version. Upgrading pandas solves this problem for me. To fix the test, I disabled the name-check for the mean operation.

The tests marked with xfail are essentially TODOs. I also ran into another segfault problem that mitigated by raising a python exception. The functionality is still not supported, but at least the interpreter won't crash.

@chmp

chmp commented Oct 26, 2016 •

Copy link
Copy Markdown
Contributor Author

Changes:

  • Rebase to master, to remove merge conflicts
  • Remove the xfails for mean/var type conversions. I assume this is a wont-fix issue, since there is no way to know the result of pandas mean/var operations without computing them.
  • Remove the xfails in the series-aggregate test that are fixed with the changes on the current branch
  • Fix nunique for series and in the process unify the code for _nunique_df_* and _nunique_series_*.

The only issues remaining are groupby-applys on multiple series that are not simple column-selects, i.e., .groupby([df['AA'], df['AB']]).apply(...) is fine, .groupby([df['AA'] + 1, df['AB'] + 1]).apply(...) is not.

Since I am now touching existing code paths, I really would appreciate a through feedback, in particular of the nunique changes.

@mrocklin mrocklin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the delay in review. This is looking pretty good to me. Some small requests follow:

Comment thread dask/dataframe/groupby.py Outdated
elif (isinstance(self.index, list) and
any(isinstance(item, Series) for item in self.index)):
# TODO: implement this
raise NotImplementedError("raise an error to prevent a segfault")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should have a better error message that users will understand. Something along the lines of "lists of Series not accepted in ...". The segfault text should be kept around as a comment.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't checked yet (working down through code) but it would be good to have an xfailed test for this if you don't have one already.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error message is changed, the x-failed tests were already part of the test-suite (test_full_groupby_multilevel and test_apply_shuffle_multilevel).

Comment thread dask/dataframe/groupby.py Outdated
"""
Return whether index is a Series sliced from df
"""
# TODO: handle list of series

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this TODO now handled below?

@chmp chmp Oct 29, 2016 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While trying to figure out this todo. If noticed that after index normalization quite some code could be simplified. I adapted the creation of _meta and _meta_nonmepty accordingly. I also added tests for the content of the _meta objects.

Comment thread dask/dataframe/groupby.py Outdated
def _get_groupby_chunk_args(obj, index):
if not isinstance(index, list):
return [obj, index]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would remove this whitespace. The if and else clauses seem related

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed the whitespace.

Comment thread dask/dataframe/groupby.py Outdated
if isinstance(index, (tuple, list)) and len(index) > 1:
return list(range(len(index)))
else:
return 0

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to have some text, perhaps just as a long comment in the code, about how these small functions _determine_levels, _get_groupby_chunk_args, etc. work together. This would help when maintaining this code and would also help newer developers.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added a module level description and short docstring to each function.

Comment thread dask/dataframe/groupby.py Outdated
msg = "Grouper for '{0}' not 1-dimensional"
raise ValueError(msg.format(index[0]))
#msg = "Grouper for '{0}' not 1-dimensional"
#raise ValueError(msg.format(index[0]))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should these lines remain or be deleted?

@chmp chmp Oct 29, 2016 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I adapted the logic to cover currently supported index values and added a test case to make sure exceptions are raised for unsupported ones.

call(ddf['c'].groupby(grouper(ddf)), agg_func, split_every=2),
# for pandas ~ 0.18, the name is not not properly propagated for
# the mean aggregation
check_names=(agg_func not in {'mean', 'nunique'}))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice tests

@chmp

chmp commented Oct 29, 2016 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Once travis is green, I'll push the changes.

Update: changes are pushed.

@chmp

chmp commented Nov 1, 2016

Copy link
Copy Markdown
Contributor Author

So, I'm quite happy with the current state. How about you, the dask maintainers?

The only functionality related to groupby(...) still not working is apply with multiple series. However, I would prefer to open an issue and deal with this topic independently.

@mrocklin

mrocklin commented Nov 1, 2016

Copy link
Copy Markdown
Member

@jcrist said he'd probably be able to take a closer look later today. It'd be good to get his thoughts.

@mrocklin mrocklin left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks pretty good to me. Most of my comments are stylistic.

This tweet came up today, which seemed timely: https://twitter.com/dan_abramov/status/793122481695559680 :)

Comment thread dask/dataframe/groupby.py Outdated


def _get_groupby_chunk_args(obj, index):
"""Get the object to group and any partioned index item as list of varargs.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo partitioned

Comment thread dask/dataframe/groupby.py Outdated
return index


def _get_groupby_chunk_args(obj, index):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function is small enough that we might just want to inline it as a ternary expression

# _get_groupby_chunk_args(obj, index)  # before
[obj, index] if isinstance(index, list) else [obj] + index  # after

I think that repeating this a few times is better than having the extra function indirection, which makes code harder to follow and maintain in the future.

Comment thread dask/dataframe/groupby.py Outdated
"""Get an index suitable for grouping meta objects.

Note, the index must be normalized. The ``meta_attribute`` should be
either ``'_meat'`` or ``'_meta_nonempty'``.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo meat

Comment thread dask/dataframe/groupby.py Outdated
return [obj] + index


def _get_index_meta(index, meta_attribute):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We might also want to inline this function. It's slightly more complex but only used in two places.

Comment thread dask/dataframe/groupby.py Outdated
return index


def _do_index_partions_align(df, index):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function is only used once and is only a few lines long. Lets just inline it for increased code locality.


# DataFrameGroupBy with column slice
assert_eq(ddf.groupby(grouper(ddf))[['B', 'C']].apply(lambda x: x.sum()),
pdf.groupby(grouper(pdf))[['B', 'C']].apply(lambda x: x.sum()))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice tests

Comment thread dask/dataframe/groupby.py Outdated
#
# Finally, the ``_get_index_meta`` allows to retrieve a index suitable for
# usage in groupby operations of the meta objects. Both empty and nonempty meta
# objects are supported.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice comment.

@jcrist

jcrist commented Nov 2, 2016

Copy link
Copy Markdown
Member

Apologies for not getting to this yesterday. Overall this looks pretty good to me. I agree with Matt on the inlining comments above - should help improve readability. Thanks for your work!

@chmp

chmp commented Nov 2, 2016

Copy link
Copy Markdown
Contributor Author

Thanks for your feedback. I will adapt the code accordingly. I hope I get to work on the PR tomorrow.

@chmp

chmp commented Nov 3, 2016

Copy link
Copy Markdown
Contributor Author

I inlined the functions as requested. To be honest, my weak preference would have been to keep separate functions, as they give additional structure to the code.

@mrocklin

mrocklin commented Nov 4, 2016

Copy link
Copy Markdown
Member

This looks fine to me. @jcrist ?

I inlined the functions as requested. To be honest, my weak preference would have been to keep separate functions, as they give additional structure to the code.

Yeah, I appreciate that my preferences here are stylistic and subjective. My general experience has been that structure feels good when you're writing code and already understand it fully but that structure feels like a burden when you're reading code for the first time or reviewing it. Structure highlights common patterns, but also adds extra steps before someone can understand what is going on. There is a tradeoff here that we need to balance each time. Do you mind if we fall on the side of less structure in this case?

@chmp

chmp commented Nov 5, 2016

Copy link
Copy Markdown
Contributor Author

Do you mind if we fall on the side of less structure in this case?

Thanks for the explanation. Don't get me wrong, I'm perfectly on board with the flat structure :)

In the end this contribution has to fit well into the overall dask source. While I tried to follow existing conventions, I did surely deviate at places. My comment was meant as a mere explanation of my choices (and preferences). In the end, you, as a maintainer, have to feel comfortable with the code and I'm happy to adapt any of my changes accordingly.

@mrocklin

mrocklin commented Nov 5, 2016

Copy link
Copy Markdown
Member

In the end, you, as a maintainer, have to feel comfortable with the code and I'm happy to adapt any of my changes accordingly.

Fortunately I am increasingly being replaced as the maintainer of dask.dataframe by a set of developers such as yourself coming up to take it over. As this happens presumably my views and coding styles should have less prominence and the views/styles of the community should take more authority.

@mrocklin

mrocklin commented Nov 5, 2016

Copy link
Copy Markdown
Member

Merging in 12 hours if no comments

@mrocklin
mrocklin merged commit 40213cc into dask:master Nov 7, 2016
@sinhrks sinhrks added this to the 0.13.0 milestone Jan 4, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants