$$ \newcommand{\dint}{\mathrm{d}} \newcommand{\vphi}{\boldsymbol{\phi}} \newcommand{\vpi}{\boldsymbol{\pi}} \newcommand{\vpsi}{\boldsymbol{\psi}} \newcommand{\vomg}{\boldsymbol{\omega}} \newcommand{\vsigma}{\boldsymbol{\sigma}} \newcommand{\vzeta}{\boldsymbol{\zeta}} \renewcommand{\vx}{\mathbf{x}} \renewcommand{\vy}{\mathbf{y}} \renewcommand{\vz}{\mathbf{z}} \renewcommand{\vh}{\mathbf{h}} \renewcommand{\b}{\mathbf} \renewcommand{\vec}{\mathrm{vec}} \newcommand{\vecemph}{\mathrm{vec}} \newcommand{\mvn}{\mathcal{MN}} \newcommand{\G}{\mathcal{G}} \newcommand{\M}{\mathcal{M}} \newcommand{\N}{\mathcal{N}} \newcommand{\S}{\mathcal{S}} \newcommand{\diag}[1]{\mathrm{diag}(#1)} \newcommand{\diagemph}[1]{\mathrm{diag}(#1)} \newcommand{\tr}[1]{\text{tr}(#1)} \renewcommand{\C}{\mathbb{C}} \renewcommand{\R}{\mathbb{R}} \renewcommand{\E}{\mathbb{E}} \newcommand{\D}{\mathcal{D}} \newcommand{\inner}[1]{\langle #1 \rangle} \newcommand{\innerbig}[1]{\left \langle #1 \right \rangle} \newcommand{\abs}[1]{\lvert #1 \rvert} \newcommand{\norm}[1]{\lVert #1 \rVert} \newcommand{\two}{\mathrm{II}} \newcommand{\GL}{\mathrm{GL}} \newcommand{\Id}{\mathrm{Id}} \newcommand{\grad}[1]{\mathrm{grad} \, #1} \newcommand{\gradat}[2]{\mathrm{grad} \, #1 \, \vert_{#2}} \newcommand{\Hess}[1]{\mathrm{Hess} \, #1} \newcommand{\T}{\text{T}} \newcommand{\dim}[1]{\mathrm{dim} \, #1} \newcommand{\partder}[2]{\frac{\partial #1}{\partial #2}} \newcommand{\rank}[1]{\mathrm{rank} \, #1} $$

Riemannian Geometry

Charts, metrics, geodesics and curvature on the sphere, with proofs, Python checks and small exercises.

Learning goals: use charts and tangent vectors; compute metrics, lengths and gradients; write geodesics, exponential maps and Hessians; measure curvature by holonomy.

Context and objectives

Course

Why do we need geometry on curved spaces?

Many unknowns do not live in a vector space. An orientation is a rotation matrix, a direction is a point of a sphere, a covariance is a positive definite matrix, a probability distribution is a point of a family with its own geometry. On such a set $\mathcal M$ we still want to differentiate functions, measure lengths, move in a straight line and optimize. Riemannian geometry provides these tools: it replaces the vector space $\mathbb R^n$ by a manifold, a space that looks like $\mathbb R^n$ near each point, and the dot product by a metric, an inner product that varies from point to point.

In this course the model example is the unit sphere $\mathbb S^2\subset\mathbb R^3$. Every notion is introduced on it with formulas, checked numerically in Python, and, when it is useful, proved. The second page, Optimization and Gradient Descent on Riemannian Manifolds, uses these tools to optimize.

A sphere with a tangent plane at a point, a geodesic and a velocity vector
A point of the sphere moves along a great circle; the velocity vector lies in the tangent plane.
Exercise

Objectives to carry out

  1. Cover the sphere with charts and check that tangent vectors are velocities of curves, orthogonal to the position (Part 1).
  2. Compute the metric induced by $\mathbb R^3$ in coordinates, the length of a curve and the Riemannian gradient, and prove that the gradient is the direction of steepest ascent (Part 2).
  3. Write the exponential and logarithm maps of the sphere, the Christoffel symbols and the geodesic equation, and check them against each other (Part 3).
  4. Compute a Riemannian Hessian and check it along geodesics (Part 3).
  5. Transport a vector around a spherical triangle and measure the holonomy; relate it to the curvature and to the area (Part 4).
  6. Deliver a short report with the numbers and the proofs (Part 5).

Each part starts with the mathematics (definitions, propositions, proofs) and proposes small exercises with a light Python starting code (TO DO lines). The correction, folded just after, is commented line by line. Try the exercise before opening it.

Course

How to work: environment

Install numpy matplotlib in a Python 3.9 or later environment (checked with Python 3.12 and NumPy 2). Run the blocks of the parts in order in one notebook or session: later exercises reuse earlier functions. The code uses finite differences so that every formula can be checked with the same tool.

PythonCode provided · imports, random generator and spherical coordinates
import numpy as npimport matplotlib.pyplot as pltrng = np.random.default_rng(0)np.set_printoptions(precision=6, suppress=True)def unit(v):    return v / np.linalg.norm(v)def X(theta, phi):    """Spherical coordinates -> point of the unit sphere S^2 in R^3."""    return np.array([np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)])

Part 1 · Manifolds, charts and tangent vectors

Course

Manifolds and charts

DefinitionManifold

A (smooth) manifold of dimension $n$ is a set $\mathcal M$ covered by charts: bijections $\varphi:U\to\varphi(U)\subset\mathbb R^n$ from open subsets $U\subset\mathcal M$ onto open subsets of $\mathbb R^n$, such that the changes of chart $\varphi_2\circ\varphi_1^{-1}$ are smooth wherever they are defined. A function on $\mathcal M$ is smooth if it is smooth in every chart.

Example: the sphere. No single chart covers $\mathbb S^2$ (a sphere is compact and a plane is not), but two do. The stereographic projection from the north pole $N=(0,0,1)$ sends $p=(p_1,p_2,p_3)\neq N$ to the point where the line $Np$ meets the plane $z=0$:

\[\varphi(p)=\frac{(p_1,p_2)}{1-p_3},\qquad \varphi^{-1}(u)=\frac{(2u_1,\,2u_2,\,|u|^2-1)}{|u|^2+1}.\]

A second chart, the projection from the south pole, covers $N$. Check: if $s=|u|^2$ then $|\varphi^{-1}(u)|^2=(4s+(s-1)^2)/(s+1)^2=1$, so $\varphi^{-1}(u)$ is on the sphere.

Exercise

Exercise 1.1 · a chart of the sphere

  1. Write the stereographic projection chart and its inverse chart_inv.
  2. Check on random points that the two maps are inverse of each other and that chart_inv(u) has norm 1.
PythonStarting code · stereographic chart
def chart(p):    return ...  # TO DO: the plane point (u1, u2) = (p1, p2) / (1 - p3)def chart_inv(u):    s = u @ u    return ...  # TO DO: (2u1, 2u2, |u|^2 - 1) / (|u|^2 + 1)p = unit(rng.normal(size=3))                # a random point of the sphereu = rng.normal(size=2)                      # a random point of the planeprint("chart_inv(chart(p)) = p     :", np.allclose(chart_inv(chart(p)), p))print("chart(chart_inv(u)) = u     :", np.allclose(chart(chart_inv(u)), u))print("chart_inv(u) is on the sphere:", np.isclose(np.linalg.norm(chart_inv(u)), 1))
Show the correction
PythonComplete solution · chart and inverse chart
def chart(p):    # Stereographic projection from the north pole N = (0, 0, 1): the line through N and p meets the plane z = 0 at chart(p).    return p[:2] / (1 - p[2])  # the plane point (u1, u2) = (p1, p2) / (1 - p3)def chart_inv(u):    # s = |u|^2. The inverse is the point of the sphere on the line through N and (u1, u2, 0).    s = u @ u    return np.array([2 * u[0], 2 * u[1], s - 1]) / (s + 1)  # (2u1, 2u2, |u|^2 - 1) / (|u|^2 + 1)p = unit(rng.normal(size=3))                # a random point of the sphereu = rng.normal(size=2)                      # a random point of the planeprint("chart_inv(chart(p)) = p     :", np.allclose(chart_inv(chart(p)), p))print("chart(chart_inv(u)) = u     :", np.allclose(chart(chart_inv(u)), u))print("chart_inv(u) is on the sphere:", np.isclose(np.linalg.norm(chart_inv(u)), 1))

The chart is a bijection between the sphere without its north pole and the whole plane: near $N$ the points of the sphere are sent far away. This is the price of covering a compact space with a chart.

Course

Tangent vectors

DefinitionTangent vector and tangent space

A tangent vector at $p\in\mathcal M$ is the velocity $\gamma'(0)$ of a smooth curve $\gamma$ with $\gamma(0)=p$. They form the tangent space $T_p\mathcal M$, a vector space of dimension $n$. In a chart, $\gamma$ becomes a curve $x(t)=\varphi(\gamma(t))$ of $\mathbb R^n$ and the velocity is represented by $\dot x(0)\in\mathbb R^n$.

The sphere as a submanifold of $\mathbb R^3$. If $\gamma$ is a curve on the sphere, $|\gamma(t)|^2=1$ for all $t$; differentiating gives $2\,\gamma(t)\cdot\gamma'(t)=0$. Hence $T_p\mathbb S^2\subset\{v:p\cdot v=0\}$, and both sets are planes, so

\[T_p\mathbb S^2=\{v\in\mathbb R^3:\ p\cdot v=0\}.\]

Moreover, the Jacobian of $\varphi^{-1}$ at $u$ maps $w\in\mathbb R^2$ to the velocity of $t\mapsto\varphi^{-1}(u+tw)$, and has rank $2$: its two columns span the tangent plane. The orthogonal projection onto $T_p\mathbb S^2$ is $P_p(z)=z-(p\cdot z)\,p$; it is linear, symmetric and satisfies $P_p^2=P_p$.

Exercise

Exercise 1.2 · tangent vectors and projection

  1. Compute the velocity of the curve $t\mapsto\varphi^{-1}(u_0+tw)$ at $t=0$ by a central difference, and check that it is orthogonal to the position.
  2. Build the $3\times2$ Jacobian of $\varphi^{-1}$ and check that its rank is 2.
  3. Write the orthogonal projection onto $T_p\mathbb S^2$ and check that it is idempotent and symmetric.
PythonStarting code · tangent vectors
u0 = np.array([0.3, -0.5])                  # a point of the plane (the chart domain)w = np.array([1.0, 2.0])                    # a direction in the planep0 = chart_inv(u0)def velocity(u0, w, h=1e-6):    return ...  # TO DO: central finite difference in tv = velocity(u0, w)print("v . p0 =", v @ p0, "(a tangent vector is orthogonal to p0)")J = ...  # TO DO: 3 x 2 matrix, column j = velocity along e_jprint("rank of J:", np.linalg.matrix_rank(J, tol=1e-6), "(dimension of the manifold)")def project(p, v):    return ...  # TO DO: v minus its component along pz = rng.normal(size=3)Pz = project(p0, z)print("P(P z) = P z:", np.allclose(project(p0, Pz), Pz), "| P z . p0 =", Pz @ p0)print("P is symmetric:", np.allclose(np.stack([project(p0, e) for e in np.eye(3)]), np.stack([project(p0, e) for e in np.eye(3)]).T))
Show the correction
PythonComplete solution · velocities, Jacobian and projection
u0 = np.array([0.3, -0.5])                  # a point of the plane (the chart domain)w = np.array([1.0, 2.0])                    # a direction in the planep0 = chart_inv(u0)def velocity(u0, w, h=1e-6):    # The curve t -> chart_inv(u0 + t w) lies on the sphere; its velocity at t = 0 is a tangent vector at p0. Central difference of order 2.    return (chart_inv(u0 + h * w) - chart_inv(u0 - h * w)) / (2 * h)  # central finite difference in tv = velocity(u0, w)print("v . p0 =", v @ p0, "(a tangent vector is orthogonal to p0)")# The Jacobian of chart_inv at u0 has two columns (one per coordinate direction): they span the tangent plane.J = np.stack([velocity(u0, e) for e in np.eye(2)], axis=1)  # 3 x 2 matrix, column j = velocity along e_jprint("rank of J:", np.linalg.matrix_rank(J, tol=1e-6), "(dimension of the manifold)")def project(p, v):    # Orthogonal projection onto T_p S^2 = {v : p . v = 0}: remove the component along p.    return v - (p @ v) * p  # v minus its component along pz = rng.normal(size=3)Pz = project(p0, z)print("P(P z) = P z:", np.allclose(project(p0, Pz), Pz), "| P z . p0 =", Pz @ p0)print("P is symmetric:", np.allclose(np.stack([project(p0, e) for e in np.eye(3)]), np.stack([project(p0, e) for e in np.eye(3)]).T))

The central difference has an error of order $h^2$ and rounding errors of order $10^{-16}/h$: $h=10^{-6}$ gives about $10^{-10}$, which is why $v\cdot p_0$ is not exactly zero.

Part 2 · Metrics, lengths and the gradient

Course

Riemannian metric and length

DefinitionRiemannian metric and length

A Riemannian metric $g$ gives each tangent space an inner product $g_p(\cdot,\cdot)$ that depends smoothly on $p$. In a chart it is a symmetric positive definite matrix $G(x)$: $g(v,w)=v^{\top}G(x)\,w$. The length of a curve $\gamma:[a,b]\to\mathcal M$ is

\[L(\gamma)=\int_a^b\sqrt{g_{\gamma(t)}(\gamma'(t),\gamma'(t))}\,dt=\int_a^b\sqrt{\dot x^{\top}G(x)\,\dot x}\,dt,\]

and the distance between two points is the infimum of the lengths of the curves joining them.

DefinitionInduced metric

The induced metric. For a submanifold of $\mathbb R^N$ parametrized by $X(x)$, we measure vectors with the dot product of $\mathbb R^N$. If $J=DX(x)$ is the Jacobian, the tangent vectors $\partial_iX$ have dot products $g_{ij}=\partial_iX\cdot\partial_jX$, that is

\[G=J^{\top}J.\]

For the sphere in coordinates $(\theta,\varphi)$, $X=(\sin\theta\cos\varphi,\sin\theta\sin\varphi,\cos\theta)$, we get $\partial_\theta X\cdot\partial_\theta X=1$, $\partial_\varphi X\cdot\partial_\varphi X=\sin^2\theta$ and $\partial_\theta X\cdot\partial_\varphi X=0$:

\[G(\theta,\varphi)=\begin{pmatrix}1&0\\0&\sin^2\theta\end{pmatrix}.\]
Exercise

Exercise 2.1 · the induced metric and the length of a curve

  1. Compute the Jacobian of $X(\theta,\varphi)$ by central differences and the metric $G=J^{\top}J$. Compare with $\operatorname{diag}(1,\sin^2\theta)$.
  2. Write the length of a curve given in coordinates, with a trapezoid rule for the integral.
  3. Check the length of a circle of latitude $\theta=\theta_0$: it should be $2\pi\sin\theta_0$.
PythonStarting code · metric and length
def jacobian(theta, phi, h=1e-6):    dth = (X(theta + h, phi) - X(theta - h, phi)) / (2 * h)    dph = (X(theta, phi + h) - X(theta, phi - h)) / (2 * h)    return np.stack([dth, dph], axis=1)def metric(theta, phi):    J = jacobian(theta, phi)    return ...  # TO DO: the Gram matrix of the two coordinate vectorsth, ph = 1.0, 0.7print(metric(th, ph))print("expected diag(1, sin^2 theta):", np.diag([1, np.sin(th) ** 2]).tolist())def length(curve, t0, t1, n=2000):    ts = np.linspace(t0, t1, n + 1)    pts = np.array([curve(t) for t in ts])                  # the curve in coordinates (theta, phi)    vel = np.gradient(pts, ts, axis=0)                      # its velocity gamma'(t)    speed = ...  # TO DO: |gamma'|_g = sqrt(gamma'^T G gamma')    return np.trapezoid(speed, ts)th0 = 1.1print("length of the circle of latitude:", length(lambda t: np.array([th0, t]), 0, 2 * np.pi), "| expected 2 pi sin(theta0) =", 2 * np.pi * np.sin(th0))
Show the correction
PythonComplete solution · induced metric and length of a curve
def jacobian(theta, phi, h=1e-6):    # Column 0 = dX/dtheta, column 1 = dX/dphi, by central differences.    dth = (X(theta + h, phi) - X(theta - h, phi)) / (2 * h)    dph = (X(theta, phi + h) - X(theta, phi - h)) / (2 * h)    return np.stack([dth, dph], axis=1)def metric(theta, phi):    J = jacobian(theta, phi)    # The metric induced by R^3: g_ij = <dX/dx^i, dX/dx^j> = (J^T J)_ij. It is a symmetric positive definite 2 x 2 matrix.    return J.T @ J  # the Gram matrix of the two coordinate vectorsth, ph = 1.0, 0.7print(metric(th, ph))print("expected diag(1, sin^2 theta):", np.diag([1, np.sin(th) ** 2]).tolist())def length(curve, t0, t1, n=2000):    ts = np.linspace(t0, t1, n + 1)    pts = np.array([curve(t) for t in ts])                  # the curve in coordinates (theta, phi)    vel = np.gradient(pts, ts, axis=0)                      # its velocity gamma'(t)    speed = np.array([np.sqrt(v @ metric(*x) @ v) for x, v in zip(pts, vel)])  # |gamma'|_g = sqrt(gamma'^T G gamma')    return np.trapezoid(speed, ts)th0 = 1.1print("length of the circle of latitude:", length(lambda t: np.array([th0, t]), 0, 2 * np.pi), "| expected 2 pi sin(theta0) =", 2 * np.pi * np.sin(th0))

The length does not depend on the parametrization of the curve (it is the integral of the speed measured with $g$), and it agrees with the Euclidean length of the curve in $\mathbb R^3$, since the metric is induced by $\mathbb R^3$.

Course

The Riemannian gradient

DefinitionRiemannian gradient

For a smooth function $f:\mathcal M\to\mathbb R$, the differential $df_p$ is the linear form $v\mapsto df_p(v)$, the derivative of $f$ along a curve of velocity $v$. The Riemannian gradient is the tangent vector $\operatorname{grad}f(p)\in T_p\mathcal M$ defined by

\[g_p\big(\operatorname{grad}f(p),v\big)=df_p(v)\quad\text{for every }v\in T_p\mathcal M.\]

In a chart, $df$ is the row vector $d=(\partial_1f,\dots,\partial_nf)$ and, since $g(h,v)=h^{\top}Gv$, the gradient is $h=G^{-1}d^{\top}$: the metric raises the index of $df$. For the Euclidean metric $G=I$ we recover the usual gradient.

PropositionSteepest ascent

Among the tangent vectors $v$ with $|v|_g=1$, the directional derivative $df_p(v)$ is largest for $v=\operatorname{grad}f/|\operatorname{grad}f|_g$, and the maximum is $|\operatorname{grad}f|_g$.

Proof

By definition of the gradient and the Cauchy–Schwarz inequality for the inner product $g_p$, $df_p(v)=g(\operatorname{grad}f,v)\le|\operatorname{grad}f|_g\,|v|_g=|\operatorname{grad}f|_g$, with equality if and only if $v$ is a positive multiple of $\operatorname{grad}f$. $\square$

PropositionGradient on a submanifold of $\mathbb R^N$

If $f$ is the restriction of a smooth function $\bar f$ of $\mathbb R^N$, then $\operatorname{grad}f(p)=P_p\,\nabla\bar f(p)$.

Proof

For $v\in T_p\mathcal M$, $g(P_p\nabla\bar f,v)=\nabla\bar f\cdot v$ because $v$ is orthogonal to $\nabla\bar f-P_p\nabla\bar f$, and $\nabla\bar f\cdot v=d\bar f(v)=df(v)$. $\square$

Exercise

Exercise 2.2 · the gradient in coordinates and on the submanifold

  1. For $f(p)=a\cdot p$ on the sphere, compute $df$ in coordinates by central differences, then the gradient $h=G^{-1}d^{\top}$.
  2. Check the characterization $g(h,v)=df(v)$ for a random $v$, and that $J\,h$ equals the projection of $a$ onto the tangent plane.
  3. Check the steepest-ascent proposition by sampling unit vectors for $g$.
PythonStarting code · gradient
a = np.array([0.3, -0.4, 0.8])              # f(p) = a . p, a "height" function on the spheref = lambda th, ph: a @ X(th, ph)th, ph = 1.0, 0.7h = 1e-6d = np.array([(f(th + h, ph) - f(th - h, ph)) / (2 * h), (f(th, ph + h) - f(th, ph - h)) / (2 * h)])    # df in coordinates: row of partial derivativesG = metric(th, ph)grad = ...  # TO DO: coordinates of grad f: solve G h = d (raising an index)v = rng.normal(size=2)                      # any tangent vector in coordinatesprint("g(grad f, v) = df(v):", np.isclose(grad @ G @ v, d @ v))p = X(th, ph)embedded = ...  # TO DO: projection of a onto the tangent plane at pprint("J h equals the projection of a:", np.allclose(jacobian(th, ph) @ grad, embedded, atol=1e-6))best = grad / np.sqrt(grad @ G @ grad)cands = rng.normal(size=(20000, 2))cands /= np.sqrt(np.einsum("ni,ij,nj->n", cands, G, cands))[:, None]       # unit vectors for gprint("best sampled df(v):", (cands @ d).max(), "| df(best) =", d @ best, "| |grad|_g =", np.sqrt(grad @ G @ grad))
Show the correction
PythonComplete solution · three ways to see the gradient
a = np.array([0.3, -0.4, 0.8])              # f(p) = a . p, a "height" function on the spheref = lambda th, ph: a @ X(th, ph)th, ph = 1.0, 0.7h = 1e-6d = np.array([(f(th + h, ph) - f(th - h, ph)) / (2 * h), (f(th, ph + h) - f(th, ph - h)) / (2 * h)])    # df in coordinates: row of partial derivativesG = metric(th, ph)grad = np.linalg.solve(G, d)  # coordinates of grad f: solve G h = d (raising an index)v = rng.normal(size=2)                      # any tangent vector in coordinatesprint("g(grad f, v) = df(v):", np.isclose(grad @ G @ v, d @ v))# Embedded formula: the Riemannian gradient on a submanifold is the orthogonal projection of the Euclidean gradient (here grad of a.p is a).p = X(th, ph)embedded = a - (a @ p) * p  # projection of a onto the tangent plane at pprint("J h equals the projection of a:", np.allclose(jacobian(th, ph) @ grad, embedded, atol=1e-6))# Steepest ascent: among the unit tangent vectors (for g), the directional derivative df(v) is largest for v = grad / |grad|_g.best = grad / np.sqrt(grad @ G @ grad)cands = rng.normal(size=(20000, 2))cands /= np.sqrt(np.einsum("ni,ij,nj->n", cands, G, cands))[:, None]       # unit vectors for gprint("best sampled df(v):", (cands @ d).max(), "| df(best) =", d @ best, "| |grad|_g =", np.sqrt(grad @ G @ grad))

The three computations agree: raising the index with $G^{-1}$, projecting the Euclidean gradient, and the best of 20,000 sampled unit directions all give the same direction, with $|\operatorname{grad}f|_g\approx0.8504$.

Part 3 · Geodesics, exponential map and Hessian

Course

Geodesics and the exponential map

DefinitionGeodesic

A geodesic is a curve that does not accelerate within the manifold. For a submanifold of $\mathbb R^N$ this means that the acceleration $\gamma''$ of the curve in $\mathbb R^N$ is orthogonal to the tangent space: $P_{\gamma(t)}\gamma''(t)=0$. A geodesic has constant speed, and locally it is the shortest path between its end points.

PropositionGeodesics of the sphere

The geodesics of the unit sphere are the great circles, $\gamma(t)=\cos(t|v|)\,p+\sin(t|v|)\,v/|v|$ with $p\cdot v=0$.

Proof

Let $\gamma$ be this curve. Then $\gamma''(t)=-|v|^2\gamma(t)$, which is orthogonal to $T_{\gamma(t)}\mathbb S^2$ because $\gamma(t)\perp T_{\gamma(t)}\mathbb S^2$. So $\gamma$ is a geodesic, with $\gamma(0)=p$ and $\gamma'(0)=v$. A geodesic is determined by these initial data (it solves a second-order ODE), so there is no other. $\square$

DefinitionExponential and logarithm maps

The exponential map $\exp_p:T_p\mathcal M\to\mathcal M$ sends $v$ to $\gamma_v(1)$: “walk straight for time 1 with initial velocity $v$”. On the sphere, $\exp_p(v)=\cos|v|\,p+\sin|v|\,v/|v|$, and its inverse is the logarithm $\log_p(q)=\dfrac{\vartheta}{\sin\vartheta}\,(q-\cos\vartheta\,p)$ with $\vartheta=\arccos(p\cdot q)$, the distance between $p$ and $q$.

Exercise

Exercise 3.1 · exponential and logarithm on the sphere

  1. Write exp_map and log_map.
  2. Check that $\exp_p(v)$ is on the sphere at distance $|v|$ from $p$, that $\log_p(\exp_p(v))=v$ and that $t\mapsto\exp_p(tv)$ has constant speed.
PythonStarting code · exp and log
def exp_map(p, v):    nv = np.linalg.norm(v)    if nv < 1e-12:        return p    return ...  # TO DO: the formula of the coursedef log_map(p, q):    c = np.clip(p @ q, -1, 1)    th = np.arccos(c)                                       # geodesic distance between p and q    if th < 1e-12:        return np.zeros(3)    return ...  # TO DO: th / sin(th) * (q - cos(th) p)p = unit(rng.normal(size=3)); v = project(p, rng.normal(size=3)) * 0.9q = exp_map(p, v)print("exp_p(v) on the sphere     :", np.isclose(np.linalg.norm(q), 1))print("distance d(p, q) = |v|     :", np.isclose(np.arccos(p @ q), np.linalg.norm(v)))print("log_p(exp_p(v)) = v        :", np.allclose(log_map(p, q), v))t, h = 0.3, 1e-6speed = np.linalg.norm(exp_map(p, (t + h) * v) - exp_map(p, (t - h) * v)) / (2 * h)print("constant speed |v|         :", np.isclose(speed, np.linalg.norm(v)))
Show the correction
PythonComplete solution · the exponential map and its inverse
def exp_map(p, v):    nv = np.linalg.norm(v)    if nv < 1e-12:        return p    # Moving along the great circle through p with initial velocity v: cos(|v|) p + sin(|v|) v / |v|.    return np.cos(nv) * p + np.sin(nv) * v / nv  # the formula of the coursedef log_map(p, q):    c = np.clip(p @ q, -1, 1)    th = np.arccos(c)                                       # geodesic distance between p and q    if th < 1e-12:        return np.zeros(3)    # The tangent vector at p pointing to q, of length th: the part of q orthogonal to p, rescaled.    return th / np.sin(th) * (q - c * p)  # th / sin(th) * (q - cos(th) p)p = unit(rng.normal(size=3)); v = project(p, rng.normal(size=3)) * 0.9q = exp_map(p, v)print("exp_p(v) on the sphere     :", np.isclose(np.linalg.norm(q), 1))print("distance d(p, q) = |v|     :", np.isclose(np.arccos(p @ q), np.linalg.norm(v)))print("log_p(exp_p(v)) = v        :", np.allclose(log_map(p, q), v))t, h = 0.3, 1e-6speed = np.linalg.norm(exp_map(p, (t + h) * v) - exp_map(p, (t - h) * v)) / (2 * h)print("constant speed |v|         :", np.isclose(speed, np.linalg.norm(v)))

The logarithm is defined for $q\neq-p$ (antipodal points are joined by infinitely many geodesics); the exponential is a bijection from the ball $|v|<\pi$ onto the sphere without $-p$.

Course

Christoffel symbols and the geodesic equation

PropositionGeodesic equation in coordinates

In coordinates, a geodesic of a metric $G(x)$ solves the system

\[\ddot x^k+\Gamma^k_{ij}(x)\,\dot x^i\dot x^j=0,\qquad \Gamma^k_{ij}=\tfrac12\,g^{kl}\big(\partial_ig_{jl}+\partial_jg_{il}-\partial_lg_{ij}\big),\]

with the Einstein convention (a repeated index is summed). The $\Gamma^k_{ij}$ are the Christoffel symbols. This equation says that the covariant acceleration vanishes; it is also the Euler–Lagrange equation of the energy $\tfrac12\int g(\dot x,\dot x)\,dt$, whose minimizers are the constant-speed shortest paths. For the sphere, the only non-zero symbols are

\[\Gamma^{\theta}_{\varphi\varphi}=-\sin\theta\cos\theta,\qquad\Gamma^{\varphi}_{\theta\varphi}=\Gamma^{\varphi}_{\varphi\theta}=\cot\theta.\]
Exercise

Exercise 3.2 · the geodesic equation in coordinates

  1. Write the Christoffel symbols from the metric with central differences of $G$, and compare with the two formulas above.
  2. Integrate the geodesic equation with a fourth-order Runge–Kutta scheme.
  3. Compare the result with the closed form $\exp_p(v)$, after converting the initial velocity to $\mathbb R^3$ with the Jacobian.
PythonStarting code · geodesic equation
def christoffel(x, h=1e-5):    """Gamma[k, i, j] = 1/2 g^{kl} (d_i g_jl + d_j g_il - d_l g_ij), derivatives by central differences."""    n = len(x)    Ginv = np.linalg.inv(metric(*x))    dG = np.zeros((n, n, n))                                # dG[l, i, j] = d g_ij / d x^l    for l in range(n):        e = np.zeros(n); e[l] = h        dG[l] = (metric(*(x + e)) - metric(*(x - e))) / (2 * h)    Gam = np.zeros((n, n, n))    for k in range(n):        for i in range(n):            for j in range(n):                Gam[k, i, j] = ...  # TO DO: the formula of the course    return Gamx = np.array([1.0, 0.7])Gam = christoffel(x)print("Gamma^theta_phiphi =", Gam[0, 1, 1], "| expected", -np.sin(x[0]) * np.cos(x[0]))print("Gamma^phi_thetaphi =", Gam[1, 0, 1], "| expected", np.cos(x[0]) / np.sin(x[0]))def geodesic(x0, v0, T=1.0, steps=200):    """RK4 for x'' = -Gamma^k_ij x'^i x'^j, written as a first-order system (x, x')."""    def rhs(s):        x, v = s[:2], s[2:]        a = ...  # TO DO: geodesic equation: acceleration = -Gamma(v, v)        return np.concatenate([v, a])    s = np.concatenate([x0, v0]); dt = T / steps    for _ in range(steps):        k1 = rhs(s); k2 = rhs(s + dt / 2 * k1); k3 = rhs(s + dt / 2 * k2); k4 = rhs(s + dt * k3)        s = s + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4)    return s[:2]x0, c0 = np.array([1.2, 0.3]), np.array([0.5, 0.9])         # start (theta, phi) and velocity in coordinatesxT = geodesic(x0, c0, T=1.0, steps=100)p0 = X(*x0); v0 = jacobian(*x0) @ c0                       # the same initial data in R^3print("coordinates vs closed form:", np.linalg.norm(X(*xT) - exp_map(p0, v0)))
Show the correction
PythonComplete solution · Christoffel symbols and Runge–Kutta
def christoffel(x, h=1e-5):    """Gamma[k, i, j] = 1/2 g^{kl} (d_i g_jl + d_j g_il - d_l g_ij), derivatives by central differences."""    n = len(x)    Ginv = np.linalg.inv(metric(*x))    dG = np.zeros((n, n, n))                                # dG[l, i, j] = d g_ij / d x^l    for l in range(n):        e = np.zeros(n); e[l] = h        dG[l] = (metric(*(x + e)) - metric(*(x - e))) / (2 * h)    Gam = np.zeros((n, n, n))    for k in range(n):        for i in range(n):            for j in range(n):                Gam[k, i, j] = 0.5 * sum(Ginv[k, l] * (dG[i, j, l] + dG[j, i, l] - dG[l, i, j]) for l in range(n))  # the formula of the course    return Gamx = np.array([1.0, 0.7])Gam = christoffel(x)print("Gamma^theta_phiphi =", Gam[0, 1, 1], "| expected", -np.sin(x[0]) * np.cos(x[0]))print("Gamma^phi_thetaphi =", Gam[1, 0, 1], "| expected", np.cos(x[0]) / np.sin(x[0]))def geodesic(x0, v0, T=1.0, steps=200):    """RK4 for x'' = -Gamma^k_ij x'^i x'^j, written as a first-order system (x, x')."""    def rhs(s):        x, v = s[:2], s[2:]        a = -np.einsum("kij,i,j->k", christoffel(x), v, v)  # geodesic equation: acceleration = -Gamma(v, v)        return np.concatenate([v, a])    s = np.concatenate([x0, v0]); dt = T / steps    for _ in range(steps):        k1 = rhs(s); k2 = rhs(s + dt / 2 * k1); k3 = rhs(s + dt / 2 * k2); k4 = rhs(s + dt * k3)        s = s + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4)    return s[:2]x0, c0 = np.array([1.2, 0.3]), np.array([0.5, 0.9])         # start (theta, phi) and velocity in coordinatesxT = geodesic(x0, c0, T=1.0, steps=100)p0 = X(*x0); v0 = jacobian(*x0) @ c0                       # the same initial data in R^3print("coordinates vs closed form:", np.linalg.norm(X(*xT) - exp_map(p0, v0)))

The two methods (an ODE in coordinates, a closed formula in $\mathbb R^3$) agree to about $3\cdot10^{-8}$, the accuracy of the finite differences used in the Christoffel symbols.

Course

Covariant derivative and Hessian

DefinitionCovariant derivative and Riemannian Hessian

To differentiate a vector field $w$ along a direction $v$ within $\mathcal M$ we keep the tangential part of the derivative in $\mathbb R^N$: $\nabla_vw=P_p\,Dw(p)[v]$ (the Levi-Civita connection of a submanifold). The Riemannian Hessian of $f$ is $\operatorname{Hess}f(p)[v]=\nabla_v\operatorname{grad}f$. On the unit sphere, for $f=\bar f|_{\mathbb S^2}$,

\[\operatorname{Hess}f(p)[v]=P_p\big(\nabla^2\bar f(p)\,v\big)-\big(p\cdot\nabla\bar f(p)\big)\,v.\]

The second term comes from the curvature of the sphere. The Hessian describes the second-order behaviour of $f$ along geodesics:

PropositionSecond derivative along a geodesic

If $\gamma$ is a geodesic, then $\dfrac{d^2}{dt^2}f(\gamma(t))=g\big(\operatorname{Hess}f[\gamma'],\gamma'\big)$.

Proof

$\frac d{dt}f(\gamma)=g(\operatorname{grad}f,\gamma')$. Differentiating the inner product with the connection, which is compatible with the metric, gives $g(\nabla_{\gamma'}\operatorname{grad}f,\gamma')+g(\operatorname{grad}f,\nabla_{\gamma'}\gamma')$. The second term vanishes for a geodesic ($\nabla_{\gamma'}\gamma'=0$) and the first one is $g(\operatorname{Hess}f[\gamma'],\gamma')$. $\square$

