How to take (mathematical) gradients with ModelingTookit.jl

Consider a Hamiltonian H=x^2 + y^2. I want automatically calculate Hamilton’s equation of motion by taking the partial derivatives wrt to x and y. How to do this with ModelingToolkit.jl? I cannot get calculate_gradient to work:

@ variables x y
H = x^2 + y^2
calculate_gradient(H)

results in

MethodError: no method matching calculate_gradient(::Symbolics.Num)

Closest candidates are:

calculate_gradient(!Matched::ModelingToolkit.OptimizationSystem)

@ ModelingToolkit C:\Users\Goran\.julia\packages\ModelingToolkit\xLMQM\src\systems\optimization\optimizationsystem.jl:118

Are you looking for the symbolic gradient? If so, you can calculate the partial derivatives symbolically using Symbolics.jl, which ModelingToolkit.jl is built on top of (as far as I know)

using ModelingToolkit, Symbolics

@variables x y
H = x^2 + y^2

Symbolics.derivative(H, x)
Symbolics.derivative(H, y)

2 Likes

Yes, exactly! Thank you very much!

1 Like