Skip to content

Commit

Permalink
Prevent empty +() when mapping to ASTs (infiniteopt#324)
Browse files Browse the repository at this point in the history
* Fix empty ast sums

* fix bugs
  • Loading branch information
pulsipher authored Oct 23, 2023
1 parent fd051e8 commit 65195d0
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/expressions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -774,7 +774,7 @@ function map_expression_to_ast(
push!(ex.args, Expr(:call, :*, c, var_mapper(v)))
end
end
if !iszero(aff.constant)
if !iszero(aff.constant) || isempty(ex.args[2:end])
push!(ex.args, aff.constant)
end
return ex
Expand All @@ -794,7 +794,10 @@ function map_expression_to_ast(
push!(ex.args, Expr(:call, :*, c, var_mapper(v1), var_mapper(v2)))
end
end
append!(ex.args, map_expression_to_ast(var_mapper, op_mapper, quad.aff).args[2:end])
aff_ex = map_expression_to_ast(var_mapper, op_mapper, quad.aff)
if aff_ex.args != [:+, 0.0] || isempty(ex.args[2:end])
append!(ex.args, aff_ex.args[2:end])
end
return ex
end

Expand Down
6 changes: 6 additions & 0 deletions test/expressions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,9 @@ end
aff = 2z + y + 42
quad = z^2 + 3 * z * y + 2z
nlp = (sin(z) + aff) ^ 3.4
aff0 = zero(GenericAffExpr{Float64, GeneralVariableRef})
quad2 = 2 * z^2
quad0 = zero(GenericQuadExpr{Float64, GeneralVariableRef})
jm = Model()
@variable(jm, x)
@variable(jm, w)
Expand All @@ -679,10 +682,13 @@ end
# test AffExpr
@testset "AffExpr" begin
@test map_expression_to_ast(vmap, aff) == :(2 * $x + $w + 42)
@test map_expression_to_ast(vmap, aff0) == :(+(0))
end
# test QuadExpr
@testset "QuadExpr" begin
@test map_expression_to_ast(vmap, quad) == :($x * $x + 3 * $x * $w + 2 * $x)
@test map_expression_to_ast(vmap, quad2) == :(+(2 * $x * $x))
@test map_expression_to_ast(vmap, quad0) == :(+(0))
end
# test GenericNonlinearExpr
@testset "GenericNonlinearExpr" begin
Expand Down

0 comments on commit 65195d0

Please sign in to comment.