Exercise

Exercise 3.3 · a Riemannian Hessian on the sphere

  1. For $f(x)=x^{\top}Ax$ on the sphere, write the Riemannian gradient and the Hessian formula above.
  2. Check with second differences of $t\mapsto f(\exp_x(tv))$ that $\frac{d^2}{dt^2}f=v\cdot\operatorname{Hess}f[v]$, and with first differences that $\frac d{dt}f=g(\operatorname{grad}f,v)$.
PythonStarting code · Hessian
A = rng.normal(size=(3, 3)); A = (A + A.T) / 2              # a symmetric matrixf = lambda x: x @ A @ x                                     # f(x) = x^T A x on the spheredef rgrad(x):    return project(x, 2 * A @ x)                            # Riemannian gradient: projected Euclidean gradientdef rhess(x, v):    return ...  # TO DO: P(Euclidean Hessian v) - (x . grad f) vx = unit(rng.normal(size=3)); v = project(x, rng.normal(size=3))h = 1e-4second = (f(exp_map(x, h * v)) - 2 * f(x) + f(exp_map(x, -h * v))) / h ** 2     # d^2/dt^2 f(geodesic) at t = 0print("d2/dt2 f(exp_x(t v)) =", second, "| v . Hess f[v] =", v @ rhess(x, v))first = (f(exp_map(x, h * v)) - f(exp_map(x, -h * v))) / (2 * h)print("d/dt f(exp_x(t v))   =", first, "| g(grad f, v)   =", rgrad(x) @ v)
Show the correction
PythonComplete solution · Hessian checked along a geodesic
A = rng.normal(size=(3, 3)); A = (A + A.T) / 2              # a symmetric matrixf = lambda x: x @ A @ x                                     # f(x) = x^T A x on the spheredef rgrad(x):    return project(x, 2 * A @ x)                            # Riemannian gradient: projected Euclidean gradientdef rhess(x, v):    # Riemannian Hessian on the sphere: the projected Euclidean Hessian minus (x . Euclidean gradient) v (a term due to the curvature of the sphere).    return project(x, 2 * A @ v) - (x @ (2 * A @ x)) * v  # P(Euclidean Hessian v) - (x . grad f) vx = unit(rng.normal(size=3)); v = project(x, rng.normal(size=3))h = 1e-4second = (f(exp_map(x, h * v)) - 2 * f(x) + f(exp_map(x, -h * v))) / h ** 2     # d^2/dt^2 f(geodesic) at t = 0print("d2/dt2 f(exp_x(t v)) =", second, "| v . Hess f[v] =", v @ rhess(x, v))first = (f(exp_map(x, h * v)) - f(exp_map(x, -h * v))) / (2 * h)print("d/dt f(exp_x(t v))   =", first, "| g(grad f, v)   =", rgrad(x) @ v)

