Autodiff working for my model function but not for my loss function

global c = data[:,2]
c_model = zeros(length(t), length(x))
function loss_julia(p::Vector{T}) where T
    (...)
    pulse_injection(c_model, x, t, c0, c_in, vp, De, t_pulse)
    return sum((c_model[:, 1] .- c).^2)
end

This is not good:

  1. Your function depends on global variables, this should be avoided almost always
  2. It looks like your pulse_injection function mutates its input arguments, conventionally this is denoted in Julia by appending a bang to the function name (pulse_injection!)
  3. You fix the type of c_model to be Array{Float64} in your zeros call. You want zeros(eltype(z), length(t), length(x)) if you are using this array in autodiff code, as it will need to accomodate dual numbers:
julia> using ForwardDiff

julia> x = zeros(3)
3-element Vector{Float64}:
 0.0
 0.0
 0.0

julia> x[1] = ForwardDiff.Dual(1)
ERROR: MethodError: no method matching Float64(::ForwardDiff.Dual{Nothing, Int64, 0})
2 Likes