Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[docs] add section of querying the Jacobian #3779

Merged
merged 2 commits into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
39 changes: 39 additions & 0 deletions docs/src/tutorials/nonlinear/querying_hessians.jl
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,42 @@ LinearAlgebra.eigvals(H_star)

# we see that they are all positive. Therefore, the Hessian is positive
# definite, and so the solution found by Ipopt is a local minimizer.

# ## Jacobians

# In addition to the Hessian, it is also possible to query other parts of the
# nonlinear model. For example, the Jacobian of the constraints can be queried
# using [`MOI.jacobian_structure`](@ref) and [`MOI.eval_constraint_jacobian`](@ref).

function compute_optimal_jacobian(model::Model)
rows = Any[]
nlp = MOI.Nonlinear.Model()
for (F, S) in list_of_constraint_types(model)
for ci in all_constraints(model, F, S)
if !(F <: VariableRef)
push!(rows, ci)
object = constraint_object(ci)
MOI.Nonlinear.add_constraint(nlp, object.func, object.set)
end
end
end
MOI.Nonlinear.set_objective(nlp, objective_function(model))
x = all_variables(model)
backend = MOI.Nonlinear.SparseReverseMode()
evaluator = MOI.Nonlinear.Evaluator(nlp, backend, index.(x))
## Initialize the Jacobian
MOI.initialize(evaluator, [:Jac])
## Query the Jacobian structure
sparsity = MOI.jacobian_structure(evaluator)
I, J, V = first.(sparsity), last.(sparsity), zeros(length(sparsity))
## Query the Jacobian values
MOI.eval_constraint_jacobian(evaluator, V, value.(x))
return SparseArrays.sparse(I, J, V, length(rows), length(x))
end

compute_optimal_jacobian(model)

# Compare that to the analytic solution:

y = value.(x)
[2y[1] 0; 2y[1]+2y[2] 2y[1]+2y[2]]
1 change: 1 addition & 0 deletions docs/styles/config/vocabularies/JuMP/accept.txt
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ functionize
geomean
hypergraph
infeasibilities
Jacobian(?s)
(lin|mixint|quad)prog
(log|root)det
(L|Q|MI|MIC)P(?s)
Expand Down
Loading