Skip to content

[WIP] add initial version of OptimizationIpopt #915

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

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
21 changes: 21 additions & 0 deletions lib/OptimizationIpopt/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Sebastian Micluța-Câmpeanu <[email protected]> and contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
21 changes: 21 additions & 0 deletions lib/OptimizationIpopt/Project.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name = "OptimizationIpopt"
uuid = "43fad042-7963-4b32-ab19-e2a4f9a67124"
authors = ["Sebastian Micluța-Câmpeanu <[email protected]> and contributors"]
version = "0.1.0"

[deps]
Ipopt = "b6b21f68-93f8-5de0-b562-5493be1d77c9"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
Optimization = "7f7a1694-90dd-40f0-9382-eb1efda571ba"
SciMLBase = "0bca4576-84f4-4d90-8ffe-ffa030f20462"
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
SymbolicIndexingInterface = "2efcf032-c050-4f8e-a9bb-153293bab1f5"

[compat]
Ipopt = "1.10.3"
LinearAlgebra = "1.11.0"
Optimization = "4.3.0"
SciMLBase = "2.90.0"
SparseArrays = "1.11.0"
SymbolicIndexingInterface = "0.3.40"
julia = "1.10"
209 changes: 209 additions & 0 deletions lib/OptimizationIpopt/src/OptimizationIpopt.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
module OptimizationIpopt

using Optimization
using Ipopt
using LinearAlgebra
using SparseArrays
using SciMLBase
using SymbolicIndexingInterface

export IpoptOptimizer

const DenseOrSparse{T} = Union{Matrix{T}, SparseMatrixCSC{T}}

struct IpoptOptimizer end

function SciMLBase.supports_opt_cache_interface(alg::IpoptOptimizer)
true
end

function SciMLBase.requiresgradient(opt::IpoptOptimizer)
true
end
function SciMLBase.requireshessian(opt::IpoptOptimizer)
true
end
function SciMLBase.requiresconsjac(opt::IpoptOptimizer)
true
end
function SciMLBase.requiresconshess(opt::IpoptOptimizer)
true
end

function SciMLBase.allowsbounds(opt::IpoptOptimizer)
true
end
function SciMLBase.allowsconstraints(opt::IpoptOptimizer)
true
end

include("cache.jl")
include("callback.jl")

function __map_optimizer_args(cache,
opt::IpoptOptimizer;
maxiters::Union{Number, Nothing} = nothing,
maxtime::Union{Number, Nothing} = nothing,
abstol::Union{Number, Nothing} = nothing,
reltol::Union{Number, Nothing} = nothing,
hessian_approximation = "exact",
verbose = false,
progress = false,
callback = nothing,
kwargs...)
jacobian_sparsity = jacobian_structure(cache)
hessian_sparsity = hessian_lagrangian_structure(cache)

eval_f(x) = eval_objective(cache, x)
eval_grad_f(x, grad_f) = eval_objective_gradient(cache, grad_f, x)
eval_g(x, g) = eval_constraint(cache, g, x)
function eval_jac_g(x, rows, cols, values)
if values === nothing
for i in 1:length(jacobian_sparsity)
rows[i], cols[i] = jacobian_sparsity[i]
end
else
eval_constraint_jacobian(cache, values, x)
end
return
end
function eval_h(x, rows, cols, obj_factor, lambda, values)
if values === nothing
for i in 1:length(hessian_sparsity)
rows[i], cols[i] = hessian_sparsity[i]
end
else
eval_hessian_lagrangian(cache, values, x, obj_factor, lambda)
end
return
end

lb = isnothing(cache.lb) ? fill(-Inf, cache.n) : cache.lb
ub = isnothing(cache.ub) ? fill(Inf, cache.n) : cache.ub

prob = Ipopt.CreateIpoptProblem(
cache.n,
lb,
ub,
cache.num_cons,
cache.lcons,
cache.ucons,
length(jacobian_structure(cache)),
length(hessian_lagrangian_structure(cache)),
eval_f,
eval_g,
eval_grad_f,
eval_jac_g,
eval_h
)
progress_callback = IpoptProgressLogger(cache.progress, cache, prob)
intermediate = (args...) -> progress_callback(args...)
Ipopt.SetIntermediateCallback(prob, intermediate)

if !isnothing(maxiters)
Ipopt.AddIpoptIntOption(prob, "max_iter", maxiters)
end
if !isnothing(maxtime)
Ipopt.AddIpoptNumOption(prob, "max_cpu_time", maxtime)
end
if !isnothing(abstol)
Ipopt.AddIpoptNumOption(prob, "tol", abstol)
end
if verbose isa Bool
Ipopt.AddIpoptIntOption(prob, "print_level", verbose * 5)
else
Ipopt.AddIpoptIntOption(prob, "print_level", verbose)
end
Ipopt.AddIpoptStrOption(prob, "hessian_approximation", hessian_approximation)

return prob
end

function map_retcode(solvestat)
status = Ipopt.ApplicationReturnStatus(solvestat)
if status in [
Ipopt.Solve_Succeeded,
Ipopt.Solved_To_Acceptable_Level,
Ipopt.User_Requested_Stop,
Ipopt.Feasible_Point_Found
]
return ReturnCode.Success
elseif status in [
Ipopt.Infeasible_Problem_Detected,
Ipopt.Search_Direction_Becomes_Too_Small,
Ipopt.Diverging_Iterates
]
return ReturnCode.Infeasible
elseif status == Ipopt.Maximum_Iterations_Exceeded
return ReturnCode.MaxIters
elseif status in [Ipopt.Maximum_CpuTime_Exceeded
Ipopt.Maximum_WallTime_Exceeded]
return ReturnCode.MaxTime
else
return ReturnCode.Failure
end
end

function SciMLBase.__solve(cache::IpoptCache)
maxiters = Optimization._check_and_convert_maxiters(cache.solver_args.maxiters)
maxtime = Optimization._check_and_convert_maxtime(cache.solver_args.maxtime)

opt_setup = __map_optimizer_args(cache,
cache.opt;
abstol = cache.solver_args.abstol,
reltol = cache.solver_args.reltol,
maxiters = maxiters,
maxtime = maxtime,
cache.solver_args...)

opt_setup.x .= cache.reinit_cache.u0

start_time = time()
status = Ipopt.IpoptSolve(opt_setup)

opt_ret = map_retcode(status)

if cache.progress
# Set progressbar to 1 to finish it
Base.@logmsg(Base.LogLevel(-1), "", progress=1, _id=:OptimizationIpopt)
end

minimum = opt_setup.obj_val
minimizer = opt_setup.x

stats = Optimization.OptimizationStats(; time = time() - start_time,
iterations = cache.iterations, fevals = cache.f_calls, gevals = cache.f_grad_calls)

finalize(opt_setup)

return SciMLBase.build_solution(cache,
cache.opt,
minimizer,
minimum;
original = opt_setup,
retcode = opt_ret,
stats = stats)
end

function SciMLBase.__init(prob::OptimizationProblem,
opt::IpoptOptimizer;
maxiters::Union{Number, Nothing} = nothing,
maxtime::Union{Number, Nothing} = nothing,
abstol::Union{Number, Nothing} = nothing,
reltol::Union{Number, Nothing} = nothing,
mtkize = false,
kwargs...)
cache = IpoptCache(prob, opt;
maxiters,
maxtime,
abstol,
reltol,
mtkize,
kwargs...
)
cache.reinit_cache.u0 .= prob.u0

return cache
end

end # OptimizationIpopt
Loading
Loading