diff --git a/lib/SimpleNonlinearSolve/src/SimpleNonlinearSolve.jl b/lib/SimpleNonlinearSolve/src/SimpleNonlinearSolve.jl index 782de6468..bf8685ea9 100644 --- a/lib/SimpleNonlinearSolve/src/SimpleNonlinearSolve.jl +++ b/lib/SimpleNonlinearSolve/src/SimpleNonlinearSolve.jl @@ -124,6 +124,29 @@ function simplenonlinearsolve_solve_up( return SciMLBase.__solve(prob, alg, args...; kwargs...) end +# Iterator Interface Error Handling +# Simple algorithms do not support the iterator interface (init/step!) +function SciMLBase.init( + prob::Union{NonlinearProblem, NonlinearLeastSquaresProblem}, + alg::AbstractSimpleNonlinearSolveAlgorithm, args...; kwargs... +) + error(""" + The Simple algorithms from SimpleNonlinearSolve.jl do not support the iterator interface (init/step!). + + The iterator interface is only available for the full-featured algorithms from NonlinearSolve.jl. + + If you need the iterator interface, please use one of the following algorithms instead: + - NewtonRaphson() + - TrustRegion() + - LevenbergMarquardt() + - And other algorithms from NonlinearSolve.jl + + If you want to solve the problem directly, use `solve(prob, alg)` instead of `init(prob, alg)`. + + Algorithm attempted: $(typeof(alg)) + """) +end + @setup_workload begin for T in (Float64,) prob_scalar = NonlinearProblem{false}((u, p) -> u .* u .- p, T(0.1), T(2)) diff --git a/lib/SimpleNonlinearSolve/test/core/iterator_interface_tests.jl b/lib/SimpleNonlinearSolve/test/core/iterator_interface_tests.jl new file mode 100644 index 000000000..60aa743e7 --- /dev/null +++ b/lib/SimpleNonlinearSolve/test/core/iterator_interface_tests.jl @@ -0,0 +1,29 @@ +@testitem "Iterator Interface Error" tags=[:core] begin + using SimpleNonlinearSolve + + # Test that Simple algorithms properly error when used with the iterator interface + f(u, p) = u .* u .- 2.0 + u0 = 1.5 + prob = NonlinearProblem(f, u0) + + # Test with various Simple algorithms + for alg in [SimpleNewtonRaphson(), SimpleBroyden(), SimpleTrustRegion(), + SimpleDFSane(), SimpleKlement(), SimpleLimitedMemoryBroyden()] + # Test that an error is thrown + err = @test_throws ErrorException init(prob, alg) + + # Verify the error message contains helpful information + msg = sprint(showerror, err.value) + @test occursin("iterator interface", msg) + @test occursin("Simple algorithms", msg) + @test occursin("NewtonRaphson()", msg) + @test occursin("solve(prob, alg)", msg) + end + + # Verify that solve() still works correctly + for alg in [SimpleNewtonRaphson(), SimpleBroyden(), SimpleTrustRegion()] + sol = solve(prob, alg) + @test sol.retcode == ReturnCode.Success + @test abs(sol.u^2 - 2.0) < 1e-6 + end +end