|
| 1 | +using Test |
| 2 | +using AlgorithmsInterface |
| 3 | + |
| 4 | +# Dummy types for a minimal iterative algorithm |
| 5 | +struct LogDummyProblem <: Problem end |
| 6 | +struct LogDummyAlgorithm <: Algorithm |
| 7 | + stopping_criterion |
| 8 | +end |
| 9 | +mutable struct LogDummyState{S <: StoppingCriterionState} <: State |
| 10 | + iterate::Float64 |
| 11 | + iteration::Int |
| 12 | + stopping_criterion_state::S |
| 13 | +end |
| 14 | + |
| 15 | +# State initialization for the dummy algorithm |
| 16 | +function AlgorithmsInterface.initialize_state(problem::LogDummyProblem, algorithm::LogDummyAlgorithm; kwargs...) |
| 17 | + sc_state = initialize_state(problem, algorithm, algorithm.stopping_criterion; kwargs...) |
| 18 | + return LogDummyState(0.0, 0, sc_state) |
| 19 | +end |
| 20 | +function AlgorithmsInterface.initialize_state!( |
| 21 | + problem::LogDummyProblem, |
| 22 | + algorithm::LogDummyAlgorithm, |
| 23 | + state::LogDummyState; |
| 24 | + kwargs... |
| 25 | + ) |
| 26 | + initialize_state!(problem, algorithm, algorithm.stopping_criterion, state.stopping_criterion_state; kwargs...) |
| 27 | + state.iterate = 0.0 |
| 28 | + state.iteration = 0 |
| 29 | + return state |
| 30 | +end |
| 31 | + |
| 32 | +# One trivial step per iteration (not relevant for the logging test) |
| 33 | +function AlgorithmsInterface.step!( |
| 34 | + ::LogDummyProblem, |
| 35 | + ::LogDummyAlgorithm, |
| 36 | + state::LogDummyState, |
| 37 | + ) |
| 38 | + state.iterate += 1.0 |
| 39 | + return state |
| 40 | +end |
| 41 | + |
| 42 | +@testset "CallbackAction logs iteration on each step" begin |
| 43 | + problem = LogDummyProblem() |
| 44 | + algorithm = LogDummyAlgorithm(StopAfterIteration(3)) |
| 45 | + |
| 46 | + # Action that logs the current iteration number at :PostStep |
| 47 | + iter_logger = CallbackAction() do problem, algorithm, state |
| 48 | + @info "Iter $(state.iteration)" |
| 49 | + end |
| 50 | + |
| 51 | + # Expect exactly three info logs for iterations 1, 2, 3 |
| 52 | + @test_logs (:info, "Iter 1") (:info, "Iter 2") (:info, "Iter 3") begin |
| 53 | + with_algorithmlogger(:PostStep => iter_logger) do |
| 54 | + solve(problem, algorithm) |
| 55 | + end |
| 56 | + end |
| 57 | +end |
0 commit comments