|
6 | 6 |
|
7 | 7 | include("testBundleAdjustmentModels.jl") |
8 | 8 | include("testBundleAdjustmentAllocations.jl") |
| 9 | + |
| 10 | +# https://github.com/JuliaSmoothOptimizers/NLPModelsTest.jl/blob/src/dercheck.jl#L43 |
| 11 | +function jacobian_residual_check( |
| 12 | + nlp::AbstractNLSModel; |
| 13 | + x::AbstractVector = nlp.meta.x0, |
| 14 | + atol::Float64 = 1.0e-6, |
| 15 | + rtol::Float64 = 1.0e-4, |
| 16 | +) |
| 17 | + |
| 18 | + # Fast exit if there are no constraints. |
| 19 | + J_errs = Dict{Tuple{Int, Int}, Float64}() |
| 20 | + nlp.nls_meta.nequ > 0 || return J_errs |
| 21 | + |
| 22 | + # Optimal-ish step for second-order centered finite differences. |
| 23 | + step = (eps(Float64) / 3)^(1 / 3) |
| 24 | + |
| 25 | + # Check constraints Jacobian. |
| 26 | + J = jac_residual(nlp, x) |
| 27 | + h = zeros(nlp.meta.nvar) |
| 28 | + cxph = zeros(nlp.nls_meta.nequ) |
| 29 | + cxmh = zeros(nlp.nls_meta.nequ) |
| 30 | + # Differentiate all constraints with respect to each variable in turn. |
| 31 | + for i = 1:(nlp.meta.nvar) |
| 32 | + h[i] = step |
| 33 | + residual!(nlp, x + h, cxph) |
| 34 | + residual!(nlp, x - h, cxmh) |
| 35 | + dcdxi = (cxph - cxmh) / 2 / step |
| 36 | + for j = 1:(nlp.nls_meta.nequ) |
| 37 | + err = abs(dcdxi[j] - J[j, i]) |
| 38 | + if err > atol + rtol * abs(dcdxi[j]) |
| 39 | + J_errs[(j, i)] = err |
| 40 | + end |
| 41 | + end |
| 42 | + h[i] = 0 |
| 43 | + end |
| 44 | + return J_errs |
| 45 | +end |
| 46 | + |
| 47 | +@testset "Test derivative Jacobian of residual" begin |
| 48 | + nls = BundleAdjustmentModel("problem-49-7776-pre") |
| 49 | + x = 10 * [-(-1.0)^i for i = 1:nls.meta.nvar] |
| 50 | + @test length(jacobian_residual_check(nls, x = x)) == 0 |
| 51 | +end |
0 commit comments