Skip to content

Fix objcons! for SimpleNLSModel #507

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

Merged
merged 11 commits into from
Aug 4, 2025
24 changes: 24 additions & 0 deletions src/nls/api.jl
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,30 @@ function obj(nls::AbstractNLSModel{T, S}, x::AbstractVector) where {T, S}
return obj(nls, x, Fx)
end

"""
f, c = objcons!(nls, x, c)
f, c = objcons!(nls, x, c, Fx; recompute::Bool=true)

In-place evaluation of constraints and objective for AbstractNLSModel.
If `Fx` is provided, it is used for the objective; otherwise, the residual is computed.
"""
function objcons!(nls::AbstractNLSModel, x::AbstractVector, c::AbstractVector)
cons_nln!(nls, x, c)
Fx = similar(x, nls.nls_meta.nequ)
residual!(nls, x, Fx)
f = 0.5 * sum(abs2, Fx)
return f, c
end

function objcons!(nls::AbstractNLSModel, x::AbstractVector, c::AbstractVector, Fx::AbstractVector; recompute::Bool=true)
cons_nln!(nls, x, c)
if recompute
residual!(nls, x, Fx)
end
f = 0.5 * sum(abs2, Fx)
return f, c
end

"""
g = grad!(nls, x, g)
g = grad!(nls, x, g, Fx; recompute::Bool=true)
Expand Down
10 changes: 10 additions & 0 deletions test/nls/simple-model.jl
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,16 @@ function NLPModels.objcons!(nls::SimpleNLSModel, x::AbstractVector, Fx::Abstract
return f, Fx
end

function NLPModels.objcons!(nls::SimpleNLSModel, x::AbstractVector, Fx::AbstractVector, res::AbstractVector; recompute::Bool=true)
@lencheck nls.meta.ncon Fx
NLPModels.cons_nln!(nls, x, Fx)
if recompute
res .= [1 - x[1]; 10 * (x[2] - x[1]^2)]
end
f = 0.5 * sum(abs2, res)
return f, Fx
end

function NLPModels.jprod(nls::SimpleNLSModel, x::AbstractVector, v::AbstractVector)
Jv = similar(v, nls.meta.ncon)
NLPModels.jprod!(nls, x, v, Jv)
Expand Down