PyTeukolsky is a numpy-based, finite-difference, time-domain solver for a
single azimuthal mode
The user supplies the black-hole parameters
The Teukolsky equation is decomposed into azimuthal modes,
Here
and complex128.
The script scripts/check_equations.py symbolically verifies the equations. It
checks (CHECK 1) that the mode equation above is the exact
git clone https://github.com/dradice/PyTeukolsky
cd PyTeukolsky
pip install -e .Core dependencies (numpy, scipy) are installed automatically.
Optional extras:
pip install "pyteukolsky[plot]" # matplotlib — for scripts/run_example.py
pip install "pyteukolsky[sympy]" # sympy>=1.18 — for scripts/check_equations.py
pip install "pyteukolsky[dev]" # pytest — to run the test suiteThen import the package:
from pyteukolsky import Grid, TeukolskyRHS, Evolution
from pyteukolsky import swsh, gaussian_pulse, project_swsh, fit_qnm_frequencyA Schwarzschild (
from pyteukolsky import Grid, TeukolskyRHS, Evolution
from pyteukolsky import swsh, gaussian_pulse, project_swsh, fit_qnm_frequency
M, a, m = 1.0, 0.0, 2
# rmin just inside r_+ = 2M to keep all interior cells outside the horizon
grid = Grid(rmin=1.99, rmax=100.0, Nmu=32, Nr=200, M=M)
rhs = TeukolskyRHS(grid, M, a, m, dissipation=0.1)
sim = Evolution(rhs)
# Time-symmetric Gaussian pulse: pass it as both slices so v = 0 exactly
psi0 = gaussian_pulse(grid, r0=10.0, sigma_r=2.0, ell=2, m=m)
sim.set_initial_data(psi0=psi0, psi1=psi0, dt_init=1e-3)
sim.add_detector(30.0)
sim.evolve(t_final=140.0, cfl=0.45)
# Project the detector mu-profile onto _{-2}Y_{2m}, then fit the ringdown
mu = grid._mu[grid.ghost : grid.ghost + grid.Nmu]
psi_22 = project_swsh(sim.waveforms[30.0], mu, swsh(-2, 2, m, mu))
omega_R, omega_I = fit_qnm_frequency(sim.times, psi_22.real,
t_start=90.0, t_end=130.0)
print(f"Mω = {M*omega_R:.4f} + {M*omega_I:.4f}i")
# Schwarzschild ℓ=m=2: Mω ≈ 0.3737 - 0.0890iTiming note (
Choosing rmin. With the logarithmic grid, choose
# Symbolic equation check (source of truth) — expect two "IDENTICAL" reports
python scripts/check_equations.py
# End-to-end demo: ringdown of a Gaussian pulse, with figures and animations
python scripts/run_example.py
# Test suite (73 tests)
pytestscripts/run_example.py evolves a time-symmetric 2D Gaussian pulse on the log-$r$
grid and writes a static figure, 1D and 2D GIF animations, and a waveform
.npz. It plots *.gif, *.npz, *_static.png) are gitignored.
The mode equation contains a mixed derivative
with the angular variable
The state vector is the pair
Working in
-
Radial. A uniform grid in
$x$ mapped to$r$ by the logarithmic map$r=M,e^{x}$ , so cells stretch geometrically in$r$ : fine near the horizon, coarse in the far zone. Built from$r_\min$ ,$r_\max$ ,$N_r$ ; the map derivatives satisfy$r'(x)=r''(x)=r$ . The domain runs from$r_\min$ inside the horizon to a large$r_\max$ , with ghost cells extending the uniform-$x$ array at both ends. Radial derivatives use 2nd-order centered stencils in$x$ mapped to$r$ by the chain rule,$\partial_r f = r'(x)^{-1}\partial_x f$ . -
Angular. A uniform, staggered grid in
$\mu$ :$\mu_j=-1+(j-\tfrac12),\Delta\mu$ ,$\Delta\mu=2/N_\mu$ , covering$\mu\in(-1,1)$ . Staggering keeps the grid off the poles$\mu=\pm1$ where the$1/(1-\mu^2)$ potential is singular; regularity there is imposed through ghost cells (below). The angular operator is discretized in flux form, evaluating$(1-\mu^2)$ at cell faces$\mu_{j\pm1/2}$ for a compact, conservative stencil.
Ghost width is 2 cells per side per direction (one for the 2nd-order stencils, two to support Kreiss–Oliger dissipation).
-
Inner (excision). Because the coordinates are horizon-penetrating and
$r_\min<r_+$ , all characteristics at the inner edge point into the hole and no physical boundary data is required. Inner radial ghosts are filled by 2nd-order extrapolation. This is only exact if every interior cell also sits at$r>r_+$ (see CLAUDE.md'srmingotcha);TeukolskyRHS(..., one_sided_horizon=True)makes the excision exact regardless ofrminby overriding the derivative stencil at the first interior column outside$r_+$ with a one-sided (outward-only) form, so that column — and hence the whole exterior domain — never reads a value from inside the horizon. -
Outer (Sommerfeld). An outgoing/radiative condition
(
$\partial_t\psi\approx-\partial_r\psi-\psi/r$ ) is applied via the outer radial ghosts. It is exact only as$r\to\infty$ ; choose$r_\max$ so reflections arrive after the physics of interest. -
Poles (
$\mu=\pm1$ ). Angular ghosts are filled by reflection across the pole with a parity factor$p$ :$\psi(\mu_{\rm ghost})=p,\psi(\mu_{\rm mirror})$ . For a spin-weight$s=-2$ , azimuthal-$m$ field the parity is$p=(-1)^{m}$ . This is confirmed correct for$\ell=m=2$ : the Schwarzschild and Kerr QNM frequencies are recovered only with$p=+1$ (Validation); forcing$p=-1$ shifts the frequency out of tolerance.
Classic explicit RK4. The time step follows from the local characteristic
speeds of the principal part, Grid.dr_cell):
The angular bound is tightest near the equator (
Kreiss–Oliger dissipation suppresses high-frequency grid noise. For the 2nd-order scheme, each RHS gets the 4th-difference operator (per direction)
scaled by the grid spacing;
pyteukolsky/
__init__.py # public API exports
grid.py # Grid: coordinates, FD operators, ghost fills
equation.py # TeukolskyRHS: precomputed coefficients + rhs()
evolve.py # Evolution: state, RK4 stepping, run loop, detectors, I/O
initialdata.py # swsh(), gaussian_pulse()
diagnostics.py # project_swsh(), fit_qnm_frequency()
scripts/
check_equations.py # symbolic verification — source of truth for coefficients
run_example.py # end-to-end demo: ringdown of a Gaussian pulse
tests/
test_grid.py # 10 tests: FD operators, 2nd-order convergence
test_equation.py # 16 tests: coefficient arrays, rhs() linearity
test_evolve.py # 30 tests: RK4 driver, CFL, detectors, I/O
test_validation.py # 12 tests: SWSH, Schwarzschild QNM, self-convergence
test_kerr.py # 5 tests: Kerr QNM vs tables, spin trend, pole parity
Owns the discretization; knows nothing about the physics.
-
__init__(rmin, rmax, Nmu, Nr, ghost=2, M=1.0)— builds the radial cell arrayrfrom the log map and the staggeredmuarray (both with ghosts); storesdx,drdx,d2rdx2,dr_cell,dmu, and 2D meshesR,MU. -
dr(f),drr(f)— first/second radial derivatives (chain-ruled through the$r(x)$ map). -
angular(f)— the Legendre operator$\partial_\mu[(1-\mu^2)\partial_\mu f]$ in flux form. -
fill_ghosts_r(f, outer="sommerfeld", dt=None)— extrapolate inner, radiate outer. -
fill_ghosts_mu(f, parity)— pole reflection with signparity. -
ko_dissipation_r(f, epsilon),ko_dissipation_mu(f, epsilon)— KO 4th differences.
Encapsulates the PDE for fixed
-
__init__(grid, M, a, m, dissipation=0.0)— precomputes the coefficient arraysSigma = R**2 + a**2*MU**2,Delta,A,invA = 1/A,Cv = 4*R + 4i*a*MU + 6M, the$\psi_r$ coefficientCr = 2iam+6r-6M,B = 4Mr, andV = (2*MU - m)**2/(1 - MU**2) - 2; sets the pole parityself.parity = (-1)**m. All coefficients are polynomial/rational in$\mu$ . -
rhs(psi, v) -> (dpsi_dt, dv_dt)— fills ghosts, forms spatial derivatives, assemblesdv_dt = invA*(L + B*dr(v) + Cv*v)anddpsi_dt = v, and adds KO dissipation if enabled.
The user-facing driver.
-
__init__(rhs)— holds theTeukolskyRHS, grid, and state(psi, v, t). -
set_initial_data(psi0, psi1, dt_init)— seedpsi = psi1,v = (psi1 - psi0)/dt_init(pass the same array twice for$v=0$ ). -
add_detector(r_extract)— register an extraction radius (stores interpolation weights). -
cfl_dt(cfl=0.5)— the CFL-limited time step. -
step(dt)— one RK4 update. -
evolve(t_final, cfl=0.5, dt=None, record_every=1, snapshot_every=None)— main loop: records detector time series and, optionally, full-grid snapshots. - Results:
times,waveforms(dict{r_extract: array (Nt, Nmu)}), optionalsnapshots. -
save_waveforms(path)/save_snapshots(path)— separate.npzfiles (waveforms small/long-lived; snapshots large/checkpoint-style).
-
swsh(spin, ell, m, mu)— spin-weighted spherical harmonic $sY{\ell m}(\mu)$ at$\varphi=0$ , implemented analytically for$s=-2$ ,$\ell=2$ via Wigner$d$ -matrix elements, ${-2}Y{2m}(\theta)=\sqrt{5/4\pi},d^2_{2,m}(\theta)$. Returns a real array. -
gaussian_pulse(grid, r0, sigma_r, ell=2, m=2, spin=-2, sigma_mu=None, amplitude=1.0)— $\psi=A\exp(-((r-r_0)/\sigma_r)^2),{{-2}Y{\ell m}}(\mu)$. Optionalsigma_muadds$\exp(-(\mu/\sigma_\mu)^2)$ to suppress the field near the poles where$V$ is large.
-
project_swsh(psi_mu, mu, swsh_profile)— project a detector's$\mu$ -profile onto a SWSH by midpoint-rule quadrature,$\psi_{\ell m}(t)=\int_{-1}^{1}\psi_m(t,\mu),\overline{Y(\mu)},d\mu$ . Handles shape(Nmu,)or(Nt, Nmu). -
fit_qnm_frequency(times, psi_t, t_start, t_end)— extract$(\omega_R, \omega_I)$ from a waveform slice. For real signals (Schwarzschild) it fits a damped cosine viascipy.optimize.curve_fit; for complex signals (Kerr) it does linear regression on$\log|\psi|$ and the unwrapped phase. Returns$(\omega_R>0,\ \omega_I<0)$ .
The solver is tested at every layer (73 tests total; run with pytest):
| Layer | File | What it checks |
|---|---|---|
| Grid & operators | test_grid.py |
FD operators reach 2nd-order convergence against analytic functions |
| RHS | test_equation.py |
coefficient arrays match check_equations.py; rhs() linearity |
| Evolution | test_evolve.py |
RK4 driver, CFL, detectors, snapshot/waveform I/O |
| Schwarzschild | test_validation.py |
SWSH normalization, |
| Kerr | test_kerr.py |
|
Schwarzschild
Kerr TeukolskyRHS already
carries the full
| code |
published |
|
|
|---|---|---|---|
| 0.5 | ~0.9% | ||
| 0.9 | ~0.4% |
The pole-parity factor
- M. Campanelli, G. Khanna, P. Laguna, J. Pullin & M. P. Ryan, Phys. Rev. D (2001), arXiv:gr-qc/0010034v2 — the formalism and initial-data prescription this code follows.
- S. A. Teukolsky, Astrophys. J. 185, 635 (1973) — the original perturbation equation.
- E. Berti, V. Cardoso & C. M. Will, Phys. Rev. D 73, 064030 (2006), arXiv:gr-qc/0512160 (tabulated QNM data) — reference QNM frequencies.
- E. W. Leaver, Proc. R. Soc. Lond. A 402, 285 (1985) — the continued-fraction method used to compute those frequencies.
scripts/check_equations.pyis the committed source of truth for every coefficient; keep equation cross-references pointing at it.scripts/run_example.pyoutput (*.gif,*.npz,*_static.png) is gitignored.