Spherical Harmonics and the Laplacian on the Sphere

Introduction

The spherical harmonics \(Y_\ell^m(\theta, \varphi)\) form a complete orthonormal set of functions on the sphere. They arise naturally as the angular part of the solutions to Laplace’s equation in spherical coordinates and play a central role in quantum mechanics, electrostatics, and geophysics.

A key property is that they are eigenfunctions of the angular Laplacian:

\[\nabla^2 Y_\ell^m = -\frac{\ell(\ell+1)}{r^2}\, Y_\ell^m\]

where \(\nabla^2\) is the full Laplacian in spherical coordinates. At fixed \(r\), the radial derivatives vanish (since \(Y_\ell^m\) does not depend on \(r\)), and the angular part alone produces the eigenvalue \(-\ell(\ell+1)/r^2\).

In this notebook we:

  1. Construct a SphericalGrid and evaluate spherical harmonics on it

  2. Verify the eigenvalue relation with grid.laplacian()

  3. Check orthonormality with surface integrals over a sphere

  4. Visualise the harmonics on the sphere

  5. Compute the eigenvalues \(\ell(\ell+1)\) from scratch on the sphere surface

[1]:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm, colors
from scipy.special import sph_harm_y

from numgrids import *

Create the Spherical Grid

We build a 3D spherical grid with coordinates \((r, \theta, \varphi)\); its axes are named r, theta and phi automatically.

  • Radial axis (\(r\)): Chebyshev nodes on \([0.5,\, 2.0]\). We work on a shell rather than a single radius so that the 3D Laplacian is well-defined; for functions that are constant in \(r\) the radial derivatives vanish.

  • Polar axis (\(\theta\)): colatitude(40) covers the full range from pole to pole. Its points \(\theta_j = (j + \frac12)\pi/40\) avoid the poles themselves, and derivatives continue across the poles (a meridian goes on at \(\varphi + \pi\)), so there is no coordinate singularity.

  • Azimuthal axis (\(\varphi\)): periodic points on \([0,\, 2\pi)\).

[2]:
grid = SphericalGrid(
    chebyshev(20, 0.5, 2.0),    # r
    colatitude(40),             # theta, pole to pole
    periodic(60),               # phi
)
R, Theta, Phi = grid.meshed_coords
print(grid)
SphericalGrid(shape=(20, 40, 60), ndims=3, axes=[
    ChebyshevAxis(num_points=20, low=0.5, high=2.0, periodic=False, name='r'),
    ColatitudeAxis(num_points=40, low=0.0, high=3.141592653589793, periodic=False, name='theta'),
    EquidistantAxis(num_points=60, low=0.0, high=6.283185307179586, periodic=True, name='phi')
])

Evaluate Spherical Harmonics on the Grid

We pick a representative set of harmonics with increasing angular complexity:

\(\ell\)

\(m\)

Description

0

0

Monopole (constant)

1

0

Dipole (z-aligned)

2

0

Quadrupole (axial)

2

2

Quadrupole (equatorial)

3

1

Octupole

4

3

Higher-order

scipy.special.sph_harm_y(l, m, theta, phi) takes the polar angle first and returns complex values. We use the real spherical harmonics \(\sqrt{2}\,\mathrm{Re}\,Y_\ell^m\) for \(m > 0\) (and \(Y_\ell^0\) for \(m = 0\)), which are real-valued and still orthonormal. grid.evaluate calls the function with the meshed coordinates.

[3]:
harmonics = [(0, 0), (1, 0), (2, 0), (2, 2), (3, 1), (4, 3)]


def real_harmonic(l, m):
    factor = 1.0 if m == 0 else np.sqrt(2)
    return lambda r, theta, phi: factor * np.real(sph_harm_y(l, m, theta, phi))


Y = {(l, m): grid.evaluate(real_harmonic(l, m)) for l, m in harmonics}
print(f"Evaluated {len(Y)} spherical harmonics on grid of shape {grid.shape}")
Evaluated 6 spherical harmonics on grid of shape (20, 40, 60)

Verify the Eigenvalue Relation

For \(f = Y_\ell^m\), the residual \(\nabla^2 f + \ell(\ell+1) f / r^2\) should vanish everywhere. We also extract a single “computed eigenvalue” as the least-squares fit of \(r^2 \nabla^2 f\) against \(f\).

