Tidal forces and tides

classical mechanics
tidal force
tides
fluid statics
Author

Basics

Published

November 25, 2026

This post aims at showing the origin of the tidal forces as a consequence of the motion of the Earth in an isolated two-body Earth-Moon system, and showing its effects on a static ocean. This model requires assumptions about equilibrium of fluids that make its predictions quite bad, as discussed in detailed later.

The assumptions about static solution is dropped in the following posts, where dynamics is introduced through a hierarchy of models of increasing complexity.

Before going into a detailed discussion of the topics, let’s summarize the main steps.

Earth in the Earth-Moon two-body system. The celestial mechanics of the isolated Earth-Moon two-body system is discussed, in order to show all the relevant contributions to the dynamics in a non-inertial reference frame on the Earth. First the two-body problem of classical mechanics is solved under the assumption of circular orbits, then relative kinematics is used to make fictitious forces appear in Newton equation of motion.

Forces in Earth non-inertial reference frame. An observer stationary w.r.t. the surface of the Earth is a non-inertial observer, that perceives two main fictitious forces, due to the motion of the Earth:

1 Earth-Moon two-body system

1.1 Kinematics

1.1.1 Useful reference frames

Let \(B\) be the center of mass (CM) of the Earth-Moon system, which we assume is an inertial reference frame.

  • Frame \((0)\): Inertial frame centered at \(B\) with axes \((\hat{\mathbf{x}}_0, \hat{\mathbf{y}}_0, \hat{\mathbf{z}}_0)\).
  • Frame \((1)\): Centered at \(B\), rotating with the orbital angular velocity of the Earth-Moon system \(\theta_1(t)\) around \(\hat{\mathbf{z}}_0\).
  • Frame \((2)\): Centered at the Earth’s center \(E\), tilted by the obliquity angle \(\varepsilon\) around \(\hat{\mathbf{y}}_0\) (or \(\hat{\mathbf{y}}_1\)).
  • Frame \((3)\): Centered at \(E\), rotating with the Earth’s daily rotation \(\theta_3(t)\) around \(\hat{\mathbf{z}}_2\).
  1. \(0 \to 1\): Rotation by \(\theta_1\) around \(\hat{\mathbf{z}}_0\) \[ \begin{cases} \hat{\mathbf{x}}_1 = \hat{\mathbf{x}}_0 \cos\theta_1 + \hat{\mathbf{y}}_0 \sin\theta_1 \\ \hat{\mathbf{y}}_1 = -\hat{\mathbf{x}}_0 \sin\theta_1 + \hat{\mathbf{y}}_0 \cos\theta_1 \\ \hat{\mathbf{z}}_1 = \hat{\mathbf{z}}_0 \end{cases} \]

  2. \(0 \to 2\): Tilt by \(\varepsilon\) around \(\hat{\mathbf{y}}_0\) \[ \begin{cases} \hat{\mathbf{x}}_2 = \hat{\mathbf{x}}_0 \cos\varepsilon - \hat{\mathbf{z}}_0 \sin\varepsilon \\ \hat{\mathbf{y}}_2 = \hat{\mathbf{y}}_0 \\ \hat{\mathbf{z}}_2 = \hat{\mathbf{x}}_0 \sin\varepsilon + \hat{\mathbf{z}}_0 \cos\varepsilon \end{cases} \]

  3. \(2 \to 3\): Rotation by \(\theta_3\) around \(\hat{\mathbf{z}}_2\) \[ \begin{cases} \hat{\mathbf{x}}_3 = \hat{\mathbf{x}}_2 \cos\theta_3 + \hat{\mathbf{y}}_2 \sin\theta_3 \\ \hat{\mathbf{y}}_3 = -\hat{\mathbf{x}}_2 \sin\theta_3 + \hat{\mathbf{y}}_2 \cos\theta_3 \\ \hat{\mathbf{z}}_3 = \hat{\mathbf{z}}_2 \end{cases} \]

  4. Local orhonormal basis using spherical coordinates on the Earth surface

    \[ \begin{cases} \hat{\mathbf{R}} = \hat{\mathbf{z}}_3 \cos\varphi + \hat{\mathbf{x}}_3 \sin\varphi \cos\Delta\theta + \hat{\mathbf{y}}_3 \sin\varphi \sin\Delta\theta \\ \hat{\boldsymbol{\theta}} = -\hat{\mathbf{x}}_3 \sin\Delta\theta + \hat{\mathbf{y}}_3 \cos\Delta\theta \\ \hat{\boldsymbol{\varphi}} = -\hat{\mathbf{z}}_3 \sin\varphi + \hat{\mathbf{x}}_3 \cos\varphi \cos\Delta\theta + \hat{\mathbf{y}}_3 \cos\varphi \sin\Delta\theta \end{cases} \]

1.1.2 Kinematics of the Earth w.r.t. the inertial reference frame \((0)\)

Here the Earth is modeled as a rigid body, with uniform mass distribution, so that its center of mass coincides with the geometric center \(E\). The configuration of a rigid body is completely determined by the position of one of its material point and the orientation w.r.t. a reference frame. Under the assumption of circular orbits, the position of the center of mass of the Earth \(E\) is uniquely identified by the angle \(\theta_3\) and the constant distance \(R_{E,1}\) between the center \(E\) and the center of mass of the Earth-Moon system \(B\). The distance \(R_{E,1}\) follows from the definition of the center of mass of the system

\[R_{E,1} = \frac{M_M}{M_E + M_M} R_{EM}\] (eq:RE1)

The velocity and the acceleration of \(E\) w.r.t. the inertial reference frame are

\[ \mathbf{v}_{E/B}^{(0)} = R_{E,1} \dot{\theta}_1 \hat{\mathbf{y}}_1 \qquad , \qquad \mathbf{a}_{E/B}^{(0)} = -R_{E,1} \dot{\theta}_1^2 \hat{\mathbf{x}}_1 \ , \]

The angular velocity of the Earth is \(\boldsymbol{\Omega}_E = \dot{\theta}_3 \hat{\mathbf{z}}_2\).

Since the dynamical equation w.r.t. the inertial frame is

\[M_E \mathbf{a}^{(0)}_{E/O} = G M_E M_M \frac{M - E}{\left| M - E \right|^3} \ ,\]

under the assumption of uniform circular orbits, \(\mathbf{a}^{(0)} = - R_{E,1} \Omega_1^2 \hat{\mathbf{x}}_1\), and \(M - E = - R_{EM} \hat{\mathbf{x}}_1\), it immediately follows

\[\Omega_1^2 R_{E,1} = \frac{G M_M}{R_{EM}^2} \ ,\]

with \(R_{E,1}\) given in {eq}eq:RE1.

1.2 Relative kinematics and equations of motion w.r.t. the non-inertial reference frame \((3)\)

For a point mass \(m\) at position \(P\) on the Earth’s surface, Newton’s second law in the inertial frame is:

\[ m \mathbf{a}^{(0)}_{P/B} = \mathbf{F} \]

