Skip to content

Commit

Permalink
Mutable sum of array to array (#278)
Browse files Browse the repository at this point in the history
* Mutable sum of array to array

* Add tests

* Fix format
  • Loading branch information
blegat authored Apr 17, 2024
1 parent 6f0e699 commit 0c464c7
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/implementations/LinearAlgebra.jl
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,25 @@ function operate!(op::Union{typeof(+),typeof(-)}, A::Array, B::AbstractArray)
return broadcast!(op, A, B)
end

function operate_to!(
output::Array,
op::Union{typeof(+),typeof(-)},
A::AbstractArray,
B::AbstractArray,
)
if axes(output) != promote_shape(A, B)
throw(
DimensionMismatch(
"Cannot sum or substract matrices of axes `$(axes(A))` and" *
" `$(axes(B))` into a matrix of axes `$(axes(output))`," *
" expected axes `$(promote_shape(A, B))`.",
),
)
end
# We don't have `MA.broadcast_to!` as it would be exactly `Base.broadcast!`.
return Base.broadcast!(op, output, A, B)
end

# We call `scaling_to_number` as `UniformScaling` do not support broadcasting
function operate!(
op::AddSubMul,
Expand Down
22 changes: 22 additions & 0 deletions test/matmul.jl
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,13 @@ end
"Cannot sum or substract a matrix of axes `$(axes(B))` into matrix of axes `$(axes(A))`, expected axes `$(axes(B))`.",
)
@test_throws err MA.operate!(+, A, B)
output = zeros(2)
A = zeros(2, 1)
B = zeros(2, 1)
err = DimensionMismatch(
"Cannot sum or substract matrices of axes `$(axes(A))` and `$(axes(B))` into a matrix of axes `$(axes(output))`, expected axes `$(axes(B))`.",
)
@test_throws err MA.operate_to!(output, +, A, B)
end
@testset "unsupported_product" begin
unsupported_product()
Expand Down Expand Up @@ -435,3 +442,18 @@ end
@test B == [1 2]
@test D == B * A
end

function test_array_sum(::Type{T}) where {T}
x = zeros(T, 2)
y = copy(x)
z = copy(y)
alloc_test(() -> MA.operate!(+, y, z), 0)
alloc_test(() -> MA.add!!(y, z), 0)
alloc_test(() -> MA.operate_to!(x, +, y, z), 0)
alloc_test(() -> MA.add_to!!(x, y, z), 0)
return
end

@testset "Array sum" begin
test_array_sum(Int)
end

0 comments on commit 0c464c7

Please sign in to comment.