The second differences agree with the formula to 8 digits. If the curvature term was missing, the check would fail: the Hessian of the restriction is not the projection of the Euclidean Hessian.

Part 4 · Parallel transport and curvature

Course

Parallel transport and curvature

DefinitionParallel transport

A vector field $v(t)$ along a curve $\gamma$ is parallel if its covariant derivative along $\gamma$ is zero: on a submanifold, $P_{\gamma(t)}v'(t)=0$, that is, $v'(t)$ is orthogonal to the tangent space. Parallel transport along $\gamma$ carries a tangent vector at $\gamma(0)$ to a tangent vector at $\gamma(1)$ while preserving lengths and angles. Numerically, transporting along a polygonal approximation amounts to projecting at each step: $v_{k+1}=P_{\gamma(t_{k+1})}v_k$ (then normalizing).

In the plane, transporting around a closed loop brings the vector back unchanged. On a curved space it comes back rotated: this is the holonomy. For a small loop it is proportional to the enclosed area, with the Gauss curvature $K$ as the coefficient. For the unit sphere $K=1$, and for the sphere of radius $r$, $K=1/r^2$.

TheoremGauss–Bonnet for a geodesic triangle

The sum of the interior angles of a geodesic triangle $T$ on a surface is $\alpha+\beta+\gamma=\pi+\iint_TK\,dA$, and the holonomy angle around $\partial T$ is $\iint_TK\,dA$. On the unit sphere, the octant triangle with vertices $e_1,e_2,e_3$ has three right angles and area $4\pi/8=\pi/2$: the sum is $3\pi/2=\pi+\pi/2$.

