Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions src/systems/codegen.jl
Original file line number Diff line number Diff line change
Expand Up @@ -667,10 +667,9 @@ function calculate_cost_hessian(sys::System; sparse = false, simplify = false)
obj = cost(sys)
dvs = unknowns(sys)
if sparse
exprs = Symbolics.sparsehessian(obj, dvs; simplify)::AbstractSparseArray
sparsity = similar(exprs, Float64)
return Symbolics.sparsehessian(obj, dvs; simplify)::AbstractSparseArray
else
exprs = Symbolics.hessian(obj, dvs; simplify)
return Symbolics.hessian(obj, dvs; simplify)
end
end

Expand Down
18 changes: 18 additions & 0 deletions test/optimizationsystem.jl
Original file line number Diff line number Diff line change
Expand Up @@ -390,3 +390,21 @@ end
obj = myeigvals_1(m)
@test_nowarn OptimizationSystem(obj, p_free, []; name = :osys)
end

@testset "Test sparse hessian" begin
rosenbrock(x, p = nothing) = (1 - x[1])^2 + 100 * (x[2] - x[1]^2)^2
@variables x[1:2]
@named sys = OptimizationSystem(rosenbrock(x))
sys = complete(sys)
prob = OptimizationProblem(sys, [x => [42.0, 12.37]]; hess = true, sparse = true)

symbolic_hess = Symbolics.hessian(cost(sys), x)
symbolic_hess_value = Symbolics.fast_substitute(symbolic_hess, Dict(x[1] => prob[x[1]], x[2] => prob[x[2]]))

oop_hess = prob.f.hess(prob.u0, prob.p)
@test oop_hess ≈ symbolic_hess_value

iip_hess = similar(prob.f.hess_prototype)
prob.f.hess(iip_hess, prob.u0, prob.p)
@test iip_hess ≈ symbolic_hess_value
end
Loading