Using relative kinematics between frame \((0)\) and frame \((3)\):

\[ \mathbf{a}^{(0)}_{P/B} = \mathbf{a}^{(0)}_{E/B} + \mathbf{a}^{(3)}_{P/E} + \boldsymbol{\alpha}_{3/0} \times \mathbf{r}_{EP} + 2\boldsymbol{\omega}_{3/0} \times \mathbf{v}^{(3)}_{P/E} + \boldsymbol{\omega}_{3/0} \times (\boldsymbol{\omega}_{3/0} \times \mathbf{r}_{EP}) \]

Solving for the acceleration \(\mathbf{a}^{(3)}_{P/E}\) observed in the Earth-fixed frame \((3)\):

\[ \mathbf{a}^{(3)}_{P/E} = \frac{\mathbf{F}}{m} - \mathbf{a}^{(0)}_{E/B} - \boldsymbol{\alpha}_{3/0} \times \mathbf{r}_{EP} - 2\boldsymbol{\omega}_{3/0} \times \mathbf{v}^{(3)}_{P/E} - \boldsymbol{\omega}_{3/0} \times (\boldsymbol{\omega}_{3/0} \times \mathbf{r}_{EP}) \]

Real force. The real force \(\mathbf{F}\) acting on a point can be written as the sum of the gravitational force due to the Earth, the gravitational force of the Moon, and other non-gravitational forces, like contact forces like the force due external reactions or to internal stress in a continuous medium.

Under the assumption of constant angular velocity of the Earth, \(\boldsymbol\omega_{3/0} = \dot\theta \hat{\mathbf{z}}_{2}\) constant, the angular acceleration is zero, \(\boldsymbol\alpha_{3/0} = \mathbf{0}\).

1.3 Forces

1.3.1 Earth gravitational pull

\[ \mathbf{F}_E = -\frac{G M_E m}{R_E^2} \hat{\mathbf{R}}_P \]

where \(\hat{\mathbf{R}}_P\) is the unit radial vector from the center of the Earth \(E\) to \(P\).

1.3.2 Tidal force: Moon gravitational pull and fictitious force due to \(- \mathbf{a}_{E/O}^{(0)}\)

Tidal force is defined as the contributions from the Moon, as the sum of the gravitational force and the fictitious force on Earth due to the motion of the center of the Earth w.r.t. the center of mass of the Earth-Moon system. Tidal force per unit mass is

\[\begin{aligned} \mathbf{g}_{\rm tidal} = \mathbf{g}_M - \mathbf{a}^{(0)}_{E/B} & = \mathbf{g}_M + \frac{G M_M}{R^2_{EM}} \hat{\mathbf{x}}_1 \\ \end{aligned}\]

Using the first order expansion of the gravitational pull from the Moon - here considered good enough for “small” \(\frac{R_{E}}{R_{EM}} \simeq 0.0166\) -, the first order expansion of tidal force reads

\[ \mathbf{g}_{\rm tidal} \approx -\frac{G M_M m}{R_{EM}^2} \frac{R_E}{R_{EM}} \left\{ \hat{\mathbf{R}}_P - 3(\hat{\mathbf{x}}_1 \cdot \hat{\mathbf{R}}_P)\hat{\mathbf{x}}_1 \right\} \]

1.3.3 Centrifugal force

Centrifugal force per unit mass reads

\[ -\boldsymbol{\omega}_{3/0} \times (\boldsymbol{\omega}_{3/0} \times \mathbf{r}_{EP}) = R_E \Omega_E^2 \sin \varphi \hat{\boldsymbol\rho}_P = R_E \Omega_E^2 \left( \sin^2\varphi \, \hat{\mathbf{R}} + \sin\varphi \cos\varphi \, \hat{\boldsymbol{\varphi}} \right) \]

since \(\hat{\boldsymbol\rho}_P = \hat{\mathbf{x}}_3 \cos\Delta\theta + \hat{\mathbf{y}}_3 \sin\Delta\theta = \hat{\mathbf{R}} \sin\varphi + \hat{\boldsymbol{\varphi}} \cos\varphi\).

1.3.4 Coriolis force

\[-2 \boldsymbol\omega_{3/0} \times \mathbf{v}^{(3)}_{P/E}\]

\[ \mathbf{F}_M = -G M_M m \frac{R_{EM}\hat{\mathbf{x}}_1 + R_E\hat{\mathbf{R}}_P}{|R_{EM}\hat{\mathbf{x}}_1 + R_E\hat{\mathbf{R}}_P|^3} = -\frac{G M_M m}{R_{EM}^2} \frac{\hat{\mathbf{x}}_1 + \frac{R_E}{R_{EM}}\hat{\mathbf{R}}_P}{\left|\hat{\mathbf{x}}_1 + \frac{R_E}{R_{EM}}\hat{\mathbf{R}}_P\right|^3} \]

Using a first-order Taylor expansion for \(\frac{R_E}{R_{EM}} \ll 1\):

\[ \mathbf{F}_M \approx -\frac{G M_M m}{R_{EM}^2} \left\{ \hat{\mathbf{x}}_1 + \frac{R_E}{R_{EM}} \left( \hat{\mathbf{R}}_P - 3(\hat{\mathbf{x}}_1 \cdot \hat{\mathbf{R}}_P)\hat{\mathbf{x}}_1 \right) \right\} \]

todo Add (or maybe a link to a section where these expansions are done once for all) the power expansion of \(|\mathbf{r} + \boldsymbol\varepsilon|^n\) for \(\frac{|\boldsymbol\varepsilon|}{|\mathbf{r}|} \ll 1\)

With \(\boldsymbol{\omega}_{3/0} = \Omega_E \hat{\mathbf{z}}_2\) and \(\mathbf{r}_{EP} = R_E \hat{\mathbf{R}}_P\): \[ \begin{aligned} -\boldsymbol{\omega}_{3/0} \times (\boldsymbol{\omega}_{3/0} \times \mathbf{r}_{EP}) &= -\Omega_E \hat{\mathbf{z}}_2 \times \left[ \Omega_E \hat{\mathbf{z}}_2 \times R_E \left( \hat{\mathbf{z}}_2 \cos\varphi + \hat{\mathbf{x}}_2 \sin\varphi \cos(\theta_3 + \Delta\theta) + \hat{\mathbf{y}}_2 \sin\varphi \sin(\theta_3 + \Delta\theta) \right) \right] \\ &= +R_E \Omega_E^2 \sin\varphi \, \hat{\rho}_P \end{aligned} \] where \(\hat{\boldsymbol\rho}_P = \hat{\mathbf{x}}_3 \cos\Delta\theta + \hat{\mathbf{y}}_3 \sin\Delta\theta = \hat{\mathbf{R}} \sin\varphi + \hat{\boldsymbol{\varphi}} \cos\varphi\). Thus: \[ -\boldsymbol{\omega}_{3/0} \times (\boldsymbol{\omega}_{3/0} \times \mathbf{r}_{EP}) = R_E \Omega_E^2 \left( \sin^2\varphi \, \hat{\mathbf{R}} + \sin\varphi \cos\varphi \, \hat{\boldsymbol{\varphi}} \right) \]

