1
1
module SparseDiffToolsPolyesterForwardDiffExt
2
2
3
- using ADTypes, SparseDiffTools, PolyesterForwardDiff
3
+ using ADTypes, SparseDiffTools, PolyesterForwardDiff, UnPack, Random, SparseArrays
4
4
import ForwardDiff
5
5
import SparseDiffTools: AbstractMaybeSparseJacobianCache, AbstractMaybeSparsityDetection,
6
6
ForwardColorJacCache, NoMatrixColoring, sparse_jacobian_cache,
@@ -17,10 +17,8 @@ struct PolyesterForwardDiffJacobianCache{CO, CA, J, FX, X} <:
17
17
end
18
18
19
19
function 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}
24
22
coloring_result = sd (ad, f, x)
25
23
fx = fx === nothing ? similar (f (x)) : fx
26
24
if coloring_result isa NoMatrixColoring
@@ -39,10 +37,8 @@ function sparse_jacobian_cache(
39
37
end
40
38
41
39
function 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}
46
42
coloring_result = sd (ad, f!, fx, x)
47
43
if coloring_result isa NoMatrixColoring
48
44
cache = __chunksize (ad, x)
@@ -79,4 +75,38 @@ function sparse_jacobian!(J::AbstractMatrix, _, cache::PolyesterForwardDiffJacob
79
75
return J
80
76
end
81
77
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
+
82
112
end
0 commit comments