Skip to content

Commit

Permalink
Merge pull request #3 from AKS1996/create_utils
Browse files Browse the repository at this point in the history
create utils.jl; begin testing
  • Loading branch information
akshay326 authored Jun 1, 2020
2 parents 909264d + 86403c9 commit d3ee3a9
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 3 deletions.
10 changes: 9 additions & 1 deletion src/DiffOpt.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
module DiffOpt

greet() = print("Hello World!")
using Random
using MathOptInterface

const MOI = MathOptInterface;
const MOIU = MathOptInterface.Utilities;

include("utils.jl")

export generate_lp

end # module
39 changes: 39 additions & 0 deletions src/utils.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""
Generates a non-trivial random MOI linear program by adding variables
and constraints to MOI compatible Optimizer `optimizer`
minimize `c' * x`
subject to `Ax <= b, x >= 0`
where `x in R^{n}, A in R^{m*n}, b in R^{m}, c in R^{n}`
Note: Mutates the `optimizer` object
"""
function generate_lp(optimizer,n,m)
s = rand(m)
s = 2*s .- 1
λ = max.(-s, 0)
s = max.(s, 0)
= rand(n)
A = rand(m, n)
b = A *.+ s
c = -A' * λ

x = MOI.add_variables(optimizer, n)

# define objective
objective_function = MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(c, x), 0.0)
MOI.set(optimizer, MOI.ObjectiveFunction{MOI.ScalarAffineFunction{Float64}}(), objective_function)
MOI.set(optimizer, MOI.ObjectiveSense(), MOI.MIN_SENSE)

# set constraints
for i in 1:m
MOI.add_constraint(
optimizer,
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm.(A[i,:], x), 0.), MOI.LessThan(b[i]),
)
end

for i in 1:n
MOI.add_constraint(optimizer,MOI.SingleVariable(x[i]),MOI.GreaterThan(0.))
end
end
8 changes: 6 additions & 2 deletions test/runtests.jl
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
using DiffOpt
using MathOptInterface
using Test

@testset "DiffOpt.jl" begin
# Write your own tests here.
const MOI = MathOptInterface;
const MOIU = MathOptInterface.Utilities;

@testset "utils" begin
include("utils.jl")
end
10 changes: 10 additions & 0 deletions test/utils.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using GLPK

@testset "Creating an LP" begin
model = GLPK.Optimizer()
= generate_lp(model,10,5)

MOI.optimize!(model)

@test MOI.get(model, MOI.TerminationStatus()) in [MOI.LOCALLY_SOLVED, MOI.OPTIMAL]
end

0 comments on commit d3ee3a9

Please sign in to comment.