Skip to content

Commit d7edbad

Browse files
Add constraint derivative tests
1 parent 50b44fa commit d7edbad

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed

src/function/mtk.jl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
struct AutoModelingToolkit <: AbstractADType end
22

33
function instantiate_function(f, x, ::AutoModelingToolkit, p, num_cons=0)
4-
4+
p = isnothing(p) ? SciMLBase.NullParameters() : p
55
sys = ModelingToolkit.modelingtoolkitize(OptimizationProblem(f, x, p))
6-
println(sys)
6+
77
if f.grad === nothing
88
grad_oop, grad_iip = ModelingToolkit.generate_gradient(sys, expression=Val{false})
99
grad(J, u) = (grad_iip(J, u, p); J)

test/ADtests.jl

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,36 @@ g!(G1, x0)
2626
h!(H1, x0)
2727

2828
cons = (x, p) -> [x[1]^2 + x[2]^2]
29-
optf = OptimizationFunction(rosenbrock, GalacticOptim.AutoModelingToolkit(), cons = cons)
30-
optprob = GalacticOptim.instantiate_function(optf, x0, GalacticOptim.AutoModelingToolkit(), nothing)
29+
optf = OptimizationFunction(rosenbrock, GalacticOptim.AutoModelingToolkit(), cons=cons)
30+
optprob = GalacticOptim.instantiate_function(optf, x0, GalacticOptim.AutoModelingToolkit(), nothing, 1)
3131
optprob.grad(G2, x0)
3232
@test G1 == G2
3333
optprob.hess(H2, x0)
3434
@test H1 == H2
35+
@test optprob.cons(x0) == [0.0]
36+
J = Array{Float64}(undef, 2)
37+
optprob.cons_j(J, [5.0, 3.0])
38+
@test J == [10.0, 6.0]
39+
H3 = [Array{Float64}(undef, 2, 2)]
40+
optprob.cons_h(H3, x0)
41+
@test H3 == [[2.0 0.0; 0.0 2.0]]
42+
43+
function con2_c(x, p)
44+
[x[1]^2 + x[2]^2, x[2] * sin(x[1]) - x[1]]
45+
end
46+
optf = OptimizationFunction(rosenbrock, GalacticOptim.AutoModelingToolkit(), cons=con2_c)
47+
optprob = GalacticOptim.instantiate_function(optf, x0, GalacticOptim.AutoModelingToolkit(), nothing, 2)
48+
optprob.grad(G2, x0)
49+
@test G1 == G2
50+
optprob.hess(H2, x0)
51+
@test H1 == H2
52+
@test optprob.cons(x0) == [0.0, 0.0]
53+
J = Array{Float64}(undef, 2, 2)
54+
optprob.cons_j(J, [5.0, 3.0])
55+
@test all(isapprox(J, [10.0 6.0; -0.149013 -0.958924]; rtol=1e-3))
56+
H3 = [Array{Float64}(undef, 2, 2), Array{Float64}(undef, 2, 2)]
57+
optprob.cons_h(H3, x0)
58+
@test H3 == [[2.0 0.0; 0.0 2.0], [-0.0 1.0; 1.0 0.0]]
3559

3660
optf = OptimizationFunction(rosenbrock, GalacticOptim.AutoForwardDiff())
3761
optprob = GalacticOptim.instantiate_function(optf, x0, GalacticOptim.AutoForwardDiff(), nothing)

0 commit comments

Comments
 (0)