%%
%
%% 1.2  Spherical coordinates (Computational example)
% We consider spherical coordinates \[\vec r = \left( {\begin{array}{*{20}{c}}
%   {r\sin \theta \cos \varphi } \\
%   {r\sin \theta \sin \varphi } \\
%   {r\cos \theta }
% \end{array}} \right)\]

clear all
syms r phi theta r_v real

%
%% 1 Space vector \vec r


r_v=[r * sin(theta) * cos(phi); r * sin(theta) * sin(phi); r * cos(theta)]

%
%% 2 Jacobian J und metric G=J^tJ
% J=\left({
% \partial x_i \over \partial q_j
% }\right), G=J'J, G_{inv}=G^{-1}

J=jacobian(r_v,[r theta phi])
G=simplify(J'*J)
G_inv=G^-1

%
%% 3 Volume of a sphere
% Invariant volume element: V_{inv}=\sqrt{(det(G))}
% Volume: V=
% \int \limits_0^{2\pi}
% \int \limits_0^\pi
% \int \limits_0^R
% V_{inv}
% dr d\theta d\varphi

syms R V 
assume(r>0 & theta>0 & theta<pi)
V_inv=simplify(sqrt(det(G)))
V=int(int(int(simplify(V_inv),r,0,R),theta,0,pi),phi,0,2*pi)

%
%% 4 Canonical momentum in spherical coordinates
% Generalized momenta:   $\left( {\begin{array}{*{20}{c}}
%   {{p_r}} \\
%   {{p_\vartheta }} \\
%   {{p_\varphi }}
% \end{array}} \right) = mG\left( {\begin{array}{*{20}{c}}
%   {\dot r} \\
%   {\dot \vartheta } \\
%   {\dot \varphi }
% \end{array}} \right)$

syms m p_v p_r p_theta p_phi T real
syms r(t) theta(t) phi(t)
Gvq=G*[r(t);theta(t);phi(t)];
disp(p_r==m*diff(Gvq(1),t)),disp(p_theta==m*diff(Gvq(2),t)),disp(p_phi==m*diff(Gvq(3),t))

%
%% 5 Kinetic energy
%  \[T = \frac{1}{{2m}}\left( {{p_r},{p_\theta },{p_\varphi }} \right){G^{ - 1}}\left( {\begin{array}{*{20}{c}}
%   {{p_r}} \\
%   {{p_\theta }} \\
%   {{p_\varphi }}
% \end{array}} \right)\]

[p_r;p_theta;p_phi]
T=1/(2*m)*ans'*G_inv*ans