diff --git a/ext/IpoptMathOptInterfaceExt/legacy.jl b/ext/IpoptMathOptInterfaceExt/legacy.jl index 4312ad6..b507f23 100644 --- a/ext/IpoptMathOptInterfaceExt/legacy.jl +++ b/ext/IpoptMathOptInterfaceExt/legacy.jl @@ -123,13 +123,26 @@ function MOI.get(model::Optimizer, ::MOI.NLPBlock) return MOI.NLPBlockData(model.evaluator) end -function MOI.set(model::Optimizer, ::MOI.NLPBlock, nlp_data::MOI.NLPBlockData) +function MOI.set( + model::Optimizer, + attr::MOI.NLPBlock, + nlp_data::MOI.NLPBlockData, +) P = MOI.Parameter{Float64} if model.number_of_nonlinear_constraints > 0 || model.has_nonlinear_objective || MOI.get(model.model, MOI.NumberOfConstraints{MOI.VariableIndex,P}()) > 0 error("Cannot mix the new and legacy nonlinear APIs") end + if model.nlp_data.has_objective && !nlp_data.has_objective + throw( + MOI.SetAttributeNotAllowed( + attr, + "Cannot replace a legacy NLP block that has an objective " * + "with one that has no objective. Rebuild the model instead.", + ), + ) + end model.nlp_data = nlp_data model.uses_nlp_block = !(nlp_data.evaluator isa _EmptyNLPEvaluator) if model.uses_nlp_block diff --git a/test/MOI_wrapper.jl b/test/MOI_wrapper.jl index b394352..59cdc3b 100644 --- a/test/MOI_wrapper.jl +++ b/test/MOI_wrapper.jl @@ -867,6 +867,15 @@ function test_NLPBlock_objective_only_with_quadratic_constraint() atol = 1e-6, ) end + attr = MOI.NLPBlock() + constraints_only = MOI.NLPBlockData([], data.evaluator, false) + @test_throws MOI.SetAttributeNotAllowed{typeof(attr)} MOI.set( + model, + attr, + constraints_only, + ) + @test MOI.get(model, attr) === data + MOI.set(model, attr, data) end return end