Closed bgctw closed 5 months ago
The problem here is that the parameter you're updating is stored in a Vector{Float64}
, but since you're trying to find gradients using ForwardDiff it tries to set it with a ForwardDiff.Dual
, which understandably throws that error. @ChrisRackauckas how do we want to support this workflow? Should there be a function that converts all the stored parameters to duals?
Also this is really an MTK thing, so maybe the issue should be transferred there? I can't do it since I don't have permissions for MTK
This should be using remake
. Mutation will never be the right answer if you're changing types.
This won't work with remake
either since that just copy
s the MTKParameters
object and calls setp
I just ran into this issue. Here is another (simpler) example using remake
, where I try to take the derivative of a DE solution that depends on 1 initial value and 1 parameter. I (naively?) expect this code to work:
using ModelingToolkit
using DifferentialEquations
using ForwardDiff
# an ODEProblem with 1 initial value and 1 parameter
@parameters k
@variables x y(x)
Dx = Differential(x)
@mtkbuild sys = ODESystem([Dx(y) ~ k], x)
prob0 = ODEProblem(sys, [y => NaN], (0, 1), [k => NaN]) # to-be-remade uninitialized problem
# a solution that depends on 1 initial value and 1 parameter
function f(y0val, kval)
prob = remake(prob0; u0=[y => y0val], p=[k => kval])
return solve(prob)[y][end] # == y(1)
end
f(1,2) # evaluate (works)
ForwardDiff.derivative(z -> f(z,2), 1) # derivative with respect to initial value (fails)
ForwardDiff.derivative(z -> f(1,z), 2) # derivative with respect to parameter (fails)
The last two lines fail with the same error as reported here. The derivative wrt the initial value can be fixed by substituting u0=[y => y0val]
to u0=ModelingToolkit.varmap_to_vars([y => y0val]
. But I can't find a way to get the derivative wrt the parameter work.
Intuitively, I would expect these two cases to work symmetrically, and for the above code to work without modification.
These are just my thoughts as an "end-user" 😃
I would have expected this code to work too. Seems there is a promotion that is missing.
How to use
setp
with ForwardDiff in cost function?When I update parameters inside a cost function with a setter that I obtained by
setp
, I get errors when trying to applyForwardDiff.gradient
to the cost function:What do I wrong in the following MWE?
resulting in error
using Julia 1.10 and package versions