Skip to content

MAINT: casting changes for int -> m8 - #13061

Closed
tylerjereddy wants to merge 1 commit into
numpy:masterfrom
tylerjereddy:issue_12927_casting_alternative
Closed

tylerjereddy wants to merge 1 commit into
numpy:masterfrom
tylerjereddy:issue_12927_casting_alternative

Conversation

@tylerjereddy

Copy link
Copy Markdown
Contributor

Alternative to #12940 that Fixes #12927.

This approach is a bit more invasive in terms of likely effect on downstream libraries, but was preferred by core developers in the linked discussions above.

This will likely still need:

  • decisions/ discussions about Warnings and / or Deprecations needed

Comment thread numpy/core/tests/test_datetime.py Resolved
Comment thread numpy/polynomial/tests/test_classes.py Resolved
* prevent int64 //= uint64 from succeeding
(a recent regression) by preventing the safe
cast from all integer types and bool to timedelta64

* corresponding unit test additions / adjustments


@pytest.mark.parametrize("int_typecode",
list(np.typecodes['AllInteger'] + '?'))

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've added bool in here now as well

# that dot() supports
dtypes = [np.dtype(code) for code in np.typecodes['All']
if code not in 'USVM']
if code not in 'USVMm']

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.

a reviewer should probably confirm that the need for this with the casting changes makes sense; I think the need for this only snuck in after I prohibited bool from casting to timedelta64

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.

Calling dot on timedeltas is nonsense, so this change seems fine

@tylerjereddy

tylerjereddy commented Mar 21, 2019 •

Copy link
Copy Markdown
Contributor Author

I've performed the following build / test sequences on pandas master branch to confirm that the changes in this feature branch do break pandas datetime behavior, so I'll aim to follow up with them, possibly with a patch if not too hard & see if they think it is too disruptive.

  • first on their master branch (e31b4f46) with numpy master branch (0eda21b)
python setup.py install --user
python setup.py build_ext --inplace
./test_fast.sh
46266 passed, 2936 skipped, 1023 xfailed, 16 xpassed in 267.92 seconds
  • then on their master branch (e31b4f46) with this feature branch (b078513)
python setup.py install --user
python setup.py build_ext --inplace
./test_fast.sh
I get an immediate traceback here related to datetime

Traceback details:

Details
ImportError while loading conftest '/mnt/c/Users/treddy/github_projects/pandas/pandas/conftest.py'.
pandas/__init__.py:42: in <module>
    from pandas.core.api import *
