|
| 1 | +@testitem "Structured Jacobians" tags=[:misc] begin |
| 2 | + using NonlinearSolve, SparseConnectivityTracer, BandedMatrices, LinearAlgebra, |
| 3 | + SparseArrays |
| 4 | + |
| 5 | + N = 16 |
| 6 | + p = rand(N) |
| 7 | + u0 = rand(N) |
| 8 | + |
| 9 | + function f!(du, u, p) |
| 10 | + for i in 2:(length(u) - 1) |
| 11 | + du[i] = u[i - 1] - 2u[i] + u[i + 1] + p[i] |
| 12 | + end |
| 13 | + du[1] = -2u[1] + u[2] + p[1] |
| 14 | + du[end] = u[end - 1] - 2u[end] + p[end] |
| 15 | + return nothing |
| 16 | + end |
| 17 | + |
| 18 | + function f(u, p) |
| 19 | + du = similar(u, promote_type(eltype(u), eltype(p))) |
| 20 | + f!(du, u, p) |
| 21 | + return du |
| 22 | + end |
| 23 | + |
| 24 | + for nlf in (f, f!) |
| 25 | + @testset "Dense AD" begin |
| 26 | + nlprob = NonlinearProblem(NonlinearFunction(nlf), u0, p) |
| 27 | + |
| 28 | + cache = init(nlprob, NewtonRaphson(); abstol = 1e-9) |
| 29 | + @test cache.jac_cache.J isa Matrix |
| 30 | + sol = solve!(cache) |
| 31 | + @test SciMLBase.successful_retcode(sol) |
| 32 | + end |
| 33 | + |
| 34 | + @testset "Unstructured Sparse AD" begin |
| 35 | + nlprob_autosparse = NonlinearProblem( |
| 36 | + NonlinearFunction(nlf; sparsity = TracerSparsityDetector()), |
| 37 | + u0, p) |
| 38 | + |
| 39 | + cache = init(nlprob_autosparse, NewtonRaphson(); abstol = 1e-9) |
| 40 | + @test cache.jac_cache.J isa SparseMatrixCSC |
| 41 | + sol = solve!(cache) |
| 42 | + @test SciMLBase.successful_retcode(sol) |
| 43 | + end |
| 44 | + |
| 45 | + @testset "Structured Sparse AD: Banded Jacobian" begin |
| 46 | + jac_prototype = BandedMatrix(-1 => ones(N - 1), 0 => ones(N), 1 => ones(N - 1)) |
| 47 | + nlprob_sparse_structured = NonlinearProblem( |
| 48 | + NonlinearFunction(nlf; jac_prototype), u0, p) |
| 49 | + |
| 50 | + cache = init(nlprob_sparse_structured, NewtonRaphson(); abstol = 1e-9) |
| 51 | + @test cache.jac_cache.J isa BandedMatrix |
| 52 | + sol = solve!(cache) |
| 53 | + @test SciMLBase.successful_retcode(sol) |
| 54 | + end |
| 55 | + |
| 56 | + @testset "Structured Sparse AD: Tridiagonal Jacobian" begin |
| 57 | + jac_prototype = Tridiagonal(ones(N - 1), ones(N), ones(N - 1)) |
| 58 | + nlprob_sparse_structured = NonlinearProblem( |
| 59 | + NonlinearFunction(nlf; jac_prototype), u0, p) |
| 60 | + |
| 61 | + cache = init(nlprob_sparse_structured, NewtonRaphson(); abstol = 1e-9) |
| 62 | + @test cache.jac_cache.J isa Tridiagonal |
| 63 | + sol = solve!(cache) |
| 64 | + @test SciMLBase.successful_retcode(sol) |
| 65 | + end |
| 66 | + end |
| 67 | +end |
0 commit comments