We present OGRePy the official Python port of the popular Mathematica tensor calculus package OGRe ObjectOriented General Relativity  a powerful yet userfriendly tool for advanced tensor calculations in mathematics and physics especially suitable for general relativity. The Python port uses the same robust and performanceoriented algorithms as the original package and retains its core design principles. However its truly objectoriented interface enabled by Python is more intuitive and flexible than the original Mathematica implementation. It utilizes SymPy for symbolic computations and Jupyter as a notebook interface. OGRePy allows calculating arbitrary tensor formulas using any combination of addition multiplication by scalar trace contraction partial derivative covariant derivative and permutation of indices. Transformations of the tensor components between different index configurations andor coordinate systems are performed seamlessly behind the scenes as needed eliminating user error due to combining incompatible representations and guaranteeing consistent results. In addition the package provides facilities for easily calculating various curvature tensors and geodesic equations in multiple representations. This paper presents the main features of the package in great detail including many examples of its use in the context of general relativity research.
['General Relativity and Quantum Cosmology', 'Computer Science - Mathematical Software', 'Computer Science - Symbolic Computation', 'Mathematics - Differential Geometry', 'G.4', 'I.1', 'J.2']
OGRePy An ObjectOriented General Relativity Package for Python
{'Barak Shoshany': 'bshoshany@brocku.ca | ORCID 0000-0003-2222-127X | https://baraksh.com/  \nDepartment of Physics, Brock University  \n1812 Sir Isaac Brock Way, St. Catharines, Ontario, L2S 3A1, Canada  \nSeptember 4, 2024', 'Abstract': 'We present OGRePy, the official Python port of the popular Mathematica tensor calculus package OGRe (Object-Oriented General Relativity) - a powerful, yet userfriendly,   tool   for   advanced   tensor   calculations   in   mathematics   and   physics, especially suitable for general relativity. The Python port uses the same robust and performance-oriented algorithms as the original package, and retains its core design principles. However, its truly object-oriented interface, enabled by Python, is more intuitive and flexible than the original Mathematica implementation. It utilizes SymPy for symbolic computations and Jupyter as a notebook interface. OGRePy allows calculating arbitrary tensor formulas using any combination of addition, multiplication by scalar, trace, contraction, partial derivative, covariant derivative, and permutation of indices. Transformations of the tensor components between different index configurations and/or coordinate systems are performed seamlessly behind the scenes as needed, eliminating user error due to combining incompatible representations, and guaranteeing consistent results. In addition, the package provides facilities for easily calculating various curvature tensors and geodesic equations in multiple representations. This paper presents the main features of the package in great detail, including many examples of its use in the context of general relativity research.', 'Summary': 'OGRePy is a modern Python package for differential geometry and tensor calculus, designed to be both powerful and user-friendly. It can be used in a variety of contexts where tensor calculations are needed, in both mathematics and physics, but it is especially suitable for general relativity.  \nTensors are abstract objects, which can be represented as multi-dimensional arrays once a choice of index configuration and coordinate system is made. OGRePy stays true to this definition, but  \ntakes away the complexities that come with combining tensors in different representations. This is done using an object-oriented programming approach, taking advantage of principles such as encapsulation and class invariants to eliminate the possibility of user error.  \nThe user initially defines each tensor in OGRePy using its explicit components in any single representation. Operations on this tensor are then done abstractly, without needing to specify which representation to use. Possible operations include addition of tensors, multiplication of tensor by scalar, trace, contraction, and partial and covariant derivatives.  \nOGRePy will automatically choose which representation to use for each tensor based on how the tensors are combined. For example, if two tensors are added, then OGRePy will automatically use the same index configuration (upper and lower indices) for both. Similarly, if two tensors are contracted, then OGRePy will automatically ensure that the contracted indices are one upper (contravariant) and one lower (covariant). OGRePy will also automatically transform all tensors being operated on to the same coordinate system.  \nTransformations between representations are done behind the scenes; all the user has to do is specify which metric to use for raising and lowering indices, and how to transform between the coordinate systems being used. This information only needs to be given once and for all when first defining the tensors and coordinate systems, and will be used automatically from that point on.  \nThis also means that there is no room for user error. The user cannot mistakenly perform "illegal" operations such as . Instead, the user simply inputs the names of the tensors, the order (but not the configuration) of indices for each, and the operations to perform - and the correct combination will be automatically deduced. 2 A μν + B μλ C λν 2 A μν + B μ λ C λν  \nOGRePy is a Python port of the popular Mathematica package OGRe [1], first released in February 2021, used by many general relativity researchers worldwide. The Python port uses the same robust and performance-oriented algorithms, and retains the package\'s core design principles. It was made to be as flexible and powerful as possible, while also being simple to learn and easy to use, and suitable for both experienced and novice researchers. OGRePy uses SymPy [2] to facilitate symbolic computations and Jupyter [3][4] as a notebook interface.  \nThe  Python   port   was   specifically   designed   to   mimic   as   much   of   the   original   Mathematica package\'s syntax as possible, while also greatly improving on that syntax in many ways due to the fact that Python, unlike Mathematica, is a truly object-oriented language. The documentation for both packages was also kept as similar in structure and scope as possible, with the same practical examples. This means that anyone who is familiar with the Mathematica version should easily be able to use the Python version, and vice versa.', 'Features': '- · Define coordinate systems and the transformation rules between them. The Jacobians are automatically calculated. Tensor components are then transformed automatically between coordinates behind the scenes as needed.\n- · Each tensor is associated with a specific metric. Tensor components are then transformed automatically between different index configurations, raising and lowering indices behind the scenes as needed.\n- · Display any tensor in any index configuration and coordinate system, either in vector/matrix form or as a list of all unique non-zero elements. Metrics can also be displayed as a line element.\n- · Automatically   simplify   tensor   components,   optionally   with   a   user-defined   simplification function.\n- · Easily calculate arbitrary tensor formulas using any combination of addition, multiplication by scalar, trace, contraction, partial derivative, covariant derivative, and permutation of indices.\n- · Built-in methods for calculating the Christoffel symbols (Levi-Civita connection), Riemann tensor, Ricci tensor and scalar, Einstein tensor, Kretschmann scalar, curve Lagrangian, and volume element from a metric.\n- · Calculate the geodesic equations in terms of an affine curve parameter, in two different ways: from the Christoffel   symbols   or   from   the   curve   Lagrangian.   For   spacetime   metrics,   the geodesic equations can be calculated in terms of the time coordinate.\n- · Easily keep track of all tensors created in a notebook session, including the relations between them - for example, see which metrics were created and which tensors are associated with each metric.\n- · Export tensor components in TeX or Mathematica format.\n- · Designed with speed and performance in mind, using optimized algorithms developed specifically for this package.\n- · Clear and detailed documentation, with many examples, in both Markdown and Jupyter notebook format.\n- · Open source. The code is extensively documented; please feel free to fork and modify it as you see fit.\n- · Under continuous and active development. Bug reports and feature requests are welcome, and should be made via GitHub issues.', 'The object-oriented design philosophy': "Object-oriented programming refers to a paradigm where a program's code is organized around objects. An object belongs to a user-defined type, called a class . The class defines the data that the object stores, as well as methods or member functions that read or manipulate that data. One of the fundamental principles of object-oriented programming is encapsulation ,   which means that the user may only access an object's data using the methods defined by the class, and is unable to access the object's data directly.  \nImportantly,   encapsulation   allows   for   the   preservation   of class   invariants .   An   invariant   is   a condition of validity that can always be assumed to be satisfied by the data stored in each object. If the methods make sure to preserve the invariant whenever they store or manipulate the data, and the user is prevented from changing the data manually and thus potentially violating the invariant, then the implementation of the class can be greatly simplified, and performance can be  \nimproved, because the class will not need to verify that the data is valid every time it performs an operation.  \nThe main idea behind OGRePy is to simplify the use of tensors by encoding all the information about a tensor in a single, self-contained object. As I mentioned above, a tensor is an abstract object. One can find components which represent this abstract entity in a particular coordinate system and index configuration, but the tensor is not its components. In OGRePy, a tensor object is initially defined (or constructed ) by providing the components of the tensor in a particular representation - but once this is done, the user does not need to worry about coordinates or indices anymore, or even remember which coordinates and indices were initially used. The abstract tensor object will automatically transform the initial data to a different coordinate system or index configuration as needed, based on the context in which it was used.  \nAs a tensor object holds the components of the same tensor in many different representations, the most important class invariant is the assumption that the different components indeed represent the same tensor. This is achieved using encapsulation; the object's data can only be modified by private   methods   that   preserve   the   invariant,   and   thus   the   user   cannot   accidentally   cause   a violation of the invariant by assigning components to one representation that are not related to the   components   of   all   other   representations   by   the   appropriate   coordinate   and/or   index transformation.  \nSince   Mathematica   is   not   an   object-oriented   language,   the   original   OGRe   package   merely simulated classes and objects using associative arrays, resulting in a somewhat awkward syntax. Python, on the other hand, is an inherently object-oriented language, and the Python package takes full advantage of that. Tensors are objects, and the various tensor operations are done directly   on   these   objects   using   methods   and   overloaded   operators.   Class   invariants   and encapsulation   guarantee   that   the   different   representations   of   the   tensor   objects   are   always consistent,   and   the   correct   representation   is   chosen   on   demand   for   each   calculation   using intelligent algorithms.", 'Global installation': 'To install OGRePy from PyPI using pip , simply run the following command in the terminal:  \npip install OGRePy  \nThe current version of OGRePy officially supports only Python v3.12 and above . It may also work with older versions of Python 3, but this is not guaranteed, as development and testing was only done with the indicated Python version. If your global Python installation is an older version, and you cannot upgrade it, consider using pyenv or pyenv-win to install multiple Python versions in parallel, or use a portable local installation to run OGRePy.  \nInstalling OGRePy using pip will also automatically install its dependent packages, ipykernel and sympy, if they are not already installed. The current version of OGRePy officially supports only ipykernel v6.29 and above and sympy v1.13 and above , so if you are still using older versions, you should upgrade these packages using the command pip install --upgrade ipykernel sympy .', 'Installing in a virtual environment': 'Advanced users may wish to install OGRePy inside a Python virtual environment in order to avoid potential dependency conflicts with other packages. To do this, first open the directory where you would like to store your new virtual environment in the terminal, and run:  \n- · python -m venv .OGRePy-env --upgrade-deps on Windows,\n- · python3 -m venv .OGRePy-env --upgrade-deps on WSL/Linux/macOS.  \nThis will create a virtual environment under the .OGRePy-env subdirectory. The --upgradedeps flag automatically upgrades pip to the latest version. To activate the virtual environment, run:  \n- · .OGRePy-env\\Scripts\\activate.bat on Windows (Command Prompt),\n- · & .OGRePy-env\\Scripts\\Activate.ps1 on Windows (PowerShell),\n- · source .OGRePy-env/bin/activate on WSL/Linux/macOS.  \nIf this worked correctly, you will see the text (.OGRePy-env) at the beginning of the terminal prompt. Now you can install OGRePy using pip as above. To deactivate the virtual environment, simply run the command deactivate in the terminal.', 'Creating a Jupyter notebook': 'OGRePy is designed to run within a Jupyter notebook. It is also possible to run it from within a Python script, usually for automation purposes, but Jupyter is required for interactivity and for displaying tensors and their components as rendered TeX equations.  \nOGRePy supports two Jupyter notebook interfaces:  \n- · Visual Studio Code: This is the officially recommended way to use OGRePy, due to helpful features such as IntelliSense, tooltips, and type checking. Download and install from the official website. Run VS Code, then create a new file with the .ipynb extension and open it, or press F1 to open the Command Pallette and choose the option "Create: New Jupyter Notebook". This will prompt you to automatically install the required VS Code extensions and Python packages if they are not already installed.\n- · JupyterLab: Install with pip install jupyterlab . Run by executing jupyter-lab in the terminal, and then create a new notebook in the web browser. Please note that JupyterLab is not officially supported, as development and testing was only done with VS Code, although I have verified that the package does work in JupyterLab.  \nIf you are running OGRePy in a virtual environment:  \n- · With Visual Studio Code, open the folder where you create the virtual environment, press F1 to open the Command Pallette, choose the option "Python: Select Interpreter", and select the .OGRePy-env environment.   The   interpreter   can   also   be   selected   for   individual   Jupyter notebooks in VS Code using the "Select Kernel" button at the top right of the notebook.\n- · With JupyterLab, first activate the virtual environment in the terminal as explained above, and then run jupyter-lab from the same terminal.', 'Importing the package': 'To load OGRePy, type the following code in a Jupyter notebook cell and execute it using Shift+Enter:  \n```\nimport OGRePy as T In [ ]:\n```  \nOGRePy: An Object-Oriented General Relativity Package for Python  \nBy Barak Shoshany (baraksh@gmail.com) (baraksh.com) v1.0.1 (2024-09-04) GitHub repository: https://github.com/bshoshany/OGRePy  \nAll of OGRePy\'s functions are now accessible via the T namespace. While it is not common practice in Python to import packages as single letters, OGRePy uses this convention because in the original Mathematica version of OGRe, all module names started with a capital T (which stands for "Tensor"). However, you can change that to another namespace if you prefer, for example import OGRePy as gr .  \nIf   desired,   the   welcome   message can be disabled by defining OGREPY\\_DISABLE\\_WELCOME = True in the notebook before importing the package. If you changed your mind later and you want to see the welcome message (for example, if you want a link to the GitHub repository), use the welcome() function:  \n```\nT . welcome() In [ ]:\n```  \nOGRePy: An Object-Oriented General Relativity Package for Python By Barak Shoshany (baraksh@gmail.com) (baraksh.com) v1.0.1 (2024-09-04) GitHub repository: https://github.com/bshoshany/OGRePy', 'Getting help': 'One of the reasons I recommend Visual Studio Code as the preferred notebook interface for this package   is   the   IntelliSense   feature,   which   displays   a   helpful   popup   with   suggestions   and information about various language components. To test this feature, once OGRePy is loaded in the notebook, create a new code cell and start typing T. - once you write the dot character, you  \nwill see a popup menu listing all the functions contained in the T namespace.  \nBrowse the menu using the arrow keys. There will be an additional popup next to this menu with the documentation for each function. If you do not see the documentation, press Ctrl+Space. You can  also   start   typing   to   filter   the   options   in   the   menu.   For   example,   if   you   type w ,   the welcome() function will be selected, and you will see the documentation for that function. In the same way, you can view the documentation and usage instructions for all OGRePy functions.  \nPress Tab to complete the code and write down the full function welcome() . Once the code is written, the popup will disappear, but it will reappear again after you write ( to   display the parameters that should go into the parentheses. You can also hover with the mouse over any function to read its documentation.  \nIf you are using JupyterLab instead of VS Code, the popups will not be displayed automatically by default, but you can press Ctrl+, to go to the settings, then click on "Code Completion" and check "Show the documentation panel" and "Enable autocompletion". (However, note that the documentation will not be formatted as nicely on JupyterLab.)  \nYou can also view the documentation for a particular OGRePy function using the function doc() . For example:  \nT . doc(T . welcome) welcome() -> None Print the welcome message. doc() itself also has documentation: T . doc(T . doc) doc(obj: Callable[..., Any] | type) -> None Print the documentation for an object as a Markdown-formatted notebook cell. If the object is a class, print the documentation for its constructor. Parameters: · obj : The object to print the documentation for. Exceptions: · OGRePyError : If no documentation exists. In [ ]: In [ ]:  \nIn [ ]:', 'Defining coordinates': 'To define tensors, we first need to define the manifold on which they reside. Since we are focusing on general relativity, we will use 4-dimensional spacetime manifolds in the following examples, but this package works equally well with manifolds that are purely spatial and/or have a different number of dimensions.  \nThe first step is to define the coordinate system. We can represent a coordinate system as a vector (or a tensor of rank 1) defining a point in space(time). In OGRePy, coordinates are represented as objects of the class Coordinates . Therefore, defining a coordinate system is a simple matter of constructing a new Coordinates object. The constructor for this class is defined as follows: x μ  \nT  \n.  \ndoc(T  \n.  \nCoordinates)  \nCoordinates(*components: s.Symbol | str) -> None  \nConstruct a new coordinate object.', 'Parameters:': '- · components :   One   or   more   strings   or   SymPy Symbol objects   specifying   the coordinates.   Strings   should   be   in   the   same   format   as   the   argument   to   SymPy\'s symbols() , e.g. "t x y z" , and it is possible to enter just one string for all the coordinates.  \nFor example, let us create an object for the Cartesian spacetime coordinates . First we will need some SymPy Symbol objects to represent the individual coordinates  , , ,   and . Conveniently, OGRePy contains a module, OGRePy.abc ,   which contains SymPy symbols for all English and Greek letters, both lowercase and uppercase. Note that the Greek letter lambda (lowercase , uppercase ) is accessed via the symbols lamda and Lamda respectively, since lambda is a reserved keyword in Python. ( t , x , y , z ) t x y z λ Λ  \nFor users familiar with SymPy: OGRePy.abc is similar to sympy.abc , except that OGRePy.abc explicitly assumes that all symbols are real, and also contains uppercase Greek letters. If complex symbols   are   desired,   they   should   be   imported   from sympy.abc or   created   directly   via sympy.Symbol or sympy.symbols() instead.  \nWe import the symbols as follows:  \n```\nfrom OGRePy.abc import t, x, y, z\n```  \nNow we have direct access to the symbols t , x , y , and z in our notebook. Let us use them to  \nconstruct our Cartesian coordinate system:  \n```\nCartesian = T . In [ ]:\n```  \n```\nCoordinates(t, x, y, z)\n```  \nHere is a breakdown of the code:  \n- · Cartesian is the name of the new object we are creating.\n- · T is the namespace we chose for OGRePy when we imported it via import OGRePy as T .\n- · Coordinates is   the   name   of   the   class   we   want   to   construct   an   instance   of.   This   class represents a coordinate system in OGRePy.\n- · Coordinates() is the constructor , that is, the function that creates a new Coordinates object representing a particular coordinate system.\n- · We can pass any number of arguments to the constructor. Usually these will be SymPy symbols representing the coordinates (but it is also possible to pass strings, which will be converted to symbols automatically).\n- · t , x , y , and z are the symbols we exported above.  \nWe can similarly define the spherical spacetime coordinates : ( t , r , θ , ϕ )  \n```\nfrom OGRePy.abc import phi, theta r = T . sym("r", nonnegative =True ) Spherical = T . Coordinates(t, r, theta, phi) In [ ]:\n```  \nNote that Greek letters are imported using the full name of the letter: theta stands for . Similarly, Theta will be the uppercase . One thing you should be aware of is that the letters and are imported as lamda and Lamda respectively, because lambda (with a b )   is   a reserved keyword in Python. θ Θ λ Λ  \nAnother thing to note here is that we defined the   coordinate manually as a SymPy Symbol object using OGRePy\'s sym() function instead of importing it from OGRePy.abc . The reason for defining   separately this way is that we get more control over the properties of this coordinate. As mentioned above, any symbol imported from OGRePy.abc is automatically assumed to be real. However, for  , we also want to indicate that it is a non-negative symbol. This signals to SymPy to treat   as non-negative when doing calculations or performing simplifications. r r r r  \nTo illustrate this point, consider that  , defined above using from OGRePy.abc import t , is a real coordinate that can be positive, negative, or zero. Therefore, when we try to simplify , we get the absolute value of  : t √ t 2 t  \n```\nT . s . simplify(T . s . sqrt(t ** 2)) In [ ]: Out[ ]: | t |\n```  \nOn the other hand, when we do the same to  , which is designated as non-negative, we simply get back, without an absolute value: r r  \n```\nT . s . simplify(T . s . sqrt(r ** 2)) In [ ]: Out[ ]: r\n```  \nIn these examples, note that SymPy is automatically imported into the OGRePy namespace as s , which means we can access the entire SymPy namespace as T.s .   This   is   done   purely   for convenience, so you don\'t have to import SymPy to the notebook separately. However, you could also import sympy directly if you prefer. Because SymPy is available as T.s , we could access the SymPy simplify() function directly via T.s.simplify() .  \nOGRePy offers two functions that can be used to create your own symbols: sym() , which is the preferred   alternative   to   calling   SymPy\'s Symbol() constructor,   and syms() ,   which   is   the preferred alternative to calling SymPy\'s symbols() function.   The   main   differences   between OGRePy\'s sym() and syms() and SymPy\'s Symbol() and symbols() are:  \n- 1. OGRePy\'s functions always add the assumption that the symbols are real, which helps with simplification.\n- 2. OGRePy\'s functions always convert strings to TeX codes. This is important, because in SymPy, Symbol("mu") != Symbol(r"\\mu") , even though they are both displayed using the same symbol. On the other hand, in OGRePy, sym("mu") == sym(r"\\mu") , which prevent errors.', 'Error checking': 'OGRePy contains   robust   error   checking.   If   you   call   the   constructor   with   invalid   input,   the construction will fail and you will get an error message telling you what to fix. For example, if you try typing T.Coordinates(42) you will get the following friendly error message:  \n- The components must be either a SymPy Array object or a list. The object 42 is of type int .  \nIf you are an advanced user who prefers to see the full traceback and/or catch the exceptions and handle them on your own, you can set T.options.friendly\\_errors = False to turn off the friendly error messages and raise exceptions instead. Set it back to True to re-enable the friendly error messages.', 'Defining metrics': 'To finish defining a (Riemannian or pseudo-Riemannian) manifold, we need to define its metric tensor. Like any other tensor in OGRePy, the metric tensor is an abstract tensor that has multiple representations.   We   "jump   start"   the   tensor   by   providing   its   components   in   one   particular representation, and all the other representations will be calculated automatically.  \nIn the case of a metric tensor, the defining representation must always be the one with two indices down: . However, it can be given in any coordinate system. In OGRePy, metrics are represented as objects of the class Metric .   Therefore, as with coordinates, defining a metric is a simple matter of constructing a new Metric object. The constructor for this class is defined as follows: g μν  \n```\nT . doc(T . In [ ]:\n```  \n- Metric) Metric(*, coords: Coordinates, components: list[Any] | s.NDimArray | s.Matrix, symbol: str | s.Symbol = g) -> None Construct a new metric object. Parameters: · coords : An OGRePy Coordinates object specifying the coordinate system of the representation of the initialization components. Will also be designated the default coordinate system of the metric. · components :   The components with which to initialize the metric. Can be a list, a SymPy Array object, or a SymPy Matrix object. · symbol (optional): A string or a SymPy Symbol object designating the symbol to be used  when   displaying   the   metric.   The   string   can   include   any   TeX   symbols,   e.g. r"     T " (note the r in front of the string, indicating that the \\ in the string is not an escape character). Exceptions: · OGRePyError : If the metric components are not an invertible symmetric matrix.  \nLet us create a tensor object for the Minkowski metric , specifying the components in Cartesian coordinates:  \n```\nMinkowski = T . Metric( coords = Cartesian, components = T . diag( -1, 1, 1, 1), symbol = "eta", ) In [ ]:\n```  \nTo define the components we used the OGRePy diag() function, which generates a diagonal matrix (a SymPy Matrix object) with the given components on the diagonal. OGRePy\'s diag() is a convenient shorthand for SymPy\'s Matrix.diag() .  \nFor the symbol, we used the string "eta" ,   which   will   be   displayed   as   the   Greek   letter . Alternatively, we could have used any TeX string, such as r"\\eta" . (Note the r in front of the string, indicating that it is a "raw" string literal, so the \\ in the string is treated as an actual \\ and not an escape character.) Internally, the string "eta" is actually converted to r"\\eta" . The η  \nsymbol argument also accepts SymPy Symbol objects, in which case it extracts the TeX code from the object, so we could have also used from OGRePy.abc import eta and then entered eta as the symbol, but that is more cumbersome.  \nSimilarly, let us define the Schwarzschild metric , this time specifying the components in spherical coordinates:  \n```\nfrom OGRePy.abc import M Schwarzschild = T . Metric( coords = Spherical, components = T . diag( -(1 -2 * M / r), 1 / (1 -2 * M / r), r ** 2, r ** 2 * T . s . sin(theta) ** 2, ), ) In [ ]:\n```  \nHere we imported the symbol M to use as the mass. Be careful not to write something like 2M instead of 2 * M . While 2M makes sense mathematically, it is not a legal Python expression. Note that we did not specify a symbol, so the symbol   will be used by default. g', 'Displaying tensors': 'In OGRePy, the term tensor object refers to any object of the Tensor class or its derived classes, which include Metric (but not Coordinates , which is not a tensor, just a list of symbols) Every tensor   object   in   OGRePy   has   a   method   called show() ,   which   shows   the   symbol,   indices, coordinates, and components in those indices and coordinates, in vector or matrix form when applicable. Let us try it for the two metrics we created:  \n```\nMinkowski . show() In [ ]:\n```  \n```\nSchwarzschild . show() η μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ -1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 ⎞ ⎟ ⎟ ⎟ ⎠ In [ ]: g μν ∣ ∣ ∣ ( t , r , θ , ϕ ) = ⎛ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎝ -1 0 0 0 0 0 0 0 0 r 2 0 0 0 0 r 2 sin 2 ( θ ) ⎞ ⎟ ⎟ ⎟ ⎟ ⎟ ⎟ ⎠ 2 M r 1 -+1 2 M r\n```  \nIn fact, calling the show() method explicitly is not necessary. If the output of a notebook cell is a tensor object, the output of the show() method will be displayed automatically:  \nMinkowski In [ ]: Out[ ]:  \nη μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ -1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 ⎞ ⎟ ⎟ ⎟ ⎠  \nA coordinate system is not a tensor, but it does have a show() method as well, and it is also executed automatically if it\'s the output of a notebook cell:  \nCartesian . show() In [ ]:  \n( t x y z )  \nSpherical In [ ]:  \nOut[ ]:  \n( t r θ ϕ )  \nThe other method available for displaying the contents of tensors is list() , which lists all of the unique (up to sign), non-zero components of the tensor. It is usually the best option for higherrank tensors, which cannot be displayed in vector or matrix form, such as the Christoffel symbols or Riemann tensor (see below). For example, let us list the components of the Minkowski metric:  \nMinkowski . list() In [ ]:  \nη tt = -η xx = -η yy = -η zz = -1  \nThere is a convenient shortcut for calling list() : simply use the ~ (invert) operator in front of the tensor. For example:  \n~ Schwarzschild In [ ]:  \ng tt = -2 M  \ng  \n1 g rr = g θθ = r 2 ϕϕ = r 2 sin 2 ( θ ) r 1 -+1 2 M r  \nIn [ ]:  \nIn [ ]:  \ncomponents in this manner.  \nIf, as in the examples above, no additional arguments are given to show() and list() ,   they display the tensors in their default indices and default coordinates, which are the ones first used to define the tensor (unless you change them later). So, for example, the default indices of the Minkowski metric are two lower indices, and its default coordinates are Cartesian. We will show later how to change these defaults, and how to display any tensor in any index configuration and coordinate system. Note that if a tensor object is displayed automatically as the output of a cell, or using   the ~ shortcut   for list() ,   it   will   always   be   displayed   in   its   default   indices   and coordinates.  \nA good practice when using OGRePy is to set up the notebook so that the result of the last assignment in the cell is automatically printed out. This will save us the trouble of writing an extra line every time we want to print out tensors we assign to variables. This is achieved by executing the following command:  \n```\nfrom IPython.core.interactiveshell import InteractiveShell\n```  \nInteractiveShell . ast\\_node\\_interactivity =  \n```\n"last\\_expr\\_or\\_assign"\n```', 'Changing the output style': 'The options object of the OGRePy package is used to set various options, which will then be respected by all functions and classes in the package. We already saw above that we can use it to turn off the friendly error message by setting T.options.friendly\\_errors = False .  \nTo control the style of the output, you can change the property T.options.css\\_style to any string of your choice. The default is just an empty string, but we can change this to any CSS style we want. For example:  \nT  \n.  \noptions  \n.  \ncss\\_style  \n=  \n"background-color: #000; color: #fff; font-size: 20px; padding: 5px"  \n~  \nSchwarzschild  \nTo reset the style to the default value, we simply "delete" the property using del :  \n<!-- image -->  \n```\ndel T . options . css\\_style Now the style is back to normal: ~ Schwarzschild In [ ]: In [ ]:\n```  \nThis is common to all properties of options ; the del operator does not delete the property, it simply resets it to the default value. Line and volume elements In   the   case   of   metrics,   we   can   also   display   them   as   a   line   element   using   the   method g tt = -1 g rr = g θθ = r 2 g ϕϕ = r 2 sin 2 ( θ ) 2 M r 1 -+1 2 M r  \nline\\_element() . For example, here are the line elements for our two metrics:  \n```\nMinkowski . line\\_element() Schwarzschild . line\\_element() In [ ]: Out[ ]: -d t 2 +d x 2 +d y 2 +d z 2 In [ ]: Out[ ]: d ϕ 2 r 2 sin 2 ( θ ) + d θ 2 r 2 + +d t 2 ( -1 ) d r 2 -+1 2 M 2 M r\n```  \n```\nNote that these are standard SymPy expressions, so they can be manipulated like any other expressions, including operations such as simplifying or factoring. As an example of a more r\n```  \ninteresting (non-diagonal) line element, consider the Alcubierre warp drive metric :  \n```\nv\\_t = T . func("v")(t) f\\_t\\_x\\_y\\_z = T . func("f")(t, x, y, z) Alcubierre = T . Metric( coords = Cartesian, components = [ [ -1 + f\\_t\\_x\\_y\\_z ** 2 * v\\_t ** 2, 0, 0, -f\\_t\\_x\\_y\\_z * v\\_t], [0, 1, 0, 0], [0, 0, 1, 0], [ -f\\_t\\_x\\_y\\_z * v\\_t, 0, 0, 1], ], )\n```  \n```\nIn [ ]:\n```  \ng μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ f 2 v 2 -1 0 0 -fv 0 1 0 0 0 0 1 0 -fv 0 0 1 ⎞ ⎟ ⎟ ⎟ ⎠  \nHere we used OGRePy\'s func() function, which is a wrapper around SymPy\'s Function class which also defines the function to be real. Note that the metric was automatically printed in matrix form, since we configured the notebook to print out the result of the last assignment. Here is a list of its non-zero components:  \n```\n~ Alcubierre In [ ]:\n```  \ng tt = f 2 v 2 -1 g tz = g zt = -fv g xx = g yy = g zz = 1  \nis a form function which is equal to 1 inside a "warp bubble" of finite radius and 0 outside it, and is the velocity of the bubble, which can be faster than the speed of light ( ). Note that for and   we used a new type of object: a SymPy Function object. This represents a function of the elements given as the arguments to the constructor, so   is a function of   while   is a function of all of the coordinates. f v v > 1 v f v t f  \nIt is easy to see that the metric is flat where , that is, outside the bubble. Its line element is: f = 0  \nAlcubierre . line\\_element() In [ ]:  \nOut[ ]:  \nd  \nt  \n2  \n(  \nf  \n2  \n(  \nt  \n,  \nx  \n,  \ny  \n,  \nz  \n)  \nv  \n2  \n(  \nt  \n)  \n-  \n1  \n)  \n-  \n2d  \nt  \nd  \nzf  \n(  \nt  \n,  \nx  \n,  \ny  \n,  \nz  \n)  \nv  \n(  \nt  \n) + d  \nx  \n2  \n+d  \ny  \n2  \n+d  \nWe can simplify it as follows. First, we expand the parentheses:  \nAlcubierre . line\\_element() . expand() In [ ]:  \nOut[ ]: d t 2 f 2 ( t , x , y , z ) v 2 ( t ) -d t 2 -2d t d zf ( t , x , y , z ) v ( t ) + d x 2 +d y 2 +d z 2  \nUsing the args method, we can split this expansion into individual terms (we put the result inside a SymPy Array so the terms will be properly displayed as SymPy expressions in the notebook):  \nargs = Alcubierre . line\\_element() . expand() . args T . s . Array(args) In [ ]:  \nOut[ ]: [ d x 2 d y 2 d z 2 -d t 2 d t 2 f 2 ( t , x , y , z ) v 2 ( t ) -2d t d zf ( t , x , y , z ) v ( t ) ]  \nNow we can factorize the third, fifth, and sixth terms together, then add the rest: (recall that indices start from zero!)  \nz  \n2  \nargs[0] + args[1] + args[3] + T . s . factor(args[2] + args[4] + args[5]) In this form, it is immediately clear that the metric is flat outside the warp bubble (where is ), and inside the warp bubble (when   is  ) it is a flat metric translated by an amount in the direction. Another thing we can do with a metric is calculate its volume elements squared, which is simply the determinant of the metric, using the method volume\\_element\\_squared() . For example: Minkowski . volume\\_element\\_squared() Schwarzschild . volume\\_element\\_squared() Alcubierre . volume\\_element\\_squared() As with the line elements, these are SymPy expressions, so they can be modified just like any other expression. Therefore, to calculate the volume element itself, we can just take the square root (adding a minus sign if the metric is Lorentzian): T . s . simplify(T . s . sqrt( -Schwarzschild . volume\\_element\\_squared())) In [ ]: Out[ ]: -d t 2 +d x 2 +d y 2 +(d tf ( t , x , y , z ) v ( t ) -d z ) 2 f 0 f 1 v ( t ) d t z In [ ]: Out[ ]: -1 In [ ]: Out[ ]: -r 4 sin 2 ( θ ) In [ ]: Out[ ]: -1 In [ ]: Out[ ]: r 2 |sin ( θ )|', 'Choosing index letters': 'By default, the show() method uses Greek letters for the indices, in a specific pre-determined order. The letters can be changed by setting the property T.options.index\\_letters to a list of symbols. The default letters are:  \n```\nT . options . index\\_letters In [ ]:\n```  \n```\n[\'\\\\mu\', \'\\\\nu\', \'\\\\rho\', \'\\\\sigma\', \'\\\\kappa\', \'\\\\lambda\', \'\\\\alpha\', \'\\\\beta\', \'\\\\gamma\', \'\\\\delta\', \'\\\\epsilon\', \'\\\\zeta\', \'\\\\epsilon\', \'\\\\theta\', \'\\\\iota\', \'\\\\xi\', \'\\\\pi\', \'\\\\tau\', \'\\\\phi\', \'\\\\chi\', \'\\\\psi\', \'\\\\omega\'] Out[ ]:\n```  \nAs you can see, they are given as strings containing TeX symbols. We can display these symbols more nicely in the notebook using the IPython package:  \n```\nfrom IPython.display import Math Math("," . join(T . options . index\\_letters)) In [ ]: Out[ ]: μ , ν , ρ , σ , κ , λ , α , β , γ , δ , ϵ , ζ , ϵ , θ , ι , ξ , π , τ , ϕ , χ , ψ , ω\n```  \nThis means that the letter will be used for the first index, for the second, and so on. However, sometimes we want to use different letters. T.options.index\\_letters can accept a list of TeX symbols, SymPy symbols, and/or strings in the same format as SymPy\'s symbols() function, that is, a space- or comma-separated list of one or more letters or TeX codes - or a mix and match of all of the above, as long as it\'s inside a list. Ranges of letters can be indicated using a colon, so for example, here is how to change the indices to lowercase English letters in alphabetical order: μ ν  \n```\nT . options . index\\_letters = ["a:z"] show() will now use these letters - in this particular order - when displaying tensors: Minkowski In [ ]: In [ ]: Out[ ]:\n```  \nη ab ∣ ∣ ∣ ( t , x , y , z ) = ⎜ ⎜ ⎜ 0 1 0 0 0 0 1 0  \n```\n⎛ ⎝ -1 0 0 0 0 0 0 1 ⎞ ⎟ ⎟ ⎟ ⎠\n```  \n```\nAs always with the object, to reset the property to its default value,\n```  \noptions index\\_letters we "delete" it using del :  \n```\ndel T . options . index\\_letters In [ ]:\n```  \nNote that list() always uses the coordinate symbols themselves for the indices (e.g. , , etc.), so it is not affected by T.options.index\\_letters . η tt η xx', 'Creating tensors in a given manifold': 'Any tensors other than coordinates and metrics are created as objects of the OGRePy class Tensor . The constructor for this class is defined as follows:  \n```\nT . doc(T . In [ ]:\n```  \n```\nTensor) Tensor(*,   metric:   Metric,   indices:   IndexConfiguration,   coords: Coordinates, components: list[Any] | s.NDimArray | s.Matrix, symbol: str | s.Symbol = \\\\square, simplify: bool = False) -> None Construct a new tensor object. Parameters:\n```  \n- · metric : An OGRePy Metric object specifying the metric which will be used to raise and lower indices for this tensor.\n- · indices : A tuple of integers specifying the index configuration of the representation of the initialization components. Each integer in the tuple can be either +1 for an upper index or -1 for a lower index. Will also be designated the default index configuration of the tensor.\n- · coords : An OGRePy Coordinates object specifying the coordinate system of the representation of the initialization components. Will also be designated the default coordinate system of the tensor.\n- · components :   The components with which to initialize the tensor. Can be a list, a SymPy Array object, or (for rank 2 tensors) a SymPy Matrix object.\n- · symbol (optional): A string or a SymPy Symbol object designating the symbol to be used  when   displaying   the   tensor.   The   string   can   include   any   TeX   symbols,   e.g. r"     T " (note the r in front of the string, indicating that the \\ in the string is not an escape character). If omitted, the placeholder ( r"\\square" ) will be used. □\n- · simplify (optional):   Whether   to   simplify   ( True )   or   not   simplify   ( False ,   the default) the components before storing them.  \nIn OGRePy, all tensor objects must have an associated metric - except coordinate objects, and the metric tensors themselves. This is because OGRePy automatically raises and lowers indices as  \nappropriate for various operations such as adding and contracting tensors, and it cannot do so without   knowing   which   metric   to   use.   Even   scalars,   which   have   no   indices,   should   still   be associated to a specific metric - since they can multiply other tensors, and you cannot multiply tensors from different manifolds together.  \nThe index configuration of the tensor is a tuple. The number of indices is the rank of the tensor. Each element in the tuple corresponds to one index, with +1 specifying an upper index and -1 specifying a lower index. For example, (-1, -1) corresponds to a tensor such as the metric , which has two lower indices, while (1, -1, -1, -1) corresponds to a tensor such as the Riemann tensor , which has one upper index followed by three lower indices. g μν R ρ σμν  \nThe components of the tensor can be given in several equivalent forms: a list, a SymPy Array object, or (for rank 2 tensors) a SymPy Matrix object. Usually, a list is the simplest option if we are   specifying   the   components   explicitly.   (For   advanced   users:   The   components   can,   more generally, be any SymPy NDimArray , including mutable and/or sparse arrays, but OGRePy always stores the components as an immutable dense array, no matter what form the input was originally in.)  \nThe components are the representation of the new tensor in the given index configuration and coordinate system. If a coordinate system is not specified, the default coordinate system of the associated metric will be used - but it is recommended to always specify the coordinate system explicitly, to avoid accidentally defining the tensor with the wrong components. The components will be automatically converted to different indices or coordinates later as needed, as we will demonstrate below.  \nTo create a scalar , or a tensor of rank 0 (with no indices), we must input an empty tuple () for the indices, and a list with exactly one item for the components. Note that a "bare" expression, not inside a list, will not work. For example, let us define the Kretschmann scalar in the Schwarzschild spacetime (below we will show how to calculate it directly from the metric):  \n```\nSchwarzschildKretschmann = T . Tensor( metric = Schwarzschild, coords = Spherical, indices = (), components = [(48 * M ** 2) / r ** 6], symbol = "K", ) In [ ]:\n```  \nOut[ ]:  \nK ∣ ∣ ∣ ( t , r , θ , ϕ ) = 48 M 2 r 6  \nSimilarly, we can create a vector , or a tensor of rank 1 (with one index). For example, let us create a vector for the 4-velocity of a particle moving at 3-velocity   along the direction in Minkowski space.   Since   the   4-velocity   has   an   upper   index   by   definition,   we   make   sure   to   define   the components in the representation of the tensor with an upper index by specifying the index v x  \n- configuration as (1,) : from OGRePy.abc import v FourVelocity = T . Tensor( metric = Minkowski, coords = Cartesian, indices = (1,), components = T . s . Array([1, v, 0, 0]) / T . s . sqrt(1 -v ** 2), ) There are a few important things to note here: 1. In Python, a tuple of one element must be specified with a comma, i.e. (1,) , because (1) would be interpreted as an integer. 2. We used a SymPy Array object to define the components since this allowed us to divide each component by the square root .   This   would not be possible with a normal Python list. 3. Since we did not specify a symbol for this tensor, its symbol is just a placeholder . We will give it a proper symbol below. Finally, as an example of a tensor of rank 2 (with two indices), let us define the stress-energy tensor for a perfect fluid, using its matrix representation with two upper indices by specifying the index configuration (1, 1) : from OGRePy.abc import p, rho PerfectFluid = T . Tensor( metric = Minkowski, coords = Cartesian, indices = (1, 1), components = T . diag(rho, p, p, p), symbol = "T", ) In [ ]: Out[ ]: □ μ ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎜ ⎜ ⎝ 0 0 ⎞ ⎟ ⎟ ⎟ ⎟ ⎟ ⎠ 1 √ 1 -v 2 v √ 1 -v 2 √ 1 -v 2 □ T μν In [ ]: Out[ ]: T μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ ρ 0 0 0 0 p 0 0 0 0 p 0 0 0 0 p ⎞ ⎟ ⎟ ⎟ ⎠  \nmost often derived by operating on lower-rank tensors, rather than defined manually via their components. We will see an example of such a derivation when we derive the Christoffel symbols and Riemann tensor from the metric below.', "Changing a tensor's symbol": 'If we ever want to change the symbol used to display a tensor, we can simply change the property symbol to any string, TeX code, or SymPy Symbol . For example, let us give the symbol to the four-velocity: u  \nFourVelocity . symbol = "u" In [ ]:  \nNow, when we display the tensor using show() or list() , this is the symbol that will be used:  \nFourVelocity In [ ]:  \nOut[ ]:  \nu μ ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎜ ⎜ ⎝ 0 0 ⎞ ⎟ ⎟ ⎟ ⎟ ⎟ ⎠ 1 √ 1 -v 2 v √ 1 -v 2', 'Raising and lowering indices': 'Raising and lowering indices is one of the most basic tensor operations. For example, if we have a vector represented with one upper index, , we can turn it into a covector, which is represented with one lower index, by contracting it with the metric: v ν  \nv μ = g μν v ν .  \nThis is called "lowering an index". Here and in the rest of this documentation, we will be using the Einstein summation convention ,   where the same index repeated exactly twice ,   once   as   an upper index and once as a lower index, implies summation over that index. In this case, the implied summation is over : ν ∈ 0, 1, 2, 3  \nv μ = 3 ∑ ν =0 g μν v ν = g μ 0 v 0 + g μ 1 v 1 + g μ 2 v 2 + g μ 3 v 3 .  \nSuch a sum over an index is called a contraction, and it is a generalization of the inner product, as we will describe in more details below. Conversely, if we have a covector , we can raise its index by contracting it with the inverse metric: w μ  \nw μ = g μν w ν .  \nThis works the same for indices of higher-rank tensors. For example, if we have a tensor of rank 2 represented with two upper indices, , we can lower either one or both of its indices: T μλ  \nT μ ν = g νλ T μλ , T μν = g μρ g νλ T ρλ .  \nIn   OGRePy,   since   tensor   objects   are abstract   tensors ,   independent   of   any   specific   index configuration, there is no notion of raising or lowering the indices of a tensor object . Instead, one simply request to display the components of the tensor with the desired index configuration, without modifying the object itself. This works with both the show() and list() methods, by simply providing as an argument the list of indices in the format ,   as   when   we created a new tensor. (±1, ±1, . . . )  \nAs an example, let us use show() to display the vector FourVelocity with a lower index, that is, with index configuration (-1,) :  \nFourVelocity . show(indices = ( -1,)) In [ ]:  \nu μ ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎜ ⎜ ⎝ -0 0 ⎞ ⎟ ⎟ ⎟ ⎟ ⎟ ⎠ 1 √ 1 -v 2 v √ 1 -v 2  \nOGRePy automatically knows to use the Minkowski metric to lower the index, which means that a   minus   sign   has   been   added   to   the   first   component,   as   expected.   Similarly,   here   is PerfectFluid with just the second index lowered, this time displayed using list() :  \nPerfectFluid . list(indices = (1, -1)) In [ ]:  \nT t t = -ρ T x x = T y y = T z z = p  \nThe components of the representation of the metric with two upper indices are the components of the inverse metric, since  \ng μλ g λν = δ ν μ .  \nTherefore, a quick way to show the components of the inverse metric is to display it with the index configuration (1, 1) :  \ng μν ∣ ∣ ∣ ( t , r , θ , ϕ ) = ⎛ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎝ -0 0 0 0 0 0 0 0 0 0 0 0 ⎞ ⎟ ⎟ ⎟ ⎟ ⎟ ⎟ ⎟ ⎠ r -2 M + r -2 M + r r 1 r 2 1 r 2 sin 2 ( θ )  \nFor the same reason, the metric with one upper and one lower index is just the identity matrix:  \nSchwarzschild . list(indices = (1, -1)) In [ ]:  \ng t t = g r r = g θ θ = g ϕ ϕ = 1  \nAs explained above, if show() or list() are   called   without any arguments, the tensor is displayed in its default index configuration , which is the one first used to define the tensor. So the 4-velocity has one upper index by default, and the stress tensor has two upper indices by default,   because   that   is   how   we   initially   defined   them.   However,   the   default   indices   can   be changed by setting the property default\\_indices .   For   example, let us change the default indices of the perfect fluid stress tensor to two lower indices:  \nPerfectFluid . default\\_indices = ( -1, -1) In [ ]:  \nNow, when we display the tensor using show() or list() without any arguments, this is the index configuration that will be used:  \nPerfectFluid In [ ]:  \nOut[ ]:  \nT μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ ρ 0 0 0 0 p 0 0 0 0 p 0 0 0 0 p ⎞ ⎟ ⎟ ⎟ ⎠', 'Coordinate transformations': 'The components of any tensor may be transformed from one coordinate system to another coordinate system using the following prescription: x μ x μ \'  \n- · For every lower index , add a factor of (i.e. the derivative of the old coordinates with respect to the new, or the Jacobian ). μ ∂ x μ / ∂ x μ \'\n- · For every upper index , add a factor of (i.e. the derivative of the new coordinates with respect to the old, or the inverse of the Jacobian). μ ∂ x μ \' / ∂ x μ  \nFor example, given a tensor with components in a coordinate system , we can transform to components in another coordinate system as follows: T αβ x μ T α \' β \' x μ \'  \nIn [ ]:  \nT α \' β \' ( x μ \' ) = / ∂ x α ∂ x α \' ∂ x β ∂ x β \'  \nFor a general rank tensor with upper indices and   lower indices , the transformation takes the form ( p , q ) p α 1 , …, α p q β 1 , …, β q  \nT α \' 1 ⋯ α \' p β \' 1 ⋯ β \' q ( x μ \' ) = ( ⋯ )( ⋯ ) T α 1 ⋯ α p β 1 ⋯ β q ( x μ ) ∂ x α \' 1 ∂ x α 1 ∂ x α \' p ∂ x α p ∂ x β \' 1 ∂ x β 1 ∂ x β \' q ∂ x β q  \nAs a mnemonic for this formula, recall that two indices may only be contracted if one of them is an upper index and the other is a lower index. If an index is in the denominator of a derivative, then its role is reversed (upper lower). Thus the old (non-primed) and new (primed) indices can only be in places that allow properly contracting the Jacobian or inverse Jacobian with the tensor. For example, is an upper index in and therefore must be contracted with a lower index. Thus, must be in the denominator, to lower its index and allow it to be contracted with the tensor. ↔ α 1 T ∂ x α 1  \nAs we saw above, OGRePy automatically knows how to raise or lower indices as needed using the appropriate metric. Similarly, any operation that requires transforming to another coordinate system will preform the transformation automatically behind the scenes. However, for this to happen, OGRePy needs to know the appropriate transformation rules. These are defined between the tensor objects representing the coordinates, which were created as Coordinates objects. The rules for transforming from a source coordinate system to a target coordinate system are stored   within   the   tensor   object   representing   the   source.   This   is   done   using   the   method set\\_coord\\_transformation() . To illustrate, let us define transformations from Cartesian to Spherical and back:  \n```\nCartesian . set\\_coord\\_transformation( target = Spherical, rules = { x: r * T . s . sin(theta) * T . s . cos(phi), y: r * T . s . sin(theta) * T . s . sin(phi), z: r * T . s . cos(theta), }, ) Spherical . set\\_coord\\_transformation( target = Cartesian, rules = { r: T . s . sqrt(x ** 2 + y ** 2 + z ** 2), theta: T . s . acos(z / T . s . sqrt(x ** 2 + y ** 2 + z ** 2)), phi: T . s . atan2(y, x), }, )\n```  \nAs you can see, the rules are supplied as a dictionary specifying the transformation from each source coordinate to the target coordinates. Note that we did not have to input a rule for t , since it stays the same in both cases; the transformation is in the spatial coordinates only.  \nNow OGRePy knows how to convert back and forth between these two coordinate systems - and this will happen automatically whenever required. We just needed to provide these rules once and for   all,   and   any   tensor   initially   defined   in   one   coordinate   system   can   now   be   automatically converted to the other.  \nAs in the case of raising and lowering indices, displaying a tensor in a different coordinate system is a simple matter of calling the methods show() or list() with an additional argument specifying the coordinate system to use. For example, let us show the Minkowski metric in spherical coordinates:  \nMinkowski . show(coords = Spherical) In [ ]:  \nη μν ∣ ∣ ∣ ( t , r , θ , ϕ ) = ⎛ ⎜ ⎜ ⎜ ⎜ ⎝ -1 0 0 0 0 1 0 0 0 0 r 2 0 0 0 0 r 2 sin 2 ( θ ) ⎞ ⎟ ⎟ ⎟ ⎟ ⎠  \nWe can also ask to see a tensor in a specific index configuration and a specific coordinate system:  \nPerfectFluid . show(coords = Spherical, indices = In [ ]:  \n(1, 1))  \nT μν ∣ ∣ ∣ ( t , r , θ , ϕ ) = ⎛ ⎜ ⎜ ⎜ ⎜ ⎜ ⎝ ρ 0 0 0 0 p 0 0 0 0 0 0 0 0 ⎞ ⎟ ⎟ ⎟ ⎟ ⎟ ⎠ p r 2 p r 2 sin 2 ( θ )  \nThe method list() works in exactly the same way, for example:  \nSchwarzschildKretschmann . list(coords = In [ ]:  \nCartesian)  \nK = 48 M 2 ( x 2 + y 2 + z 2 ) 3  \nJust as with default indices, every tensor has a default coordinate system, which is, initially, the one we used to create it. We can change it by setting the property default\\_coords ,   and   then whenever we display the tensor, it will be displayed in that coordinate system if no other coordinate system is specified. For example, let\'s change the default coordinates of the perfect fluid stress tensor to spherical coordinates:  \nNow, when we display the tensor using show() or list() without any arguments (or with just a choice of indices), this is the coordinate system that will be used:  \n```\n~ PerfectFluid In [ ]:\n```  \nT tt = ρ T rr = p T θθ = pr 2 T ϕϕ = pr 2 sin 2 ( θ )  \nNote that the coordinate transformation we defined is only invertible for . However, since we defined the coordinate   above as a non-negative symbol, this is already taken care of by SymPy behind the scenes. To illustrate this, let us define a new scalar in Minkowski space, which is equal to the spatial distance from the origin: r ≥ 0 r  \n```\nSpatialDistance = T . Tensor( metric = Minkowski, coords = Cartesian, indices = (), components = [T . s . sqrt(x ** 2 + y ** 2 + z ** symbol = "d", ) In [ ]:\n```  \nOut[ ]:  \n```\n2)],\n```  \nd ∣ ∣ ∣ ( t , x , y , z ) = √ x 2 + y 2 + z 2  \nWhen we convert this scalar to spherical coordinates, we get  , as expected: r  \n```\nSpatialDistance . show(coords = Spherical) In [ ]:\n```  \nd ∣ ∣ ∣ ( t , r , θ , ϕ ) = r  \nHowever, if we did not define   as a non-negative symbol, we would have obtained instead. r | r |', 'Replacing symbols in the tensor components': 'By using the replace argument of list() and show() , we can replace symbols in the tensor components with other symbols or numerical values. The replacement must be in the form of a dictionary, where each key in the dictionary will be replaced with its value. Each of the keys and the values of the dictionary can be either a SymPy Symbol object or a SymPy Expr object. The components will then be simplified, and the tensor will be displayed with the new components. Note that this only applies to displaying the components; the tensor data itself will not change.  \nFor example, perhaps we would like to display the value of the Kretschmann scalar for a particular  \nSchwarzschildKretschmann . show(replace = In [ ]:  \n{M: 1, r: 10})  \nK ∣ ∣ ∣ ( t , r , θ , ϕ ) = 3 62500  \nOr maybe we would like to display the perfect fluid stress tensor with   equal to  : p ρ  \nPerfectFluid . list(replace = {p: rho}) In [ ]:  \nT tt = T rr = ρ T θθ = ρ r 2 T ϕϕ = ρ r 2 sin 2 ( θ )  \nThe replacement can, of course, also be combined with a choice of indices and/or coordinates:  \nPerfectFluid . list(coords = Cartesian, indices = (1, 1), replace = {p: rho}) In [ ]:  \nT tt = T xx = T yy = T zz = ρ  \nAnother, more advanced, thing we can do with list() and show() is to pass a function to be executed on each tensor component before printing it. We will see an example below, in the "Geodesic equations from the Lagrangian" section.', 'Customizing the simplification function': "Whenever OGRePy performs an operation that creates or modifies tensor components, such as converting between index representations or coordinate systems, it automatically simplifies the result using SymPy's simplify() . However, advanced users may want to have more control over this simplification process. This can be done using by setting T.options.simplify\\_func to a function of your choice.  \nFor example, you may want to customize the arguments passed to simplify (such as ratio or inverse , see here for more information), or you may want to use specific SymPy simplification functions such as powsimp() or logcombine() in a specific combination, or even refine() with specific assumptions.  \nIn extreme situations, you may even want to cancel simplification altogether, if it is taking too long, which can be achieved using T.options.simplify\\_func = lambda x: x -   that   is, replacing the simplification function with the identity function.  \nNote that changing the simplification function will not automatically apply it to any existing tensors. The reason is that when OGRePy calculates the components of a tensor in a particular  \nrepresentation, it calculates them once and for all , and then saves them in the object's data to be reused later. This is done to improve performance, so that the components don't have to be recalculated every time they are needed.  \nWe can force re-simplification of the stored components of a specific tensor using the method simplify() . As usual with the options object, you may restore the simplification function to the default, SymPy's simplify() , with the command del T.options.simplify\\_func .", 'Getting information about tensors': "The info() method can be used to display the information encoded in a tensor object in human-readable form. Here is an example:  \n```\nMinkowski . info() In [ ]:\n```  \n- · Name : Minkowski · Class : Metric · Symbol : · Rank : 2 · Dimensions : 4 · Default Coordinates : Cartesian · Default Indices : (-1, -1) · Associated Metric For : FourVelocity , PerfectFluid , SpatialDistance As for and , OGRePy defines a convenient shortcut for calling : use the η μν  \nshow() list() info() + (unary plus) operator in front of the tensor. For example:  \n```\n+ PerfectFluid In [ ]:\n```  \n- · Name : PerfectFluid\n- · Class : Tensor\n- · Symbol : T μν\n- · Rank : 2\n- · Dimensions : 4\n- · Default Coordinates : Spherical\n- · Default Indices : (-1, -1)\n- · Metric : Minkowski  \nA Coordinates object also has an info() method, and it can be used to check which tensors use this coordinate system as their default:  \n```\n+ Cartesian In [ ]:\n```  \n- · Name : Cartesian\n- · Class : Coordinates\n- · Dimensions : 4\n- · Default Coordinates For : Minkowski , Alcubierre , FourVelocity , SpatialDistance  \nIt is also possible to get each of these properties of the tensor individually, using the properties symbol , default\\_indices , and default\\_coords and the methods rank() , dim() , and metric() . Note that the symbol, default indices, and default coordinates are properties that can be changed, but rank() , dim() ,   and metric() are   read-only  properties obtained using methods, as it doesn't make sense to change these properties. Here are some examples of using these properties and methods. The symbol is a bit cryptic:  \n```\nPerfectFluid . symbol 'T[0][1]' In [ ]: Out[ ]:\n```  \nThe purpose of the [0][1] is to serve as a placeholders for indices, since the actual letters that will be used as the indices can be different each time. (These placeholders are added automatically when we create the tensor, there is no need to specify them manually, although you can if you want.) To get the symbol as a TeX string, we can use the tex\\_symbol() method, and pass its output to the IPython Math() function to display it in the notebook:  \nMath(PerfectFluid . tex\\_symbol()) Similarly, we can use the default\\_indices and default\\_coords properties to obtain the default indices and coordinates: In [ ]: Out[ ]: T μν  \n```\nPerfectFluid . default\\_indices (-1, -1) PerfectFluid . default\\_coords In [ ]: Out[ ]: In [ ]: Out[ ]:\n```  \n( t r θ ϕ )  \nAnd we can use the metric() method to obtain the associated metric:  \nIn [ ]:  \nOut[ ]:  \nη μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ -1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 ⎞ ⎟ ⎟ ⎟ ⎠  \nIn the last two examples, default\\_coords and metric() ,   notice   that   the   output   directly shows the tensors used as the default coordinates and associated metric respectively. This is because default\\_coords and metric() return a reference to the relevant Coordinates or Metric object respectively, and that object then gets displayed in the notebook using the show() method, as it is the output of the cell.  \nHowever, since we are working inside a notebook, it would be helpful to know the name of the notebook variable referring to this Coordinates or Metric object. It turns out that is not at all straightforward to obtain this information in Python, since an object reference might not even be associated to any specific variable, or it may be associated to more than one variable. Luckily, OGRePy comes with a special algorithm to figure out which notebook variables refer to which objects. We already saw that algorithm in action when we used the info() method above. However, we can also obtain the name of the variable by simply converting the object to a string using the str constructor. This works on both Coordinate and Metric objects:  \n```\nstr(PerfectFluid . default\\_coords) 'Spherical' str(PerfectFluid . metric()) 'Minkowski' In [ ]: Out[ ]: In [ ]: Out[ ]:\n```  \nThat same algorithm powers the module function info() , which lists all the tensors created so far, including the names of the variables used to define these tensors. Here are all the tensors we defined so far in this notebook:  \n```\nT . info() In [ ]:\n```  \n9 tensor objects created: 2 coordinates, 3 metrics, 4 tensors.  \nCoordinate systems:  \n- 1. Cartesian (id: 0x21c55f5d760 ), default for: Minkowski , Alcubierre , FourVelocity , SpatialDistance\n- 2. Spherical (id: 0x21c55f96430 ), default for: Schwarzschild , SchwarzschildKretschmann , PerfectFluid  \nMetrics and associated tensors:  \n- 1. Minkowski (symbol: ) (id: 0x21c56751bd0 ), used by: FourVelocity , PerfectFluid , SpatialDistance η μν\n- 2. Schwarzschild (symbol: ) (id: 0x21c56881b20 ), used by: SchwarzschildKretschmann g μν\n- 3. Alcubierre (symbol: ) (id: 0x21c56882150 ) g μν", 'Tensors:': '- 1. SchwarzschildKretschmann (symbol: ) (id: 0x21c57c4db70 ) K\n- 2. FourVelocity (symbol: ) (id: 0x21c57c69c10 ) u μ\n- 3. PerfectFluid (symbol: ) (id: 0x21c57c69620 ) T μν\n- 4. SpatialDistance (symbol:  ) (id: 0x21c580709f0 ) d  \nWe see that we created 9 tensors in total so far: 2 coordinate systems, 3 metrics, 3 tensors associated with the Minkowski metric, and 1 tensor associated with the Schwarzschild metric.', 'Getting the components of a tensor': 'Sometimes you may want to extract the components of a tensor in a specific representation as a list, so you can use them outside of this package, as regular SymPy expressions rather than tensor objects.   This   is   done   using   the components() method.   For   example,   we   can   retrieve   the components of the inverse Schwarzschild metric (with two upper indices):  \nInverseSchwarzschild  \n=  \nSchwarzschild  \n.  \ncomponents(coords  \n=  \nSpherical, indices  \n=  \n(1, 1))  \n```\n⎡ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ -0 0 0 0 0 0 0 0 0 0 0 0 ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦ r -2 M + r -2 M + r r 1 r 2 1 r 2 sin 2 ( θ )\n```  \nWe can now treat InverseSchwarzschild as any other SymPy Array - for example, extract the element at a particular position:  \nIn [ ]:  \nOut[ ]:  \nOut[ ]: -r -2 M + r  \nIf the desired index configuration and/or coordinate system are not specified, the default ones will be used. However, it is important to always know exactly which representation the components are in, to avoid confusion. Thus, you will be notified which representation was used:  \nSchwarzschild . In [ ]:  \n```\ncomponents()\n```  \nOGRePy : Using default coordinate system Spherical and default index configuration (-1, -1).  \nOut[ ]:  \n⎡ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ -1 0 0 0 0 0 0 0 0 r 2 0 0 0 0 r 2 sin 2 ( θ ) ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦ 2 M r 1 -+1 2 M r  \nThis warning can be disabled by adding the argument warn=False .  \nSince components() returns a SymPy Array ,   we can use the subs() method to perform replacements, just like the replace argument of show() and list() (see   above).   For example, here are the components of the Schwarzschild metric on the hypersurface with : θ = π /2  \nSchwarzschild . components() . subs({theta: T . s . pi / 2}) In [ ]:  \nOGRePy : Using default coordinate system Spherical and default index configuration (-1, -1).  \nOut[ ]:  \n⎡ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ -1 0 0 0 0 0 0 0 0 r 2 0 0 0 0 r 2 ⎤ ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦ 2 M r 1 -+1 2 M r  \nIn the case of a coordinate system, that is, a Coordinates object, components() takes no arguments, since a coordinate system cannot have multiple representations:  \nSpherical . In [ ]:  \n```\ncomponents()\n```  \nOut[ ]: [ t r θ ϕ  \n]', 'Calculations with tensors': 'Now that we have all the bookkeeping of tensors out of the way, we can finally discuss how to use those tensors in calculations. In OGRePy, all tensor calculations are performed by simply using normal operations such as addition and multiplications on the tensors. However, this does not work the same as operating, for example, on integers; in most tensor operations, we also have to specify indices . Some of these indices will be *free indices , which will remain in the final result, while others may be **contraction indices , which will be contracted upon.  \nOGRePy supports a comprehensive collection of tensor operations. A tensor calculation in OGRePy can   involve   any   number   of   tensor   objects   and   can   contain   any   combination   of   addition, multiplication by scalar, trace, contraction, partial derivative, and covariant derivative. The result will be stored in a new tensor object. Let us now go over these operations one by one, and give some examples.', 'Addition of tensors': 'Addition of tensors in OGRePy is represented by a sum of the form tensor1(index1, index2, ...) + tensor2(index1, index2, ...) ,   where tensor1 and tensor2 are   the   tensor objects to be added, and (index1, index2, ...) are   the index specifications for   each tensor, given as SymPy symbols. (Note that an index specification is not the same as an index configuration , which is a tuple of the form (Â±1, Â±1, ...) specifying which indices are up (+1) and which are down (-1).)  \nNote that you do not specify the position (upper or lower) of the indices. Furthermore, just like in any tensor equation, the index letters themselves have no meaning ; they are just placeholders. Therefore, (a, b, c) , (X, Y, Z) ,   and (alpha, beta, gamma) are   all   completely equivalent. The only requirement is that the indices are consistent ; in the case of addition, this means that both tensors being added must have the same indices up to permutation .  \nThe following constraints apply to addition of tensors:  \n- · You may not add a tensor representing a coordinate system to any other tensor, since coordinates do not transform like tensors.\n- · You may not add two tensors associated with different metrics, since their sum would have undefined transformation properties.\n- · You may not add two tensors with different ranks, since that is not a well-defined operation.\n- · As stated above, both tensors must have the same indices up to permutation. and (with   inverted   indices   on   the   second   tensor)   are   both   okay,   but doesn\'t make sense, as it has more free indices than the rank of the result (that is, the result will be of the form instead of ). A μν + B μν A μν + B νμ A μν + B αβ T μναβ T μν  \nAs an example, let us add the Minkowski metric and the perfect fluid stress tensor . First we import symbols from OGRePy.abc to use as indices, then we perform the actual sum: η μν T μν  \n```\nfrom OGRePy.abc import mu, nu result = Minkowski(mu, nu) + PerfectFluid(mu, nu) In [ ]:\n```  \n```\nOut[ ]: η μν + T μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ ρ -1 0 0 0 0 p +1 0 0 0 0 p +1 0 0 0 0 p +1 ⎞ ⎟ ⎟ ⎟ ⎠\n```  \nIn [ ]:  \nOut[ ]:  \nNotice that the addition operation returned a new tensor object. This tensor\'s symbol has been automatically set to reflect the formula that was used to create it. However, often we want the new tensor to have its own single-letter symbol. To do that, we can use the symbol property:  \nresult  \n.  \nsymbol  \n=  \n"S"  \nresult  \nS μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ ρ -1 0 0 0 0 p +1 0 0 0 0 p +1 0 0 0 0 p +1 ⎞ ⎟ ⎟ ⎟ ⎠  \nWith this symbol, the tensor equation we calculated becomes:  \nS μν = η μν + T μν .  \nThe order of indices we specify for each tensor matters. To give an example, let us define the following non-symmetric tensor:  \n```\nNonSymmetric = T . Tensor( metric = Minkowski, coords = Cartesian, indices = ( -1, -1), components = [[0, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], symbol = "N", ) In [ ]:\n```  \nOut[ ]:  \nIn [ ]:  \nOut[ ]:  \nN μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ⎞ ⎟ ⎟ ⎟ ⎠  \nIf we add it to the Minkowski metric, we get:  \nMinkowski(mu, nu)  \n+  \nNonSymmetric(mu, nu)  \nη μν + N μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ -1 0 0 1 0 1 0 0 0 0 1 0 0 0 0 1 ⎞ ⎟ ⎟ ⎟ ⎠  \nNote that in this example we did not save the new tensor object in a variable, we just showed the result. However, if we flip its index specification from (mu, nu) to (nu, mu) , then we instead get:  \nη μν + N νμ ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ -1 0 0 0 0 1 0 0 0 0 1 0 1 0 0 1 ⎞ ⎟ ⎟ ⎟ ⎠  \nTo stress an important point, there is no difference between NonSymmetric(mu, nu) and NonSymmetric(nu, mu) on its own, as the index labels themselves are meaningless unless there is some context in which they obtain meaning - as is always the case for tensor expressions. However,   there   is   a   big   difference   between,   for   example, Minkowski(mu,   nu)   + NonSymmetric(mu, nu) and Minkowski(mu, nu) + NonSymmetric(nu, mu) , as the indices have a different order, and thus the two expressions refer to adding different components.  \nOf course, any number of tensors can be added, not just two - and the same tensor can be added multiple times, with different index specifications each time. For example, we can calculate the following expression:  \nMinkowski(mu, nu) + PerfectFluid(mu, nu) + NonSymmetric(mu, nu) + NonSymmetric(nu, mu) In [ ]:  \nOut[ ]:  \nIn [ ]:  \nOut[ ]:  \nη μν + T μν + N μν + N νμ ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ ρ -1 0 0 1 0 p +1 0 0 0 0 p +1 0 1 0 0 p +1 ⎞ ⎟ ⎟ ⎟ ⎠', 'More on index specifications': 'For calculations that involve many indices, it may be more convenient to specify the indices as a string instead of individual symbols. This also saves us the trouble of importing or defining those symbols explicitly. This string must be given in the same format as SymPy\'s symbols() function, that is, a space- or comma-separated list of one or more letters or TeX codes. It is also possible to provide a list of strings, or even mix and match symbols and strings. For example, the previous calculation can also be written as follows:  \nMinkowski(mu, nu)  \n+  \nPerfectFluid("mu nu")  \n+  \nNonSymmetric("mu", nu)  \n+  \nNonSymmetric("nu",  \nη μν + T μν + N μν + N νμ ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ ρ -1 0 0 1 0 p +1 0 0 0 0 p +1 0 1 0 0 p +1 ⎞ ⎟ ⎟ ⎟ ⎠  \nIndex specifications have a use even if we are not doing a calculation: they change the indices that appear   when show() is   called,   instead   of   the   default   index   letters   (as   specified   using T.options.index\\_letters ). For example, with the default index letters, NonSymmetric will  \nbe displayed with the indices : μν  \nNonSymmetric In [ ]: Out[ ]:  \nN μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ⎞ ⎟ ⎟ ⎟ ⎠  \nHowever, if we want to display it with the indices instead, we can simply indicate these indices in parentheses: αβ  \nNonSymmetric("alpha beta") In [ ]:  \nOut[ ]:  \nN αβ ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ⎞ ⎟ ⎟ ⎟ ⎠  \nAnother alternative syntax is available for those who prefer the index specification format from the Mathematica version of OGRe: a string where each letter is a separate symbol, with no spaces between the letters, e.g. "abc" corresponds to (a, b, c). This format is less useful in the Python version since there is no easy way to enter Greek indices as individual letters; in Mathematica it\'s easy to write e.g. "Î¼Î½" using escape sequences, but in Python it\'s easier to write "mu nu" or use symbols named mu and nu explicitly. The Mathematica format is accessible via square brackets, e.g.:  \nNonSymmetric["ab"] In [ ]: Out[ ]:  \nN ab ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 ⎞ ⎟ ⎟ ⎟ ⎠', 'Multiplication of tensor by scalar': 'Multiplication of tensor by scalar in OGRePy is represented by a product of the form scalar * tensor(index1,   index2,   ...) ,   where tensor is   the   tensor   object   to   be   multiplied, (index1, index2, ...) is an index specification as for addition, and scalar is the scalar to multiply by. Note that scalar should be a number or SymPy expression, and not a tensor object of rank 0. To multiply a tensor by a tensor of rank 0, use contraction instead, as detailed in the next section.  \n2 * Minkowski(mu, nu) In [ ]: Out[ ]:  \n2 η μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ -2 0 0 0 0 2 0 0 0 0 2 0 0 0 0 2 ⎞ ⎟ ⎟ ⎟ ⎠  \nWhile in this example the indices seem redundant, they are necessary because in most non-trivial situations we would like to combine multiplication with other operations, such as addition or contraction, in which the order of indices matters. For example, consider:  \n2 * t * Minkowski(mu, nu) -3 * x * PerfectFluid(mu, nu) + 4 * y * NonSymmetric(mu, nu) In [ ]:  \nOut[ ]:  \n2 t η μν -3 xT μν +4 yN μν -5 zN νμ ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ -3 ρ x -2 t 0 0 4 y 0 -3 px +2 t 0 0 0 0 -3 px +2 t 0 -5 z 0 0 -3 px +2 t', 'Taking traces and contracting tensors: theoretical review': 'The most complicated tensor operation is contraction ,   a   generalization   of   the   vector   inner product. This is done by summing over one or more disjoint pairs of indices, with each pair containing exactly one upper index and one lower index. Raising and lowering indices is one example  of   contraction:   the   metric   (or   its   inverse)   is   contracted   with   a   tensor.   Coordinate transformations are another example, where we contract the Jacobian (or its inverse) with a tensor.  \nThe simplest example of contraction is the vector inner product ,   which   is   defined   as   the contraction of a vector (one upper index) with a covector (one lower index):  \nv μ w μ = g μν v μ w ν = g ( v , w ).  \nThe middle part of this equality comes from the fact that, as explained above, when we lower an index on , we use the metric: w ν  \nw μ = g μν w ν .  \nThis, in turn, justifies the notation on the right-hand side, as this is, in fact, an inner product of two vectors using the metric   (in index-free notation). g ( v , w ) g  \nContraction of indices in higher-rank tensors is simply a generalization of the inner product, for example:  \nA μα B αν = g αβ A μα B β ν .  \nWe can also contract more than one index:  \nA μν B μν = g μα g νβ A μν B αβ .  \nThis simply amounts to the fact that lowering both indices of involves contracting each index with the metric. We can even contract two indices of the same tensor : B αβ  \nA μ μ = g μν A μν .  \nThis is called taking the trace . Furthermore, it is also possible to contract pairs of indices from more than two tensors at the same time:  \nA μν B νρ C ρσ = g να g ρβ A μν B αβ C ρσ .  \nHowever, such operations can always be broken down into individual contractions of pairs of tensors. For example, in this case, one could first contract with and then contract the result with - which is indeed how this kind of contraction will be performed in OGRePy in practice: B νρ C ρσ A μν  \nA μν B νρ C ρσ = A μν ( B νρ C ρσ ) .  \nIn a contraction, there are two types of indices: contracted indices , which are summed upon, and free indices , which are not summed upon. The rank of the tensor that results from the contraction is the number of free indices. So for example, in the expression we have one contracted index, , and two free indices, and  . Therefore, the resulting tensor is of rank two: A μα B αν α μ ν  \nT μ ν = A μα B αν .', 'Taking traces and contracting tensors: OGRePy syntax': 'Contraction of tensors in OGRePy is represented by an expression of the form tensor1(index1, index2, ...) @ tensor2(index1, index2, ...) , where tensor1 and tensor2 are the tensor objects to be contracted, and (index1, index2, ...) are the index specifications for each tensor. Any matching indices in both index specifications will be contracted. This means that, for example, is   calculated using v(mu) @ w(mu) and is   calculated using A(mu, nu) @ B(nu, rho) @ C(rho, sigma) . Note that the user doesn\'t need to worry about the contracted indices being one upper and one lower, which is a common source of errors when contracting tensors by hand; the order of the indices, and whether the same index repeats twice, is all that matters. v μ w μ A μν B νρ C ρσ  \nAs a first example, let us create the stress-energy tensor for a perfect fluid with a 4-velocity . This is defined as follows: u μ  \nT μν = ( ρ + p ) u μ u ν + pg μν .  \n<!-- image -->  \nEven though this does not involve any contractions, it still counts as a "trivial" contraction, since two tensors (the 4-velocities) are juxtaposed next to each other to create another tensor. This is also known as an outer product .   Therefore, it uses the same @ operator syntax as any other  \ncontraction, except that there are no matching indices . Note that this expression involves not just contraction (in the first term), but also multiplication by scalar (in both terms), and addition of the two terms together. Again, OGRePy takes care of everything behind the scene, so this just works:  \nPerfectFluidFromVelocity = (rho + p) * FourVelocity(mu) @ FourVelocity(nu) + p * Minkowski PerfectFluidFromVelocity . symbol = "T" PerfectFluidFromVelocity In [ ]:  \nOut[ ]:  \nT μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎝ -0 0 -0 0 0 0 p 0 0 0 0 p ⎞ ⎟ ⎟ ⎟ ⎟ ⎟ ⎟ ⎠ -ρ -pv 2 v 2 -1 v ( ρ + p ) v 2 -1 v ( ρ + p ) v 2 -1 -ρ v 2 -p v 2 -1  \nIndeed, for we get the previously defined stress tensor: v = 0  \nPerfectFluidFromVelocity . show(replace = In [ ]:  \n{v: 0})  \nT μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ ρ 0 0 0 0 p 0 0 0 0 p 0 0 0 0 p ⎞ ⎟ ⎟ ⎟ ⎠  \nMultiplying a tensor by a scalar (i.e. a tensor of rank 0) is also done using a "trivial" contraction with no contracted indices. For example:  \n(SpatialDistance() @ Minkowski(mu, nu)) . show(coords = Spherical) In [ ]:  \nd η μν ∣ ∣ ∣ ( t , r , θ , ϕ ) = ⎛ ⎜ ⎜ ⎜ ⎜ ⎝ -r 0 0 0 0 r 0 0 0 0 r 3 0 0 0 0 r 3 sin 2 ( θ ) ⎞ ⎟ ⎟ ⎟ ⎟ ⎠  \nNote the empty index specification () , which is mandatory in order for OGRePy to recognize that the scalar is involved in a tensor calculation. We can also multiply a scalar by another scalar:  \nSpatialDistance() @ SpatialDistance() In [ ]: Out[ ]:  \ndd ∣ ∣ ∣ ( t , x , y , z ) = x 2 + y 2 + z 2  \nNow let us demonstrate some non-trivial contractions. First, we have the inner product of vectors in this case, we get the norm (squared) of the 4-velocity, since we are contracting it with itself:  \nFourVelocity(mu) @ FourVelocity(mu) In [ ]:  \nOut[ ]:  \nu μ u μ ∣ ∣ ∣ ( t , x , y , z ) = -1  \nWe can also contract several tensors together, with two matching pairs of indices:  \nFourVelocity(mu) @ PerfectFluidFromVelocity(mu, nu) @ NonSymmetric(nu, rho) In [ ]:  \nOut[ ]:  \nu μ T μ ν N ν ρ ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎜ ⎝ 0 0 0 -⎞ ⎟ ⎟ ⎟ ⎟ ⎠ ρ √ 1 -v 2  \nFinally, to take the trace of a tensor, we simply match pairs of indices in that tensor\'s index specification:  \nMinkowski(mu, mu) In [ ]: Out[ ]:  \nPerfectFluid("mu mu") In [ ]:  \nOut[ ]:  \nT μ μ ∣ ∣ ∣ ( t , r , θ , ϕ ) = -ρ +3 p  \nOf course, this also works for tensors with more than two indices, as we will see below. Any combination of indices can be used, with no limit on the number of traces taken for each tensor.', 'Derivatives and curvature tensors': 'The partial   derivative is   represented   in   OGRePy   using   the   class PartialD .   It   can   be contracted   with   other   tensors   using   the   usual   OGRePy   contraction   notation   -   including   an appropriate index specification - to calculate gradients and divergences. ∂ μ  \nThe gradient of a tensor is the partial derivative acting on the tensor with a free index, e.g. for a tensor, for a vector, or for a rank-2 tensor, resulting in a tensor of one rank higher (due to the extra index). In OGRePy, this is done by contracting the PartialD object from the left with the tensor, using the contraction operator @ .   For example, we can calculate the gradient of the Kretschmann scalar as follows: ∂ μ ∂ μ ϕ ∂ μ u ν ∂ μ T νλ ∂ μ K  \nη μ μ ∣ ∣ ∣ ( t , x , y , z ) = 4  \nT . PartialD(mu) @ SchwarzschildKretschmann() In [ ]:  \nOut[ ]:  \n∂ μ K ∣ ∣ ∣ ( t , r , θ , ϕ ) = ⎛ ⎜ ⎜ ⎜ ⎜ ⎝ 0 -0 0 ⎞ ⎟ ⎟ ⎟ ⎟ ⎠ 288 M 2 r 7  \nAnd here is the gradient of the Schwarzschild metric:  \n~ (T . PartialD(mu) @ Schwarzschild("alpha beta")) In [ ]:  \n∂ r g tt = -∂ r g rr = -∂ r g θθ = 2 r ∂ r g ϕϕ = 2 r sin 2 ( θ ) ∂ θ g ϕϕ = 2 r 2 sin ( θ ) cos ( θ ) 2 M r 2 2 M r 2 ( -+1 ) 2 2 M r  \nThe divergence of a tensor is the contraction of the partial derivative with one of the tensor\'s indices, e.g. for a vector or for a rank-2 tensor, resulting in a tensor of one rank lower . To illustrate, let us create the position vector of a particle in Minkowski space: ∂ μ ∂ μ u μ ∂ μ T μν  \n```\nPosition = T . Tensor( metric = Minkowski, coords = Cartesian, indices = (1,), components = [t, x, y, z], symbol = "x", ) In [ ]:\n```  \nOut[ ]:  \nIts gradient is:  \nT . PartialD(mu) @ In [ ]:  \n```\nPosition(nu)\n```  \nx μ ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ t x y z ⎞ ⎟ ⎟ ⎟ ⎠  \nOut[ ]:  \n∂ μ x ν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 ⎞ ⎟ ⎟ ⎟ ⎠  \nAnd its divergence is:  \nT . PartialD(mu) @ Position(mu) In [ ]:  \nOut[ ]:  \n∂ μ x μ ∣ ∣ ∣ ( t , x , y , z ) = 4  \nAs you can see, the syntax for both the gradient and divergence is the same; if the index specification  of PartialD matches one of the indices of the tensor to its right, then the divergence will be calculated, otherwise the gradient will be calculated.  \nWARNING: When applying partial derivatives to tensors, the result generally does not transform like a tensor under a coordinate transformation. For this reason, in general relativity we normally use the covariant derivative instead of a partial derivative. However, there are three important exceptions, where partial derivatives must be used: in the covariant derivative itself, the Levi-Civita connection , and the Riemann tensor , all of which will be discussed below.  \nOf these  three   special   cases,   the   covariant   derivative   and   the   Riemann   tensor   turn   out   to nonetheless   transform   like   tensors   under   coordinate   transformations,   due   to   cancellations. However, the Levi-Civita connection, whose components are called the Christoffel symbols , has a special transformation rule, which is used automatically by OGRePy, as we will show.  \nIn all other cases, if the user creates an arbitrary tensor using partial derivatives, the result will generally transform incorrectly under a coordinate transformation in OGRePy. Therefore, it is highly recommended to avoid using partial derivatives in OGRePy unless you really know what you\'re doing.', 'The Christoffel symbols': 'The Christoffel symbols are a very important tensor-like object in differential geometry. They are the components of the Levi-Civita connection , which is the unique torsion-free connection that preserves the metric. The Christoffel symbols are defined as follows:  \nΓ λ μν = g λσ ( ∂ μ g νσ + ∂ ν g σμ -∂ σ g μν ) . 1 2  \nEach of the terms inside the parentheses is a gradient of the metric, with different indices. For example, the first term is   represented in OGRePy as T.PartialD(mu) @ metric(nu, sigma) where metric is the tensor object representing the metric. Since OGRePy allows us to ∂ μ g νσ  \neasily perform an arbitrary number of contraction, addition, multiplication by scalar, and partial derivative operations, we can calculate the Christoffel symbols of the Schwarzschild metric directly as follows: (We used SymPy\'s Rational class to create a symbolic 1/2 in the front, otherwise it would have been a numeric 0.5)  \n```\nfrom OGRePy.abc import lamda, sigma WrongSchwarzschildChristoffel = T . s . Rational(1, 2) * Schwarzschild(lamda, sigma) @ (T . PartialD WrongSchwarzschildChristoffel . symbol = "Gamma" WrongSchwarzschildChristoffel . default\\_indices = (1, -1, -1) ~ WrongSchwarzschildChristoffel In [ ]:\n```  \nΓ t tr = Γ t rt = Γ r tt = Γ r rr = Γ r θθ = 2 M -r Γ r ϕϕ = (2 M -r ) sin 2 ( θ ) Γ θ r θ = Γ θ θ r = Γ ϕ r ϕ = Γ ϕ ϕ r = Γ θ ϕϕ = -Γ ϕ θϕ = Γ ϕ ϕθ = M r ( -2 M + r ) M ( -2 M + r ) r 3 M r (2 M -r ) 1 r sin (2 θ ) 2 1 tan ( θ )  \nHowever, there is a problem; as we mentioned above, the Christoffel symbols are not the components of a tensor , meaning that the Levi-Civita connection does not transform as a tensor does under a coordinate transformation. Indeed, by transforming the metric in the definition, one can show that  \nΓ λ \' μ \' ν \' = Γ λ μν + . ∂ x μ ∂ x μ \' ∂ x ν ∂ x ν \' ∂ x λ \' ∂ x λ ∂ x λ \' ∂ x λ ∂ 2 x λ ∂ x μ \' ∂ x ν \'  \nThe first term is the familiar transformation rule for a tensor, with one factor of the Jacobian per index as usual. However, there is also an extra second term, meaning that the Christoffel symbols do not transform like a tensor.  \n(Similarly, you are also not supposed to raise or lower indices in the Christoffel symbols, but in practice, you can do that as long as you make it clear that it\'s just an abuse of notation - you are only   adding   factors   of   the   metric,   not   creating   a   new   tensor   representation   with   different transformation properties.)  \nDue to the extra transformation term, the tensor object WrongSchwarzschildChristoffel we calculated   manually   above must   not   be   used !   Instead,   we   should   use   the   method  \nchristoffel() of the Metric class, which not only performs the calculation automatically for us, but also marks the result as a special tensor object with special transformation properties (more precisely, it will be an instance of the Christoffel subclass):  \n```\n~ Schwarzschild . christoffel() In [ ]:\n```  \nΓ t tr = Γ t rt = Γ r tt = Γ r rr = Γ r θθ = 2 M -r Γ r ϕϕ = (2 M -r ) sin 2 ( θ ) Γ θ r θ = Γ θ θ r = Γ ϕ r ϕ = Γ ϕ ϕ r = Γ θ ϕϕ = -Γ ϕ θϕ = Γ ϕ ϕθ = M r ( -2 M + r ) M ( -2 M + r ) r 3 M r (2 M -r ) 1 r sin (2 θ ) 2 1 tan ( θ )  \nThese are the same components we got before, but now they will transform properly. In addition, the tensor object automatically has the correct index configuration (1, -1, -1) .  \nFor maximal clarity, let us demonstrate the discrepancy in the coordinate transformation with a simple test metric:  \n```\nx, 1, 1, 1),\n```  \n```\nSimpleMetric = T . Metric( coords = Cartesian, components = T . diag( -) In [ ]:\n```  \nOut[ ]:  \ng μν ∣ ∣ ∣ ( t , x , y , z ) = ⎛ ⎜ ⎜ ⎜ ⎝ -x 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 ⎞ ⎟ ⎟ ⎟ ⎠  \nWe calculate   its   Christoffel   symbols   in   two   ways.   First   manually,   as   we   did   above   for   the Schwarzschild metric:  \n```\nWrongSimpleMetricChristoffel = T . s . Rational(1, 2) * SimpleMetric(lamda, sigma) @ (T . PartialD WrongSimpleMetricChristoffel . symbol = "Gamma" WrongSimpleMetricChristoffel . default\\_indices = (1, -1, -1) ~ WrongSimpleMetricChristoffel In [ ]:\n```  \nIn [ ]:  \nIn [ ]:  \nΓ t tx = Γ t xt = Γ x tt = 1 2 x 1 2  \nThen, with the built-in christoffel() method:  \n~ (SimpleMetricChristoffel := SimpleMetric . christoffel())  \nΓ t tx = Γ t xt = Γ x tt = 1 2 x 1 2  \nNote that in this example we used Python\'s "walrus operator" := ,   which   is   an   assignment operator   which   returns   the   result   of   the   assignment   (this   is   also   called   an   "assignment expression"). This allowed us to easily call list() on the result by prepending the ~ operator, instead of having to write an additional line.  \nThe two results have the same components, as expected. But now, let us now transform them to spherical coordinates. First, we transform the tensor object obtained using christoffel() :  \nSimpleMetricChristoffel . list(coords = Spherical)  \nΓ t tr = Γ t rt = Γ t t θ = Γ t θ t = Γ t t ϕ = Γ t ϕ t = -Γ r tt = Γ r θθ = -r Γ r ϕϕ = -r sin 2 ( θ ) Γ θ tt = Γ θ r θ = Γ θ θ r = Γ ϕ r ϕ = Γ ϕ ϕ r = Γ θ ϕϕ = -Γ ϕ tt = -Γ ϕ θϕ = Γ ϕ ϕθ = 1 2 r 1 2 tan ( θ ) tan ( ϕ ) 2 sin ( θ ) cos ( ϕ ) 2 cos ( ϕ ) cos ( θ ) 2 r 1 r sin (2 θ ) 2 sin ( ϕ ) 2 r sin ( θ ) 1 tan ( θ )  \nThis is the correct representation of the Christoffel symbols in spherical coordinates, as the extra term in the transformation was taken into account. However, if we transform the Christoffel symbols we obtained by manual calculation, we get:  \n```\nWrongSimpleMetricChristoffel . list(coords = Spherical) In [ ]:\n```  \nΓ t tr = Γ t rt = Γ t t θ = Γ t θ t = Γ t t ϕ = Γ t ϕ t = -Γ r tt = Γ θ tt = Γ ϕ tt = -1 2 r 1 2 tan ( θ ) tan ( ϕ ) 2 sin ( θ ) cos ( ϕ ) 2 cos ( ϕ ) cos ( θ ) 2 r sin ( ϕ ) 2 r sin ( θ )  \nThis is not the correct result, since the transformation did not take into account the extra term. To verify that the former result is indeed the correct one, let us change the default coordinate system of SimpleMetric to spherical:  \nSimpleMetric . default\\_coords = Spherical In [ ]:  \nNow, when we calculate the Christoffel symbols manually from this metric, we will get their correct representation in spherical coordinates. This is because OGRePy always performs the calculations internally in the default coordinates of the first tensor in any operation (e.g. A for the contraction A @ B ), so the result will be calculated from scratch in spherical coordinates, instead of being calculated first in Cartesian coordinates and then transformed:  \n```\nWrongSimpleMetricChristoffel2 = T . s . Rational(1, 2) * SimpleMetric(lamda, sigma) @ (T . PartialD WrongSimpleMetricChristoffel2 . symbol = "Gamma" WrongSimpleMetricChristoffel2 . default\\_indices = (1, -1, -1) ~ WrongSimpleMetricChristoffel2 In [ ]:\n```  \nΓ t tr = Γ t rt = Γ t t θ = Γ t θ t = Γ t t ϕ = Γ t ϕ t = -Γ r tt = Γ r θθ = -r Γ r ϕϕ = -r sin 2 ( θ ) Γ θ tt = Γ θ r θ = Γ θ θ r = Γ ϕ r ϕ = Γ ϕ ϕ r = Γ θ ϕϕ = -Γ ϕ tt = -Γ ϕ θϕ = Γ ϕ ϕθ = 1 2 r 1 2 tan ( θ ) tan ( ϕ ) 2 sin ( θ ) cos ( ϕ ) 2 cos ( ϕ ) cos ( θ ) 2 r 1 r sin (2 θ ) 2 sin ( ϕ ) 2 r sin ( θ ) 1 tan ( θ )  \nIndeed, this is the exact same result we got when we transformed SimpleMetricChristoffel to spherical coordinates. We have learned an important lesson: since the Christoffel symbols do not transform like a tensor, we should always use the built-in method christoffel() of the Metric class to calculate them, which ensures that they transform properly. (Of course, this method is also much more convenient than writing the explicit definition...)  \nFor future use, let us define the Friedmann-Lemaitre-Robertson-Walker (FLRW) metric , which describes an expanding universe:  \na\\_t = T . func("a")(t) FLRW = T . Metric( coords = Spherical, components = T . diag( -1, a\\_t ** 2, a\\_t ** 2 * r ** 2, a\\_t ** 2 * r ** 2 * T . s . sin(theta) ** 2), ) Here, is the scale factor . This metric has the line element: FLRW . line\\_element() In [ ]: Out[ ]: g μν ∣ ∣ ∣ ( t , r , θ , ϕ ) = ⎛ ⎜ ⎜ ⎜ ⎜ ⎝ -1 0 0 0 0 a 2 0 0 0 0 a 2 r 2 0 0 0 0 a 2 r 2 sin 2 ( θ ) ⎞ ⎟ ⎟ ⎟ ⎟ ⎠ a ( t ) In [ ]:  \nOut[ ]: d ϕ 2 r 2 a 2 ( t ) sin 2 ( θ ) + d θ 2 r 2 a 2 ( t ) + d r 2 a 2 ( t ) -d t 2  \nand the volume element squared:  \nFLRW . volume\\_element\\_squared() In [ ]:  \nOut[ ]: -r 4 a 6 ( t ) sin 2 ( θ )  \nIts Christoffel symbols can be easily calculated using christoffel() :  \n~ FLRW . christoffel() In [ ]:  \nΓ t rr = ∂ t aa Γ t θθ = ∂ t aar 2 Γ t ϕϕ = ∂ t aar 2 sin 2 ( θ ) Γ r tr = Γ r rt = Γ θ t θ = Γ θ θ t = Γ ϕ t ϕ = Γ ϕ ϕ t = Γ r θθ = -r Γ r ϕϕ = -r sin 2 ( θ ) Γ θ r θ = Γ θ θ r = Γ ϕ r ϕ = Γ ϕ ϕ r = Γ θ ϕϕ = -Γ ϕ θϕ = Γ ϕ ϕθ = ∂ t a a 1 r sin (2 θ ) 2 1 tan ( θ )', 'The Riemann tensor': 'The Riemann curvature tensor can be calculated from the Christoffel symbols using the definition: R ρ σμν  \nR ρ σμν = ∂ μ Γ ρ νσ -∂ ν Γ ρ μσ + Γ ρ μλ Γ λ νσ -Γ ρ νλ Γ λ μσ  \nEven though it contains partial derivatives, it nonetheless transforms like a tensor under a change of coordinates, because the extra transformation terms exactly cancel each other. To calculate this tensor, we can simply write down the formula explicitly with the correct indices contracted:  \n```\nSchwarzschild In [ ]:\n```  \n```\nSchwarzschildRiemann = ( T . PartialD(mu) @ Schwarzschild . christoffel(rho, nu, sigma) -T . PartialD(nu) @ )\n```  \n<!-- image -->  \nNotice that this time we used the christoffel() method with arguments corresponding to an index specification; this is simply a shortcut for using the () operator on the resulting tensor, as we have done above.  \nIt would be more instructive to use list() to display the components, but we should change the symbol to first, since the current symbol contain the entire formula and would be very cumbersome to display multiple times: R  \n```\nSchwarzschildRiemann . symbol = "R" ~ SchwarzschildRiemann In [ ]:\n```  \nR t t rr = R t t θθ = R r r θθ = -R θ t t θ = -R θ r r θ = -R t t ϕϕ = R r r ϕϕ = -R ϕ t t ϕ = -R ϕ r r ϕ = -R t r rt = R t θ θ t = R t ϕ ϕ t = R r t tr = R r r tt = R r θ θ r = R r ϕ ϕ r = R θ θ tt = R ϕ ϕ tt = R θ θ rr = R ϕ ϕ rr = R θ θ ϕϕ = -R ϕ θ θϕ = R θ ϕ ϕθ = -R ϕ ϕ θθ = -2 M r 2 ( -2 M + r ) M r M sin 2 ( θ ) r 2 M ( -2 M + r ) r 4 M (2 M -r ) r 4 2 M r 2 (2 M -r ) 2 M (2 M -r ) r 4 M r 2 ( -2 M + r ) M ( -2 M + r ) r 4 M r 2 (2 M -r ) 2 M sin 2 ( θ ) r 2 M r  \nHere we run into another issue: we wanted , but what we actually got was , since this is the order of indices from left to right in the definition. There are two ways to fix this in OGRePy. One is to use the permute() method. We simply need to call permute() with as the old indices and as the new indices to fix the issue: R ρ σμν R ρ μνσ μρνσ ρσμν  \nR t rtr = R t rrt = R t θ t θ = -R t θθ t = R r θ r θ = -R r θθ r = -R t ϕ t ϕ = -R t ϕϕ t = R r ϕ r ϕ = -R r ϕϕ r = -R r ttr = R r trt = R θ tt θ = R ϕ tt ϕ = R θ t θ t = R ϕ t ϕ t = R θ rr θ = R ϕ rr ϕ = R θ r θ r = R ϕ r ϕ r = R θ ϕθϕ = -R θ ϕϕθ = R ϕ θθϕ = -R ϕ θϕθ = -2 M r 2 ( -2 M + r ) 2 M r 2 (2 M -r ) M r M sin 2 ( θ ) r 2 M ( -2 M + r ) r 4 2 M (2 M -r ) r 4 M (2 M -r ) r 4 M ( -2 M + r ) r 4 M r 2 ( -2 M + r ) M r 2 (2 M -r ) 2 M sin 2 ( θ ) r 2 M r  \nNow we have obtained the correct expression for the Riemann tensor of the Schwarzschild metric. In fact, we did not have to specify the old indices explicitly; since SchwarzschildRiemann is the result of a tensor calculation, it actually remembers the index specification it obtained as a result of the calculation, and this will be used automatically if the old argument is not specified.  \nThe other way to fix this is to wrap the original calculation inside the calc() function, which is simply a convenience function that allows us to calculate a tensor, change its symbol, and permute its indices in just one function call. We will show examples of its usage below.', 'Exact sign checks with list()': "The sharp-eyed reader may have noticed that, when we used list() on the Schwarzschild Riemann tensor above, it listed, for example, the components and separately, even though they are the negatives of each other. Unfortunately, SymPy's comparison operation is very rudimentary,   comparing   the   general   structure   of   the   expression   rather   than   an   actual mathematical comparison. This can be seen on even simpler comparisons - for example, the following   comparison   will   yield False even   though   the   two   expressions   are   clearly mathematically equal: R t rtr R t rrt  \nexpr1 = 1 / (1 -x) expr2 = -(1 / (x -1)) expr1 == expr2 In [ ]:  \nFalse Out[ ]:  \nThis can be resolved by noticing that if   and   only   if .   So   if   we   subtract   one expression from the other, simplify the result, and compare to zero, we will get a correct answer: a = b a -b = 0  \nIn [ ]:  \nT . s . simplify(expr1 -expr2) == 0  \nTrue Out[ ]:  \nNormally, list() doesn't do this for every single component of the tensor, since that could be a very time-consuming task for large tensors with complicated components. However, we could ask list() to perform these more precise comparisons by adding the exact=True option:  \nSchwarzschildRiemann . list(exact =True ) In [ ]:  \nR t rtr = -R t rrt = R t θ t θ = -R t θθ t = R r θ r θ = -R r θθ r = -R t ϕ t ϕ = -R t ϕϕ t = R r ϕ r ϕ = -R r ϕϕ r = -R r ttr = -R r trt = R θ tt θ = -R θ t θ t = R ϕ tt ϕ = -R ϕ t ϕ t = R θ rr θ = -R θ r θ r = R ϕ rr ϕ = -R ϕ r ϕ r = R θ ϕθϕ = -R θ ϕϕθ = R ϕ θθϕ = -R ϕ θϕθ = -2 M r 2 ( -2 M + r ) M r M sin 2 ( θ ) r 2 M ( -2 M + r ) r 4 M (2 M -r ) r 4 M r 2 ( -2 M + r ) 2 M sin 2 ( θ ) r 2 M r  \nYou can see that now list() correctly identifies all of the components that are negatives of each other, resulting in a much shorter list. If you're wondering why this option only applies to comparing components that are the negative of each other, rather than all comparison - that is because OGRePy automatically simplifies all tensor components in advance, so if two components are the same, they should already be simplified to the exact same expression.  \nThe Riemann tensor with all its indices   lowered   satisfies   the   following   symmetry   and   antisymmetry relations:  \nR ρσμν = -R σρμν = -R ρσνμ = R μνρσ  \nIn [ ]:", 'SchwarzschildRiemann . list(indices = ( -1, -1, -1, -1), exact =True )': 'R trtr = -R trrt = -R rttr = R rtrt = -R t θ t θ = -R t θθ t = -R θ tt θ = R θ t θ t = R t ϕ t ϕ = -R t ϕϕ t = -R ϕ tt ϕ = R ϕ t ϕ t = R r θ r θ = -R r θθ r = -R θ rr θ = R θ r θ r = R r ϕ r ϕ = -R r ϕϕ r = -R ϕ rr ϕ = R ϕ r ϕ r = R θϕθϕ = -R θϕϕθ = -R ϕθθϕ = R ϕθϕθ = 2 Mr sin 2 ( θ ) 2 M r 3 M ( -2 M + r ) r 2 M ( -2 M + r ) sin 2 ( θ ) r 2 M 2 M -r M sin 2 ( θ ) 2 M -r  \nThis shows that the symmetry and anti-symmetry relations are indeed satisfied.', 'The riemann() method and caching': "Don't worry - you don't need to write the explicit definition of the Riemann tensor every time you want to calculate it. Instead, OGRePy offers the method riemann() of the Metric class. For example, for the FLRW metric we get:  \nFLRW . riemann() . list(exact =True ) In [ ]:  \nR t rtr = -R t rrt = -R t θ t θ = -R t θθ t = -R t ϕ t ϕ = -R t ϕϕ t = -R r ttr = -R r trt = -R θ tt θ = -R θ t θ t R r θ r θ = -R r θθ R r ϕ r ϕ = -R r ϕϕ R θ rr θ = -R θ r θ  \nNotice two things here. First, we did not save the result in a variable. The reason is that the results of the riemann() method, and in fact all similar methods such as christoffel() , are cached. This means that the next time we call FLRW.riemann() ,   we will get the exact same tensor indeed, it won't just be another tensor with the same components, it will be a reference to the exact same object we got the first time.  \nSecond, calculating the Riemann tensor requires first calculating the Christoffel symbols, which we did not do. Behind the scenes, the riemann() method obtains the Christoffel symbols by calling the christoffel() method. In turn, the christoffel() checks if the Christoffel symbols have already been calculated. If so, it returns the cached results, and if not, it calculated, caches, and returns the results.  \nAs a result, even though we did not call FLRW.christoffel() before, the Christoffel symbols have in fact already been calculated and cached for us, so if we call it now we will get the result immediately:  \n~ FLRW . In [ ]:  \n```\nchristoffel()\n```  \nΓ t rr = ∂ t aa Γ t θθ = ∂ t aar 2 Γ t ϕϕ = ∂ t aar 2 sin 2 ( θ ) Γ r tr = Γ r rt = Γ θ t θ = Γ θ θ t = Γ ϕ t ϕ = Γ ϕ ϕ t = Γ r θθ = -r Γ r ϕϕ = -r sin 2 ( θ ) Γ θ r θ = Γ θ θ r = Γ ϕ r ϕ = Γ ϕ ϕ r = Γ θ ϕϕ = -Γ ϕ θϕ = Γ ϕ ϕθ = ∂ t a a 1 r sin (2 θ ) 2 1 tan ( θ )  \nThe same principle also applies to the other built-in methods for calculating curvature tensors, which we will present below; they always calculate and cache any intermediate tensors in their definitions automatically as needed.  \nStandard practice when using OGRePy is to never save the Christoffel symbols, Riemann tensor, etc. in their own variables. Instead, you must call the christoffel() , riemann() , etc. methods every time you want to access these tensors.  \nThe reason behind this is to maintain consistency between the metric and its curvature tensors. For example, let's say we decided to redefine the FLRW metric. Since tensor components in OGRePy are immutable, meaning they cannot be changed after the tensor object is created, this means we actually create a new Metric object and save it in the same FLRW variable. If we previously   calculated   the   Christoffel   symbols   and   saved   them   in   a   variable   called FLRWChristoffel , that variable now stores the Christoffel symbols for the old FLRW metric, and is   therefore   inconsistent   with   the   new   one.   On   the   other   hand,   if   we   simply   use   the FLRW.christoffel() method, we are guaranteed to always get the correct Christoffel symbols for the metric stored in the FLRW variable.  \nIn this documentation, we will continue to create variables for curvature tensors because we will be calculating them explicitly and therefore they are not cached, but in normal use you should instead simply rely on OGRePy's comprehensive caching algorithms.", 'The Kretschmann scalar': 'The Kretschmann scalar is a curvature invariant calculated by contracting all the indices of the  \nIn [ ]:  \nOut[ ]:  \nRiemann tensor with itself:  \nK = R ρσνμ R ρσνμ .  \nRecall that above, we gave the Kretschmann scalar for the Schwarzschild metric as an example of a scalar. Now that we have the Riemann tensor, and the ability to contract tensors, we can actually calculate the Kretschmann scalar from scratch:  \nSchwarzschild . riemann(rho, sigma, mu, nu) @ Schwarzschild . riemann(rho, sigma, mu, nu)  \nR μνρσ R μνρσ ∣ ∣ ∣ ( t , r , θ , ϕ ) = 48 M 2 r 6  \nNote that like the christoffel() method, the riemann() method allows you to pass an index specification for use in calculations. As usual, OGRePy allows you to calculate this curvature tensor directly, using the method kretschmann() of the Metric class,   without typing the formula explicitly.  \nThis method follows the same caching algorithm as christoffel() and riemann() :   it   will calculate the Riemann tensor (and as a side effect, the Christoffel symbols) if they have not already been calculated, otherwise it will use the cached results, and it will cache its own result for later use.', 'The Ricci tensor and scalar': 'The Ricci tensor is the trace of the first and third indices of the Riemann tensor: R μν  \nR μν = R λ μλν .  \nTherefore,   we   can   calculate   it   by   taking   the   trace,   with   the   usual   OGRePy   syntax.   For   the Schwarzschild metric, the Ricci tensor vanishes:  \n~ Schwarzschild . In [ ]:  \n```\nriemann(lamda, mu, lamda, nu)\n```  \nNo non-zero elements.  \nWe can also use the convenience method ricci\\_tensor() of the Metric class. For example, here is the Ricci tensor for the FLRW metric:  \n~ FLRW . In [ ]:  \n```\nricci\\_tensor()\n```  \nR tt = -R rr = 2 ∂ t a 2 + a ∂ t a R θθ = r 2 ( 2 ∂ t a 2 + a ∂ t a ) R ϕϕ = r 2 ( 2 ∂ t a 2 + a ∂ t a ) sin 2 ( θ ) 3 ∂ t a d d t a d d t d d t d d t  \nThe Ricci scalar is the trace of the Ricci tensor:  \nR = R λ λ = g μν R μν  \nWe can calculate it from the Ricci tensor by taking the trace:  \nFLRW . ricci\\_tensor(mu, mu) In [ ]:  \nOut[ ]:  \nR μ μ ∣ ∣ ∣ ( t , r , θ , ϕ ) = 6 ( ∂ t a 2 + a ∂ t a ) d d t a 2  \nOr, as usual, we can simply use the shorthand method ricci\\_scalar() to calculate it directly from the metric:  \nFLRW . ricci\\_scalar() In [ ]:  \nOut[ ]:  \nR ∣ ∣ ∣ ( t , r , θ , ϕ ) = 6 ( ∂ t a 2 + a ∂ t a ) d d t a 2', 'The Einstein tensor': 'The Einstein tensor is given by: G μν  \nG μν = R μν -Rg μν . 1 2  \nAs with all other curvature tensors, we can calculate it by combining the previously calculated tensors with the usual syntax:  \n~ (FLRW . ricci\\_tensor(mu, nu) -T . s . Rational(1, 2) * FLRW . ricci\\_scalar() @ FLRW(mu, nu)) In [ ]:  \nR tt -Rg tt = R rr -Rg rr = -∂ t a 2 -2 a ∂ t a R θθ -Rg θθ = r 2 ( -∂ t a 2 -2 a ∂ t a ) R ϕϕ -Rg ϕϕ = r 2 ( -∂ t a 2 -2 a ∂ t a ) sin 2 ( θ ) 1 2 3 ∂ t a 2 a 2 1 2 d d t 1 2 d d t 1 2 d d t  \nOr we can use the built-in module einstein() :  \n~ FLRW . einstein() In [ ]:  \nG tt = G rr = -∂ t a 2 -2 a ∂ t a G θθ = r 2 ( -∂ t a 2 -2 a ∂ t a ) G ϕϕ = r 2 ( -∂ t a 2 -2 a ∂ t a ) sin 2 ( θ ) 3 ∂ t a 2 a 2 d d t d d t d d t', 'Covariant derivatives': 'The partial derivative has limited use in general relativity, as it does not transform like a tensor . Therefore, it is only used in special cases, such as calculating the Christoffel symbols and the Riemann tensor. The covariant derivative is a generalization of the partial derivative, which does transform like a tensor (as long as it acts on a proper tensor). It is defined as follows: ∇ μ  \n- · On a scalar , the covariant derivative acts as . Φ ∇ μ Φ = ∂ μ Φ\n- · On a vector , the covariant derivative acts as . v μ ∇ μ v ν = ∂ μ v ν + Γ ν μλ v λ\n- · On a covector , the covariant derivative acts as . w μ ∇ μ w ν = ∂ μ w ν -Γ λ μν w λ  \nMore generally, on a rank tensor with components , the covariant derivative is defined as follows: ( p , q ) T ν 1 ⋯ ν p σ 1 ⋯ σ q ∇ μ T ν 1 ⋯ ν p σ 1 ⋯ σ q  \n- · The first term will be the partial derivative . ∂ μ T ν 1 ⋯ ν p σ 1 ⋯ σ q\n- · We add one term for each upper index . Γ ν i μλ T ν 1 ⋯ λ ⋯ ν p σ 1 ⋯ σ q ν i\n- · We subtract one term for each lower index . Γ λ μσ i T ν 1 ⋯ ν p σ 1 ⋯ λ ⋯ σ q σ i  \nNote that even though the covariant derivative is made from ingredients that do not transform like tensors - the partial derivative and the Christoffel symbols - the unwanted terms in the transformations of these ingredients cancel each other exactly, so that in the end, the entire sum does transform like a tensor.  \nAs usual, we can, of course, write down the covariant derivative manually. For example, the covariant divergence of the metric is:  \n∇ μ g αβ = ∂ μ g αβ -Γ λ μα g λβ -Γ λ μβ g αλ .  \nIt should vanish, by definition, for any metric; this is what we meant when we said the Levi-Civita connection preserves the metric. Indeed, we have for the Schwarzschild metric:  \nfrom OGRePy.abc import alpha, beta ~ (T . PartialD(mu) @ Schwarzschild(alpha, beta) -Schwarzschild . christoffel(lamda, mu, alpha In [ ]:  \nNo non-zero elements.  \nMuch more conveniently, the covariant derivative is represented in OGRePy using the class CovariantD .   It   will   automatically   add   the   correct   terms,   as   detailed   above,   for   each   of   the tensor\'s indices, using the (possibly cached) Christoffel symbols of the tensor\'s associated metric. To use it, simply contract it with any tensor, just like PartialD . For example, we can check that the covariant derivative of the FLRW metric also vanishes:  \n~ (T . CovariantD(mu) @ In [ ]:  \nFLRW(mu, nu))  \nNo non-zero elements.  \nThe covariant divergence of the Einstein tensor is:  \n∇ μ G μν = ∂ μ G μν + Γ μ μλ G λν + Γ ν μλ G μλ .  \nNote that it involves a contraction in the index , which becomes a trace in the first Christoffel symbol. This expression vanishes because of the Bianchi identity : μ  \n∇ μ R μν = ∇ ν R ⟹ ∇ μ G μν = 0. 1 2  \nTo calculate it in OGRePy, we simply write:  \n~ (T . CovariantD(mu) @ FLRW . In [ ]:  \neinstein(mu, nu))  \nNo non-zero elements.  \nFinally, for a non-trivial result, let us recall that the stress-energy tensor should be conserved :  \n∇ μ T μν = ∂ μ T μν + Γ μ μλ T λν + Γ ν μλ T μλ = 0.  \nThis follows from the fact that , combined with the Einstein equation : ∇ μ G μν = 0  \nG μν = κ T μν ,  \nwhere and is   Newton\'s gravitational constant. However, unlike ,   the relation is not an identity; it is an energy-momentum conservation equation .   To derive the equation for the FLRW metric, let us first define the rest-frame fluid 4-velocity in this spacetime: κ = 8 π G G ∇ μ G μν = 0 ∇ μ T μν = 0  \n```\nRestVelocity = T . Tensor(metric = FLRW, coords = Spherical, indices = (1,), components = [1, 0, 0 In [ ]: Out[ ]:\n```  \nu μ ∣ ∣ ∣ ( t , r , θ , ϕ ) = ⎛ ⎜ ⎜ ⎜ ⎝ 1 0 0 0 ⎞ ⎟ ⎟ ⎟ ⎠  \nUsing the 4-velocity and the metric, we redefine the perfect fluid stress tensor in the FLRW spacetime   using   the   formula ,   and   give and spacetime dependence: T μν = ( ρ + p ) u μ u ν + pg μν ρ p  \n```\nrho\\_t\\_r\\_t\\_p = T . func("rho")(t, r, theta, phi) p\\_t\\_r\\_t\\_p = T . func("p")(t, r, theta, phi) PerfectFluidFLRW = T . calc( formula = (rho\\_t\\_r\\_t\\_p + p\\_t\\_r\\_t\\_p) * RestVelocity(mu) @ RestVelocity(nu) + p\\_t\\_r\\_t\\_p symbol = "T", ) In [ ]:\n```  \nOut[ ]:  \nT μν ∣ ∣ ∣ ( t , r , θ , ϕ ) = ⎛ ⎜ ⎜ ⎜ ⎜ ⎜ ⎜ ⎝ ρ ( t , r , θ , ϕ ) 0 0 0 0 0 0 0 0 0 0 0 0 ⎞ ⎟ ⎟ ⎟ ⎟ ⎟ ⎟ ⎠ p a 2 p a 2 r 2 p a 2 r 2 sin 2 ( θ )  \nFinally, we take the covariant derivative of the stress tensor:  \n~ (T . CovariantD(mu) @ In [ ]:  \n```\nPerfectFluidFLRW(mu, nu))\n```  \n∇ μ T μ t = ∇ μ T μ r = ∇ μ T μθ = ∇ μ T μϕ = ∂ t ρ ( t , r , θ , ϕ ) a +3 ∂ t a ( p + ρ ( t , r , θ , ϕ )) a ∂ r p a 2 ∂ θ p a 2 r 2 ∂ ϕ p a 2 r 2 sin 2 ( θ )  \nFrom demanding that the   component vanishes, we get the following equation: t  \n˙ ρ = -3( ρ + p ) . ˙ a a  \nWe see that in an expanding universe, energy is not conserved, but rather, the energy density changes with time in a way that depends on the scale factor. If the universe is not expanding, that is, , then energy will be conserved. ˙ a = 0', 'The curve Lagrangian': 'Consider a curve ,   which   is   a   function on   the   manifold   where is   called   the curve parameter . The curve Lagrangian of a metric is defined as the norm-squared of the tangent to the curve: x μ ( λ ) λ  \nL = g μν ˙ x μ ˙ x ν ,  \nwhere is   the   first   derivative of with respect to the curve parameter (in   Newton dot notation). We can calculate it using the method lagrangian() of   the Metric class.   For example: ˙ x μ x μ λ  \nMinkowski . lagrangian() In [ ]:  \nOut[ ]:  \nSchwarzschild . lagrangian() In [ ]:  \nOut[ ]:  \nL ∣ ∣ ∣ ( t , r , θ , ϕ ) = -˙ r 2 r 2 + ˙ t 2 (2 M -r ) 2 + r 3 (2 M -r ) ( ˙ ϕ 2 sin 2 ( θ ) + ˙ θ 2 ) r (2 M -r )  \nFLRW . lagrangian() In [ ]:  \nOut[ ]:  \nL ∣ ∣ ∣ ( t , r , θ , ϕ ) = ˙ ϕ 2 a 2 r 2 sin 2 ( θ ) + ˙ θ 2 a 2 r 2 + ˙ r 2 a 2 -˙ t 2  \nAlcubierre . lagrangian() In [ ]:  \nOut[ ]:  \nL ∣ ∣ ∣ ( t , x , y , z ) = ˙ t 2 ( f 2 v 2 -1 ) -2 ˙ t ˙ zfv + ˙ x 2 + ˙ y 2 + ˙ z 2  \nNotice how show() (and list() as well) use Newton dot notation for the derivatives of the  \nL ∣ ∣ ∣ ( t , x , y , z ) = -˙ t 2 + ˙ x 2 + ˙ y 2 + ˙ z 2  \nIn [ ]:  \ncoordinate   functions,   for   improved   readability.   To   get   the   full   expressions   with   the   explicit derivatives, we can use components() . For example:  \nMinkowski . lagrangian() . components()  \nOGRePy : Using default coordinate system Cartesian and default index configuration ().  \nOut[ ]: [ -( t ( λ ) ) 2 + ( x ( λ ) ) 2 + ( y ( λ ) ) 2 + ( z ( λ ) ) 2 ] d d λ d d λ d d λ d d λ', 'Geodesic equations from the Lagrangian': "By applying the Euler-Lagrange equations to the curve Lagrangian:  \n( ) -= 0, d d λ ∂ L ∂˙ x μ ∂ L ∂ x μ  \nwe can obtain  the   geodesic   equations   for   our   spacetime.   This   is   done   using   the   method geodesic\\_from\\_lagrangian() of the Metric class. For the Minkowski metric, the geodesic equations are:  \n~ Minkowski . geodesic\\_from\\_lagrangian() In [ ]:  \n0 t = -∂ λ ( -˙ t ) 0 x = -x 0 y = -y 0 z = -z  \nNote that this method only calculates the left-hand side of the Euler-Lagrange equations; if we equate the result to zero, we will get the actual geodesics equations. This is hinted at visually by setting the resulting tensor's symbol to 0, so that you actually see the equations when using list() . It is trivial to see that the solution to these equations is simply a curve with a constant velocity; in a flat Minkowski spacetime, particles experience no gravitational force, and thus no acceleration (unless some other force acts on them, of course).  \nThe derivatives with respect to the curve parameter are kept unevaluated in the output of geodesic\\_from\\_lagrangian() ,   by   using   the   SymPy Derivative class   and   passing doit=False to simplify() . This simplifies the equations, and can sometimes help solve them by inspection. In this simple example, since SymPy simplifies the second derivatives even if doit=False is used, the second derivatives are actually evaluated (except from the first one, due to the minus sign), but in more complicated metrics they will remain unevaluated. λ  \nIf we want to activate the derivatives, we simply need to apply the doit() method to them. Recall that list() and show() can   apply   a   function   to   the   tensor's   components   before displaying them, so we just need to pass a lambda function that executes the doit() method on each component:  \n0 t = t 0 x = -x 0 y = -y 0 z = -z  \nNow the derivatives have been activated.  \nAs with the Lagrangian itself, the geodesic equations are displayed in compact notation when using list() . If we want the full expressions with the explicit derivatives, for example in order to pass  them   to dsolve() and   actually   solve   the   equations,   we   can   use components() -remembering to apply doit() to activate the derivatives:  \nMinkowski . geodesic\\_from\\_lagrangian() . components() . doit() In [ ]:  \nOGRePy : Using default coordinate system Cartesian and default index configuration (1,).  \nOut[ ]: [ t ( λ ) -x ( λ ) -y ( λ ) -z ( λ ) ] d 2 d λ 2 d 2 d λ 2 d 2 d λ 2 d 2 d λ 2  \nThis is a SymPy Array where each of the 4 components is a differential equation (with assumed). It can be easily solved by passing it to SymPy's dsolve() : = 0  \nT . s . Array(T . s . dsolve(Minkowski . geodesic\\_from\\_lagrangian() . components() . doit())) In [ ]:  \nOGRePy : Using default coordinate system Cartesian and default index configuration (1,).  \nOut[ ]: [ t ( λ ) = C 1 + C 2 λ x ( λ ) = C 3 + C 4 λ y ( λ ) = C 5 + C 6 λ z ( λ ) = C 7 + C 8 λ ]  \nNote that this will return a list of solutions, so we converted it back to a SymPy Array so it will be displayed nicely in the notebook.  \nWe can similarly find the geodesic equations of other metrics. For example, here they are for the Schwarzschild metric:  \n~ Schwarzschild . geodesic\\_from\\_lagrangian() In [ ]:  \n(  \n0 t = -∂ λ ( ) 0 r = ) ˙ t (2 M -r ) r -4 M 3 ˙ t 2 +4 M 2 ˙ ϕ 2 r 3 sin 2 ( θ ) + 4 M 2 ˙ θ 2 r 3 +4 M 2 ˙ t 2 r -4 M 2 ∂ λ ( -) r 2 -4 M ˙ ϕ 2 r 4 sin 2 -∂ λ ( -) r 4 ˙ rr 2 M -r ˙ rr 2 M -r r 2 (4 M 2 -4 Mr + 2  \n0 θ = -∂ λ ( ˙ θ r 2 0 ϕ = -∂ λ ( ˙ ϕ r 2 sin 2 ( θ ) ) ˙ ϕ r 2 sin (2 θ ) 2  \n(Note that the   component is very long, ugly, and complicated. In the Mathematica version of OGRe, we get a much shorter and nicer expression, but if the two expressions are compared by exporting this expression from SymPy to Mathematica (which can be done using the mathematica() method), it turns out that the SymPy expression is in fact correct, just not simplified properly. This appears to be an issue with SymPy's simplify() function, but it could perhaps be resolved by using specific SymPy simplification functions, and it is possible that in the future SymPy's simplification algorithms will improve.) r  \nAs another example, here are the geodesic equations for the FLRW metric:  \n~ FLRW . geodesic\\_from\\_lagrangian() In [ ]:  \n0 t = ˙ ϕ 2 ∂ t aar 2 sin 2 ( θ ) + ˙ θ 2 ∂ t aar 2 + ˙ r 2 ∂ t aa -∂ λ ( -˙ t ) 0 r = ˙ ϕ 2 a 2 r sin 2 ( θ ) + ˙ θ 2 a 2 r -∂ λ ( ˙ ra 2 ) 0 θ = -∂ λ ( ˙ θ a 2 r 2 ) 0 ϕ = -∂ λ ( ˙ ϕ a 2 r 2 sin 2 ( θ ) ) ˙ ϕ 2 a 2 r 2 sin (2 θ ) 2  \nAnd finally, here they are for the Alcubierre metric:  \n~ Alcubierre . geodesic\\_from\\_lagrangian() In [ ]:  \n0 t = ˙ t 2 fv ( ∂ t fv + ∂ t vf ) -˙ t ˙ z ∂ t fv -˙ t ˙ z ∂ t vf -∂ λ ( ˙ t ( f 2 v 2 -1 ) - ˙ zfv ) 0 x = -x + ˙ t 2 ∂ x ffv 2 -˙ t ˙ z ∂ x fv 0 y = -y + ˙ t 2 ∂ y ffv 2 -˙ t ˙ z ∂ y fv 0 z = ˙ t 2 ∂ z ffv 2 -˙ t ˙ z ∂ z fv -∂ λ ( -˙ t fv + ˙ z )  \nThe latter is a good example of how we can solve the geodesic equations by inspection. Indeed, it is easy to see that  \n˙ x μ = (1, 0, 0, vf )  \nis a solution to this system of equations, since then we have and , and both terms in each equation vanish (the last term in the first equation will reduce to , which is of course zero). We can check this solution by replacing the coordinate functions with their solutions; since we will be left with in the first equation, we must also activate the derivative. ˙ x = ˙ y = 0 ( fv ˙ t - ˙ z ) = 0 ∂ λ ( -1) ∂ λ ( -1)  \nHowever, for this we have to write the coordinates explicitly as functions of the curve parameter, even when they are arguments of a function; for example, should be instead be . Luckily, OGRePy offers several ways to simplify this process. The Coordinates class contains the method of\\_param() , which returns the coordinates as functions of the curve parameter: v ( t ) v ( t ( λ ))  \n```\nCartesian . of\\_param() [t(\\lambda), x(\\lambda), y(\\lambda), z(\\lambda)] However, what we really want is an easy way to replace the coordinates with functions of the curve   parameter.   We   can   obtain   a   list   of   such   replacements   using   the   method of\\_param\\_dict() : param = Cartesian . of\\_param\\_dict() {t: t(\\lambda), x: x(\\lambda), y: y(\\lambda), z: z(\\lambda)} Similarly, of\\_param\\_dot() returns the first derivatives of the coordinates: Cartesian . of\\_param\\_dot() [Derivative(t(\\lambda), \\lambda), Derivative(x(\\lambda), \\lambda), Derivative(y(\\lambda), \\lambda), Derivative(z(\\lambda), \\lambda)] But   again,   what   we   really   want   is   a   dictionary   of   replacements,   obtained   using of\\_param\\_dot\\_dict() : dot = Cartesian . of\\_param\\_dot\\_dict() {t: Derivative(t(\\lambda), \\lambda), x: Derivative(x(\\lambda), \\lambda), y: Derivative(y(\\lambda), \\lambda), z: Derivative(z(\\lambda), \\lambda)} We can now use the param dictionary as an argument to the subs() method to replace the arguments in the function   and  : display(v\\_t . subs(param)) display(f\\_t\\_x\\_y\\_z . subs(param)) In [ ]: Out[ ]: In [ ]: Out[ ]: In [ ]: Out[ ]: In [ ]: Out[ ]: v f In [ ]: v ( t ( λ ))\n```  \nf ( t ( λ ), x ( λ ), y ( λ ), z ( λ ))  \nThe explicit solution is given by  \n```\n˙ t ( λ ) = 1, ˙ x ( λ ) = 0, ˙ y ( λ ) = 0, ˙ z ( λ ) = v ( t ( λ )) × f ( t ( λ ), x ( λ ), y ( λ ), z ( λ )).\n```  \nLet us define a dictionary of replacements which maps each derivative of the coordinates to its solution:  \n```\nsolution = {dot[t]: 1, dot[x]: 0, dot[y]: 0, dot[z]: v\\_t . subs(param) * f\\_t\\_x\\_y\\_z . subs(param {Derivative(t(\\lambda), \\lambda): 1, Derivative(x(\\lambda), \\lambda): 0, Derivative(y(\\lambda), \\lambda): 0, Derivative(z(\\lambda), \\lambda): f(t(\\lambda), x(\\lambda), y(\\lambda), z(\\lambda))*v(t (\\lambda))} Now all we need to do is perform these substitution, and then simplify. We can do this by passing ,   and   setting will also In [ ]: Out[ ]:\n```  \nthe   dictionary   as   the   value   of   the replace argument   to   instruct list() simplify=True to the expression after doing the replacement. Note that simplify() automatically call doit() to evaluate the derivatives with respect to : λ  \n```\nAlcubierre . geodesic\\_from\\_lagrangian() . list(replace = solution, simplify =True In [ ]:\n```  \n```\n)\n```  \nNo non-zero elements.  \nSince   this   solution   zeros   all   the   elements,   it   must   be   the   correct   solution   to   the   geodesic equations. We could use a substitution procedure similar to the one we used here to verify solutions to any geodesic equations.  \nThis solution indicates that we are traveling with velocity in the direction; the warp bubble (inside which, as you recall, ) moves whatever is inside it, such as a spaceship, through space at the velocity  , but there is no limit on   - it can even be faster than light! v z f = 1 v v", 'Geodesic equations from the Christoffel symbols': 'Another way of obtaining the geodesic equations is using the covariant derivative, and thus the Christoffel symbols:  \n˙ x ρ ∇ ρ ˙ x σ = 0 ⟹ x σ + Γ σ μν ˙ x μ ˙ x ν = 0.  \nIn   OGRePy,   we   can   calculate   the   left-hand   side   of   this   equation   using   the geodesic\\_from\\_christoffel() method of the Metric class. For example:', '~ Schwarzschild . geodesic\\_from\\_christoffel()': '~ FLRW . geodesic\\_from\\_christoffel()  \n~ Alcubierre . geodesic\\_from\\_christoffel()  \n0 t = t  \n0 x = x  \n0 y = y  \n0 z = z  \n0 t = -2 M ˙ r ˙ t + t r (2 M -r ) r (2 M -r )  \n0 r = M ˙ r 2 r 2 -M ˙ t 2 (2 M -r ) 2 + r 3 (2 M -r ) ( r + ˙ ϕ 2 (2 M -r ) sin 2 ( θ ) + ˙ θ 2 (2 M -r ) ) r 3 (2 M -r )  \n2  \n0 θ = ¨ θ -+ 0 ϕ = ¨ ϕ + + ˙ ϕ sin (2 θ ) 2 2 ˙ θ ˙ r r 2 ˙ ϕ ˙ θ tan ( θ ) 2 ˙ ϕ ˙ r r  \n0 t = t + ˙ ϕ 2 ∂ t aar 2 sin 2 ( θ ) + ˙ θ 2 ∂ t aar 2 + ˙ r 2 ∂ t aa 0 r = r -˙ ϕ 2 r sin 2 ( θ ) -˙ θ 2 r + 0 θ = ¨ θ -+ + 0 ϕ = ¨ ϕ + + + 2 ˙ r ˙ t ∂ t a a ˙ ϕ 2 sin (2 θ ) 2 2 ˙ θ ˙ r r 2 ˙ θ ˙ t ∂ t a a 2 ˙ ϕ ˙ θ tan ( θ ) 2 ˙ ϕ ˙ r r 2 ˙ ϕ ˙ t ∂ t a a  \n0 t = t + ˙ t 2 ∂ z ff 2 v 3 -˙ t ˙ x ∂ x ffv 2 -˙ t ˙ y ∂ y ffv 2 -2 ˙ t ˙ z ∂ z ffv 2 + ˙ x ˙ z ∂ x fv + ˙ y ˙ z ∂ y fv + ˙ z 2 ∂ z fv  \n0 x = x -˙ t 2 ∂ x ffv 2 + ˙ t ˙ z ∂ x fv  \n0 y = y -˙ t 2 ∂ y ffv 2 + ˙ t ˙ z ∂ y fv  \n0 z = z + ˙ t 2 ( -∂ t fv -∂ t vf + ∂ z ff 3 v 4 -∂ z ffv 2 ) -˙ t ˙ x ∂ x fv ( f 2 v 2 +1 ) -˙ t ˙ y ∂ y fv ( f 2 v 2 +1 ) -2 ˙ t  \nOften, you will find that the Lagrangian method produces simpler equations, which can even be solved by inspection, as we did for the Alcubierre metric. This is due to the possibility of leaving the derivative unevaluated. However, in other cases, the Christoffel method might produce simpler   equations.   We   can   clearly   see   that   by   comparing   the   geodesics   equations   for   the Schwarzschild metric obtained via the Lagrangian vs. Christoffel methods. λ  \nThe best thing to do is to try both methods and see which one produces simpler or nicer results for   the   specific   metric   in   question.   Note   that   the   system   of   equations   obtained   using geodesic\\_from\\_lagrangian() will   often   be   different   from   the   one   obtained   using geodesic\\_from\\_christoffel() , but both systems will always have the same solutions.', 'Geodesics equations in terms of the time coordinate': 'If the metric is a spacetime metric, it is often convenient to obtain the geodesic equations in terms of the time parameter, instead of an affine curve parameter. It can be shown that the geodesic equations in terms of the time coordinate are given by  \n+ ( Γ σ μν -Γ 0 μν ) = 0, d 2 x σ d t 2 d x σ d t d x μ d t d x ν d t  \nwhere we are assuming the time coordinate is   and it is the first (zero) coordinate. These equations can be obtained using the geodesic\\_time\\_param() method of the Metric class. Note that geodesic\\_time\\_param() assumes time is the first coordinate, but the coordinate does not need to have the symbol  . As an example, the equations for the FLRW metric in Cartesian coordinates in terms of a curve parameter are: t t  \nFLRW . geodesic\\_from\\_christoffel() . list(coords = Cartesian) In [ ]:  \n0 t = t + ˙ x 2 ∂ t aa + ˙ y 2 ∂ t aa + ˙ z 2 ∂ t aa 0 x = x + 0 y = y + 0 z = z + 2 ˙ t ˙ x ∂ t a a 2 ˙ t ˙ y ∂ t a a 2 ˙ t ˙ z ∂ t a a  \nBut in terms of  , we only need 3 equations: t  \nFLRW . geodesic\\_time\\_param() . list(coords = Cartesian) In [ ]:  \n0 x = x - ˙ x 3 ∂ t ( a ) a - ˙ x ˙ y 2 ∂ t ( a ) a - ˙ x ˙ z 2 ∂ t ( a ) a + 0 y = y - ˙ x 2 ˙ y ∂ t ( a ) a - ˙ y 3 ∂ t ( a ) a - ˙ y ˙ z 2 ∂ t ( a ) a + 0 z = z - ˙ x 2 ˙ z ∂ t ( a ) a - ˙ y 2 ˙ z ∂ t ( a ) a - ˙ z 3 ∂ t ( a ) a + 2 ˙ x ∂ t ( a ) a 2 ˙ y ∂ t ( a ) a 2 ˙ z ∂ t ( a ) a  \nThese equations are easier to solve. For simplicity, assume that we are only moving along the x coordinate. Then we only have one equation to solve:  \nFLRW\\_eq = FLRW . geodesic\\_time\\_param() . components(coords = Cartesian, indices = (1,))[1] In [ ]: Out[ ]: 2  \n-a ( t ) a ( t ) ( x ( t ) ) 3 -a ( t ) a ( t ) x ( t ) ( y ( t ) ) 2 -a ( t ) a ( t ) x ( t ) ( z ( t ) ) 2 + x ( t ) + d dt d dt d dt d dt d dt d dt d dt d dt d 2 dt 2  \nWe are assuming that , so let us remove them from the equation. First, let us get ˙ y ( t ) = ˙ z ( t ) = 0  \ndictionaries mapping the coordinates to functions of time. This is identical to what we did above for the Alcubierre metric, except that this time we pass   to the of\\_param functions so we get functions of   instead of : t t λ  \nparam = Cartesian . of\\_param\\_dict(t) In [ ]:  \n{t: t(t), x: x(t), y: y(t), z: z(t)} Out[ ]:  \ndot = Cartesian . of\\_param\\_dot\\_dict(t) In [ ]:  \nOut[ ]:  \n{t: Derivative(t(t), t),  \nx: Derivative(x(t), t),  \ny: Derivative(y(t), t),  \nz: Derivative(z(t), t)}  \nIf we now substitute in the equation, it simplifies considerably: ˙ y ( t ) = ˙ z ( t ) = 0  \nFLRW\\_eq . subs({dot[y]: 0, dot[z]: 0}) In [ ]:  \nOut[ ]: -a ( t ) a ( t ) ( x ( t ) ) 3 + x ( t ) + d dt d dt d 2 dt 2 2 a ( t ) x ( t ) d dt d dt a ( t )  \nThe solution can be obtained using dsolve() in terms of an integral over , passing in the second argument as the function to solve for. The command to do that is all\\_solutions = T.s.Array(T.s.dsolve(FLRWEq.subs({dot[y]: 0, dot[z]: 0}), param[x])) ,   but   I   did not include it in the notebook because it takes a very long time to run. The solution found by SymPy is (after some beautification): a ( t ) x ( t )  \nx ( t ) = C 1 ± ∫ d t 1 a ( t ) √ 1 + C 2 a 2 ( t )  \nWe can use the rhs property to obtain the right-hand side of the equation, selecting the positive solution (at position 1 of the array): all\\_solutions[1].rhs .   By   taking   the   derivative   with respect to  , all\\_solutions[1].rhs.diff(t) , we can get the coordinate velocity along  : t ˙ x x  \n˙ x ( t ) = 1 a ( t ) √ 1 + C 2 a 2 ( t )', 'Changing the curve parameter': 'By default, the curve parameter is . However, sometimes we want to use another parameter - for example   for proper time. To change the parameter, we can set T.options.curve\\_parameter to a symbol of our choice, whether as a string or a SymPy Symbol . As an example, let us change it to : λ τ τ  \npreviously calculated . The curve parameter should instead be changed at the beginning of the session, before calculating any tensors which use it, such as Lagrangians or geodesic equations. Indeed, the curve parameter for the Minkowski Lagrangian, which we already calculated, is still : λ  \nMinkowski . lagrangian() . In [ ]:  \n```\ncomponents()\n```  \nOGRePy : Using default coordinate system Cartesian and default index configuration ().  \nOut[ ]: [ -( t ( λ ) ) 2 + ( x ( λ ) ) 2 + ( y ( λ ) ) 2 + ( z ( λ ) ) 2 ] d d λ d d λ d d λ d d λ  \nBut for newly calculated Lagrangians, it will be  : τ  \n```\nT . Metric( coords = Cartesian, components = T . diag( -1, 1, 1, 1), ) . lagrangian() . components() In [ ]:\n```  \nOGRePy : Using default coordinate system Cartesian and default index configuration ().  \nOut[ ]: [ -( t ( τ ) ) 2 + ( x ( τ ) ) 2 + ( y ( τ ) ) 2 + ( z ( τ ) ) 2 ] d d τ d d τ d d τ d d τ', 'Bug reports and feature requests': 'This package is under continuous and active development. If you encounter any bugs, or if you would like to request any additional features, please feel free to open a new issue on GitHub and I will look into it as soon as I can.', 'Contribution and pull request policy': "Contributions are always welcome. However, I release my projects in cumulative updates after editing and testing them locally on my system, so my policy is to never accept any pull requests . If you open a pull request, and I decide to incorporate your suggestion into the project, I will first modify your code to comply with the project's coding conventions (formatting, syntax, naming, comments, programming practices, etc.), and perform some tests to ensure that the change doesn't break anything. I will then merge it into the next release of the project, possibly together with some other changes. The new release will also include a note in CHANGELOG.md with a link to your pull request, and modifications to the documentation in README.md as needed.  \nTo create a development environment for this package, download the source code directly from the GitHub repository, then create a virtual environment in the root folder of the repository as explained above, activate it, and run pip install ipykernel sympy to install the dependent packages.  \nFor   your   convenience,   a   PowerShell   script,   update\\_packages.ps1,   is   provided   in   the   GitHub repository to allow easily updating all outdated packages. Another script, compile\\_docs.ps1, is used to compile the documentation in README.md to a Jupyter notebook and run the notebook. Finally, cleanup.ps1, is used to clean up Python and Jupyter cache folders.  \nThis package was developed in Visual Studio Code. The .vscode folder is provided in the GitHub repository for your convenience, including tasks for running the above PowerShell scripts. It is highly recommended to install the following linters:  \n- · Pyright: install the Pylance VS Code extension.\n- · Ruff: pip install ruff and install the VS Code extension.\n- · Pylint: pip install pylint and install the VS Code extension.  \nConfigurations for all 3 linters are included in the pyproject.toml file in the GitHub repository.", 'Starring the repository': 'If you found this project useful, please consider starring it on GitHub! This allows me to see how many people are using my code, and motivates me to keep working to improve it.', 'Acknowledgements': 'I   would   like   to   thank   my   student   Jared   Wogan,   whose   undergraduate   research   project,   a preliminary   Python   port   of   my   Mathematica   package   OGRe,   motivated   and   inspired   me   to eventually write my own port, OGRePy. I acknowledge the support of the Natural Sciences and Engineering Research Council of Canada (NSERC), RGPIN-2024-04063.', 'Copyright and citing': 'Copyright (c) 2024 Barak Shoshany. Licensed under the MIT license.  \nIf you use this package in software of any kind, please provide a link to the GitHub repository in the source code and documentation. If you use this package in published research, please cite this arXiv paper.', 'Other projects to check out': 'This   package   is   a   Python   port   of   OGRe:   An   Object-Oriented   General   Relativity   Package   for Mathematica [1]. You may also be interested in BS::thread\\_pool : a fast, lightweight, and easyto-use C++17 thread pool library for high-performance scientific computing [5].', 'References': '[1]   Barak   Shoshany, "OGRe: An Object-Oriented General Relativity Package for Mathematica", Journal of Open Source Software, 6(65), 3416 (2021), doi:10.21105/joss.03416, arXiv:2109.04193  \n(2021)  \n- [2] Meurer A, Smith CP, Paprocki M, Č ertík O, Kirpichev SB, Rocklin M, Kumar A, Ivanov S, Moore JK, Singh S, Rathnayake T, Vig S, Granger BE, Muller RP, Bonazzi F, Gupta H, Vats S, Johansson F, Pedregosa F, Curry MJ, Terrel AR, Rou č ka Š, Saboo A, Fernando I, Kulal S, Cimrman R, and Scopatz A., "SymPy: Symbolic Computing In Python", PeerJ Computer Science 3:e103, doi:10.7717/peerjcs.103 (2017)\n- [3] Fernando Perez and Brian E. Granger, "IPython: A System for Interactive Scientific Computing", Computing in Science & Engineering, vol. 9, no. 3, pp. 21-29, May-June 2007, doi:10.1109/ MCSE.2007.53 (2007)  \n[4] Marijan Beg, Juliette Taka, Thomas Kluyver, Alexander Konovalov, Min Ragan-Kelley, Nicolas M. Thiéry, and Hans Fangohr, "Using Jupyter for Reproducible Scientific Workflows", Computing in Science & Engineering 23, no. 2 (2021): 36-46, doi:10.1109/MCSE.2021.3052101 (2021)  \n[5] Barak Shoshany, "A C++17 Thread Pool for High-Performance Scientific Computing", SoftwareX 26 (2024) 101687, doi:10.1016/j.softx.2024.101687, arXiv:2105.00613 (2024)'}