{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "markdown-000",
      "metadata": {},
      "source": [
        "# Computational relativity\n",
        "\n",
        "[Read the lesson](https://tirta.co/a-byte-of-physics/computational-relativity). This notebook includes the lesson text and its Python examples in reading order. Run the setup cell, then run the remaining cells from top to bottom. In Colab, use File → Save a copy in Drive to keep your edits. You can run and edit this view without changing the course source. Examples use illustrative data unless stated otherwise."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-001",
      "metadata": {},
      "source": [
        "import importlib.metadata\n",
        "import subprocess\n",
        "import sys\n",
        "\n",
        "requirements = {\"numpy\": (2, 0), \"sympy\": (1, 13), \"matplotlib\": (3, 8)}\n",
        "to_install = []\n",
        "for package, minimum in requirements.items():\n",
        "    try:\n",
        "        installed = importlib.metadata.version(package)\n",
        "        version = tuple(int(part) for part in installed.split(\".\")[:2])\n",
        "    except importlib.metadata.PackageNotFoundError:\n",
        "        version = (0, 0)\n",
        "    if version < minimum:\n",
        "        to_install.append(f\"{package}>={minimum[0]}.{minimum[1]}\")\n",
        "if to_install:\n",
        "    subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", *to_install])\n",
        "\n",
        "import numpy as np\n",
        "import sympy as sp\n",
        "import matplotlib\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "print(\"Python\", sys.version.split()[0])\n",
        "print(\"NumPy\", np.__version__)\n",
        "print(\"SymPy\", sp.__version__)\n",
        "print(\"Matplotlib\", matplotlib.__version__)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-002",
      "metadata": {},
      "source": [
        "Many important predictions of relativity can be calculated exactly: a Lorentz\n",
        "boost, a freely moving particle, or an ideal black hole with perfect symmetry.\n",
        "Real systems such as two orbiting black holes, a merging pair of neutron stars,\n",
        "or collapsing matter usually have too little symmetry for a closed-form\n",
        "solution. **Computational relativity**, commonly called numerical relativity in\n",
        "the strong-gravity setting, turns Einstein's equations into a finite numerical\n",
        "initial-value problem.\n",
        "\n",
        "The result is not simply a picture of curved spacetime. It is a solution tied to\n",
        "initial data, coordinates, gauge conditions, a finite grid, boundary conditions,\n",
        "an evolution formulation, and estimates of numerical error. A trustworthy run\n",
        "must report those choices and show that physically meaningful outputs remain\n",
        "stable when the numerical approximation is improved.\n",
        "\n",
        "## From one geometric equation to a time evolution\n",
        "\n",
        "Einstein's field equation is\n",
        "\n",
        "\n",
        "$$\n",
        "G_{\\mu\\nu}+\\Lambda g_{\\mu\\nu}=\\frac{8\\pi G}{c^4}T_{\\mu\\nu}\n",
        "$$\n",
        "\n",
        "\n",
        "The spacetime metric\n",
        "$g_{\\mu\\nu}$\n",
        "describes geometry. The Einstein tensor\n",
        "$G_{\\mu\\nu}$\n",
        "contains derivatives of that metric, and the stress-energy tensor\n",
        "$T_{\\mu\\nu}$\n",
        "describes matter and non-gravitational fields. The cosmological constant is\n",
        "$\\Lambda$.\n",
        "\n",
        "The compact equation is covariant: it does not choose a preferred coordinate\n",
        "system. A computer, however, needs a sequence of states labeled by a time\n",
        "coordinate. A **three-plus-one decomposition** slices four-dimensional\n",
        "spacetime into three-dimensional spatial hypersurfaces. Each slice carries:\n",
        "\n",
        "- a spatial metric $\\gamma_{ij}$,\n",
        "- an extrinsic curvature\n",
        "  $K_{ij}$,\n",
        "- matter fields when present,\n",
        "- a lapse $\\alpha$\n",
        "  controlling proper time between slices, and\n",
        "- a shift $\\beta^i$\n",
        "  controlling how spatial coordinates move between slices.\n",
        "\n",
        "The lapse and shift are gauge choices. Changing them can make coordinate\n",
        "trajectories look very different without changing the underlying spacetime.\n",
        "\n",
        "## Evolution equations and constraints\n",
        "\n",
        "The decomposition produces two kinds of equations. **Evolution equations**\n",
        "advance the state from one slice to the next. **Constraint equations** must hold\n",
        "on the initial slice and should remain satisfied during exact evolution.\n",
        "Numerical truncation and boundary errors cause nonzero constraint residuals, so\n",
        "their behavior is a central diagnostic.\n",
        "\n",
        "In geometric units where\n",
        "$G=c=1$, the\n",
        "Hamiltonian constraint has the schematic form\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathcal H={}^{(3)}R+K^2-K_{ij}K^{ij}-16\\pi\\rho=0\n",
        "$$\n",
        "\n",
        "\n",
        "and the momentum constraints can be written\n",
        "\n",
        "\n",
        "$$\n",
        "\\mathcal M^i=D_j\\left(K^{ij}-\\gamma^{ij}K\\right)-8\\pi S^i=0\n",
        "$$\n",
        "\n",
        "\n",
        "Here ${}^{(3)}R$\n",
        "is the spatial curvature scalar,\n",
        "$K=\\gamma^{ij}K_{ij}$,\n",
        "and $\\rho$ and\n",
        "$S^i$ describe matter as\n",
        "seen by observers normal to the slice. These equations are shown to explain the\n",
        "workflow, not as a complete solver."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-003",
      "metadata": {},
      "source": [
        "import sympy as sp\n",
        "\n",
        "# Flat vacuum initial data: spatial curvature and extrinsic curvature vanish.\n",
        "spatial_metric = sp.eye(3)\n",
        "extrinsic_curvature = sp.zeros(3)\n",
        "scalar_curvature, matter_energy_density = 0, 0\n",
        "trace_k = sp.trace(extrinsic_curvature)\n",
        "hamiltonian = scalar_curvature + trace_k**2 - sp.trace(extrinsic_curvature**2)\n",
        "assert hamiltonian == 0 and matter_energy_density == 0\n",
        "print(\"Flat-vacuum Hamiltonian constraint:\", hamiltonian)\n",
        "# This checks one exact initial state; it is not a general-relativity solver.\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-004",
      "metadata": {},
      "source": [
        "## Why formulation matters\n",
        "\n",
        "Writing the field equation in a mathematically equivalent form does not\n",
        "guarantee equally stable numerical evolution. Modern codes often use a\n",
        "Baumgarte–Shapiro–Shibata–Nakamura formulation, a generalized-harmonic\n",
        "formulation, or a related strongly hyperbolic system. These introduce evolved\n",
        "variables and sometimes constraint-damping terms designed to control numerical\n",
        "errors.\n",
        "\n",
        "The formulation, gauge, and boundary treatment work together. A stable time\n",
        "integrator cannot rescue an ill-posed continuum system. Likewise, a well-posed\n",
        "formulation can still fail when a boundary injects constraint violations or a\n",
        "coordinate gauge stretches the grid until resolution is lost.\n",
        "\n",
        "## Building valid initial data\n",
        "\n",
        "One cannot usually place two isolated black-hole metrics side by side and begin\n",
        "evolving them. The combined data must satisfy the constraint equations.\n",
        "Initial-data methods choose some freely specifiable fields and solve elliptic\n",
        "equations for the remaining fields. The choices encode physical assumptions\n",
        "about masses, spins, momentum, orbit, and unwanted initial gravitational\n",
        "radiation.\n",
        "\n",
        "For matter systems, an equation of state and matter constraints are also needed.\n",
        "Different plausible neutron-star equations of state can produce physical\n",
        "differences larger than the remaining grid error. Numerical convergence does\n",
        "not remove uncertainty in the physical model.\n",
        "\n",
        "## Discretizing space and time\n",
        "\n",
        "The continuous fields are stored on a finite representation: finite-difference\n",
        "grids, spectral elements or domains, finite-volume meshes for fluids, or a\n",
        "combination. Compact objects need high resolution nearby while emitted waves\n",
        "travel through a much larger region, so adaptive mesh refinement or multiple\n",
        "spectral domains are common.\n",
        "\n",
        "An explicit evolution method must respect a stability restriction related to\n",
        "the Courant–Friedrichs–Lewy condition:\n",
        "\n",
        "\n",
        "$$\n",
        "\\Delta t\\leq C_{\\mathrm{CFL}}\\frac{\\Delta x}{{v_{\\mathrm{max}}}}\n",
        "$$\n",
        "\n",
        "\n",
        "The precise constant depends on the spatial scheme, time integrator,\n",
        "dimensionality, grid geometry, and characteristic speeds. Reducing spatial\n",
        "spacing without reducing the time step can therefore make a previously stable\n",
        "run unstable."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-005",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "\n",
        "spacings = np.array([0.1, 0.05, 0.025])\n",
        "maximum_speed, courant = 1.0, 0.4  # Units with c=1.\n",
        "time_step = courant * spacings.min() / maximum_speed\n",
        "print(\"Step limited by finest spacing:\", time_step)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-006",
      "metadata": {},
      "source": [
        "## Black holes on a grid\n",
        "\n",
        "A black-hole singularity cannot be represented as an ordinary finite grid value.\n",
        "Two major strategies avoid evolving the singular point directly:\n",
        "\n",
        "- **Excision** removes an interior region hidden inside an apparent horizon and\n",
        "  uses the fact that physical characteristics cannot escape the event horizon.\n",
        "- **Moving punctures** factor or transform singular behavior so the coordinate\n",
        "  puncture can move across the numerical grid while evolved variables remain\n",
        "  manageable.\n",
        "\n",
        "An apparent horizon can be located on individual slices, but an event horizon is\n",
        "a global object whose location depends on the future spacetime. Horizon mass,\n",
        "spin, area, and shape are therefore accompanied by definitions and numerical\n",
        "uncertainties rather than inferred from a dark region in a visualization.\n",
        "\n",
        "## Extracting gravitational waves\n",
        "\n",
        "The metric components near a source are strongly coordinate-dependent.\n",
        "Gravitational radiation is commonly extracted on coordinate spheres at several\n",
        "radii using quantities such as the Newman–Penrose scalar\n",
        "$\\Psi_4$. Far from the\n",
        "source, it is related to the two gravitational-wave polarizations by\n",
        "\n",
        "\n",
        "$$\n",
        "\\Psi_4\\approx\\ddot h_+-i\\ddot h_\\times\n",
        "$$\n",
        "\n",
        "\n",
        "up to sign and convention choices that must be stated. Recovering strain\n",
        "requires two integrations in time or a frequency-domain procedure, each of\n",
        "which needs careful treatment of integration constants and low-frequency drift.\n",
        "\n",
        "Waveforms are extracted at several finite radii and extrapolated toward large\n",
        "radius, or computed with methods that reach future null infinity. Moving the\n",
        "extraction radius is an essential check because a waveform can appear converged\n",
        "on the grid while retaining near-zone or gauge contamination.\n",
        "\n",
        "## Measuring convergence\n",
        "\n",
        "Suppose a method has leading error\n",
        "\n",
        "\n",
        "$$\n",
        "Q(h)=Q_{\\mathrm{exact}}+Ch^p+\\mathcal O(h^{p+1})\n",
        "$$\n",
        "\n",
        "\n",
        "where $h$ is grid spacing and\n",
        "$p$ is convergence order.\n",
        "Run the same physical problem at three resolutions\n",
        "$h,\\,h/r,\\,h/r^2$.\n",
        "If the leading-error model applies, the differences satisfy approximately\n",
        "\n",
        "\n",
        "$$\n",
        "\\frac{Q(h)-Q(h/r)}{Q(h/r)-Q(h/r^2)}\\approx r^p\n",
        "$$\n",
        "\n",
        "\n",
        "so an observed order can be estimated:\n",
        "\n",
        "\n",
        "$$\n",
        "p_{\\mathrm{obs}}\\approx\\frac{\\ln\\left|\\frac{Q(h)-Q(h/r)}{Q(h/r)-Q(h/r^2)}\\right|}{\\ln r}\n",
        "$$\n",
        "\n",
        "\n",
        "The formal order printed in a method's documentation is not enough. Mesh\n",
        "interfaces, shocks, horizon treatment, and boundaries can lower the observed\n",
        "order. Compare waveform phase and amplitude, horizon quantities, conservation\n",
        "errors, and constraint norms—not only one visually smooth plot."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-007",
      "metadata": {},
      "source": [
        "# A controlled second-order finite-difference example at the same probe.\n",
        "steps = np.array([0.2, 0.1, 0.05])\n",
        "results = np.sin(steps) / steps\n",
        "coarse_change, fine_change = results[0] - results[1], results[1] - results[2]\n",
        "order = np.log(abs(coarse_change / fine_change)) / np.log(2)\n",
        "print(\"Observed derivative convergence order:\", order)\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-008",
      "metadata": {},
      "source": [
        "## Constraint norms need context\n",
        "\n",
        "A code may record an\n",
        "$L_2$ norm such as\n",
        "\n",
        "\n",
        "$$\n",
        "\\|\\mathcal H\\|_2=\\sqrt{\\frac{1}{V}\\int_V|\\mathcal H|^2\\,dV}\n",
        "$$\n",
        "\n",
        "\n",
        "but a single small number is not a proof of correctness. State the domain,\n",
        "normalization, excluded regions, units, and resolution. A residual can be small\n",
        "because the normalization is large, and a global norm can hide a severe local\n",
        "violation. Plot spatial maxima and convergence as well as integrated norms.\n",
        "\n",
        "Constraint violations should remain controlled and decrease at the expected\n",
        "rate under refinement while physical observables converge. Constraint damping\n",
        "can reduce one diagnostic without correcting a bad matter model or boundary\n",
        "condition.\n",
        "\n",
        "## A reproducible evolution loop"
      ]
    },
    {
      "cell_type": "code",
      "id": "code-009",
      "metadata": {},
      "source": [
        "# A scalar wave is a small test of a propagation scheme, not Einstein evolution.\n",
        "N, length = 100, 1.0\n",
        "x = np.arange(N) * length / N\n",
        "dx, dt = length / N, 0.005\n",
        "current = np.sin(2 * np.pi * x)\n",
        "previous = np.sin(2 * np.pi * (x + dt))\n",
        "for step in range(100):\n",
        "    following = (\n",
        "        2 * current\n",
        "        - previous\n",
        "        + (dt / dx) ** 2 * (np.roll(current, -1) - 2 * current + np.roll(current, 1))\n",
        "    )\n",
        "    previous, current = current, following\n",
        "exact = np.sin(2 * np.pi * (x - 100 * dt))\n",
        "print(\"Scalar-wave error after 0.5 time units:\", np.max(abs(current - exact)))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-010",
      "metadata": {},
      "source": [
        "A production code also needs parallel communication, restart consistency,\n",
        "provenance, deterministic or characterized reductions, and protection against\n",
        "silent hardware or storage faults. Those engineering details affect scientific\n",
        "reproducibility.\n",
        "\n",
        "## Validation hierarchy\n",
        "\n",
        "Before trusting a binary merger, test increasingly demanding cases:\n",
        "\n",
        "1. Evolve flat Minkowski spacetime and verify that it stays flat apart from\n",
        "   controlled numerical error.\n",
        "2. Evolve known analytic or semi-analytic solutions, such as gauge waves or a\n",
        "   stationary single black hole, and compare against the expected result.\n",
        "3. Verify conservation laws and constraints on standard matter tests.\n",
        "4. Reproduce published benchmark problems.\n",
        "5. Compare independent formulations or codes where possible.\n",
        "6. Refine the mesh, move the outer boundary, vary the extraction radii, and\n",
        "   alter gauge parameters without changing the intended physical result beyond\n",
        "   the error budget.\n",
        "\n",
        "These checks find different failures. A convergent answer can converge to the\n",
        "wrong continuum problem if the boundary or initial data are wrong. A small\n",
        "constraint residual can coexist with inaccurate waveform phase. Agreement\n",
        "between independent methods is especially valuable because they are less likely\n",
        "to share the same implementation error.\n",
        "\n",
        "## Coordinates, observables, and scope\n",
        "\n",
        "Coordinate separation between two black-hole punctures is not automatically a\n",
        "physical distance. Coordinate merger time is not automatically an observable.\n",
        "Prefer quantities defined at infinity, quasi-local horizon measures with stated\n",
        "definitions, proper distances when meaningful, and invariant curvature scalars.\n",
        "When a coordinate-dependent diagnostic is useful for debugging, label it as\n",
        "such.\n",
        "\n",
        "This lesson is a workflow introduction, not an implementation of a\n",
        "general-relativity solver. Full systems include tensor discretization,\n",
        "constraint-preserving boundaries, atmosphere treatments for fluids, magnetic\n",
        "fields, neutrino transport, equations of state, and many other specialized\n",
        "choices. The requested introductory textbooks establish relativity and its\n",
        "invariants; the Einstein Toolkit documentation supplies the specialized\n",
        "computational practices referenced here.\n",
        "\n",
        "## A worked Python notebook\n",
        "\n",
        "Use a unit characteristic speed and Courant factor 0.4 to inspect refinement cost. The question for this calculation is precise: how does **stable propagation time step**\n",
        "change when we change **grid spacing**, while keeping the other choices fixed?\n",
        "The earlier sections explain the physical relationship. Here we turn one part of that\n",
        "relationship into a calculation that you can run, inspect, and change in Google Colab.\n",
        "\n",
        "This scalar propagation estimate is not an evolution system for spacetime curvature. Keep that sentence beside the results. A formula can return a number outside\n",
        "its useful range, and a plotting library will usually draw that number without asking\n",
        "whether the physical assumptions still hold. The selected interval is from\n",
        "0.01 to 0.2 scaled length units. It gives us a specific domain to discuss\n",
        "instead of leaving the graph's range to a software default.\n",
        "\n",
        "Use the notebook link above the lesson, run the setup cell, and then run the cells in\n",
        "order. The code below is also included there. NumPy handles the arrays of numerical\n",
        "values, SymPy keeps the equation symbolic, and Matplotlib draws the results. If these\n",
        "libraries or notebook cells are unfamiliar, start with\n",
        "[Your first physics notebook](https://tirta.co/a-byte-of-physics/your-first-physics-notebook).\n",
        "\n",
        "### State the relationship before choosing a graph\n",
        "\n",
        "In this small example, `q` stands for grid spacing, expressed in scaled length units. The output is\n",
        "stable propagation time step, expressed in scaled time units. The equation below uses the numerical values in those\n",
        "units. Any fixed coefficients therefore carry the units needed to make the relation\n",
        "consistent. A value supplied in another unit must be converted before it enters this\n",
        "expression.\n",
        "\n",
        "\n",
        "$$\n",
        "f(q) = 0.4 q\n",
        "$$\n",
        "\n",
        "\n",
        "This is a function of one changing input. It is not a statement that the physical\n",
        "system has only one variable. We deliberately hold the other inputs fixed so that one\n",
        "cause of variation is visible. Changing several inputs at once would make it harder\n",
        "to tell which change produced the output difference. Write down the held-fixed choices\n",
        "before trying a different experiment.\n",
        "\n",
        "At 0.05 scaled length units, the expression gives 0.02 scaled time units. This is our\n",
        "reference calculation. It is a prediction of the stated example, not a new measurement.\n",
        "Its displayed digits help us compare implementations. They should not be read as a\n",
        "claim that physical inputs are known to six significant figures."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-011",
      "metadata": {},
      "source": [
        "import numpy as np\n",
        "import sympy as sp\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "q = sp.Symbol(\"q\", real=True)\n",
        "expression = sp.sympify(\"0.4*q\", locals={\"q\": q})\n",
        "reference_input = 0.05\n",
        "reference_output = float(expression.subs(q, reference_input))\n",
        "print(\"Input:\", reference_input, \"scaled length units\")\n",
        "print(\"Predicted stable propagation time step:\", reference_output, \"scaled time units\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-012",
      "metadata": {},
      "source": [
        "`sp.Symbol` declares a mathematical symbol. It does not assign a numerical measurement\n",
        "to that symbol. `subs` then replaces the symbol with our chosen input, and `float`\n",
        "converts the resulting symbolic number into a standard Python numerical value.\n",
        "Keeping these steps separate lets us inspect the equation before numerical substitution.\n",
        "It also prevents a later plot from becoming the only surviving record of the model.\n",
        "\n",
        "### Compare a few cases you can explain\n",
        "\n",
        "Before drawing hundreds of points, calculate three. The lower endpoint gives\n",
        "0.004 scaled time units. The midpoint, at 0.105 scaled length units, gives\n",
        "0.042 scaled time units. The upper endpoint gives 0.08 scaled time units.\n",
        "Read these together with the assumptions: they describe different choices of grid spacing\n",
        "within the same example, with the other inputs held fixed.\n",
        "\n",
        "These three values are a useful first check, but they do not establish the shape between\n",
        "them. Two endpoints can be equal even when the curve bends or oscillates in between.\n",
        "Likewise, a large change between endpoints does not tell us whether the relationship is\n",
        "linear. We need the equation and intermediate samples to answer those questions."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-013",
      "metadata": {},
      "source": [
        "evaluate = sp.lambdify(q, expression, modules=\"numpy\")\n",
        "inputs = np.array([0.01, 0.10500000000000001, 0.2])\n",
        "outputs = np.asarray(evaluate(inputs), dtype=float)\n",
        "outputs = np.broadcast_to(outputs, inputs.shape)\n",
        "for input_value, output_value in zip(inputs, outputs):\n",
        "    print(\n",
        "        f\"{input_value:.6g} scaled length units -> \"\n",
        "        f\"{output_value:.6g} scaled time units\"\n",
        "    )\n",
        "assert np.all(np.isfinite(outputs))\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-014",
      "metadata": {},
      "source": [
        "`lambdify` turns the symbolic expression into a numerical function. We explicitly select\n",
        "NumPy as its numerical backend so it can accept an array. The same expression now has\n",
        "two useful forms: one for algebra and one for calculating many cases. The assertion\n",
        "checks that the chosen inputs produce finite outputs. It would catch an infinity or an\n",
        "undefined numerical result, but a finite value can still be physically inappropriate.\n",
        "\n",
        "### Make a graph that answers the question\n",
        "\n",
        "The horizontal axis shows grid spacing; the vertical axis shows stable propagation time step. Every plotted\n",
        "point is a prediction of the same expression. We mark the reference case separately\n",
        "so that a reader can connect the earlier printed value to its place on the curve.\n",
        "The axis labels include units because a shape without a scale cannot tell us the size\n",
        "of a physical effect."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-015",
      "metadata": {},
      "source": [
        "input_grid = np.linspace(0.01, 0.2, 301)\n",
        "output_grid = np.asarray(evaluate(input_grid), dtype=float)\n",
        "output_grid = np.broadcast_to(output_grid, input_grid.shape)\n",
        "fig, ax = plt.subplots(figsize=(7, 4))\n",
        "ax.plot(input_grid, output_grid, label=\"Stated model\")\n",
        "ax.scatter([reference_input], [reference_output], label=\"Reference case\", zorder=3)\n",
        "ax.set_xlabel(\"Grid spacing (scaled length units)\")\n",
        "ax.set_ylabel(\"Stable propagation time step (scaled time units)\")\n",
        "ax.legend()\n",
        "ax.grid(alpha=0.25)\n",
        "fig.tight_layout()\n",
        "plt.show()\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-016",
      "metadata": {},
      "source": [
        "Look for a sign change, a turning point, or a region where the curve becomes steep.\n",
        "Connect each feature to the expression rather than to the colour of the line. If the\n",
        "curve has a minimum or maximum, changing the input in opposite directions may have\n",
        "similar effects on the output near that point. If it is nearly straight over a short\n",
        "interval, a local linear approximation may be useful even when the complete expression\n",
        "is nonlinear.\n",
        "\n",
        "Increasing the number of samples makes the line smoother and may reveal features that\n",
        "a coarse grid missed. It does not improve the physical inputs or enlarge the model's\n",
        "validity range. For quantities that can take only discrete values, use the line as a\n",
        "guide to the relationship and interpret only the allowed input values. A plotting\n",
        "function does not enforce such restrictions for you.\n",
        "\n",
        "### Measure the local sensitivity\n",
        "\n",
        "A derivative asks a more specific question than the whole graph: how quickly does\n",
        "stable propagation time step change near the reference input? Its units are the output unit divided by\n",
        "the input unit. For this calculation, the derivative at 0.05 scaled length units is\n",
        "0.4 in those ratio units. Locally, the output increases as the\n",
        "input increases. This statement is local; the sign or size of the slope can be different\n",
        "elsewhere on the curve.\n",
        "\n",
        "\n",
        "$$\n",
        "f'(q) = 0.4\n",
        "$$\n",
        "\n",
        "\n",
        "For a small input change, multiply the derivative by that change to estimate the output\n",
        "change. Then compare that estimate with a fresh evaluation of the full expression.\n",
        "The distinction between these two calculations matters: the derivative gives a tangent\n",
        "approximation, while substitution evaluates the chosen expression at the new point."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-017",
      "metadata": {},
      "source": [
        "slope_expression = sp.diff(expression, q)\n",
        "slope_at_reference = float(slope_expression.subs(q, reference_input))\n",
        "changed_input = 0.05095\n",
        "linear_prediction = reference_output + slope_at_reference * (\n",
        "    changed_input - reference_input\n",
        ")\n",
        "full_prediction = float(evaluate(changed_input))\n",
        "print(\"Symbolic derivative:\", slope_expression)\n",
        "print(\"Tangent prediction:\", linear_prediction, \"scaled time units\")\n",
        "print(\"Full expression:\", full_prediction, \"scaled time units\")\n",
        "print(\n",
        "    \"Approximation difference:\",\n",
        "    full_prediction - linear_prediction,\n",
        "    \"scaled time units\",\n",
        ")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-018",
      "metadata": {},
      "source": [
        "Here the changed input is 0.05095 scaled length units. The tangent estimate is\n",
        "0.02038 scaled time units, while the full expression gives\n",
        "0.02038 scaled time units. If the two values are close, it means the chosen\n",
        "input change is small enough for this local approximation at this point. It does not\n",
        "mean the entire model is linear. If the slope is zero, a quadratic or higher-order term\n",
        "may supply the leading change instead.\n",
        "\n",
        "This is also the beginning of uncertainty propagation. If the input has a small stated\n",
        "standard uncertainty, the magnitude of the slope times that uncertainty estimates one\n",
        "contribution to output uncertainty. Do not automatically use the same rule for a wide\n",
        "interval, a discontinuity, a turning point with zero first derivative, or several\n",
        "correlated uncertain inputs. Those situations need more of the model than one slope.\n",
        "\n",
        "### Check the derivative with numerical differences\n",
        "\n",
        "We can estimate the same slope from values on either side of the reference point.\n",
        "Subtract the lower output from the upper output and divide by twice the input step.\n",
        "Parentheses are essential: the entire output difference must be divided by the entire\n",
        "input interval. Without them, Python can execute a different mathematical expression\n",
        "while still producing a plausible number.\n",
        "\n",
        "The calculation below uses three decreasing step sizes. Each estimate is compared with\n",
        "the symbolic derivative, so the reference is independent of the numerical difference\n",
        "formula. Near an endpoint, it is acceptable here to evaluate a small extension only\n",
        "because the displayed mathematical expression is smooth there; such a check does not\n",
        "assert that extrapolated values describe additional physical cases."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-019",
      "metadata": {},
      "source": [
        "input_span = 0.19\n",
        "for fraction in [1e-2, 1e-3, 1e-4]:\n",
        "    step = input_span * fraction\n",
        "    upper = float(evaluate(reference_input + step))\n",
        "    lower = float(evaluate(reference_input - step))\n",
        "    numerical_slope = (upper - lower) / (2 * step)\n",
        "    difference = numerical_slope - slope_at_reference\n",
        "    print(f\"step={step:.6g}: slope={numerical_slope:.6g}, difference={difference:.6g}\")\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-020",
      "metadata": {},
      "source": [
        "For a smooth function, reducing the step often reduces the approximation error at first.\n",
        "Very small steps can eventually make subtraction of nearly equal floating-point values\n",
        "less reliable. Therefore “smaller” is not an unlimited guarantee of “better.” Compare\n",
        "the observed behaviour over a useful range of steps instead of choosing the smallest\n",
        "number the computer can represent.\n",
        "\n",
        "An absolute slope difference is useful when the expected slope is near zero. A relative\n",
        "difference would divide by a very small reference and could look enormous even when the\n",
        "absolute discrepancy is tiny. Away from zero, a relative difference can help compare\n",
        "quantities with very different scales. The tolerance should reflect the question and\n",
        "the numerical method, rather than a universal decimal threshold copied into every test.\n",
        "\n",
        "### Change the example and preserve the reasoning\n",
        "\n",
        "Make one copy of the reference calculation before editing it. Choose a second value of\n",
        "grid spacing inside the stated interval, predict whether stable propagation time step will rise or fall,\n",
        "and then evaluate the expression. Place the prediction and the result in a text cell.\n",
        "If they disagree, identify whether the mistake was in the sign, the unit conversion,\n",
        "the algebra, or the assumption about how the curve behaves.\n",
        "\n",
        "Next choose a shorter plotting interval around the reference point. Compare the local\n",
        "curve with its tangent approximation. Then widen the interval again. The difference\n",
        "shows why a useful local estimate need not describe the whole range. Keep the axis\n",
        "labels and numerical scale visible when comparing the plots; automatic axis limits can\n",
        "make two different effects appear equally large.\n",
        "\n",
        "Finally, return to the physical limit stated at the start: This scalar propagation estimate is not an evolution system for spacetime curvature. Describe one change\n",
        "to the setup that would violate that limit. State what new input, equation, or observation\n",
        "would be needed before trusting an answer in the changed situation. This last step\n",
        "connects the Python experiment to the physics instead of treating successful execution\n",
        "as the only criterion for a useful result.\n",
        "\n",
        "Before saving, restart the runtime and run all cells in order. A result that depends on\n",
        "an earlier, now-deleted input cell is not reproducible from the saved notebook. Keep\n",
        "unrounded values for later calculations, round only the reported output, and label any\n",
        "new data as measured, assumed, or generated. The graph and printed values should remain\n",
        "traceable to the same expression and the same choices of inputs.\n",
        "\n",
        "### Recover the output change by integrating the slope\n",
        "\n",
        "There is another way to check that the expression and its derivative describe the same\n",
        "relationship. Add up the small output changes predicted by the slope across the chosen\n",
        "input interval. In the continuous limit, this integral equals the output at the upper\n",
        "endpoint minus the output at the lower endpoint. The result has units of scaled time units:\n",
        "the input unit in the integration cancels the input unit in the denominator of the slope.\n",
        "\n",
        "This statement is about the mathematics of this particular relationship. It does not\n",
        "assign a new physical meaning to an arbitrary area under a graph. For example, an area\n",
        "under force versus distance represents work, while an area under a different pair of\n",
        "quantities may represent something else or have no standard name. Always carry the\n",
        "axis units through the calculation before naming an integral."
      ]
    },
    {
      "cell_type": "code",
      "id": "code-021",
      "metadata": {},
      "source": [
        "slope_function = sp.lambdify(q, slope_expression, modules=\"numpy\")\n",
        "endpoint_change = float(evaluate(0.2) - evaluate(0.01))\n",
        "for points in [101, 201, 401]:\n",
        "    grid = np.linspace(0.01, 0.2, points)\n",
        "    slopes = np.asarray(slope_function(grid), dtype=float)\n",
        "    slopes = np.broadcast_to(slopes, grid.shape)\n",
        "    integrated_change = np.trapezoid(slopes, grid)\n",
        "    print(\n",
        "        points,\n",
        "        \"integrated change:\",\n",
        "        integrated_change,\n",
        "        \"endpoint change:\",\n",
        "        endpoint_change,\n",
        "    )\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "id": "markdown-022",
      "metadata": {},
      "source": [
        "The trapezoidal rule joins neighbouring slope samples with straight segments and adds\n",
        "their signed areas. A negative contribution remains negative; replacing every slope\n",
        "by its magnitude would calculate a different quantity. Increasing the sample count\n",
        "provides a practical refinement check. If the values do not settle toward the endpoint\n",
        "difference, first inspect the interval, singularities, and array ordering.\n",
        "\n",
        "Do not conclude that two agreeing calculations prove the model is physically complete.\n",
        "Both use the same selected relationship, so an omitted effect would be omitted from\n",
        "both. Their agreement is evidence that the numerical tools implement that relationship\n",
        "consistently. Comparing with an independent experiment or a more appropriate physical\n",
        "model is a separate test.\n",
        "\n",
        "Keep this comparison in the notebook when you change the expression. It is particularly\n",
        "useful after adding a coefficient, changing a sign convention, or converting an input\n",
        "unit. A code cell that produces a smooth graph can conceal these mistakes; a second\n",
        "calculation of the same output change gives you another place to notice them.\n",
        "\n",
        "## Sources\n",
        "\n",
        "- [OpenStax, *University Physics Volume 3*, Chapter 5, “Relativity”](https://openstax.org/books/university-physics-volume-3/pages/5-introduction).\n",
        "- [Tipler and Llewellyn, *Modern Physics*, relativity chapters](https://web.pdx.edu/~pmoeck/books/Tipler_Llewellyn.pdf).\n",
        "- [Benjamin Crowell, *Light and Matter*, relativity foundations](https://open.umn.edu/opentextbooks/textbooks/light-and-matter).\n",
        "- [Physics LibreTexts, General Relativity bookshelf](https://phys.libretexts.org/Bookshelves/Relativity/General_Relativity_(Crowell)).\n",
        "- [Einstein Toolkit documentation, numerical-relativity infrastructure and tutorials](https://docs.einsteintoolkit.org/et-docs/)."
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.12"
    },
    "colab": {
      "name": "computational-relativity.ipynb",
      "provenance": []
    },
    "tirta": {
      "lesson": "https://tirta.co/a-byte-of-physics/computational-relativity",
      "source_sha256": "8e211e32e1779aa010544dadf22c1548bf5743086caac2125908aa793d1e953c"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
