Skip to content
This repository was archived by the owner on Aug 22, 2025. It is now read-only.

Commit 1f55f52

Browse files
committed
Overwrite pre-allocated Jacobian when using oop so it can be nonzero.
1 parent 8dc0db0 commit 1f55f52

2 files changed

Lines changed: 11 additions & 4 deletions

File tree

src/differentiation/compute_jacobian_ad.jl

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,11 @@ function forwarddiff_color_jacobian(J::SparseMatrixCSC{<:Number},f,x::AbstractAr
189189
cols_index_c = cols_index[pick_inds]
190190
Ji = sparse(rows_index_c, cols_index_c, dx[rows_index_c],nrows,ncols)
191191
# J = J + Ji
192-
J .+= Ji
192+
if j == 1 && i == 1
193+
J .= Ji # overwrite pre-allocated matrix
194+
else
195+
J .+= Ji
196+
end
193197
color_i += 1
194198
(color_i > maxcolor) && return J
195199
end
@@ -199,7 +203,11 @@ function forwarddiff_color_jacobian(J::SparseMatrixCSC{<:Number},f,x::AbstractAr
199203
(col_index > ncols) && return J
200204
Ji = mapreduce(i -> i==col_index ? partials.(vec(fx), j) : adapt(parameterless_type(J),zeros(eltype(J),nrows)), hcat, 1:ncols)
201205
# J = J + (size(Ji)!=size(J) ? reshape(Ji,size(J)) : Ji) #branch when size(dx) == (1,) => size(Ji) == (1,) while size(J) == (1,1)
202-
J .+= (size(Ji)!=size(J) ? reshape(Ji,size(J)) : Ji) #branch when size(dx) == (1,) => size(Ji) == (1,) while size(J) == (1,1)
206+
if j == 1 && i == 1
207+
J .= (size(Ji)!=size(J) ? reshape(Ji,size(J)) : Ji) # overwrite pre-allocated matrix
208+
else
209+
J .+= (size(Ji)!=size(J) ? reshape(Ji,size(J)) : Ji) #branch when size(dx) == (1,) => size(Ji) == (1,) while size(J) == (1,1)
210+
end
203211
end
204212
end
205213
end

test/test_ad.jl

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,10 +115,9 @@ _J1 = forwarddiff_color_jacobian(oopf, x, colorvec = repeat(1:3,10), sparsity =
115115
@test _J1 J
116116
@test fcalls == 1
117117

118-
119118
#oop with in-place Jacobian
120119
fcalls = 0
121-
_oop_jacout = spzeros(size(J)...)
120+
_oop_jacout = sparse(1.01 .* J) # want to be nonzero to check that the pre-allocated matrix is overwritten properly
122121
forwarddiff_color_jacobian(_oop_jacout, oopf, x; colorvec = repeat(1:3,10), sparsity = _J, jac_prototype = _J)
123122
@test _oop_jacout J
124123
@test typeof(_oop_jacout) == typeof(_J)

0 commit comments

Comments
 (0)