diff --git a/README.md b/README.md index c815281..c264cdd 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,35 @@ To create a grouped sum, use `lazy_sum` as follows: lazy_sum(0.5 * R[j] * (u[i, j]^2) for i in 1:N, j in 1:p), ) ``` +## Solve polynomial models with HiGHS + +Register the generator and scalar polynomial bridges to use affine and +quadratic lazy sums with HiGHS: + +```julia +using JuMP, GenOpt +import HiGHS + +model = Model(HiGHS.Optimizer) +add_bridge(model, GenOpt.FunctionGeneratorBridge) +add_bridge(model, GenOpt.PolynomialFunctionBridge) +@variable(model, x[1:4]) +@constraint(model, [i in 1:4], x[i] >= 0, container = ParametrizedArray) +@constraint(model, lazy_sum(x[i] + 1 for i in 1:4) <= 12) +@objective(model, Min, lazy_sum((x[i] - i)^2 for i in 1:4)) +optimize!(model) +``` + +GenOpt tracks known polynomial expressions using `PolynomialFunction{F}`, where +`F` is the affine or quadratic output type. The shared builders accumulate lazy +sum terms directly into that type when the optimizer needs it. HiGHS supports +quadratic objectives, but not quadratic constraints. Ordinary, untagged +`MOI.ScalarNonlinearFunction` inputs are not handled by these polynomial bridges. + +Polynomial lowering currently requires filters to refer only to the iterators +bound by their sum. A filter depending on an enclosing generator raises an +explicit error. + ## Solve with ExaModels Install ExaModels and a solver such as MadNLP: diff --git a/examples/opf/runtests.jl b/examples/opf/runtests.jl index 46371ea..fabaeb2 100644 --- a/examples/opf/runtests.jl +++ b/examples/opf/runtests.jl @@ -37,8 +37,10 @@ const NONLINEAR = FunctionGenerator{MOI.ScalarNonlinearFunction} end # The reference bus angle, over the single reference bus. @test dims[(AFFINE, MOI.Zeros)] == [1] - # The 4 branch flow definitions and the 2 bus power balances, over 3 components each. - @test dims[(NONLINEAR, MOI.Zeros)] == fill(3, 6) + # The 4 branch flow definitions contain trigonometric terms. + @test dims[(NONLINEAR, MOI.Zeros)] == fill(3, 4) + # The 2 bus power balances contain affine sums and squared voltages. + @test dims[(QUADRATIC, MOI.Zeros)] == [3, 3] # `angmin[i] <= va[..] - va[..] <= angmax[i]` stays one interval constraint carrying # the per-branch bounds, rather than two inequalities per branch. @test dims[(AFFINE, MOI.HyperRectangle{Float64})] == [3] @@ -53,9 +55,12 @@ end b = JuMP.backend(model) F = MOI.get(b, MOI.ObjectiveFunctionType()) # The `lazy_sum` over the generators is not expanded into 3 cost terms. - @test F == SumGenerator{MOI.ScalarQuadraticFunction{Float64}} + @test F == GenOpt.PolynomialFunction{MOI.ScalarQuadraticFunction{Float64}} obj = MOI.get(b, MOI.ObjectiveFunction{F}()) - @test prod(it -> length(it.values), obj.iterators) == 3 + @test obj.func.head == :+ + generator = only(obj.func.args) + @test generator isa SumGenerator{MOI.ScalarQuadraticFunction{Float64}} + @test prod(it -> length(it.values), generator.iterators) == 3 end end # module TestOPF diff --git a/examples/quadrotor/runtests.jl b/examples/quadrotor/runtests.jl index a8fd87e..af006e5 100644 --- a/examples/quadrotor/runtests.jl +++ b/examples/quadrotor/runtests.jl @@ -77,12 +77,26 @@ end @testset "objective keeps its generators" begin b = JuMP.backend(model) F = MOI.get(b, MOI.ObjectiveFunctionType()) - @test F == MOI.ScalarNonlinearFunction - obj = MOI.get(b, MOI.ObjectiveFunction{F}()) + @test F == PolynomialFunction{MOI.ScalarQuadraticFunction{Float64}} + obj = MOI.get(b, MOI.ObjectiveFunction{F}()).func # The three `lazy_sum` terms are summed without being expanded. @test obj.head == :+ - @test all(a -> a isa SumGenerator, obj.args) - terms = [prod(it -> length(it.values), a.iterators) for a in obj.args] + # Additions may be nested, with polynomial degree tags around each sum. + pending = Any[obj] + sums = SumGenerator{MOI.ScalarQuadraticFunction{Float64}}[] + while !isempty(pending) + arg = pop!(pending) + if arg isa PolynomialFunction + push!(pending, arg.func) + elseif arg isa MOI.ScalarNonlinearFunction + @test arg.head == :+ + append!(pending, arg.args) + else + @test arg isa SumGenerator{MOI.ScalarQuadraticFunction{Float64}} + push!(sums, arg) + end + end + terms = [prod(it -> length(it.values), a.iterators) for a in sums] # `N * p` control terms, `N * n` stage terms and `n` terminal terms. # Older JuMP versions may reorder terms when flattening the objective sum. @test sort(terms) == sort([N * 4, N * n, n]) diff --git a/ext/GenOptExaModelsExt.jl b/ext/GenOptExaModelsExt.jl index 60d7c5a..72b7472 100644 --- a/ext/GenOptExaModelsExt.jl +++ b/ext/GenOptExaModelsExt.jl @@ -7,7 +7,11 @@ module GenOptExaModelsExt import ExaModels import GenOpt: - FunctionGenerator, SumGenerator, ContiguousArrayOfVariables, IteratorIndex + FunctionGenerator, + SumGenerator, + PolynomialFunction, + ContiguousArrayOfVariables, + IteratorIndex import MathOptInterface as MOI # The triggers of this extension are a strict superset of the ones of @@ -18,6 +22,34 @@ const ExaModelsMOI = Base.get_extension(ExaModels, :ExaModelsMOI) # Objective +function MOI.supports( + ::ExaModelsMOI.Optimizer, + ::MOI.ObjectiveFunction{<:PolynomialFunction}, +) + return true +end + +function MOI.set( + model::ExaModelsMOI.Optimizer, + ::MOI.ObjectiveFunction{F}, + f::F, +) where {F<:PolynomialFunction} + # Unwrap the degree tag, keeping generator templates and iterator data. + return MOI.set( + model, + MOI.ObjectiveFunction{MOI.ScalarNonlinearFunction}(), + f.func, + ) +end + +function ExaModelsMOI.update_bin!( + bins::Vector{ExaModelsMOI.Bin}, + fn::ExaModelsMOI.AbstractBin, + f::PolynomialFunction, +) + return ExaModelsMOI.update_bin!(bins, fn, f.func) +end + function MOI.supports( ::ExaModelsMOI.Optimizer, ::MOI.ObjectiveFunction{<:SumGenerator}, @@ -103,6 +135,11 @@ function _data(iterators) end exagen(α::Number, _) = α +exagen(f::PolynomialFunction, offsets) = exagen(f.func, offsets) + +function ExaModelsMOI._exafy(f::PolynomialFunction, data::Tuple, var_to_data) + return ExaModelsMOI._exafy(f.func, data, var_to_data) +end function exagen(f::MOI.ScalarNonlinearFunction, offsets) if f.head != :getindex diff --git a/src/Bridges/Bridges.jl b/src/Bridges/Bridges.jl index aaae2ba..5b11ed0 100644 --- a/src/Bridges/Bridges.jl +++ b/src/Bridges/Bridges.jl @@ -4,3 +4,4 @@ # in the LICENSE.md file or at https://opensource.org/licenses/MIT. include("Constraint/Constraint.jl") +include("polynomial_function.jl") diff --git a/src/Bridges/Constraint/Constraint.jl b/src/Bridges/Constraint/Constraint.jl index 6d4863d..afa2a14 100644 --- a/src/Bridges/Constraint/Constraint.jl +++ b/src/Bridges/Constraint/Constraint.jl @@ -4,3 +4,4 @@ # in the LICENSE.md file or at https://opensource.org/licenses/MIT. include("function_generator.jl") +include("polynomial_function.jl") diff --git a/src/Bridges/Constraint/function_generator.jl b/src/Bridges/Constraint/function_generator.jl index ea49906..ce7623e 100644 --- a/src/Bridges/Constraint/function_generator.jl +++ b/src/Bridges/Constraint/function_generator.jl @@ -200,6 +200,143 @@ end _expand(idx::IteratorIndex, values) = values[idx.value] _expand(x, _) = x # constants, MOI.VariableIndex, etc. +# These leaves arrive through Vector{Any}. Keep boxed helpers generic so a +# trimmed image does not need new leaf-type specializations at runtime. +Base.@nospecializeinfer function _expand( + @nospecialize(func::PolynomialFunction), + values, +) + return _expand(func.func, values) +end + +const _AnySumGenerator = Union{SumGenerator,FilteredSumGenerator} + +Base.@nospecializeinfer function _sum_filter( + @nospecialize(func::SumGenerator), + _, +) + return true +end +Base.@nospecializeinfer function _sum_filter( + @nospecialize(func::FilteredSumGenerator), + values, +)::Bool + return _expand_filter(func.filter, values, func.iterators) +end + +_expand_filter(value, values) = _expand(value, values) + +function _filter_iterator_position(value, iterators)::Int + source = value.iterators[value.index.value] + for k in eachindex(iterators) + if iterators[k].identity === source.identity + return k + end + end + return throw( + ArgumentError( + "Correlated lazy-sum filters are not supported: " * + "a filter iterator is outside the sum's domain", + ), + ) +end + +function _check_filter_scope(value, iterators) + if value isa IteratorValues + _filter_iterator_position(value, iterators) + elseif value isa _Filtered + _check_filter_scope(value.iterator, iterators) + elseif value isa FilterExpression + for arg in value.args + _check_filter_scope(arg, iterators) + end + end + return +end + +Base.@nospecializeinfer function _check_sum_filter( + @nospecialize(func::SumGenerator) +) + return +end +Base.@nospecializeinfer function _check_sum_filter( + @nospecialize(func::FilteredSumGenerator) +) + return _check_filter_scope(func.filter, func.iterators) +end + +function _expand_filter(value, values, iterators) + iterators === nothing && return _expand_filter(value, values) + if value isa IteratorValues + position = _filter_iterator_position(value, iterators) + return values[position][value.value_index] + elseif value isa _Filtered + return _expand_filter(value.iterator, values, iterators) + end + return _expand_filter(value, values) +end + +function _expand_filter(filter::FilterExpression, values, iterators = nothing) + if filter.head === :(==) && length(filter.args) == 2 + return _expand_filter(filter.args[1], values, iterators) == + _expand_filter(filter.args[2], values, iterators) + end + args = map(arg -> _expand_filter(arg, values, iterators), filter.args) + return getfield(Base, filter.head)(args...) +end + +# Each sum owns its IteratorIndex scope. Allocate its scratch arrays once, +# not once per term, and never overwrite values belonging to an outer sum. +# A callback returning false stops the traversal early. +Base.@nospecializeinfer function _foreach_sum_term( + f::F, + @nospecialize(func::_AnySumGenerator) +)::Bool where {F} + _check_sum_filter(func) + sizes = length.(func.iterators) + nit = length(func.iterators) + positions = ones(Int, nit) + values = Vector{Any}(undef, nit) + for _ in 1:prod(sizes) + for k in 1:nit + values[k] = @inbounds @inline getindex( + func.iterators[k].values, + positions[k], + ) + end + if _sum_filter(func, values) && !f(func.func, values) + return false + end + for k in 1:nit + positions[k] += 1 + if positions[k] <= sizes[k] + break + end + positions[k] = 1 + end + end + return true +end + +# The normal affine/quadratic walkers accumulate sums directly. This general +# expansion remains for their uncommon conversion and constant-folding paths. +Base.@nospecializeinfer function _expand( + @nospecialize(func::_AnySumGenerator), + _, +) + args = Any[] + _foreach_sum_term(func) do term, values + push!(args, _expand(term, values)) + return true + end + if isempty(args) + return 0 + elseif all(_is_numeric, args) + return _eval_op(:+, args) + end + return MOI.ScalarNonlinearFunction(:+, args) +end + _is_numeric(::Number) = true _is_numeric(_) = false @@ -308,6 +445,30 @@ macro _expand_recurse(kind, out, arg, values, coef, T) return Expr(:block, __source__, body) end +Base.@nospecializeinfer function _expand_affine_sum!( + out::MOI.ScalarAffineFunction{T}, + @nospecialize(func::_AnySumGenerator), + coef::T, +) where {T} + _foreach_sum_term(func) do term, values + _expand_affine!(out, term, values, coef) + return true + end + return +end + +Base.@nospecializeinfer function _expand_quadratic_sum!( + out::MOI.ScalarQuadraticFunction{T}, + @nospecialize(func::_AnySumGenerator), + coef::T, +) where {T} + _foreach_sum_term(func) do term, values + _expand_quadratic!(out, term, values, coef) + return true + end + return +end + # Entry point. `arg` is typically read out of `Vector{Any}` (so its static # type is `Any`). Multi-method dispatch on `arg` would pay a per-call # allocation for the dispatch tuple; using a single method with a manual @@ -365,6 +526,20 @@ function _expand_affine_snf!( return end _expand_affine_fallback!(out, expr, values, coef) + elseif h === :/ && length(args) == 2 + denominator = args[2] + constant = @_try_const T denominator values + if constant !== nothing + new_coef = convert(T, coef / constant) + numerator = args[1] + @_expand_recurse affine out numerator values new_coef T + return + end + _expand_affine_fallback!(out, expr, values, coef) + elseif h === :^ && length(args) == 2 && _is_unit_exponent(args[2]) + base = args[1] + @_expand_recurse affine out base values coef T + return elseif h === :getindex _expand_getindex_affine!(out, args, values, coef) return @@ -380,12 +555,19 @@ end # Keep uncommon forms (including embedded MOI polynomials) out of the # allocation-free walker. Conversion still rejects non-affine expressions. -function _expand_affine_fallback!( +Base.@nospecializeinfer function _expand_affine_fallback!( out::MOI.ScalarAffineFunction{T}, - expr, + @nospecialize(expr), values, coef::T, ) where {T} + if expr isa PolynomialFunction + _expand_affine_snf!(out, expr.func, values, coef) + return + elseif expr isa _AnySumGenerator + _expand_affine_sum!(out, expr, coef) + return + end f = convert(MOI.ScalarAffineFunction{T}, _expand(expr, values)) for term in f.terms push!( @@ -630,7 +812,17 @@ Base.@nospecializeinfer function _eval_index(@nospecialize(x), values)::Float64 # `:getindex` nodes here so index expressions like `k + 1` work # under the JuMP-built path. coll = args[1] - v = _expand(coll, values) + # Keep bound-iterator access visible to a trimmed image instead + # of dispatching `_expand` on the erased collection argument. + v = if coll isa IteratorIndex + value = values[coll.value] + while value isa IteratorIndex + value = values[value.value] + end + value + else + _expand(coll, values) + end if n == 2 return _float_index( _iterator_component(v, _to_int(args[2], values)), @@ -734,17 +926,38 @@ end if _contains_variable(expr, values) return nothing end + if expr isa _AnySumGenerator + # Fold numeric sums in the target coefficient type. `_eval_op` + # would first float integer data, losing large-integer precision. + out = MOI.ScalarAffineFunction(MOI.ScalarAffineTerm{T}[], zero(T)) + _expand_affine_sum!(out, expr, one(T)) + return isempty(out.terms) ? out.constant : nothing + end value = _expand(expr, values) return value isa Number ? T(value) : nothing end # This check is deliberately conservative: an unrecognized variable lookup # may reach the general folder, but a known variable cannot be a constant. -Base.@nospecializeinfer function _contains_variable(@nospecialize(expr), values) +Base.@nospecializeinfer @inline function _contains_variable( + @nospecialize(expr), + values, +)::Bool if expr isa MOI.VariableIndex return true elseif expr isa IteratorIndex return _contains_variable(values[expr.value], values) + elseif expr isa PolynomialFunction + return _contains_variable(expr.func, values) + elseif expr isa _AnySumGenerator + is_constant = _foreach_sum_term(expr) do term, sum_values + return !_contains_variable(term, sum_values) + end + return !is_constant + elseif expr isa MOI.ScalarAffineFunction + return !isempty(expr.terms) + elseif expr isa MOI.ScalarQuadraticFunction + return !isempty(expr.affine_terms) || !isempty(expr.quadratic_terms) elseif expr isa MOI.ScalarNonlinearFunction if expr.head === :getindex && expr.args[1] isa ContiguousArrayOfVariables @@ -829,6 +1042,20 @@ function _expand_quadratic_snf!( @_expand_recurse affine saf2 a2 values unit T _accumulate_product!(out, saf1, saf2, coef) return + elseif h === :/ && length(args) == 2 + denominator = args[2] + constant = @_try_const T denominator values + if constant !== nothing + new_coef = convert(T, coef / constant) + numerator = args[1] + @_expand_recurse quadratic out numerator values new_coef T + return + end + _expand_quadratic_fallback!(out, expr, values, coef) + elseif h === :^ && length(args) == 2 && _is_unit_exponent(args[2]) + base = args[1] + @_expand_recurse quadratic out base values coef T + return elseif h === :^ && length(args) == 2 && _is_square_exponent(args[2]) saf = MOI.ScalarAffineFunction(MOI.ScalarAffineTerm{T}[], zero(T)) unit = one(T) @@ -884,20 +1111,43 @@ function _expand_quadratic_snf!( end end +@inline function _is_unit_exponent(value) + # Exponents come from Vector{Any}. Narrow before comparison so a trimmed + # image retains primitive comparisons rather than dispatching on Real. + if value isa Int + return value == 1 + elseif value isa Float64 + return value == 1.0 + elseif value isa Float32 + return value == 1.0f0 + end + return value isa Real && value == 1 +end + @inline function _is_square_exponent(value) - # The exponent is read from Vector{Any}; expose the literal integer case. if value isa Int return value == 2 + elseif value isa Float64 + return value == 2.0 + elseif value isa Float32 + return value == 2.0f0 end - return value == 2 + return value isa Real && value == 2 end -function _expand_quadratic_fallback!( +Base.@nospecializeinfer function _expand_quadratic_fallback!( out::MOI.ScalarQuadraticFunction{T}, - expr, + @nospecialize(expr), values, coef::T, ) where {T} + if expr isa PolynomialFunction + _expand_quadratic_snf!(out, expr.func, values, coef) + return + elseif expr isa _AnySumGenerator + _expand_quadratic_sum!(out, expr, coef) + return + end f = convert(MOI.ScalarQuadraticFunction{T}, _expand(expr, values)) for term in f.quadratic_terms push!( diff --git a/src/Bridges/Constraint/polynomial_function.jl b/src/Bridges/Constraint/polynomial_function.jl new file mode 100644 index 0000000..ae7004c --- /dev/null +++ b/src/Bridges/Constraint/polynomial_function.jl @@ -0,0 +1,138 @@ +# 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. + +""" + PolynomialFunctionBridge{T,F,S} + +Lower a `PolynomialFunction{F}` constraint to its concrete polynomial type `F`. +Constants are moved into the scalar set, as required by solvers such as HiGHS. +Only the moved constant is retained: function queries reconstruct an equivalent +wrapper from the current inner function, including after variable deletion. +""" +mutable struct PolynomialFunctionBridge{T,F,S} <: + MOI.Bridges.Constraint.AbstractFunctionConversionBridge{F,S} + constraint::MOI.ConstraintIndex{F,S} + constant::T +end + +function MOI.supports_constraint( + ::Type{PolynomialFunctionBridge{T}}, + ::Type{PolynomialFunction{F}}, + ::Type{<:MOI.AbstractScalarSet}, +) where {T,F} + return MOI.Utilities.is_coefficient_type(F, T) +end + +function MOI.Bridges.Constraint.concrete_bridge_type( + ::Type{PolynomialFunctionBridge{T}}, + ::Type{PolynomialFunction{F}}, + ::Type{S}, +) where {T,F,S<:MOI.AbstractScalarSet} + return PolynomialFunctionBridge{T,F,S} +end + +function MOI.Bridges.Constraint.bridge_constraint( + ::Type{PolynomialFunctionBridge{T,F,S}}, + model::MOI.ModelLike, + func::PolynomialFunction{F}, + set::S, +) where {T,F,S} + polynomial = convert(F, func) + constant = + MOI.Utilities.supports_shift_constant(S) ? polynomial.constant : zero(T) + constraint = MOI.Utilities.normalize_and_add_constraint( + model, + polynomial, + set; + allow_modify_function = true, + ) + return PolynomialFunctionBridge{T,F,S}(constraint, constant) +end + +function MOI.get( + model::MOI.ModelLike, + ::MOI.ConstraintFunction, + bridge::PolynomialFunctionBridge{T,F}, +) where {T,F} + func = copy(MOI.get(model, MOI.ConstraintFunction(), bridge.constraint)) + func.constant += bridge.constant + return convert(PolynomialFunction{F}, func) +end + +function MOI.get( + model::MOI.ModelLike, + ::MOI.ConstraintSet, + bridge::PolynomialFunctionBridge{T,F,S}, +) where {T,F,S} + set = MOI.get(model, MOI.ConstraintSet(), bridge.constraint) + if MOI.Utilities.supports_shift_constant(S) + return MOI.Utilities.shift_constant(set, bridge.constant) + end + return set +end + +function MOI.set( + model::MOI.ModelLike, + ::MOI.ConstraintFunction, + bridge::PolynomialFunctionBridge{T,F,S}, + func::PolynomialFunction{F}, +) where {T,F,S} + set = MOI.get(model, MOI.ConstraintSet(), bridge) + polynomial = convert(F, func) + constant = + MOI.Utilities.supports_shift_constant(S) ? polynomial.constant : zero(T) + polynomial, set = MOI.Utilities.normalize_constant( + polynomial, + set; + allow_modify_function = true, + ) + MOI.set(model, MOI.ConstraintFunction(), bridge.constraint, polynomial) + MOI.set(model, MOI.ConstraintSet(), bridge.constraint, set) + bridge.constant = constant + return +end + +function MOI.set( + model::MOI.ModelLike, + attr::MOI.ConstraintSet, + bridge::PolynomialFunctionBridge{T,F,S}, + set::S, +) where {T,F,S} + if MOI.Utilities.supports_shift_constant(S) + set = MOI.Utilities.shift_constant(set, -bridge.constant) + end + MOI.set(model, attr, bridge.constraint, set) + return +end + +function MOI.get( + model::MOI.ModelLike, + attr::Union{MOI.ConstraintPrimal,MOI.ConstraintPrimalStart}, + bridge::PolynomialFunctionBridge, +) + value = MOI.get(model, attr, bridge.constraint) + return value === nothing ? nothing : value + bridge.constant +end + +function MOI.set( + model::MOI.ModelLike, + attr::MOI.ConstraintPrimalStart, + bridge::PolynomialFunctionBridge, + value, +) + shifted = value === nothing ? nothing : value - bridge.constant + MOI.set(model, attr, bridge.constraint, shifted) + return +end + +""" + PolynomialFunctions{T}(model) + +Wrap `model` in a constraint `SingleBridgeOptimizer` that lowers typed polynomial +functions. To retain ordinary bridge selection, register +`PolynomialFunctionBridge{T}` with `MOI.Bridges.add_bridge` instead. +""" +const PolynomialFunctions{T,OT<:MOI.ModelLike} = + MOI.Bridges.Constraint.SingleBridgeOptimizer{PolynomialFunctionBridge{T},OT} diff --git a/src/Bridges/polynomial_function.jl b/src/Bridges/polynomial_function.jl new file mode 100644 index 0000000..041ea78 --- /dev/null +++ b/src/Bridges/polynomial_function.jl @@ -0,0 +1,48 @@ +# 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. + +const _PolynomialTarget = + Union{MOI.ScalarAffineFunction,MOI.ScalarQuadraticFunction} + +function Base.convert( + ::Type{F}, + func::PolynomialFunction{F}, +) where {F<:_PolynomialTarget} + return _build_function(F, func.func, Any[]) +end + +function Base.convert( + ::Type{PolynomialFunction{F}}, + func::F, +) where {F<:_PolynomialTarget} + return PolynomialFunction{F}(convert(MOI.ScalarNonlinearFunction, func)) +end + +function Base.convert( + ::Type{PolynomialFunction{F}}, + func::MOI.ScalarNonlinearFunction, +) where {F<:_PolynomialTarget} + return PolynomialFunction{F}(func) +end + +# Unrelated MOI bridges cannot operate directly on this structured wrapper. +# The concrete-target objective conversion below handles it explicitly. +function MOI.Utilities.is_coefficient_type(::Type{<:PolynomialFunction}, ::Type) + return false +end + +function MOI.Bridges.Constraint.conversion_cost( + ::Type{F}, + ::Type{PolynomialFunction{F}}, +) where {F<:_PolynomialTarget} + return 1.0 +end + +function MOI.Bridges.Objective.supports_objective_function( + ::Type{<:MOI.Bridges.Objective.FunctionConversionBridge{T,F}}, + ::Type{PolynomialFunction{G}}, +) where {T,F<:MOI.AbstractFunction,G<:_PolynomialTarget} + return F === G && MOI.Utilities.is_coefficient_type(G, T) +end diff --git a/src/GenOpt.jl b/src/GenOpt.jl index fb0ae2d..d994b94 100644 --- a/src/GenOpt.jl +++ b/src/GenOpt.jl @@ -8,6 +8,7 @@ module GenOpt import MutableArithmetics as MA include("MOI_wrapper.jl") +include("polynomial.jl") include("Bridges/Bridges.jl") include("JuMP_wrapper.jl") diff --git a/src/operators.jl b/src/operators.jl index 3bbdfa9..180203f 100644 --- a/src/operators.jl +++ b/src/operators.jl @@ -83,6 +83,10 @@ struct IteratorValues value_index::Int end +function _expand_filter(value::IteratorValues, values) + return values[value.index.value][value.value_index] +end + function Base.show(io::IO, i::IteratorValues) print(io, "iterator(") print(io, getindex.(i.iterators[i.index.value].values, i.value_index)) @@ -322,6 +326,8 @@ const _AnyLazySum{E,V} = Union{LazySum{E,V},FilteredLazySum{E,V}} JuMP._is_real(::_AnyLazySum) = true JuMP.variable_ref_type(s::_AnyLazySum) = JuMP.variable_ref_type(s.expr) +JuMP.variable_ref_type(::Type{<:_AnyLazySum{E,V}}) where {E,V} = V +_variable_ref_type(::_AnyLazySum{<:Real}) = nothing # `JuMP.:+(::AbstractJuMPScalar, ::AbstractJuMPScalar)` calls `iszero` which # defaults to `x == zero(x)`. A `LazySum` is never simplified away so we @@ -333,16 +339,16 @@ function JuMP.check_belongs_to_model(s::_AnyLazySum, model::JuMP.AbstractModel) return _check_belongs_to_model(s.expr, model) end -function MA.promote_operation( - ::Union{typeof(+),typeof(-),typeof(*),MA.AddSubMul}, - ::Type{<:JuMP._GenericAffOrQuadExpr{T,V}}, - ::Type{<:_AnyLazySum{E,V}}, -) where {T,E,V} - return JuMP.GenericNonlinearExpr{V} +_sum_function_type(::Type{E}) where {E} = JuMP.moi_function_type(E) + +# Numeric summands have no standalone MOI numeric function type. Keep their +# raw template nonlinear; the outer polynomial tag supplies a coefficient type. +function _sum_function_type(::Type{E}) where {E<:Real} + return MOI.ScalarNonlinearFunction end -function JuMP.moi_function(s::LazySum{E}) where {E} - return SumGenerator{JuMP.moi_function_type(E)}( +function _raw_moi_function(s::LazySum{E}) where {E} + return SumGenerator{_sum_function_type(E)}( JuMP.moi_function(s.expr), s.iterators, ) @@ -358,8 +364,15 @@ function JuMP.jump_function_type( } end -function JuMP.moi_function(s::FilteredLazySum{E}) where {E} - return FilteredSumGenerator{JuMP.moi_function_type(E)}( +function JuMP.jump_function(model, f::SumGenerator{F}) where {F} + E = JuMP.jump_function_type(model, F) + return LazySum( + ExprTemplate{E}(JuMP.jump_function(model, f.func), f.iterators), + ) +end + +function _raw_moi_function(s::FilteredLazySum{E}) where {E} + return FilteredSumGenerator{_sum_function_type(E)}( JuMP.moi_function(s.expr), s.iterators, s.filter, @@ -376,6 +389,247 @@ function JuMP.jump_function_type( } end +function JuMP.jump_function(model, f::FilteredSumGenerator{F}) where {F} + E = JuMP.jump_function_type(model, F) + template = ExprTemplate{E}(JuMP.jump_function(model, f.func), f.iterators) + return FilteredLazySum(template, f.filter) +end + +_polynomial_target_type(::Type, ::Type) = nothing +function _polynomial_target_type( + ::Type{E}, + ::Type{V}, +) where {E<:Union{Real,JuMP.AbstractVariableRef},V} + return MOI.ScalarAffineFunction{JuMP.value_type(V)} +end +function _polynomial_target_type( + ::Type{E}, + ::Type, +) where {E<:JuMP._GenericAffOrQuadExpr} + return JuMP.moi_function_type(E) +end + +function JuMP.moi_function(s::_AnyLazySum{E,V}) where {E,V} + raw = _raw_moi_function(s) + F = _polynomial_target_type(E, V) + if F === nothing + return raw + end + return PolynomialFunction{F}(MOI.ScalarNonlinearFunction(:+, Any[raw])) +end + +function JuMP.moi_function_type(::Type{LazySum{E,V}}) where {E,V} + F = _polynomial_target_type(E, V) + return F === nothing ? SumGenerator{_sum_function_type(E)} : + PolynomialFunction{F} +end + +function JuMP.moi_function_type(::Type{FilteredLazySum{E,V}}) where {E,V} + F = _polynomial_target_type(E, V) + return F === nothing ? FilteredSumGenerator{_sum_function_type(E)} : + PolynomialFunction{F} +end + +""" + PolynomialExpr{E,V} + +A scalar expression whose structured nonlinear tree is known to have the +polynomial degree represented by JuMP expression type `E`. +""" +struct PolynomialExpr{E,V<:JuMP.AbstractVariableRef} <: JuMP.AbstractJuMPScalar + expr::JuMP.GenericNonlinearExpr{V} +end + +function PolynomialExpr{E}(expr::JuMP.GenericNonlinearExpr{V}) where {E,V} + return PolynomialExpr{E,V}(expr) +end + +const _StructuredScalar = Union{_AnyLazySum,PolynomialExpr} + +_type(::Type{<:_AnyLazySum{E}}) where {E} = E +_type(::Type{<:PolynomialExpr{E}}) where {E} = E +_type(::Type{E}) where {E} = E +_type(::PolynomialExpr{E}) where {E} = E +_type(::_AnyLazySum{E}) where {E} = E +_expr(f::PolynomialExpr) = f.expr +_variable_ref_type(::PolynomialExpr{<:Real}) = nothing +JuMP.variable_ref_type(::Type{PolynomialExpr{E,V}}) where {E,V} = V +JuMP._is_real(::PolynomialExpr) = true +Base.iszero(::PolynomialExpr) = false +JuMP.owner_model(f::PolynomialExpr) = JuMP.owner_model(f.expr) +function JuMP.check_belongs_to_model( + f::PolynomialExpr, + model::JuMP.AbstractModel, +) + return JuMP.check_belongs_to_model(f.expr, model) +end +function JuMP.function_string(mime, f::PolynomialExpr) + return JuMP.function_string(mime, f.expr) +end + +function JuMP.moi_function(f::PolynomialExpr{E,V}) where {E,V} + return PolynomialFunction{_polynomial_target_type(E, V)}( + JuMP.moi_function(f.expr), + ) +end +function JuMP.moi_function_type(::Type{PolynomialExpr{E,V}}) where {E,V} + return PolynomialFunction{_polynomial_target_type(E, V)} +end +function JuMP.jump_function_type(model, ::Type{PolynomialFunction{F}}) where {F} + return PolynomialExpr{ + JuMP.jump_function_type(model, F), + JuMP.variable_ref_type(model), + } +end +function JuMP.jump_function(model, f::PolynomialFunction{F}) where {F} + return PolynomialExpr{JuMP.jump_function_type(model, F)}( + JuMP.jump_function(model, f.func), + ) +end + +function _structured_result( + ::Type{E}, + expr::JuMP.GenericNonlinearExpr{V}, +) where {E,V} + if _polynomial_target_type(E, V) === nothing + return expr + end + return PolynomialExpr{E,V}(expr) +end + +function _structured_univariate(f::F, op, x) where {F} + V = JuMP.variable_ref_type(x) + expr = JuMP.GenericNonlinearExpr{V}(op, _expr(x)) + if op === :- + return _structured_result(MA.promote_operation(-, _type(x)), expr) + end + return expr +end + +function _structured_multivariate(f::F, op, x, y) where {F} + V = something( + _variable_ref_type(x), + _variable_ref_type(y), + JuMP.VariableRef, + ) + T = JuMP.value_type(V) + a, b = _expr(x), _expr(y) + a = a isa Real ? convert(T, a) : a + b = b isa Real && op !== :^ ? convert(T, b) : b + expr = JuMP.GenericNonlinearExpr{V}(op, a, b) + if op === :^ && y isa Real && y == 1 + return _structured_result(_type(x), expr) + elseif op === :^ && y isa Real && y == 2 + return _structured_result( + MA.promote_operation(*, _type(x), _type(x)), + expr, + ) + elseif op === :+ || op === :- || op === :* || (op === :/ && y isa Real) + return _structured_result( + MA.promote_operation(f, _type(x), _type(y)), + expr, + ) + end + return expr +end + +for f in MOI.Nonlinear.DEFAULT_UNIVARIATE_OPERATORS + if f !== :+ && isdefined(Base, f) + @eval function Base.$f(x::_StructuredScalar) + return _structured_univariate($f, $(QuoteNode(f)), x) + end + end +end + +for f in (:+, :-, :*, :/, :^, :atan, :min, :max) + op = QuoteNode(f) + @eval begin + function Base.$f(x::_StructuredScalar, y::Real) + return _structured_multivariate($f, $op, x, y) + end + function Base.$f(x::Real, y::_StructuredScalar) + return _structured_multivariate($f, $op, x, y) + end + function Base.$f(x::_StructuredScalar, y::JuMP.AbstractJuMPScalar) + return _structured_multivariate($f, $op, x, y) + end + function Base.$f(x::JuMP.AbstractJuMPScalar, y::_StructuredScalar) + return _structured_multivariate($f, $op, x, y) + end + function Base.$f(x::_StructuredScalar, y::_StructuredScalar) + return _structured_multivariate($f, $op, x, y) + end + function Base.$f(x::_ScalarWithIterator, y::_StructuredScalar) + return _multivariate($f, $op, x, y) + end + function Base.$f(x::_StructuredScalar, y::_ScalarWithIterator) + return _multivariate($f, $op, x, y) + end + end +end + +_structured_variable_ref_type(::Type{<:Real}) = nothing +_structured_variable_ref_type(::Type{<:_AnyLazySum{<:Real}}) = nothing +_structured_variable_ref_type(::Type{<:PolynomialExpr{<:Real}}) = nothing +function _structured_variable_ref_type( + ::Type{X}, +) where {X<:JuMP.AbstractJuMPScalar} + return JuMP.variable_ref_type(X) +end + +Base.:^(::Irrational{:ℯ}, y::_StructuredScalar) = exp(y) + +function _structured_promote(f, ::Type{X}, ::Type{Y}) where {X,Y} + V = something( + _structured_variable_ref_type(X), + _structured_variable_ref_type(Y), + JuMP.VariableRef, + ) + E = MA.promote_operation(f, _type(X), _type(Y)) + return _polynomial_target_type(E, V) === nothing ? + JuMP.GenericNonlinearExpr{V} : PolynomialExpr{E,V} +end + +for op in (+, -, *) + @eval begin + function MA.promote_operation( + ::typeof($op), + ::Type{X}, + ::Type{Y}, + ) where {X<:_StructuredScalar,Y<:Union{Real,JuMP.AbstractJuMPScalar}} + return _structured_promote($op, X, Y) + end + function MA.promote_operation( + ::typeof($op), + ::Type{X}, + ::Type{Y}, + ) where {X<:Union{Real,JuMP.AbstractJuMPScalar},Y<:_StructuredScalar} + return _structured_promote($op, X, Y) + end + function MA.promote_operation( + ::typeof($op), + ::Type{X}, + ::Type{Y}, + ) where {X<:_StructuredScalar,Y<:_StructuredScalar} + return _structured_promote($op, X, Y) + end + function MA.promote_operation( + ::typeof($op), + ::Type{<:_StructuredScalar}, + ::Type{JuMP.GenericNonlinearExpr{V}}, + ) where {V<:JuMP.AbstractVariableRef} + return JuMP.GenericNonlinearExpr{V} + end + function MA.promote_operation( + ::typeof($op), + ::Type{JuMP.GenericNonlinearExpr{V}}, + ::Type{<:_StructuredScalar}, + ) where {V<:JuMP.AbstractVariableRef} + return JuMP.GenericNonlinearExpr{V} + end + end +end + # From the code: # `lazy_sum(... for j in 1:n if j == i)` # we want to transform the filter into an expression graph `==(i, j)` @@ -386,6 +640,10 @@ struct _Filtered{I} iterator::I end +function _expand_filter(value::_Filtered, values) + return _expand_filter(value.iterator, values) +end + Base.getindex(v::Array, i::_Filtered) = _Filtered(_getindex(v, i.iterator)) Base.getindex(d::Dict, i::_Filtered) = _Filtered(_getindex(d, i.iterator)) diff --git a/src/polynomial.jl b/src/polynomial.jl new file mode 100644 index 0000000..9007e15 --- /dev/null +++ b/src/polynomial.jl @@ -0,0 +1,77 @@ +# 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. + +""" + PolynomialFunction{F}(func::MOI.ScalarNonlinearFunction) + +A structured nonlinear expression declared convertible to polynomial type `F`, +either `MOI.ScalarAffineFunction{T}` or `MOI.ScalarQuadraticFunction{T}`. The +expression, including lazy sums, is retained until a receiving optimizer needs +the polynomial representation. Conversion validates the declaration. +""" +struct PolynomialFunction{ + F<:Union{MOI.ScalarAffineFunction,MOI.ScalarQuadraticFunction}, +} <: MOI.AbstractScalarFunction + func::MOI.ScalarNonlinearFunction +end + +function Base.copy(f::PolynomialFunction{F}) where {F} + return PolynomialFunction{F}(copy(f.func)) +end + +function Base.isapprox(a::PolynomialFunction, b::PolynomialFunction; kwargs...) + return isapprox(a.func, b.func; kwargs...) +end + +function MOI.Utilities.map_indices( + index_map::I, + f::PolynomialFunction{F}, +) where {I<:Function,F} + return PolynomialFunction{F}(MOI.Utilities.map_indices(index_map, f.func)) +end + +function MOI.Utilities.is_canonical(f::PolynomialFunction) + return MOI.Utilities.is_canonical(f.func) +end + +function MOI.Utilities.canonicalize!(f::PolynomialFunction) + MOI.Utilities.canonicalize!(f.func) + return f +end + +MOI.constant(::PolynomialFunction, ::Type{T}) where {T} = zero(T) +function MOI.constant( + ::PolynomialFunction{MOI.ScalarAffineFunction{T}}, +) where {T} + return zero(T) +end +function MOI.constant( + ::PolynomialFunction{MOI.ScalarQuadraticFunction{T}}, +) where {T} + return zero(T) +end + +function Base.isapprox(a::SumGenerator, b::SumGenerator; kwargs...) + return isapprox(a.func, b.func; kwargs...) && + length(a.iterators) == length(b.iterators) && + all( + ai.values == bi.values for + (ai, bi) in zip(a.iterators, b.iterators) + ) +end + +function Base.isapprox( + a::FilteredSumGenerator, + b::FilteredSumGenerator; + kwargs..., +) + return a.filter === b.filter && + isapprox(a.func, b.func; kwargs...) && + length(a.iterators) == length(b.iterators) && + all( + ai.values == bi.values for + (ai, bi) in zip(a.iterators, b.iterators) + ) +end diff --git a/test/Bridges/polynomial_builder.jl b/test/Bridges/polynomial_builder.jl new file mode 100644 index 0000000..b4373f5 --- /dev/null +++ b/test/Bridges/polynomial_builder.jl @@ -0,0 +1,447 @@ +# 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 TestPolynomialBuilder + +using Test +import GenOpt +import MathOptInterface as MOI + +_snf(head, args...) = MOI.ScalarNonlinearFunction(head, Any[args...]) + +function _variable_sum(indices) + return GenOpt.SumGenerator{MOI.VariableIndex}( + _snf( + :getindex, + GenOpt.ContiguousArrayOfVariables(0, (3,)), + GenOpt.IteratorIndex(1), + ), + GenOpt.Iterator[GenOpt.Iterator(indices)], + ) +end + +function _build(::Type{F}, expression) where {F} + return @inferred GenOpt._build_function(F, expression, Any[]) +end + +function test_affine_and_wrapped_sums() + x = MOI.VariableIndex.(1:3) + sum = _variable_sum([1, 3]) + for T in (Float32, Float64) + F = MOI.ScalarAffineFunction{T} + expected = MOI.ScalarAffineFunction( + [MOI.ScalarAffineTerm(one(T), xi) for xi in x[[1, 3]]], + zero(T), + ) + @test _build(F, sum) ≈ expected + expression = _snf(:+, sum, T(2)) + wrapped = GenOpt.PolynomialFunction{F}(expression) + expected.constant = T(2) + @test _build(F, wrapped) ≈ expected + @test _build(F, _snf(:-, wrapped)) ≈ + MOI.Utilities.operate(-, T, expected) + @test _build(F, _snf(:/, wrapped, T(2))) ≈ + MOI.Utilities.operate(/, T, expected, T(2)) + for exponent in (1, one(T)) + @test _build(F, _snf(:^, wrapped, exponent)) ≈ expected + end + end + return +end + +function test_quadratic_sums_and_products() + x = MOI.VariableIndex.(1:3) + left, right = _variable_sum([1, 2]), _variable_sum([2, 3]) + for T in (Float32, Float64) + F = MOI.ScalarQuadraticFunction{T} + square_sum = + GenOpt.SumGenerator{F}(_snf(:^, left.func, 2), left.iterators) + expected = MOI.ScalarQuadraticFunction( + [MOI.ScalarQuadraticTerm(T(2), xi, xi) for xi in x[1:2]], + MOI.ScalarAffineTerm{T}[], + zero(T), + ) + @test _build(F, square_sum) ≈ expected + product = _snf(:*, left, right) + expected = MOI.ScalarQuadraticFunction( + [ + MOI.ScalarQuadraticTerm(one(T), x[1], x[2]), + MOI.ScalarQuadraticTerm(one(T), x[1], x[3]), + MOI.ScalarQuadraticTerm(T(2), x[2], x[2]), + MOI.ScalarQuadraticTerm(one(T), x[2], x[3]), + ], + MOI.ScalarAffineTerm{T}[], + zero(T), + ) + @test _build(F, product) ≈ expected + square = _snf(:^, left, 2) + expected = MOI.ScalarQuadraticFunction( + [ + MOI.ScalarQuadraticTerm(T(2), x[1], x[1]), + MOI.ScalarQuadraticTerm(T(2), x[1], x[2]), + MOI.ScalarQuadraticTerm(T(2), x[2], x[2]), + ], + MOI.ScalarAffineTerm{T}[], + zero(T), + ) + @test _build(F, square) ≈ expected + tagged = GenOpt.PolynomialFunction{F}(square) + @test _build(F, tagged) ≈ expected + @test _build(F, _snf(:/, tagged, T(2))) ≈ + MOI.Utilities.operate(/, T, expected, T(2)) + @test _build(F, _snf(:^, tagged, one(T))) ≈ expected + end + return +end + +function test_constant_sum_coefficients() + x = MOI.VariableIndex(1) + for T in (Float32, Float64) + F = MOI.ScalarAffineFunction{T} + data = T[nextfloat(one(T)), 2, 3] + sum = GenOpt.SumGenerator{F}( + _snf(:getindex, data, GenOpt.IteratorIndex(1)), + GenOpt.Iterator[GenOpt.Iterator([1, 2, 3])], + ) + for (coefficient, expected) in ( + (_snf(:+, sum, one(T)), Base.sum(data) + one(T)), + (_snf(:sin, sum), sin(Base.sum(data))), + ) + @test GenOpt._try_const(T, coefficient, Any[]) === expected + expression = _snf(:*, coefficient, x) + reference = MOI.ScalarAffineFunction( + [MOI.ScalarAffineTerm(expected, x)], + zero(T), + ) + @test _build(F, expression) ≈ reference + wrapped = GenOpt.PolynomialFunction{F}(coefficient) + @test GenOpt._try_const(T, wrapped, Any[]) === expected + @test _build(F, _snf(:*, wrapped, x)) ≈ reference + divisor = _snf(:+, sum, one(T)) + reference = MOI.ScalarAffineFunction( + [ + MOI.ScalarAffineTerm( + T(one(T) / (Base.sum(data) + one(T))), + x, + ), + ], + zero(T), + ) + @test _build(F, _snf(:/, x, divisor)) ≈ reference + end + empty_sum = GenOpt.SumGenerator{F}( + sum.func, + GenOpt.Iterator[GenOpt.Iterator(Int[])], + ) + @test GenOpt._try_const(T, empty_sum, Any[]) === zero(T) + @test _build(F, empty_sum) ≈ convert(F, zero(T)) + end + return +end + +function test_filtered_sums() + sum = _variable_sum([1, 2, 3]) + for T in (Float32, Float64), + F in (MOI.ScalarAffineFunction{T}, MOI.ScalarQuadraticFunction{T}) + + for (value, expected) in ((2, MOI.VariableIndex(2)), (4, zero(T))) + filtered = GenOpt.FilteredSumGenerator{MOI.VariableIndex}( + sum.func, + sum.iterators, + GenOpt.FilterExpression( + :(==), + Any[GenOpt.IteratorIndex(1), value], + ), + ) + @test _build(F, filtered) ≈ convert(F, expected) + end + i = GenOpt.iterator([1, 2, 3]) + wrapped_index = _snf(:getindex, GenOpt.IteratorIndex(1), 1) + filtered = GenOpt.FilteredSumGenerator{MOI.VariableIndex}( + _snf( + :getindex, + GenOpt.ContiguousArrayOfVariables(0, (3,)), + wrapped_index, + ), + i.iterators, + GenOpt.FilterExpression(:(==), Any[GenOpt._Filtered(i), 2]), + ) + @test _build(F, filtered) ≈ convert(F, MOI.VariableIndex(2)) + excluded = GenOpt.FilteredSumGenerator{MOI.VariableIndex}( + sum.func, + sum.iterators, + GenOpt.FilterExpression( + :!, + Any[GenOpt.FilterExpression( + :(==), + Any[GenOpt.IteratorIndex(1), 2], + )], + ), + ) + expected = MOI.ScalarAffineFunction( + [ + MOI.ScalarAffineTerm(one(T), MOI.VariableIndex(i)) for + i in (1, 3) + ], + zero(T), + ) + @test _build(F, excluded) ≈ convert(F, expected) + end + return +end + +function test_sum_domain_shapes() + for T in (Float32, Float64) + F = MOI.ScalarAffineFunction{T} + constant = GenOpt.SumGenerator{F}(_snf(:+, T(2)), GenOpt.Iterator[]) + @test _build(F, constant) ≈ convert(F, T(2)) + sum = GenOpt.SumGenerator{MOI.VariableIndex}( + _snf( + :getindex, + GenOpt.ContiguousArrayOfVariables(0, (1, 3)), + GenOpt.IteratorIndex(1), + GenOpt.IteratorIndex(2), + ), + GenOpt.Iterator[GenOpt.Iterator([1]), GenOpt.Iterator([1, 3])], + ) + expected = MOI.ScalarAffineFunction( + [ + MOI.ScalarAffineTerm(one(T), MOI.VariableIndex(i)) for + i in (1, 3) + ], + zero(T), + ) + @test _build(F, sum) ≈ expected + end + return +end + +function test_filter_scope_validation() + for T in (Float32, Float64), axis in ([1, 2], Int[]) + F = MOI.ScalarAffineFunction{T} + inner = GenOpt.iterator(axis) + outer = GenOpt.iterator([1, 2]) + index = _snf(:getindex, GenOpt.IteratorIndex(1), 1) + sum = GenOpt.FilteredSumGenerator{MOI.VariableIndex}( + _snf(:getindex, GenOpt.ContiguousArrayOfVariables(0, (3,)), index), + inner.iterators, + GenOpt.FilterExpression(:(==), Any[inner, GenOpt._Filtered(outer)]), + ) + # Both iterators use ordinal 1, but have distinct binding identities. + # Treating the outer iterator as local would silently select all terms. + @test_throws r"Correlated lazy-sum filters" _build(F, sum) + generator = GenOpt.FunctionGenerator{F}(_snf(:+, sum), outer.iterators) + model = MOI.Utilities.Model{T}() + MOI.add_variables(model, 3) + @test_throws r"Correlated lazy-sum filters" GenOpt.add_constraints( + model, + generator, + MOI.LessThan(zero(T)), + ) + end + for T in (Float32, Float64) + F = MOI.ScalarAffineFunction{T} + selected = GenOpt.iterator([1, 2, 3]) + other = GenOpt.iterator([1]) + sum = GenOpt.FilteredSumGenerator{MOI.VariableIndex}( + _snf( + :getindex, + GenOpt.ContiguousArrayOfVariables(0, (3,)), + _snf(:getindex, GenOpt.IteratorIndex(2), 1), + ), + GenOpt.Iterator[only(other.iterators), only(selected.iterators)], + GenOpt.FilterExpression(:(==), Any[selected, 2]), + ) + # A local reference may have a different ordinal in its source domain. + @test _build(F, sum) ≈ convert(F, MOI.VariableIndex(2)) + end + return +end + +function test_nested_iterator_scopes() + x = MOI.VariableIndex.(1:3) + inner = _variable_sum([1, 3]) + outer = _variable_sum([2, 3]) + for T in (Float32, Float64) + F = MOI.ScalarQuadraticFunction{T} + nested = + GenOpt.SumGenerator{F}(_snf(:*, outer.func, inner), outer.iterators) + expected = MOI.ScalarQuadraticFunction( + [ + MOI.ScalarQuadraticTerm(one(T), x[2], x[1]), + MOI.ScalarQuadraticTerm(one(T), x[2], x[3]), + MOI.ScalarQuadraticTerm(one(T), x[3], x[1]), + MOI.ScalarQuadraticTerm(T(2), x[3], x[3]), + ], + MOI.ScalarAffineTerm{T}[], + zero(T), + ) + @test _build(F, nested) ≈ expected + @test GenOpt._build_function(F, nested, Any[99]) ≈ expected + affine = MOI.ScalarAffineFunction{T} + generator = GenOpt.FunctionGenerator{affine}( + _snf(:-, inner, outer.func), + outer.iterators, + ) + model = MOI.Utilities.Model{T}() + MOI.add_variables(model, 3) + rows = GenOpt.add_constraints(model, generator, MOI.LessThan(zero(T))) + @test length(rows) == 2 + for (row, variable) in zip(rows, x[2:3]) + reference = MOI.ScalarAffineFunction( + [ + MOI.ScalarAffineTerm(one(T), x[1]), + MOI.ScalarAffineTerm(one(T), x[3]), + MOI.ScalarAffineTerm(-one(T), variable), + ], + zero(T), + ) + @test MOI.get(model, MOI.ConstraintFunction(), row) ≈ reference + end + end + return +end + +function test_incompatible_polynomial_promises() + sum = _variable_sum([1, 2]) + for T in (Float32, Float64) + affine = MOI.ScalarAffineFunction{T} + quadratic = MOI.ScalarQuadraticFunction{T} + square = _snf(:*, sum, sum) + @test_throws InexactError _build( + affine, + GenOpt.PolynomialFunction{affine}(square), + ) + cubic = _snf(:*, square, sum) + @test_throws InexactError _build( + quadratic, + GenOpt.PolynomialFunction{quadratic}(cubic), + ) + for F in (affine, quadratic) + @test_throws InexactError _build( + F, + _snf(:/, sum, MOI.VariableIndex(3)), + ) + end + end + return +end + +function test_wrapped_iterator_index_chain() + expression = _snf(:getindex, GenOpt.IteratorIndex(1), 1) + values = Any[GenOpt.IteratorIndex(2), (2,)] + @test @inferred(GenOpt._eval_index(expression, values)) === 2.0 + return +end + +function test_literal_exponent_types() + for (value, unit, square) in ( + (0, false, false), + (1, true, false), + (2, false, true), + (0.0, false, false), + (1.0, true, false), + (2.0, false, true), + (0.0f0, false, false), + (1.0f0, true, false), + (2.0f0, false, true), + (1 // 1, true, false), + (2 // 1, false, true), + (MOI.VariableIndex(1), false, false), + ) + @test (@inferred GenOpt._is_unit_exponent(value)) === unit + @test (@inferred GenOpt._is_square_exponent(value)) === square + end + sum = _variable_sum([1, 2]) + for T in (Float32, Float64) + affine = MOI.ScalarAffineFunction( + [MOI.ScalarAffineTerm(one(T), MOI.VariableIndex(i)) for i in 1:2], + zero(T), + ) + for exponent in (1.0, 1.0f0), + F in (MOI.ScalarAffineFunction{T}, MOI.ScalarQuadraticFunction{T}) + + @test _build(F, _snf(:^, sum, exponent)) ≈ convert(F, affine) + end + quadratic = MOI.ScalarQuadraticFunction( + [ + MOI.ScalarQuadraticTerm( + T(2), + MOI.VariableIndex(1), + MOI.VariableIndex(1), + ), + MOI.ScalarQuadraticTerm( + T(2), + MOI.VariableIndex(1), + MOI.VariableIndex(2), + ), + MOI.ScalarQuadraticTerm( + T(2), + MOI.VariableIndex(2), + MOI.VariableIndex(2), + ), + ], + MOI.ScalarAffineTerm{T}[], + zero(T), + ) + for exponent in (2.0, 2.0f0) + @test _build(typeof(quadratic), _snf(:^, sum, exponent)) ≈ quadratic + end + end + return +end + +function test_constant_sum_integer_precision() + F = MOI.ScalarAffineFunction{BigFloat} + large = Int64(2)^53 + 1 + sum = GenOpt.SumGenerator{F}( + _snf(:getindex, [large, Int64(2)], GenOpt.IteratorIndex(1)), + GenOpt.Iterator[GenOpt.Iterator([1, 2])], + ) + expected = BigFloat(large) + BigFloat(2) + @test GenOpt._try_const(BigFloat, sum, Any[]) == expected + lowered = _build(F, _snf(:*, sum, MOI.VariableIndex(1))) + @test only(lowered.terms).coefficient == expected + @test only(lowered.terms).coefficient isa BigFloat + for polynomial in ( + MOI.ScalarAffineFunction( + [MOI.ScalarAffineTerm(1.0, MOI.VariableIndex(1))], + 0.0, + ), + MOI.ScalarQuadraticFunction( + [ + MOI.ScalarQuadraticTerm( + 2.0, + MOI.VariableIndex(1), + MOI.VariableIndex(1), + ), + ], + MOI.ScalarAffineTerm{Float64}[], + 0.0, + ), + ) + embedded = GenOpt.SumGenerator{typeof(polynomial)}( + _snf(:+, polynomial), + GenOpt.Iterator[], + ) + @test GenOpt._try_const(Float64, embedded, Any[]) === nothing + end + 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 + +TestPolynomialBuilder.runtests() diff --git a/test/Bridges/polynomial_function.jl b/test/Bridges/polynomial_function.jl new file mode 100644 index 0000000..f300049 --- /dev/null +++ b/test/Bridges/polynomial_function.jl @@ -0,0 +1,239 @@ +# 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 TestPolynomialFunctionBridges + +using Test +import GenOpt +import HiGHS +import JuMP +import MathOptInterface as MOI + +function runtests() + for name in names(@__MODULE__; all = true) + if startswith(string(name), "test_") + @testset "$(name)" begin + getfield(@__MODULE__, name)() + end + end + end + return +end + +function _polynomial(::Type{F}, head, args...) where {F} + return GenOpt.PolynomialFunction{F}( + MOI.ScalarNonlinearFunction(head, Any[args...]), + ) +end + +function test_polynomial_conversions() + x = MOI.VariableIndex(1) + for T in (Float32, Float64), + F in (MOI.ScalarAffineFunction{T}, MOI.ScalarQuadraticFunction{T}) + + raw = MOI.ScalarNonlinearFunction(:+, Any[x, T(2)]) + func = @inferred convert(GenOpt.PolynomialFunction{F}, raw) + @test func.func === raw + native = @inferred convert(F, func) + @test native isa F + @test native ≈ convert( + F, + MOI.ScalarAffineFunction([MOI.ScalarAffineTerm(one(T), x)], T(2)), + ) + reconstructed = @inferred convert(GenOpt.PolynomialFunction{F}, native) + @test convert(F, reconstructed) ≈ native + @test !MOI.Utilities.is_coefficient_type(typeof(func), T) + @test MOI.Bridges.Constraint.conversion_cost(F, typeof(func)) == 1.0 + end + @test isinf( + MOI.Bridges.Constraint.conversion_cost( + MOI.ScalarAffineFunction{Float64}, + MOI.ScalarNonlinearFunction, + ), + ) + invalid = _polynomial(MOI.ScalarAffineFunction{Float64}, :*, x, x) + @test_throws InexactError convert( + MOI.ScalarAffineFunction{Float64}, + invalid, + ) + return +end + +function test_polynomial_constraint_attributes() + for T in (Float32, Float64), + F in (MOI.ScalarAffineFunction{T}, MOI.ScalarQuadraticFunction{T}) + + inner = MOI.Utilities.MockOptimizer( + MOI.Utilities.UniversalFallback(MOI.Utilities.Model{T}()), + T, + ) + model = GenOpt.PolynomialFunctions{T}(inner) + x = MOI.add_variables(model, 2) + func = _polynomial( + F, + :+, + MOI.ScalarNonlinearFunction(:*, Any[T(2), x[1]]), + x[2], + T(3), + ) + set = MOI.LessThan(T(10)) + @test MOI.supports_constraint(model, typeof(func), typeof(set)) + ci = MOI.add_constraint(model, func, set) + bridge = MOI.Bridges.bridge(model, ci) + @test bridge isa GenOpt.PolynomialFunctionBridge{T,F,typeof(set)} + @test MOI.get(bridge, MOI.NumberOfConstraints{F,typeof(set)}()) == 1 + @test MOI.get(bridge, MOI.ListOfConstraintIndices{F,typeof(set)}()) == + [bridge.constraint] + @test MOI.get(inner, MOI.ConstraintFunction(), bridge.constraint).constant === + zero(T) + @test MOI.get(inner, MOI.ConstraintSet(), bridge.constraint) == + MOI.LessThan(T(7)) + @test MOI.get(model, MOI.ConstraintSet(), ci) == set + @test convert(F, MOI.get(model, MOI.ConstraintFunction(), ci)) ≈ + convert(F, func) + MOI.set(model, MOI.ConstraintPrimalStart(), ci, nothing) + @test MOI.get(model, MOI.ConstraintPrimalStart(), ci) === nothing + MOI.set(model, MOI.ConstraintPrimalStart(), ci, T(9)) + @test MOI.get(inner, MOI.ConstraintPrimalStart(), bridge.constraint) === + T(6) + @test MOI.get(model, MOI.ConstraintPrimalStart(), ci) === T(9) + MOI.set(model, MOI.ConstraintDualStart(), ci, T(2)) + @test MOI.get(model, MOI.ConstraintDualStart(), ci) === T(2) + MOI.Utilities.mock_optimize!(inner, T[1, 2], (F, typeof(set)) => T[5]) + @test MOI.get(model, MOI.ConstraintPrimal(), ci) === T(7) + @test MOI.get(model, MOI.ConstraintDual(), ci) === T(5) + replacement = _polynomial( + F, + :+, + MOI.ScalarNonlinearFunction(:*, Any[T(3), x[1]]), + x[2], + T(-2), + ) + MOI.set(model, MOI.ConstraintFunction(), ci, replacement) + @test MOI.get(model, MOI.ConstraintSet(), ci) == set + @test MOI.get(inner, MOI.ConstraintSet(), bridge.constraint) == + MOI.LessThan(T(12)) + @test convert(F, MOI.get(model, MOI.ConstraintFunction(), ci)) ≈ + convert(F, replacement) + MOI.set(model, MOI.ConstraintSet(), ci, MOI.LessThan(T(4))) + @test MOI.get(inner, MOI.ConstraintSet(), bridge.constraint) == + MOI.LessThan(T(6)) + @test MOI.get(model, MOI.ConstraintSet(), ci) == MOI.LessThan(T(4)) + MOI.delete(model, x[2]) + expected = convert( + F, + MOI.ScalarAffineFunction([MOI.ScalarAffineTerm(T(3), x[1])], T(-2)), + ) + @test convert(F, MOI.get(model, MOI.ConstraintFunction(), ci)) ≈ + expected + MOI.delete(model, ci) + @test !MOI.is_valid(model, ci) + @test !MOI.is_valid(inner, bridge.constraint) + end + return +end + +function test_polynomial_unshiftable_set() + F = MOI.ScalarAffineFunction{Float64} + inner = MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()) + model = GenOpt.PolynomialFunctions{Float64}(inner) + x = MOI.add_variable(model) + func = _polynomial(F, :+, x, 2.0) + ci = MOI.add_constraint(model, func, MOI.Integer()) + bridge = MOI.Bridges.bridge(model, ci) + @test bridge.constant == 0.0 + @test MOI.get(model, MOI.ConstraintSet(), ci) == MOI.Integer() + @test convert(F, MOI.get(model, MOI.ConstraintFunction(), ci)) ≈ + convert(F, func) + replacement = _polynomial(F, :-, x, 1.0) + MOI.set(model, MOI.ConstraintFunction(), ci, replacement) + MOI.set(model, MOI.ConstraintSet(), ci, MOI.Integer()) + @test MOI.get(model, MOI.ConstraintSet(), ci) == MOI.Integer() + @test convert(F, MOI.get(model, MOI.ConstraintFunction(), ci)) ≈ + convert(F, replacement) + return +end + +function test_polynomial_objective_bridge() + for T in (Float32, Float64), + F in (MOI.ScalarAffineFunction{T}, MOI.ScalarQuadraticFunction{T}) + + inner = MOI.Utilities.MockOptimizer(MOI.Utilities.Model{T}(), T) + model = MOI.Bridges.full_bridge_optimizer(inner, T) + x = MOI.add_variables(model, 2) + func = _polynomial(F, :+, x[1], x[2], T(3)) + attr = MOI.ObjectiveFunction{typeof(func)}() + @test MOI.supports(model, attr) + MOI.set(model, MOI.ObjectiveSense(), MOI.MIN_SENSE) + MOI.set(model, attr, func) + @test MOI.get(inner, MOI.ObjectiveFunctionType()) == F + @test MOI.get(model, MOI.ObjectiveFunctionType()) == typeof(func) + @test convert(F, MOI.get(model, attr)) ≈ convert(F, func) + MOI.Utilities.mock_optimize!(inner, T[1, 2]) + @test MOI.get(model, MOI.ObjectiveValue()) === T(6) + MOI.set(model, MOI.ObjectiveSense(), MOI.MAX_SENSE) + @test MOI.get(inner, MOI.ObjectiveSense()) == MOI.MAX_SENSE + MOI.delete(model, x[2]) + expected = convert( + F, + MOI.ScalarAffineFunction( + [MOI.ScalarAffineTerm(one(T), x[1])], + T(3), + ), + ) + @test convert(F, MOI.get(model, attr)) ≈ expected + MOI.set(model, MOI.ObjectiveSense(), MOI.FEASIBILITY_SENSE) + @test isempty(MOI.Bridges.Objective.bridges(model)) + end + return +end + +function test_highs_polynomial_support() + inner = HiGHS.Optimizer() + model = MOI.Bridges.full_bridge_optimizer(inner, Float64) + MOI.Bridges.add_bridge(model, GenOpt.PolynomialFunctionBridge{Float64}) + A = GenOpt.PolynomialFunction{MOI.ScalarAffineFunction{Float64}} + Q = GenOpt.PolynomialFunction{MOI.ScalarQuadraticFunction{Float64}} + S = MOI.LessThan{Float64} + @test MOI.supports_constraint(model, A, S) + @test !MOI.supports_constraint(model, Q, S) + @test MOI.supports(model, MOI.ObjectiveFunction{A}()) + @test MOI.supports(model, MOI.ObjectiveFunction{Q}()) + @test !MOI.supports_constraint(model, MOI.ScalarNonlinearFunction, S) + @test !MOI.supports( + model, + MOI.ObjectiveFunction{MOI.ScalarNonlinearFunction}(), + ) + return +end + +function test_highs_lazy_sum_objectives_and_constraints() + model = JuMP.Model(HiGHS.Optimizer) + JuMP.set_silent(model) + JuMP.add_bridge(model, GenOpt.PolynomialFunctionBridge) + JuMP.@variable(model, x[1:3] >= 0) + affine = GenOpt.lazy_sum(x[i] + 1 for i in 1:3) + JuMP.@constraint(model, affine <= 9) + JuMP.@constraint(model, -GenOpt.lazy_sum(x[i] for i in 1:3) <= -6) + quadratic = GenOpt.lazy_sum((x[i] - i)^2 for i in 1:3) + JuMP.@objective(model, Min, quadratic) + JuMP.optimize!(model) + @test JuMP.termination_status(model) == MOI.OPTIMAL + @test JuMP.value.(x) ≈ [1.0, 2.0, 3.0] atol = 1e-6 + @test JuMP.objective_value(model) ≈ 0.0 atol = 1e-6 + @test MOI.get(JuMP.unsafe_backend(model), MOI.ObjectiveFunctionType()) == + MOI.ScalarQuadraticFunction{Float64} + JuMP.@objective(model, Max, GenOpt.lazy_sum(x[i] for i in 1:3)) + JuMP.optimize!(model) + @test JuMP.termination_status(model) == MOI.OPTIMAL + @test JuMP.objective_value(model) ≈ 6.0 + @test MOI.get(JuMP.unsafe_backend(model), MOI.ObjectiveFunctionType()) == + MOI.ScalarAffineFunction{Float64} + return +end + +end + +TestPolynomialFunctionBridges.runtests() diff --git a/test/Bridges/runtests.jl b/test/Bridges/runtests.jl index 877b5eb..791622a 100644 --- a/test/Bridges/runtests.jl +++ b/test/Bridges/runtests.jl @@ -4,3 +4,5 @@ # in the LICENSE.md file or at https://opensource.org/licenses/MIT. include("Constraint/function_generator.jl") +include("polynomial_builder.jl") +include("polynomial_function.jl") diff --git a/test/ExaModels.jl b/test/ExaModels.jl index e93b2af..2327165 100644 --- a/test/ExaModels.jl +++ b/test/ExaModels.jl @@ -159,6 +159,50 @@ function test_single_sum_objective() return end +function test_typed_sum_structure() + for mixed in (false, true) + model = Model() + @variable(model, x[1:4]) + linear = GenOpt.lazy_sum(i * x[i] for i in 1:4) + quadratic = GenOpt.lazy_sum(x[i]^2 for i in 1:4) + expression = mixed ? linear + quadratic : quadratic + @objective(model, Min, expression) + func = MOI.get( + backend(model), + MOI.ObjectiveFunction{JuMP.moi_function_type(typeof(expression))}(), + ) + @test func isa GenOpt.PolynomialFunction + optimizer = ExaModels.Optimizer(nothing) + set_optimizer(model, () -> optimizer) + MOI.Utilities.attach_optimizer(backend(model)) + @test length(optimizer.objs) == (mixed ? 2 : 1) + @test all(bin -> length(bin.data) == 4, optimizer.objs) + end + return +end + +function test_polynomial_leaf_unwrapping() + extension = Base.get_extension(GenOpt, :GenOptExaModelsExt) + F = MOI.ScalarAffineFunction{Float64} + lookup = MOI.ScalarNonlinearFunction( + :getindex, + Any[GenOpt.ContiguousArrayOfVariables(0, (1,)), 1], + ) + template = MOI.ScalarNonlinearFunction(:+, Any[lookup, 2.0]) + wrapped = GenOpt.PolynomialFunction{F}(template) + @test typeof(extension.exagen(wrapped, nothing)) == + typeof(extension.exagen(template, nothing)) + func = MOI.ScalarNonlinearFunction(:+, Any[MOI.VariableIndex(1), 2.0]) + wrapped = GenOpt.PolynomialFunction{F}(func) + head, data = extension.ExaModelsMOI._exafy(wrapped, (), nothing) + expected_head, expected_data = + extension.ExaModelsMOI._exafy(func, (), nothing) + @test typeof(head) == typeof(expected_head) + @test data == expected_data + @test wrapped.func === func + 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 diff --git a/test/JuliaC/MyApp/src/MyApp.jl b/test/JuliaC/MyApp/src/MyApp.jl index 9e8204b..3fb880b 100644 --- a/test/JuliaC/MyApp/src/MyApp.jl +++ b/test/JuliaC/MyApp/src/MyApp.jl @@ -228,6 +228,60 @@ function check_no_iterators() return end +function check_typed_polynomials() + model = BridgeModel{Float64}() + x = MOI.add_variables(model, 3) + block = GenOpt.ContiguousArrayOfVariables(0, (3,)) + i = GenOpt.IteratorIndex(1) + sum = GenOpt.SumGenerator{Affine}( + snf(:*, i, snf(:getindex, block, i)), + GenOpt.Iterator[GenOpt.Iterator([1, 2, 3])], + ) + affine = GenOpt.PolynomialFunction{Affine}(snf(:+, sum, 1.0)) + lowered = convert(Affine, affine) + @assert lowered.constant == 1.0 + @assert length(lowered.terms) == 3 + @assert [term.coefficient for term in lowered.terms] == [1.0, 2.0, 3.0] + result = MOI.Bridges.Constraint.bridge_constraint( + GenOpt.PolynomialFunctionBridge{Float64,Affine,MOI.LessThan{Float64}}, + model, + affine, + MOI.LessThan(10.0), + ) + @assert MOI.get(model, MOI.ConstraintSet(), result.constraint).upper == 9.0 + @assert MOI.get(model, MOI.ConstraintFunction(), result.constraint).constant == + 0.0 + for exponent in (1, 1.0, 1.0f0) + identity = GenOpt.PolynomialFunction{Affine}(snf(:^, sum, exponent)) + f = convert(Affine, identity) + @assert length(f.terms) == 3 + @assert f.constant == 0.0 + end + for exponent in (2.0, 2.0f0) + square = GenOpt.PolynomialFunction{Quadratic}(snf(:^, sum, exponent)) + @assert length(convert(Quadratic, square).quadratic_terms) == 9 + end + quadratic = GenOpt.PolynomialFunction{Quadratic}(snf(:^, sum, 2)) + objective_bridge = MOI.Bridges.Objective.bridge_objective( + MOI.Bridges.Objective.FunctionConversionBridge{ + Float64, + Quadratic, + typeof(quadratic), + }, + model, + quadratic, + ) + q = MOI.get(model, MOI.ObjectiveFunction{Quadratic}()) + @assert length(q.quadratic_terms) == 9 + @assert isempty(q.affine_terms) + @assert q.constant == 0.0 + @assert MOI.get(objective_bridge, MOI.NumberOfVariables()) == 0 + @assert MOI.get(model, MOI.ConstraintFunction(), result).func isa + MOI.ScalarNonlinearFunction + @assert length(x) == 3 + return +end + function main(args::Vector{String})::Cint check_affine(MOI.GreaterThan{Float64}, MOI.Nonnegatives(3)) check_affine(MOI.LessThan{Float64}, MOI.Nonpositives(3)) @@ -237,6 +291,7 @@ function main(args::Vector{String})::Cint check_quadratic() check_empty() check_no_iterators() + check_typed_polynomials() return 0 end diff --git a/test/operators.jl b/test/operators.jl index 9c3935b..5668124 100644 --- a/test/operators.jl +++ b/test/operators.jl @@ -134,7 +134,9 @@ function test_filtered_sum_moi_utilities() JuMP.@variable(model, x[1:3]) group = [1, 1, 2] lazy = GenOpt.lazy_sum(x[j] for j in 1:3 if group[j] == 1) - generator = JuMP.moi_function(lazy) + polynomial = JuMP.moi_function(lazy) + @test JuMP.moi_function_type(typeof(lazy)) == typeof(polynomial) + generator = only(polynomial.func.args) copied = copy(generator) @test copied isa GenOpt.FilteredSumGenerator @@ -162,6 +164,49 @@ function test_filtered_sum_moi_utilities() return end +function test_lazy_sum_moi_function_type() + model = JuMP.Model() + JuMP.@variable(model, x[1:3]) + lazy = GenOpt.lazy_sum(x[i] for i in 1:3) + @test JuMP.moi_function_type(typeof(lazy)) == + typeof(JuMP.moi_function(lazy)) + constraint = JuMP.@constraint(model, lazy <= 1.0) + @test JuMP.is_valid(model, constraint) + stored = MOI.get( + JuMP.backend(model), + MOI.ConstraintFunction(), + JuMP.index(constraint), + ) + @test stored isa + GenOpt.PolynomialFunction{MOI.ScalarAffineFunction{Float64}} + @test _has_sum(stored) + return +end + +function test_lazy_sum_unary_operators() + model = JuMP.Model() + JuMP.@variable(model, x[1:3]) + sums = ( + GenOpt.lazy_sum(x[i] for i in 1:3), + GenOpt.lazy_sum(x[i] for i in 1:3 if i == 2), + GenOpt.lazy_sum(i + 1 for i in 1:3), + GenOpt.lazy_sum(i + 1 for i in 1:3 if i == 2), + ) + for sum in sums + @test +sum === sum + negative = -sum + @test negative isa GenOpt.PolynomialExpr + @test negative.expr.head == :- + @test only(negative.expr.args) === sum + func = JuMP.moi_function(negative) + @test func.func.head == :- + child = only(func.func.args) + @test typeof(child) == JuMP.moi_function_type(typeof(sum)) + @test only(child.func.args).iterators === sum.iterators + end + return +end + function test_deferred_getindex_map_indices() model = JuMP.Model() JuMP.@variable(model, x[1:2]) @@ -180,12 +225,30 @@ end _data_arrays(::Any) = GenOpt._DataArray[] _data_arrays(a::GenOpt._DataArray) = [a] +function _data_arrays( + f::Union{ + GenOpt.PolynomialFunction, + GenOpt.SumGenerator, + GenOpt.FilteredSumGenerator, + }, +) + return _data_arrays(f.func) +end 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::Union{ + GenOpt.PolynomialFunction, + GenOpt.SumGenerator, + GenOpt.FilteredSumGenerator, + }, +) + return _arrays(f.func) +end function _arrays(f::MOI.ScalarNonlinearFunction) return reduce(vcat, _arrays.(f.args); init = _arrays(nothing)) end @@ -205,7 +268,7 @@ function test_lazy_sum_promotion() JuMP.@variable(model, x[1:3]) s = GenOpt.lazy_sum(x[j] for j in 1:3) @test GenOpt.MA.promote_operation(+, JuMP.AffExpr, typeof(s)) == - JuMP.GenericNonlinearExpr{JuMP.VariableRef} + GenOpt.PolynomialExpr{JuMP.AffExpr,JuMP.VariableRef} return end @@ -366,21 +429,199 @@ function test_lazy_sum_sum() @test b isa GenOpt.LazySum{JuMP.AffExpr,JuMP.VariableRef} JuMP.@objective(model, Min, a + b) F = MOI.get(model, MOI.ObjectiveFunctionType()) - @test F == MOI.ScalarNonlinearFunction - func = MOI.get(model, MOI.ObjectiveFunction{F}()) + @test F == GenOpt.PolynomialFunction{MOI.ScalarQuadraticFunction{Float64}} + func = MOI.get(model, MOI.ObjectiveFunction{F}()).func @test func.head == :+ - @test func.args[1] isa SumGenerator{MOI.ScalarQuadraticFunction{Float64}} - @test func.args[2] isa SumGenerator{MOI.ScalarAffineFunction{Float64}} + @test only(func.args[1].func.args) isa + SumGenerator{MOI.ScalarQuadraticFunction{Float64}} + @test only(func.args[2].func.args) isa + SumGenerator{MOI.ScalarAffineFunction{Float64}} return end _has_filtered_sum(x) = if x isa MOI.ScalarNonlinearFunction any(_has_filtered_sum, x.args) + elseif x isa GenOpt.PolynomialFunction + _has_filtered_sum(x.func) else x isa GenOpt.FilteredSumGenerator end +_has_sum(::Any) = false +_has_sum(::Union{GenOpt.SumGenerator,GenOpt.FilteredSumGenerator}) = true +_has_sum(f::GenOpt.PolynomialFunction) = _has_sum(f.func) +_has_sum(f::MOI.ScalarNonlinearFunction) = any(_has_sum, f.args) + +function test_polynomial_lazy_sum_targets() + for T in (Float32, Float64) + model = JuMP.GenericModel{T}() + JuMP.@variable(model, x[1:3]) + for (sum, F) in ( + (GenOpt.lazy_sum(x[i] for i in 1:3), MOI.ScalarAffineFunction{T}), + ( + GenOpt.lazy_sum(2x[i] + 1 for i in 1:3), + MOI.ScalarAffineFunction{T}, + ), + ( + GenOpt.lazy_sum(x[i]^2 for i in 1:3), + MOI.ScalarQuadraticFunction{T}, + ), + ( + GenOpt.lazy_sum(x[i] for i in 1:3 if i == 2), + MOI.ScalarAffineFunction{T}, + ), + ) + polynomial = @inferred JuMP.moi_function(sum) + @test polynomial isa GenOpt.PolynomialFunction{F} + @test (@inferred MOI.constant(polynomial)) === zero(T) + @test JuMP.moi_function_type(typeof(sum)) == typeof(polynomial) + @test only(polynomial.func.args).iterators === sum.iterators + @test _has_sum(polynomial) + end + nonlinear = GenOpt.lazy_sum(sin(x[i]) for i in 1:3) + @test JuMP.moi_function(nonlinear) isa + GenOpt.SumGenerator{MOI.ScalarNonlinearFunction} + @test JuMP.moi_function_type(typeof(nonlinear)) == + typeof(JuMP.moi_function(nonlinear)) + end + return +end + +function test_polynomial_scalar_arithmetic() + for T in (Float32, Float64) + model = JuMP.GenericModel{T}() + JuMP.@variable(model, x[1:3]) + sum = GenOpt.lazy_sum(x[i] for i in 1:3) + quadratic = GenOpt.lazy_sum(x[i]^2 for i in 1:3) + for (expression, F) in ( + (sum + x[1], MOI.ScalarAffineFunction{T}), + (x[1] + sum, MOI.ScalarAffineFunction{T}), + (sum - 1, MOI.ScalarAffineFunction{T}), + (1 - sum, MOI.ScalarAffineFunction{T}), + (sum * 2, MOI.ScalarAffineFunction{T}), + (2 * sum, MOI.ScalarAffineFunction{T}), + (sum / 2, MOI.ScalarAffineFunction{T}), + (sum + sum, MOI.ScalarAffineFunction{T}), + (sum * x[1], MOI.ScalarQuadraticFunction{T}), + (sum * sum, MOI.ScalarQuadraticFunction{T}), + (sum^1, MOI.ScalarAffineFunction{T}), + (sum^2, MOI.ScalarQuadraticFunction{T}), + (quadratic + sum, MOI.ScalarQuadraticFunction{T}), + ((sum + 1) * x[1], MOI.ScalarQuadraticFunction{T}), + ) + @test expression isa GenOpt.PolynomialExpr + @test JuMP.variable_ref_type(expression) == typeof(x[1]) + @test JuMP.moi_function(expression) isa GenOpt.PolynomialFunction{F} + @test JuMP.moi_function_type(typeof(expression)) == + typeof(JuMP.moi_function(expression)) + @test _has_sum(JuMP.moi_function(expression)) + end + for nonlinear in + (sin(sum), sum^3, sum^x[1], quadratic * x[1], sum / x[1], ℯ^sum) + @test nonlinear isa JuMP.GenericNonlinearExpr + @test JuMP.moi_function(nonlinear) isa MOI.ScalarNonlinearFunction + end + macro_expression = JuMP.@expression(model, 2sum + x[1]) + @test macro_expression isa GenOpt.PolynomialExpr + i = GenOpt.iterator([1, 2]) + V = typeof(x[1]) + @test (sum + x[i]) isa GenOpt.ExprTemplate{JuMP.GenericAffExpr{T,V},V} + @test (sum * i) isa GenOpt.ExprTemplate{JuMP.GenericAffExpr{T,V},V} + @test (sum * x[i]) isa GenOpt.ExprTemplate{JuMP.GenericQuadExpr{T,V},V} + @test (x[i] * (sum + 1)) isa + GenOpt.ExprTemplate{JuMP.GenericQuadExpr{T,V},V} + for op in (+, -, *) + @test GenOpt.MA.promote_operation( + op, + typeof(sum), + typeof(sin(x[1])), + ) == JuMP.GenericNonlinearExpr{V} + @test GenOpt.MA.promote_operation( + op, + typeof(sin(x[1])), + typeof(sum), + ) == JuMP.GenericNonlinearExpr{V} + @test GenOpt.MA.promote_operation(op, Int, typeof(sum)) == + typeof(op(1, sum)) + @test GenOpt.MA.promote_operation(op, typeof(sum), Int) == + typeof(op(sum, 1)) + end + @test GenOpt.MA.promote_operation(*, typeof(quadratic), typeof(x[1])) == + JuMP.GenericNonlinearExpr{V} + end + return +end + +function test_polynomial_function_utilities() + x = MOI.VariableIndex(1) + f = GenOpt.PolynomialFunction{MOI.ScalarAffineFunction{Float64}}( + MOI.ScalarNonlinearFunction(:+, Any[x, 2.0]), + ) + copied = copy(f) + @test copied ≈ f + @test copied.func !== f.func + @test MOI.Utilities.is_canonical(f) + @test MOI.Utilities.canonicalize!(copied) === copied + @test MOI.constant(f, Float32) === 0.0f0 + mapped = MOI.Utilities.map_indices(v -> MOI.VariableIndex(v.value + 1), f) + @test mapped.func.args[1] == MOI.VariableIndex(2) + @test f.func.args[1] == x + return +end + +function test_polynomial_numeric_placeholder_promotion() + model = JuMP.GenericModel{Float32}() + JuMP.@variable(model, x) + numeric = GenOpt.lazy_sum(i + 1 for i in 1:3) + for constant in (numeric, numeric + 1) + for expression in + (constant + x, x + constant, constant * x, x * constant) + @test expression isa GenOpt.PolynomialExpr{ + JuMP.GenericAffExpr{Float32,typeof(x)}, + typeof(x), + } + @test JuMP.moi_function(expression) isa + GenOpt.PolynomialFunction{MOI.ScalarAffineFunction{Float32}} + end + @test GenOpt.MA.promote_operation(+, typeof(constant), typeof(x)) == + typeof(constant + x) + @test GenOpt.MA.promote_operation(*, typeof(x), typeof(constant)) == + typeof(x * constant) + end + return +end + +function test_polynomial_sum_function_roundtrip() + model = JuMP.Model() + JuMP.@variable(model, x[1:3]) + for sum in ( + GenOpt.lazy_sum(x[i] for i in 1:3), + GenOpt.lazy_sum(x[i] for i in 1:3 if i == 2), + ) + f = JuMP.moi_function(sum) + reconstructed = JuMP.jump_function(model, f) + @test typeof(reconstructed) == JuMP.jump_function_type(model, typeof(f)) + @test JuMP.moi_function_type(typeof(reconstructed)) == typeof(f) + @test _has_sum(JuMP.moi_function(reconstructed)) + @test copy(f) ≈ f + @test MOI.Utilities.map_indices(identity, f) ≈ f + @test JuMP.owner_model(reconstructed) === JuMP.owner_model(sum) + @test JuMP.owner_model(reconstructed + x[1]) === model + @test JuMP.check_belongs_to_model(reconstructed, model) === nothing + @test_throws JuMP.VariableNotOwned JuMP.check_belongs_to_model( + reconstructed, + JuMP.Model(), + ) + if sum isa GenOpt.LazySum + @test !isempty( + JuMP.function_string(MIME("text/plain"), reconstructed), + ) + end + end + return +end + # Integration test for a filtered `lazy_sum` used inside a constraint of a JuMP model. # # Why it is useful: "sum over the members of a group" is ubiquitous (flow balance at a node,