Skip to content

Commit 6250778

Browse files
Merge pull request #186 from JuliaDiff/hesscache
Refresh Hessian caches on run
2 parents bf30a03 + b06e3e7 commit 6250778

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

src/hessians.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,12 @@ function finite_difference_hessian!(H,f,x,
137137

138138
if inplace === Val(true)
139139
_xpp, _xpm, _xmp, _xmm = xpp, xpm, xmp, xmm
140+
copyto!(xpp,x)
141+
copyto!(xpm,x)
142+
copyto!(xmp,x)
143+
copyto!(xmm,x)
144+
else # ignore the cache since immutable
145+
xpp, xpm, xmp, xmm = copy(x), copy(x), copy(x), copy(x)
140146
end
141147

142148
for i = 1:n

test/finitedifftests.jl

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -348,17 +348,17 @@ end
348348
_g(x) = x[1]^2 + x[2]
349349
_∇g(x) = [2x[1], 1.0]
350350
x = [1.0, 3.0]
351-
fx = _g(x)
351+
fx = _g(x)
352352
c1, c2 = zero(x), zero(x)
353353
c3 = zero(x)
354354
res = zero(x)
355355
gcache = FiniteDiff.GradientCache{Float64, Vector{Float64}, Vector{Float64}, Vector{Float64}, Val(:forward), Float64, Val(false)}(fx, c1, c2, c3)
356356
FiniteDiff.finite_difference_gradient!(res, _g, x, gcache)
357-
@test res _∇g(x)
357+
@test res _∇g(x)
358358
x = [2.7, 1.0]
359359
gcache = @set gcache.fx = _g(x)
360360
FiniteDiff.finite_difference_gradient!(res, _g, x, gcache)
361-
@test res _∇g(x)
361+
@test res _∇g(x)
362362
end
363363

364364
# Jacobian tests
@@ -488,7 +488,7 @@ f_in = oopf(x)
488488
@test err_func(FiniteDiff.finite_difference_jacobian(oopf, x, complex_cache), J_ref) < 1e-14
489489
end
490490

491-
# Test default colorvec construction
491+
# Test default colorvec construction
492492
θ = rand(2)
493493
y0 = rand(1)
494494
cache = FiniteDiff.JacobianCache(copy(θ), copy(y0), copy(y0), Val(:forward))
@@ -540,3 +540,11 @@ Base.getindex(x::ImmutableVector, i::Integer) = x.x[i]
540540
@test J Matrix(I, 2, 2)
541541
end
542542
end
543+
544+
@testset "Hessian Cache test" begin
545+
# https://github.com/JuliaDiff/FiniteDiff.jl/issues/185
546+
f(x) = sum(abs2, x)
547+
x1, x2 = float.(1:4), float.(5:8);
548+
@test FiniteDiff.finite_difference_hessian(f, x1, FiniteDiff.HessianCache(x1)) == Diagonal(2*ones(4))
549+
@test FiniteDiff.finite_difference_hessian(f, x1, FiniteDiff.HessianCache(x2)) == Diagonal(2*ones(4))
550+
end

0 commit comments

Comments
 (0)