diff --git a/Project.toml b/Project.toml index a7f39b0..a1df270 100644 --- a/Project.toml +++ b/Project.toml @@ -17,6 +17,6 @@ GenOptExaModelsExt = ["ExaModels", "MathOptInterface"] [compat] ExaModels = "0.12.1" JuMP = "1.29" -MathOptInterface = "1.51" +MathOptInterface = "1.54" MutableArithmetics = "1.8.0" julia = "1.10" diff --git a/src/GenOpt.jl b/src/GenOpt.jl index 462204d..cb47e61 100644 --- a/src/GenOpt.jl +++ b/src/GenOpt.jl @@ -8,6 +8,7 @@ module GenOpt import MutableArithmetics as MA include("MOI_wrapper.jl") +include("MOF.jl") include("bridge.jl") include("JuMP_wrapper.jl") diff --git a/src/MOF.jl b/src/MOF.jl new file mode 100644 index 0000000..98b8a2c --- /dev/null +++ b/src/MOF.jl @@ -0,0 +1,220 @@ +# 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. + +# Experimental MathOptFormat serialization. MathOptInterface's MOF reader and +# writer dispatch through open generic functions, so GenOpt can extend them +# without replacing either implementation. + +const _MOF = MOI.FileFormats.MOF + +function _mof_function_type(::Type{MOI.ScalarAffineFunction{T}}) where {T} + return "ScalarAffineFunction" +end + +function _mof_function_type(::Type{MOI.ScalarQuadraticFunction{T}}) where {T} + return "ScalarQuadraticFunction" +end + +function _mof_function_type(::Type{MOI.ScalarNonlinearFunction}) + return "ScalarNonlinearFunction" +end + +function _moi_function_type(::Val{:ScalarAffineFunction}, ::Type{T}) where {T} + return MOI.ScalarAffineFunction{T} +end + +function _moi_function_type( + ::Val{:ScalarQuadraticFunction}, + ::Type{T}, +) where {T} + return MOI.ScalarQuadraticFunction{T} +end + +function _moi_function_type( + ::Val{:ScalarNonlinearFunction}, + ::Type{T}, +) where {T} + return MOI.ScalarNonlinearFunction +end + +function _moi_function_type(name::String, ::Type{T}) where {T} + return _moi_function_type(Val(Symbol(name)), T) +end + +# Encode GenOpt leaves as nonlinear operator nodes. This reuses MOF's nonlinear +# DAG writer and reader, followed by a small decoding pass. +function _MOF._convert_nonlinear_to_mof( + index::IteratorIndex, + node_list::Vector{Any}, + name_map::Dict{MOI.VariableIndex,String}, +) + return _MOF._convert_nonlinear_to_mof( + MOI.ScalarNonlinearFunction(:GenOptIteratorIndex, Any[index.value]), + node_list, + name_map, + ) +end + +function _MOF._convert_nonlinear_to_mof( + array::ContiguousArrayOfVariables, + node_list::Vector{Any}, + name_map::Dict{MOI.VariableIndex,String}, +) + return _MOF._convert_nonlinear_to_mof( + MOI.ScalarNonlinearFunction( + :GenOptContiguousArrayOfVariables, + Any[array.offset, array.size...], + ), + node_list, + name_map, + ) +end + +function _mof_generator_to_object( + generator::Union{FunctionGenerator{F},SumGenerator{F}}, + type::String, + name_map::Dict{MOI.VariableIndex,String}, +) where {F} + node_list = Any[] + root = _MOF._convert_nonlinear_to_mof(generator.func, node_list, name_map) + return ( + type = type, + function_type = _mof_function_type(F), + root = root, + node_list = node_list, + iterators = _mof_iterator_to_object.(generator.iterators), + ) +end + +function _MOF.moi_to_object( + generator::FunctionGenerator, + name_map::Dict{MOI.VariableIndex,String}, +) + return _mof_generator_to_object( + generator, + "GenOptFunctionGenerator", + name_map, + ) +end + +function _MOF.moi_to_object( + generator::SumGenerator, + name_map::Dict{MOI.VariableIndex,String}, +) + return _mof_generator_to_object(generator, "GenOptSumGenerator", name_map) +end + +function _mof_iterator_value_to_object(value::Tuple) + return ( + type = "GenOptTuple", + values = _mof_iterator_value_to_object.(value), + ) +end +function _mof_iterator_value_to_object(value::Symbol) + return (type = "GenOptSymbol", value = string(value)) +end +_mof_iterator_value_to_object(value) = value + +function _mof_iterator_to_object(iterator::Iterator{T}) where {T<:Integer} + values = iterator.values + if length(values) >= 2 + step = values[2] - values[1] + if all(i -> values[i] - values[i-1] == step, 2:length(values)) + return ( + type = "GenOptRangeIterator", + start = first(values), + step = step, + length = length(values), + ) + end + end + return _mof_explicit_iterator_to_object(iterator) +end + +function _mof_iterator_to_object(iterator::Iterator) + return _mof_explicit_iterator_to_object(iterator) +end + +function _mof_explicit_iterator_to_object(iterator::Iterator) + return ( + type = "GenOptExplicitIterator", + values = _mof_iterator_value_to_object.(iterator.values), + ) +end + +function _mof_iterator_value_to_moi(value::Dict) + type = value["type"] + if type == "GenOptTuple" + return Tuple(_mof_iterator_value_to_moi.(value["values"])) + elseif type == "GenOptSymbol" + return Symbol(value["value"]) + end + return error("Unsupported GenOpt iterator value: $type") +end + +_mof_iterator_value_to_moi(value) = value + +function _mof_iterator_to_moi(object::Dict) + type = object["type"] + if type == "GenOptRangeIterator" + values = range( + object["start"]; + step = object["step"], + length = object["length"], + ) + return Iterator(values) + elseif type == "GenOptExplicitIterator" + return Iterator(_mof_iterator_value_to_moi.(object["values"])) + end + return error("Unsupported GenOpt iterator: $type") +end + +function _decode_mof_template(f::MOI.ScalarNonlinearFunction) + args = Any[_decode_mof_template(arg) for arg in f.args] + if f.head == :GenOptIteratorIndex + return IteratorIndex(only(args)) + elseif f.head == :GenOptContiguousArrayOfVariables + return ContiguousArrayOfVariables(args[1], Tuple(args[2:end])) + end + return MOI.ScalarNonlinearFunction(f.head, args) +end + +_decode_mof_template(x) = x + +function _generator_from_mof( + ::Type{T}, + object::Dict, + name_map::Dict{String,MOI.VariableIndex}, +) where {T} + template = _MOF._parse_scalar_nonlinear_function( + T, + object["root"], + object["node_list"], + name_map, + ) + F = _moi_function_type(object["function_type"], T) + iterators = Iterator[_mof_iterator_to_moi(it) for it in object["iterators"]] + return F, _decode_mof_template(template), iterators +end + +function _MOF.function_to_moi( + ::Val{:GenOptFunctionGenerator}, + ::Type{T}, + object::Dict, + name_map::Dict{String,MOI.VariableIndex}, +) where {T} + F, template, iterators = _generator_from_mof(T, object, name_map) + return FunctionGenerator{F}(template, iterators) +end + +function _MOF.function_to_moi( + ::Val{:GenOptSumGenerator}, + ::Type{T}, + object::Dict, + name_map::Dict{String,MOI.VariableIndex}, +) where {T} + F, template, iterators = _generator_from_mof(T, object, name_map) + return SumGenerator{F}(template, iterators) +end diff --git a/test/MOF.jl b/test/MOF.jl new file mode 100644 index 0000000..07ad6e3 --- /dev/null +++ b/test/MOF.jl @@ -0,0 +1,147 @@ +# 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 TestMOF + +using Test +import GenOpt +import MathOptInterface as MOI + +function _round_trip(source) + writer_model = MOI.FileFormats.MOF.Model(use_nlp_block = false) + MOI.copy_to(writer_model, source) + text = sprint(write, writer_model) + destination = MOI.FileFormats.MOF.Model(use_nlp_block = false) + read!(IOBuffer(text), destination) + return text, destination +end + +function test_function_generator_round_trip() + source = MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()) + x = MOI.add_variables(source, 3) + for (i, xi) in enumerate(x) + MOI.set(source, MOI.VariableName(), xi, "x[$i]") + end + x_block = GenOpt.ContiguousArrayOfVariables(0, (3,)) + template = MOI.ScalarNonlinearFunction( + :-, + Any[ + MOI.ScalarNonlinearFunction( + :getindex, + Any[x_block, GenOpt.IteratorIndex(1)], + ), + 1.0, + ], + ) + generator = GenOpt.FunctionGenerator{MOI.ScalarAffineFunction{Float64}}( + template, + [GenOpt.Iterator(1:3)], + ) + MOI.add_constraint(source, generator, MOI.Zeros(3)) + objective = GenOpt.SumGenerator{MOI.ScalarAffineFunction{Float64}}( + template, + [GenOpt.Iterator(1:3)], + ) + MOI.set(source, MOI.ObjectiveSense(), MOI.MIN_SENSE) + MOI.set(source, MOI.ObjectiveFunction{typeof(objective)}(), objective) + + text, destination = _round_trip(source) + @test occursin("GenOptFunctionGenerator", text) + @test occursin("GenOptSumGenerator", text) + @test occursin("GenOptRangeIterator", text) + + cis = MOI.get( + destination, + MOI.ListOfConstraintIndices{typeof(generator),MOI.Zeros}(), + ) + @test length(cis) == 1 + restored = MOI.get(destination, MOI.ConstraintFunction(), only(cis)) + @test isapprox(restored, generator) + + restored_objective = + MOI.get(destination, MOI.ObjectiveFunction{typeof(objective)}()) + @test isapprox(restored_objective.func, objective.func) + @test only(restored_objective.iterators).values == + only(objective.iterators).values + return +end + +function test_quadratic_nonlinear_and_explicit_iterators() + source = MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()) + x = MOI.add_variables(source, 3) + for (i, xi) in enumerate(x) + MOI.set(source, MOI.VariableName(), xi, "x[$i]") + end + x_block = GenOpt.ContiguousArrayOfVariables(0, (3,)) + entry = MOI.ScalarNonlinearFunction( + :getindex, + Any[x_block, GenOpt.IteratorIndex(1)], + ) + # The values of this iterator are tuples of an integer and a symbol so they + # exercise the explicit encoding instead of the range one. + pairs = GenOpt.Iterator([(1, :a), (2, :b), (3, :c)]) + generator = GenOpt.FunctionGenerator{MOI.ScalarQuadraticFunction{Float64}}( + MOI.ScalarNonlinearFunction(:*, Any[entry, entry]), + [pairs], + ) + MOI.add_constraint(source, generator, MOI.Zeros(3)) + # The values are integers but they are not evenly spaced so the explicit + # encoding is used as well. + objective = GenOpt.SumGenerator{MOI.ScalarNonlinearFunction}( + MOI.ScalarNonlinearFunction(:log, Any[entry]), + [GenOpt.Iterator([1, 2, 5])], + ) + MOI.set(source, MOI.ObjectiveSense(), MOI.MIN_SENSE) + MOI.set(source, MOI.ObjectiveFunction{typeof(objective)}(), objective) + + text, destination = _round_trip(source) + @test occursin("ScalarQuadraticFunction", text) + @test occursin("ScalarNonlinearFunction", text) + @test occursin("GenOptExplicitIterator", text) + @test occursin("GenOptTuple", text) + @test occursin("GenOptSymbol", text) + @test !occursin("GenOptRangeIterator", text) + + cis = MOI.get( + destination, + MOI.ListOfConstraintIndices{typeof(generator),MOI.Zeros}(), + ) + restored = MOI.get(destination, MOI.ConstraintFunction(), only(cis)) + @test isapprox(restored.func, generator.func) + @test only(restored.iterators).values == pairs.values + restored_objective = + MOI.get(destination, MOI.ObjectiveFunction{typeof(objective)}()) + @test isapprox(restored_objective.func, objective.func) + @test only(restored_objective.iterators).values == + only(objective.iterators).values + return +end + +function test_unsupported_mof_objects() + @test_throws( + ErrorException("Unsupported GenOpt iterator value: GenOptVector"), + GenOpt._mof_iterator_value_to_moi(Dict("type" => "GenOptVector")), + ) + @test_throws( + ErrorException("Unsupported GenOpt iterator: GenOptProductIterator"), + GenOpt._mof_iterator_to_moi(Dict("type" => "GenOptProductIterator")), + ) + return +end + +function runtests() + for name in names(@__MODULE__; all = true) + if startswith("$(name)", "test_") + @testset "$(name)" begin + getfield(@__MODULE__, name)() + end + end + end + return +end + +end + +TestMOF.runtests()