Skip to content

Commit 64bcfab

Browse files
committed
Use pinv if inv fails
1 parent 521b831 commit 64bcfab

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/broyden.jl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ function perform_step!(cache::GeneralBroydenCache{iip, IJ, UR}) where {iip, IJ,
155155
T = eltype(cache.u)
156156

157157
if IJ === :true_jacobian && cache.stats.nsteps == 0
158-
cache.J⁻¹ = inv(jacobian!!(cache.J⁻¹, cache)) # This allocates
158+
cache.J⁻¹ = __safe_inv(jacobian!!(cache.J⁻¹, cache)) # This allocates
159159
end
160160

161161
@bb cache.du = cache.J⁻¹ × vec(cache.fu)
@@ -179,7 +179,7 @@ function perform_step!(cache::GeneralBroydenCache{iip, IJ, UR}) where {iip, IJ,
179179
return nothing
180180
end
181181
if IJ === :true_jacobian
182-
cache.J⁻¹ = inv(jacobian!!(cache.J⁻¹, cache))
182+
cache.J⁻¹ = __safe_inv(jacobian!!(cache.J⁻¹, cache))
183183
else
184184
cache.inv_alpha = __initial_inv_alpha(cache.inv_alpha, cache.alpha_initial,
185185
cache.u, cache.fu, cache.internalnorm)

src/utils.jl

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -526,3 +526,24 @@ end
526526
@inline __diag(x::AbstractMatrix) = diag(x)
527527
@inline __diag(x::AbstractVector) = x
528528
@inline __diag(x::Number) = x
529+
530+
# Safe Inverse: Try to use `inv` but if lu fails use `pinv`
531+
function __safe_inv(A::StridedMatrix{T}) where {T}
532+
LinearAlgebra.checksquare(A)
533+
if istriu(A)
534+
A_ = UpperTriangular(A)
535+
issingular = any(iszero, @view(A_[diagind(A_)]))
536+
!issingular && return triu!(parent(inv(A_)))
537+
elseif istril(A)
538+
A_ = LowerTriangular(A)
539+
issingular = any(iszero, @view(A_[diagind(A_)]))
540+
!issingular && return tril!(parent(inv(A_)))
541+
else
542+
F = lu(A; check = false)
543+
if issuccess(F)
544+
Ai = LinearAlgebra.inv!(F)
545+
return convert(typeof(parent(Ai)), Ai)
546+
end
547+
end
548+
return pinv(A)
549+
end

0 commit comments

Comments
 (0)