|
| 1 | +module SimpleNonlinearSolveTaylorDiffExt |
| 2 | +using SimpleNonlinearSolve |
| 3 | +using SimpleNonlinearSolve: ImmutableNonlinearProblem, ReturnCode, build_solution, check_termination, init_termination_cache |
| 4 | +using SimpleNonlinearSolve: __maybe_unaliased, _get_fx, __fixed_parameter_function |
| 5 | +using MaybeInplace: @bb |
| 6 | +using SciMLBase: isinplace |
| 7 | + |
| 8 | +import TaylorDiff |
| 9 | + |
| 10 | +@inline function __get_higher_order_derivatives(::SimpleHouseholder{N}, prob, f, x) where N |
| 11 | + vN = Val(N) |
| 12 | + l = map(one, x) |
| 13 | + |
| 14 | + if isinplace(prob) |
| 15 | + fx = f(x) |
| 16 | + invf = x -> inv.(f(x)) |
| 17 | + bundle = TaylorDiff.derivatives(invf, fx, x, l, vN) |
| 18 | + else |
| 19 | + t = TaylorDiff.make_seed(x, l, vN) |
| 20 | + ft = f(t) |
| 21 | + fx = map(TaylorDiff.primal, ft) |
| 22 | + bundle = inv.(ft) |
| 23 | + end |
| 24 | + num = TaylorDiff.extract_derivative(bundle, N - 1) |
| 25 | + den = TaylorDiff.extract_derivative(bundle, N) |
| 26 | + return num, den, fx |
| 27 | +end |
| 28 | + |
| 29 | +function SciMLBase.__solve(prob::ImmutableNonlinearProblem, alg::SimpleHouseholder{N}, |
| 30 | + args...; abstol = nothing, reltol = nothing, maxiters = 1000, |
| 31 | + termination_condition = nothing, alias_u0 = false, kwargs...) where N |
| 32 | + x = __maybe_unaliased(prob.u0, alias_u0) |
| 33 | + length(x) == 1 || |
| 34 | + throw(ArgumentError("SimpleHouseholder only supports scalar problems")) |
| 35 | + fx = _get_fx(prob, x) |
| 36 | + @bb xo = copy(x) |
| 37 | + f = __fixed_parameter_function(prob) |
| 38 | + |
| 39 | + abstol, reltol, tc_cache = init_termination_cache( |
| 40 | + prob, abstol, reltol, fx, x, termination_condition) |
| 41 | + |
| 42 | + for i in 1:maxiters |
| 43 | + num, den, fx = __get_higher_order_derivatives(alg, prob, f, x) |
| 44 | + |
| 45 | + if i == 1 |
| 46 | + iszero(fx) && build_solution(prob, alg, x, fx; retcode = ReturnCode.Success) |
| 47 | + else |
| 48 | + # Termination Checks |
| 49 | + tc_sol = check_termination(tc_cache, fx, x, xo, prob, alg) |
| 50 | + tc_sol !== nothing && return tc_sol |
| 51 | + end |
| 52 | + |
| 53 | + @bb copyto!(xo, x) |
| 54 | + @bb x .+= (N - 1) .* num ./ den |
| 55 | + end |
| 56 | + |
| 57 | + return build_solution(prob, alg, x, fx; retcode = ReturnCode.MaxIters) |
| 58 | +end |
| 59 | + |
| 60 | +end |
0 commit comments