Skip to content

Commit

Permalink
Add convergenceexception information (JuliaLang#484)
Browse files Browse the repository at this point in the history
In order to add informative hints to ConvergenceExceptions, I have added a
`info` field to `ConvergenceException` structs. If the `info` field is not
empty, it will also be printed with the error message for
`ConvergenceExceptions`. This is useful to inform the user of why he or she may
be experiencing problems with convergence, and to suggest ways to avoid these
errors. For an example of this, see JuliaStats/GLM.jl#303.
  • Loading branch information
galenlynch authored and nalimilan committed Apr 14, 2019
1 parent 81a07a1 commit 413d51a
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/statmodels.jl
Original file line number Diff line number Diff line change
Expand Up @@ -467,21 +467,26 @@ struct ConvergenceException{T<:Real} <: Exception
iters::Int
lastchange::T
tol::T
function ConvergenceException{T}(iters, lastchange::T, tol::T) where T<:Real
msg::String
function ConvergenceException{T}(iters, lastchange::T, tol::T, msg::String) where T<:Real
if tol > lastchange
throw(ArgumentError("Change must be greater than tol."))
else
new(iters, lastchange, tol)
new(iters, lastchange, tol, msg)
end
end
end

ConvergenceException(iters, lastchange::T=NaN, tol::T=NaN) where {T<:Real} =
ConvergenceException{T}(iters, lastchange, tol)
ConvergenceException(iters, lastchange::T=NaN, tol::T=NaN,
msg::AbstractString="") where {T<:Real} =
ConvergenceException{T}(iters, lastchange, tol, String(msg))

function Base.showerror(io::IO, ce::ConvergenceException)
print(io, "failure to converge after $(ce.iters) iterations.")
if !isnan(ce.lastchange)
print(io, " Last change ($(ce.lastchange)) was greater than tolerance ($(ce.tol)).")
end
if !isempty(ce.msg)
print(io, ' ', ce.msg)
end
end
3 changes: 3 additions & 0 deletions test/statmodels.jl
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,8 @@ m = rand(3,4)
@test sprint(showerror, ConvergenceException(10, 0.2, 0.1)) ==
"failure to converge after 10 iterations. Last change (0.2) was greater than tolerance (0.1)."

@test sprint(showerror, ConvergenceException(10, 0.2, 0.1, "Try changing maxIter.")) ==
"failure to converge after 10 iterations. Last change (0.2) was greater than tolerance (0.1). Try changing maxIter."

err = @test_throws ArgumentError ConvergenceException(10,.1,.2)
@test err.value.msg == "Change must be greater than tol."

0 comments on commit 413d51a

Please sign in to comment.