From a183f8cd21212b765b842477e8a365f7b4706b40 Mon Sep 17 00:00:00 2001 From: odow Date: Tue, 18 Feb 2025 10:37:37 +1300 Subject: [PATCH] Add row-wise constructors for VectorAffine and VectorQuadratic functions Co-authored-by: Mathieu Besancon --- src/Utilities/functions.jl | 12 ++++++++++++ test/Utilities/functions.jl | 38 +++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/src/Utilities/functions.jl b/src/Utilities/functions.jl index 2d558f92e4..df8194ec1e 100644 --- a/src/Utilities/functions.jl +++ b/src/Utilities/functions.jl @@ -2217,6 +2217,12 @@ function vectorize(funcs::AbstractVector{MOI.ScalarAffineFunction{T}}) where {T} return MOI.VectorAffineFunction(terms, constant) end +function MOI.VectorAffineFunction( + funcs::AbstractVector{MOI.ScalarAffineFunction{T}}, +) where {T} + return vectorize(funcs) +end + """ vectorize(funcs::AbstractVector{MOI.ScalarQuadraticFunction{T}}) where T @@ -2251,6 +2257,12 @@ function vectorize( return MOI.VectorQuadraticFunction(quadratic_terms, affine_terms, constant) end +function MOI.VectorQuadraticFunction( + funcs::AbstractVector{MOI.ScalarQuadraticFunction{T}}, +) where {T} + return vectorize(funcs) +end + function vectorize(x::AbstractVector{MOI.ScalarNonlinearFunction}) # Explicitly construct the output vector here because don't know that `x` # has a `convert` method to `Vector`. diff --git a/test/Utilities/functions.jl b/test/Utilities/functions.jl index 6438436103..3ff95fda95 100644 --- a/test/Utilities/functions.jl +++ b/test/Utilities/functions.jl @@ -2179,6 +2179,44 @@ function test_deprecated_eval_term() return end +function test_VectorAffineFunction_row_constructor() + x = MOI.VariableIndex(1) + f = MOI.VectorAffineFunction([1.0 * x + 2.0, 3.0 * x + 4.0]) + g = MOI.VectorAffineFunction( + MOI.VectorAffineTerm{Float64}[ + MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(1.0, x)), + MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(3.0, x)), + ], + [2.0, 4.0], + ) + @test f ≈ g + return +end + +function test_VectorQuadraticFunction_row_constructor() + x, y = MOI.VariableIndex.(1:2) + row1 = 1.0 * x * x + 1.0 * y * y + 2.0 * x + 3.0 * y + 4.2 + row2 = 3.0 * x * x + 3.0 * y * y + 1.0 * x + 3.0 * y + 1.2 + f = MOI.VectorQuadraticFunction([row1, row2]) + @test f ≈ MOI.Utilities.vectorize([row1, row2]) + @test f ≈ MOI.VectorQuadraticFunction( + [ + MOI.VectorQuadraticTerm(1, MOI.ScalarQuadraticTerm(2.0, x, x)), + MOI.VectorQuadraticTerm(1, MOI.ScalarQuadraticTerm(2.0, y, y)), + MOI.VectorQuadraticTerm(2, MOI.ScalarQuadraticTerm(6.0, x, x)), + MOI.VectorQuadraticTerm(2, MOI.ScalarQuadraticTerm(6.0, y, y)), + ], + [ + MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(2.0, x)), + MOI.VectorAffineTerm(1, MOI.ScalarAffineTerm(3.0, y)), + MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(1.0, x)), + MOI.VectorAffineTerm(2, MOI.ScalarAffineTerm(3.0, y)), + ], + [4.2, 1.2], + ) + return +end + end # module TestUtilitiesFunctions.runtests()