# How to take (mathematical) gradients with ModelingTookit.jl

**URL:** <https://discourse.julialang.org/t/how-to-take-mathematical-gradients-with-modelingtookit-jl/102161>\
**Category:** Modelling & Simulations\
**Created:** [July 27, 2023, 3:32pm UTC](https://discourse.julialang.org/t/how-to-take-mathematical-gradients-with-modelingtookit-jl/102161 "2023-07-27T15:32:07Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jamblejoe](https://avatars.discourse-cdn.com/v4/letter/j/ee7513/32.png) [@jamblejoe](https://discourse.julialang.org/u/jamblejoe)\
**Post date:** [July 27, 2023, 3:32pm UTC](https://discourse.julialang.org/t/how-to-take-mathematical-gradients-with-modelingtookit-jl/102161/1 "2023-07-27T15:32:07Z")

</div>

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:

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

```

results in

```julia
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

```

---

<div class="post-metadata">

**Author:** ![Dale\_James\_Black](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/dale_james_black/32/11595_2.png) [@Dale\_James\_Black](https://discourse.julialang.org/u/Dale_James_Black)\
**Post date:** [July 27, 2023, 6:18pm UTC](https://discourse.julialang.org/t/how-to-take-mathematical-gradients-with-modelingtookit-jl/102161/2 "2023-07-27T18:18:10Z")

</div>

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)

```julia
using ModelingToolkit, Symbolics

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

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

```

 ![image](https://global.discourse-cdn.com/julialang/original/3X/c/a/cace917ba3b2163670bea1b1dc1d49ad29efceaa.png)

---

<div class="post-metadata">

**Author:** ![jamblejoe](https://avatars.discourse-cdn.com/v4/letter/j/ee7513/32.png) [@jamblejoe](https://discourse.julialang.org/u/jamblejoe)\
**Post date:** [July 27, 2023, 8:30pm UTC](https://discourse.julialang.org/t/how-to-take-mathematical-gradients-with-modelingtookit-jl/102161/3 "2023-07-27T20:30:46Z")

</div>

Yes, exactly! Thank you very much!