[4]:
print(f"{'l':>3}  {'m':>3}  {'Expected -l(l+1)':>17}  {'Computed':>15}  {'Max residual':>13}")
print("-" * 60)
for l, m in harmonics:
    f = Y[(l, m)]
    lap_f = grid.laplacian(f)
    residual = np.abs(lap_f + l * (l + 1) / R**2 * f).max()
    computed = np.sum(R**2 * lap_f * f) / np.sum(f * f)
    print(f"{l:>3d}  {m:>3d}  {-l * (l + 1):>17d}  {computed:>15.10f}  {residual:>13.2e}")
  l    m   Expected -l(l+1)         Computed   Max residual
------------------------------------------------------------
  0    0                  0     0.0000000000       2.83e-12
  1    0                 -2    -2.0000000000       6.16e-11
  2    0                 -6    -6.0000000000       5.12e-11
  2    2                 -6    -6.0000000000       7.19e-12
  3    1                -12   -12.0000000000       3.66e-11
  4    3                -20   -20.0000000000       8.45e-12

The computed eigenvalues match \(-\ell(\ell+1)\) to high precision, confirming that SphericalGrid.laplacian() correctly implements the full spherical Laplacian including the metric terms.

Orthonormality via Surface Integrals

Each boundary face of a grid can integrate over itself. The face "r_high" is the outer sphere of radius \(r = 2\), and face.integrate includes the surface element \(r^2 \sin\theta\). Hence

\[\frac{1}{r^2}\oint Y_\ell^m\, Y_{\ell'}^{m'}\, dA = \delta_{\ell\ell'}\,\delta_{mm'}.\]

Because the colatitude axis covers the whole sphere and integrates with Fejér’s quadrature rule, the Gram matrix is the identity to machine precision.

[5]:
sphere = grid.faces["r_high"]
r_outer = 2.0
labels = list(Y)
gram = np.array([[sphere.integrate(Y[a] * Y[b]) / r_outer**2 for b in labels] for a in labels])

np.set_printoptions(precision=5, suppress=True)
print("Gram matrix of the harmonics:")
print(gram)
print(f"max deviation from the identity: {np.abs(gram - np.eye(len(labels))).max():.1e}")
Gram matrix of the harmonics:
[[ 1. -0.  0. -0.  0. -0.]
 [-0.  1. -0.  0.  0.  0.]
 [ 0. -0.  1.  0.  0.  0.]
 [-0.  0.  0.  1. -0. -0.]
 [ 0.  0.  0. -0.  1.  0.]
 [-0.  0.  0. -0.  0.  1.]]
max deviation from the identity: 2.0e-15

3D Sphere Surface Plots

We take the values on the outer sphere and draw them on a closed surface. The grid has no points exactly on the poles, so the pole values are obtained by spectral interpolation – which works across the poles – and the periodic seam at \(\varphi = 0\) is closed by repeating the first column.

[6]:
theta = np.concatenate([[0.0], grid.coords[1], [np.pi]])
phi = np.concatenate([grid.coords[2], [2 * np.pi]])
T, P = np.meshgrid(theta, phi, indexing="ij")
X, Yc, Z = np.sin(T) * np.cos(P), np.sin(T) * np.sin(P), np.cos(T)

def on_closed_sphere(f):
    # values on the outer sphere, plus interpolated pole values and the closed seam
    outer = f[-1]
    poles = grid.interpolate(f, [(r_outer, 0.0, 0.0), (r_outer, np.pi, 0.0)], method="spectral")
    values = np.vstack([np.full(outer.shape[1], poles[0]), outer, np.full(outer.shape[1], poles[1])])
    return np.hstack([values, values[:, :1]])

fig = plt.figure(figsize=(14, 12))
norm = colors.Normalize(vmin=-1, vmax=1)
for idx, (l, m) in enumerate([(0, 0), (1, 0), (2, 0), (2, 2)]):
    ax = fig.add_subplot(2, 2, idx + 1, projection="3d")
    vals = on_closed_sphere(Y[(l, m)])
    vals = vals / np.abs(vals).max()
    ax.plot_surface(X, Yc, Z, facecolors=cm.RdBu_r(norm(vals)), rstride=1, cstride=1,
                    antialiased=False, shade=False)
    ax.set_title(f"$Y_{{{l}}}^{{{m}}}$", fontsize=16)
    ax.set_box_aspect([1, 1, 1])
    ax.set_axis_off()

