11module SparseDiffToolsPolyesterForwardDiffExt
22
3- using ADTypes, SparseDiffTools, PolyesterForwardDiff
3+ using ADTypes, SparseDiffTools, PolyesterForwardDiff, UnPack, Random, SparseArrays
44import ForwardDiff
55import SparseDiffTools: AbstractMaybeSparseJacobianCache, AbstractMaybeSparsityDetection,
66 ForwardColorJacCache, NoMatrixColoring, sparse_jacobian_cache,
@@ -17,10 +17,8 @@ struct PolyesterForwardDiffJacobianCache{CO, CA, J, FX, X} <:
1717end
1818
1919function sparse_jacobian_cache (
20- ad:: Union {AutoSparsePolyesterForwardDiff,
21- AutoPolyesterForwardDiff},
22- sd:: AbstractMaybeSparsityDetection , f:: F , x;
23- fx = nothing ) where {F}
20+ ad:: Union{AutoSparsePolyesterForwardDiff, AutoPolyesterForwardDiff} ,
21+ sd:: AbstractMaybeSparsityDetection , f:: F , x; fx = nothing ) where {F}
2422 coloring_result = sd (ad, f, x)
2523 fx = fx === nothing ? similar (f (x)) : fx
2624 if coloring_result isa NoMatrixColoring
@@ -39,10 +37,8 @@ function sparse_jacobian_cache(
3937end
4038
4139function sparse_jacobian_cache (
42- ad:: Union {AutoSparsePolyesterForwardDiff,
43- AutoPolyesterForwardDiff},
44- sd:: AbstractMaybeSparsityDetection , f!:: F , fx,
45- x) where {F}
40+ ad:: Union{AutoSparsePolyesterForwardDiff, AutoPolyesterForwardDiff} ,
41+ sd:: AbstractMaybeSparsityDetection , f!:: F , fx, x) where {F}
4642 coloring_result = sd (ad, f!, fx, x)
4743 if coloring_result isa NoMatrixColoring
4844 cache = __chunksize (ad, x)
@@ -79,4 +75,38 @@ function sparse_jacobian!(J::AbstractMatrix, _, cache::PolyesterForwardDiffJacob
7975 return J
8076end
8177
78+ # # Approximate Sparsity Detection
79+ function (alg:: ApproximateJacobianSparsity )(
80+ ad:: AutoSparsePolyesterForwardDiff , f:: F , x; fx = nothing , kwargs... ) where {F}
81+ @unpack ntrials, rng = alg
82+ fx = fx === nothing ? f (x) : fx
83+ ck = __chunksize (ad, x)
84+ J = fill! (similar (fx, length (fx), length (x)), 0 )
85+ J_cache = similar (J)
86+ x_ = similar (x)
87+ for _ in 1 : ntrials
88+ randn! (rng, x_)
89+ PolyesterForwardDiff. threaded_jacobian! (f, J_cache, x_, ck)
90+ @. J += abs (J_cache)
91+ end
92+ return (JacPrototypeSparsityDetection (; jac_prototype = sparse (J), alg. alg))(ad, f, x;
93+ fx, kwargs... )
94+ end
95+
96+ function (alg:: ApproximateJacobianSparsity )(ad:: AutoSparsePolyesterForwardDiff , f:: F , fx, x;
97+ kwargs... ) where {F}
98+ @unpack ntrials, rng = alg
99+ ck = __chunksize (ad, x)
100+ J = fill! (similar (fx, length (fx), length (x)), 0 )
101+ J_cache = similar (J)
102+ x_ = similar (x)
103+ for _ in 1 : ntrials
104+ randn! (rng, x_)
105+ PolyesterForwardDiff. threaded_jacobian! (f, fx, J_cache, x_, ck)
106+ @. J += abs (J_cache)
107+ end
108+ return (JacPrototypeSparsityDetection (; jac_prototype = sparse (J), alg. alg))(ad, f, x;
109+ fx, kwargs... )
110+ end
111+
82112end
0 commit comments