Skip to content

Commit 418e167

Browse files
Sacha0ararslan
authored andcommitted
Fix broadcast! for structured matrix destinations. (#20886)
1 parent 805f096 commit 418e167

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

base/sparse/higherorderfns.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1009,6 +1009,7 @@ struct PromoteToSparse end
10091009
# broadcast containertype definitions for structured matrices
10101010
StructuredMatrix = Union{Diagonal,Bidiagonal,Tridiagonal,SymTridiagonal}
10111011
_containertype(::Type{<:StructuredMatrix}) = PromoteToSparse
1012+
broadcast_indices(::Type{PromoteToSparse}, A) = indices(A)
10121013

10131014
# combinations explicitly involving Tuples and PromoteToSparse collections
10141015
# divert to the generic AbstractArray broadcast code

test/sparse/higherorderfns.jl

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,33 @@ end
415415
end
416416
end
417417

418+
@testset "broadcast! where the destination is a structured matrix" begin
419+
# Where broadcast!'s destination is a structured matrix, broadcast! should fall back
420+
# to the generic AbstractArray broadcast! code (at least for now).
421+
N, p = 5, 0.4
422+
A = sprand(N, N, p)
423+
sA = A + transpose(A)
424+
D = Diagonal(rand(N))
425+
B = Bidiagonal(rand(N), rand(N - 1), true)
426+
T = Tridiagonal(rand(N - 1), rand(N), rand(N - 1))
427+
S = SymTridiagonal(rand(N), rand(N - 1))
428+
# why some of the tests below are broken:
429+
# Diagonal setindex! allows setting off-diagonal entries to zero. Subtypes of
430+
# AbstractTriangular allow analogs. But Bidiagonal, Tridiagonal, and SymTridiagonal
431+
# do not, which seems like a bug. setindex! behavior like that for Diagonal and
432+
# subtypes of AbstractTriangular is necessary for Bidiagonal, Tridiagonal, and
433+
# SymTridiagonal to be targets of the AbstractArray broadcast! methods, hence
434+
# the test failures below.
435+
@test broadcast!(sin, copy(D), D) == Diagonal(sin.(D))
436+
@test_broken broadcast!(sin, copy(B), B) == Bidiagonal(sin.(B), true)
437+
@test_broken broadcast!(sin, copy(T), T) == Tridiagonal(sin.(T))
438+
@test_broken broadcast!(sin, copy(S), S) == SymTridiagonal(sin.(S))
439+
@test broadcast!(*, copy(D), D, A) == Diagonal(broadcast(*, D, A))
440+
@test_broken broadcast!(*, copy(B), B, A) == Bidiagonal(broadcast(*, B, A), true)
441+
@test_broken broadcast!(*, copy(T), T, A) == Tridiagonal(broadcast(*, T, A))
442+
@test_broken broadcast!(*, copy(S), T, sA) == SymTridiagonal(broadcast(*, T, sA))
443+
end
444+
418445
@testset "map[!] over combinations of sparse and structured matrices" begin
419446
N, p = 10, 0.4
420447
A = sprand(N, N, p)

0 commit comments

Comments
 (0)