todo

2 Static ocean

Assuming the ocean is at rest with respect to the Earth, \(\mathbf{a}^{(3)}_{P/E} \simeq \mathbf{0}\), \(\mathbf{v}^{(3)}_{P/E} \simeq \mathbf{0}\) (Coriolis force is zero). The internal stress into a fluid at rest or in rigid motion is \(\mathbb{T} = - p \mathbb{I}\), so that the contribution per unit volume in momentum equation is \(- \nabla P\).

Momentum equation in the non-inertial reference frame,

\[\rho \mathbf{a}^{(3)}_{/E} = \nabla \cdot \mathbb{T} + \rho \mathbf{g} - \rho \left\{ \mathbf{a}^{(0)}_{E/B} - \boldsymbol\alpha_{3/0} \times \mathbf{r}_{P/E} - 2 \boldsymbol\omega_{3/0} \times \mathbf{v}^{(3)}_{/E} - \boldsymbol\omega_{3/0} \times \boldsymbol\omega_{3/0} \times \mathbf{r}_{/E} \right\}\]

under the assumption of static ocean, becomes

\[\mathbf{0} = -\nabla P + \rho \mathbf{g} - \rho \left\{ \mathbf{a}^{(0)}_{E/B} - \boldsymbol\omega_{3/0} \times \boldsymbol\omega_{3/0} \times \mathbf{r}_{/E} \right\}\]

Convective form of momentum differential equation in an inertial reference frame reads

\[\rho \left\{ \partial_t \mathbf{u} + ( \mathbf{u} \cdot \nabla ) \mathbf{u} \right\} = \rho \mathbf{g} + \nabla \cdot \mathbb{T} \ .\]

The term on the left-hand side of the equal is the material derivative of the velocity field, and thus the acceleration of fluid particles,

\[\mathbf{a} = \frac{D \mathbf{u}}{D t} = \partial_t \mathbf{u} + \mathbf{u} \cdot \nabla \mathbf{u} \ , \]

linking Lagrangian and Eulerian description of continuous media. Here the acceleration w.r.t. the inertial reference frame is written as a function of the kinematic variables of the non-inertial reference frame using relative kinematics,

\[\mathbf{a}^{(3)}_{P/E} = \mathbf{a}^{(0)}_{P/B} - \mathbf{a}^{(0)}_{E/B} - \boldsymbol\alpha_{3/0} \times \mathbf{r}_{P/E} - 2 \boldsymbol\omega_{3/0} \times \mathbf{v}^{(3)}_{P/E} - \boldsymbol\omega_{3/0} \times \boldsymbol\omega_{3/0} \times \mathbf{r}_{/E} \]

2.1 Projection in the local reference frame

Using spherical coordinates

We describe point \(P\) in spherical coordinates \((r, \varphi, \Delta\theta)\) stationary with respect to frame \((3)\), where \(\varphi\) is the colatitude (angle from \(\hat{\mathbf{z}}_3 = \hat{\mathbf{z}}_2\)) and \(\Delta\theta\) is the longitude relative to \(\hat{\mathbf{x}}_3\).

2.1.1 Local Orthonormal Basis \((\hat{\mathbf{R}}, \hat{\boldsymbol{\theta}}, \hat{\boldsymbol{\varphi}})\)

\[ \begin{cases} \hat{\mathbf{R}} = \hat{\mathbf{z}}_3 \cos\varphi + \hat{\mathbf{x}}_3 \sin\varphi \cos\Delta\theta + \hat{\mathbf{y}}_3 \sin\varphi \sin\Delta\theta \\ \hat{\boldsymbol{\theta}} = -\hat{\mathbf{x}}_3 \sin\Delta\theta + \hat{\mathbf{y}}_3 \cos\Delta\theta \\ \hat{\boldsymbol{\varphi}} = -\hat{\mathbf{z}}_3 \sin\varphi + \hat{\mathbf{x}}_3 \cos\varphi \cos\Delta\theta + \hat{\mathbf{y}}_3 \cos\varphi \sin\Delta\theta \end{cases} \]

2.1.2 Centrifugal Term Evaluation

With \(\boldsymbol{\omega}_{3/0} = \Omega_E \hat{\mathbf{z}}_2\) and \(\mathbf{r}_{EP} = R_E \hat{\mathbf{R}}_P\): \[ \begin{aligned} -\boldsymbol{\omega}_{3/0} \times (\boldsymbol{\omega}_{3/0} \times \mathbf{r}_{EP}) &= -\Omega_E \hat{\mathbf{z}}_2 \times \left[ \Omega_E \hat{\mathbf{z}}_2 \times R_E \left( \hat{\mathbf{z}}_2 \cos\varphi + \hat{\mathbf{x}}_2 \sin\varphi \cos(\theta_3 + \Delta\theta) + \hat{\mathbf{y}}_2 \sin\varphi \sin(\theta_3 + \Delta\theta) \right) \right] \\ &= +R_E \Omega_E^2 \sin\varphi \, \hat{\rho}_P \end{aligned} \] where \(\hat{\rho}_P = \hat{\mathbf{x}}_3 \cos\Delta\theta + \hat{\mathbf{y}}_3 \sin\Delta\theta = \hat{\mathbf{R}} \sin\varphi + \hat{\boldsymbol{\varphi}} \cos\varphi\). Thus: \[ -\boldsymbol{\omega}_{3/0} \times (\boldsymbol{\omega}_{3/0} \times \mathbf{r}_{EP}) = R_E \Omega_E^2 \left( \sin^2\varphi \, \hat{\mathbf{R}} + \sin\varphi \cos\varphi \, \hat{\boldsymbol{\varphi}} \right) \]

2.1.3 Tidal Term Projection (\(\hat{\mathbf{x}}_1 \cdot \hat{\mathbf{R}}_P\))

Expressing \(\hat{\mathbf{x}}_1\) in frame \((2)\): \[ \hat{\mathbf{x}}_1 = (\hat{\mathbf{x}}_2 \cos\varepsilon + \hat{\mathbf{z}}_2 \sin\varepsilon)\cos\theta_1 + \hat{\mathbf{y}}_2 \sin\theta_1 \] Taking the dot product with \(\hat{\mathbf{R}}_P = \hat{\mathbf{z}}_2 \cos\varphi + \hat{\mathbf{x}}_2 \sin\varphi \cos(\theta_3 + \Delta\theta) + \hat{\mathbf{y}}_2 \sin\varphi \sin(\theta_3 + \Delta\theta)\): \[ \hat{\mathbf{x}}_1 \cdot \hat{\mathbf{R}}_P = \cos\varepsilon \cos\theta_1 \sin\varphi \cos(\theta_3 + \Delta\theta) + \sin\theta_1 \sin\varphi \sin(\theta_3 + \Delta\theta) + \sin\varepsilon \cos\theta_1 \cos\varphi \]

