|
| 1 | +import SparseArrays |
| 2 | +using BenchmarkTools |
| 3 | + |
| 4 | +import MathOptInterface as MOI |
| 5 | + |
| 6 | +# Inspired from MatrixOfConstraints |
| 7 | +MOI.Utilities.@product_of_sets( |
| 8 | + _EqualTos, |
| 9 | + MOI.EqualTo{T}, |
| 10 | +) |
| 11 | + |
| 12 | +a = 1 |
| 13 | + |
| 14 | +function _equality_constraints( |
| 15 | + A::AbstractMatrix{T}, |
| 16 | + b::AbstractVector{T}, |
| 17 | +) where {T} |
| 18 | + sets = _EqualTos{T}() |
| 19 | + for _ in eachindex(b) |
| 20 | + MOI.Utilities.add_set( |
| 21 | + sets, |
| 22 | + MOI.Utilities.set_index(sets, MOI.EqualTo{T}), |
| 23 | + ) |
| 24 | + end |
| 25 | + MOI.Utilities.final_touch(sets) |
| 26 | + constants = MOI.Utilities.Hyperrectangle(b, b) |
| 27 | + model = MOI.Utilities.MatrixOfConstraints{T}(A, constants, sets) |
| 28 | + model.final_touch = true |
| 29 | + return model |
| 30 | +end |
| 31 | + |
| 32 | +function _free_variables(n, ::Type{T}) where {T} |
| 33 | + model = MOI.Utilities.VariablesContainer{T}() |
| 34 | + for _ in 1:n |
| 35 | + MOI.add_variable(model) |
| 36 | + end |
| 37 | + return model |
| 38 | +end |
| 39 | + |
| 40 | +function lp_standard_form(m, n; p = 0.1, tr = false) |
| 41 | + T = Float64 |
| 42 | + A = SparseArrays.sprand(T, m, n, p) |
| 43 | + if tr |
| 44 | + A = copy(A')' |
| 45 | + end |
| 46 | + b = rand(m) |
| 47 | + return MOI.Utilities.GenericModel{T}( |
| 48 | + MOI.Utilities.ObjectiveContainer{T}(), |
| 49 | + _free_variables(n, T), |
| 50 | + _equality_constraints(A, b), |
| 51 | + ) |
| 52 | +end |
| 53 | + |
| 54 | +function bench(m, args...; kws...) |
| 55 | + T = Float64 |
| 56 | + model = lp_standard_form(m, args...; kws...) |
| 57 | + ci = MOI.ConstraintIndex{MOI.ScalarAffineFunction{T},MOI.EqualTo{T}}(rand(1:m)) |
| 58 | + return @benchmark MOI.get($model, MOI.ConstraintFunction(), $ci) |
| 59 | +end |
| 60 | + |
| 61 | +bench(10, 100000) |
| 62 | +bench(10, 100000, tr = true) |
| 63 | + |
| 64 | +function prof(m, args...) |
| 65 | + T = Float64 |
| 66 | + model = lp_standard_form(m, args...) |
| 67 | + return @profview for i in 1:m |
| 68 | + ci = MOI.ConstraintIndex{MOI.ScalarAffineFunction{T},MOI.EqualTo{T}}(rand(1:m)) |
| 69 | + MOI.get(model, MOI.ConstraintFunction(), ci) |
| 70 | + end |
| 71 | +end |
| 72 | + |
| 73 | +prof(10, 100000) |
0 commit comments