Skip to content

Commit 1762fd9

Browse files
committed
Add W indices to sparse J to avoid iszero check
1 parent 5a49e93 commit 1762fd9

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

src/systems/codegen.jl

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -186,16 +186,14 @@ function calculate_jacobian(sys::System;
186186
if sparse
187187
jac = sparsejacobian(rhs, dvs; simplify)
188188
if get_iv(sys) !== nothing
189-
W_s = W_sparsity(sys)
190-
(Is, Js, Vs) = findnz(W_s)
191-
# Add nonzeros of W as non-structural zeros of the Jacobian (to ensure equal
192-
# results for oop and iip Jacobian)
193-
for (i, j) in zip(Is, Js)
194-
iszero(jac[i, j]) && begin
195-
jac[i, j] = 1
196-
jac[i, j] = 0
197-
end
198-
end
189+
# Add nonzeros of W as non-structural zeros of the Jacobian
190+
# (to ensure equal results for oop and iip Jacobian)
191+
JIs, JJs, JVs = findnz(jac)
192+
WIs, WJs, _ = findnz(W_sparsity(sys))
193+
append!(JIs, WIs) # explicitly put all W's indices also in J,
194+
append!(JJs, WJs) # even if it duplicates some indices
195+
append!(JVs, zeros(eltype(JVs), length(WIs))) # add zero
196+
jac = SparseArrays.sparse(JIs, JJs, JVs) # values at duplicate indices are summed; not overwritten
199197
end
200198
else
201199
jac = jacobian(rhs, dvs; simplify)

0 commit comments

Comments
 (0)