1- function num_vecjac! (du, f:: F , x, v, cache1 = similar (v), cache2 = similar (v), cache3 = similar (v);
2- compute_f0 = true ) where {F}
1+ function num_vecjac! (du, f:: F , x, v, cache1 = similar (v), cache2 = similar (v),
2+ cache3 = similar (x); compute_f0 = true ) where {F}
33 compute_f0 && (f (cache1, x))
44 T = eltype (x)
55 # Should it be min? max? mean?
@@ -15,19 +15,35 @@ function num_vecjac!(du, f::F, x, v, cache1 = similar(v), cache2 = similar(v), c
1515 return du
1616end
1717
18+ # Special Non-Allocating case for StaticArrays
19+ function num_vecjac (f:: F , x:: SArray , v:: SArray , f0 = nothing ) where {F}
20+ f0 === nothing ? (_f0 = f (x)) : (_f0 = f0)
21+ vv = reshape (v, axes (_f0))
22+ T = eltype (x)
23+ ϵ = sqrt (eps (real (T))) * max (one (real (T)), abs (norm (x)))
24+ du = zeros (typeof (x))
25+ for i in 1 : length (x)
26+ cache = Base. setindex (x, x[i] + ϵ, i)
27+ f0 = f (cache)
28+ du = Base. setindex (du, (((f0 .- _f0) ./ ϵ)' * vv), i)
29+ end
30+ return du
31+ end
32+
1833function num_vecjac (f:: F , x, v, f0 = nothing ) where {F}
1934 f0 === nothing ? (_f0 = f (x)) : (_f0 = f0)
2035 vv = reshape (v, axes (_f0))
2136 T = eltype (x)
2237 # Should it be min? max? mean?
2338 ϵ = sqrt (eps (real (T))) * max (one (real (T)), abs (norm (x)))
2439 du = similar (x)
25- cache = copy (x)
40+ cache = similar (x)
41+ copyto! (cache, x)
2642 for i in 1 : length (x)
27- cache[i] += ϵ
28- f0 = f (x )
29- cache[i] = x[i]
30- du[i] = ((( f0 .- _f0) ./ ϵ)' * vv)[1 ]
43+ cache = allowed_setindex! (cache, x [i] + ϵ, i)
44+ f0 = f (cache )
45+ cache = allowed_setindex! (cache, x[i], i)
46+ du = allowed_setindex! (du, ((( f0 .- _f0) ./ ϵ)' * vv)[1 ], i)
3147 end
3248 return vec (du)
3349end
@@ -93,7 +109,7 @@ function VecJac(f, u::AbstractArray, p = nothing, t = nothing; fu = nothing,
93109end
94110
95111function _vecjac (f:: F , fu, u, autodiff:: AutoFiniteDiff ) where {F}
96- cache = (similar (fu), similar (fu), similar (fu ))
112+ cache = (similar (fu), similar (fu), similar (u ))
97113 pullback = nothing
98114 return AutoDiffVJP (f, u, cache, autodiff, pullback)
99115end
0 commit comments