(Note: If the obliquity \(\varepsilon = 0\), this simplifies to \(\hat{\mathbf{x}}_1 \cdot \hat{\mathbf{R}}_P = \sin\varphi \cos(\theta_3 + \Delta\theta - \theta_1)\).)

We can decompose \(\hat{\mathbf{x}}_1\) in the local basis as: \[ \hat{\mathbf{x}}_1 = (\hat{\mathbf{x}}_1 \cdot \hat{\mathbf{R}})\hat{\mathbf{R}} + (\hat{\mathbf{x}}_1 \cdot \hat{\boldsymbol{\varphi}})\hat{\boldsymbol{\varphi}} + (\hat{\mathbf{x}}_1 \cdot \hat{\boldsymbol{\theta}})\hat{\boldsymbol{\theta}} \] where:

  • \(\hat{\mathbf{x}}_1 \cdot \hat{\boldsymbol{\theta}} = -\cos\varepsilon \cos\theta_1 \sin(\theta_3 + \Delta\theta) + \sin\theta_1 \cos(\theta_3 + \Delta\theta)\)
  • \(\hat{\mathbf{x}}_1 \cdot \hat{\boldsymbol{\varphi}} = \cos\varepsilon \cos\theta_1 \cos\varphi \cos(\theta_3 + \Delta\theta) + \sin\theta_1 \cos\varphi \sin(\theta_3 + \Delta\theta) - \sin\varepsilon \cos\theta_1 \sin\varphi\)

2.2 Hydrostatic equilibrium and free surface height \(\zeta(\theta, \varphi)\)

Assuming a fluid particle is approximately at rest with respect to the Earth (\(\mathbf{a}^{(3)}_{P/E} \approx \mathbf{0}\), \(\mathbf{v}^{(3)}_{P/E} \approx \mathbf{0}\)) and \(\frac{\mathbf{F}_{\text{non-g}}}{m} = -\frac{1}{\rho}\nabla P\):

2.2.1 Component Equations

  1. Radial direction (\(\hat{\mathbf{R}}\)): \[ 0 = -g^E_r - g^M_r + 3\frac{G M_M}{R_{EM}^2} \frac{r}{R_{EM}} (\hat{\mathbf{x}}_1 \cdot \hat{\mathbf{R}}_P)^2 + r \Omega_E^2 \sin^2\varphi - \frac{1}{\rho}\partial_r P \] where \(g^E_r = \frac{G M_E}{r^2}\) and \(g^M_r = \frac{G M_M}{R_{EM}^2}\frac{r}{R_{EM}}\).

  2. Azimuthal direction (\(\hat{\boldsymbol{\theta}}\)): \[ \frac{1}{\rho r \sin\varphi} \partial_\theta P = g_{\theta, \text{tidal}} \]

  3. Polar/Colatitude direction (\(\hat{\boldsymbol{\varphi}}\)): \[ \frac{1}{\rho r} \partial_\varphi P = g_{\varphi, \text{tidal}} + r \Omega_E^2 \sin\varphi \cos\varphi \]

2.2.2 Radial Integration

Let \(r_0\) be the unperturbed spherical radius and \(\zeta(\varphi, \theta_3 + \Delta\theta)\) be the free surface elevation. Integrating the radial equation from \(r = r_0\) to \(r = r_0 + \zeta\) (assuming \(\zeta \ll r_0\)):

  • Earth’s gravity term: \[ -\int_{r_0}^{r_0+\zeta} \frac{G M_E}{r^2} dr = \left. \frac{G M_E}{r} \right|_{r_0}^{r_0+\zeta} = G M_E \left( \frac{1}{r_0 + \zeta} - \frac{1}{r_0} \right) \approx -\frac{G M_E}{r_0^2}\zeta \]

  • Tidal term: \[ -\int_{r_0}^{r_0+\zeta} \frac{G M_M}{R_{EM}^3} r \left( 1 - 3(\hat{\mathbf{x}}_1 \cdot \hat{\mathbf{R}}_P)^2 \right) dr \approx -\frac{G M_M}{R_{EM}^3} \left( 1 - 3(\hat{\mathbf{x}}_1 \cdot \hat{\mathbf{R}}_P)^2 \right) r_0 \zeta \]

Combining the integrated terms gives the pressure difference across the layer: \[ \frac{1}{\rho} \int_{r_0}^{r_0+\zeta} \partial_r P \, dr = \frac{P_{\text{atm}} - P(r_0, \mathbf{x})}{\rho} = f(\mathbf{x})\zeta \]

2.2.3 Boundary Condition on the Free Surface

On the free surface \(r_s = r_0 + \zeta(\varphi, \theta)\), the pressure is constant: \(P(r_0 + \zeta, \varphi, \theta) = P_{\text{atm}}\). Taking total derivatives along the surface: \[ \left.\frac{\partial P}{\partial r}\right|_{r_s} \frac{\partial \zeta}{\partial \varphi} + \left.\frac{\partial P}{\partial \varphi}\right|_{r_s} = 0, \qquad \left.\frac{\partial P}{\partial r}\right|_{r_s} \frac{\partial \zeta}{\partial \theta} + \left.\frac{\partial P}{\partial \theta}\right|_{r_s} = 0 \]

Using the first-order hydrostatic approximation \(\left.\frac{1}{\rho}\frac{\partial P}{\partial r}\right|_{r_s} \approx -\frac{G M_E}{r_0^2}\): \[ \begin{cases} \dfrac{\partial \zeta}{\partial \theta} \approx \dfrac{r_0^3}{G M_E} \, g_{\theta, \text{tidal}} \sin\varphi \\[10pt] \dfrac{\partial \zeta}{\partial \varphi} \approx \dfrac{r_0^3}{G M_E} \left( g_{\varphi, \text{tidal}} + r_0 \Omega_E^2 \sin\varphi \cos\varphi \right) \end{cases} \]

2.2.4 Equilibrium Tide Solution

Recognizing that the tidal accelerations derive from a potential proportional to \(|\hat{\mathbf{R}}_P \cdot \hat{\mathbf{x}}_1|^2\), these partial differential equations become: \[ \begin{aligned} 0 &= \frac{\partial}{\partial \theta} \left\{ -\zeta + \frac{r_0^4}{G M_E} \frac{M_M}{R_{EM}^3} \frac{3}{2} |\hat{\mathbf{R}}_P \cdot \hat{\mathbf{x}}_1|^2 + \dots \right\} \\ 0 &= \frac{\partial}{\partial \varphi} \left\{ -\zeta + \frac{r_0^4}{G M_E} \frac{M_M}{R_{EM}^3} \frac{3}{2} |\hat{\mathbf{R}}_P \cdot \hat{\mathbf{x}}_1|^2 + \frac{1}{2} \frac{r_0^4 \Omega_E^2}{G M_E} \sin^2\varphi \right\} \end{aligned} \]

