Skip to content

merge_asof and prefix_reduction - #4877

Merged
TomAugspurger merged 34 commits into
dask:masterfrom
codercody:master
Jun 21, 2019
Merged

TomAugspurger merged 34 commits into
dask:masterfrom
codercody:master

Conversation

@codercody

Copy link
Copy Markdown
Contributor
  • Tests added / passed
  • Passes flake8 dask
  • Added a parallel prefix sum algorithm to core
  • Fixed a small bug with methods.boundary_slice (they forgot one edge case)
  • Added merge_asof

For merge_asof(left, right), the algorithm is to:

  1. slice up left so that its divisions are left.divisions U right.divisions
  2. pair up the ith part on the left to the jth part on the right when the former is a subset (in terms of indices) of the latter
  3. pad the right part with the last row of partition j-1 (roughly) and the first row of partition j+1 (roughly) in case the data needs to be retrieved from another partition
  4. merge all the paired padded parts and combine

merge_asof_demo

The things I know I messed up in this PR (and would like help fixing) are

  • I didn't modify the sphinx code because I didn't understand how to
  • My test cases are in a completely separate file from test_multi.py
  • I didn't include any test cases for the prefix sum yet since I didn't expect to turn it into a method of its own until the very end I decided to (though I did thoroughly test it beforehand)

@jakirkham

Copy link
Copy Markdown
Member

@jcrist, would you be able to take a look at this?

@mrocklin

mrocklin commented Jun 4, 2019

Copy link
Copy Markdown
Member

Hi @codercody , this looks like exciting work. I have a few rough suggestions, though I suspect that folks like @TomAugspurger or @jrbourbeau (who know a bit more about dask dataframe) may have more.

  1. If possible, it would be good not to include moderately large testing files in the repository. This makes things a little bloated. Ideally you would be able to quickly generate some artificial data as part of a test.
  2. Similarly, those tests should probably be pretty fast and easy to understand, so smaller testing datasets would be welcome.
  3. I suspect that thee linter will yell at you. You might want to run flake8 dask on your code in order to get a sense of expectations. This is also available here: https://travis-ci.org/dask/dask/jobs/541084621

@TomAugspurger TomAugspurger 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.

Thanks @codercody, still going through this.

Comment thread dask/dataframe/core.py Resolved
Comment thread dask/dataframe/tests/test_multi.py Resolved
Comment thread dask/dataframe/tests/test_multi.py Resolved
Comment thread dask/dataframe/tests/test_multi.py Outdated
B = pd.DataFrame({'a': [1, 2, 3, 6, 7], 'right_val': [1, 2, 3, 6, 7]})
b = dd.from_pandas(B, npartitions=2)

C = pd.merge_asof(A, B, on='a', allow_exact_matches=False).set_index('a')

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.

Why is the set-index needed here? I haven't looked at the implementation yet, forgive me if that's explained there.

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.

Sorry. When Pandas does a merge_asof on a particular column, the resulting dataframe gets reindexed 0, 1, .... This is the one place where my implementation differs from Pandas': if your merge_asof on a particular column using mine, it sets the index as that on column. I could alternatively do a reset_index() in my implementation but I find it kind of silly.

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.

Furthermore, this is causing Travis CI to mess up, since I guess this causes some index to be permuted in a different way.

E       AssertionError: Index are different
E       
E       Index values are different (100.0 %)
E       [left]:  Index([u'price', u'quantity', u'ticker', u'ask', u'bid'], dtype='object')
E       [right]: Index([u'ask', u'bid', u'price', u'quantity', u'ticker'], dtype='object')

Do you know what I should do to fix this to pass Travis CI?

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.

Ideally we would match pandas output.

We may not be able to entirely in this case. This might be a case where we need each partition to have its own RangeIndex(0, len(partition)).

Comment thread dask/dataframe/tests/test_multi.py Resolved
Comment thread dask/dataframe/multi.py Resolved
Comment thread dask/dataframe/multi.py
if left is None or right is None:
raise ValueError("Cannot merge_asof on empty DataFrames")

