Skip to content

Commit 413d51a

Browse files
galenlynchnalimilan
authored andcommitted
Add convergenceexception information (#484)
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.
1 parent 81a07a1 commit 413d51a

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

src/statmodels.jl

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -467,21 +467,26 @@ struct ConvergenceException{T<:Real} <: Exception
467467
iters::Int
468468
lastchange::T
469469
tol::T
470-
function ConvergenceException{T}(iters, lastchange::T, tol::T) where T<:Real
470+
msg::String
471+
function ConvergenceException{T}(iters, lastchange::T, tol::T, msg::String) where T<:Real
471472
if tol > lastchange
472473
throw(ArgumentError("Change must be greater than tol."))
473474
else
474-
new(iters, lastchange, tol)
475+
new(iters, lastchange, tol, msg)
475476
end
476477
end
477478
end
478479

479-
ConvergenceException(iters, lastchange::T=NaN, tol::T=NaN) where {T<:Real} =
480-
ConvergenceException{T}(iters, lastchange, tol)
480+
ConvergenceException(iters, lastchange::T=NaN, tol::T=NaN,
481+
msg::AbstractString="") where {T<:Real} =
482+
ConvergenceException{T}(iters, lastchange, tol, String(msg))
481483

482484
function Base.showerror(io::IO, ce::ConvergenceException)
483485
print(io, "failure to converge after $(ce.iters) iterations.")
484486
if !isnan(ce.lastchange)
485487
print(io, " Last change ($(ce.lastchange)) was greater than tolerance ($(ce.tol)).")
486488
end
489+
if !isempty(ce.msg)
490+
print(io, ' ', ce.msg)
491+
end
487492
end

test/statmodels.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,5 +40,8 @@ m = rand(3,4)
4040
@test sprint(showerror, ConvergenceException(10, 0.2, 0.1)) ==
4141
"failure to converge after 10 iterations. Last change (0.2) was greater than tolerance (0.1)."
4242

43+
@test sprint(showerror, ConvergenceException(10, 0.2, 0.1, "Try changing maxIter.")) ==
44+
"failure to converge after 10 iterations. Last change (0.2) was greater than tolerance (0.1). Try changing maxIter."
45+
4346
err = @test_throws ArgumentError ConvergenceException(10,.1,.2)
4447
@test err.value.msg == "Change must be greater than tol."

0 commit comments

Comments
 (0)