pandas/core/api.py:7: in <module>
    from pandas.core.arrays.integer import (
pandas/core/arrays/__init__.py:6: in <module>
    from .datetimes import DatetimeArray  # noqa
pandas/core/arrays/datetimes.py:30: in <module>
    from pandas.core.arrays import datetimelike as dtl
pandas/core/arrays/datetimelike.py:37: in <module>
    from pandas.tseries import frequencies
pandas/tseries/frequencies.py:28: in <module>
    from pandas.tseries.offsets import (
pandas/tseries/offsets.py:2239: in <module>
    class Tick(liboffsets._Tick, SingleConstructorOffset):
pandas/tseries/offsets.py:2240: in Tick
    _inc = Timedelta(microseconds=1000)
pandas/_libs/tslibs/timedeltas.pyx:1189: in pandas._libs.tslibs.timedeltas.Timedelta.__new__
    raise ValueError("cannot construct a Timedelta from the "
E   ValueError: cannot construct a Timedelta from the passed arguments, allowed keywords are [weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds]

@tylerjereddy

Copy link
Copy Markdown
Contributor Author

The initial reaction on the pandas side seems very positive (cross-linked above). The casting effect on built-in sum vs. np.sum() is something I didn't fully understand when writing that patch. Probably obvious to the ufunc experts.

@tylerjereddy

tylerjereddy commented Mar 22, 2019 •

Copy link
Copy Markdown
Contributor Author

To summarize one thing that surprised me a little from making changes in pandas:

arr = np.array([0, 1, 2], dtype='m8[s]')
np.sum(arr) # works
arr[0] + arr[1] + arr[2] # works
# The following doesn't work--CPython must
# try to work with ints and cast back?
sum(arr)
# numpy.core._exceptions.UFuncTypeError: Cannot cast ufunc 'add' input 0 from dtype('int64') to dtype('<m8[s]') with casting rule 'same_kind'

Not sure there's much we can do about built-in sum

@eric-wieser

Copy link
Copy Markdown
Member

Buultin sum adds 0 as a default. sum(arr, datetime64(0)) works fine

@tylerjereddy

Copy link
Copy Markdown
Contributor Author

Thanks Eric, I'll mention that in the pandas PR--I guess it isn't a big deal.

@eric-wieser

Copy link
Copy Markdown
Member

Note that the built-in sum should be avoided anyway, it doesn't produce the right dtype when the array is empty.

@tylerjereddy

Copy link
Copy Markdown
Contributor Author

Compensating changes merged on the pandas side, so doesn't look disruptive to them.

@hameerabbasi

Copy link
Copy Markdown
Contributor

I'd like this in... As datetime64 isn't really compatible with any of the floating point or integer types. Indeed, I'd consider it a bug and not a feature. It also more correctly follows the rules of casting='safe'.

If a fast sum is required, use an initial= kwarg for np.sum.

@tylerjereddy tylerjereddy changed the title WIP, MAINT: casting changes for int -> m8 MAINT: casting changes for int -> m8 Mar 29, 2019
@jbrockmendel

Copy link
Copy Markdown
Contributor

@tylerjereddy is this still a going concern? If/when this happens, pandas can rip out some ugly arithmetic shims that implement it there.

@seberg

seberg commented Jun 4, 2019

Copy link
Copy Markdown
Member

Probably still is a concern. @jbrockmendel and @hameerabbasi would you want to rush this? If not too much, I will tag this with 1.18 and you can nudge us to merge it soon after the 1.17.x branching? Just a thought, I am starting to worry a bit about making 1.17 too large (and it is getting close in any case).

I suppose we are missing a bit of review here, but it seems fairly straight forward and far along on first glance.

@seberg seberg added this to the 1.18.0 release milestone Jun 4, 2019
@jbrockmendel

Copy link
Copy Markdown
Contributor

Definitely don't rush on pandas' account. Even once it's merged it'll be a few release cycles before we can rely on it.

@hameerabbasi

Copy link
Copy Markdown
Contributor

Yes, 1.18.x is fine. 🙂

@jbrockmendel

Copy link
Copy Markdown
Contributor

@tylerjereddy anything I can do to help make this a reality?

@tylerjereddy

Copy link
Copy Markdown
Contributor Author

@jbrockmendel Maybe @eric-wieser or @seberg can chime in on if this is still desired & an appropriate time for the change & also if we need warnings / deprecations in this case. I'm a little less active on NumPy than SciPy lately but can probably (slowly) respond to reviewer requests.

@seberg seberg added the 56 - Needs Release Note. Needs an entry in doc/release/upcoming_changes label Oct 15, 2019
@mattip

mattip commented Oct 15, 2019

Copy link
Copy Markdown
Member

Let's try to put this in.

@tylerjereddy could you fix the conflict and add a release note?

@eric-wieser would you like to take one last look?


_npy_can_cast_safely_table[NPY_STRING][NPY_UNICODE] = 1;
_npy_can_cast_safely_table[NPY_BOOL][NPY_TIMEDELTA] = 1;
_npy_can_cast_safely_table[NPY_BOOL][NPY_TIMEDELTA] = 0;

@eric-wieser eric-wieser Oct 15, 2019 •

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 this should go on line 3916 instead, as

        if (i != NPY_DATETIME && i != NPY_TIMEDELTA) {
            /*
             * Bool -> <Anything> except datetime (since
             *                    it would assume implicit units)
             */
            _npy_can_cast_safely_table[NPY_BOOL][i] = 1;
        }

a = np.arange('1969-05', '1970-05', 2, dtype='M8')
assert_equal(a.dtype, np.dtype('M8[M]'))
assert_equal(a,
np.datetime64('1969-05') + np.arange(12, step=2))

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 great if we could keep this test somehow... Trying to work out how.

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.

If gh-14714 goes in, adding dtype='m8' to the arange call would do the trick.

Without it, you need to change 12 to 0, 12 as well.

offsets = np.array([0, 0, 1, 1, 2, 3, 5, 10, 20], dtype='m8[D]')
bins = np.array([0, 2, 7, 20], dtype='m8[D]')
dates = begin + offsets
date_bins = begin + bins

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 doesn't look right - I think you should leave what you touched unchanged, and it should read

dates = begin + offsets.astype('m8[D]')
date_bins = begin + bins.astype('m8[D]')

Comment on lines +346 to +349
# NOTE: produces DeprecationWarning with recent casting adjustment
# blocking int64-> m8
#assert_equal((d_edge - begin).astype(int), i_edge)
#assert_equal(t_edge.astype(int), i_edge)

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.

With the change I suggest above you should be able to leave this in

Comment on lines 304 to +307
if not issubclass(stype, Number) or issubclass(stype, bool):
continue
s = stype(5)
if stype == np.timedelta64:

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 we just not register timedelta64 as a Number? Or is that too hard?

@eric-wieser eric-wieser 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.

Not a huge fan of weakening the tests to pull this off. Also a little worried that issubclass(np.timedelta64, numbers.Number) appears to still be true.

@mattip

mattip commented Nov 25, 2019

Copy link
Copy Markdown
Member

@tylerjereddy do you want help updating this from the reviews?

@seberg

seberg commented Nov 25, 2019

Copy link
Copy Markdown
Member

Opst, I think this was superceded by gh-14718

@seberg

seberg commented Nov 25, 2019

Copy link
Copy Markdown
Member

Thanks Tyler, the other one is in, so closing this one!

@seberg seberg closed this Nov 25, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

03 - Maintenance 06 - Regression 56 - Needs Release Note. Needs an entry in doc/release/upcoming_changes component: numpy.datetime64 (and timedelta64)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

int64 //= uint64 succeeds in 1.16.1

6 participants