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

make similar(A<:AbstractTriangular, opts...) consistently preserve A's underlying storage type #24162

Merged
merged 1 commit into from
Oct 19, 2017
Merged
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
10 changes: 6 additions & 4 deletions base/linalg/triangular.jl
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,12 @@ for t in (:LowerTriangular, :UnitLowerTriangular, :UpperTriangular,
convert(::Type{AbstractMatrix{T}}, A::$t) where {T} = convert($t{T}, A)
convert(::Type{Matrix}, A::$t{T}) where {T} = convert(Matrix{T}, A)

function similar(A::$t, ::Type{T}) where T
B = similar(A.data, T)
return $t(B)
end
# For A<:AbstractTriangular, similar(A[, neweltype]) should yield a matrix with the same
# triangular type and underlying storage type as A. The following method covers these cases.
similar(A::$t, ::Type{T}) where {T} = $t(similar(parent(A), T))
# On the other hand, similar(A, [neweltype,] shape...) should yield a matrix of the underlying
# storage type of A (not wrapped in a triangular type). The following method covers these cases.
similar(A::$t, ::Type{T}, dims::Dims{N}) where {T,N} = similar(parent(A), T, dims)

copy(A::$t) = $t(copy(A.data))

Expand Down
12 changes: 12 additions & 0 deletions test/linalg/triangular.jl
Original file line number Diff line number Diff line change
Expand Up @@ -516,3 +516,15 @@ using Main.TestHelpers.Furlong
let A = UpperTriangular([Furlong(1) Furlong(4); Furlong(0) Furlong(1)])
@test sqrt(A) == Furlong{1//2}.(UpperTriangular([1 2; 0 1]))
end

@testset "similar should preserve underlying storage type" begin
m, n = 4, 3
sparsemat = sprand(m, m, 0.5)
for TriType in (UpperTriangular, LowerTriangular, UnitUpperTriangular, UnitLowerTriangular)
trisparsemat = TriType(sparsemat)
@test isa(similar(trisparsemat), typeof(trisparsemat))
@test isa(similar(trisparsemat, Float32), TriType{Float32,<:SparseMatrixCSC{Float32}})
@test isa(similar(trisparsemat, (n, n)), typeof(sparsemat))
@test isa(similar(trisparsemat, Float32, (n, n)), SparseMatrixCSC{Float32})
end
end