diff --git a/Project.toml b/Project.toml index a0d0876..a7f39b0 100644 --- a/Project.toml +++ b/Project.toml @@ -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" diff --git a/ext/GenOptExaModelsExt.jl b/ext/GenOptExaModelsExt.jl new file mode 100644 index 0000000..60d7c5a --- /dev/null +++ b/ext/GenOptExaModelsExt.jl @@ -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 diff --git a/src/JuMP_wrapper.jl b/src/JuMP_wrapper.jl index 568ba8a..a37030c 100644 --- a/src/JuMP_wrapper.jl +++ b/src/JuMP_wrapper.jl @@ -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)) diff --git a/src/MOI_wrapper.jl b/src/MOI_wrapper.jl index dd9fb6b..fd1c44b 100644 --- a/src/MOI_wrapper.jl +++ b/src/MOI_wrapper.jl @@ -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 diff --git a/src/operators.jl b/src/operators.jl index e8ce8b3..3bbdfa9 100644 --- a/src/operators.jl +++ b/src/operators.jl @@ -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. diff --git a/test/ExaModels.jl b/test/ExaModels.jl new file mode 100644 index 0000000..e93b2af --- /dev/null +++ b/test/ExaModels.jl @@ -0,0 +1,179 @@ +# 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. + +# Scope: the `GenOptExaModelsExt` extension, end to end with +# `ExaModels.Optimizer`. + +module TestExaModels + +using Test +using JuMP +import ExaModels +import GenOpt +import MadNLP + +function runtests() + for name in names(@__MODULE__; all = true) + if startswith("$(name)", "test_") + @testset "$(name)" begin + getfield(@__MODULE__, name)() + end + end + end + return +end + +# Simplified quadrotor of the ExaModels tutorial. If `parameters` is true, MOI +# parameters are created before the variables so the MOI variable indices of +# the JuMP model differ from the ones of `ExaModels.Optimizer`. +function _quadrotor(; parameters::Bool = false) + N, n, p, dt, g = 3, 9, 4, 0.1, 9.81 + xf = [1.0, 0, 0, 1, 0, 0, 0, 0, 0] + Q = zeros(n) + Q[1] = Q[4] = 1.0 + Qf = ones(n) + R = ones(p) + itr1 = [(i, j, xf[j]) for i in 1:N for j in 1:n if Q[j] != 0] + itr2 = [(j, xf[j]) for j in 1:n] + model = Model() + if parameters + @variable(model, par1 in MOI.Parameter(2.0)) + @variable(model, par2 in MOI.Parameter(3.0)) + end + @variable(model, x[1:(N+1), 1:n]) + @variable(model, u[1:N, 1:p]) + c = GenOpt.ParametrizedArray + @constraint(model, [i in 1:n], x[1, i] == 0, container = c) + @constraint( + model, + [i in 1:N], + x[i+1, 1] == x[i, 1] + x[i, 2] * dt, + container = c + ) + @constraint( + model, + [i in 1:N], + x[i+1, 2] == x[i, 2] + u[i, 1] * dt, + container = c + ) + @constraint( + model, + [i in 1:N], + x[i+1, 3] == x[i, 3] + x[i, 4] * dt, + container = c + ) + @constraint( + model, + [i in 1:N], + x[i+1, 4] == x[i, 4] + u[i, 2] * dt, + container = c + ) + @constraint( + model, + [i in 1:N], + x[i+1, 5] == x[i, 5] + x[i, 6] * dt, + container = c + ) + @constraint( + model, + [i in 1:N], + x[i+1, 6] == x[i, 6] + (u[i, 3] - g) * dt, + container = c, + ) + @constraint( + model, + [i in 1:N], + x[i+1, 7] == x[i, 7] + u[i, 1] * dt, + container = c + ) + @constraint( + model, + [i in 1:N], + x[i+1, 8] == x[i, 8] + u[i, 2] * dt, + container = c + ) + @constraint( + model, + [i in 1:N], + x[i+1, 9] == x[i, 9] + u[i, 4] * dt, + container = c + ) + @objective( + model, + Min, + GenOpt.lazy_sum(0.5 * R[j] * (u[i, j]^2) for i in 1:N, j in 1:p) + + GenOpt.lazy_sum( + 0.5 * Q[it[2]] * (x[it[1], it[2]] - it[3])^2 for it in itr1 + ) + + GenOpt.lazy_sum( + 0.5 * Qf[it[1]] * (x[N+1, it[1]] - it[2])^2 for it in itr2 + ), + ) + return model +end + +function _optimize!(model) + set_optimizer(model, () -> ExaModels.Optimizer(MadNLP.madnlp)) + set_attribute(model, "print_level", MadNLP.ERROR) + optimize!(model) + return +end + +function test_quadrotor() + model = _quadrotor() + _optimize!(model) + @test objective_value(model) ≈ 8.1797 atol = 1e-3 + return +end + +function test_quadrotor_structure() + # The 10 `@constraint` with `container = GenOpt.ParametrizedArray` are 1 + # initial condition over `n = 9` and 9 dynamics over `N = 3`. They should + # not be scalarized: each one should be a block augmenting the 36 rows. + m = ExaModels.ExaModel(_quadrotor()) + @test m.meta.ncon == 36 + @test sort([length(c.itr) for c in m.cons]) == [fill(3, 9); 9; 36] + return +end + +function test_quadrotor_parameters() + model = _quadrotor(; parameters = true) + _optimize!(model) + @test objective_value(model) ≈ 8.1797 atol = 1e-3 + return +end + +function test_single_sum_objective() + N = 4 + model = Model() + @variable(model, x[1:N]) + c = GenOpt.ParametrizedArray + @constraint(model, [i in 1:N], x[i] >= 2, container = c) + @constraint(model, [i in 1:N], x[i] <= 3, container = c) + @objective(model, Min, GenOpt.lazy_sum((x[i] - i)^2 for i in 1:N)) + _optimize!(model) + @test objective_value(model) ≈ 2 atol = 1e-6 + @test value.(x) ≈ [2, 2, 3, 3] atol = 1e-3 + return +end + +function test_deferred_getindex() + # `d[i + j]` involves two iterators so it is kept as a `getindex` of the + # data which is not supported by the extension + d = [1.0, 2.0, 3.0] + model = Model() + @variable(model, x[1:2]) + @objective( + model, + Min, + GenOpt.lazy_sum(d[i+j] * x[i]^2 for i in 1:2, j in 1:1), + ) + @test_throws ErrorException _optimize!(model) + return +end + +end # module + +TestExaModels.runtests() diff --git a/test/Project.toml b/test/Project.toml index 01577c4..af963c7 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -1,7 +1,9 @@ [deps] +ExaModels = "1037b233-b668-4ce9-9b63-f9f681f55dd2" GenOpt = "f2c049d8-7489-4223-990c-4f1c121a4cde" HiGHS = "87dc4568-4c63-4d18-b0c0-bb2238e4078b" JuMP = "4076af6c-e467-56ae-b986-b466b2749572" +MadNLP = "2621e9c9-9eb4-46b1-8089-e8c72242dfb6" MathOptInterface = "b8f27783-ece8-5eb3-8dc8-9495eed66fee" PGLib = "07a8691f-3d11-4330-951b-3c50f98338be" PowerModels = "c36e90e8-916a-50a6-bd94-075b64ef4655" diff --git a/test/operators.jl b/test/operators.jl index a206995..9c3935b 100644 --- a/test/operators.jl +++ b/test/operators.jl @@ -142,11 +142,54 @@ function test_filtered_sum_moi_utilities() @test copied.filter === generator.filter @test MOI.Utilities.is_canonical(copied) @test MOI.Utilities.canonicalize!(copied) === copied - @test MOI.Utilities.map_indices(MOI.Utilities.IndexMap(), copied) === copied - @test MOI.Utilities.map_indices(identity, copied) === copied + mapped = MOI.Utilities.map_indices(identity, copied) + @test mapped isa GenOpt.FilteredSumGenerator + @test mapped.iterators === copied.iterators + @test mapped.filter === copied.filter + @test _arrays(mapped.func) == _arrays(copied.func) + # Shift the variables as `MOI.copy_to` does when, e.g., parameters are + # added first in the destination + index_map = MOI.Utilities.IndexMap() + for xi in x + vi = JuMP.index(xi) + index_map[vi] = MOI.VariableIndex(vi.value + 2) + end + mapped = MOI.Utilities.map_indices(index_map, copied) + @test _arrays(mapped.func) == [GenOpt.ContiguousArrayOfVariables(2, (3,))] + # The variables are no longer contiguous + index_map[JuMP.index(x[2])] = MOI.VariableIndex(10) + @test_throws ErrorException MOI.Utilities.map_indices(index_map, copied) + return +end + +function test_deferred_getindex_map_indices() + model = JuMP.Model() + JuMP.@variable(model, x[1:2]) + d = [1.0, 2.0, 3.0] + # `d[i + j]` involves two iterators so `d` is kept in the function + generator = + JuMP.moi_function(GenOpt.lazy_sum(d[i+j] * x[i] for i in 1:2, j in 1:1)) + data = _data_arrays(generator.func) + @test length(data) == 1 + @test only(data).data === d + mapped = MOI.Utilities.map_indices(identity, generator) + @test _data_arrays(mapped.func) == data + @test only(_data_arrays(mapped.func)) === only(data) return end +_data_arrays(::Any) = GenOpt._DataArray[] +_data_arrays(a::GenOpt._DataArray) = [a] +function _data_arrays(f::MOI.ScalarNonlinearFunction) + return reduce(vcat, _data_arrays.(f.args); init = _data_arrays(nothing)) +end + +_arrays(::Any) = GenOpt.ContiguousArrayOfVariables[] +_arrays(a::GenOpt.ContiguousArrayOfVariables) = [a] +function _arrays(f::MOI.ScalarNonlinearFunction) + return reduce(vcat, _arrays.(f.args); init = _arrays(nothing)) +end + function test_jump_function_type() model = JuMP.Model() F = MOI.ScalarAffineFunction{Float64}