Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/src/submodules/Utilities/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ Utilities.all_coefficients
Utilities.unsafe_add
Utilities.isapprox_zero
Utilities.modify_function
Utilities.zero_with_output_dimension
```

The following functions can be used to canonicalize a function:
Expand Down
12 changes: 12 additions & 0 deletions src/Utilities/functions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -566,15 +566,27 @@ function Base.getindex(
return MOI.VectorQuadraticFunction(vat, vqt, it.f.constants[output_indices])
end

"""
zero_with_output_dimension(::Type{T}, output_dimension::Integer) where {T}

Create an instance of type `T` with the output dimension `output_dimension`.

This is mostly useful in Bridges, when code needs to be agnostic to the type of
vector-valued function that is passed in.
"""
function zero_with_output_dimension end

function zero_with_output_dimension(::Type{Vector{T}}, n::Integer) where {T}
return zeros(T, n)
end

function zero_with_output_dimension(
::Type{MOI.VectorAffineFunction{T}},
n::Integer,
) where {T}
return MOI.VectorAffineFunction{T}(MOI.VectorAffineTerm{T}[], zeros(T, n))
end

function zero_with_output_dimension(
::Type{MOI.VectorQuadraticFunction{T}},
n::Integer,
Expand Down
36 changes: 36 additions & 0 deletions test/Utilities/functions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1723,3 +1723,39 @@ end
[0.0, 0.0, 0.0],
)
end

@testset "zero_with_output_dimension" begin
f = MOI.Utilities.zero_with_output_dimension(Vector{Int}, 2)
@test f == [0, 0]
@test f isa Vector{Int}

g = MOI.Utilities.zero_with_output_dimension(Vector{Float64}, 2)
@test g == [0.0, 0.0]
@test g isa Vector{Float64}

h = MOI.Utilities.zero_with_output_dimension(
MOI.VectorAffineFunction{Int},
2,
)
@test MOI.output_dimension(h) == 2
@test isapprox(
h,
MOI.VectorAffineFunction{Int}(MOI.VectorAffineTerm{Int}[], [0, 0]),
)
@test h isa MOI.VectorAffineFunction{Int}

i = MOI.Utilities.zero_with_output_dimension(
MOI.VectorQuadraticFunction{Int},
2,
)
@test MOI.output_dimension(i) == 2
@test isapprox(
i,
MOI.VectorQuadraticFunction{Int}(
MOI.VectorQuadraticTerm{Int}[],
MOI.VectorAffineTerm{Int}[],
[0, 0],
),
)
@test i isa MOI.VectorQuadraticFunction{Int}
end