if isinstance(left, pd.DataFrame) and isinstance(right, pd.DataFrame):

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.

@mrocklin what's best for cuDF here? Would a dispatchable merge_asof, and replace these checks with is_dataframe_like be best?

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 think that we should use is_dataframe_like universally.

I think that we should continue to use pd.merge_asof until some other pandas implementation supports the operation, at that point I think that we would either try to add a method, or a dispatchable function. I wouldn't worry about this until that happens though.

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.

So, to be clear @codercody , if you can replace checks like

isinstance(df, pd.DataFrame)

with

is_dataframe_like(df)

That would be welcome.

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 was trying to copy line 346 in the merge implementation, where they separately handled when left and right are actually pd.DataFrames and not dd.DataFrames. If you don't want me to handle this case, then I'm just going to delete this check altogether. Is that fine?

Comment thread dask/dataframe/multi.py Resolved
Comment thread dask/dataframe/multi.py Resolved
Comment thread dask/dataframe/multi.py Resolved
…ically created helper functions to module helper functions in compute_heads and compute_tails

@TomAugspurger TomAugspurger 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.

Can you check on the CI failure: https://travis-ci.org/dask/dask/jobs/544385948#L1798

It's possible you're relying on dict ordering here, while we support Python 3.5.

@mrocklin

Copy link
Copy Markdown
Member

@codercody I see that you reacted with the Confused emoji to @TomAugspurger 's recent comment below:

It's possible you're relying on dict ordering here, while we support Python 3.5.

To expand on this, it looks like the tests are failing, but only in Python 3.5, and not in any newer Python versions. You can see the failure here: https://travis-ci.org/dask/dask/jobs/544385948

Details
____________________________ test_merge_asof_on_by _____________________________
[gw2] linux -- Python 3.5.6 /home/travis/miniconda/envs/test-environment/bin/python
    def test_merge_asof_on_by():
        times_A = [pd.to_datetime(d) for d in ['2016-05-25 13:30:00.023',
                                               '2016-05-25 13:30:00.023',
                                               '2016-05-25 13:30:00.030',
                                               '2016-05-25 13:30:00.041',
                                               '2016-05-25 13:30:00.048',
                                               '2016-05-25 13:30:00.049',
                                               '2016-05-25 13:30:00.072',
                                               '2016-05-25 13:30:00.075']]
        tickers_A = ['GOOG', 'MSFT', 'MSFT', 'MSFT', 'GOOG', 'AAPL', 'GOOG', 'MSFT']
        bids_A = [720.50, 51.95, 51.97, 51.99, 720.50, 97.99, 720.50, 52.01]
        asks_A = [720.93, 51.96, 51.98, 52.00, 720.93, 98.01, 720.88, 52.03]
        times_B = [pd.to_datetime(d) for d in ['2016-05-25 13:30:00.023',
                                               '2016-05-25 13:30:00.038',
                                               '2016-05-25 13:30:00.048',
                                               '2016-05-25 13:30:00.048',
                                               '2016-05-25 13:30:00.048']]
        tickers_B = ['MSFT', 'MSFT', 'GOOG', 'GOOG', 'AAPL']
        prices_B = [51.95, 51.95, 720.77, 720.92, 98.00]
        quantities_B = [75, 155, 100, 100, 100]
    
        A = pd.DataFrame({'time': times_A, 'ticker': tickers_A, 'bid': bids_A, 'ask': asks_A})
        a = dd.from_pandas(A, npartitions=4)
        B = pd.DataFrame({'time': times_B, 'ticker': tickers_B, 'price': prices_B, 'quantity': quantities_B})
        b = dd.from_pandas(B, npartitions=3)
    
        C = pd.merge_asof(B, A, on='time', by='ticker').set_index('time')
        c = merge_asof(b, a, on='time', by='ticker')
>       assert_eq(c, C)
dask/dataframe/tests/test_multi.py:342: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
dask/dataframe/utils.py:697: in assert_eq
    a = _check_dask(a, check_names=check_names, check_dtypes=check_dtypes)
dask/dataframe/utils.py:653: in _check_dask
    tm.assert_index_equal(dsk.columns, result.columns)
