|
| 1 | +@testitem "Nonlinear Least Squares" tags=[:core] begin |
| 2 | + using LinearAlgebra |
| 3 | + |
| 4 | + true_function(x, θ) = @. θ[1] * exp(θ[2] * x) * cos(θ[3] * x + θ[4]) |
| 5 | + |
| 6 | + θ_true = [1.0, 0.1, 2.0, 0.5] |
| 7 | + x = [-1.0, -0.5, 0.0, 0.5, 1.0] |
| 8 | + y_target = true_function(x, θ_true) |
| 9 | + |
| 10 | + function loss_function(θ, p) |
| 11 | + ŷ = true_function(p, θ) |
| 12 | + return ŷ .- y_target |
| 13 | + end |
| 14 | + |
| 15 | + function loss_function!(resid, θ, p) |
| 16 | + ŷ = true_function(p, θ) |
| 17 | + @. resid = ŷ - y_target |
| 18 | + return |
| 19 | + end |
| 20 | + |
| 21 | + θ_init = θ_true .+ 0.1 |
| 22 | + prob_oop = NonlinearLeastSquaresProblem{false}(loss_function, θ_init, x) |
| 23 | + |
| 24 | + @testset "Solver: $(nameof(typeof(solver)))" for solver in [ |
| 25 | + SimpleNewtonRaphson(AutoForwardDiff()), SimpleGaussNewton(AutoForwardDiff()), |
| 26 | + SimpleNewtonRaphson(AutoFiniteDiff()), SimpleGaussNewton(AutoFiniteDiff())] |
| 27 | + sol = solve(prob_oop, solver) |
| 28 | + @test norm(sol.resid, Inf) < 1e-12 |
| 29 | + end |
| 30 | + |
| 31 | + prob_iip = NonlinearLeastSquaresProblem( |
| 32 | + NonlinearFunction{true}(loss_function!, resid_prototype = zeros(length(y_target))), |
| 33 | + θ_init, x) |
| 34 | + |
| 35 | + @testset "Solver: $(nameof(typeof(solver)))" for solver in [ |
| 36 | + SimpleNewtonRaphson(AutoForwardDiff()), SimpleGaussNewton(AutoForwardDiff()), |
| 37 | + SimpleNewtonRaphson(AutoFiniteDiff()), SimpleGaussNewton(AutoFiniteDiff())] |
| 38 | + sol = solve(prob_iip, solver) |
| 39 | + @test norm(sol.resid, Inf) < 1e-12 |
| 40 | + end |
| 41 | +end |
0 commit comments