diff --git a/src/Utilities/functions.jl b/src/Utilities/functions.jl index 2d558f92e4..2675e8512c 100644 --- a/src/Utilities/functions.jl +++ b/src/Utilities/functions.jl @@ -2207,14 +2207,7 @@ Returns the vector of scalar affine functions in the form of a `MOI.VectorAffineFunction{T}`. """ function vectorize(funcs::AbstractVector{MOI.ScalarAffineFunction{T}}) where {T} - nterms = - mapreduce(func -> number_of_affine_terms(T, func), +, funcs, init = 0) - out_dim = mapreduce(func -> output_dim(T, func), +, funcs, init = 0) - terms = Vector{MOI.VectorAffineTerm{T}}(undef, nterms) - constant = zeros(T, out_dim) - fill_vector(terms, T, fill_terms, number_of_affine_terms, funcs) - fill_vector(constant, T, fill_constant, output_dim, funcs) - return MOI.VectorAffineFunction(terms, constant) + return MOI.VectorAffineFunction(funcs) end """ diff --git a/src/functions.jl b/src/functions.jl index b6193e0192..f088cc3cee 100644 --- a/src/functions.jl +++ b/src/functions.jl @@ -578,6 +578,19 @@ function VectorAffineFunction{T}(f::VectorOfVariables) where {T} return VectorAffineFunction(terms, constants) end +function VectorAffineFunction( + rows::AbstractVector{ScalarAffineFunction{T}}, +) where {T} + ret = VectorAffineFunction{T}(VectorAffineTerm{T}[], T[]) + for (row, f) in enumerate(rows) + push!(ret.constants, f.constant) + for term in f.terms + push!(ret.terms, VectorAffineTerm(row, term)) + end + end + return ret +end + """ VectorQuadraticTerm{T}( output_index::Int64, diff --git a/test/functions.jl b/test/functions.jl index d6143d161b..e4b14b42e8 100644 --- a/test/functions.jl +++ b/test/functions.jl @@ -129,6 +129,20 @@ function test_functions_convert_ScalarQuadraticFunction() ) end +function test_vectoraffinefunction_creation() + 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_isapprox_VectorOfVariables() x = MOI.VariableIndex(1) y = MOI.VariableIndex(2)