Integrating yields the equilibrium surface elevation \(\zeta(\theta, \varphi)\) (including both the lunar tidal bulge and the rotational equatorial bulge): \[ \zeta(\theta, \varphi) = \zeta_0 + \frac{3}{2} \frac{r_0^4}{R_{EM}^3} \frac{M_M}{M_E} |\hat{\mathbf{R}}_P \cdot \hat{\mathbf{x}}_1|^2(\theta, \varphi) + \frac{1}{2} \frac{r_0^4 \Omega_E^2}{G M_E} \sin^2\varphi \]

Equilibrium Tide & Rotational Flattening (Single 3D + Frames 0-3)
"""
Equilibrium tide + rotational flattening of the sea surface, Earth-Moon system
==============================================================================
Single 3D figure with:
  - Buttons to switch between Tidal, Total, and Rotation (centrifugal) fields
  - Buttons to toggle Opacity (Opaque / Glass) and Reference Frames (0, 1, 2, 3)
  - Origins (B and E) and basis vectors (x_i, y_i, z_i) for Frames 0, 1, 2, 3

Run in Google Colab as a single cell (plotly and numpy are preinstalled).
"""
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.io as pio

pio.renderers.default = "notebook_connected"

# ───────────────────────── physical constants (SI) ─────────────────────────
G     = 6.67430e-11
M_E   = 5.9722e24          # Earth mass [kg]
M_m   = 7.342e22           # Moon mass  [kg]
r0    = 6.371e6            # mean Earth radius [m]
R_EM  = 3.844e8            # Earth-Moon distance [m]
Omega = 7.2921159e-5       # Earth spin rate [rad/s]

# ───────────────────────── user parameters ─────────────────────────
EPS_DEG       = 23.44      # obliquity: angle between spin axis and orbit normal
THETA1_DEG    =  0.0       # orbital phase of the Earth centre shown at start
SPIN_DEG      = 30.0       # theta_3: initial Earth rotation phase (non-zero makes Frame 3 distinct from Frame 2)
N_FRAMES      = 24         # frames of the theta1 slider/animation
EXAG          = {"tidal": 1e6, "total": 30.0, "rotation": 30.0}  # radial relief exaggeration
EARTH_OPACITY = 0.45       # initial opacity (<1 shows the CM/orbit inside the Earth)
SHOW_FRAMES_INIT = True    # whether Frames 0..3 triads are visible initially

eps    = np.radians(EPS_DEG)
theta3 = np.radians(SPIN_DEG)
spin   = theta3

# ───────────────────────── derived quantities ─────────────────────────
a_E = R_EM * M_m / (M_E + M_m)               # radius of the Earth-centre orbit around the CM
g0  = G * M_E / r0**2
A   = 1.5 * (M_m / M_E) * r0**4 / R_EM**3    # coefficient of (x1.R0)^2   [m]
B   = 0.5 * Omega**2 * r0**4 / (G * M_E)     # coefficient of cos^2(lat)  [m]

# ───────────────────────── reference frames (0, 1, 2, 3) ─────────────────────────
# Frame (0): inertial frame centered at B (CM)
X0 = np.array([1.0, 0.0, 0.0])
Y0 = np.array([0.0, 1.0, 0.0])
Z0 = np.array([0.0, 0.0, 1.0])


def frame1_basis(theta1):
    """Frame (1): centered at B, rotated by theta1 around z0."""
    c1, s1 = np.cos(theta1), np.sin(theta1)
    x1 = c1 * X0 + s1 * Y0
    y1 = -s1 * X0 + c1 * Y0
    z1 = Z0.copy()
    return x1, y1, z1


def frame2_basis():
    """Frame (2): centered at E, tilted by obliquity eps around y0."""
    ce, se = np.cos(eps), np.sin(eps)
    x2 = ce * X0 - se * Z0
    y2 = Y0.copy()
    z2 = se * X0 + ce * Z0
    return x2, y2, z2


def frame3_basis(th3=theta3):
    """Frame (3): centered at E, rotated by theta3 around z2."""
    x2, y2, z2 = frame2_basis()
    c3, s3 = np.cos(th3), np.sin(th3)
    x3 = c3 * x2 + s3 * y2
    y3 = -s3 * x2 + c3 * y2
    z3 = z2.copy()
    return x3, y3, z3


EZ, EA, EB = frame2_basis()[2], frame2_basis()[0], frame2_basis()[1]


def R0_hat(theta, lat):
    """Unit vector (inertial frame) of the surface point (theta, lat)."""
    theta, lat = np.broadcast_arrays(theta, lat)
    return ((np.cos(lat) * np.cos(theta))[..., None] * EA
            + (np.cos(lat) * np.sin(theta))[..., None] * EB
            + np.sin(lat)[..., None] * EZ)


def x1_hat(theta1):
    return frame1_basis(theta1)[0]


def cos_psi(theta1, theta, lat):
    """x1 . R0 in closed form."""
    return (np.cos(theta1) * (np.cos(eps) * np.cos(lat) * np.cos(theta)
                              + np.sin(eps) * np.sin(lat))
            + np.sin(theta1) * np.cos(lat) * np.sin(theta))


# ───────────────────────── fields ─────────────────────────
def zeta_tidal(theta1, theta, lat):
    return A * (cos_psi(theta1, theta, lat) ** 2 - 1.0 / 3.0)


def zeta_rot(lat):
    return B * (np.cos(lat) ** 2 - 2.0 / 3.0)


def zeta_full(theta1, theta, lat, zeta0):
    return zeta0 + A * cos_psi(theta1, theta, lat) ** 2 + B * np.cos(lat) ** 2


def sphere_mean(f, n=64, m=128):
    x, w = np.polynomial.legendre.leggauss(n)
    lat = np.arcsin(x)
    lon = np.linspace(0, 2 * np.pi, m, endpoint=False)
    LON, LAT = np.meshgrid(lon, lat)
    return np.sum(f(LON, LAT) * w[:, None]) / (w.sum() * m)


def find_zeta0(theta1):
    return -sphere_mean(lambda th, la: zeta_full(theta1, th, la, 0.0))


# ───────────────────────── helper: sub-lunar point ─────────────────────────
def wrap180(x):
    return (x + 180.0) % 360.0 - 180.0


def sublunar(theta1):
    m = -x1_hat(theta1)
    lat_s = np.degrees(np.arcsin(m @ EZ))
    L_s = wrap180(np.degrees(np.arctan2(m @ EB, m @ EA)) - SPIN_DEG)
    return [L_s, wrap180(L_s + 180.0)], [lat_s, -lat_s]


def add_controls(fig, names, labels, prefix="day = "):
    anim = dict(frame=dict(duration=120, redraw=True), transition=dict(duration=0))
    fig.update_layout(
        updatemenus=[dict(type="buttons", direction="left", x=0.0, y=-0.02, xanchor="left", yanchor="top",
                          buttons=[dict(label="Play", method="animate", args=[None, dict(anim, fromcurrent=True)]),
                                   dict(label="Pause", method="animate",
                                        args=[[None], dict(mode="immediate", frame=dict(duration=0, redraw=False),
                                                           transition=dict(duration=0))])])],
        sliders=[dict(active=0, x=0.12, len=0.85, y=-0.02, yanchor="top",
                      currentvalue=dict(prefix=prefix),
                      steps=[dict(method="animate", label=lb,
                                  args=[[nm], dict(mode="immediate", frame=dict(duration=0, redraw=True),
                                                   transition=dict(duration=0))])
                             for nm, lb in zip(names, labels)])])


