Let’s say I have an expensive scalar that shows up multiple times in my set of differential equations. Is there a way to tell ModelingToolkit to hoist that calculation out and only do it once? If I use an intermediate calculation it seems to just get copied everywhere it is used. E.g. using cosine as an dummy expensive calculation:
@parameters ω, t
@variables ψ₁(t), ψ₂(t)
@derivatives D'~t
expensive_f = cos(ω*t)
eqs = [D(ψ₁) ~ expensive_f*ψ₂,
D(ψ₂) ~ expensive_f*ψ₁]
de = ODESystem(eqs)
generate_function(de)[2]
:((var"##MTIIPVar#335", var"##MTKArg#331", var"##MTKArg#332", var"##MTKArg#333")->begin
@inbounds begin
let (ψ₁, ψ₂, ω, t) = (var"##MTKArg#331"[1], var"##MTKArg#331"[2], var"##MTKArg#332"[1], var"##MTKArg#333")
var"##MTIIPVar#335"[1] = cos(ω * t) * ψ₂
var"##MTIIPVar#335"[2] = cos(ω * t) * ψ₁
end
end
nothing
end)
Looking through the @code_llvm there are still two cos calls and but by @code_native there is only one. Perhaps the compiler is always clever enough to pick this up…