JuliaDiff / JuliaDiff/ForwardDiff.jl

derivative(f!, y, x) doesn't work if y is complex, even if x is real

Open
#818 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Julia
Stars
1k
Forks
160
PR merge metrics
No merged PRs in 30d

Description

Here is an MWE. For f(x) generating a complex array for x::Real, derivative(f, x) works:

julia> VERSION
v"1.12.6"

julia> using ForwardDiff: derivative

julia> f(x::Real) = [cis(x), cis(x)];

julia> derivative(f, 0.0)
2-element Vector{ComplexF64}:
 -0.0 + 1.0im
 -0.0 + 1.0im

However, derivative for an overwriting f! generates an error, if f! overwrites a complex array:

julia> f!(y::AbstractVector{<:Complex}, x::Real) = (y .= cis(x));

julia> y = Vector{ComplexF64}(undef, 2);  # f!(y, x) produces same result as y .= f(x)

julia> derivative(f!, y, 0.0)
ERROR: MethodError: no method matching ForwardDiff.DerivativeConfig(::typeof(f!), ::Vector{ComplexF64}, ::Float64)
The type `ForwardDiff.DerivativeConfig` exists, but no method is defined for this combination of argument types when trying to construct it.

Closest candidates are:
  ForwardDiff.DerivativeConfig(::F, ::AbstractArray{Y}, ::X) where {F, X<:Real, Y<:Real}
   @ ForwardDiff ~/code/ForwardDiff/src/config.jl:82
  ForwardDiff.DerivativeConfig(::F, ::AbstractArray{Y}, ::X, ::T) where {F, X<:Real, Y<:Real, T}
   @ ForwardDiff ~/code/ForwardDiff/src/config.jl:82

Stacktrace:
 [1] derivative(f!::typeof(f!), y::Vector{ComplexF64}, x::Float64)
   @ ForwardDiff ~/code/ForwardDiff/src/derivative.jl:27
 [2] top-level scope
   @ REPL[6]:1

Is this an intentional limitation of derivative(f!, y, x)? Given that f and f! in the above example perform the same calculation except that the latter is overwriting, it looks strange that derivative(f!, y, x) doesn't work while derivative(f, x) works.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with derivative.jl and config.jl, especially the derivative(f!, y, x) entry point and the DerivativeConfig methods shown in the error. Compare the real-array constraints with the complex output example, then determine whether the limitation should be fixed or documented and validate the result with relevant coverage.

Written by the indexing model from the issue text.

Assessment

Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.