A type error of Turing

I want to use Turing to fit parameters from my costume function like

function sersic2d(x, y; I_e::Float64=1.0, r_e::Float64=1.0, n::Float64=1.0, x0::Float64=1.0, y0::Float64=1.0)
    r = sqrt.((x .- x0) .^ 2 .+ (y .- y0) .^ 2)
    return I_e .* exp.(-b_n(n) .* ((r ./ r_e) .^ (1 / n) .- 1))
end

But I got error of

MethodError: no method matching sersic2d(::Matrix{Float64}, ::Matrix{Float64}, ::Float64, ::Float64, ::Float64, ::Float64, ::Float64)

Closest candidates are:
  sersic2d(::Any, ::Any; I_e, r_e, n, x0, y0)
   @ Main ~/Documents/VScodeProjects/Jens/jl_notebook_cell_df34fa98e69747e1a8f8a730347b8e2f_X44sZmlsZQ==.jl:12

It seems the type of parameter in my function doesn’t match the function. How can I fix it?

Plus, it turns out

TypeError: in keyword argument I_e, expected Float64, got a value of type ForwardDiff.Dual{ForwardDiff.Tag{Turing.TuringTag, Float64}, Float64, 6}

After I change ‘,’ to ‘;’ to separate keyword arguments.

It seems you called sersic2d by passing everything as a positional argument, instead of only the first two? Perhaps you forgot the semicolon ; that is meant to separate keyword arguments?

1 Like

Thanks, it works, but it turns out to be another error

TypeError: in keyword argument I_e, expected Float64, got a value of type ForwardDiff.Dual{ForwardDiff.Tag{Turing.TuringTag, Float64}, Float64, 6}

In order for ForwardDiff.jl to work it passes a special number (Dual) through your function. So if you restrict your function to only accept Float64 it won’t work with the Dual type that ForwardDiff passes to it. To solve this you could:

  1. Remove the types from the function signature entirely
  2. Relax the type assertions to <:Real
  3. Use a different autodiff backend such as Mooncake.jl

I would recommend doing #1 unless the types are actually used for dispatch.

Limitations of ForwardDiff: Limitations of ForwardDiff · ForwardDiff

How to switch autodiff backend in Turing: Automatic Differentiation – Turing.jl

Julia docs on when to use types in functions: Functions · The Julia Language

1 Like