mappable = cm.ScalarMappable(norm=norm, cmap=cm.RdBu_r)
fig.subplots_adjust(right=0.85)
fig.colorbar(mappable, cax=fig.add_axes([0.88, 0.15, 0.03, 0.7]), label="Normalised harmonic value")
fig.suptitle("Spherical Harmonics on the Unit Sphere", fontsize=18, y=0.98)
plt.show()
../_images/examples_spherical-harmonics_12_0.png

Verifying the Gradient

For functions that depend only on the angles, the radial component of grid.gradient() must vanish, while the angular components are non-zero for \(\ell > 0\).

[7]:
print(f"{'l':>3}  {'m':>3}  {'max |grad_r|':>14}  {'max |grad_theta|':>18}  {'max |grad_phi|':>16}")
print("-" * 65)
for l, m in harmonics:
    gr, gt, gp = grid.gradient(Y[(l, m)])
    print(f"{l:>3d}  {m:>3d}  {np.abs(gr).max():>14.2e}  {np.abs(gt).max():>18.6e}  {np.abs(gp).max():>16.6e}")
  l    m    max |grad_r|    max |grad_theta|    max |grad_phi|
-----------------------------------------------------------------
  0    0        3.95e-15        1.387779e-15      0.000000e+00
  1    0        1.28e-14        9.764516e-01      5.570137e-14
  2    0        1.38e-14        1.886516e+00      3.442534e-14
  2    2        1.37e-14        1.089180e+00      2.171451e+00
  3    1        1.42e-14        3.632430e+00      3.649322e+00
  4    3        1.48e-14        3.513012e+00      4.079325e+00

Computing the Eigenvalues from Scratch

So far we verified known eigenfunctions. Now we compute them. The surface of the unit sphere is a 2D curvilinear coordinate system \((\theta, \varphi)\) with scale factors \(h_\theta = 1\) and \(h_\varphi = \sin\theta\). SphericalSurfaceGrid builds the Laplace–Beltrami operator from these scale factors, and eig finds its spectrum. No boundary conditions are needed: the sphere has no boundary, and with a colatitude axis the poles are ordinary points.

We expect the eigenvalues \(\ell(\ell+1) = 0, 2, 6, 12, \ldots\), each with degeneracy \(2\ell + 1\).

[8]:
surface = SphericalSurfaceGrid(colatitude(20), periodic(40))

eigenvalues, modes = (-surface.laplacian_operator()).eig(k=16)
print(np.round(eigenvalues, 10) + 0.0)
[ 0.  2.  2.  2.  6.  6.  6.  6.  6. 12. 12. 12. 12. 12. 12. 12.]
[9]:
fig, axes = plt.subplots(1, 4, figsize=(18, 4))
for ax, i in zip(axes, [0, 1, 4, 9]):
    mode = modes[i] / np.abs(modes[i]).max()
    surface.plot(mode, ax=ax, cmap="RdBu_r", colorbar=False, vmin=-1, vmax=1)
    ax.set_title(f"eigenvalue {round(eigenvalues[i], 10) + 0.0:.4f}")
plt.tight_layout()
plt.show()
../_images/examples_spherical-harmonics_17_0.png

The computed spectrum reproduces \(\ell(\ell+1)\) with the correct degeneracies \(1, 3, 5, 7\) – the eigenmodes are (linear combinations of) the spherical harmonics, shown above in the \((\theta, \varphi)\) plane.

Summary

This notebook demonstrated:

  1. ``SphericalGrid`` with a colatitude axis that covers the sphere from pole to pole, and grid.evaluate for sampling functions.

  2. Vector calculus: grid.laplacian reproduces \(\nabla^2 Y_\ell^m = -\ell(\ell+1) Y_\ell^m / r^2\) and grid.gradient has no radial component for angular functions.

  3. Surface integrals with grid.faces["r_high"].integrate, confirming orthonormality to machine precision.

  4. ``cartesian_coords`` for 3D visualisation.

  5. ``SphericalSurfaceGrid``, whose Laplace–Beltrami eigenvalues computed with eig are exactly \(\ell(\ell+1)\) with the correct degeneracies.