From 3f78ad4131e603be8343de7122e366fb3e7c59b6 Mon Sep 17 00:00:00 2001 From: odow Date: Sun, 8 Oct 2023 21:02:16 +0200 Subject: [PATCH] [Nonlinear] add support for is_empty and empty\! --- src/Nonlinear/model.jl | 21 +++++++++++++++++++++ test/Nonlinear/Nonlinear.jl | 28 ++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/src/Nonlinear/model.jl b/src/Nonlinear/model.jl index cc7c466402..531d715053 100644 --- a/src/Nonlinear/model.jl +++ b/src/Nonlinear/model.jl @@ -4,6 +4,27 @@ # Use of this source code is governed by an MIT-style license that can be found # in the LICENSE.md file or at https://opensource.org/licenses/MIT. +function MOI.empty!(model::Model) + model.objective = nothing + empty!(model.expressions) + empty!(model.constraints) + empty!(model.parameters) + model.operators = OperatorRegistry() + model.last_constraint_index = 0 + return +end + +function MOI.is_empty(model::Model) + return model.objective === nothing && + isempty(model.expressions) && + isempty(model.constraints) && + isempty(model.parameters) && + isempty(model.operators.registered_univariate_operators) && + isempty(model.operators.registered_multivariate_operators) && + model.last_constraint_index === 0 + return +end + function Base.copy(::Model) return error("Copying nonlinear problems not yet implemented") end diff --git a/test/Nonlinear/Nonlinear.jl b/test/Nonlinear/Nonlinear.jl index fe986bc43f..a5f2720817 100644 --- a/test/Nonlinear/Nonlinear.jl +++ b/test/Nonlinear/Nonlinear.jl @@ -1103,6 +1103,34 @@ function test_parse_unsupported_operator() return end +function test_is_empty() + model = MOI.Nonlinear.Model() + @test MOI.is_empty(model) + x = MOI.VariableIndex(1) + Nonlinear.set_objective(model, :(log($x))) + @test !MOI.is_empty(model) + MOI.empty!(model) + @test MOI.is_empty(model) + Nonlinear.add_constraint(model, :(log($x)), MOI.GreaterThan(1.0)) + @test !MOI.is_empty(model) + MOI.empty!(model) + @test MOI.is_empty(model) + Nonlinear.add_expression(model, :(sin($x)^2)) + @test !MOI.is_empty(model) + MOI.empty!(model) + @test MOI.is_empty(model) + Nonlinear.add_parameter(model, 1.2) + @test !MOI.is_empty(model) + MOI.empty!(model) + @test MOI.is_empty(model) + f(x) = log(x + 1) + Nonlinear.register_operator(model, :f, 1, f) + @test !MOI.is_empty(model) + MOI.empty!(model) + @test MOI.is_empty(model) + return +end + end TestNonlinear.runtests()