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
7 changes: 7 additions & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ JuMP = "4076af6c-e467-56ae-b986-b466b2749572"
MathOptInterface = "b8f27783-ece8-5eb3-8dc8-9495eed66fee"
MutableArithmetics = "d8a4904e-b15c-11e9-3269-09a3773c0cb0"

[weakdeps]
ExaModels = "1037b233-b668-4ce9-9b63-f9f681f55dd2"

[extensions]
GenOptExaModelsExt = ["ExaModels", "MathOptInterface"]

[compat]
ExaModels = "0.12.1"
JuMP = "1.29"
MathOptInterface = "1.51"
MutableArithmetics = "1.8.0"
Expand Down
144 changes: 144 additions & 0 deletions ext/GenOptExaModelsExt.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
# Copyright (c) 2024: Benoît Legat and contributors
#
# 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.

module GenOptExaModelsExt

import ExaModels
import GenOpt:
FunctionGenerator, SumGenerator, ContiguousArrayOfVariables, IteratorIndex
import MathOptInterface as MOI

# The triggers of this extension are a strict superset of the ones of
# `ExaModelsMOI` so `ExaModelsMOI` is precompiled and loaded before this one,
# see https://github.com/JuliaLang/julia/pull/56368 and
# https://github.com/JuliaLang/julia/pull/49891
const ExaModelsMOI = Base.get_extension(ExaModels, :ExaModelsMOI)

# Objective

function MOI.supports(
::ExaModelsMOI.Optimizer,
::MOI.ObjectiveFunction{<:SumGenerator},
)
return true
end

function MOI.set(
model::ExaModelsMOI.Optimizer,
::MOI.ObjectiveFunction{F},
f::F,
) where {F<:SumGenerator}
empty!(model.objs)
ExaModelsMOI.update_bin!(model.objs, ExaModelsMOI.ObjectiveBin(), f)
return
end

# This is also called for each `SumGenerator` of a `+` in the objective
function ExaModelsMOI.update_bin!(
bins::Vector{ExaModelsMOI.Bin},
::ExaModelsMOI.ObjectiveBin,
f::SumGenerator,
)
lengths = map(it -> length(first(it.values)), f.iterators)
if length(lengths) == 1 && lengths[] == 1
bin = ExaModelsMOI.Bin(
exagen(f.func, nothing),
only.(f.iterators[].values),
)
else
bin = ExaModelsMOI.Bin(
exagen(f.func, _offsets(lengths)),
_data(f.iterators),
)
end
push!(bins, bin)
return bins
end

# Constraints

const _Sets = Union{MOI.Zeros,MOI.Nonnegatives,MOI.Nonpositives}

function MOI.supports_constraint(
::ExaModelsMOI.Optimizer,
::Type{<:FunctionGenerator},
::Type{<:_Sets},
)
return true
end

_bounds(::MOI.Zeros, ::Type{T}) where {T} = (zero(T), zero(T))
_bounds(::MOI.Nonnegatives, ::Type{T}) where {T} = (zero(T), typemax(T))
_bounds(::MOI.Nonpositives, ::Type{T}) where {T} = (typemin(T), zero(T))

function MOI.add_constraint(
model::ExaModelsMOI.Optimizer{T},
f::FunctionGenerator,
s::_Sets,
) where {T}
row = length(model.lcon) + 1
lengths = map(it -> length(first(it.values)), f.iterators)
# The row index is appended to each element of the data
row_expr = ExaModels.DataIndexed(ExaModels.DataSource(), sum(lengths) + 1)
data = [(d..., row + i - 1) for (i, d) in enumerate(_data(f.iterators))]
head = row_expr => exagen(f.func, _offsets(lengths))
push!(model.cons, ExaModelsMOI.Bin(head, data))
l, u = _bounds(s, T)
append!(model.lcon, fill(l, MOI.dimension(s)))
append!(model.ucon, fill(u, MOI.dimension(s)))
return MOI.ConstraintIndex{typeof(f),typeof(s)}(row)
end

# Convert GenOpt expression trees to ExaModels format

_offsets(lengths) = [0; cumsum(lengths)[1:(end-1)]]

function _data(iterators)
values = ntuple(i -> iterators[i].values, length(iterators))
return vec(map(Base.Iterators.ProductIterator(values)) do I
return reduce((i, j) -> tuple(i..., j...), I)
end)
end

exagen(α::Number, _) = α

