Skip to content

Fix to_vec with Integers #191

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name = "FiniteDifferences"
uuid = "26cc04aa-876d-5657-8c51-4c34ba976000"
version = "0.12.18"
version = "0.12.19"

[deps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
Expand Down
2 changes: 1 addition & 1 deletion src/grad.jl
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,4 @@ end

Compute the gradient of `f` for any `xs` for which [`to_vec`](@ref) is defined.
"""
grad(fdm, f, xs...) = j′vp(fdm, f, 1, xs...) # `j′vp` with seed of 1
grad(fdm, f, xs...) = j′vp(fdm, f, one(f(xs...)), xs...) # `j′vp` with seed of 1
5 changes: 5 additions & 0 deletions src/to_vec.jl
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ function to_vec(z::Complex)
return [real(z), imag(z)], Complex_from_vec
end

function to_vec(x::Integer)
Integer_from_vec(_) = x
return Bool[], Integer_from_vec
end

# Base case -- if x is already a Vector{<:Real} there's no conversion necessary.
to_vec(x::Vector{<:Real}) = (x, identity)

Expand Down
8 changes: 8 additions & 0 deletions test/to_vec.jl
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,14 @@ function test_to_vec(x::T; check_inferred=true) where {T}
end

@testset "to_vec" begin

# Integers are non-differentiable. to_vec should only preserve the differentiable bits
# of a type so that they can be appropriately perturbed.
@testset "Int" begin
@test isempty(to_vec(4)[1])
test_to_vec(5)
end

@testset "$T" for T in (Float32, ComplexF32, Float64, ComplexF64)
if T == Float64
test_to_vec(1.0)
Expand Down