Skip to content

Commit

Permalink
macro support for range constraints
Browse files Browse the repository at this point in the history
  • Loading branch information
mlubin committed Jun 23, 2013
1 parent a378142 commit 9c0391d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 7 deletions.
5 changes: 4 additions & 1 deletion src/MathProg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export
Variable,
AffExpr,
QuadExpr,
Constraint,
LinearConstraint,
MultivarDict,

# Functions
Expand Down Expand Up @@ -235,6 +235,9 @@ type LinearConstraint
ub::Float64
end

LinearConstraint(terms::AffExpr,lb::Number,ub::Number) =
LinearConstraint(terms,float(lb),float(ub))

addConstraint(m::Model, c::LinearConstraint) = push!(m.linconstr,c)

print(io::IO, c::LinearConstraint) = print(io, conToStr(c))
Expand Down
31 changes: 25 additions & 6 deletions src/macros.jl
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,31 @@ macro addConstraint(m, x)
error("Expected comparison operator in constraint $x")
end
aff = gensym()
lhs = :($(x.args[1]) - $(x.args[3])) # move everything to the lhs
esc(quote
$aff = AffExpr()
$(parseExpr(lhs, aff, 1.0))
addConstraint($m, $(x.args[2])($aff,0) )
end)
if length(x.args) == 3 # simple comparison
lhs = :($(x.args[1]) - $(x.args[3])) # move everything to the lhs
esc(quote
$aff = AffExpr()
$(parseExpr(lhs, aff, 1.0))
addConstraint($m, $(x.args[2])($aff,0) )
end)
else
# ranged row
if length(x.args) != 5 || x.args[2] != :<= || x.args[4] != :<=
error("Only ranged rows of the form lb <= expr <= ub are supported")
end
lb = x.args[1]
ub = x.args[5]
esc(quote
$aff = AffExpr()
if !isa($lb,Number)
error(string("Expected ",$lb," to be a number"))
elseif !isa($ub,Number)
error(string("Expected ",$ub," to be a number"))
end
$(parseExpr(x.args[3],aff,1.0))
addConstraint($m, MathProg.LinearConstraint($aff,$lb,$ub))
end)
end
end

macro setObjective(m, x)
Expand Down
2 changes: 2 additions & 0 deletions test/macros.jl
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ let
@test conToStr(m.linconstr[end]) == "3.0 x + -1.0 y + -3.3 w + -6.6 z == 5.0"
@addConstraint(m, (x+y)/2 == 1)
@test conToStr(m.linconstr[end]) == "0.5 x + 0.5 y == 1.0"
@addConstraint(m, -1 <= x-y <= 1)
@test conToStr(m.linconstr[end]) == "-1.0 <= 1.0 x + -1.0 y <= 1.0"
end

let
Expand Down

0 comments on commit 9c0391d

Please sign in to comment.