function exagen(f::MOI.ScalarNonlinearFunction, offsets)
if f.head != :getindex
# This assumes that we support only the default functions in
# `MOI.Nonlinear`, like `ExaModelsMOI._exafy`
op = getfield(MOI.Nonlinear, f.head)
return op((exagen(e, offsets) for e in f.args)...)
end
v = f.args[1]
if v isa ContiguousArrayOfVariables
# `ExaModelsMOI` uses the MOI variable index as ExaModels index
idx = exagen(f.args[2], offsets)
if !iszero(v.offset)
idx = v.offset + idx
end
cp = cumprod(v.size)
for i in 3:length(f.args)
idx += cp[i-2] * (exagen(f.args[i], offsets) - 1)
end
return ExaModels.Var(idx)
elseif v isa IteratorIndex
@assert length(f.args) == 2
@assert f.args[2] isa Integer
if isnothing(offsets)
@assert isone(f.args[2])
return ExaModels.DataSource()
end
return ExaModels.DataIndexed(
ExaModels.DataSource(),
offsets[v.value] + f.args[2],
)
end
return error(
"Unexpected the first operand of `getindex` to be of type " *
"`$(typeof(v))`",
)
end

end # module
4 changes: 3 additions & 1 deletion src/JuMP_wrapper.jl
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ function ArrayOfVariables(
end

Base.size(array::ArrayOfVariables) = array.size
function Base.getindex(A::ArrayOfVariables{T,N,V}, I...) where {T,N,V}
# Restricting to integers lets `Base` handle other indices, e.g.,
# `CartesianIndex` which JuMP uses when iterating in `check_belongs_to_model`
function Base.getindex(A::ArrayOfVariables{T,N,V}, I::Integer...) where {T,N,V}
index =
A.offset + Base._to_linear_index(Base.CartesianIndices(A.size), I...)
return V(A.model, MOI.VariableIndex(index))
Expand Down
55 changes: 45 additions & 10 deletions src/MOI_wrapper.jl
Original file line number Diff line number Diff line change
Expand Up @@ -176,18 +176,53 @@ function MOI.Utilities.canonicalize!(
return s
end

# `MOI.Utilities.IndexMap` is an `AbstractDict` so `map_indices` with an
# `IndexMap` is redirected by MOI to the methods below.

function MOI.Utilities.map_indices(
::MOI.Utilities.IndexMap,
func::Union{FunctionGenerator,SumGenerator,FilteredSumGenerator},
)
# TODO check it's identity
return func
index_map::F,
array::ContiguousArrayOfVariables,
) where {F<:Function}
offset = index_map(MOI.VariableIndex(array.offset + 1)).value - 1
# The variables have to remain contiguous in the same order.
for i in 1:length(array)
if index_map(MOI.VariableIndex(array.offset + i)).value != offset + i
error(
"Cannot map the indices of a `ContiguousArrayOfVariables` as " *
"the variables are no longer contiguous after the mapping.",
)
end
end
return ContiguousArrayOfVariables(offset, array.size)
end

function MOI.Utilities.map_indices(
::Function,
func::Union{FunctionGenerator,SumGenerator,FilteredSumGenerator},
)
# TODO check it's identity
return func
index_map::F,
func::FunctionGenerator{G},
) where {F<:Function,G}
return FunctionGenerator{G}(
MOI.Utilities.map_indices(index_map, func.func),
func.iterators,
)
end

function MOI.Utilities.map_indices(
index_map::F,
func::SumGenerator{G},
) where {F<:Function,G}
return SumGenerator{G}(
MOI.Utilities.map_indices(index_map, func.func),
func.iterators,
)
end

function MOI.Utilities.map_indices(
index_map::F,
func::FilteredSumGenerator{G},
) where {F<:Function,G}
return FilteredSumGenerator{G}(
MOI.Utilities.map_indices(index_map, func.func),
func.iterators,
func.filter,
)
end
2 changes: 2 additions & 0 deletions src/operators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,8 @@ JuMP.moi_function(array::_DataArray) = array
JuMP.check_belongs_to_model(::_DataArray, ::JuMP.AbstractModel) = nothing
JuMP.moi_function(::JuMP.GenericModel, array::_DataArray) = array
JuMP.jump_function(_, array::_DataArray) = array
# The data does not contain any variable or constraint index
MOI.Utilities.map_indices(::Function, array::_DataArray) = array

# A lookup involving several domains cannot be appended to one iterator's
# values. Keep it symbolic until the Cartesian product is expanded instead.
Expand Down
Loading
Loading