@@ -348,6 +348,9 @@ function finite_difference_jacobian!(
348
348
fill! (J,false )
349
349
end
350
350
351
+ # fast path if J and sparsity are both SparseMatrixCSC and have the same sparsity pattern
352
+ sparseCSC_common_sparsity = _use_sparseCSC_common_sparsity (J, sparsity)
353
+
351
354
if fdtype == Val (:forward )
352
355
vfx1 = _vec (fx1)
353
356
@@ -378,7 +381,11 @@ function finite_difference_jacobian!(
378
381
# J is a sparse matrix, so decompress on the fly
379
382
@. vfx1 = (vfx1 - vfx) / epsilon
380
383
if ArrayInterface. fast_scalar_indexing (x1)
381
- _colorediteration! (J,sparsity,rows_index,cols_index,vfx1,colorvec,color_i,n)
384
+ if sparseCSC_common_sparsity
385
+ _colorediteration! (J,vfx1,colorvec,color_i,n)
386
+ else
387
+ _colorediteration! (J,sparsity,rows_index,cols_index,vfx1,colorvec,color_i,n)
388
+ end
382
389
else
383
390
#=
384
391
J.nzval[rows_index] .+= (colorvec[cols_index] .== color_i) .* vfx1[rows_index]
@@ -417,8 +424,12 @@ function finite_difference_jacobian!(
417
424
f (fx1, x1)
418
425
f (fx, x)
419
426
@. vfx1 = (vfx1 - vfx) / 2 epsilon
420
- if ArrayInterface. fast_scalar_indexing (x1)
421
- _colorediteration! (J,sparsity,rows_index,cols_index,vfx1,colorvec,color_i,n)
427
+ if ArrayInterface. fast_scalar_indexing (x1)
428
+ if sparseCSC_common_sparsity
429
+ _colorediteration! (J,vfx1,colorvec,color_i,n)
430
+ else
431
+ _colorediteration! (J,sparsity,rows_index,cols_index,vfx1,colorvec,color_i,n)
432
+ end
422
433
else
423
434
if J isa SparseMatrixCSC
424
435
@. void_setindex! ((J. nzval,), getindex ((J. nzval,), rows_index) + (getindex ((_color,), cols_index) == color_i) * getindex ((vfx1,), rows_index), rows_index)
@@ -443,8 +454,12 @@ function finite_difference_jacobian!(
443
454
@. x1 = x1 + im * epsilon * (_color == color_i)
444
455
f (fx,x1)
445
456
@. vfx = imag (vfx) / epsilon
446
- if ArrayInterface. fast_scalar_indexing (x1)
447
- _colorediteration! (J,sparsity,rows_index,cols_index,vfx,colorvec,color_i,n)
457
+ if ArrayInterface. fast_scalar_indexing (x1)
458
+ if sparseCSC_common_sparsity
459
+ _colorediteration! (J,vfx,colorvec,color_i,n)
460
+ else
461
+ _colorediteration! (J,sparsity,rows_index,cols_index,vfx,colorvec,color_i,n)
462
+ end
448
463
else
449
464
if J isa SparseMatrixCSC
450
465
@. void_setindex! ((J. nzval,), getindex ((J. nzval,), rows_index) + (getindex ((_color,), cols_index) == color_i) * getindex ((vfx,),rows_index), rows_index)
0 commit comments