Skip to content

Commit

Permalink
Merge cf3da70 into f31be21
Browse files Browse the repository at this point in the history
  • Loading branch information
odow authored Mar 6, 2025
2 parents f31be21 + cf3da70 commit 2002f56
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
8 changes: 8 additions & 0 deletions src/Nonlinear/SymbolicAD/SymbolicAD.jl
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ function simplify!(f::MOI.ScalarAffineFunction{T}) where {T}
if isempty(f.terms)
return f.constant
end
if iszero(f.constant) && length(f.terms) == 1
term = only(f.terms)
if isone(term.coefficient)
return term.variable
end
end
return f
end

Expand Down Expand Up @@ -1589,6 +1595,8 @@ function _add_to_affine!(
end
end
return _add_to_affine!(ret, something(y, one(T)), convert(T, scale))
elseif f.head == :/ && f.args[2] isa Real
return _add_to_affine!(ret, f.args[1], convert(T, scale / f.args[2]))
end
return # An unsupported f.head
end
Expand Down
19 changes: 9 additions & 10 deletions test/Nonlinear/SymbolicAD.jl
Original file line number Diff line number Diff line change
Expand Up @@ -199,22 +199,21 @@ function test_simplify_ScalarAffineFunction()
x = MOI.VariableIndex(1)
@test SymbolicAD.simplify(1.0 * x + 1.0) 1.0 * x + 1.0
@test SymbolicAD.simplify(1.0 * x + 2.0 * x + 1.0) 3.0 * x + 1.0
@test SymbolicAD.simplify(1.0 * x) == x
@test SymbolicAD.simplify(2.0 * x) 2.0 * x
return
end

function test_simplify_ScalarQuadraticFunction()
x = MOI.VariableIndex(1)
f = MOI.ScalarQuadraticFunction(
MOI.ScalarQuadraticTerm{Float64}[],
[MOI.ScalarAffineTerm{Float64}(1.0, x)],
1.0,
)
terms = MOI.ScalarQuadraticTerm{Float64}[]
f = MOI.ScalarQuadraticFunction(terms, [MOI.ScalarAffineTerm(1.0, x)], 1.0)
@test SymbolicAD.simplify(f) 1.0 * x + 1.0
f = MOI.ScalarQuadraticFunction(
MOI.ScalarQuadraticTerm{Float64}[],
MOI.ScalarAffineTerm{Float64}[],
2.0,
)
f = MOI.ScalarQuadraticFunction(terms, [MOI.ScalarAffineTerm(2.0, x)], 0.0)
@test SymbolicAD.simplify(f) 2.0 * x + 0.0
f = MOI.ScalarQuadraticFunction(terms, [MOI.ScalarAffineTerm(1.0, x)], 0.0)
@test SymbolicAD.simplify(f) == x
f = MOI.ScalarQuadraticFunction(terms MOI.ScalarAffineTerm{Float64}[], 2.0)
@test SymbolicAD.simplify(f) === 2.0
@test SymbolicAD.simplify(1.0 * x * x + 1.0) 1.0 * x * x + 1.0
g = 1.0 * x * x + 2.0 * x * x + 1.0
Expand Down

0 comments on commit 2002f56

Please sign in to comment.