Skip to content

Commit 402f7cc

Browse files
committed
CR improvement from @YingboMa
* use `simplify` instead of custom reductions * ✅ test coverage for sparse operations with Operations
1 parent fc93acb commit 402f7cc

File tree

2 files changed

+36
-10
lines changed

2 files changed

+36
-10
lines changed

src/operations.jl

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,9 +55,8 @@ Base.isequal(::Operation, ::Constant ) = false
5555
Base.isequal(::Constant , ::Operation) = false
5656

5757
# provide iszero for Operations to help sparse addition and multiplication
58-
Base.iszero(O::Operation) = ((O.op == identity) && iszero(O.args[1])) ||
59-
((O.op == +) && all(iszero(arg) for arg in O.args)) ||
60-
((O.op == *) && any(iszero(arg) for arg in O.args))
58+
# e.g. we want to tell the sparse library that iszero(zero(Operation) + zero(Operation)) == true
59+
Base.iszero(x::Operation) = (_x = simplify(x); _x isa Constant && iszero(_x.value))
6160

6261
Base.show(io::IO, O::Operation) = print(io, convert(Expr, O))
6362

test/operation_overloads.jl

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,34 @@
1-
using ModelingToolkit
2-
using LinearAlgebra
3-
@variables a,b,c,d
4-
X = [a b;c d]
5-
det(X)
6-
lu(X)
7-
inv(X)
1+
using ModelingToolkit
2+
using LinearAlgebra
3+
using SparseArrays: sparse
4+
using Test
5+
6+
@variables a,b,c,d
7+
8+
# test some matrix operations don't throw errors
9+
X = [a b;c d]
10+
det(X)
11+
lu(X)
12+
inv(X)
13+
14+
# test operations with sparse arrays and Operations
15+
# note `isequal` instead of `==` because `==` would give another Operation
16+
17+
# test that we can create a sparse array of Operation
18+
Oarray = zeros(Operation, 2,2)
19+
Oarray[2,2] = a
20+
@test isequal(sparse(Oarray), sparse([2], [2], [a]))
21+
22+
# test Operation * sparse
23+
@test isequal(a * sparse([2], [2], [1]), sparse([2], [2], [a * 1]))
24+
25+
# test sparse{Operation} + sparse{Operation}
26+
A = sparse([2], [2], [a])
27+
B = sparse([2], [2], [b])
28+
@test isequal(A + B, sparse([2], [2], [a+b]))
29+
30+
# test sparse{Operation} * sparse{Operation}
31+
C = sparse([1, 2], [2, 1], [c, c])
32+
D = sparse([1, 2], [2, 1], [d, d])
33+
34+
@test isequal(C * D, sparse([1,2], [1,2], [c * d, c * d]))

0 commit comments

Comments
 (0)