From fef7019f0b366d7f18e2795d4f5e72bd69e9f26c Mon Sep 17 00:00:00 2001 From: Daisuke Oyama Date: Wed, 15 May 2019 23:31:35 +0900 Subject: [PATCH] Document how to use `MOI.VectorAffineFunction` Close #170 --- docs/src/optimization.md | 63 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/docs/src/optimization.md b/docs/src/optimization.md index 061b9006..516c8858 100644 --- a/docs/src/optimization.md +++ b/docs/src/optimization.md @@ -126,3 +126,66 @@ m = Model() poly = polyhedron(m, CDDLib.Library(:exact)) ``` + +## Using a Polyhedra Optimizer with MathOptInterface + +Polyhedra Optimizers by dafault support only a few constraint types in MathOptInterface (MOI). +Apply `MOI.Bridges.full_bridge_optimizer` to a Polyhedra Optimizer to enable a broader set of constraint types, such as `VectorAffineFunction`: +see the [list](http://www.juliaopt.org/MathOptInterface.jl/dev/apimanual/#Constraints-by-function-set-pairs-1) from MOI. + +As an example, consider the linear program: +```math +\[ +\max\ c x \quad \text{s.t.}\ A x \leq b,\ x \geq 0 +\] +``` +where +```julia +A = [1 2; 3 1] +b = [1, 2] +c = [1, 1] +``` + +Let us solve this program with `CDDLib.Optimizer` in exact arithmetic. +To set up: + +```julia +using CDDLib +using MathOptInterface +const MOI = MathOptInterface + +m, n = size(A) +T = Rational{BigInt} + +# Enable `VectorAffineTerm`, `VectorOfVariables`, `Nonnegatives`, `Nonpositives` +optimizer = MOI.Bridges.full_bridge_optimizer(CDDLib.Optimizer{T}(), T) + +# max cx +x = MOI.add_variables(optimizer, n) +MOI.set(optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{T}}(), + MOI.ScalarAffineFunction{T}(MOI.ScalarAffineTerm{T}.(c, x), 0)) +MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MAX_SENSE) + +# Ax - b <= 0 +terms = MOI.VectorAffineTerm{T}.( + 1:m, MOI.ScalarAffineTerm{T}.(A, reshape(x, 1, n)) +) +f = MOI.VectorAffineFunction{T}(vec(terms), -b) +MOI.add_constraint(optimizer, f, MOI.Nonpositives(m)) + +# x >= 0 +MOI.add_constraint(optimizer, MOI.VectorOfVariables(x), MOI.Nonnegatives(n)) +``` + +To solve: + +```julia +MOI.optimize!(optimizer) +MOI.get(optimizer, MOI.VariablePrimal(), x) +``` + +``` +2-element Array{Rational{BigInt},1}: + 3//5 + 1//5 +```