Exercise

Exercise 4.1 · holonomy around the octant triangle

  1. Write the parallel transport of a vector along the great circle from $p$ to $q$, by projecting at each small step.
  2. Transport $v_0=e_3$ (tangent at $e_1$) along $e_1\to e_2\to e_3\to e_1$.
  3. Compute the signed angle between $v_0$ and the transported vector, and compare with $K\times\text{area}=\pi/2$.
PythonStarting code · parallel transport
def transport_along_geodesic(p, q, v, n=2000):    """Parallel transport of v along the great circle from p to q, by small steps."""    w = log_map(p, q)                                       # initial velocity of the geodesic    pts = [exp_map(p, t * w) for t in np.linspace(0, 1, n + 1)]    for a, b in zip(pts[:-1], pts[1:]):        v = ...  # TO DO: keep the tangential part at the next point        v = v / np.linalg.norm(v)                           # the transport preserves lengths: undo the small shrinking due to the projection    return ve1, e2, e3 = np.eye(3)v0 = e3.copy()                                              # a tangent vector at e1 (e3 is orthogonal to e1)v = v0for a, b in [(e1, e2), (e2, e3), (e3, e1)]:    v = transport_along_geodesic(a, b, v)                   # one side of the triangle after the otherv = v / np.linalg.norm(v)angle = np.arctan2(e1 @ np.cross(v0, v), v0 @ v)            # signed angle from v0 to the transported vectorprint("holonomy angle =", angle, "| pi/2 =", np.pi / 2)area = 4 * np.pi / 8                                        # the octant triangle is 1/8 of the sphereprint("curvature K * area =", 1.0 * area)
Show the correction
PythonComplete solution · parallel transport around a spherical triangle
def transport_along_geodesic(p, q, v, n=2000):    """Parallel transport of v along the great circle from p to q, by small steps."""    w = log_map(p, q)                                       # initial velocity of the geodesic    pts = [exp_map(p, t * w) for t in np.linspace(0, 1, n + 1)]    for a, b in zip(pts[:-1], pts[1:]):        v = project(b, v)  # keep the tangential part at the next point        v = v / np.linalg.norm(v)                           # the transport preserves lengths: undo the small shrinking due to the projection    return ve1, e2, e3 = np.eye(3)v0 = e3.copy()                                              # a tangent vector at e1 (e3 is orthogonal to e1)v = v0for a, b in [(e1, e2), (e2, e3), (e3, e1)]:    v = transport_along_geodesic(a, b, v)                   # one side of the triangle after the otherv = v / np.linalg.norm(v)angle = np.arctan2(e1 @ np.cross(v0, v), v0 @ v)            # signed angle from v0 to the transported vectorprint("holonomy angle =", angle, "| pi/2 =", np.pi / 2)area = 4 * np.pi / 8                                        # the octant triangle is 1/8 of the sphereprint("curvature K * area =", 1.0 * area)

