Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement value for GenericQuadExpr. #1588

Merged
merged 5 commits into from
Nov 8, 2018
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/quad_expr.jl
Original file line number Diff line number Diff line change
Expand Up @@ -232,4 +232,16 @@ function Base.copy(q::GenericQuadExpr, new_model::Model)
copy(q.qcoeffs), copy(q.aff, new_model))
end

# TODO: result_value for QuadExpr
# Requires that foo(::VarType) is defined.
odow marked this conversation as resolved.
Show resolved Hide resolved
function value(ex::GenericQuadExpr{CoefType, VarType},
foo::Function) where {CoefType, VarType}
RetType = Base.promote_op(
(ctype, vtype) -> ctype * foo(vtype) * foo(vtype), CoefType, VarType)
ret = convert(RetType, value(ex.aff, foo))
for (vars, coef) in ex.terms
ret += coef * foo(vars.a) * foo(vars.b)
end
return ret
end

JuMP.result_value(ex::JuMP.GenericQuadExpr) = value(ex, JuMP.result_value)
13 changes: 13 additions & 0 deletions test/expr.jl
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,19 @@ function expressions_test(ModelType::Type{<:JuMP.AbstractModel}, VariableRefType
@test @inferred(JuMP.value(expr2, i -> 1.0)) == 2.0
end

@testset "value for GenericQuadExpr" begin
# 1 + 2x(1) + 3x(2)
affine_term = JuMP.GenericAffExpr(1.0, 1 => 2.0, 2 => 3.0)
# 1 + 2x(1) + 3x(2) + 4x(1)^2 + 5x(1)*x(2) + 6x(2)^2
expr = JuMP.GenericQuadExpr(affine_term,
JuMP.UnorderedPair(1, 1) => 4.0,
JuMP.UnorderedPair(1, 2) => 5.0,
JuMP.UnorderedPair(2, 2) => 6.0)
@test typeof(@inferred(JuMP.value(expr, i -> 1.0))) == Float64
@test @inferred(JuMP.value(expr, i -> 1.0)) == 21
@test @inferred(JuMP.value(expr, i -> 2.0)) == 71
end

@testset "add_to_expression!(::GenericAffExpr{C,V}, ::V)" begin
aff = JuMP.GenericAffExpr(1.0, :a => 2.0)
@test JuMP.isequal_canonical(JuMP.add_to_expression!(aff, :b),
Expand Down
2 changes: 2 additions & 0 deletions test/generate_and_solve.jl
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,8 @@
@test JuMP.result_dual(c1) == -1.0
@test JuMP.result_dual(c2) == 2.0
@test JuMP.result_dual(c3) == 3.0

@test JuMP.result_value(2 * x + 3 * y * x) == 2.0
end

@testset "SOC" begin
Expand Down