Skip to content

Commit

Permalink
Merge pull request #179 from WIAS-PDELib/jf/logging
Browse files Browse the repository at this point in the history
Jf/logging
  • Loading branch information
j-fu authored Feb 16, 2025
2 parents f8193cd + 1c86264 commit 0b4c68c
Show file tree
Hide file tree
Showing 10 changed files with 162 additions and 78 deletions.
3 changes: 2 additions & 1 deletion docs/src/internal.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,5 +127,6 @@ VoronoiFVM.integrate(::Type{<:Cylindrical2D}, coordl, coordr, hnormal, velofunc;
VoronoiFVM.doolittle_ludecomp!
VoronoiFVM.doolittle_lusolve!
VoronoiFVM.bernoulli_horner
VoronoiFVM._print_error
VoronoiFVM._warn
VoronoiFVM._info
```
7 changes: 7 additions & 0 deletions docs/src/misc.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ Modules = [VoronoiFVM]
Pages = ["vfvm_xgrid.jl"]
```


## Output (re)direction
```@docs
VoronoiFVM.log_output!
VoronoiFVM.print_output!
```

## Exception types
```@docs
VoronoiFVM.AssemblyError
Expand Down
4 changes: 3 additions & 1 deletion src/VoronoiFVM.jl
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,9 @@ VERSION >= v"1.11.0-DEV.469" && eval(Meta.parse("public System, AbstractSystem,
# export to be deprecated
export partitioning, Equationwise

include("vfvm_logging_exceptions.jl")
VERSION >= v"1.11.0-DEV.469" && eval(Meta.parse("public print_output!, log_output!"))

include("vfvm_formfactors.jl")
export meas, project
export unknown_indices
Expand All @@ -150,7 +153,6 @@ include("vfvm_linsolve_deprecated.jl")
include("vfvm_linsolve.jl")
export DirectSolver, GMRESIteration, CGIteration, BICGstabIteration, NoBlock, EquationBlock, PointBlock

include("vfvm_exceptions.jl")
include("vfvm_assembly.jl")
include("vfvm_solver.jl")
export solve!, solve
Expand Down
55 changes: 0 additions & 55 deletions src/vfvm_exceptions.jl

This file was deleted.

2 changes: 1 addition & 1 deletion src/vfvm_linsolve.jl
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ function _solve_linear!(u, state, nlhistory, control, method_linear, A, b)
nlhistory.nlin = sol.iters
catch err
if (control.handle_exceptions)
_print_error(err, stacktrace(catch_backtrace()))
_warn(err, stacktrace(catch_backtrace()))
throw(LinearSolverError())
else
rethrow(err)
Expand Down
123 changes: 123 additions & 0 deletions src/vfvm_logging_exceptions.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
"""
$(TYPEDEF)
Exception thrown if Newton's method convergence fails.
"""
struct ConvergenceError <: Exception end

"""
$(TYPEDEF)
Exception thrown if error occurred during assembly (e.g. domain error)
"""
struct AssemblyError <: Exception end

"""
$(TYPEDEF)
Exception thrown if error occurred during factorization.
"""
struct LinearSolverError <: Exception end

"""
$(TYPEDEF)
Exception thrown if embedding fails
"""
struct EmbeddingError <: Exception
msg::String
end

log_output::Bool = false

"""
print_output!()
Write all subsequent output of the VoronoiFVM package to screen via println().
This is the default.
If enabled in Pluto notebooks, the output is directed to the terminal widget
below a pluto cell. Warnings in addition are sent via logging in order to not
miss them.
This behavior can be changed via [`log_output!`](@ref).
For fine-tuning solver output, see the `verbose` flag in [`SolverControl`](@ref).
"""
print_output!() = global log_output = false


"""
log_output!()
Write all subsequent output of the VoronoiFVM package to screen via Julia's
logging methods (using @info or @warn).
This behavior can be changed via [`print_output!`](@ref).
For fine-tuning solver output, see the `verbose` flag in [`SolverControl`](@ref).
"""
log_output!() = global log_output = true


"""
_warn(str)
Warning output, either via @warn or via println.
In Pluto notebooks, @warn is always used.
"""
function _warn(str)
global log_output
if log_output
@warn str
else
if isdefined(Main, :PlutoRunner)
@warn str
end
println("WARNING: $(str)")
end
return
end

"""
_info(str)
Info output, either via @info or via println.
"""
function _info(str)
global log_output
if log_output
@info str
else
println(str)
end
return
end


"""
_warn(error, backtrace)
Print error when catching exceptions
"""
function _warn(err, backtrace)
io = IOBuffer()
println(io, err)
nlines = 0
for i in 1:min(nlines, length(backtrace))
line = @sprintf("%s", backtrace[i])
L = length(line)
if L < 80
println(io, line)
else
print(io, line[1:35])
print(io, " ... ")
println(io, line[(L - 35):L])
end
end
# if length(backtrace) > nlines
# println(io, "...")
# end
return _warn(String(take!(io)))
end
2 changes: 1 addition & 1 deletion src/vfvm_physics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ function _showstruct(io::IO, this::AbstractData)
myround(s::Symbol; kwargs...) = s
myround(i::Int; kwargs...) = i
myround(b::Bool; kwargs...) = b
println(typeof(this))
println(io, typeof(this))
for name in fieldnames(typeof(this))
println(io, "$(lpad(name, 20)) = $(myround.(getfield(this, name), sigdigits = 5))")
end
Expand Down
38 changes: 21 additions & 17 deletions src/vfvm_solver.jl
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ function solve_step!(
damp = 1.0
if !state.system.is_linear
if doprint(control, 'n')
println("\n [n]ewton: #it(lin) |update| cont3tion |round| #rd")
_info(" [n]ewton: #it(lin) |update| cont3tion |round| #rd")
end
damp = control.damp_initial
rnorm = control.rnorm(solution)
Expand Down Expand Up @@ -80,7 +80,7 @@ function solve_step!(
neval += nev
catch err
if (control.handle_exceptions)
_print_error(err, stacktrace(catch_backtrace()))
_warn(err, stacktrace(catch_backtrace()))
throw(AssemblyError())
else
rethrow(err)
Expand Down Expand Up @@ -132,16 +132,18 @@ function solve_step!(
itstring = @sprintf("it=% 3d", niter)
end
if control.max_round > 0
@printf(
"%s %.3e %.3e %.3e % 2d\n",
out = @sprintf(
"%s %.3e %.3e %.3e % 2d",
itstring,
norm,
norm / oldnorm,
dnorm,
nround
)
_info(out)
else
@printf("%s %.3e %.3e\n", itstring, norm, norm / oldnorm)
out = @sprintf("%s %.3e %.3e", itstring, norm, norm / oldnorm)
_info(out)
end
end
if niter > 1 && norm / oldnorm > 1.0 / control.tol_mono
Expand Down Expand Up @@ -174,16 +176,16 @@ function solve_step!(

if neval > 0
if ncalloc ÷ neval + nballoc ÷ neval > 0 && doprint(control, 'a') && !is_precompiling()
@warn "[a]llocations in assembly loop: cells: $(ncalloc ÷ neval), bfaces: $(nballoc ÷ neval)"
_warn("[a]llocations in assembly loop: cells: $(ncalloc ÷ neval), bfaces: $(nballoc ÷ neval)")
end
end

if doprint(control, 'n') && !state.system.is_linear
println(" [n]ewton: $(round(t, sigdigits = 3)) seconds asm: $(round(100 * tasm / t, sigdigits = 3))%, linsolve: $(round(100 * tlinsolve / t, sigdigits = 3))%")
_info(" [n]ewton: $(round(t, sigdigits = 3)) seconds asm: $(round(100 * tasm / t, sigdigits = 3))%, linsolve: $(round(100 * tlinsolve / t, sigdigits = 3))%")
end

if doprint(control, 'l') && state.system.is_linear
println(" [l]inear($(nameof(typeof(method_linear)))): $(round(t, sigdigits = 3)) seconds")
_info(" [l]inear($(nameof(typeof(method_linear)))): $(round(t, sigdigits = 3)) seconds")
end

solution.history = nlhistory
Expand Down Expand Up @@ -303,7 +305,7 @@ function solve_transient!(


if doprint(control, 'e')
println("[e]volution: start in $(extrema(lambdas))")
_info("[e]volution: start in $(extrema(lambdas))")
end

λ0 = 0
Expand Down Expand Up @@ -353,7 +355,7 @@ function solve_transient!(
catch err
err = "Problem at $(λstr)=$(λ |> rd), Δ$(λstr)=$(Δλ |> rd):\n$(err)"
if (control.handle_exceptions)
_print_error(err, stacktrace(catch_backtrace()))
_warn(err, stacktrace(catch_backtrace()))
else
rethrow(err)
end
Expand All @@ -374,21 +376,21 @@ function solve_transient!(
Returning prematurely before $(λstr)[end]=$(lambdas[end] |> rd)
"""
if control.handle_exceptions
@warn err
_warn(err)
else
throw(ErrorException(err))
end
break # give up lowering stepsize, break out if "while !solved" loop
elseif !errored
if doprint(control, 'e')
println("[e]volution: forced first timestep: Δu/Δu_opt=$(Δu / Δu_opt |> rd)")
_info("[e]volution: forced first timestep: Δu/Δu_opt=$(Δu / Δu_opt |> rd)")
end
forced = true
solved = true
else
err = "Convergence problem in first timestep"
if control.handle_exceptions
@warn err
_warn(err)
else
throw(ErrorException(err))
end
Expand All @@ -399,7 +401,8 @@ function solve_transient!(
# reduce time step
Δλ = max(Δλ_min, Δλ * Δλ_decrease)
if doprint(control, 'e')
@printf("[e]volution: Δu/Δu_opt=%.3e => retry: Δ%s=%.3e\n", Δu / Δu_opt, λstr, Δλ)
out = @sprintf("[e]volution: Δu/Δu_opt=%.3e => retry: Δ%s=%.3e\n", Δu / Δu_opt, λstr, Δλ)
_info(out)
end
end
end
Expand All @@ -409,7 +412,7 @@ function solve_transient!(
if solved
istep = istep + 1
if doprint(control, 'e')
@printf(
out = @sprintf(
"[e]volution: step=%d %s=%.3e Δ%s=%.3e Δu=%.3e\n",
istep,
λstr,
Expand All @@ -418,6 +421,7 @@ function solve_transient!(
Δλ,
Δu
)
_info(out)
end
if control.log
push!(allhistory, solution.history)
Expand Down Expand Up @@ -472,15 +476,15 @@ function solve_transient!(

if solved
if ! lambdas[i + 1]) # check end of interval has been reached in inner loop
@warn "λ=$(λ), lambdas[i+1]=$(lambdas[i + 1])"
_warn("λ=$(λ), lambdas[i+1]=$(lambdas[i + 1])")
end
else
break # emergency exit
end
end # for i = 1:(length(lambdas)-1), end outer loop

if doprint(control, 'e')
println("[e]volution: $(round(t0 + t1, sigdigits = 3)) seconds")
_info("[e]volution: $(round(t0 + t1, sigdigits = 3)) seconds")
end

tsol.history = allhistory
Expand Down
2 changes: 2 additions & 0 deletions src/vfvm_solvercontrol.jl
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ Base.@kwdef mutable struct SolverControl
- false: "da"
Switch off all output including deprecation warnings via `verbose=""`.
In the output, corresponding messages are marked e.g. via '[n]', `[a]` etc. (besides of '[l]')
For switching between printing output and logging output, see [`log_output!`](@ref) and [`print_output!`](@ref) .
"""
verbose::Union{Bool, String} = false

Expand Down
Loading

0 comments on commit 0b4c68c

Please sign in to comment.