The transported vector is rotated by exactly $\pi/2$: the rotation equals the curvature times the area, as the theorem predicts. Here the scheme has no discretization error, because the transported vector is, on each side, either perpendicular or tangent to the great circle, and the projection keeps it so; for a generic initial vector the error decreases like the inverse of the number of steps.

Exercise

Exercise 4.2 · the angle excess, and the curvature as a limit

  1. Compute the three interior angles of a geodesic triangle with the logarithm map.
  2. Check the octant: the angle sum is $3\pi/2$.
  3. For a small triangle $p,\exp_p(\varepsilon a),\exp_p(\varepsilon b)$ with $a,b$ orthonormal, compare the excess with the area $\varepsilon^2/2$ of the plane triangle: the ratio should tend to $K=1$.
PythonStarting code · angle excess
def angle_at(p, q, r):    a, b = log_map(p, q), log_map(p, r)                     # the two sides, as tangent vectors at p    return ...  # TO DO: angle between the two directionsdef angle_sum(p, q, r):    return angle_at(p, q, r) + angle_at(q, r, p) + angle_at(r, p, q)e1, e2, e3 = np.eye(3)print("octant: angle sum =", angle_sum(e1, e2, e3), "| 3 pi / 2 =", 1.5 * np.pi, "| excess =", angle_sum(e1, e2, e3) - np.pi)p = unit(rng.normal(size=3))a = unit(project(p, rng.normal(size=3))); b = unit(np.cross(p, a))        # an orthonormal basis of T_p S^2for eps in [0.8, 0.4, 0.1, 0.02]:    q, r = exp_map(p, eps * a), exp_map(p, eps * b)    excess = angle_sum(p, q, r) - np.pi    ...  # TO DO: ratio excess / plane area, tends to the curvature K
Show the correction
PythonComplete solution · angle sum and curvature
def angle_at(p, q, r):    a, b = log_map(p, q), log_map(p, r)                     # the two sides, as tangent vectors at p    return np.arccos((a @ b) / (np.linalg.norm(a) * np.linalg.norm(b)))  # angle between the two directionsdef angle_sum(p, q, r):    return angle_at(p, q, r) + angle_at(q, r, p) + angle_at(r, p, q)e1, e2, e3 = np.eye(3)print("octant: angle sum =", angle_sum(e1, e2, e3), "| 3 pi / 2 =", 1.5 * np.pi, "| excess =", angle_sum(e1, e2, e3) - np.pi)p = unit(rng.normal(size=3))a = unit(project(p, rng.normal(size=3))); b = unit(np.cross(p, a))        # an orthonormal basis of T_p S^2for eps in [0.8, 0.4, 0.1, 0.02]:    q, r = exp_map(p, eps * a), exp_map(p, eps * b)    excess = angle_sum(p, q, r) - np.pi    print(f"eps = {eps:5.2f}: excess / (plane area eps^2 / 2) = {excess / (eps ** 2 / 2):.4f}")  # ratio excess / plane area, tends to the curvature K