theta1_list = np.radians(THETA1_DEG) + 2 * np.pi * np.arange(N_FRAMES) / N_FRAMES
names  = [str(k) for k in range(N_FRAMES)]
labels = ["%.0f deg" % (np.degrees(t) % 360) for t in theta1_list]

# ═════════════════════════ 2D maps ═════════════════════════
lon_d = np.linspace(-180, 180, 181)
lat_d = np.linspace(-90, 90, 91)
LON2, LAT2 = np.meshgrid(np.radians(lon_d), np.radians(lat_d))


def maps2d(theta1):
    th = LON2 + spin
    z0 = find_zeta0(theta1)
    return zeta_full(theta1, th, LAT2, z0), zeta_tidal(theta1, th, LAT2)


tot_all = [maps2d(t)[0] for t in theta1_list]
lim_tot = max(np.abs(z).max() for z in tot_all)
lim_tid = 2 * A / 3

fig2d = make_subplots(rows=2, cols=1, vertical_spacing=0.12,
                      subplot_titles=("Total zeta(theta, lat)  [m]", "Tidal part only  [m]"))


def frame2d(k):
    Zt, Zd = maps2d(theta1_list[k])
    Ls, Bs = sublunar(theta1_list[k])
    mk = dict(size=10, color="gold", line=dict(color="black", width=1.5), symbol="star")
    return [go.Heatmap(x=lon_d, y=lat_d, z=np.round(Zt, 4), zmin=-lim_tot, zmax=lim_tot, colorscale="RdBu_r",
                       colorbar=dict(title="m", x=1.0, y=.75, len=0.42),
                       hovertemplate="lon %{x:.0f} lat %{y:.0f}<br>zeta = %{z:.3f} m<extra></extra>"),
            go.Heatmap(x=lon_d, y=lat_d, z=np.round(Zd, 4), zmin=-lim_tid, zmax=lim_tid, colorscale="RdBu_r",
                       colorbar=dict(title="m", x=1.0, y=.25, len=0.52),
                       hovertemplate="lon %{x:.0f} lat %{y:.0f}<br>zeta_tide = %{z:.3f} m<extra></extra>"),
            go.Scatter(x=Ls, y=Bs, mode="markers", marker=mk, name="sub-lunar / antipode", showlegend=True),
            go.Scatter(x=Ls, y=Bs, mode="markers", marker=mk, showlegend=False)]


d0 = frame2d(0)
fig2d.add_trace(d0[0], row=1, col=1)
fig2d.add_trace(d0[1], row=2, col=1)
fig2d.add_trace(d0[2], row=1, col=1)
fig2d.add_trace(d0[3], row=2, col=1)
fig2d.frames = [go.Frame(name=names[k], data=frame2d(k), traces=[0, 1, 2, 3]) for k in range(N_FRAMES)]
for c in (1, 2):
    fig2d.update_xaxes(title_text="geographic longitude [deg]", range=[-180, 180], row=c, col=1)
    fig2d.update_yaxes(title_text="latitude [deg]", range=[-90, 90], row=c, col=1)
fig2d.update_layout(height=800, width=600, margin=dict(b=90),
                    title="Equilibrium sea surface (eps = %.2f deg, spin = %.0f deg)" % (EPS_DEG, SPIN_DEG))
add_controls(fig2d, names, labels)
fig2d.show()
Code

# ═════════════════════════ Unified 3D Earth + Frames 0..3 ═════════════════════════
KM = 1e3
L3 = np.linspace(-180, 180, 121)
lat3 = np.linspace(-90, 90, 61)
LON3, LAT3 = np.meshgrid(np.radians(L3), np.radians(lat3))

MODES = ("tidal", "total", "rotation")
SCALE = {
    "tidal":    (100.0, "tidal zeta [cm]"),
    "total":    (1.0,   "total zeta [m]"),
    "rotation": (1.0,   "rotational zeta [m]"),
}
nan3 = np.full((1, 3), np.nan)

n_days = 3
Omega1_Omega3 = 1. / 29.
theta3_list = np.radians(  SPIN_DEG) + 2 * np.pi * np.arange(N_FRAMES) / N_FRAMES * n_days
theta1_list = np.radians(THETA1_DEG) + 2 * np.pi * np.arange(N_FRAMES) / N_FRAMES * n_days * Omega1_Omega3

labels = ["%.3f" % ( (np.degrees(t - theta3_list[0]) / 360 )) for t in theta3_list]

def shown_field(show, theta1, th, lat):
    if show == "tidal":
        return zeta_tidal(theta1, th, lat)
    if show == "rotation":
        return zeta_rot(lat) + 0 * th
    return zeta_full(theta1, th, lat, find_zeta0(theta1))


def xyz(P):
    P = np.atleast_2d(P)
    return dict(x=np.round(P[:, 0], 1), y=np.round(P[:, 1], 1), z=np.round(P[:, 2], 1))


def build_frame_triads(theta1, theta3):
    """Return origins and basis vectors (in km) for Frames 0, 1, 2, 3 at orbital phase theta1."""

    O0 = np.zeros(3)                      # B (CM)
    OE = a_E * x1_hat(theta1) / KM        # E (Earth center)
    vec_len = 1.25 * r0 / KM              # visual length of basis arrows

    x1, y1, z1 = frame1_basis(theta1)
    x2, y2, z2 = frame2_basis()
    x3, y3, z3 = frame3_basis(theta3)

    def triad_lines(origin, vx, vy, vz, scale=1.0):
        pts = []
        for v in (vx * scale, vy * scale, vz * scale):
            pts.extend([origin, origin + v, nan3])
        return np.vstack(pts)

    def triad_tips(origin, vx, vy, vz, labels_xyz, scale=1.0):
        tips = np.vstack([origin + vx * scale, origin + vy * scale, origin + vz * scale])
        return tips, labels_xyz

    scale_f = 3000.0
    
    f0_lines = triad_lines(O0, X0*scale_f, Y0*scale_f, Z0*scale_f, scale=1.0)
    f1_lines = triad_lines(O0, x1*scale_f, y1*scale_f, z1*scale_f, scale=1.0)
    f2_lines = triad_lines(OE, x2*scale_f, y2*scale_f, z2*scale_f, scale=1.0)
    f3_lines = triad_lines(OE, x3*scale_f, y3*scale_f, z3*scale_f, scale=1.0)

    f0_tips, f0_lbl = triad_tips(O0, X0*scale_f, Y0*scale_f, Z0*scale_f, ["x0", "y0", "z0"], scale=1.0)
    f1_tips, f1_lbl = triad_tips(O0, x1*scale_f, y1*scale_f, z1*scale_f, ["x1", "y1", "z1"], scale=1.0)
    f2_tips, f2_lbl = triad_tips(OE, x2*scale_f, y2*scale_f, z2*scale_f, ["x2", "y2", "z2"], scale=1.0)
    f3_tips, f3_lbl = triad_tips(OE, x3*scale_f, y3*scale_f, z3*scale_f, ["x3", "y3", "z3"], scale=1.0)

    origins_pts = np.vstack([O0, OE])
    origins_lbl = ["B (Frame 0, 1)", "E (Frame 2, 3)"]

    return {
        "origins": (origins_pts, origins_lbl),
        "f0_lines": f0_lines, "f0_tips": (f0_tips, f0_lbl),
        "f1_lines": f1_lines, "f1_tips": (f1_tips, f1_lbl),
        "f2_lines": f2_lines, "f2_tips": (f2_tips, f2_lbl),
        "f3_lines": f3_lines, "f3_tips": (f3_tips, f3_lbl),
    }


