Skip to content

Commit d737990

Browse files
committed
minor performance optimization in expand_derivatives
1 parent 2fc15cf commit d737990

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

src/differentials.jl

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,19 +48,33 @@ function expand_derivatives(O::Operation,simplify=true)
4848
isa(o, Operation) || return O
4949
isa(o.op, Variable) && return O
5050

51-
x = sum(1:length(o.args)) do i
51+
l = length(o.args)
52+
exprs = []
53+
c = 0
54+
55+
for i in 1:l
5256
t2 = expand_derivatives(D(o.args[i]),false)
5357

54-
if _iszero(t2)
55-
return t2
58+
x = if _iszero(t2)
59+
t2
5660
elseif _isone(t2)
57-
return derivative(o, i)
61+
derivative(o, i)
62+
else
63+
derivative(o, i) * t2
64+
end
65+
if x isa Expression
66+
push!(exprs, x)
5867
else
59-
return derivative(o, i) * t2
68+
c += x
6069
end
6170
end
6271

63-
return simplify ? ModelingToolkit.simplify(x) : x
72+
if isempty(exprs)
73+
return c
74+
else
75+
x = Operation(+, !iszero(c) ? vcat(c, exprs) : exprs)
76+
return simplify ? ModelingToolkit.simplify(x) : x
77+
end
6478
end
6579

6680
return simplify ? ModelingToolkit.simplify(O) : O

0 commit comments

Comments
 (0)