The ratios $1.1055,\ 1.0267,\ 1.0017,\ 1.0001$ for $\varepsilon=0.8,\ 0.4,\ 0.1,\ 0.02$ converge to $1=K$ quadratically in $\varepsilon$: curvature is the second-order defect of the plane geometry.

Part 5 · Deliverables and limits

Exercise

Build a defensible report

  1. Explain why two charts are needed for the sphere and write the transition map between the two stereographic charts.
  2. Prove that $T_p\mathbb S^2=p^{\perp}$ and that the projection $P_p$ is symmetric.
  3. Prove the steepest-ascent proposition and the formula $\operatorname{grad}f=P_p\nabla\bar f$.
  4. Derive the Christoffel symbols of the sphere from $G=\operatorname{diag}(1,\sin^2\theta)$ and check them against the numerical ones.
  5. Report holonomy and angle excess for another geodesic triangle (a different octant, or a triangle with a $60^{\circ}$ angle) and compare with the area.
  6. Extension: repeat the Hessian check with a function of your choice, or on the circle of radius $r$ (curvature $1/r$) instead of the sphere.
Course

What these notes leave out

We worked on a single example, the unit sphere, and on submanifolds of $\mathbb R^N$, where the connection and the exponential map have closed forms. The general theory (abstract manifolds, the Levi-Civita connection from the Koszul formula, the Riemann curvature tensor, the second fundamental form, Lie groups) is in the references below. Geodesic completeness, the injectivity radius and the global structure of $\exp_p$ were only touched upon: the exponential is not injective on the whole tangent space, and the distance is the infimum of lengths, not always attained.

References and related learning

Course

Books and notes