Reputation: 13
I'm trying to get a Jacobian matrix for L, with a vector q and q^dot, but couldn't get a proper matrix. Could anyone help me to get the matrix by using this Zygote package correctly? FYI, I'm totally noob to this differentiable programming world. Any references to study DP or AD from scratch would be also welcomed. Thank you :)
using LinearAlgebra
using Zygote
using DifferentialEquations
## CONSTANTS
g = 9.81;
## PARAMS
m₁ = 1;
m₂ = 1;
l₁ = 1;
l₂ = 1;
## TEST SAMPLE
θ₁=30*pi/180;
θ₂=15*pi/180;
ω₁=2.;
ω₂=1.;
q1 = [θ₁;θ₂]
q̇1 = [ω₁;ω₂]
##
M(q)=[(m₁+m₂)*l₁^2 l₁*l₂*m₂*cos(q[1]-q[2]);
l₁*l₂*m₂*cos(q[1]-q[2]) m₂*l₂^2];
U(q) = g*(m₁*(-l₁*cos(q[1])) +
m₂*(-l₁*cos(q[1])-l₂*cos(q[2])));
T(q,q̇) = ((1/2).*q̇'*M(q)*q̇)[1]
V(q,q̇) = U(q)
L(q,q̇) = T(q,q̇) - V(q,q̇);
## gradient((a, b) -> a*b, 2, 3)
∂L_∂q(f,q,q̇) = gradient(f,q,q̇)[1]; #Partial Diff. w/ q Vector
∂L_∂q̇(f,q,q̇) = gradient(f,q,q̇)[2]; #Partial Diff. w/ q̇ Vector
∂L_∂q(L,q1,q̇1) #OKAY
∂L_∂q̇(L,q1,q̇1) #OKAY
∂∂L_∂q∂q̇(f,q,q̇) = gradient(((q, q̇) -> ∂L_∂q(f,q,q̇)),q,q̇)[2];
∂∂L_∂q∂q̇(L,q1,q̇1) #ERROR
Upvotes: 1
Views: 479
Reputation: 19152
Zygote over Zygote won't currently work, so I would recommend Tracker over Zygote for this:
using LinearAlgebra
using Zygote
using DifferentialEquations
import Tracker
## CONSTANTS
g = 9.81;
## PARAMS
m₁ = 1;
m₂ = 1;
l₁ = 1;
l₂ = 1;
## TEST SAMPLE
θ₁=30*pi/180;
θ₂=15*pi/180;
ω₁=2.;
ω₂=1.;
q1 = [θ₁;θ₂]
q̇1 = [ω₁;ω₂]
##
M(q)=[(m₁+m₂)*l₁^2 l₁*l₂*m₂*cos(q[1]-q[2]);
l₁*l₂*m₂*cos(q[1]-q[2]) m₂*l₂^2];
U(q) = g*(m₁*(-l₁*cos(q[1])) +
m₂*(-l₁*cos(q[1])-l₂*cos(q[2])));
T(q,q̇) = ((1/2).*q̇'*M(q)*q̇)[1]
V(q,q̇) = U(q)
L(q,q̇) = T(q,q̇) - V(q,q̇);
## gradient((a, b) -> a*b, 2, 3)
∂L_∂q(f,q,q̇) = gradient(f,q,q̇)[1]; #Partial Diff. w/ q Vector
∂L_∂q̇(f,q,q̇) = gradient(f,q,q̇)[2]; #Partial Diff. w/ q̇ Vector
∂L_∂q(L,q1,q̇1) #OKAY
∂L_∂q̇(L,q1,q̇1) #OKAY
∂∂L_∂q∂q̇(f,q,q̇) = Tracker.gradient(((q, q̇) -> ∂L_∂q(f,q,q̇)),q,q̇)[2];
∂∂L_∂q∂q̇(L,q1,q̇1)
Upvotes: 1