DiffEqDiffTools - addtional variables in objective function

Hi, I have found DiffEqDiffTools.finite_difference_jacobian to be quite useful, thanks to the devs :smile:

I just have a question regarding passing additional variables in the objective function. The standard format would be:

function f(fvec,x)
    fvec[1] = (x[1]+3)*(x[2]^3-7)+18
    fvec[2] = sin(x[2]*exp(x[1])-1)

which would work with e.g.:

J = DiffEqDiffTools.finite_difference_jacobian(f, x)

however, what if I needed to pass additional variables into the function:

function f(fvec,x,constants)
    fvec[1] = (x[1]+3)*(x[2]^3-7)+18 + constants[1]*x[1] + constants[2]
    fvec[2] = sin(x[2]*exp(x[1])-1) - constants[3]

This function definition does not work with DiffEqDiffTools.finite_difference_jacobian since it expects f((::Array{Float64,1}, ::Array{Float64,1})). In the above case without making “constants” global, is there a way to pass the variable to the function and still be compatible with DiffEqDiffTools.finite_difference_jacobian? Note, in my actual usage case there are a large number of structs being passed into the objective function and since it is computing a relatively large Jacobian the function calls need to be as efficient as possible.


Use a closure:

J = DiffEqDiffTools.finite_difference_jacobian((fvec,x)->f(fvec,x,constants), x)

Thanks a lot for the answer (to a probably a trivial question)