Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions cpp/src/arrow/compute/kernels/codegen_internal.cc
Original file line number Diff line number Diff line change
Expand Up @@ -588,17 +588,20 @@ bool HasDecimal(const std::vector<TypeHolder>& types) {
return false;
}

void PromoteIntegerForDurationArithmetic(std::vector<TypeHolder>* types) {
void PromoteNumericForDurationArithmetic(std::vector<TypeHolder>* types) {
bool has_duration = std::any_of(types->begin(), types->end(), [](const TypeHolder& t) {
return t.id() == Type::DURATION;
});

if (!has_duration) return;

// Require implicit casts to int64 to match duration's bit width
// Require implicit casts to int64 to match duration's bit width, and to float64,
// the only floating point type with duration kernels
for (auto& type : *types) {
if (is_integer(type.id())) {
type = int64();
} else if (is_floating(type.id())) {
type = float64();
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion cpp/src/arrow/compute/kernels/codegen_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -1459,7 +1459,7 @@ ARROW_EXPORT
bool HasDecimal(const std::vector<TypeHolder>& types);

ARROW_EXPORT
void PromoteIntegerForDurationArithmetic(std::vector<TypeHolder>* types);
void PromoteNumericForDurationArithmetic(std::vector<TypeHolder>* types);

// END of DispatchBest helpers
// ----------------------------------------------------------------------
Expand Down
54 changes: 51 additions & 3 deletions cpp/src/arrow/compute/kernels/scalar_arithmetic.cc
Original file line number Diff line number Diff line change
Expand Up @@ -785,7 +785,7 @@ struct ArithmeticFunction : ScalarFunction {

if (name_ == "multiply" || name_ == "multiply_checked" || name_ == "divide" ||
name_ == "divide_checked") {
PromoteIntegerForDurationArithmetic(types);
PromoteNumericForDurationArithmetic(types);
}
}

Expand Down Expand Up @@ -1126,6 +1126,44 @@ void AddArithmeticFunctionDurationTime(std::shared_ptr<ScalarFunction> func) {
std::move(exec_4)));
}

// Apply Op in double precision and truncate toward zero, like numpy. Durations
// beyond 2^53 lose precision in the conversion to double.
// NaN and out of range results are errors, also in the unchecked functions, where
// integer overflow wraps around instead. numpy returns NaT for these, but Arrow has
// no NaT, and casting an out of range double to int64 is undefined behaviour.
template <typename Op>
struct DurationByFloat {
template <typename T, typename Arg0, typename Arg1>
static T Call(KernelContext* ctx, Arg0 left, Arg1 right, Status* st) {
double value = Op::template Call<double, double, double>(
ctx, static_cast<double>(left), static_cast<double>(right), st);

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.

static_cast<double> is only exact up to 2^53, so larger durations lose their low bits even when multiplied by 1.0:

multiply(duration[ns] [9007199254740993], 1.0) -> [9007199254740992]

2^53 ns is about 104 days, so this is easy to hit with duration[ns]. numpy behaves the same way, so I don't think we need to do better here, but it should be mentioned in the docs.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Documented in the kernel comment and compute.rst: durations beyond 2^53 lose precision when converted to float64, as in numpy.

double truncated = std::trunc(value);

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.

Truncation matches numpy, but it makes the round trip from the issue lossy, because n / unit * unit often lands just below n in float64:

d = [1, 2, 3, 100] (duration[s]), unit = 49s
multiply(divide(d, unit), unit) -> [0, 1, 3, 100]
multiply(100s, 0.29)            -> [28]

numpy also gives 0 for 1 / 49 * 49. Rounding to nearest would fix the round trip, but then the example from the issue would no longer match numpy (3s * 0.5 would give 2 instead of 1).

I'm fine with keeping truncation for numpy compatibility, but please document this caveat. @randolf-scholz does truncation work for your use case?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Kept truncation and documented the caveat in compute.rst, with 1s / 49s × 49s coming back as 0s.

// The int64 range is [-2^63, 2^63); the comparison is false for NaN
if (ARROW_PREDICT_FALSE(!(truncated >= -0x1p63 && truncated < 0x1p63))) {
*st = Status::Invalid(std::isnan(truncated) ? "result is NaN" : "overflow");

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.

The unchecked variants raise here, which differs from their neighbours: unchecked multiply(duration, int64) wraps on overflow and divide(1.0, 0.0) returns inf.

It also differs from numpy, which returns NaT for td * nan, td * inf and td / 0.0. So "like numpy" only holds for the truncation.

Raising seems reasonable to me, since an out of range static_cast is undefined behaviour and we have no NaT. Did you consider emitting null for the unchecked variants instead? Either way, please make the comment and the docs explicit about this.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I kept raising: null would make an invalid result look like a missing value, and there is no NaT. The comment, the docstrings and compute.rst now say this differs from the unchecked integer kernels and from numpy.

return 0;
}
return static_cast<T>(truncated);
}
};

// Add Op(duration, float64) -> duration, and Op(float64, duration) -> duration for
// Multiply. The same kernels are used for the checked and unchecked functions.
// Other floating point types are cast to float64 in DispatchBest.
template <typename Op>
void AddDurationByFloatKernels(ScalarFunction* func) {
for (auto unit : TimeUnit::values()) {
auto exec =
ScalarBinaryNotNull<Int64Type, Int64Type, DoubleType, DurationByFloat<Op>>::Exec;
DCHECK_OK(func->AddKernel({duration(unit), float64()}, duration(unit), exec));

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.

Only an exact float64 matches. multiply(duration[s], float32) (and halffloat) still raises:

NotImplemented: Function 'multiply' has no kernel matching input types (duration[s], float)

All integer widths work because PromoteIntegerForDurationArithmetic casts them to int64 in DispatchBest. Could we promote floats to float64 there as well, and add a CheckDispatchBest case? If you would rather leave that for a follow-up, please add a test that pins the current behaviour and open an issue.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

float32 and halffloat are now cast to float64 in DispatchBest, like integers are cast to int64 (the helper is renamed to PromoteNumericForDurationArithmetic), with CheckDispatchBest and execution tests.

if constexpr (std::is_same_v<Op, Multiply>) {
exec = ScalarBinaryNotNull<Int64Type, DoubleType, Int64Type,
DurationByFloat<Op>>::Exec;
DCHECK_OK(func->AddKernel({float64(), duration(unit)}, duration(unit), exec));
}
}
}

const FunctionDoc absolute_value_doc{
"Calculate the absolute value of the argument element-wise",
("Results will wrap around on integer overflow.\n"
Expand Down Expand Up @@ -1166,7 +1204,10 @@ const FunctionDoc sub_checked_doc{
const FunctionDoc mul_doc{"Multiply the arguments element-wise",
("Results will wrap around on integer overflow.\n"
"Use function \"multiply_checked\" if you want overflow\n"
"to return an error."),
"to return an error.\n"
"A duration multiplied by a floating-point number is\n"
"computed in float64 and truncated toward zero, and\n"
"overflow and NaN always return an error."),
{"x", "y"}};

const FunctionDoc mul_checked_doc{
Expand All @@ -1180,7 +1221,10 @@ const FunctionDoc div_doc{
("Integer division by zero returns an error. However, integer overflow\n"
"wraps around, and floating-point division by zero returns an infinite.\n"
"Use function \"divide_checked\" if you want to get an error\n"
"in all the aforementioned cases."),
"in all the aforementioned cases.\n"
"A duration divided by a floating-point number is computed in float64\n"
"and truncated toward zero, and division by zero, overflow and NaN\n"
"always return an error."),
{"dividend", "divisor"}};

const FunctionDoc div_checked_doc{
Expand Down Expand Up @@ -1711,6 +1755,7 @@ void RegisterScalarArithmetic(FunctionRegistry* registry) {
DCHECK_OK(multiply->AddKernel({duration(unit), int64()}, duration(unit), exec));
DCHECK_OK(multiply->AddKernel({int64(), duration(unit)}, duration(unit), exec));
}
AddDurationByFloatKernels<Multiply>(multiply.get());

DCHECK_OK(registry->AddFunction(std::move(multiply)));

Expand All @@ -1727,6 +1772,7 @@ void RegisterScalarArithmetic(FunctionRegistry* registry) {
DCHECK_OK(
multiply_checked->AddKernel({int64(), duration(unit)}, duration(unit), exec));
}
AddDurationByFloatKernels<Multiply>(multiply_checked.get());

DCHECK_OK(registry->AddFunction(std::move(multiply_checked)));

Expand All @@ -1740,6 +1786,7 @@ void RegisterScalarArithmetic(FunctionRegistry* registry) {
DCHECK_OK(
divide->AddKernel({duration(unit), int64()}, duration(unit), std::move(exec)));
}
AddDurationByFloatKernels<DivideChecked>(divide.get());

// Add divide(duration, duration) -> float64
for (auto unit : TimeUnit::values()) {
Expand All @@ -1761,6 +1808,7 @@ void RegisterScalarArithmetic(FunctionRegistry* registry) {
DCHECK_OK(divide_checked->AddKernel({duration(unit), int64()}, duration(unit),
std::move(exec)));
}
AddDurationByFloatKernels<DivideChecked>(divide_checked.get());

// Add divide_checked(duration, duration) -> float64
for (auto unit : TimeUnit::values()) {
Expand Down
53 changes: 53 additions & 0 deletions cpp/src/arrow/compute/kernels/scalar_temporal_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -1749,6 +1749,59 @@ TEST_F(ScalarTemporalTest, TestTemporalDivideDuration) {
{duration(TimeUnit::NANO), duration(TimeUnit::NANO)});
}

TEST_F(ScalarTemporalTest, TestTemporalMultiplyDivideDurationByFloat) {
// Results are truncated, slots with a null are not computed, -2^63 is in range
for (auto u : TimeUnit::values()) {
auto durations =
ArrayFromJSON(duration(u), "[10, 5, 7, -5, 2, null, 1, -4611686018427387904]");
for (auto op : {"multiply", "multiply_checked"}) {
CheckScalarBinaryCommutative(
op, durations,
ArrayFromJSON(float64(), "[2.5, 1.5, 1.5, 1.5, 0.4, NaN, null, 2]"),
ArrayFromJSON(duration(u),
"[25, 7, 10, -7, 0, null, null, -9223372036854775808]"));
}
for (auto op : {"divide", "divide_checked"}) {
CheckScalarBinary(
op, durations, ArrayFromJSON(float64(), "[0.5, 2, 2, 2, 3, 0, null, 0.5]"),
ArrayFromJSON(duration(u),
"[20, 2, 3, -2, 0, null, null, -9223372036854775808]"));
}
}
// NaN and out of range results, and division by zero, are errors in all variants
auto one = ArrayFromJSON(duration(TimeUnit::SECOND), "[1]");
auto big = ArrayFromJSON(duration(TimeUnit::SECOND), "[4611686018427387904]");
auto nan = ArrayFromJSON(float64(), "[NaN]");
for (auto op : {"multiply", "multiply_checked"}) {
EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid, ::testing::HasSubstr("NaN"),
CallFunction(op, {nan, one}));
EXPECT_RAISES_WITH_MESSAGE_THAT(
Invalid, ::testing::HasSubstr("overflow"),
CallFunction(op, {big, ArrayFromJSON(float64(), "[2]")}));
}
for (auto op : {"divide", "divide_checked"}) {
EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid, ::testing::HasSubstr("NaN"),
CallFunction(op, {one, nan}));
EXPECT_RAISES_WITH_MESSAGE_THAT(
Invalid, ::testing::HasSubstr("overflow"),
CallFunction(op, {big, ArrayFromJSON(float64(), "[-0.25]")}));
EXPECT_RAISES_WITH_MESSAGE_THAT(
Invalid, ::testing::HasSubstr("divide by zero"),
CallFunction(op, {one, ArrayFromJSON(float64(), "[0]")}));
}
// float32 and halffloat are cast to float64
auto s = duration(TimeUnit::SECOND);
for (auto ty : {float16(), float32()}) {
for (auto op : {"multiply", "multiply_checked", "divide", "divide_checked"}) {
CheckDispatchBest(op, {s, ty}, {s, float64()});
}
CheckDispatchBest("multiply", {ty, s}, {float64(), s});
CheckScalarBinaryCommutative("multiply", ArrayFromJSON(s, "[5, -3]"),
ArrayFromJSON(ty, "[1.5, 0.5]"),
ArrayFromJSON(s, "[7, -1]"));
}
}

TEST_F(ScalarTemporalTest, TestTemporalDifferenceWeeks) {
auto raw_days = ArrayFromJSON(timestamp(TimeUnit::SECOND), R"([
"2021-08-09", "2021-08-10", "2021-08-11", "2021-08-12", "2021-08-13", "2021-08-14", "2021-08-15",
Expand Down
6 changes: 6 additions & 0 deletions docs/source/cpp/compute.rst
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,12 @@ appropriately. Mixed decimal and floating-point arguments will cast all
arguments to floating-point, while mixed decimal and integer arguments will
cast all arguments to decimals.
Mixed time resolution temporal inputs will be cast to finest input resolution.
A duration multiplied or divided by a floating-point number is computed in
float64 and then truncated toward zero, like numpy. Durations beyond 2^53 lose
precision in the conversion to float64, and the truncation can make round trips
lossy: ``multiply(divide(d, u), u)`` gives 0s for ``d = 1s`` and ``u = 49s``.
NaN, overflow and division by zero are errors in all variants, whereas the
unchecked integer kernels wrap around on overflow and numpy returns NaT.

+-------------------+--------+-------------------------+-------------------------------+-------+
| Function name | Arity | Input types | Output type | Notes |
Expand Down
17 changes: 17 additions & 0 deletions python/pyarrow/tests/test_compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -1941,6 +1941,23 @@ def test_arithmetic_multiply():
assert result.equals(expected)


def test_arithmetic_multiply_divide_duration_by_float():
# Example from GH-48003. Results are truncated toward zero, like numpy.
x = pa.array([0, 1, 2, 3, 4, 5], type=pa.duration("s"))
half = pa.array([0, 0, 1, 1, 2, 2], type=pa.duration("s"))
assert pc.multiply(x, 0.5).equals(half)
assert pc.multiply(0.5, x).equals(half)
assert pc.multiply(x, pa.scalar(0.5, pa.float32())).equals(half)
assert pc.divide(x, 2.0).equals(half)
assert pc.multiply(x, 1.5).equals(
pa.array([0, 1, 3, 4, 6, 7], type=pa.duration("s")))

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.

Could you also add the round trip from Randolf's second example in the issue? That is the actual use case:

deltas = pa.array([1, 2, 3], type=pa.duration("s"))
unit = pa.scalar(1, type=pa.duration("s"))
assert pc.multiply(pc.divide(deltas, unit), unit).equals(deltas)

And one case with the float on the left, e.g. pc.multiply(0.5, x).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Added Randolf's round trip and pc.multiply(0.5, x), plus a float32 case.


# Round trip through float64 from GH-48003
deltas = pa.array([1, 2, 3], type=pa.duration("s"))
unit = pa.scalar(1, type=pa.duration("s"))
assert pc.multiply(pc.divide(deltas, unit), unit).equals(deltas)


def test_arithmetic_remainder_modulo():
left = pa.array([7, -7, 7, -7, None])
right = pa.array([3, 3, -3, -3, 3])
Expand Down