{ "cells": [ { "cell_type": "markdown", "id": "15304ed6", "metadata": {}, "source": [ "$\\textbf{Lead Author: Adele Myers}$\n", "\n", "Inspired by: Guigui, Miolane, Pennec, 2022. Introduction to Riemannian Geometry and Geometric Statistics: from basic theory to implementation with Geomstats." ] }, { "cell_type": "markdown", "id": "57539ed2", "metadata": {}, "source": [ "In this section, we will:\n", "\n", "1. Define the Connection\n", "2. Discuss parallel vector fields and parallel transport\n", "3. Define Geodesics with the Connection\n", "4. Define the Connection in Local Coordinates (with Christoffel Symbols)\n", "5. Discuss Logarithms and Exponentials\n", "6. Give an overview of the Connection Class in Geomstats\n", "7. Discuss the RiemannianMetric subclass of the Connection Class" ] }, { "cell_type": "markdown", "id": "53e8d770", "metadata": {}, "source": [ "This notebook provides an overview of the $\\textbf{Connection}$ class in Geomstats. Intuitively: a connection is a mathematical operator that tells you how much a vector will change when you move it along a manifold in the direction of another vector. The symbol for connection is $\\nabla$, and $\\nabla_{\\vec{u}} \\vec{v}$ denotes how much vector $\\vec{v}$ would change if you moved it an infinitesimal distance in the direction of vector $\\vec{u}$ (see figure below)." ] }, { "cell_type": "markdown", "id": "c8cb8b35", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "id": "7819b85d", "metadata": {}, "source": [ "# 1. What is a Connection?" ] }, { "cell_type": "markdown", "id": "cdf81e67", "metadata": {}, "source": [ "We will start by defining the connection $\\textit{mathematically}$, and then we will define the connection again in a more $\\textit{conceptual and intuitive}$ way with examples. " ] }, { "cell_type": "markdown", "id": "e6ddcae9", "metadata": {}, "source": [ "## 1.1 General Mathematical Definition of the Connection" ] }, { "cell_type": "markdown", "id": "75363a29", "metadata": {}, "source": [ "Let $M$ be a smooth manifold. A $\\textbf{connection}$ on $M$ is an $\\mathbb{R}$-bilinear map $\\nabla: \\Gamma (T M) \\times \\Gamma (T M) \\to \\Gamma (T M)$ that verifies for all $X,Y \\in \\Gamma (T M), \\forall f \\in C^\\infty(M)$:\n", "\n", "1. (linearity of the $1^{st}$ argument): $\\nabla_{f X} Y = f \\nabla_{X} Y$\n", "\n", "2. (Leibniz rule in $2^{nd}$ argument): $\\nabla_{X} (fY) = X(f)Y+ f\\nabla_{X} Y$" ] }, { "cell_type": "markdown", "id": "dc44538e", "metadata": {}, "source": [ "$\\textbf{What is this saying}:$\n", "\n", "$\\textbf{1. First, let's dissect the map}$ $\\nabla: \\Gamma (T M) \\times \\Gamma (T M) \\to \\Gamma (T M)$.\n", "\n", "\"$\\nabla:$\" - this part is saying that it is the connection (denoted $\\nabla$) that is performing the transformation.\n", "\n", "\"$T M$\" - this symbolizes the $\\textbf{tangent bundle}$ of the manifold $M$. A tangent bundle is the collection of all tangent spaces on the manifold $M$. A tangent bundle is itself also a manifold.\n", "\n", "\"$\\Gamma(T M)$\" - $\\Gamma(T M)$ denotes the space of vector fields. A single element of $\\Gamma(T M)$ is a single vector field on the manifold $M$. A vector field is comprised of a set of vectors on the manifold, where there is a vector at each point, and that vector is an element of the tangent space at that point (shown below). " ] }, { "cell_type": "markdown", "id": "39f0420a", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "id": "536039d4", "metadata": {}, "source": [ "Putting all of this together, $\\nabla: \\Gamma (T M) \\times \\Gamma (T M) \\to \\Gamma (T M)$ is simply saying that the connection is a transformation which takes two arguments, both of which are vector fields (comprised of tangent vectors), and the result of the transformation is another vector field (comprised of tangent vectors)." ] }, { "cell_type": "markdown", "id": "7432cd4a", "metadata": {}, "source": [ "$\\textbf{2. Now, let's consider the conditions that the connection must satisfy.}$ \n", "1. (linearity of the $1^{st}$ argument): $\\nabla_{f X} Y = f \\nabla_{X} Y$\n", "\n", "2. (Leibniz rule in $2^{nd}$ argument): $\\nabla_{X} (fY) = X(f)Y+ f\\nabla_{X} Y$\n", "\n", "Here, there is not much to dissect mathematically, but we should wonder why the connection must satisfy the conditions. The vector field $\\nabla_{X} Y$ (remember $X$ and $Y$ are vector $\\textit{fields}$) is also called the $\\textbf{covariant derivative}$ of $Y$ with respect to $X$. If we think of $\\nabla_{X}$ as a derivative of some sort, then it makes sense that $\\nabla_{X}$ would have to follow a set of rules. Condition 1 is the equivalent of saying $\\frac{d(fX)}{dx}=f\\frac{d(X)}{dx}$ in euclidean space. Similarly, condition 2 is the differential geometry equivalent of the product rule: $\\frac{d(u*v)}{dx}= \\frac{d(u)}{dx}*v +u*\\frac{d(v)}{dx}$. In summary, the connection must follow rules just as our familiar derivative must follow rules, and these rules have a similar form." ] }, { "cell_type": "markdown", "id": "14633047", "metadata": {}, "source": [ "## 1.2 What does the Connection actually do? -- a more friendly description of the connection, with an example" ] }, { "cell_type": "markdown", "id": "97888b3d", "metadata": {}, "source": [ "Consider a single vector $\\vec{a_p}$, tangent to the manifold at point $p$ (shown in the figure below)." ] }, { "cell_type": "markdown", "id": "590e8658", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "id": "37738a60", "metadata": {}, "source": [ "Now, suppose you want to see what vector $\\vec{a_p}$ looks like when it is translated to a different point on the manifold. You may be asking why we are placing importance on this question-- because for a vector in cartesian coordinates, this question would be trivial. If you translated vector $\\vec{a_p}$ to a different point in cartesian coordinates, the vector itself would not change (as shown in the figure below)." ] }, { "cell_type": "markdown", "id": "8635a5dd", "metadata": {}, "source": [ " " ] }, { "cell_type": "markdown", "id": "86d31417", "metadata": {}, "source": [ "A spatially translated vector in cartesian coordinates does not change because the basis vectors in cartesian coordinates are translationally invariant, meaning all points in cartesian coordinates have the same set of basis vectors." ] }, { "cell_type": "markdown", "id": "5d097e78", "metadata": {}, "source": [ "This is not, however, necessarily true for points on a manifold-- if you move a tangent vector from one point to another (i.e. from one tangent space to another), the vector will not necessarily look the same after this transformation. (The figure below shows that when $\\vec{a_p}$ is translated to a different point on the manifold, it could be pointing in a direction different from its original direction.)" ] }, { "cell_type": "markdown", "id": "b15d45d0", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "id": "172b984b", "metadata": {}, "source": [ "This is why the connection is such an important concept as we analyze data on manifolds. The connection helps us quantify how much a vector will change when we move it from one point to another on a manifold." ] }, { "cell_type": "markdown", "id": "4336b8e9", "metadata": {}, "source": [ "More specifically, the connection is able to tell us how one vector will change if it is moved in the direction of another vector. For example, if vectors $\\vec{a}$ and $\\vec{b}$ exist in the same tangent plane, then the connection $\\nabla_{\\vec{b}} \\vec{a}$ tells us how much the vector $\\vec{a}$ will change if it is moved an infinitesimally small distance in the direction of $\\vec{b}$ (shown in the figure below)." ] }, { "cell_type": "markdown", "id": "2d48c2ff", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "id": "42157196", "metadata": {}, "source": [ "# 2. Why is the Connection important (big picture)? -- parallel transport, parallel vector fields" ] }, { "cell_type": "markdown", "id": "0719b542", "metadata": {}, "source": [ "The connection defines $\\textit{how much a vector will change when you move it in a certain direction}$, and thus the connection also defines what it means for a vector $\\textbf{not}$ to change when you move it in a certain direction. (If the connection between two vectors: $\\nabla_{\\vec{u}} \\vec{v}$ is equal to zero, then $\\vec{v}$ does not change as you move it along $\\vec{u}$.) In this section, we will use this aspect of the connection to define $\\textbf{parallel vector fields}$, which will allow us to introduce the notion of $\\textbf{parallel transport}$." ] }, { "cell_type": "markdown", "id": "d6cc1dca", "metadata": {}, "source": [ "$\\textbf{The Notion of \"Parallel\" in Euclidean Space-- and why this definition does not work in \"manifold space\".}$" ] }, { "cell_type": "markdown", "id": "9b92edc2", "metadata": {}, "source": [ "In Euclidean space, we say that two vectors, $\\vec{a}$ and $\\vec{b}$ are \"parallel\" if they are \"side by side\" and have the same distance continuously between them. However, we cannot use this same notion of \"parallel\" on a manifold because manifolds are more complicated spaces. In fact, on a manifold, we cannot even define the notion of \"distance\" without equipping a manifold with something called a \"metric\" (which we will discuss later in this notebook). \n", "\n", "Long story short: on manifolds, the word \"parallel\" does not hold the same simple definition that it holds in cartesian coordinates. In differential geometry, the notion of \"parallel\" is defined by $\\textbf{parallel vector fields}$. $\\textbf{Parallel vector fields}$ are then used to define and construct the idea of $\\textbf{parallel transport}$." ] }, { "cell_type": "markdown", "id": "e0777006", "metadata": {}, "source": [ "## 2.1 Parallel Vector Fields" ] }, { "cell_type": "markdown", "id": "3d49f0b0", "metadata": {}, "source": [ "The connection defines $\\textit{how much a vector changes when you move it in a certain direction}$, and thus the connection also defines what it means for a vector $\\textbf{not}$ to change when you move it in a certain direction. This will allow us to introduce the concept of a parallel vector field." ] }, { "cell_type": "markdown", "id": "8c7f4933", "metadata": {}, "source": [ "$\\textbf{1. Precise Definition of a Parallel vector field}$\n", "\n", "Let $M$ be a smooth manifold and $\\nabla$ a connection on $M$. For any curve $\\gamma : [a,b] \\to M$ in $M$, a vector fied $X$ is a $''\\textbf{parallel vector field}''$ $\\textit{along a curve}$ $\\gamma(t)$ if \n", "\n", "$$\\nabla_{\\dot{\\gamma}(t)} X(t)=0$$\n", "\n", "where $\\dot{\\gamma}(t)$ is a vector that is tangent to the curve $\\gamma(t)$." ] }, { "cell_type": "markdown", "id": "2722989f", "metadata": {}, "source": [ "$\\textbf{2. What does this mean?}$ \n", "\n", "When we say that $X$ is \"parallel\", you may be asking yourself \"parallel to what?\" because when we say that a vector is \"parallel\" in Euclidean space, we mean that the vector is parallel $\\textit{to}$ another vector. However, when we say that a $\\textbf{vector field}$ is $\\textbf{parallel}$ $\\textbf{along a curve}$ on a manifold, the definition of \"parallel\" is given by the relation above.\n", "\n", "Let's explain the definition above in words instead of math notation. First remember that a vector field $\\textbf{X}$ is comprised of a set of vectors $\\vec{X_p} \\in \\textbf{T_pM}$ where $p$ can be any point on the manifold.\n", "\n", "Now, consider a vector field $\\textbf{X}$ that lies along a curve $\\gamma(t)$. This means that each one of the vectors in $\\textbf{X}$ stems from a point along $\\gamma(t)$. This vector field is a $\\textbf{parallel vector field}$ if it satisfies:\n", "\n", "$$\\nabla_{\\dot{\\gamma}(t)} X(t)=0.$$\n", "\n", "In other words: if we were to move each point in the vector field $\\textbf{X}$ infinitesimally along the curve $\\gamma$ in the direction of $\\gamma$'s tangent vector $\\dot{\\gamma}$, the vector field $\\textbf{X}$ would not change. Note that this means that in differential geometry, we can only define the term \"parallel\" when we define it $\\textit{along a curve}$. The figure below shows that at each point $t$ along the curve $\\gamma$, the vector field satisfies $\\nabla_{\\dot{\\gamma}(t)} X(t)=0$, which means that the vector field shown in pink is a parallel vector field." ] }, { "cell_type": "markdown", "id": "d134ed5c", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "id": "9ee7d5f5", "metadata": {}, "source": [ "## 2.2 Parallel Transport" ] }, { "cell_type": "markdown", "id": "10ac9a0c", "metadata": {}, "source": [ "The parallel transport of a vector $\\vec{v}$ along $\\gamma$ from point $\\gamma(a)$ to point $\\gamma(s)$ is denoted by $\\vec{v'} = \\prod_{\\gamma,a}^s \\vec{v}$. Parallel transport along a curve $\\gamma$ tells us what an initial tangent vector $\\vec{v}$ would look like if it is transported along the curve $\\gamma$ from point $\\gamma(a)$ to point $\\gamma(s)$. Thus, the parallel transport tells us what a vector would look like if it was transported from one tangent space ($T_{\\gamma(a)}M$) to another tangent space ($T_{\\gamma(s)}M$).\n", "\n", "Conceptually, this is exactly like solving a differential equation: we can find a \"solution\" (in this case: the transported vector) to the equation $\\nabla_{\\dot \\gamma(t)} X(\\gamma(t)) = 0$ if we are given initial conditions (in this case: an initial point and tangent vector). Note that $X(\\gamma(t))$ in the differential equation simply indicates that the vector field $X$ is parallel along the curve $\\gamma(t)$. In other words, the parallel transport calculates the parallel vector field along the curve $\\gamma(t)$ and then selects the element of the vector field that lies at the final point $\\gamma(s)$. The figure below shows this process." ] }, { "cell_type": "markdown", "id": "b206b4ad", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "id": "146fa0c6", "metadata": {}, "source": [ "Note that the connection was able to tell us how a vector would change infinitesimally if we move a vector in the direction of another vector, but here, we are able to use parallel transport to calculate how a vector will change if it is translated a $\\textbf{non-infinitesimal}$ distance." ] }, { "cell_type": "markdown", "id": "04c152fc", "metadata": {}, "source": [ "# 3. Defining Geodesics with the Connection" ] }, { "cell_type": "markdown", "id": "b405c76e", "metadata": {}, "source": [ "## 3.1 Intuitive Definition of a Geodesic\n", "\n", "To gain intuition about what a geodesic is, we can think of a geodesic as the \"shortest path\" between two points on a geodesic. Note, however, that at this point we cannot quantify ''distance'' because we have not yet introduced Riemannian metrics yet (introduced later in this notebook). Still, we wanted to present this more intuitive definition here for readers who have never heard of a geodesic before. " ] }, { "cell_type": "markdown", "id": "c3dfc416", "metadata": {}, "source": [ "## 3.2 Defining a geodesic with the connection\n", "\n", "Each point and tangent vector pair on a manifold has a unique geodesic going through it. We can use the connection and parallel vector fields to provide another definition of a geodesic. A curve is said to be \"autoparallel\" (and a geodesic) if \n", "$$\\nabla_{\\dot{\\gamma}(t)} \\dot{\\gamma}(t)=0$$\n", "is true for all $t$ along the curve. This means that for each point on a geodesic, moving that point's tangent vector in the direction of itself will not change the tangent vector." ] }, { "cell_type": "markdown", "id": "d4fbe566", "metadata": {}, "source": [ "## 3.3 Building Intuition with Physics\n", "\n", "It is difficult to comprehend why geodesics are important without examples. Physics, and general relativity in particular, provides many such examples. One of the best examples arises when we consider the paths of objects in spacetime. Spacetime is the $\\textit{four-dimensional}$ \"fabric\" that makes up the universe, and it is a manifold. Spacetime curves around masses (like planets, stars, black holes), which means that in those areas, we cannot approximate the space as being Euclidean. It is in these spaces that we must use geodesics to predict the paths that objects will follow-- because free particles (and light) follow geodesics in space. \n", "\n", "In fact, telescopes have confirmed that light bends around very massive objects like black holes (shown below)." ] }, { "cell_type": "markdown", "id": "4d253c78", "metadata": {}, "source": [ "\n" ] }, { "cell_type": "markdown", "id": "f98ed5ff", "metadata": {}, "source": [ "This is just one example of why geodesics are crucial to understanding real-world data. Other examples exist in areas like biophysics where the trajectory of cells along a manifold may follow geodesics. " ] }, { "cell_type": "markdown", "id": "e6f38d37", "metadata": {}, "source": [ "# 4. Description of Connection in Local Coordinates (using Christoffel Symbols)" ] }, { "cell_type": "markdown", "id": "f51194f8", "metadata": {}, "source": [ "In $\\textbf{local coordinates}$, the connection can be described mathematically using $\\textbf{Christoffel Symbols}$:\n", "\n", "$$\\nabla_{\\partial_i} \\partial_j = \\Gamma_{i j}^{k} \\partial_k$$\n", "\n", "where $\\partial_i,\\partial_j$ are basis vectors and elements of $T_pM$ (the tangent space of some point $p$ on the manifold), and $\\Gamma$ is called a $\\textbf{Christoffel symbol}$. How ''local'' is ''local''? Local coordinates describe a coordinate system that is limited to an infinitely small area on a manifold. This makes sense because the connection is only defined infinitesimally." ] }, { "cell_type": "markdown", "id": "57896818", "metadata": {}, "source": [ "## 4.1 Math Notation: $\\mathbf{ \\partial_i}$ Basis Vector" ] }, { "cell_type": "markdown", "id": "2f064f0a", "metadata": {}, "source": [ "${\\partial_i}$ is equivalent to $\\vec{e}_i$. For example, in three dimensions, one could express the basis vectors $\\hat{x}, \\hat{y}, \\hat{z}$ as either $\\vec{e}_x, \\vec{e}_y, \\vec{e}_z$ or as $\\partial_x, \\partial_y, \\partial_z$." ] }, { "cell_type": "markdown", "id": "a64e3ad1", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "id": "99940905", "metadata": {}, "source": [ "Note/practicality: basis vectors on a manifold may differ at each point, which means that basis vectors are actually dependent on the tangent space $T_pM$ to which they belong. Thus, we \"should\" be writing $\\vec{e}_i(p)$, but in practice, the point $p$ is omitted." ] }, { "cell_type": "markdown", "id": "1255f083", "metadata": {}, "source": [ "## 4.2 Einstein Notation" ] }, { "cell_type": "markdown", "id": "bef6babb", "metadata": {}, "source": [ "The $i$ and $j$ in each Christoffel symbol can index any one of the basis vectors of a space. For example, in 3D space, $i$ can be $x, y,$ or $z$, and $j$ can be $x, y,$ or $z$. The $k$ in the Christoffel symbol is different because it is used in a superscript and a subscript. In Einstein notation, when a letter is used in a superscript and a subscript, this is equivalent to a sum over all basis vectors. \n", "\n", "For example, if we chose $i=x$ and $j=z$, then the connection statement (where the sum over $k$ is stated explicitly) would read as:\n", "\n", "$$\\nabla_{\\partial_x} \\partial_z = \\Gamma_{x z}^{k} \\partial_k$$\n", "\n", "$$=\\Sigma_{k=x,y,z} \\Gamma_{x z}^{k} \\partial_k$$\n", "\n", "$$=\\Gamma_{x z}^{x} \\partial_x + \\Gamma_{x z}^{y} \\partial_y + \\Gamma_{x z}^{z} \\partial_z$$" ] }, { "cell_type": "markdown", "id": "d5f32aa5", "metadata": {}, "source": [ "## 4.3 What does a Christoffel Symbol represent?" ] }, { "cell_type": "markdown", "id": "3a027833", "metadata": {}, "source": [ "The best way to gain intuition of what a Christoffel symbol represents is through an example.\n", "\n", "As discussed in section 1.2, the connection $\\nabla_{\\partial_x} \\partial_z$ would tell us how the basis vector $\\partial_z$ would change if we moved it along the manifold in the direction of $\\partial_x$. Now, we know that we can represent $\\nabla_{\\partial_x} \\partial_z$ with Christoffel symbols as:\n", "\n", "$$\\nabla_{\\partial_x} \\partial_z = \\Gamma_{x z}^{x} \\partial_x + \\Gamma_{x z}^{y} \\partial_y + \\Gamma_{x z}^{z} \\partial_z$$\n", "\n", "so the right hand side of the equation should tell us something about the overall rate of change of $\\partial_z$ when we move $\\partial_z$ in the direction of $\\partial_x$. Therefore, it seems natural that each of the Christoffel symbols would represent a rate of change. For example, $\\Gamma_{x z}^{y}$ tells us the rate of change (in the $\\partial_y$ direction) of $\\partial_z$ when we move $\\partial_z$ in the direction of $\\partial_x$." ] }, { "cell_type": "markdown", "id": "f6c284e1", "metadata": {}, "source": [ "## 4.4 The Geodesic Equation in local coordinates\n", "\n", "The geodesic equation can also be expressed in terms of Christoffel symbols in local coordinates:\n", "\n", "$$\\ddot{\\gamma}^{k}(t)+\\Gamma_{i j}^{k} \\dot{\\gamma}^{i}(t) \\dot{\\gamma}^{j}(t)=0.$$" ] }, { "cell_type": "markdown", "id": "5b62c147", "metadata": {}, "source": [ "## 4.5 Why should we care about Christoffel Symbols and this representation of the connection?" ] }, { "cell_type": "markdown", "id": "41d0800f", "metadata": {}, "source": [ "The ability to represent the connection with Christoffel symbols is $\\textit{essential}$ because Christoffel symbols are something we can actually compute. Up until now, we have presented somewhat abstract formulae with no actual method for computation. Now, with Christoffel symbols, we can compute actual values for the connection. We do not yet have the tools to calculate Christoffel symbols at this point in our tutorial, but we will learn later in the notebook." ] }, { "cell_type": "markdown", "id": "1e480240", "metadata": {}, "source": [ "# 5. Additional Important Mathematical concepts utilized by `Connection` Class: Logarithm, Exponential" ] }, { "cell_type": "markdown", "id": "dd5e1889", "metadata": {}, "source": [ "In Euclidean space, addition and subtraction allow us to operate on initial points to generate new points. On manifolds, exponentials and logarithms allow us to operate on points and/or tangent vectors to get new points or tangent vectors." ] }, { "cell_type": "markdown", "id": "10e63b9e", "metadata": {}, "source": [ "## Exponentials on Manifolds" ] }, { "cell_type": "markdown", "id": "b3bad62e", "metadata": {}, "source": [ "In Euclidean space, $\\textit{addition}$ is a tool which takes two points $p_1, p_2$, \"adds\" them, and generates a third, larger point $p_3$ (as shown in the figure below). Addition gives us a way to \"move forward\" in Euclidean space." ] }, { "cell_type": "markdown", "id": "d4c37fe2", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "id": "f49021bf", "metadata": {}, "source": [ "On manifolds, the $\\textit{exponential}$ provides a tool which \"takes the exponential of the tangent vector at point $p$\" to generate a third point on the manifold. The exponential does this by 1) identifying the unique geodesic $\\gamma$ that goes through $p$ and $v_p$, 2) identifying the \"length\" $l$ of the tangent vector $v_p$, and 3) calculating another point $p'$ along $\\gamma(t)$ that is a \"distance\" $l$ from the initial point $p$ (see figure below). Note again that the notion of \"length\" and \"distance\" is different on a manifold than it is in Euclidean space and that quantifying length is not something that we will be able to do without specifying a metric (discussed in `RiemannianMetric` section)." ] }, { "cell_type": "markdown", "id": "798b9180", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "id": "998755f1", "metadata": {}, "source": [ "The exponential is often described as being the \"differential geometry version\" of addition." ] }, { "cell_type": "markdown", "id": "cdad9a32", "metadata": {}, "source": [ "## Logarithms on Manifolds" ] }, { "cell_type": "markdown", "id": "24eb26f5", "metadata": {}, "source": [ "In Euclidean space, $\\textit{subtraction}$ is an operation which allows us to take the third point $p_3$ and one of the initial points $p_1$ and extract the other initial point $p_2$ (as shown in the figure below)." ] }, { "cell_type": "markdown", "id": "c4e506ba", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "id": "329a1461", "metadata": {}, "source": [ "Similarly, the $\\textit{logarithm}$ allows us to take the final point $p'$ and the initial point $p$ to extract the tangent vector $v_p$ at the initial point. The logarithm is able to do this by 1) identifying the unique geodesic $\\gamma$ that connects the two points 2) calculating the \"length\" of that geodesic 3) generating the unique tangent vector at $p$, with a \"length\" equal to that of the geodesic (shown in the figure below). Again, remember that \"length\" is not something that we can quantify without specifying a metric, which we will not be able to do until the `RiemannianMetric` section.\n", "\n", "A key point here is that if you know a point and a tangent vector at that point, you can calculate a unique geodesic that goes through that point, and similarly, if you know the point and geodesic, you should be able to extract the unique tangent vector that produced that geodesic. " ] }, { "cell_type": "markdown", "id": "c725ecdd", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "id": "9d54454b", "metadata": {}, "source": [ "The logarithm is the inverse map of the exponential and is often described as being the \"differential geometry version\" of subtraction." ] }, { "cell_type": "markdown", "id": "c94f2a35", "metadata": {}, "source": [ "# 6. Geomstats Documentation: The `Connection` Class" ] }, { "cell_type": "markdown", "id": "1871e147", "metadata": {}, "source": [ "The `Connection` class in geomstats has four methods and one subclass, whose structure is shown below:" ] }, { "cell_type": "markdown", "id": "d509b1a9", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "id": "a3772172", "metadata": {}, "source": [ "The methods of the `Connection` class also equip the `RiemannianMetric` subclass with the tools it needs to perform calculations on manifolds (we will discuss the `RiemannianMetric` class later in this notebook)." ] }, { "cell_type": "markdown", "id": "a6229c7b", "metadata": {}, "source": [ "We will first print the key methods of the `Connection` class, and then at the end we will print the entire connection class for anyone who is interested." ] }, { "cell_type": "code", "execution_count": 1, "id": "e730c4ef", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "INFO: Using numpy backend\n" ] } ], "source": [ "import geomstats.backend as gs\n", "\n", "gs.random.seed(2020)" ] }, { "cell_type": "markdown", "id": "c762acd4", "metadata": {}, "source": [ "## 6.1 method: `parallel_transport()`" ] }, { "cell_type": "markdown", "id": "40c103d4", "metadata": {}, "source": [ "This is the method in the `Connection` class which calculates the parallel transport of a given tangent vector, in the direction of another tangent vector. Run the following code to see the `parallel_transport` method in Geomstats:" ] }, { "cell_type": "code", "execution_count": 2, "id": "500c447b", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " def parallel_transport(\n", " self, tangent_vec, base_point, direction=None, end_point=None\n", " ):\n", " r\"\"\"Compute the parallel transport of a tangent vector.\n", "\n", " Closed-form solution for the parallel transport of a tangent vector\n", " along the geodesic between two points `base_point` and `end_point`\n", " or alternatively defined by :math:`t \\mapsto exp_{(base\\_point)}(\n", " t*direction)`.\n", "\n", " Parameters\n", " ----------\n", " tangent_vec : array-like, shape=[..., {dim, [n, m]}]\n", " Tangent vector at base point to be transported.\n", " base_point : array-like, shape=[..., {dim, [n, m]}]\n", " Point on the manifold. Point to transport from.\n", " direction : array-like, shape=[..., {dim, [n, m]}]\n", " Tangent vector at base point, along which the parallel transport\n", " is computed.\n", " Optional, default: None.\n", " end_point : array-like, shape=[..., {dim, [n, m]}]\n", " Point on the manifold. Point to transport to.\n", " Optional, default: None.\n", "\n", " Returns\n", " -------\n", " transported_tangent_vec: array-like, shape=[..., {dim, [n, m]}]\n", " Transported tangent vector at `exp_(base_point)(tangent_vec_b)`.\n", " \"\"\"\n", " raise NotImplementedError(\n", " \"The closed-form solution of parallel transport is not known, \"\n", " \"use the ladder_parallel_transport instead.\"\n", " )\n" ] } ], "source": [ "import inspect\n", "\n", "from geomstats.geometry.connection import Connection\n", "\n", "for line in inspect.getsourcelines(Connection.parallel_transport)[0]:\n", " line = line.replace(\"\\n\", \"\")\n", " print(line)" ] }, { "cell_type": "markdown", "id": "56736bf7", "metadata": {}, "source": [ "## 6.2 method: `geodesic_equation()`" ] }, { "cell_type": "markdown", "id": "f7677aad", "metadata": {}, "source": [ "This is the method in the `Connection` class which calculates the geodesic that a given tangent vector will follow on the manifold. In this code, note the use of the christoffel symbols that allows us to give the expression of the geodesic equation in local coordinates. Also note the use of the function \"einsum\" which refers to the Einstein summation that we described above. Run the code below to see the `geodesic_equation` method in Geomstats. " ] }, { "cell_type": "code", "execution_count": 3, "id": "2369a6b5", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " def geodesic_equation(self, state, _time):\n", " \"\"\"Compute the geodesic ODE associated with the connection.\n", "\n", " Parameters\n", " ----------\n", " state : array-like, shape=[..., dim]\n", " Tangent vector at the position.\n", " _time : array-like, shape=[..., dim]\n", " Point on the manifold, the position at which to compute the\n", " geodesic ODE.\n", "\n", " Returns\n", " -------\n", " geodesic_ode : array-like, shape=[..., dim]\n", " Value of the vector field to be integrated at position.\n", " \"\"\"\n", " position, velocity = state\n", " gamma = self.christoffels(position)\n", " equation = gs.einsum(\"...kij,...i->...kj\", gamma, velocity)\n", " equation = -gs.einsum(\"...kj,...j->...k\", equation, velocity)\n", " return gs.stack([velocity, equation])\n" ] } ], "source": [ "import inspect\n", "\n", "from geomstats.geometry.connection import Connection\n", "\n", "for line in inspect.getsourcelines(Connection.geodesic_equation)[0]:\n", " line = line.replace(\"\\n\", \"\")\n", " print(line)" ] }, { "cell_type": "markdown", "id": "5e671689", "metadata": {}, "source": [ "## 6.3 method: `exp()` (exponential)" ] }, { "cell_type": "markdown", "id": "1d6f264b", "metadata": {}, "source": [ "This is the method in the `Connection` class which computes the exponential of a point and a vector on a manifold. Run the following code to see the `exp` method in Geomstats:" ] }, { "cell_type": "code", "execution_count": 4, "id": "f1948777", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " def exp(self, tangent_vec, base_point):\n", " \"\"\"Exponential map associated to the affine connection.\n", "\n", " Parameters\n", " ----------\n", " tangent_vec : array-like, shape=[..., dim]\n", " Tangent vector at the base point.\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold.\n", "\n", " Returns\n", " -------\n", " exp : array-like, shape=[..., dim]\n", " Point on the manifold.\n", " \"\"\"\n", " _check_exp_solver(self)\n", " return self.exp_solver.exp(self._space, tangent_vec, base_point)\n" ] } ], "source": [ "import inspect\n", "\n", "from geomstats.geometry.connection import Connection\n", "\n", "for line in inspect.getsourcelines(Connection.exp)[0]:\n", " line = line.replace(\"\\n\", \"\")\n", " print(line)" ] }, { "cell_type": "markdown", "id": "cbd89564", "metadata": {}, "source": [ "## 6.4 method: `log()` (logarithm)" ] }, { "cell_type": "markdown", "id": "61ff442a", "metadata": {}, "source": [ "This is the method in the `Connection` class which computes the logarithm of two points on a manifold. Run the following code to see the `log` method in Geomstats:" ] }, { "cell_type": "code", "execution_count": 5, "id": "cbe07840", "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " def log(self, point, base_point):\n", " \"\"\"Compute logarithm map associated to the affine connection.\n", "\n", " Solve the boundary value problem associated to the geodesic equation\n", " using the Christoffel symbols and conjugate gradient descent.\n", "\n", " Parameters\n", " ----------\n", " point : array-like, shape=[..., dim]\n", " Point on the manifold.\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold.\n", " n_steps : int\n", " Number of discrete time steps to take in the integration.\n", " Optional, default: N_STEPS.\n", " step : str, {'euler', 'rk4'}\n", " Numerical scheme to use for integration.\n", " Optional, default: 'euler'.\n", " max_iter\n", " verbose\n", " tol\n", "\n", " Returns\n", " -------\n", " tangent_vec : array-like, shape=[..., dim]\n", " Tangent vector at the base point.\n", " \"\"\"\n", " _check_log_solver(self)\n", " return self.log_solver.log(self._space, point, base_point)\n" ] } ], "source": [ "import inspect\n", "\n", "from geomstats.geometry.connection import Connection\n", "\n", "for line in inspect.getsourcelines(Connection.log)[0]:\n", " line = line.replace(\"\\n\", \"\")\n", " print(line)" ] }, { "cell_type": "markdown", "id": "94a00c58", "metadata": {}, "source": [ "## 6.5 The full `Connection` class\n", "\n", "Run the code below to see the entire code for the `Connection` class:" ] }, { "cell_type": "code", "execution_count": 6, "id": "fde96c70", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class Connection(ABC):\n", " r\"\"\"Class for affine connections.\n", "\n", " Parameters\n", " ----------\n", " space : Manifold object\n", " M in the tuple (M, g).\n", " \"\"\"\n", "\n", " def __init__(self, space):\n", " self._space = space\n", "\n", " def christoffels(self, base_point):\n", " \"\"\"Christoffel symbols associated with the connection.\n", "\n", " The contravariant index is on the first dimension.\n", "\n", " Parameters\n", " ----------\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold.\n", "\n", " Returns\n", " -------\n", " gamma : array-like, shape=[..., dim, dim, dim]\n", " Christoffel symbols, with the contravariant index on\n", " the first dimension.\n", " \"\"\"\n", " raise NotImplementedError(\"The Christoffel symbols are not implemented.\")\n", "\n", " def geodesic_equation(self, state, _time):\n", " \"\"\"Compute the geodesic ODE associated with the connection.\n", "\n", " Parameters\n", " ----------\n", " state : array-like, shape=[..., dim]\n", " Tangent vector at the position.\n", " _time : array-like, shape=[..., dim]\n", " Point on the manifold, the position at which to compute the\n", " geodesic ODE.\n", "\n", " Returns\n", " -------\n", " geodesic_ode : array-like, shape=[..., dim]\n", " Value of the vector field to be integrated at position.\n", " \"\"\"\n", " position, velocity = state\n", " gamma = self.christoffels(position)\n", " equation = gs.einsum(\"...kij,...i->...kj\", gamma, velocity)\n", " equation = -gs.einsum(\"...kj,...j->...k\", equation, velocity)\n", " return gs.stack([velocity, equation])\n", "\n", " def exp(self, tangent_vec, base_point):\n", " \"\"\"Exponential map associated to the affine connection.\n", "\n", " Parameters\n", " ----------\n", " tangent_vec : array-like, shape=[..., dim]\n", " Tangent vector at the base point.\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold.\n", "\n", " Returns\n", " -------\n", " exp : array-like, shape=[..., dim]\n", " Point on the manifold.\n", " \"\"\"\n", " _check_exp_solver(self)\n", " return self.exp_solver.exp(self._space, tangent_vec, base_point)\n", "\n", " def log(self, point, base_point):\n", " \"\"\"Compute logarithm map associated to the affine connection.\n", "\n", " Solve the boundary value problem associated to the geodesic equation\n", " using the Christoffel symbols and conjugate gradient descent.\n", "\n", " Parameters\n", " ----------\n", " point : array-like, shape=[..., dim]\n", " Point on the manifold.\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold.\n", " n_steps : int\n", " Number of discrete time steps to take in the integration.\n", " Optional, default: N_STEPS.\n", " step : str, {'euler', 'rk4'}\n", " Numerical scheme to use for integration.\n", " Optional, default: 'euler'.\n", " max_iter\n", " verbose\n", " tol\n", "\n", " Returns\n", " -------\n", " tangent_vec : array-like, shape=[..., dim]\n", " Tangent vector at the base point.\n", " \"\"\"\n", " _check_log_solver(self)\n", " return self.log_solver.log(self._space, point, base_point)\n", "\n", " def _pole_ladder_step(\n", " self, base_point, next_point, base_shoot, return_geodesics=False\n", " ):\n", " \"\"\"Compute one Pole Ladder step.\n", "\n", " One step of pole ladder scheme [LP2013a]_ using the geodesic to\n", " transport along as main_geodesic of the parallelogram.\n", "\n", " Parameters\n", " ----------\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold, from which to transport.\n", " next_point : array-like, shape=[..., dim]\n", " Point on the manifold, to transport to.\n", " base_shoot : array-like, shape=[..., dim]\n", " Point on the manifold, end point of the geodesics starting\n", " from the base point with initial speed to be transported.\n", " return_geodesics : bool, optional (defaults to False)\n", " Whether to return the geodesics of the\n", " construction.\n", "\n", " Returns\n", " -------\n", " next_step : dict of array-like and callable with following keys:\n", " next_tangent_vec : array-like, shape=[..., dim]\n", " Tangent vector at end point.\n", " end_point : array-like, shape=[..., dim]\n", " Point on the manifold, closes the geodesic parallelogram of the\n", " construction.\n", " geodesics : list of callable, len=3 (only if\n", " `return_geodesics=True`)\n", " Three geodesics of the construction.\n", "\n", " References\n", " ----------\n", " .. [LP2013a] Marco Lorenzi, Xavier Pennec. Efficient Parallel Transport\n", " of Deformations in Time Series of Images: from Schild's to\n", " Pole Ladder. Journal of Mathematical Imaging and Vision, Springer\n", " Verlag, 2013,50 (1-2), pp.5-17. ⟨10.1007/s10851-013-0470-3⟩\n", " \"\"\"\n", " mid_tangent_vector_to_shoot = (\n", " 1.0 / 2.0 * self.log(base_point=base_point, point=next_point)\n", " )\n", "\n", " mid_point = self.exp(\n", " base_point=base_point, tangent_vec=mid_tangent_vector_to_shoot\n", " )\n", "\n", " tangent_vector_to_shoot = -self.log(base_point=mid_point, point=base_shoot)\n", "\n", " end_shoot = self.exp(base_point=mid_point, tangent_vec=tangent_vector_to_shoot)\n", "\n", " geodesics = []\n", " if return_geodesics:\n", " main_geodesic = self.geodesic(\n", " initial_point=base_point, end_point=next_point\n", " )\n", " diagonal = self.geodesic(initial_point=mid_point, end_point=base_shoot)\n", " final_geodesic = self.geodesic(\n", " initial_point=next_point, end_point=end_shoot\n", " )\n", " geodesics = [main_geodesic, diagonal, final_geodesic]\n", " return {\"geodesics\": geodesics, \"end_point\": end_shoot}\n", "\n", " def _schild_ladder_step(\n", " self, base_point, next_point, base_shoot, return_geodesics=False\n", " ):\n", " \"\"\"Compute one Schild's Ladder step.\n", "\n", " One step of the Schild's ladder scheme [LP2013a]_ using the geodesic to\n", " transport along as one side of the parallelogram.\n", "\n", " Parameters\n", " ----------\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold, from which to transport.\n", " next_point : array-like, shape=[..., dim]\n", " Point on the manifold, to transport to.\n", " base_shoot : array-like, shape=[..., dim]\n", " Point on the manifold, end point of the geodesics starting\n", " from the base point with initial speed to be transported.\n", " return_geodesics : bool\n", " Whether to return points computed along each geodesic of the\n", " construction.\n", " Optional, default: False.\n", "\n", " Returns\n", " -------\n", " transported_tangent_vector : array-like, shape=[..., dim]\n", " Tangent vector at end point.\n", " end_point : array-like, shape=[..., dim]\n", " Point on the manifold, closes the geodesic parallelogram of the\n", " construction.\n", "\n", " References\n", " ----------\n", " .. [LP2013a] Marco Lorenzi, Xavier Pennec. Efficient Parallel Transport\n", " of Deformations in Time Series of Images: from Schild's to\n", " Pole Ladder. Journal of Mathematical Imaging and Vision, Springer\n", " Verlag, 2013,50 (1-2), pp.5-17. ⟨10.1007/s10851-013-0470-3⟩\n", " \"\"\"\n", " mid_tangent_vector_to_shoot = (\n", " 1.0 / 2.0 * self.log(base_point=base_shoot, point=next_point)\n", " )\n", "\n", " mid_point = self.exp(\n", " base_point=base_shoot, tangent_vec=mid_tangent_vector_to_shoot\n", " )\n", "\n", " tangent_vector_to_shoot = -self.log(base_point=mid_point, point=base_point)\n", "\n", " end_shoot = self.exp(base_point=mid_point, tangent_vec=tangent_vector_to_shoot)\n", "\n", " geodesics = []\n", " if return_geodesics:\n", " main_geodesic = self.geodesic(\n", " initial_point=base_point, end_point=next_point\n", " )\n", " diagonal = self.geodesic(initial_point=base_point, end_point=end_shoot)\n", " second_diagonal = self.geodesic(\n", " initial_point=base_shoot, end_point=next_point\n", " )\n", " final_geodesic = self.geodesic(\n", " initial_point=next_point, end_point=end_shoot\n", " )\n", " geodesics = [main_geodesic, diagonal, second_diagonal, final_geodesic]\n", " return {\"geodesics\": geodesics, \"end_point\": end_shoot}\n", "\n", " def ladder_parallel_transport(\n", " self,\n", " tangent_vec,\n", " base_point,\n", " direction,\n", " n_rungs=1,\n", " scheme=\"pole\",\n", " alpha=1,\n", " return_geodesics=False,\n", " ):\n", " \"\"\"Approximate parallel transport using the pole ladder scheme.\n", "\n", " Approximate Parallel transport using either the pole ladder or the\n", " Schild's ladder scheme [LP2013b]_. Pole ladder is exact in symmetric\n", " spaces and of order two in general while Schild's ladder is a first\n", " order approximation [GP2020]_. Both schemes are available on any affine\n", " connection manifolds whose exponential and logarithm maps are\n", " implemented. `tangent_vec` is transported along the geodesic starting\n", " at the base_point with initial tangent vector `direction`.\n", "\n", " Parameters\n", " ----------\n", " tangent_vec : array-like, shape=[..., dim]\n", " Tangent vector at base point to transport.\n", " direction : array-like, shape=[..., dim]\n", " Tangent vector at base point, initial speed of the geodesic along\n", " which to transport.\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold, initial position of the geodesic along\n", " which to transport.\n", " n_rungs : int\n", " Number of steps of the ladder.\n", " Optional, default: 1.\n", " scheme : str, {'pole', 'schild'}\n", " The scheme to use for the construction of the ladder at each step.\n", " Optional, default: 'pole'.\n", " alpha : float\n", " Exponent for the scaling of the vector to transport. Must be\n", " greater or equal to 1, 2 is optimal. See [GP2020]_.\n", " Optional, default: 2\n", "\n", " Returns\n", " -------\n", " ladder : dict of array-like and callable with following keys\n", " transported_tangent_vector : array-like, shape=[..., dim]\n", " Approximation of the parallel transport of tangent vector a.\n", " trajectory : list of list of callable, len=n_steps\n", " List of lists containing the geodesics of the\n", " construction, only if `return_geodesics=True` in the step\n", " function. The geodesics are methods of the class connection.\n", "\n", " References\n", " ----------\n", " .. [LP2013b] Lorenzi, Marco, and Xavier Pennec. “Efficient Parallel\n", " Transport of Deformations in Time Series of Images: From Schild to\n", " Pole Ladder.” Journal of Mathematical Imaging and Vision 50, no. 1\n", " (September 1, 2014): 5–17.\n", " https://doi.org/10.1007/s10851-013-0470-3.\n", "\n", " .. [GP2020] Guigui, Nicolas, and Xavier Pennec. “Numerical Accuracy\n", " of Ladder Schemes for Parallel Transport on Manifolds.”\n", " Foundations of Computational Mathematics, June 18, 2021.\n", " https://doi.org/10.1007/s10208-021-09515-x.\n", " \"\"\"\n", " geomstats.errors.check_integer(n_rungs, \"n_rungs\")\n", " if alpha < 1:\n", " raise ValueError(\"alpha must be greater or equal to one\")\n", " current_point = base_point\n", " next_tangent_vec = tangent_vec / (n_rungs**alpha)\n", " methods = {\"pole\": self._pole_ladder_step, \"schild\": self._schild_ladder_step}\n", " single_step = methods[scheme]\n", " base_shoot = self.exp(base_point=current_point, tangent_vec=next_tangent_vec)\n", " trajectory = []\n", " for i_point in range(n_rungs):\n", " frac_tan_vector_b = (i_point + 1) / n_rungs * direction\n", " next_point = self.exp(base_point=base_point, tangent_vec=frac_tan_vector_b)\n", " next_step = single_step(\n", " base_point=current_point,\n", " next_point=next_point,\n", " base_shoot=base_shoot,\n", " return_geodesics=return_geodesics,\n", " )\n", " current_point = next_point\n", " base_shoot = next_step[\"end_point\"]\n", " trajectory.append(next_step[\"geodesics\"])\n", " transported_tangent_vec = self.log(base_shoot, current_point)\n", " if n_rungs % 2 == 1 and scheme == \"pole\":\n", " transported_tangent_vec *= -1.0\n", " transported_tangent_vec *= n_rungs**alpha\n", " return {\n", " \"transported_tangent_vec\": transported_tangent_vec,\n", " \"end_point\": current_point,\n", " \"trajectory\": trajectory,\n", " }\n", "\n", " def riemann_tensor(self, base_point):\n", " r\"\"\"Compute Riemannian tensor at base_point.\n", "\n", " In the literature the Riemannian curvature tensor is noted :math:`R_{ijk}^l`.\n", "\n", " Following tensor index convention (ref. Wikipedia), we have:\n", " :math:`R_{ijk}^l = dx^l(R(X_j, X_k)X_i)`\n", "\n", " which gives :math:`R_{ijk}^l` as a sum of four terms:\n", "\n", " .. math::\n", " \\partial_j \\Gamma^l_{ki} - \\partial_k \\Gamma^l_{ji}\n", " + \\Gamma^l_{jm} \\Gamma^m_{ki} - \\Gamma^l_{km} \\Gamma^m_{ji}\n", "\n", " Note that geomstats puts the contravariant index on\n", " the first dimension of the Christoffel symbols.\n", "\n", " Parameters\n", " ----------\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold.\n", "\n", " Returns\n", " -------\n", " riemann_curvature : array-like, shape=[..., dim, dim, dim, dim]\n", " riemann_tensor[...,i,j,k,l] = R_{ijk}^l\n", " Riemannian tensor curvature,\n", " with the contravariant index on the last dimension.\n", " \"\"\"\n", " if len(self._space.shape) > 1:\n", " raise NotImplementedError(\n", " \"Riemann tensor not implemented for manifolds with points of ndim > 1.\"\n", " )\n", " christoffels = self.christoffels(base_point)\n", " jacobian_christoffels = gs.autodiff.jacobian_vec(self.christoffels)(base_point)\n", "\n", " prod_christoffels = gs.einsum(\n", " \"...ijk,...klm->...ijlm\", christoffels, christoffels\n", " )\n", " riemann_curvature = (\n", " gs.einsum(\"...ijlm->...lmji\", jacobian_christoffels)\n", " - gs.einsum(\"...ijlm->...ljmi\", jacobian_christoffels)\n", " + gs.einsum(\"...ijlm->...mjli\", prod_christoffels)\n", " - gs.einsum(\"...ijlm->...lmji\", prod_christoffels)\n", " )\n", "\n", " return riemann_curvature\n", "\n", " def curvature(self, tangent_vec_a, tangent_vec_b, tangent_vec_c, base_point):\n", " r\"\"\"Compute the Riemann curvature map R.\n", "\n", " For three tangent vectors at base point :math:`P`:\n", "\n", " - :math:`X|_P = tangent\\_vec\\_a`,\n", " - :math:`Y|_P = tangent\\_vec\\_b`,\n", " - :math:`Z|_P = tangent\\_vec\\_c`,\n", "\n", " the curvature(X, Y, Z, P) is defined by\n", " :math:`R(X,Y)Z = \\nabla_X \\nabla_Y Z - \\nabla_Y \\nabla_X Z - \\nabla_[X, Y]Z`.\n", "\n", " The output is the tangent vector:\n", " :math:`dx^l(R(X, Y)Z) = R_{ijk}^l X_j Y_k Z_i`\n", " written with Einstein notation.\n", "\n", " Parameters\n", " ----------\n", " tangent_vec_a : array-like, shape=[..., dim]\n", " Tangent vector at `base_point`.\n", " tangent_vec_b : array-like, shape=[..., dim]\n", " Tangent vector at `base_point`.\n", " tangent_vec_c : array-like, shape=[..., dim]\n", " Tangent vector at `base_point`.\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold.\n", "\n", " Returns\n", " -------\n", " curvature : array-like, shape=[..., dim]\n", " curvature(X, Y, Z, P)[..., l] = dx^l(R(X, Y)Z)\n", " Tangent vector at `base_point`.\n", " \"\"\"\n", " riemann = self.riemann_tensor(base_point)\n", " curvature = gs.einsum(\n", " \"...ijkl, ...j, ...k, ...i -> ...l\",\n", " riemann,\n", " tangent_vec_a,\n", " tangent_vec_b,\n", " tangent_vec_c,\n", " )\n", " return curvature\n", "\n", " def ricci_tensor(self, base_point):\n", " r\"\"\"Compute Ricci curvature tensor at base_point.\n", "\n", " The Ricci curvature tensor :math:`\\mathrm{Ric}_{ij}` is defined as:\n", " :math:`\\mathrm{Ric}_{ij} = R_{ikj}^k`\n", " with Einstein notation.\n", "\n", " Parameters\n", " ----------\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold.\n", "\n", " Returns\n", " -------\n", " ricci_tensor : array-like, shape=[..., dim, dim]\n", " ricci_tensor[...,i,j] = Ric_{ij}\n", " Ricci tensor curvature.\n", " \"\"\"\n", " riemann_tensor = self.riemann_tensor(base_point)\n", " ricci_tensor = gs.einsum(\"...ijkj -> ...ik\", riemann_tensor)\n", " return ricci_tensor\n", "\n", " def directional_curvature(self, tangent_vec_a, tangent_vec_b, base_point):\n", " r\"\"\"Compute the directional curvature (tidal force operator).\n", "\n", " For two tangent vectors at base_point :math:`P`:\n", "\n", " - :math:`X|_P = tangent\\_vec\\_a`,\n", " - :math:`Y|_P = tangent\\_vec\\_b`,\n", "\n", " the directional curvature, better known\n", " in relativity as the tidal force operator,\n", " is defined by\n", " :math:`R_Y(X) = R(Y,X)Y`.\n", "\n", " Parameters\n", " ----------\n", " tangent_vec_a : array-like, shape=[..., dim]\n", " Tangent vector at `base_point`.\n", " tangent_vec_b : array-like, shape=[..., dim]\n", " Tangent vector at `base_point`.\n", " base_point : array-like, shape=[..., dim]\n", " Base-point on the manifold.\n", "\n", " Returns\n", " -------\n", " directional_curvature : array-like, shape=[..., dim]\n", " Tangent vector at `base_point`.\n", " \"\"\"\n", " return self.curvature(tangent_vec_b, tangent_vec_a, tangent_vec_b, base_point)\n", "\n", " def curvature_derivative(\n", " self,\n", " tangent_vec_a,\n", " tangent_vec_b,\n", " tangent_vec_c,\n", " tangent_vec_d,\n", " base_point=None,\n", " ):\n", " r\"\"\"Compute the covariant derivative of the curvature.\n", "\n", " For four tangent vectors at base_point :math:`P`:\n", "\n", " - :math:`H|_P = tangent\\_vec\\_a`,\n", " - :math:`X|_P = tangent\\_vec\\_b`,\n", " - :math:`Y|_P = tangent\\_vec\\_c`,\n", " - :math:`Z|_P = tangent\\_vec\\_d`,\n", "\n", " the covariant derivative of the curvature is defined as:\n", " :math:`(\\nabla_H R)(X, Y) Z |_P`.\n", "\n", " Parameters\n", " ----------\n", " tangent_vec_a : array-like, shape=[..., dim]\n", " Tangent vector at `base_point`.\n", " tangent_vec_b : array-like, shape=[..., dim]\n", " Tangent vector at `base_point`.\n", " tangent_vec_c : array-like, shape=[..., dim]\n", " Tangent vector at `base_point`.\n", " tangent_vec_d : array-like, shape=[..., dim]\n", " Tangent vector at `base_point`.\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold.\n", "\n", " Returns\n", " -------\n", " curvature_derivative : array-like, shape=[..., dim]\n", " Tangent vector at base-point.\n", " \"\"\"\n", " raise NotImplementedError(\n", " \"The covariant derivative of the curvature is not implemented.\"\n", " )\n", "\n", " def directional_curvature_derivative(\n", " self, tangent_vec_a, tangent_vec_b, base_point=None\n", " ):\n", " r\"\"\"Compute the covariant derivative of the directional curvature.\n", "\n", " For tangent vector fields at base_point :math:`P`:\n", "\n", " - :math:`X|_P = tangent\\_vec\\_a`,\n", " - :math:`Y|_P = tangent\\_vec\\_b`,\n", "\n", " the covariant derivative (in the direction `X`)\n", " :math:`(\\nabla_X R_Y)(X) |_P = (\\nabla_X R)(Y, X) Y |_P` of the\n", " directional curvature (in the direction `Y`)\n", " :math:`R_Y(X) = R(Y, X) Y`\n", " is a quadratic tensor in `X` and `Y` that\n", " plays an important role in the computation of the moments of the\n", " empirical Fréchet mean.\n", "\n", " References\n", " ----------\n", " .. [Pennec] Pennec, Xavier. Curvature effects on the empirical mean in\n", " Riemannian and affine Manifolds: a non-asymptotic high\n", " concentration expansion in the small-sample regime. Preprint. 2019.\n", " https://arxiv.org/abs/1906.07418\n", " \"\"\"\n", " return self.curvature_derivative(\n", " tangent_vec_a, tangent_vec_b, tangent_vec_a, tangent_vec_b, base_point\n", " )\n", "\n", " def _geodesic_from_exp(self, initial_point, initial_tangent_vec):\n", " \"\"\"Generate parameterized function for the geodesic curve.\n", "\n", " Parameters\n", " ----------\n", " initial_point : array-like, shape=[..., dim]\n", " Point on the manifold, initial point of the geodesic.\n", " initial_tangent_vec : array-like, shape=[..., dim],\n", " Tangent vector at base point, the initial speed of the geodesics.\n", " Optional, default: None.\n", " If None, an end point must be given and a logarithm is computed.\n", "\n", " Returns\n", " -------\n", " path : callable\n", " Time parameterized geodesic curve. If a batch of initial\n", " conditions is passed, the output array's first dimension\n", " represents the different initial conditions, and the second\n", " corresponds to time.\n", " \"\"\"\n", " ndim = self._space.point_ndim\n", " ijk = \"ijk\"[: self._space.point_ndim]\n", "\n", " multiple_tangent = initial_tangent_vec.ndim > ndim\n", " multiple_point = initial_point.ndim > ndim\n", " is_batch = multiple_tangent or multiple_point\n", "\n", " def path(t):\n", " \"\"\"Generate parameterized function for geodesic curve.\n", "\n", " Parameters\n", " ----------\n", " t : array-like, shape=[n_points,]\n", " Times at which to compute points of the geodesics.\n", " \"\"\"\n", " t = gs.array(t)\n", " t = gs.cast(t, initial_tangent_vec.dtype)\n", " t = gs.to_ndarray(t, to_ndim=1)\n", "\n", " tangent_vecs = gs.einsum(f\"n,...{ijk}->...n{ijk}\", t, initial_tangent_vec)\n", " if is_batch:\n", " if multiple_point and multiple_tangent:\n", " points_at_time_t = [\n", " self.exp(tv, pt) for tv, pt in zip(tangent_vecs, initial_point)\n", " ]\n", "\n", " elif multiple_point:\n", " points_at_time_t = [\n", " self.exp(tangent_vecs, pt) for pt in initial_point\n", " ]\n", "\n", " elif multiple_tangent:\n", " points_at_time_t = [\n", " self.exp(tv, initial_point) for tv in tangent_vecs\n", " ]\n", "\n", " return gs.stack(points_at_time_t, axis=0)\n", "\n", " return self.exp(tangent_vecs, initial_point)\n", "\n", " return path\n", "\n", " def _geodesic_ivp(self, initial_point, initial_tangent_vec):\n", " \"\"\"Solve geodesic initial value problem.\n", "\n", " Compute the parameterized function for the geodesic starting at\n", " initial_point with initial velocity given by initial_tangent_vec.\n", "\n", " Parameters\n", " ----------\n", " initial_point : array-like, shape=[..., dim]\n", " Initial point.\n", "\n", " initial_tangent_vec : array-like, shape=[..., dim]\n", " Tangent vector at initial point.\n", "\n", " Returns\n", " -------\n", " path : function\n", " Parameterized function for the geodesic curve starting at\n", " initial_point with velocity initial_tangent_vec.\n", " \"\"\"\n", " if _check_exp_solver(self, raise_=False) and hasattr(\n", " self.exp_solver, \"geodesic_ivp\"\n", " ):\n", " return self.exp_solver.geodesic_ivp(\n", " self._space, initial_tangent_vec, initial_point\n", " )\n", "\n", " return self._geodesic_from_exp(initial_point, initial_tangent_vec)\n", "\n", " def _geodesic_bvp(self, initial_point, end_point):\n", " \"\"\"Solve geodesic boundary problem.\n", "\n", " Compute the parameterized function for the geodesic starting at\n", " initial_point and ending at end_point.\n", "\n", " Parameters\n", " ----------\n", " initial_point : array-like, shape=[..., dim]\n", " Initial point.\n", " end_point : array-like, shape=[..., dim]\n", " End point.\n", "\n", " Returns\n", " -------\n", " path : function\n", " Parameterized function for the geodesic curve starting at\n", " initial_point and ending at end_point.\n", " \"\"\"\n", " if _check_log_solver(self, raise_=False) and hasattr(\n", " self.log_solver, \"geodesic_bvp\"\n", " ):\n", " return self.log_solver.geodesic_bvp(\n", " self._space,\n", " end_point,\n", " initial_point,\n", " )\n", " return NotImplemented\n", "\n", " def geodesic(self, initial_point, end_point=None, initial_tangent_vec=None):\n", " \"\"\"Generate parameterized function for the geodesic curve.\n", "\n", " Geodesic curve defined by either:\n", "\n", " - an initial point and an initial tangent vector,\n", " - an initial point and an end point.\n", "\n", " Parameters\n", " ----------\n", " initial_point : array-like, shape=[..., dim]\n", " Point on the manifold, initial point of the geodesic.\n", " end_point : array-like, shape=[..., dim], optional\n", " Point on the manifold, end point of the geodesic. If None,\n", " an initial tangent vector must be given.\n", " initial_tangent_vec : array-like, shape=[..., dim],\n", " Tangent vector at base point, the initial speed of the geodesics.\n", " Optional, default: None.\n", " If None, an end point must be given and a logarithm is computed.\n", "\n", " Returns\n", " -------\n", " path : callable\n", " Time parameterized geodesic curve. If a batch of initial\n", " conditions is passed, the output array's first dimension\n", " represents the different initial conditions, and the second\n", " corresponds to time.\n", " \"\"\"\n", " if end_point is None and initial_tangent_vec is None:\n", " raise ValueError(\n", " \"Specify an end point or an initial tangent \"\n", " \"vector to define the geodesic.\"\n", " )\n", " if end_point is not None:\n", " if initial_tangent_vec is not None:\n", " raise ValueError(\n", " \"Cannot specify both an end point and an initial tangent vector.\"\n", " )\n", "\n", " out = self._geodesic_bvp(initial_point, end_point)\n", " if out is not NotImplemented:\n", " return out\n", "\n", " initial_tangent_vec = self.log(end_point, initial_point)\n", "\n", " return self._geodesic_ivp(initial_point, initial_tangent_vec)\n", "\n", " def parallel_transport(\n", " self, tangent_vec, base_point, direction=None, end_point=None\n", " ):\n", " r\"\"\"Compute the parallel transport of a tangent vector.\n", "\n", " Closed-form solution for the parallel transport of a tangent vector\n", " along the geodesic between two points `base_point` and `end_point`\n", " or alternatively defined by :math:`t \\mapsto exp_{(base\\_point)}(\n", " t*direction)`.\n", "\n", " Parameters\n", " ----------\n", " tangent_vec : array-like, shape=[..., {dim, [n, m]}]\n", " Tangent vector at base point to be transported.\n", " base_point : array-like, shape=[..., {dim, [n, m]}]\n", " Point on the manifold. Point to transport from.\n", " direction : array-like, shape=[..., {dim, [n, m]}]\n", " Tangent vector at base point, along which the parallel transport\n", " is computed.\n", " Optional, default: None.\n", " end_point : array-like, shape=[..., {dim, [n, m]}]\n", " Point on the manifold. Point to transport to.\n", " Optional, default: None.\n", "\n", " Returns\n", " -------\n", " transported_tangent_vec: array-like, shape=[..., {dim, [n, m]}]\n", " Transported tangent vector at `exp_(base_point)(tangent_vec_b)`.\n", " \"\"\"\n", " raise NotImplementedError(\n", " \"The closed-form solution of parallel transport is not known, \"\n", " \"use the ladder_parallel_transport instead.\"\n", " )\n", "\n", " def injectivity_radius(self, base_point):\n", " \"\"\"Compute the radius of the injectivity domain.\n", "\n", " This is is the supremum of radii r for which the exponential map is a\n", " diffeomorphism from the open ball of radius r centered at the base\n", " point onto its image.\n", "\n", " Parameters\n", " ----------\n", " base_point : array-like, shape=[..., {dim, [n, m]}]\n", " Point on the manifold.\n", "\n", " Returns\n", " -------\n", " radius : array-like, shape=[...,]\n", " Injectivity radius.\n", " \"\"\"\n", " raise NotImplementedError(\"The injectivity range is not implemented yet.\")\n" ] } ], "source": [ "import inspect\n", "\n", "from geomstats.geometry.connection import Connection\n", "\n", "for line in inspect.getsourcelines(Connection)[0]:\n", " line = line.replace(\"\\n\", \"\")\n", " print(line)" ] }, { "cell_type": "markdown", "id": "f7b1814b", "metadata": {}, "source": [ "# 7. `RiemannianMetric` Sub-Class" ] }, { "cell_type": "markdown", "id": "0043d12d", "metadata": {}, "source": [ "The `RiemannianMetric` class is the only subclass of the `Connection` class. Its function in `Geomstats` is so important that we will dedicate a whole additional section of this notebook to it." ] }, { "cell_type": "markdown", "id": "98ed7694", "metadata": {}, "source": [ "## 7.1 Riemannian Metrics" ] }, { "cell_type": "markdown", "id": "fa6822e6", "metadata": {}, "source": [ "When we considered \"connections\" on manifolds, we had to erase what we thought we knew about transporting vectors. We had to accept the fact that transporting a vector is much more complicated on a manifold because the basis vectors are not identical at each point on a manifold, which leads to much more complicated calculations. Additionally, we had to generalize what we knew about transporting vectors on a Euclidean space. \n", "\n", "Similarly, here we will erase our previous notions of \"measurement\" (distance, angles, curvature, etc.) because the concept of such measurements is quite different on manifolds than in Euclidean space. In fact, there is no way to define notions of such measurements on a manifold until you equip the manifold with a something called a ''metric''.\n", "\n", "A $\\textbf{Riemannian Metric}$ $g$ on a manifold $M$ is a family of inner products $(\\langle.,.\\rangle_p)_{p\\in M}$ on each tangent space $T_pM$ such that $\\langle.,.\\rangle_p$ depends smoothly on $p$. If this does not make sense, then just understand that a Riemannian Metric allows us to describe the space of a manifold using \"inner products\", which allows us to define distance functions and other measurement functions on manifolds. " ] }, { "cell_type": "markdown", "id": "1adaea9d", "metadata": {}, "source": [ "## 7.2 How is the Riemannian Metric Connected with the Connection?" ] }, { "cell_type": "markdown", "id": "b6a1493a", "metadata": {}, "source": [ "$\\textbf{1. First, each Riemannian Metric generates a unique Levi-Civita connection.}$ A Levi-Civita connection is a special type of connection that is \"torsion-free\" and \"compatible\". For now, do not worry about what \"torsion-free\" and \"compatible\" mean. Just know that when we work with connections in Geomstats, we are working with Levi-Civita connections. \n", "\n", "$\\textbf{2. Second, the Riemannian Metric ''g'' allows us to calculate Christoffel symbols.}$ Recall from earlier in this notebook that we can calculate the connection in local coordinates by using christoffel symbols ($\\Gamma_{i j}^{k}$). However, we can only calculate these Christoffel symbols if we have equip the manifold with a metric. In the case of a Levi-Civita connection, the Christoffel symbols can be calculated from the metric as follows:\n", "$$\\Gamma_{i j}^{k} = \\frac{1}{2}g^{lk}(\\partial_i g_{jl}+\\partial_j g_{li}-\\partial_l g_{ij})$$" ] }, { "cell_type": "markdown", "id": "73440a40", "metadata": {}, "source": [ "## 7.3 `RiemannianMetric` in `Geomstats`" ] }, { "cell_type": "markdown", "id": "6ada5067", "metadata": {}, "source": [ "The `RiemannianMetric` subclass is the class that actually performs calculations on manifolds. This is because we cannot perform \"general\" calculations like logarithm, exponential, parallel transport, and calculating geodesics without first being equip with a metric. The `RiemannianMetric` subclass contains a collection of metrics that `Geomstats` users may use to perform calculations on manifolds. The structure of the `RiemannianMetric` class is shown below." ] }, { "cell_type": "markdown", "id": "c1f3a2bd", "metadata": {}, "source": [ "" ] }, { "cell_type": "code", "execution_count": 7, "id": "b7ce35a4", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "class RiemannianMetric(Connection, ABC):\n", " \"\"\"Class for Riemannian and pseudo-Riemannian metrics.\n", "\n", " The associated Levi-Civita connection on the tangent bundle.\n", " \"\"\"\n", "\n", " def __init__(self, space, signature=None):\n", " super().__init__(space=space)\n", " if signature is None:\n", " signature = (space.dim, 0)\n", " self.signature = signature\n", "\n", " def __mul__(self, scalar):\n", " \"\"\"Multiply the metric by a scalar.\n", "\n", " This method multiplies the (0,2) metric tensor by a scalar. Note that this does\n", " not scale distances by the scalar. That would require multiplication by the\n", " square of the scalar.\n", "\n", " Parameters\n", " ----------\n", " scalar : float\n", " The number by which to multiply the metric.\n", "\n", " Returns\n", " -------\n", " metric : ScalarProductMetric\n", " The metric multiplied by the scalar\n", " \"\"\"\n", " from geomstats.geometry.scalar_product_metric import ScalarProductMetric\n", "\n", " if not isinstance(scalar, float):\n", " return NotImplemented\n", " return ScalarProductMetric(self, scalar)\n", "\n", " def __rmul__(self, scalar):\n", " \"\"\"Multiply the metric by a scalar.\n", "\n", " This method multiplies the (0,2) metric tensor by a scalar. Note that this does\n", " not scale distances by the scalar. That would require multiplication by the\n", " square of the scalar.\n", "\n", " Parameters\n", " ----------\n", " scalar : float\n", " The number by which to multiply the metric.\n", "\n", " Returns\n", " -------\n", " metric : ScalarProductMetric\n", " The metric multiplied by the scalar.\n", " \"\"\"\n", " return self * scalar\n", "\n", " def metric_matrix(self, base_point=None):\n", " \"\"\"Metric matrix at the tangent space at a base point.\n", "\n", " Parameters\n", " ----------\n", " base_point : array-like, shape=[..., dim]\n", " Base point.\n", " Optional, default: None.\n", "\n", " Returns\n", " -------\n", " mat : array-like, shape=[..., dim, dim]\n", " Inner-product matrix.\n", " \"\"\"\n", " raise NotImplementedError(\n", " \"The computation of the metric matrix is not implemented.\"\n", " )\n", "\n", " def cometric_matrix(self, base_point=None):\n", " \"\"\"Inner co-product matrix at the cotangent space at a base point.\n", "\n", " This represents the cometric matrix, i.e. the inverse of the\n", " metric matrix.\n", "\n", " Parameters\n", " ----------\n", " base_point : array-like, shape=[..., dim]\n", " Base point.\n", " Optional, default: None.\n", "\n", " Returns\n", " -------\n", " cometric_matrix : array-like, shape=[..., dim, dim]\n", " Inverse of inner-product matrix.\n", " \"\"\"\n", " metric_matrix = self.metric_matrix(base_point)\n", " return gs.linalg.inv(metric_matrix)\n", "\n", " def inner_product_derivative_matrix(self, base_point=None):\n", " r\"\"\"Compute derivative of the inner prod matrix at base point.\n", "\n", " Writing :math:`g_{ij}` the inner-product matrix at base point,\n", " this computes :math:`mat_{ijk} = \\partial_k g_{ij}`, where the\n", " index k of the derivation is put last.\n", "\n", " Parameters\n", " ----------\n", " base_point : array-like, shape=[..., dim]\n", " Base point.\n", " Optional, default: None.\n", "\n", " Returns\n", " -------\n", " metric_derivative : array-like, shape=[..., dim, dim, dim]\n", " Derivative of the inner-product matrix, where the index\n", " k of the derivation is last: :math:`mat_{ijk} = \\partial_k g_{ij}`.\n", " \"\"\"\n", " return gs.autodiff.jacobian_vec(self.metric_matrix)(base_point)\n", "\n", " def christoffels(self, base_point):\n", " r\"\"\"Compute Christoffel symbols of the Levi-Civita connection.\n", "\n", " The Koszul formula defining the Levi-Civita connection gives the\n", " expression of the Christoffel symbols with respect to the metric:\n", " :math:`\\Gamma^k_{ij}(p) = \\frac{1}{2} g^{lk}(\n", " \\partial_i g_{jl} + \\partial_j g_{li} - \\partial_l g_{ij})`,\n", " where:\n", "\n", " - :math:`p` represents the base point, and\n", " - :math:`g` represents the Riemannian metric tensor.\n", "\n", " Note that the function computing the derivative of the metric matrix\n", " puts the index of the derivation last.\n", "\n", " Parameters\n", " ----------\n", " base_point: array-like, shape=[..., dim]\n", " Base point.\n", "\n", " Returns\n", " -------\n", " christoffels: array-like, shape=[..., dim, dim, dim]\n", " Christoffel symbols, where the contravariant index is first.\n", " \"\"\"\n", " cometric_mat_at_point = self.cometric_matrix(base_point)\n", " metric_derivative_at_point = self.inner_product_derivative_matrix(base_point)\n", "\n", " term_1 = gs.einsum(\n", " \"...lk,...jli->...kij\", cometric_mat_at_point, metric_derivative_at_point\n", " )\n", " term_2 = gs.einsum(\n", " \"...lk,...lij->...kij\", cometric_mat_at_point, metric_derivative_at_point\n", " )\n", " term_3 = -gs.einsum(\n", " \"...lk,...ijl->...kij\", cometric_mat_at_point, metric_derivative_at_point\n", " )\n", "\n", " return 0.5 * (term_1 + term_2 + term_3)\n", "\n", " def inner_product(self, tangent_vec_a, tangent_vec_b, base_point):\n", " \"\"\"Inner product between two tangent vectors at a base point.\n", "\n", " Parameters\n", " ----------\n", " tangent_vec_a: array-like, shape=[..., dim]\n", " Tangent vector at base point.\n", " tangent_vec_b: array-like, shape=[..., dim]\n", " Tangent vector at base point.\n", " base_point: array-like, shape=[..., dim]\n", " Base point.\n", " Optional, default: None.\n", "\n", " Returns\n", " -------\n", " inner_product : array-like, shape=[...,]\n", " Inner-product.\n", " \"\"\"\n", " inner_prod_mat = self.metric_matrix(base_point)\n", " aux = gs.einsum(\"...j,...jk->...k\", tangent_vec_a, inner_prod_mat)\n", " return gs.dot(aux, tangent_vec_b)\n", "\n", " def inner_coproduct(self, cotangent_vec_a, cotangent_vec_b, base_point):\n", " \"\"\"Compute inner coproduct between two cotangent vectors at base point.\n", "\n", " This is the inner product associated to the cometric matrix.\n", "\n", " Parameters\n", " ----------\n", " cotangent_vec_a : array-like, shape=[..., dim]\n", " Cotangent vector at `base_point`.\n", " cotangent_vet_b : array-like, shape=[..., dim]\n", " Cotangent vector at `base_point`.\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold.\n", "\n", " Returns\n", " -------\n", " inner_coproduct : float\n", " Inner coproduct between the two cotangent vectors.\n", " \"\"\"\n", " vector_2 = gs.einsum(\n", " \"...ij,...j->...i\", self.cometric_matrix(base_point), cotangent_vec_b\n", " )\n", " return gs.dot(cotangent_vec_a, vector_2)\n", "\n", " def hamiltonian(self, state):\n", " r\"\"\"Compute the hamiltonian energy associated to the cometric.\n", "\n", " The Hamiltonian at state :math:`(q, p)` is defined by\n", "\n", " .. math::\n", " H(q, p) = \\frac{1}{2} _q\n", "\n", " where :math:`<\\cdot, \\cdot>_q` is the cometric at :math:`q`.\n", "\n", " Parameters\n", " ----------\n", " state : tuple of arrays\n", " Position and momentum variables. The position is a point on the\n", " manifold, while the momentum is cotangent vector.\n", "\n", " Returns\n", " -------\n", " energy : float\n", " Hamiltonian energy at `state`.\n", " \"\"\"\n", " position, momentum = state\n", " return 1.0 / 2 * self.inner_coproduct(momentum, momentum, position)\n", "\n", " def squared_norm(self, vector, base_point=None):\n", " \"\"\"Compute the square of the norm of a vector.\n", "\n", " Squared norm of a vector associated to the inner product\n", " at the tangent space at a base point.\n", "\n", " Parameters\n", " ----------\n", " vector : array-like, shape=[..., dim]\n", " Vector.\n", " base_point : array-like, shape=[..., dim]\n", " Base point.\n", " Optional, default: None.\n", "\n", " Returns\n", " -------\n", " sq_norm : array-like, shape=[...,]\n", " Squared norm.\n", " \"\"\"\n", " return self.inner_product(vector, vector, base_point)\n", "\n", " def norm(self, vector, base_point=None):\n", " \"\"\"Compute norm of a vector.\n", "\n", " Norm of a vector associated to the inner product\n", " at the tangent space at a base point.\n", "\n", " Note: This only works for positive-definite\n", " Riemannian metrics and inner products.\n", "\n", " Parameters\n", " ----------\n", " vector : array-like, shape=[..., dim]\n", " Vector.\n", " base_point : array-like, shape=[..., dim]\n", " Base point.\n", " Optional, default: None.\n", "\n", " Returns\n", " -------\n", " norm : array-like, shape=[...,]\n", " Norm.\n", " \"\"\"\n", " sq_norm = self.squared_norm(vector, base_point)\n", " return gs.sqrt(sq_norm)\n", "\n", " def normalize(self, vector, base_point):\n", " \"\"\"Normalize tangent vector at a given point.\n", "\n", " Parameters\n", " ----------\n", " vector : array-like, shape=[..., dim]\n", " Tangent vector at base_point.\n", " base_point : array-like, shape=[..., dim]\n", " Point.\n", "\n", " Returns\n", " -------\n", " normalized_vector : array-like, shape=[..., dim]\n", " Unit tangent vector at base_point.\n", " \"\"\"\n", " norm = self.norm(vector, base_point)\n", " norm = gs.where(norm == 0, gs.ones(norm.shape), norm)\n", " indices = \"ijk\"[: self._space.point_ndim]\n", " return gs.einsum(f\"...{indices},...->...{indices}\", vector, 1 / norm)\n", "\n", " def random_unit_tangent_vec(self, base_point, n_vectors=1):\n", " \"\"\"Generate a random unit tangent vector at a given point.\n", "\n", " Parameters\n", " ----------\n", " base_point : array-like, shape=[..., dim]\n", " Point.\n", " n_vectors : float\n", " Number of vectors to be generated at base_point.\n", " For vectorization purposes n_vectors can be greater than 1 iff\n", " base_point consists of a single point.\n", "\n", " Returns\n", " -------\n", " normalized_vector : array-like, shape=[..., n_vectors, dim]\n", " Random unit tangent vector at base_point.\n", " \"\"\"\n", " is_batch = check_is_batch(self._space.point_ndim, base_point)\n", " if is_batch and n_vectors > 1:\n", " raise ValueError(\n", " \"Several tangent vectors is only applicable to a single base point.\"\n", " )\n", " point_shape = self._space.shape\n", " vec_shape = (n_vectors, *point_shape) if n_vectors > 1 else point_shape\n", " random_vector = gs.random.rand(*vec_shape)\n", " return self.normalize(random_vector, base_point)\n", "\n", " def squared_dist(self, point_a, point_b, **kwargs):\n", " \"\"\"Squared geodesic distance between two points.\n", "\n", " Parameters\n", " ----------\n", " point_a : array-like, shape=[..., dim]\n", " Point.\n", " point_b : array-like, shape=[..., dim]\n", " Point.\n", "\n", " Returns\n", " -------\n", " sq_dist : array-like, shape=[...,]\n", " Squared distance.\n", " \"\"\"\n", " log = self.log(point=point_b, base_point=point_a, **kwargs)\n", "\n", " return self.squared_norm(vector=log, base_point=point_a)\n", "\n", " def dist(self, point_a, point_b, **kwargs):\n", " \"\"\"Geodesic distance between two points.\n", "\n", " Note: It only works for positive definite\n", " Riemannian metrics.\n", "\n", " Parameters\n", " ----------\n", " point_a : array-like, shape=[..., dim]\n", " Point.\n", " point_b : array-like, shape=[..., dim]\n", " Point.\n", "\n", " Returns\n", " -------\n", " dist : array-like, shape=[...,]\n", " Distance.\n", " \"\"\"\n", " sq_dist = self.squared_dist(point_a, point_b, **kwargs)\n", " return gs.sqrt(sq_dist)\n", "\n", " def dist_broadcast(self, point_a, point_b):\n", " \"\"\"Compute the geodesic distance between points.\n", "\n", " If n_samples_a == n_samples_b then dist is the element-wise\n", " distance result of a point in points_a with the point from\n", " points_b of the same index. If n_samples_a not equal to\n", " n_samples_b then dist is the result of applying geodesic\n", " distance for each point from points_a to all points from\n", " points_b.\n", "\n", " Parameters\n", " ----------\n", " point_a : array-like, shape=[n_samples_a, dim]\n", " Set of points in the Poincare ball.\n", " point_b : array-like, shape=[n_samples_b, dim]\n", " Second set of points in the Poincare ball.\n", "\n", " Returns\n", " -------\n", " dist : array-like, \\\n", " shape=[n_samples_a, dim] or [n_samples_a, n_samples_b, dim]\n", " Geodesic distance between the two points.\n", " \"\"\"\n", " ndim = len(self._space.shape)\n", "\n", " if point_a.shape[-ndim:] != point_b.shape[-ndim:]:\n", " raise ValueError(\"Manifold dimensions not equal\")\n", "\n", " if ndim in (point_a.ndim, point_b.ndim) or (point_a.shape == point_b.shape):\n", " return self.dist(point_a, point_b)\n", "\n", " n_samples = point_a.shape[0] * point_b.shape[0]\n", " point_a_broadcast, point_b_broadcast = gs.broadcast_arrays(\n", " point_a[:, None], point_b[None, ...]\n", " )\n", "\n", " point_a_flatten = gs.reshape(\n", " point_a_broadcast, (n_samples,) + point_a.shape[-ndim:]\n", " )\n", " point_b_flatten = gs.reshape(\n", " point_b_broadcast, (n_samples,) + point_a.shape[-ndim:]\n", " )\n", "\n", " dist = self.dist(point_a_flatten, point_b_flatten)\n", " dist = gs.reshape(dist, (point_a.shape[0], point_b.shape[0]))\n", " return gs.squeeze(dist)\n", "\n", " def dist_pairwise(self, points, n_jobs=1, **joblib_kwargs):\n", " \"\"\"Compute the pairwise distance between points.\n", "\n", " Parameters\n", " ----------\n", " points : array-like, shape=[n_samples, dim]\n", " Set of points in the manifold.\n", " n_jobs : int\n", " Number of jobs to run in parallel, using joblib. Note that a\n", " higher number of jobs may not be beneficial when one computation\n", " of a geodesic distance is cheap.\n", " Optional. Default: 1.\n", " **joblib_kwargs : dict\n", " Keyword arguments to joblib.Parallel\n", "\n", " Returns\n", " -------\n", " dist : array-like, shape=[n_samples, n_samples]\n", " Pairwise distance matrix between all the points.\n", "\n", " See Also\n", " --------\n", " `joblib documentations `_\n", " \"\"\"\n", " n_samples = points.shape[0]\n", " rows, cols = gs.triu_indices(n_samples)\n", "\n", " @joblib.delayed\n", " @joblib.wrap_non_picklable_objects\n", " def pickable_dist(x, y):\n", " \"\"\"Wrap distance function to make it pickable.\"\"\"\n", " return self.dist(x, y)\n", "\n", " pool = joblib.Parallel(n_jobs=n_jobs, **joblib_kwargs)\n", " out = pool(pickable_dist(points[i], points[j]) for i, j in zip(rows, cols))\n", "\n", " return geometry.symmetric_matrices.SymmetricMatrices.matrix_representation(\n", " gs.array(out)\n", " )\n", "\n", " def diameter(self, points):\n", " \"\"\"Give the distance between two farthest points.\n", "\n", " Distance between the two points that are farthest away from each other\n", " in points.\n", "\n", " Parameters\n", " ----------\n", " points : array-like, shape=[..., dim]\n", " Points.\n", "\n", " Returns\n", " -------\n", " diameter : float\n", " Distance between two farthest points.\n", " \"\"\"\n", " diameter = 0.0\n", " n_points = points.shape[0]\n", "\n", " for i in range(n_points - 1):\n", " dist_to_neighbors = self.dist(points[i, :], points[i + 1 :, :])\n", " dist_to_farthest_neighbor = gs.amax(dist_to_neighbors)\n", " diameter = gs.maximum(diameter, dist_to_farthest_neighbor)\n", "\n", " return diameter\n", "\n", " def closest_neighbor_index(self, point, neighbors):\n", " \"\"\"Closest neighbor of point among neighbors.\n", "\n", " Parameters\n", " ----------\n", " point : array-like, shape=[..., dim]\n", " Point.\n", " neighbors : array-like, shape=[n_neighbors, dim]\n", " Neighbors.\n", "\n", " Returns\n", " -------\n", " closest_neighbor_index : int\n", " Index of closest neighbor.\n", " \"\"\"\n", " n_points = point.shape[0] if gs.ndim(point) == gs.ndim(neighbors) else 1\n", " n_neighbors = neighbors.shape[0]\n", "\n", " if n_points > 1 and n_neighbors > 1:\n", " neighbors = gs.repeat(neighbors, n_points, axis=0)\n", "\n", " point = gs.concatenate([point for _ in range(n_neighbors)])\n", "\n", " closest_neighbor_index = gs.argmin(\n", " gs.transpose(\n", " gs.reshape(self.dist(point, neighbors), (n_neighbors, n_points)),\n", " ),\n", " axis=1,\n", " )\n", "\n", " if n_points == 1:\n", " return closest_neighbor_index[0]\n", "\n", " return closest_neighbor_index\n", "\n", " def normal_basis(self, basis, base_point=None):\n", " \"\"\"Normalize the basis with respect to the metric.\n", "\n", " This corresponds to a renormalization of each basis vector.\n", "\n", " Parameters\n", " ----------\n", " basis : array-like, shape=[dim, dim]\n", " Matrix of a metric.\n", " base_point\n", "\n", " Returns\n", " -------\n", " basis : array-like, shape=[dim, n, n]\n", " Normal basis.\n", " \"\"\"\n", " norms = self.squared_norm(basis, base_point)\n", "\n", " return gs.einsum(\"i, ikl->ikl\", 1.0 / gs.sqrt(norms), basis)\n", "\n", " def covariant_riemann_tensor(self, base_point):\n", " r\"\"\"Compute purely covariant version of Riemannian tensor at base_point.\n", "\n", " In the literature the covariant riemannian tensor is noted :math:`R_{ijkl}`.\n", "\n", " Convention used in the literature (tensor index notation, ref. Wikipedia) is:\n", " :math:`R_{ijkl} = `\n", " where :math:`x_i` is the i-th basis vector of the tangent space at base point.\n", "\n", " In other words:\n", " [cov_riemann_tensor]_{ijkl} = [metric_matrix]_{im} [riemann_tensor]_{jkl}^m\n", "\n", " Parameters\n", " ----------\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold.\n", "\n", " Returns\n", " -------\n", " covariant_tensor : array-like, shape=[..., dim, dim, dim, dim]\n", " covariant_riemann_tensor[..., i, j, k, l] = R_{ijkl}\n", " Covariant version of Riemannian curvature tensor.\n", " \"\"\"\n", " riemann_tensor = self.riemann_tensor(base_point)\n", " metric = self.metric_matrix(base_point)\n", " return gs.einsum(\"...ij, ...klmj->...iklm\", metric, riemann_tensor)\n", "\n", " def sectional_curvature(self, tangent_vec_a, tangent_vec_b, base_point=None):\n", " r\"\"\"Compute the sectional curvature.\n", "\n", " In the literature sectional curvature is noted K.\n", "\n", " For two orthonormal tangent vectors :math:`x,y` at a base point,\n", " the sectional curvature is defined by :math:`K(x,y) = `.\n", "\n", " For non-orthonormal vectors, it is\n", " :math:`K(x,y) = / ( - ^2)`.\n", "\n", " sectional_curvature(X, Y, P) = K(X,Y) where X, Y are tangent vectors\n", " at base point P.\n", "\n", " The information manifold of multinomial distributions has constant\n", " sectional curvature given by :math:`K = 2 \\sqrt{n}`.\n", "\n", " Parameters\n", " ----------\n", " tangent_vec_a : array-like, shape=[..., dim]\n", " Tangent vector at `base_point`.\n", " tangent_vec_b : array-like, shape=[..., dim]\n", " Tangent vector at `base_point`.\n", " base_point : array-like, shape=[..., dim]\n", " Point in the manifold.\n", "\n", " Returns\n", " -------\n", " sectional_curvature : array-like, shape=[...,]\n", " Sectional curvature at `base_point`.\n", " \"\"\"\n", " curvature = self.curvature(\n", " tangent_vec_a, tangent_vec_b, tangent_vec_b, base_point\n", " )\n", " sectional = self.inner_product(curvature, tangent_vec_a, base_point)\n", " norm_a = self.squared_norm(tangent_vec_a, base_point)\n", " norm_b = self.squared_norm(tangent_vec_b, base_point)\n", " inner_ab = self.inner_product(tangent_vec_a, tangent_vec_b, base_point)\n", " normalization_factor = norm_a * norm_b - inner_ab**2\n", " return gs.divide(sectional, normalization_factor, ignore_div_zero=True)\n", "\n", " def scalar_curvature(self, base_point):\n", " r\"\"\"Compute scalar curvature at base_point.\n", "\n", " In the literature scalar_curvature is noted S and writes:\n", " :math:`S = g^{ij} Ric_{ij}`,\n", " with Einstein notation, where we recognize the trace of the Ricci\n", " tensor according to the Riemannian metric :math:`g`.\n", "\n", " Parameters\n", " ----------\n", " base_point : array-like, shape=[..., dim]\n", " Point on the manifold.\n", "\n", " Returns\n", " -------\n", " curvature : array-like, shape=[...,]\n", " Scalar curvature.\n", " \"\"\"\n", " ricci_tensor = self.ricci_tensor(base_point)\n", " cometric_matrix = self.cometric_matrix(base_point)\n", " return gs.einsum(\"...ij, ...ij -> ...\", cometric_matrix, ricci_tensor)\n" ] } ], "source": [ "from geomstats.geometry.riemannian_metric import RiemannianMetric\n", "\n", "for line in inspect.getsourcelines(RiemannianMetric)[0]:\n", " line = line.replace(\"\\n\", \"\")\n", " print(line)" ] }, { "cell_type": "markdown", "id": "50d697d2", "metadata": {}, "source": [ "# 8. Conclusion\n", "\n", "Key take-aways from this notebook:\n", "1. The connection tells us how much one vector in $T_pM$ changes when you move it infinitesimally in the direction of another vector in $T_pM$.\n", "2. The connection defines what it means for a vector to change, so it also allows us to define what it means for a vector to $\\textbf{not}$ change. This allows us to define the notion of parallel vector fields and parallel transport.\n", "3. A parallel vector field $X$ along a curve $\\gamma$ satisfies $$\\nabla_{\\dot{\\gamma}(t)} X(t)=0$$ which means that each point along $\\gamma$, the vector $x \\in X$ will not change if it is moved infinitesimally in the direction of the curve's tangent vector $\\dot{\\gamma(t)}$.\n", "4. The parallel transport tells you what a vector would look like if you transported it non-infinitesimally along a curve.\n", "5. Equipping a manifold with a Riemannian metric is the only way to define a notion of ''distance\", ''length\" or any other sort of measurement on manifolds." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" } }, "nbformat": 4, "nbformat_minor": 5 }