../../../miniconda/envs/test-environment/lib/python3.5/site-packages/pandas/util/testing.py:922: in assert_index_equal
    raise_assert_detail(obj, msg, left, right)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
obj = 'Index', message = 'Index values are different (100.0 %)'
left = Index(['price', 'quantity', 'ticker', 'ask', 'bid'], dtype='object')
right = Index(['ask', 'bid', 'price', 'quantity', 'ticker'], dtype='object')
diff = None
    def raise_assert_detail(obj, message, left, right, diff=None):
        if isinstance(left, np.ndarray):
            left = pprint_thing(left)
        elif is_categorical_dtype(left):
            left = repr(left)
        if isinstance(right, np.ndarray):
            right = pprint_thing(right)
        elif is_categorical_dtype(right):
            right = repr(right)
    
        msg = """{obj} are different
    
    {message}
    [left]:  {left}
    [right]: {right}""".format(obj=obj, message=message, left=left, right=right)
    
        if diff is not None:
            msg += "\n[diff]: {diff}".format(diff=diff)
    
>       raise AssertionError(msg)
E       AssertionError: Index are different
E       
E       Index values are different (100.0 %)
E       [left]:  Index(['price', 'quantity', 'ticker', 'ask', 'bid'], dtype='object')
E       [right]: Index(['ask', 'bid', 'price', 'quantity', 'ticker'], dtype='object')

Given the fact that this is an ordering thing, and that it's only on Python 3.5, Tom was guessing that this was due to expecting that dicts are consistently ordered, which is something that changed between 3.5 and 3.6. In Python 3.6 calling list(my_dict) always gives the same result, and is consistent with the order of the input.

To make things concrete, if you create an environment with Python 3.5 do your tests pass for you?

Also, as a quick note, many of the maintainers track PRs by e-mail. We get notifications when someone pushes a new commit or makes a comment, but not when someone reacts to a comment with an emoji, hence the delay in response here.

@mrocklin

Copy link
Copy Markdown
Member

@TomAugspurger other than the dict ordering issue is this ready to go in, or does it still need more work?

This is one of the few substantial outstanding PRs that we have before we might use black. I have a slight preference to black-ify things before the release, which I would ideally like to do soon. (though that's somewhat arbitrary, black could slip, or we could redo this PR after black.

@mrocklin mrocklin mentioned this pull request Jun 20, 2019
Comment thread dask/dataframe/tests/test_multi.py Outdated
B = pd.DataFrame({'a': [1, 2, 3, 6, 7], 'right_val': [1, 2, 3, 6, 7]})
b = dd.from_pandas(B, npartitions=2)

C = pd.merge_asof(A, B, on='a').set_index('a')

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 still concerns me. I'm looking into why it's necessary now.

@TomAugspurger

Copy link
Copy Markdown
Member

@codercody apologies for the flurry of commits. Can yo take a look at 0e60df1 and confirm that it looks OK?

That matches the output, other than the index. With Dask's merge_asof, each partition has its on RangeIndex(0, n_rows). We need to document the difference in behavior somewhere, but the wraps we're using to copy the docstring doesn't allow that. The usual utils.derived_from only works with classes at the moment.

Docs probably aren't a blocker.

@TomAugspurger

Copy link
Copy Markdown
Member

Sorry, I seem to have broken things (right now I think it's an issue with concat no longer implicitly sorting. I'll take a look in a couple hours).

@TomAugspurger

TomAugspurger commented Jun 20, 2019 •

Copy link
Copy Markdown
Member

fd6cef3 should pass. This is probably good to go, though I would like to see the docs issue from #4877 (comment) addressed eventually.

@TomAugspurger

Copy link
Copy Markdown
Member

Still seem to have a column order issue with pandas 0.21.x.

@mrocklin

Copy link
Copy Markdown
Member

Green check mark :)

@TomAugspurger

Copy link
Copy Markdown
Member

Alrighty, here goes.

Thanks @codercody, nice work!

@TomAugspurger
TomAugspurger merged commit 367ab9f into dask:master Jun 21, 2019
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