Skip to content
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

fix(python): fix ufunc in agg (change __ufunc_array__ so it uses is_elementwise=True parameter) #14135

Merged
merged 2 commits into from
Feb 3, 2024

Conversation

deanm0000
Copy link
Collaborator

Fixes #13557

I was back burnering whether or not there was a good way to tell if a ufunc was elementwise for a while now when I realized that they're all elementwise.

I did this test:

import numpy as np
import polars as pl
import scipy.special as ss
from polars.testing import assert_frame_equal
npufuncs = []
for x in dir(np):
    if getattr(np,x).__class__==np.ufunc:
        npufuncs.append(x)
ssufuncs = []
for x in dir(ss):
    if getattr(ss, x).__class__==np.ufunc:
        ssufuncs.append(x)
        
df=pl.DataFrame({'a':[1,1,2,2],
                 'b':[1.1,2.2,3.3,4.4],
                 'c':[3.1,4.2,5.3,6.4]})

goodufuncs = {"<module 'numpy' from '/usr/local/lib/python3.11/site-packages/numpy/__init__.py'>":[],
              "<module 'scipy.special' from '/usr/local/lib/python3.11/site-packages/scipy/special/__init__.py'>":[]}
for cls, xlist in {np:npufuncs, ss:ssufuncs}.items():
    for x in xlist:
        onearg=True
        while True:
            try:
                if onearg:
                    assert_frame_equal(
                        df.group_by('a',maintain_order=True).agg(pl.col('b').map_batches(getattr(cls,x), is_elementwise=True)),
                        df.group_by('a',maintain_order=True).agg(pl.col('b').map_batches(getattr(cls,x), is_elementwise=False))
                    )
                else:
                    assert_frame_equal(
                        df.group_by('a',maintain_order=True).agg(pl.struct('b','c')
                            .map_batches(lambda z, cls=cls, x=x: getattr(cls,x)(z.struct.field('b'), z.struct.field('c')), is_elementwise=True)),
                        df.group_by('a',maintain_order=True).agg(pl.struct('b','c')
                            .map_batches(lambda z, cls=cls, x=x: getattr(cls,x)(z.struct.field('b'), z.struct.field('c')), is_elementwise=False))
                    )
                goodufuncs[str(cls)].append(x)
                break

            except Exception as err:
                if "takes from 2 to " in str(err):
                    onearg=False
                else:
                    print(f"{x} gave {err}")
                    break

At the end, there are no assertion errors so for stock ufuncs in numpy and scipy.special it is safe to dispatch them with map_batches(func, is_elementwise=True) For any other ufunc, like the result of using numba.guvectorize there will be a warning that they should call their function through map_batches.

@ritchie46
Copy link
Member

Ah, ok, thanks for testing that. 😄 Thanks for the this change. It should probably to less surprises.

@ritchie46 ritchie46 merged commit 975af10 into pola-rs:main Feb 3, 2024
11 checks passed
@deanm0000 deanm0000 deleted the fix_ufunc_map_batches branch August 26, 2024 14:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
fix Bug fix python Related to Python Polars
Projects
None yet
Development

Successfully merging this pull request may close these issues.

ComputeError when applying an UDF in a group_by aggregation
2 participants