I’m trying to do mixed symbolic and numeric derivatives. I want to define a type that holds a function that I will use to differentiate on in the future, this function may be ill-defined, so I would like to be able to operate on symbols.
In this MWE, I define an example type that stores the function. ForwardDiff
works fine with the symbolic arguments as long as the function definition is exact.
using Symbolics, ForwardDiff
struct ExampleType
func
end
function foo(obj, args)
tempfunc(θ) = obj.func(θ...)
return ForwardDiff.gradient(tempfunc, args)
end
myobj1 = ExampleType(+)
@variables r, θ
foo(myobj1, [r,θ]) # This works
The problem appears if I define a function that returns some sort of symbol.
function ω(r, θ)
@variables ω(..)
return ω(r,θ)
end
myobj2 = ExampleType(ω)
foo(myobj2, [r,θ]) # This does not work
I get the following error message when I attempt to do this.
ERROR: DimensionMismatch: gradient(f, x) expects that f(x) is a real number. Perhaps you meant jacobian(f, x)?
I’ve tried defining a custom diff_rule with no luck.
ForwardDiff.DiffRules.@define_diffrule Main.ω(r, θ) = :(Differential($r)(ω($r,$θ))), :(Differential($θ)(ω($r,$θ)))
f
Is there someway to define custom derivatives on these. sort of objects?