Skip to content
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

non mutating gradient #159

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
30 changes: 29 additions & 1 deletion src/gradients.jl
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,12 @@ function finite_difference_gradient(
end
end
cache = GradientCache(df, x, fdtype, returntype, inplace)
finite_difference_gradient!(df, f, x, cache, relstep=relstep, absstep=absstep, dir=dir)
if typeof(x) <: AbstractArray && fdtype == Val(:central)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why the check for AbstractArray? I would think that the non-! call should always do a non-mutating version by default.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The check for AbstractArray is only because I changed the vector->scalar code and not the scalar->vector code.
Since by #157 , the latter should be replaced with jacobian calls.
Once that is done, x should be restrained to Num.

df = finite_difference_gradient(f, x, cache, relstep=relstep, absstep=absstep, dir=dir)
else
df = finite_difference_gradient!(df,f, x, cache, relstep=relstep, absstep=absstep, dir=dir)
end
return df
end

function finite_difference_gradient!(
Expand Down Expand Up @@ -169,6 +174,29 @@ end

# vector of derivatives of a vector->scalar map by each component of a vector x
# this ignores the value of "inplace", because it doesn't make much sense
function finite_difference_gradient(
f,
x::AbstractVector{<:Number},
cache::GradientCache{T1,T2,T3,T4,fdtype,returntype,inplace};
relstep=default_relstep(fdtype, eltype(x)),
absstep=relstep,
dir=true) where {T1,T2,T3,T4,fdtype,returntype,inplace}

df = deepcopy(x) # how to get correct output type here cache.returntype

if fdtype == Val(:central)
@inbounds for i ∈ eachindex(x)
epsilon = compute_epsilon(fdtype, x[i], relstep, absstep, dir)
c1 = f(setindex(x,x[i]+epsilon ,i))
c2 = f(setindex(x,x[i]-epsilon ,i))
dfi = (c1-c2)/(2epsilon)
df = setindex(df,dfi,i)
end
else
fdtype_error(returntype)
end
df
end
function finite_difference_gradient!(
df,
f,
Expand Down