Skip to content

Commit

Permalink
Implement .P property for LU factorizations
Browse files Browse the repository at this point in the history
This matches the Base API.
  • Loading branch information
c42f committed Nov 28, 2019
1 parent d83e43f commit 0fd60a5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/lu.jl
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,24 @@ Base.iterate(S::LU, ::Val{:U}) = (S.U, Val(:p))
Base.iterate(S::LU, ::Val{:p}) = (S.p, Val(:done))
Base.iterate(S::LU, ::Val{:done}) = nothing

@inline function Base.getproperty(F::LU, s::Symbol)
if s === :P
U = getfield(F, :U)
p = getfield(F, :p)
one(similar_type(p, Size(U)))[:,invperm(p)]
else
getfield(F, s)
end
end

function Base.show(io::IO, mime::MIME{Symbol("text/plain")}, F::LU)
println(io, LU) # Don't show full type - this will be in the factors
println(io, "L factor:")
show(io, mime, F.L)
println(io, "\nU factor:")
show(io, mime, F.U)
end

# LU decomposition
function lu(A::StaticMatrix, pivot::Union{Val{false},Val{true}}=Val(true))
L, U, p = _lu(A, pivot)
Expand Down Expand Up @@ -136,9 +154,6 @@ end
:(SVector{$(M-1),Int}($(tuple(2:M...))))
end

# Base.lufact() interface is fairly inherently type unstable. Punt on
# implementing that, for now...

\(F::LU, v::AbstractVector) = F.U \ (F.L \ v[F.p])
\(F::LU, B::AbstractMatrix) = F.U \ (F.L \ B[F.p,:])

Expand Down
9 changes: 9 additions & 0 deletions test/lu.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
using StaticArrays, Test, LinearAlgebra

@testset "LU utils" begin
F = lu(SA[1 2; 3 4])

@test @inferred((F->F.p)(F)) === SA[2, 1]
@test @inferred((F->F.P)(F)) === SA[0 1; 1 0]

@test occursin(r"^StaticArrays.LU.*L factor.*U factor"s, sprint(show, MIME("text/plain"), F))
end

@testset "LU decomposition ($m×$n, pivot=$pivot)" for pivot in (true, false), m in [0:4..., 15], n in [0:4..., 15]
a = SMatrix{m,n,Int}(1:(m*n))
l, u, p = @inferred(lu(a, Val{pivot}()))
Expand Down

0 comments on commit 0fd60a5

Please sign in to comment.