Skip to content

Commit cf3da70

Browse files
committed
[Nonlinear.SymbolicAD] add two more simplification cases
1 parent f31be21 commit cf3da70

File tree

2 files changed

+17
-10
lines changed

2 files changed

+17
-10
lines changed

src/Nonlinear/SymbolicAD/SymbolicAD.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,12 @@ function simplify!(f::MOI.ScalarAffineFunction{T}) where {T}
7777
if isempty(f.terms)
7878
return f.constant
7979
end
80+
if iszero(f.constant) && length(f.terms) == 1
81+
term = only(f.terms)
82+
if isone(term.coefficient)
83+
return term.variable
84+
end
85+
end
8086
return f
8187
end
8288

@@ -1589,6 +1595,8 @@ function _add_to_affine!(
15891595
end
15901596
end
15911597
return _add_to_affine!(ret, something(y, one(T)), convert(T, scale))
1598+
elseif f.head == :/ && f.args[2] isa Real
1599+
return _add_to_affine!(ret, f.args[1], convert(T, scale / f.args[2]))
15921600
end
15931601
return # An unsupported f.head
15941602
end

test/Nonlinear/SymbolicAD.jl

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -199,22 +199,21 @@ function test_simplify_ScalarAffineFunction()
199199
x = MOI.VariableIndex(1)
200200
@test SymbolicAD.simplify(1.0 * x + 1.0) 1.0 * x + 1.0
201201
@test SymbolicAD.simplify(1.0 * x + 2.0 * x + 1.0) 3.0 * x + 1.0
202+
@test SymbolicAD.simplify(1.0 * x) == x
203+
@test SymbolicAD.simplify(2.0 * x) 2.0 * x
202204
return
203205
end
204206

205207
function test_simplify_ScalarQuadraticFunction()
206208
x = MOI.VariableIndex(1)
207-
f = MOI.ScalarQuadraticFunction(
208-
MOI.ScalarQuadraticTerm{Float64}[],
209-
[MOI.ScalarAffineTerm{Float64}(1.0, x)],
210-
1.0,
211-
)
209+
terms = MOI.ScalarQuadraticTerm{Float64}[]
210+
f = MOI.ScalarQuadraticFunction(terms, [MOI.ScalarAffineTerm(1.0, x)], 1.0)
212211
@test SymbolicAD.simplify(f) 1.0 * x + 1.0
213-
f = MOI.ScalarQuadraticFunction(
214-
MOI.ScalarQuadraticTerm{Float64}[],
215-
MOI.ScalarAffineTerm{Float64}[],
216-
2.0,
217-
)
212+
f = MOI.ScalarQuadraticFunction(terms, [MOI.ScalarAffineTerm(2.0, x)], 0.0)
213+
@test SymbolicAD.simplify(f) 2.0 * x + 0.0
214+
f = MOI.ScalarQuadraticFunction(terms, [MOI.ScalarAffineTerm(1.0, x)], 0.0)
215+
@test SymbolicAD.simplify(f) == x
216+
f = MOI.ScalarQuadraticFunction(terms MOI.ScalarAffineTerm{Float64}[], 2.0)
218217
@test SymbolicAD.simplify(f) === 2.0
219218
@test SymbolicAD.simplify(1.0 * x * x + 1.0) 1.0 * x * x + 1.0
220219
g = 1.0 * x * x + 2.0 * x * x + 1.0

0 commit comments

Comments
 (0)