def make_unified_3d(init_show="tidal"):
    E = EXAG[init_show]
    fac, unit = SCALE[init_show]
    lim = fac * max(np.abs(shown_field(init_show, t, LON3 + spin, LAT3)).max() for t in theta1_list)
    rlim = 2.15 * r0 / KM

    def pos(show, theta1, lon_deg, lat_rad, lift=1.0):
        lon_deg, lat_rad = np.broadcast_arrays(np.asarray(lon_deg, float), np.asarray(lat_rad, float))
        th = np.radians(lon_deg) + spin
        r = (r0 + EXAG[show] * shown_field(show, theta1, th, lat_rad)) / KM * lift
        return a_E * x1_hat(theta1) / KM + r[..., None] * R0_hat(th, lat_rad)

    def geom(show, theta1, theta3):
        c = a_E * x1_hat(theta1) / KM
        x1 = x1_hat(theta1)
        P = pos(show, theta1, np.degrees(LON3), LAT3)
        Zs = SCALE[show][0] * shown_field(show, theta1, LON3 + spin, LAT3)
        la = np.radians(np.linspace(-90, 90, 91))
        lo = np.linspace(-180, 180, 181)
        segs = []
        for l in range(-180, 180, 30):
            segs += [pos(show, theta1, l, la, 1.003), nan3]
        for b in (-60, -30, 30, 60):
            segs += [pos(show, theta1, lo, np.radians(b), 1.003), nan3]
        tri = build_frame_triads(theta1, theta3)
        return dict(
            P=P, Zs=Zs, grat=np.vstack(segs),
            eq=pos(show, theta1, lo, 0.0, 1.004),
            pm=pos(show, theta1, 0.0, la, 1.004),
            ctr=c[None, :],
            axis=np.array([c - 1.35 * r0 / KM * EZ, c + 1.35 * r0 / KM * EZ]),
            cml=np.array([[0.0, 0.0, 0.0], c]),
            em=np.array([1.6 * r0 / KM * x1, -1.9 * r0 / KM * x1]),
            moon=(-1.9 * r0 / KM * x1)[None, :],
            **tri,
        )

    def dynamic_trace_updates(show, theta1, theta3):
        g = geom(show, theta1, theta3)
        P = g["P"]
        updates = [
            dict(x=np.round(P[..., 0], 1), y=np.round(P[..., 1], 1), z=np.round(P[..., 2], 1),
                 surfacecolor=np.round(g["Zs"], 4)),
        ]
        for k in ("grat", "eq", "pm", "ctr", "axis", "cml", "em", "moon"):
            updates.append(xyz(g[k]))
        # Frame origins & triads (indices 9..18)
        o_pts, _ = g["origins"]
        updates.append(xyz(o_pts))
        for fk in ("f0", "f1", "f2", "f3"):
            updates.append(xyz(g[f"{fk}_lines"]))
            t_pts, _ = g[f"{fk}_tips"]
            updates.append(xyz(t_pts))
        return updates

    g = geom(init_show, theta1_list[0], theta3_list[0])
    P = g["P"]
    vis = SHOW_FRAMES_INIT

    surface = go.Surface(
        x=np.round(P[..., 0], 1), y=np.round(P[..., 1], 1), z=np.round(P[..., 2], 1),
        surfacecolor=np.round(g["Zs"], 4), colorscale="RdBu_r", cmin=-lim, cmax=lim, opacity=EARTH_OPACITY,
        colorbar=dict(title=unit, len=0.7, x=0.97, thickness=14),
        lighting=dict(ambient=0.55, diffuse=0.8, specular=0.25, roughness=0.5, fresnel=0.1),
        lightposition=dict(x=2e4, y=-2e4, z=2e4),
        hovertemplate="zeta = %{surfacecolor:.3f}<extra></extra>", showlegend=False,
    )

    o_pts, o_lbl = g["origins"]
    f0_t_pts, f0_t_lbl = g["f0_tips"]
    f1_t_pts, f1_t_lbl = g["f1_tips"]
    f2_t_pts, f2_t_lbl = g["f2_tips"]
    f3_t_pts, f3_t_lbl = g["f3_tips"]

    dyn = [
        surface,                                                                             # 0
        go.Scatter3d(**xyz(g["grat"]), mode="lines", line=dict(color="rgba(50,50,50,0.35)", width=1.5),
                     hoverinfo="skip", showlegend=False),                                    # 1
        go.Scatter3d(**xyz(g["eq"]), mode="lines", line=dict(color="black", width=3),
                     name="equator", hoverinfo="skip"),                                      # 2
        go.Scatter3d(**xyz(g["pm"]), mode="lines", line=dict(color="dimgray", width=3),
                     name="prime meridian", hoverinfo="skip"),                               # 3
        go.Scatter3d(**xyz(g["ctr"]), mode="markers", marker=dict(size=5, color="black"),
                     name="Earth centre"),                                                   # 4
        go.Scatter3d(**xyz(g["axis"]), mode="lines+text", text=["", "N"], textposition="top center",
                     line=dict(color="green", width=7), name="rotation axis"),                # 5
        go.Scatter3d(**xyz(g["cml"]), mode="lines", line=dict(color="magenta", width=8),
                     name="CM -> Earth centre"),                                             # 6
        go.Scatter3d(**xyz(g["em"]), mode="lines", line=dict(color="gray", dash="dash", width=4),
                     name="Earth-Moon line"),                                                # 7
        go.Scatter3d(**xyz(g["moon"]), mode="markers+text", text=["Moon (not to scale)"],
                     textposition="top center", marker=dict(size=9, color="slategray", symbol="diamond"),
                     name="Moon direction"),                                                 # 8
        # Frame origins B and E (index 9)
        go.Scatter3d(**xyz(o_pts), mode="markers+text", text=o_lbl, textposition="bottom center",
                     marker=dict(size=7, color="crimson", symbol="circle"),
                     name="Origins B & E", visible=vis),                                     # 9
        # Frame 0 basis vectors (indices 10, 11)
        go.Scatter3d(**xyz(g["f0_lines"]), mode="lines", line=dict(color="#1f77b4", width=6),
                     name="Frame 0 basis (x0,y0,z0)", visible=vis, hoverinfo="skip"),       # 10
        go.Scatter3d(**xyz(f0_t_pts), mode="markers+text", text=f0_t_lbl, textposition="top center",
                     marker=dict(size=4, color="#1f77b4"), name="Frame 0 labels",
                     visible=vis, showlegend=False),                                       # 11
        # Frame 1 basis vectors (indices 12, 13)
        go.Scatter3d(**xyz(g["f1_lines"]), mode="lines", line=dict(color="#ff7f0e", width=6),
                     name="Frame 1 basis (x1,y1,z1)", visible=vis, hoverinfo="skip"),       # 12
        go.Scatter3d(**xyz(f1_t_pts), mode="markers+text", text=f1_t_lbl, textposition="top center",
                     marker=dict(size=15, color="#ff7f0e"), name="Frame 1 labels",
                     visible=vis, showlegend=False),                                       # 13
        # Frame 2 basis vectors (indices 14, 15)
        go.Scatter3d(**xyz(g["f2_lines"]), mode="lines", line=dict(color="#2ca02c", width=6),
                     name="Frame 2 basis (x2,y2,z2)", visible=vis, hoverinfo="skip"),       # 14
        go.Scatter3d(**xyz(f2_t_pts), mode="markers+text", text=f2_t_lbl, textposition="top center",
                     marker=dict(size=4, color="#2ca02c"), name="Frame 2 labels",
                     visible=vis, showlegend=False),                                       # 15
        # Frame 3 basis vectors (indices 16, 17)
        go.Scatter3d(**xyz(g["f3_lines"]), mode="lines", line=dict(color="#9467bd", width=6),
                     name="Frame 3 basis (x3,y3,z3)", visible=vis, hoverinfo="skip"),       # 16
        go.Scatter3d(**xyz(f3_t_pts), mode="markers+text", text=f3_t_lbl, textposition="top center",
                     marker=dict(size=4, color="#9467bd"), name="Frame 3 labels",
                     visible=vis, showlegend=False),                                       # 17
    ]

    phi_c = np.linspace(0, 2 * np.pi, 361)
    static = [
        go.Scatter3d(x=[0], y=[0], z=[0], mode="markers+text", text=["CM"], textposition="bottom center",
                     marker=dict(size=6, color="red"), name="centre of mass of the system"),
        go.Scatter3d(x=a_E / KM * np.cos(phi_c), y=a_E / KM * np.sin(phi_c), z=0 * phi_c, mode="lines",
                     line=dict(color="orange", width=5), name="trajectory of Earth centre"),
        go.Scatter3d(x=1.85 * r0 / KM * np.cos(phi_c), y=1.85 * r0 / KM * np.sin(phi_c), z=0 * phi_c, mode="lines",
                     line=dict(color="rgba(120,120,120,0.5)", width=2, dash="dot"), name="orbit plane (ring)"),
        go.Scatter3d(x=[0, 0], y=[0, 0], z=[-1.5 * r0 / KM, 1.5 * r0 / KM], mode="lines",
                     line=dict(color="royalblue", width=3, dash="dash"), name="orbit normal"),
    ]

    n_dyn = len(dyn)
    fig = go.Figure(data=dyn + static)

    def make_frames_for_mode(mode_name):
        return [
            go.Frame(
                name=names[k],
                data=[go.Surface(**u) if idx == 0 else go.Scatter3d(**u)
                      for idx, u in enumerate(dynamic_trace_updates(mode_name, theta1_list[k], theta3_list[k]))],
                traces=list(range(n_dyn)),
            )
            for k in range(N_FRAMES)
        ]

    frames_by_mode = {m: make_frames_for_mode(m) for m in MODES}
    fig.frames = frames_by_mode[init_show]

    hide = dict(visible=False, range=[-rlim, rlim])
    fig.update_layout(
        template="plotly_white", height=820, margin=dict(l=0, r=0, t=65, b=60),
        title="Equilibrium sea surface — %s field (relief exaggerated x%g)" % (init_show, E),
        scene=dict(xaxis=hide, yaxis=hide, zaxis=hide, aspectmode="cube",
                   camera=dict(eye=dict(x=0.85, y=-1.25, z=0.65), up=dict(x=0, y=0, z=1))),
        legend=dict(x=0.01, y=0.99, bgcolor="rgba(255,255,255,0.78)"),
    )
    add_controls(fig, names, labels)
    # fig.layout.sliders[0].font.color = "rgba(0,0,0,0)"
    fig.layout.sliders[0].currentvalue.font.size = 14

    # Build mode buttons that update current view AND swap fig.frames
    # Note: in Plotly, buttons use `update` (restyle + relayout) and we attach frames via a small callback/js or update
    mode_buttons = []
    for m in MODES:
        m_lim = SCALE[m][0] * max(np.abs(shown_field(m, t, LON3 + spin, LAT3)).max() for t in theta1_list)
        u0 = dynamic_trace_updates(m, theta1_list[0], theta3_list[0])
        restyle_dict = {
            "x": [u["x"] for u in u0],
            "y": [u["y"] for u in u0],
            "z": [u["z"] for u in u0],
            "surfacecolor": [u0[0]["surfacecolor"]] + [None] * (n_dyn - 1),
            "cmin": [-m_lim] + [None] * (n_dyn - 1),
            "cmax": [m_lim] + [None] * (n_dyn - 1),
            "colorbar.title.text": [SCALE[m][1]] + [None] * (n_dyn - 1),
        }
        mode_buttons.append(dict(
            label=m.capitalize(),
            method="update",
            args=[
                restyle_dict,
                {"title": "Equilibrium sea surface — %s field (relief exaggerated x%g)" % (m, EXAG[m])},
                list(range(n_dyn)),
            ],
        ))

    frame_triad_indices = list(range(9, 18))
    fig.update_layout(updatemenus=list(fig.layout.updatemenus) + [
        dict(type="buttons", direction="left", x=0.0, y=1.02, xanchor="left", yanchor="bottom",
             buttons=mode_buttons),
        dict(type="buttons", direction="left", x=0.52, y=1.02, xanchor="center", yanchor="bottom",
             buttons=[dict(label="Frames 0–3: On", method="restyle", args=[{"visible": True}, frame_triad_indices]),
                      dict(label="Frames 0–3: Off", method="restyle", args=[{"visible": False}, frame_triad_indices])]),
        dict(type="buttons", direction="left", x=1.0, y=1.02, xanchor="right", yanchor="bottom",
             buttons=[dict(label="Opaque Earth", method="restyle", args=[{"opacity": 1.0}, [0]]),
                      dict(label="Glass Earth", method="restyle", args=[{"opacity": 0.45}, [0]])]),
    ])
    return fig


fig3d = make_unified_3d("tidal")
fig3d.show()