Skip to content

What would a clock inside a shell measure?

A clock can run slowly where the gravitational force vanishes. We let the source, the material pressure and the clock respond to one scalar field. A second shell, two sheets of light and a laboratory clock comparison test different parts of that proposal. Moving bound pairs test whether their rest energies predict their inertia.

Which clock reading tests the field equation?

An observer at the center of a hollow spherical shell feels no gravitational force. A clock there still runs slowly relative to a distant clock. In the previous moving-channel model the quantity that shifted the clock had to point in a direction. The shell's symmetry prohibited any such direction at the center. A scalar field can remain nonzero there. Previous shell test

This study lets a positive-energy scalar on a lattice change the local clock gates and the propagation of packets. We calibrate the optical response to the vacuum exterior of one spherical source. We then let the field and the material radius of a shell adjust together. A single shell gives the same static readings as Einstein gravity, including its material pressure and its total mass. That result survives a force-free interior.

Comparison reserved after the exterior calibrationWhat happens
A second shell surrounding two clocksIn a stationary example the clock and rod ratio is 527/507. A spherical Einstein vacuum requires 1.
A shell undergoing radial pulsationsThe sourced scalar carries energy away as a spherical wave. Einstein gravity has a static spherical vacuum exterior.
Two sheets of light after calibration with cold matterWith the cold-matter pair normalized to 1, the positive scalar predicts 4. Linearized Einstein gravity gives 3.
A bound pair used as a rod and a clockAfter calibrating its size and breakup frequency, its measured model dispersion still misses the common-metric prediction.
Published strontium clock readings one centimeter apartThe measured differential shift agrees with a separate height and gravimeter calibration. The experiment samples Earth's local gradient.

The full goal is a single microscopic law for matter, clocks, light and the field they source. The scalar candidate, the constrained energy benchmark and the lattice tensor model below have different microscopic assumptions. Their successes cannot be combined into one finished theory. The material challenge is to recover universal rods and the stress-dependent field through the same dynamics.

How the local clock and light gates respond

Sections in this chapter

A scalar field constant inside a hollow shell can shift a local clock without supplying a force at the center. To implement that in the walk, give each cell a real coordinate u and a conjugate momentum. Couple neighboring u values by positive harmonic springs, fix u=0 at infinity, and let the local spin gates depend on u. In the static continuum limit take the gradient coefficient to be c⁴/(2πG). Its numerical normalization and the following material functions must be supplied or measured.

At a fixed global tick period let the fraction N=(1−u)/(1+u) multiply a rest clock's dimensionless mass phase m₀. Let A=(1+u)² be the candidate rod scale. Use two different spin axes on the outgoing and returning stages for each coordinate direction. Around that direction tilt the axes oppositely so that their mean has magnitude wγ=w₀N/A, where w₀ is the reference packet speed in cell units. The six gates remain unitary and the high-symmetry zero-momentum crossing has coordinate speeds wγ in all three directions. The proper speed inferred with clocks N and rods A is w₀. The bound-state chapter independently tests whether actual matter can provide those rods. Earlier six-gate derivation

For the doubled massive walk, set m=m₀N and mean spin-axis magnitude wₘ=wγ√(tan m/m), in its real interval with wₘ≤1. A direct spin calculation along a coordinate axis gives cos Ω=cos m [1−2wₘ²sin²(k/2)]. Its rest phase and its quadratic kinetic dispersion agree with N√[m₀²+(w₀k/A)²] through order k². The full finite-momentum band has measurable corrections. A stationary occupation in a slowly changing patch feeds back on the conjugate field momentum through its quasienergy derivative. For a held, positive rest excitation this derivative is (ℏm₀/T)N′(u). Using the same energy derivative for source and detector imposes reciprocity. An exact continuous conserved energy for arbitrary driven Floquet states does not follow.

Propagate through a nonuniform patch

Implement each fine shift by rotating the local spinor into the selected basis, shifting the two components by opposite fine cells, then rotating back at each destination. This preserves the full norm. For tilts made by real rotations around a perpendicular axis, the two stages in one coordinate direction have first-order generator σᵢ[wγ∂ᵢ+(∂ᵢwγ)/2] in the real-time transport equation with an overall minus sign. The derivative of wγ is required for norm conservation of the half-density wavefunction.

The checker compares the actual axial slice of the six-stage unitary with an independent characteristic solution. In a periodic smooth coordinate y defined by x=y+0.2 sin y, choose the material field that makes wγ=0.6(1+0.2 cos y). The right-moving continuum envelope then translates uniformly in y, with amplitude divided by √(dx/dy). Refining the grid tests the measured propagation, including this change of amplitude, at the same final time. This verifies a selected static background and a low-momentum matter calibration; the spring field and the shell matter still have to supply that background self-consistently.

Lapse and momentum for moving packets

If two pulses really change how far a time slice advances, their order has a geometric consequence. In flat space, advance first with a uniform pulse and then with a pulse whose duration grows linearly along y. Undo the pulses in that same order. The loop leaves a small translation along y. Its size, to leading order, depends on the clocks and the gradient applied. Every test packet on that slice should see the same translation. This is the matter part of the hypersurface-deformation test with a common spatial metric. Teitelboim’s derivation90096-1)

We can perform a related control sequence on the untilted, massless six-stage walk. Prepare two packets with exactly the same position envelope along y. Change only their carrier momentum along x. One simulation shifted the first packet by 0.863 cells and the second by 0.447 cells. A third input stayed centered. These are predicted position counts for a particular choice of clock pulse. The pulse uses an additional two-state control.

Carrier momentum along xDisplacement per squared pulse angle in the weak limitMean displacement after 24 finite loops, in cells
00.9218800.863317
π/40.4609400.447500
π/200

How to generate and read the pulses

One unitary tick W has eigenphases ±Ω with cos Ω = cos kₓ cos kᵧ cos k_z. Momenta are in inverse coarse cells and time is in ticks. Select the local Hermitian energy H = (W† − W)/(2i). A state with tick eigenvalue exp(−iΩ) has energy sin Ω. For a real spatial pulse profile f, use H[f] = (fH + Hf)/2. A constant f generates a uniform pulse. The choice f = y supplies a gradient. On the finite ring the gradient has a seam far from the prepared packet.

A local circuit realizes both pulse generators to first order in the tunable rotation angle. Its two control labels hold identical copies of the walk. A rotation at each site mixes the copies through the angle θf/4. Conjugate this rotation by a forward or inverse tick on one copy at a time. Use four such layers, in the order (copy 1, W, minus), (copy 0, W†, minus), (copy 1, W†, plus), (copy 0, W, plus). The signs specify the rotation. Their summed first-order generator is σᵧ on the copy label times H[f]. The checker uses each layer and its exact inverse. Circuit and position-count replay

Let P₁ and Pᶠ denote the resulting uniform and graded pulses. The loop PᶠP₁(Pᶠ)⁻¹(P₁)⁻¹, read from right to left, has leading generator B = i[H,H[f]]. The control label disappears at this order because σᵧ² = 1. For any profile, B = i[H²,f]/2 exactly as an operator identity. In the infinite-lattice linear-gradient limit, H² = (1 − cos²kₓ cos²kᵧ cos²k_z)I gives B = cos²kₓ cos²k_z sin kᵧ cos kᵧ. A packet’s displacement per θ² is the momentum derivative of B averaged over its preparation. For motion along y this is the average of cos²kₓ cos²k_z cos(2kᵧ). For two preparations with the same y profile and zero z momentum, the response relative to the zero-x carrier is exactly cos²kₓ whenever the reference response is nonzero. On the branch near zero, the relative discrepancy is below 1% for wavelengths along x longer than 62.7 coarse cells. The response changes sign for a narrow packet centered along y at π/2.

The table uses a 128-site y ring, zero z momentum and a compact envelope proportional to 1 + cos(πy/9) on sites −8 through 8. Its two-site coherence is 0.921880. In the first row the measured coefficients at pulse angles 0.04, 0.02 and 0.01 are 0.917489, 0.920774 and 0.921603, approaching that independent prediction. For the finite-count column we alternate loops at +0.2 and −0.2 for twelve pairs. Norm is conserved and the final probability within ten cells of the seam is below 10⁻¹⁴. The difference between the first two mean positions is 0.416 cells. With independent, ideal position detections, 1,892 preparations per setting suffice for at least 95% probability that their sample means are ordered correctly, using the computed variances and the one-sided Chebyshev bound. Pulse imperfections and detection loss require separate calibration.

The phase that the original tick accumulates is Ω. Repeating the continuum matter-bracket test for that choice gives a coefficient Ω∂ᵢΩ for the local translation generator. In a relativistic band with squared speed w² that coefficient is w²kᵢ. For the shell chapter’s massless tilted axial gates, cos Ω = 1 − w²(1 − cos k). At w = 4/5 and k = π/2 the coefficient is 0.824928 against 1.005310 for the continuum law. That 82.1% ratio concerns the generator. The displacement table uses the finite-depth sin Ω pulse and takes a further momentum derivative. Both the choice of clock and the carrier momentum are experimentally meaningful.

A packet localized in all three directions

The zero displacement at kₓ = π/2 in the first table requires a sharp transverse momentum. What happens when the source occupies a finite volume? Prepare a product envelope with amplitudes (1, 2, 3, 2, 1) on five consecutive coarse sites along each axis and an x-directed carrier. All 125 occupied sites lie on the even fine-site grid. The position standard deviation is 0.918 coarse cells along each axis. A real-space calculation applies the six spin-dependent half-cell shifts in order x, y, z, z, y, x. It predicts weak y displacements of 0.306532, 0.200831 and 0.095130 coarse cells per squared pulse angle at respective x carriers 0, π/4 and π/2. All three preparations have the same position distribution. A spread of x momenta gives the π/2 preparation a positive response.

An independent check uses H² = 1 − cos²kₓ cos²kᵧ cos²k_z, which is scalar in spin. With the pulse order above, B = i[H,H[y]] = i[H²,y]/2. The weak displacement is 2 Im ⟨yψ|Bψ⟩. In momentum space this gives the average of cos²kₓ cos(2kᵧ) cos²k_z. For a real separable envelope centered at carrier (Kₓ,0,0), it equals Cᵧ(1 + Cₓ cos 2Kₓ)(1 + C_z)/4, where Cᵢ is the normalized envelope overlap with its translate by two coarse cells along axis i. Here Cᵢ = 10/19 on every axis. The result holds for any fixed spin preparation, including a spin mixture independent of position. Replay the three-dimensional packet

Two equal-energy waves that a spatial shift can distinguish

On a fixed lattice, can any choice of the local clock coupling reproduce a spatial shift? Take the actual phase per tick on the regular positive band, Ω(k) = arccos(cos kₓ cos kᵧ cos k_z). Use one coarse cell and one tick as units, with ℏ = 1. The limiting speed at the node is then one. On the line k = (π/2,y,0), Ω = π/2 for every y. The spin direction is (cos y,sin y,0), so the overlap of normalized positive-band spinors at y and y+Q has magnitude cos(Q/2) for |Q| < π. Published six-shift dispersion

Let H₀ generate the uniform clock and H[N] specify its modulation by a spatial profile N. Between any two eigenstates with the same H₀ energy, the matrix element of [H[N],H₀] vanishes for every H[N]. This also applies if H₀ is a single-valued function of Ω on this band patch. By contrast, the usual generator of a spatial shift with velocity profile ∂ᵧN is the symmetrized product of ∂ᵧN and pᵧ. For N = exp(iQY), which combines two real modulations, its matrix element has magnitude

|Q(y+Q/2) ⟨u(y+Q)|u(y)⟩| = |Q(y+Q/2) cos(Q/2)|.

At y = Q = π/4 this is 0.854843 in the chosen units. On successively larger periodic lattices Q can approach zero while y remains fixed. Dividing by |Q| then gives |y|, compared with zero for the clock commutator. The finite-Q number uses the stated shift ordering and spinor overlap. A regular local correction containing derivatives of the shift profile contributes at order Q² or higher. Preserving ordinary translations for a uniform shift therefore preserves the discrepancy at first order in Q. A discrete theory that only realizes these spacetime generators in its low-momentum limit has a different requirement.

For a narrow packet, the Poisson bracket of N(X)E(p) with E(p) gives E ∇ₚE · ∇N. The geometric shift would give p · ∇N. Equality for every direction requires E² = |p|² + constant on the connected patch. The native phase does approach this condition near zero. Its expansion is Ω ∂ᵢΩ = kᵢ[1 − Σⱼ≠ᵢ kⱼ²/3] + O(|k|⁵). Along each axis the condition holds locally. At k = (π/4,π/4,0), the ratio for either nonzero component is 4/(3√3). These statements concern the clock and spatial rods of the isolated walk. Teitelboim, normal and tangential hypersurface deformations90096-1)

How a moving material can close the local bracket

The earlier one-dimensional material model already shows how a rod can carry the difference between ray momentum and energy flow. A three-dimensional example checks the bracket itself for an anisotropic band. Introduce three dynamical scalar material labels Φᴬ and a ray phase θ in an assumed Minkowski metric, with signature (−,+,+,+). Their gradients define a positive matrix Bᴬᴮ = ∂Φᴬ·∂Φᴮ. The material velocity u is the future unit four-vector satisfying u·∂Φᴬ = 0 for each label. Define kᴬ = ∂Φᴬ·∂θ. These three scalars equal the components of physical phase momentum in the unstrained resting material. This definition chooses how the band changes when strained. One-dimensional moving-material calculation

E(k) = Ω(k),     Y = u·∂θ + E(k),
L = −ρ(B) + Y²/(2g),        ρ(B) = [tr(B)−1]/2,        g > 0.

Here L is the matter Lagrangian density in Cartesian inertial coordinates. Use a single smooth positive-energy patch and define the proper action density n = −Y/g. In the resting material, θ̇ = −E−gn and the ray energy density is nE+gn²/2. The quadratic density term specifies a repulsive compressibility and makes the local phase dynamics regular. The dilute limit recovers the chosen single-ray frequency. The full material stress also depends on the strain prescription. Neither that pressure law nor the material’s inertial density is measured by the walk.

There is a pointwise check before any numerical calculation. Write q for all four scalar fields, v = q̇, and wᵢ = ∂ᵢq. Invariance of L under an infinitesimal boost gives Σ(Lᵥwᵢ + L_wᵢv) = 0, with the sum over fields. Where the Legendre map is invertible, π = Lᵥ, h_π = v and h_wᵢ = −L_wᵢ. Thus

Σ h_π h_wᵢ = Σ π wᵢ = Dᵢ,
{H[N],H[M]} = ∫ (N∂ᵢM−M∂ᵢN) Dᵢ d³x,     H[N] = ∫ N h d³x.

The second line follows by integrating the field Poisson bracket by parts for periodic or decaying profiles. With this active field convention the physical translation momentum density is −Dᵢ. At unstrained rest the phase carries n p and the material supplies n[(E+gn)∇ₚE−p]. For g = 1/2, n = 0.2 and p = (π/2,π/4,0), the bare phase momentum is (0.314159,0.157080,0), while the total is (0.236286,0,0).

The kinetic Hessian at unstrained rest and Y = 0 is diag(1,1,1,0) + (∂ᵥY)(∂ᵥY)ᵀ/g. Its last gradient entry is one, so this matrix is positive definite and remains so in a neighborhood. The replay also tests a moving, strained state with positive laboratory action density 0.037214. Two finite-difference step sizes agree within 0.000002 in all four positive Cholesky diagonal entries. The first calculation gives 1.02568, 1.02114, 1.05258, and 1.33845. Independent temporal and spatial derivatives agree in the bracket density to within 10⁻⁹. This checks local Legendre regularity in a concrete sector. It establishes the normal–normal matter bracket under the chosen relativistic continuum dynamics. A dynamical metric with its own constraints and a microscopic realization by the quantum walk remain separate requirements. Replay the band and material calculations

A force measurement in a cesium band

Ben Dahan and colleagues prepared cold cesium atoms in the ground band of a standing light wave. Ramping the frequency difference between the two lattice beams set a constant inertial force in the lattice frame. After a selected evolution time, the group switched off the lattice and measured the momentum distribution by Raman spectroscopy. The slope of the mean velocity gave the inverse inertial mass through d⟨v⟩/dt = F/m*. The response changed sign between the band center and edge under the same force. Ben Dahan et al., Figs. 3 and 4(b)

Ground-band momentumMeasured m*/m_Cs, approximatePlotted vertical half-spanCalculated band valueWith momentum resolution
q = 0, zone center+1.810.30+2.16+2.18
q = k, zone edge−1.890.41−1.55−1.59

Both rows use the nominal depth U₀ = 5.7 Eᵣ. The measured values and bar lengths are digitized from the rightmost pair of points in Fig. 4(b). The paper describes the center mass as about twice the free-atom mass. It gives no confidence level for the mass error bars. The independent calculation uses the paper's potential U(z) = U₀ sin²(kz) and single-photon recoil Eᵣ = ℏ²k²/(2m_Cs). With x = q/k and s = U₀/Eᵣ, the plane-wave Hamiltonian has diagonal entries (x+2j)²+s/2 and adjacent entries −s/4. The curvature of its lowest eigenvalue ε gives m_Cs/m* = ε″(x)/2. For the last column the replay averages the curvature over a Gaussian of width σ_q = k/18 before taking its inverse, using the momentum resolution reported by the authors. The measured points set neither the depth nor any fitted curvature in this replay. The comparison tests the sign and approximate magnitude of inertia in a sinusoidal cesium band. The walk's pulse echo requires its own measurement. Band and marker replay

For a reproducible graphic reading, the original Fig. 4 bitmap is 1284 × 804 pixels. Its +2 and −2 ticks are at rows about 76.5 and 599. The 5.7 Eᵣ marker centers are at rows 101 and 584.5, with bar ends near 62–140 and 532–638, measured down from the bitmap's top. One pixel is about 0.008 in mass-ratio units. The inspected PDF has SHA-256 fbe520e14974219874debf7879a604609cf6014ffd3ad3df0ad3195a56dcfeb9. Full paper, page 4

Let six source occupations set the central clock

Sections in this chapter

Place a scalar coordinate u on each of 27 material cells in a 3 × 3 × 3 cube. Anchor the neighboring exterior cells at u=0. Each undirected nearest-neighbor bond stores energy κ(Δu)²/2. A held rest occupation with bare energy m has energy mN(u), where N=(1−u)/(1+u) is the same local gate law used for the clock. Take six equal occupations on the nearest axial neighbors of the center. All 27 interior coordinates are free to adjust. Only the outside boundary is fixed.

The stationary equation is κLu=2m/(1+u)² on an occupied site; it is Lu=0 on an empty one, with L the positive graph Laplacian. This follows by varying one common energy. For nonnegative rest loads the Hessian is the positive Dirichlet Laplacian plus diagonal 4m/(1+u)³ in the physical range. The static solution in that range is unique.

By cubic symmetry the center and the six occupied sites have the same value s. The twelve edge and eight corner values are 2s/5 and s/5. Force balance at each occupied site gives s(1+s)²=10m/(17κ). Choosing m/κ=544/1715 gives s=1/7, so the central clock runs at 3/4 of its unloaded reference rate. The vector force at the center vanishes by inversion. This is a finite material calculation with a discrete set of sources, not a discretized continuum thin shell. A Newton solve of all 27 site equations independently reproduces the four values.

The clock changes what it measures

Let a probe add bare rest energy ε at the central site and allow all the coordinates to settle. In the limit ε→0 the derivative of the minimized energy with respect to ε is exactly the original clock rate N(s). The next derivative is −[N′(s)]² times the central element of the inverse stiffness matrix. For the example that inverse element is 7/(34κ). The curvature of the energy is therefore −16807/(34816κ). The full grid solve checks both derivatives.

A finite clock calibrated against the same probe in the empty cube measures a slightly different ratio. The code computes that ratio without linearizing the site forces. A rapid transition with the medium frozen would read the fixed-coordinate gap instead. The difference distinguishes a probe that relaxes the source from one that samples it quickly. The calculation uses a classical field at its energy minimum and pinned rest occupations. Quantum field fluctuations, the cost of the pins and the constitution of the rods need additional dynamics for a universal material theory.

A shell supported by its own material pressure

Sections in this chapter

A spherical material shell can hold itself at a fixed radius in the static Einstein benchmark. Its proper energy fixes the exterior mass, its tangential pressure balances gravity, and a clock anywhere in the empty interior runs at the same reduced rate. A concrete area-elastic material gives an interior rate of 3/4 of the rate at infinity and a positive restoring force for radial motion. This calculation assumes Einstein gravity, physical lengths from its spatial metric, and universal metric coupling. Numerical and exact replay

Varying both fields and the shell radius

Use isotropic coordinates with spatial line element ψ⁴(dr² + r²dΩ²), lapse N = χ/ψ and zero shift. The matter action for a static shell is minus its proper energy E(A) times its clock rate N. The shell's area is A = 4πq²ψ(q)⁴, where q is its isotropic coordinate radius. At fixed particle content and entropy, positive tangential surface pressure is P = −dE/dA and proper surface energy density is σ = E/A.

For this benchmark take the static Einstein–Hilbert action with the boundary term for a fixed asymptotically flat metric, per unit time at infinity. The three-dimensional scalar curvature is −8ψ⁻⁵Δψ. Consequently the gravitational bulk integrand N√g R⁽³⁾ becomes −8χΔψ. Integrating by parts with the matching boundary term gives the stationary functional

I = [c⁴/(2πG)] ∫ ∇χ · ∇ψ d³x − [χ(q)/ψ(q)] E(A).

The cross term follows from the Einstein action. The benchmark supplies no microscopic derivation of this gravitational action or independent dynamics for either scalar. The boundary normalization sets I to zero for empty Minkowski spacetime. Arnowitt, Deser and Misner, the gravitational action and total energy

Each field is harmonic away from the shell. Regularity makes both interior fields constant. At infinity both tend to one. Write p = ψ(q), h = χ(q), a = q(p−1), d = q(h−1) and K = 2c⁴/G. The exterior fields are ψ = 1+a/r and χ = 1+d/r. Evaluating the exterior gradient integral gives an exact three-variable action. Its three stationary conditions are

I(q,p,h) = Kq(p−1)(h−1) − (h/p)E(4πq²p⁴),

∂ₕI = 0:   Kq(p−1) = E/p,
∂ₚI = 0:   Kq(h−1) = −h(E+4AP)/p²,
∂qI = 0:   K(p−1)(h−1) = −2hAP/(qp).

In the radius variation p and h are held fixed. This is equivalent to varying the exterior integration constants together with the radius because (q,p,h) are independent coordinates on this family. Holding q fixed throughout would assign the missing radial force to an unspecified support.

Binding, pressure and the interior clock

Let R = qp² be the physical area radius, m₀ = E/c² the proper mass including material energy, μ = Gm₀/(Rc²) and M the ADM mass seen at infinity. On the regular ordinary exterior branch 0 < μ < 1, the three equations imply

p = 1/(1−μ/2),      P/σ = μ/[4(1−μ)],      h = 2−p,      d = −a,
N_inside = h/p = 1−μ = √[1−2GM/(Rc²)],
M = 2ac²/G = m₀ − Gm₀²/(2Rc²).

Thus the exterior is the exact Schwarzschild exterior in isotropic coordinates. In the empty interior the spatial scale is constant and local gravity vanishes. The common clock rate remains calibrated to infinity. The on-shell action equals −Mc². A separate static mass check includes the two tangential stress directions and gives N_inside(E+2AP) = Mc². Strain energy enters m₀ through the material function E(A). The value of m₀ can change during an adiabatic change of area.

The full Israel junction equations provide an independent check. With flat interior and Schwarzschild exterior, the angular equation for radial shell motion and its ordinary-branch first integral are

√(1+Ṙ²/c²) − √[1−2GM/(Rc²)+Ṙ²/c²] = Gm₀/(Rc²),
Mc² = E(R)√(1+Ṙ²/c²) − G E(R)²/(2Rc⁴).

The dot denotes proper time on the shell. The static tangential junction equation gives P = c⁴[(1−GM/(Rc²))/N_inside−1]/(8πGR), which yields the same pressure. These are known thin-shell relations. The radius variation above recovers the support pressure directly from the material action. Israel, thin-shell junction conditions · LeMaitre and Poisson, spherical equilibria and dynamics

Which gravitational equation the restricted variation loses

Restricting the spatial metric to one conformal factor before varying retains only its trace equation. In a static vacuum one also needs the trace-free part of N Ricᵢⱼ − DᵢDⱼN = 0, where D is the spatial covariant derivative. For the two harmonic exterior fields the exact Cartesian-coordinate residual is

ψ² [N Ricᵢⱼ − DᵢDⱼN] = −(a+d)(3nᵢnⱼ−δᵢⱼ)/r³,     nᵢ = xᵢ/r.

The free-radius stationarity condition and the material stresses select d = −a for this single spherical shell, so the residual vanishes. A generic solution of the two independent vacuum Laplace equations has a nonzero residual. The spherical calculation therefore cannot establish a full tensor theory from two scalar field equations.

A causal material with radial restoring force

The radial first integral supplies a positive kinetic term EṘ²/(2c²). Define the energy at rest U(R) = E(R) − GE(R)²/(2Rc⁴). A strict radial minimum requires U′ = 0 and U″ > 0, with E differentiated along the adiabatic material law. Define w = P/σ and η = dP/dσ. The squared material sound speed for this isotropic surface equation of state is c²η. Area conservation of material energy gives dE/dR = −2AP/R. At equilibrium,

R²U″/E = (1−μ)[4η(1+w)−2w] − μ(1+2w)²,
Ω_proper² = c² U″/E,
η > w(3+8w+8w²)/[2(1+w)]   for a radial restoring force.

As a concrete material law, choose a reference radius R₀ with μ₀ = 1/4, area A₀ and proper energy E₀. Write x = A/A₀. The stored energy E(A)/E₀ = [3x + 13x⁻¹ᐟ³]/16 specifies a compressible shell. Its stress-free area occurs at x = (13/9)³ᐟ⁴, so the working area is under compression. At x = 1 it gives w = 1/12, η = 1/3 and sound speed c/√3. The critical derivative for radial stability here is 67/468. All three stationarity conditions hold, and

N_inside = 3/4,        GM/(R₀c²) = 7/32,
Ω_proper² = (89/144)c²/R₀²,       Ω_infinity² = (89/256)c²/R₀².

A causal bound follows for this family of spherical equilibria independent of the particular example. At η = 1, marginality occurs at the positive root of 8w³+8w²+w−2 = 0. If 0 ≤ η ≤ 1 and the restoring force is strictly positive, then w < 0.382439, μ < 0.604705, and N_inside > 0.395295, with these displayed thresholds rounded. The equivalent upper threshold for GM/(Rc²) is 0.421871.

The example tests radial, adiabatic perturbations only. Its area response supplies a bulk modulus but assigns no independent surface shear or bending stiffness. Pitre, Schneider and Poisson found growing nonspherical modes for the infinitesimal barotropic perfect-fluid shell over the parameters they sampled. Establishing stability for a physical elastic shell would also require its response to shear, bending and nonspherical motion. Pitre, Schneider and Poisson, nonradial shell stability

Run the standard-library replay to check the three first derivatives, binding energy, junction pressure and kinetic relation, the omitted tensor equation, the second derivative of the independently evaluated ADM energy, and the causal threshold. Run shell.py

One scalar passes the single shell and fails the nested shells

Sections in this chapter

Consider a local material variable u whose free energy is a positive sum of squared differences between neighboring cells. In the static continuum limit use (c⁴/2πG)∫|∇u|² d³x. The boundary value at infinity is zero. In the vacuum between sources u is harmonic. This is a new scalar degree of freedom, independent of the compatible displacements in the previous study.

Choose two material responses to the same u. A clock in a uniform patch runs at N(u)=(1−u)/(1+u) relative to infinity. A spatial interval dx has proposed proper length A(u)dx with A(u)=(1+u)². These functions are calibrated to the Schwarzschild exterior in isotropic coordinates. In spherical vacuum with u=a/r they reproduce its clock rate and its optical delay. The meaningful tests are what happens when matter is varied, when stress supports a shell, and when a second source changes the background. The independent bound rod tested later does not automatically implement A.

A shell that supplies its own pressure

In this chapter set G=c=1, so energy, mass and length have the same unit. For a shell at coordinate radius r and scalar value u, its area is 4πR² with R=rA(u). Let μ(R) be its proper material energy, including the energy of compression. The field is constant inside and falls as ru/r′ outside. The full static energy after eliminating the field in each open region is

E = N(u) μ(r A(u)) + 2 r u².

Vary u and r independently. The u equation equates the integrated scalar charge to the jump in the radial field gradient. The r equation supplies the pressure needed to hold the shell together. The exterior mass inferred from the asymptotic clock rate is M=2ru. Substitution of both stationarity equations gives M=μ/(1+u) and E=M. Since R=r(1+u)², this is precisely M=μ−μ²/(2R). The interior clock rate is constant and equals 1−μ/R. It remains shifted at the force-free center. These are derived single-shell results for the specified responses and energy.

The example with μ=1 and R=4 has u=1/7, M=E=7/8 and interior clock rate 3/4. The necessary tangential pressure divided by surface energy density is 1/12. The independent Einstein thin-shell calculation in the preceding chapter gives the same numbers. For comparison with earlier scalar field-energy approaches, see Giulini.

Put a second shell outside the clocks

Take two disjoint shells. In the vacuum gap the positive scalar has the form u=d+a/r. The outer source contributes the constant d, while a is the coefficient due to the inner source. A local rod survey gives the circumference radius R=r(1+d+a/r)² and the radial derivative s=dR/dℓ=(1+d−a/r)/(1+d+a/r), where dℓ=A dr. A static spherical vacuum in general relativity is a Schwarzschild region with an arbitrary constant time normalization. There the lapse satisfies N=C s. A change of reference clock cancels out of the following observable:

clock-and-rod ratio = [N(r₂)/N(r₁)] / [s(r₂)/s(r₁)].

GR gives one for any two radii in that vacuum gap. The scalar instead gives N/s=(1−d−a/r)/(1+d−a/r). A constant background affects the two readouts differently at the two radii. For d=1/10, a=1/4 and clocks at 1 and 2, the predicted ratio is 527/507, about 1.03945. These dimensionless numbers illustrate an exact difference, not a measured discrepancy. If both loads are weak, the deviation in this two-clock ratio begins at the product of the inner and outer fields. With either load absent it vanishes. Spherical vacuum theorem

Check the supporting material and the mass

There is a stationary example with the inner shell at 4/5 and the outer shell at 3. The exterior scalar coefficient is 11/20. For u₁,u₂ at the shells, the field energy is 2[(u₁−u₂)²/(1/r₁−1/r₂)+r₂u₂²]. Add Nᵢμᵢ for each shell, then vary both fields and both radii. The required proper masses are 1243/1600 and 781/1200. Both pressures are positive. Their ratios to surface energy density are 125/517 and 96/539.

For each shell write y for the surface area divided by its equilibrium area. The material energy law μ(y)=μ(1)[(η−w)y+(1+w)y⁻η]/(1+η) gives that pressure ratio w at y=1 and a tangential sound speed c√η. With η=0.8 the four-variable static energy has a positive radial Hessian in the numerical check. No external holding force has been included. This is a spherical equilibrium calculation; bending and nonspherical modes require their own material response.

The total field and material energy is 209/192. The mass inferred from the exterior is 11/10, larger by 11/960. All the supporting pressure in this model is included. Matching an entire single-shell family therefore concealed a failure of both the annular clock ratio and mass accounting. This test assumes a canonical scalar vacuum energy and that local rods and clocks depend only on its value. Separate metric variables, gradient-sensitive readouts or a different vacuum dynamics can change the result.

How shell work transfers to clocks and rods

Can adding small amounts of shell material determine what two clocks will read? Hold the areal radius R fixed and let F(m,μ) be the exterior mass after adding proper energy μ to a spherical layer around interior mass m. Assume quasistatic assembly, additive proper-energy increments and a response that depends only on the current enclosed mass at that radius. Then F(F(m,μ),ν)=F(m,μ+ν). Differentiating with respect to ν at zero gives ∂μF=f(R,F), where the generator f(R,m)=∂μF(m,0) is the incremental energy delivered to infinity per unit of proper energy. For positive f one can check the normalization response directly by differentiating the relation μ=∫[m,F] dm′/f(R,m′). This gives ∂mF=f(R,F)/f(R,m). Composition leaves f to be measured or supplied.

For the Einstein benchmark, take this incremental energy to be the independently specified Schwarzschild clock rate f(R,m)=√(1−2m/R) for an isolated layer. Integrating gives the following rule, also obtained from the angular junction condition. Here a and b are the interior and exterior one-sided radial slopes dR/dℓ at the shell. Continuity of the shell clock gives the inward multiplier J for the vacuum lapse normalization in N=C dR/dℓ. Israel junction conditions · Martinez on shell energy and pressure

a = √(1−2m/R),        b = a−μ/R > 0
F = m+aμ−μ²/(2R),    ∂μF = b,    J = ∂mF = b/a

Starting from an empty core, apply F at R₁ and then at R₂>R₁. The exterior mass is M. A reference clock at infinity assigns rates N₁=b₁b₂/a₂ to the inner shell and its cavity, and N₂=b₂ to the outer shell. An outer load rescales every inner clock by J₂=b₂/a₂ while leaving the gap's rod slopes fixed at fixed inner mass. The inner-to-outer clock ratio is b₁/a₂, independent of the outer load. Here proper radial lengths follow from the spherical vacuum metric. A microscopic material rod still needs its own calibration.

There is a second way to read each clock. At fixed radii ∂M/∂μᵢ=Nᵢ. With both radii free, the static junction pressure obeys 8πRp=(1/b+b−1/a−a)/2 and the full differential is dM=Σᵢ Nᵢ[dμᵢ+pᵢ d(4πRᵢ²)]. This compares neighboring supported equilibria. An adiabatic material law with dμᵢ=−pᵢ d(4πRᵢ²) restricts which variations are available. The mixed response gives a reciprocity check at fixed radii.

∂N₁/∂μ₂ = ∂N₂/∂μ₁ = −b₁/(R₂a₂).

For R₁=8, μ₁=2, R₂=224/15 and μ₂=28/15, the slopes are b₁=3/4, a₂=7/8 and b₂=3/4. The predicted M is 49/15 and the clocks read 9/14 and 3/4. Independently varying the two proper energies in the replay gives mixed responses −0.057397959186 and −0.057397959180, compared with −45/784. Varying the radii at fixed proper energies gives 3/112 and 11/448 for the pressure-work derivatives. Numerical replay

Even reciprocity and the Newtonian binding term leave an ambiguity. For example, fβ=√(1−2m/R)[1+β(m/R)²] generates a composable flow with the same leading binding energy. Starting from empty space it gives F(0,μ)=μ−μ²/(2R)+βμ³/(3R²)+O(μ⁴/R³). Selecting β=0 requires further physical input. The source rule above reproduces the Einstein shell benchmark conditionally. The scalar counterexample and the limited sensitivity of the terrestrial clock measurement still apply.

Scale of a laboratory comparison

The exact excess of the two-clock ratio over one is 2d(z₁−z₂)/[(1+d−z₂)(1−d−z₁)], where zᵢ=a/rᵢ. As an illustration use a 1,000 kg outer shell of radius one meter, a 10 kg inner source and clocks at 0.2 and 0.4 meters. Taking the ordinary Newtonian G for the calibration, the first-order central clock shift from the outer shell would be about 7.4 × 10⁻²⁵. The nonlinear nested-shell ratio differs from one by only 6.9 × 10⁻⁵¹. The strontium comparison later in this study has uncertainty on the order of 10⁻¹⁹. It probes a much larger terrestrial potential gradient and cannot distinguish these two shell laws in this laboratory example.

Surround the two clocks with more matter

Keep the inner coefficient at 1/4 and the clocks at coordinate radii 1 and 2. Change the constant contribution from the outer shell and compare their rate ratio with independently surveyed rods.

Clock and rod ratio 1.03945

The spherical Einstein vacuum predicts 1.00000 at every setting.

A breathing shell radiates in the clock scalar model

Sections in this chapter

Give the clock scalar w = 2u a canonical wave equation with propagation speed c. A freely breathing spherical elastic shell then emits a monopole wave. At material stiffness dP/dσ = 1/3, a direct retarded-field calculation gives a normalized amplitude of 1.083085. Four-dimensional vacuum general relativity predicts a time-independent exterior for the same exactly spherical motion. This is a theoretical discriminator. Static scalar coupling · Retarded-field replay

A freely oscillating source

Let M be the proper mass at the material's zero-pressure radius R. The small displacement is ξ(t) = A cos(Ωt), with A/R and ΩA/c both small. The equilibrium surface energy density is σ₀ = Mc²/(4πR²). At fixed material content dE = −P d(area). Since P₀ = 0, the total proper energy is constant to first order even though the surface density changes. Writing η = dP/dσ at equilibrium gives δP = −2ησ₀ ξ/R.

The tangential stress tensor is δP(δᵢⱼ−nᵢnⱼ)δ(r−R). Its spatial divergence is −2δP nᵢ δ(r−R)/R. Balancing the time derivative of the radial momentum density against this divergence yields

M ξ̈ = 8πR δP,     ∫Σᵢ Tⁱⁱ d³x = 8πR² δP = MR ξ̈,
Ω² = 4ηc²/R²,      x = ΩR/c = 2√η.

Expansion creates tensile stress and inward acceleration. The surface responds to its own strain, so an external driver or fixed prop contributes no uncounted source. Take weak compactness ε = GM/(Rc²) ≪ 1 and ε ≪ η so that static self-gravity only perturbs this material equilibrium. The finite-speed scalar calculation uses the material motion to leading order in G and follows cycles short compared with the damping time. Spherical shell mechanics and stress conservation

Two contributions to the outgoing wave

At small w the clocks and rods in the specified scalar model give a matter-action coupling +w S with S = T⁰⁰ + ΣᵢTⁱⁱ. The canonical field normalization is c⁴/(8πG) multiplying (∂ₜw)²/c² − |∇w|² in the Lagrangian density. With retarded boundary conditions the far-zone field from a source amplitude S̃ is G S̃/(c⁴r). The scalar propagation speed and universal coupling are inputs.

A spherical surface of radius R has normalized Fourier form factor j₀(kR), the angular mean of exp(−ikR cosθ). Conservation of proper mass at first order makes its energy contribution proportional to a radius derivative. The pressure term follows the acceleration. For the peak complex amplitude multiplying exp(−iΩt), take k = Ω/c, j₀(x) = sin(x)/x and j₁(x) = −j₀′(x). Then

δT̃⁰⁰      = Mc² A k j₀′(x),
Σᵢ δT̃ⁱⁱ  = −MR A Ω² j₀(x),
S̃         = −MR A Ω² H(x),       H(x) = j₀(x) + j₁(x)/x.

Both terms have the same sign. The energy-density term arises from retardation across the moving shell even though the total material energy has no first-order oscillation. At long wavelength H = 4/3 − x²/5 + O(x⁴). An alternative angular expression is H = ¼∫₋₁¹(3−μ²) cos(xμ) dμ. It decreases for 0 < x ≤ 2 and H(2) = 0.672348. Consequently finite travel time across the shell leaves a nonzero monopole at every positive causal stiffness 0 < η ≤ 1.

Writing r for observer distance, the spherical outgoing waveform and cycle-averaged power are

δw(r,t) = −[GMR A Ω²/(c⁴r)] H(x) cos[Ω(t−r/c)],
⟨P⟩ = [GM²R² A² Ω⁶/(2c⁵)] H(x)² .

The outgoing flux is c³(∂ₜw)²/(4πG). The factor 1/2 in the power uses peak displacement A. For the radial mode energy MΩ²A²/2 the corresponding radiation quality factor ΩE_mode/⟨P⟩ is 1/[ε x³H(x)²].

Direct retarded check

The numerical calculation solves the emission-time equation tₑ = t−r/c + μ[R+ξ(tₑ)]/c separately for each direction cosine μ. Integrating a moving radial delta function supplies the Jacobian 1/[1−μ ξ̇(tₑ)/c]. The program integrates the density and tangential stress over this moving surface, differentiates with respect to signed amplitude at A = 0, and separately differentiates the resulting waveform in observer time to check the mean flux. At η = 1/3 it finds H = 1.083084703 and a dimensionless mean-power coefficient H²/2 = 0.586536235. Reproduce the angular and flux tests

The Einstein exterior obeys the Jebsen–Birkhoff theorem in spherical vacuum. Its mass is constant during internal spherical motion with no material or other radiation crossing the exterior. The scalar theory supplies an additional propagating degree of freedom carrying the flux above. Testing that prediction physically requires sensitivity to this specific scalar coupling and control of departures from spherical symmetry. Deser and Franklin, spherical vacuum and constancy of mass

A measured polarization comparison from GW170817

What would a differential interferometer see if this scalar supplied an entire binary signal? At first order the model has h₀₀ = 4u, hᵢⱼ = 4uδᵢⱼ and h₀ᵢ = 0. For a plane wave u(t−n·x/c), with x⁰ = ct, its local tidal tensor is R₀ᵢ₀ⱼ = −2ü(δᵢⱼ+nᵢnⱼ)/c² in the convention d²ξⁱ/dt² = −c²R₀ᵢ₀ⱼξʲ. The longitudinal tidal acceleration is twice either transverse one. For equal, short Michelson arms along unit vectors a and b, the differential detector tensor is D = (aa−bb)/2. Its trace vanishes. The differential strain is therefore 4u D:nn = −4u F_b, where F_b = D:(I−nn) is the conventional transverse-breathing antenna factor. The common sign and amplitude can be absorbed into the scalar waveform. This degeneracy concerns differential readout in the long-wavelength limit.

At the GW170817 merger epoch the replay projects the optical counterpart direction onto the LALSuite arm vectors. The signed D:nn factors are −0.098, +0.178 and −0.059 for Hanford, Livingston and Virgo respectively, with the LAL x-minus-y arm convention. These are geometric response factors before detector noise, source amplitude or arrival-time shifts. The calculation uses the catalog sky position and mean Greenwich sidereal angle, approximating UT1 by UTC. LALSuite 7.26 arm vectors · Coulter et al., optical position · GWOSC merger time and event data

Abbott et al. compared pure polarizations coherently across those three instruments using the IMRPhenomPv2 phase model. They report log₁₀ of the tensor-to-scalar Bayes factor 23.09 ± 0.08 with the sky fixed to NGC 4993 and 5.84 ± 0.09 with the sky free. If the binary signal followed the tested waveform and priors and this scalar accounted for its entire detectable polarization, it would have the strongly disfavored pure-scalar antenna pattern. These are the collaboration's evidence ratios. A model-specific binary waveform or a tensor-plus-scalar mixture requires its own likelihood analysis. Abbott et al., Tests of General Relativity with GW170817

Can a bound pair serve as an independent material rod?

Sections in this chapter

A light pulse can measure a coordinate speed. To test a spatial scale independently, prepare a pair of massive particles in a stationary bound state and image their separation over many preparations. Its root-mean-square separation is a measurable length even though its mean separation vector is zero. Its breakup threshold and its response to a small center-of-mass momentum expose two further properties of the same object. On a cubic lattice the three measurements disagree with a common metric scaling by 27.6% in the example below. Offline calculation

Three readings from one pair

Take a nearly uniform, static patch with zero shift, clock factor N and proper distance dℓ = λ dx, where λ=ψ². Normalize both factors to one in a reference patch. An identical proper rod of coordinate length R₀ in the reference should occupy R=R₀/λ in the second patch. A spectroscopic energy difference should obey Δ=NΔ₀. An independent local two-level clock can determine N by Ramsey spectroscopy. In the model below its two internal states may be assigned the same hopping and contact attraction, so its spin-flip frequency can be read independently of pair motion.

Let D=d²E/dkₓ² at zero center-of-mass wavevector, with kₓ measured in radians per coordinate length. A small momentum kick and a group-velocity measurement give D from vₓ = D kₓ/ℏ to first order. If the same proper dispersion applies in both patches, E(kₓ)=N E₀(kₓ/λ) up to a momentum-independent offset. This predicts D=ND₀/λ². The combination

C = D / (Δ R²)

must therefore agree across the patches for the same species. It is dimensionless and requires no light-speed fit. The coordinate speed of a separately calibrated light mode supplies a fourth test, c(coord)/c₀ = N/λ.

An exact calibration on a chain

Give each of two distinguishable particles hopping −J between neighboring sites of fixed coordinate spacing a. When they occupy the same site, lower their energy by U>0. This finite-range Hermitian Hamiltonian generates unitary evolution. The particles experience no applied force. At zero center-of-mass momentum, moving either particle changes the relative site index by one. The relative hopping is −2J. The bound-state solution has amplitude proportional to exp(−κ|n|), with sinh κ = U/(4J) = g. Its image has site probability P(n) = tanh(κ) exp(−2κ|n|). Summing a²n²P(n) gives R²=a²/(2g²) exactly. Valiente and Petrosyan, exact Hubbard dimer states

Write w = √(1+g²). The scattering continuum starts at −4J and the pair band is E(k) = −√(U² + 16J² cos²(ka/2)). Its breakup threshold is Δ=4J(w−1) and its curvature is D=Ja²/w. These three measurements give C=(1+1/w)/2. The exact expression decreases with binding strength. A spatial scaling can reproduce the RMS length by changing J/U. At finite lattice spacing that same change also alters the dimensionless value of C.

For example, set g₀=3/4 and g₁=4/3. The rod shrinks to 9/16 of its reference length, corresponding to λ=16/9. Choose J₁=3NJ₀/8 and U₁=2NJ₀. Then the breakup threshold has the specified clock scaling exactly. Yet C falls from 9/10 to 4/5. The moving pair has 8/9 of the curvature predicted from the rod and clock for any positive N. The site histogram offers another test. Its signed-separation probability ratio P(n+1)/P(n) for n≥0 is 1/4 in the reference and 1/9 in the second patch. If opposite separations are combined into one bin, use consecutive nonzero-distance bins to avoid the factor of two at the origin. A length inferred from the tail shrinks by ln 2 / ln 3 even though the RMS length shrinks by 9/16. In the weak-binding, long-rod limit g ≪ 1, C=1−g²/4+O(g⁴) and the discrepancy becomes small.

A composite that moves in all three dimensions

Now allow the two particles to hop to all six neighbors on a simple cubic lattice. Let δ=Δ/J and write qᵢ for dimensionless relative momenta. At zero center-of-mass momentum the two-body Schrödinger equation gives

b(q) = δ + 4 Σ_i (1 − cos q_i)
φ(q) ∝ 1/b(q)                 J/U = ⟨1/b(q)⟩
Z = ⟨1/b(q)²⟩
R_x²/a² = 16 ⟨sin²(q_x)/b(q)⁴⟩ / Z
D_x/(J a²) = ⟨cos(q_x)/b(q)²⟩ / Z.

The brackets denote the uniform average over the cubic Brillouin zone. The radius follows from the squared momentum derivative of the normalized wavefunction. For the curvature, the two-body kinetic energy along x is −4J cos(kₓa/2) cos(qₓ). Its first derivative vanishes as an operator at kₓ=0, so the second derivative of the eigenvalue is the expectation of the second derivative of the kinetic energy. Cubic symmetry gives the same result along all three axes. The cubic lattice has a binding threshold near U/J=7.914, so parameters must be chosen for an existing pair. Kornilovitch, two-particle binding on lattices

Breakup energy Δ/JRequired U/JRMS separation Rₓ/aBand curvature Dₓ/(Ja²)C
0.59.471720.7764460.6241022.070443
211.728570.3767380.4256791.499587

The ratio of measured radii gives λ=2.060968. Choosing J₁=NJ₀/4 matches the threshold frequency exactly. The ratio of the two C values then gives 0.724283 of the predicted curvature. The checker evaluates the three-dimensional momentum integrals, independently transforms the x coordinate to sum the separation probabilities, and solves for the pair energy again after a small center-of-mass kick. The calculation specifies an additional massive matter sector for the spin walk. Deriving its hopping and attraction from the same spatial and temporal fields as the light walk would be a further requirement.

An experimental comparison

Prepare narrow center-of-mass packets near zero momentum in two homogeneous lattice settings. Calibrate J from the single-particle band and an independent two-level splitting from spectroscopy. Resolve both particles, including double occupancies, to measure Rₓ. Locate the breakup onset with momentum selection and an independently measured line response. Use a reserved small kick to obtain Dₓ and compare the two values of C. Correct the imaging efficiency separately for equal-site and separated pairs. The breakup onset is a spectroscopic reference; a broad loss peak alone does not determine it. Optical-lattice experiments have demonstrated repulsively bound pairs and atom-resolved two-particle correlations. The ratios above are new comparisons proposed for these explicit attractive Hamiltonians. Winkler et al., bound atom pairs · Preiss et al., two-particle correlations

Does pressure gravitate through the same channel as energy?

Sections in this chapter

A slow mass can respond correctly to a beam of light even when the predicted interaction between two light beams is wrong. The distinction can be made with two stationary source patterns that obey energy and momentum conservation. Work at weak field with variation along z. Pattern D is cold matter with negligible pressure. Pattern L has the same energy density in four equal streams of light travelling along +x, −x, +y and −y. Its energy flux cancels and its transverse stresses are Tₓₓ=Tᵧᵧ=E/2. Neither pattern has a z momentum flux. Modulating the intensity in z preserves conservation to the order used here.

Consider a nonzero Fourier mode and subtract the uniform background. A wide sheet is the corresponding local laboratory idealization. A finite cavity must include the stresses in its supports. This calculation predicts an exchange coefficient for prescribed conserved sources; the gravitational interaction of two such light sheets has not been measured in this study.

Three measurements with one normalization

For linearized Einstein gravity the attractive static exchange coefficient is proportional to 2T₁·T₂−tr(T₁)tr(T₂), where the contraction uses the Minkowski metric. Normalize the cold matter pair coefficient to one and give each source the same energy modulation. For sources with isotropic transverse stress, write s=T⁰⁰ and t=Tₓₓ+Tᵧᵧ. The coefficient is s₁s₂+s₁t₂+t₁s₂. It gives the following three numbers.

Two source patternsCold and coldCold and lightLight and light
Linearized Einstein response123
One attractive scalar fitted to the first two results124
Any number of stable unconstrained scalar exchange modes fitted to those results12At least 4

For the scalar model of the shell, this is a direct consequence of its clock and rod laws. At u=0, N=1−2u+… and log A=2u+…. Varying the coordinate energy of matter gives δE=E δN−t δlog A for these sources. The resulting charge is proportional to s+t. Reciprocal source and detector couplings therefore give the product (s₁+t₁)(s₂+t₂).

More generally, minimizing a positive quadratic energy of any number of ordinary, freely relaxing static fields gives a response matrix Kᵢⱼ=qᵢᵀH⁻¹qⱼ for the fields coupled to each source. At fixed nonzero wave number, H is their positive stiffness matrix. Cauchy–Schwarz requires Kᴅʟ² ≤ KᴅᴅKʟʟ. Once the first two readings are 1 and 2, the third must be at least 4. The Einstein matrix has determinant −1. The conclusion concerns the long-range exchange from linear, reciprocal, unconstrained fields. It allows directly imposed contact interactions, additional constraints and additional independently coupled sectors to be tested on their own terms.

Two opposite x-directed streams also allow an orientation test. Rotate the other balanced two-stream source through angle θ in the plane. The Einstein coefficient becomes 2(1+cos²θ), ranging from 4 to 2, even though its energy and summed pressure stay fixed. An orientation-sensitive tensor response is required for this comparison. Original investigation of the gravitational field produced by light

A constrained static model matches three stress couplings

Sections in this chapter

A scalar field and a link field with positive quadratic field energies can reproduce the static massless spin-2 interaction between energy and isotropic transverse stress. The construction imposes a Gauss law with transverse stress as its charge. That charge assignment fails a dynamical test on ordinary matter, including a wave whose total transverse stress is zero at every instant. Offline lattice and matter replay

Normalize to the attraction between two energy densities

Use flat spacetime with signature (−,+,+,+). For a nonzero stationary Fourier mode along z take T⁰⁰ = s, Tˣˣ = Tʸʸ = t/2 and all remaining components zero. Static conservation is automatic. The calculation concerns Fourier components of sources, whose amplitudes can be signed. For two independently specified sources, the four-dimensional massless Einstein residue normalized to the dust–dust coefficient is

2 T₁^{μν} T₂_{μν} − tr(T₁) tr(T₂)
  = 2(s₁s₂ + t₁t₂/2) − (−s₁+t₁)(−s₂+t₂)
  = s₁s₂ + s₁t₂ + t₁s₂
  = (s₁+t₁)(s₂+t₂) − t₁t₂.

The positive residue convention multiplies a negative static energy kernel. Thus the required matrix on (s,t) is [[1,1],[1,0]], with determinant −1. In SI units its continuum cross energy is −(4πG/c⁴) times the bilinear residue integrated with the Green operator (−Δ)⁻¹. Its Green function is 1/(4πr); s and t are energy densities. Massless exchange between conserved sources, Damour, Kogan and Papazoglou

A finite lattice realization

Give a simple cubic lattice unit spacing and periodic boundaries. For a node field φ, D is the forward link gradient. The divergence is −D†, so L = D†D is positive. Write G₀ = L⁺ for the inverse with the constant mode removed. Set s and t to have zero spatial mean. This selects perturbations about a background and satisfies the exact net-charge condition on a periodic cell. Let g > 0 set the common coupling. Use the ordinary node and oriented-link inner products and minimize

H/g = ½‖Dφ‖² − ⟨s+t,φ⟩ + ½‖E‖²,       div E = t.

The scalar solution is φ = G₀(s+t). The minimum-norm link field is E = −DG₀t. Any added divergence-free flux is orthogonal to this field and raises its energy by its own squared norm divided by two, in units of g. The source-dependent scalar minimum is negative. The forced electric energy is positive.

H_min/g = −½⟨s+t,G₀(s+t)⟩ + ½⟨t,G₀t⟩.

Subtracting the two separate source energies from the energy of their sum leaves the attractive-normalized matrix below. All entries use the same Green operator.

ChannelScalar relaxationConstrained linksSum
Energy–energy101
Energy–transverse stress101
Transverse stress–energy101
Transverse stress–transverse stress1−10

For a z-directed lattice wave at finite k, the common denominator is exactly 4 sin²(k/2). It approaches k² at long wavelengths. The replay works in real space per unit transverse area. It integrates the link constraint, minimizes over the uniform flux, integrates the scalar potential and tests its discrete Poisson equation. For the neutral eight-cell profile (2,−1,0,3,−4,−1,2,−1), ⟨f,G₀f⟩ = 16 exactly. The mixed-channel cross energy is −16g and the pure stress cross energy vanishes. An independent periodic Green-function inversion reproduces the potentials. The replay also tests shifted profiles and modes with exact denominators 2, 3 and 4.

This match assumes equal scalar and electric coefficients and the stated matter couplings. A mismatch leaves a residual stress–stress pole. The indefinite matrix here relates external sources; both quadratic field energies are positive for fixed admissible sources. A dynamical stability or propagating-mode claim would require a time-dependent field and matter theory.

Can transverse stress be an electric charge?

In a local Maxwell implementation the divergence of its electric evolution equation gives ∂τt + div J = 0. Energy–momentum conservation instead makes T⁰⁰ the density of energy and T⁰ⁱ the densities of momentum. Spatial stresses act as momentum fluxes. Consider a classical, free real Klein–Gordon field with mass m in a periodic flat box, in units c = ℏ = 1. Its stress tensor provides a direct test of the proposed charge assignment beyond the stationary source sector.

For the homogeneous solution φ = A cos(mτ), s = A²m²/2 stays constant. Its isotropic pressure is −s cos(2mτ), so t = Tˣˣ+Tʸʸ = −2s cos(2mτ). The integrated candidate charge oscillates on a closed box despite exact energy and momentum conservation.

Excluding the mean mode leaves a stronger test. Use a single traveling wave φ = A cos(kz−ωτ), with k nonzero and periodic, ω² = m²+k². Substitution in the canonical stress tensor gives

t = (∂τφ)² − (∂zφ)² − m²φ² = −A²m² cos[2(kz−ωτ)].

Its mean vanishes at every instant. At the oscillatory Fourier component, charge continuity nevertheless requires Jᶻ = (ω/k)t. With fixed field amplitude, |ω/k| reaches 2.236, 10.050 and 50.010 for k/m = 0.5, 0.1 and 0.02. On successively larger tori k can approach zero while the local field and its finite derivatives remain bounded. A regular, translation-invariant current built only from those local matter variables cannot supply the required divergent Fourier amplitude. The Fourier ratio is a continuity requirement and carries no inference about signal speed. A longitudinal inverse derivative, additional degrees of freedom carrying current, or a different off-static charge law would change the hypothesis. Coherent massive scalar dynamics, Turner

What changes with a tensor constraint?

For a symmetric rank-two link or continuum field, simply imposing a double-divergence Gauss law ∂ᵢ∂ⱼEᵢⱼ = t and minimizing ½∫EᵢⱼEᵢⱼ gives a static |t|²/(2k⁴) cost for each nonzero Fourier mode. This introduces a different pole and requires a conserved scalar charge, with further moment constraints under suitable boundary conditions. A single divergence ∂ᵢEᵢⱼ = ρⱼ can give a 1/k² static kernel, but its source is a conserved vector density. Ordinary momentum density can supply such a continuity law because Tⁱʲ is its flux. Choosing the transverse stress as a vector charge still needs a new matter law. Pretko, tensor Gauss laws and conservation

Linearized Einstein gravity already couples consistently to an ordinary conserved stress tensor. Its Hamiltonian constraint uses ∂ᵢ∂ⱼhᵢⱼ − Δhᵢᵢ = 16πG T⁰⁰ in units c = 1. Its momentum constraints use T⁰ⁱ, and the spatial evolution equations contain Tⁱʲ. The linearized Bianchi identity preserves the constraints when ∂μT^{μν} = 0. That solution introduces metric variables, their constraints and evolution together. The scalar-and-electric construction above supplies a static comparison on the specified two-source sector alone. Arnowitt, Deser and Misner, constraints and evolution

Which pressure perturbations produce a tidal wave?

Sections in this chapter

A conserved pressure perturbation changes the relative acceleration of test masses. At finite frequency the mean transverse pressure has a longitudinal tidal response with no massless pole. Shear has a different signature. It drives two transverse orientations, gains a phase of π across resonance and can leave a wave after the source switches off. These statements follow from a local linear spin-two benchmark coupled to the source. They provide a target for a microscopic theory of the coupling.

A local conserved source

Use flat-background signature (−,+,+,+), c = 1 and modes exp[i(kz−ωt)]. Resolve stresses in the plane normal to z into Tˣˣ = P+A, Tʸʸ = P−A and Tˣʸ = B. Write T⁰⁰ = ρ, T⁰ᶻ = uρ and Tᶻᶻ = u²ρ with u = ω/k, for k ≠ 0. This source obeys ∂μ T^{μν} = 0. The replay uses the full tensor with indices 0,x,y,z.

There are local ways to generate these modes. A compact scalar f gives a transverse trace source Tⁱʲ = (δⁱʲ∇²−∂ᵢ∂ⱼ)f with T⁰μ = 0. Its spatial divergence vanishes for an arbitrary time envelope. An independent symmetric compact tensor H gives shear through Tⁱʲ = εⁱᵃᵇ εʲᶜᵈ ∂ₐ∂𝑐 Hᵦ𝑑. A scalar F generates the longitudinal sector via T⁰⁰ = −∂²_z F, T⁰ᶻ = ∂ₜ∂_z F and Tᶻᶻ = −∂²ₜ F. Sums preserve conservation. These constructions describe prescribed first-order perturbations. A material that can generate them, its background energy, and how it exchanges energy with a drive require a distinct model.

Where the pressure pole cancels

Assume a massless symmetric tensor with linear gauge invariance, the harmonic-gauge wave equation □h̄μν = −16πG Tμν, conserved-source coupling and retarded initial data. Let D = k²−(ω+i0)². With trace T taken using the Minkowski metric, its retarded response is hμν = 16πG (Tμν−ημνT/2)/D. This is the linear Einstein response. The assumptions specify a continuum completion and require independent justification for the microscopic walk. Carroll, weak fields and gravitational radiation · Deser, local spin-two coupling

For a real second source denoted by primes, set δ = 1−u². Contracting h with it gives the following normalized exchange, written away from D = 0. Complex modes pair with the conjugated probe.

T'·h/(16πG) = δρρ'/(2k²) + (ρP' + ρ'P)/k² + 2(AA' + BB')/D .

The density and mean pressure cross term survives the static limit. The mean-pressure self term cancels at every frequency. At the massless pole the residue with respect to D is 2(AA′+BB′). For a source paired with its conjugate the residue is 2(|A|²+|B|²), which is nonnegative. It equals 2 for the numerical drive A = 0.6, B = 0.8i below. The propagating channels are the transverse traceless (TT) strains with two independent polarizations.

A static scalar and a compensating Gauss field can represent the density/pressure kernel as [(ρ+2P)(ρ′+2P′)/2 − 2PP′]/k². That algebra alone leaves the dynamics undetermined. For example, propagating its first term with 1/D and keeping the second at 1/k² gives a spurious pure-pressure self exchange of 2(1/D−1/k²) for unit P = P′. At u = 0.99 and 1.01 the dimensionless values k² times this exchange are +98.50 and −101.50. The full conserved spin-two contraction gives zero in both cases. This specific continuation also lacks the shear residue. Other microscopic proposals must specify their constraints and couplings before making this comparison.

A gauge-invariant detector

A nearby freely falling separation ξ measures the relative acceleration −Rⁱ₀ⱼ₀ ξʲ to first order. Define Eᵢⱼ = R₀ᵢ₀ⱼ/(8πG). For the selected propagation direction, direct differentiation of h gives

Ezz = P + δρ/2
(Exx + Eyy)/2 = u²ρ/2
(Exx − Eyy)/2 = ω² A/D
Exy = ω² B/D .

Take two orthogonal unit arms normal to z, rotated by θ from x and y. Half the difference of the two directional readings is ω²[A cos(2θ)+B sin(2θ)]/D. Arms at 0° read the plus polarization and arms at 45° read the cross polarization. For normalized ρ = 0.7, P = 1, A = 0.6 and B = 0.8i, Ezz goes from 1.006965 to 0.992965 as u runs from 0.99 to 1.01. The in-phase plus reading goes from +29.551 to −30.451, and the quadrature cross reading from +39.401i to −40.601i. Adding a pure-gauge derivative to every metric component leaves the computed tidal tensor unchanged. For the compact scalar f above, the pure-pressure response in general momentum directions is Eᵢⱼ = ∂ᵢ∂ⱼf. It is localized to the source and compatible with retarded evolution.

Switching the source off on a finite lattice

The replay advances retarded wave equations with unit space and time steps on 256 periodic z sites. Compatible first differences on staggered grids have symbols iK and −iΩ, with K = 2sin(k/2) and Ω = 2sin(ω/2) after assigning each field its physical grid phase. Their products give the centered second differences in the update. The conservation and exchange checks use these common derivative symbols. The axial pressure/shear burst has T⁰μ = Tᶻμ = 0 and is exactly conserved on this grid. It uses a width-three spatial second difference of a unit impulse, initially zero fields, and a four-period drive at k = 2π/16. The plane model is uniform across x and y. Temporal forcing is cos(ωt) for unit pressure, 0.6cos(ωt) for plus, and 0.8sin(ωt) for cross.

A freely falling readout at site 20 first responds on tick 19, its lattice distance from the nearest driven site. The pointwise identity Ezz = P holds to 8.9 × 10⁻¹⁶ throughout. After switch-off the projected free plus and cross amplitudes are 7.638235 and 10.184313 relative to the source's spatial Fourier coefficient. For a drive lasting L = 64 ticks and phase step α = 2π/16, the causal oscillator convolution gives the free signals 0.6 L tan(α/2) sin(nα) and −0.8 L tan(α/2) cos(nα). Direct time stepping agrees within 5.3 × 10⁻¹³. These are forcing-duration-dependent linear response amplitudes. They are numerical results for a specified source, not experimental clock or gravitational-wave data.

Run python3 pressure_wave.py for the exchange, gauge, propagation and detector checks. Standard-library replay

Which waves can a local tensor rotor carry?

Sections in this chapter

A positive harmonic tensor lattice gives an explicit construction of two transverse traceless (TT) polarizations. The choice of local magnetic energy determines their dispersion. A squared double curl gives three modes with ω proportional to k². An additional constraint removes the breathing mode, and a squared Cotton tensor gives two modes with ω proportional to k³. Neither spectrum matches the linear-gravity benchmark simply by rescaling time. A positive wave equation can reach linear dispersion on a prescribed TT sector. The harder question is how a microscopic Hamiltonian selects that sector.

These calculations use a noncompact, quadratic approximation to rotor coordinates. The large energy cost that selects a quantized Gauss sector in a compact model, its defects, and the survival of a phase under interactions require separate evidence. Xu's early paper used a specific fcc boson model. Xu and Hořava explicitly distinguish three polarizations at z = 2 from two at z = 3. Gu and Wen give a semiclassical derivation of cubic modes in their L-type qubit model and describe their linear N-type result as a proposal based on a less controlled approximation. The isotropic stiffnesses below define our benchmark. Xu, early preprint · Xu, published model · Xu and Hořava · Gu and Wen

Positive local quadratic energies

Let A and E be symmetric canonical tensors with inner product A:B = Σᵢⱼ AᵢⱼBᵢⱼ. A real diagonal component lives at a cell vertex and an off-diagonal component at its coordinate face center. The Fourier symbol of a nearest-neighbor difference referred to its midpoint is iKᵢ, where Kᵢ = 2sin(kᵢa/2)/a. Put Xw = K × w and B = X A Xᵀ. This real symbol fixes the overall sign convention for the double curl. Both differences are local. At nonzero momentum write P = I−KKᵀ/|K|².

Impose the vector Gauss constraint div E = 0. It generates changes of A by symmetrized vector gradients, so B is invariant. For K along z the independent canonical pairs have components xx, yy and xy. On their two-by-two block B = |K|²[P tr(A) − A]. The Hamiltonian H₂ = ½Σ(E:E + B:B) therefore has three equal frequencies |K|². The transverse trace xx+yy breathes, and xx−yy and xy carry tensor polarization. Counting gauge constraints here means projecting to an exact charge-free sector. A generic soft penalty on continuous momenta alone does not establish a microscopic gap.

Now impose tr E = 0 as a further first-class constraint. It generates the Weyl shift A → A + If. Under this shift B changes by |K|²P f. Replace B by C = curl[B − I tr(B)/2], dropping the overall Fourier phase i when computing its norm. Under the Weyl shift the bracket changes by −KKᵀf, whose curl vanishes. C is symmetric, traceless and transverse, and has magnitude |K|³ times the TT amplitude. Its extra single curl lives on the dual staggered grid. With H₃ = ½Σ(E:E + C:C) the only oscillators at nonzero K are the two TT components, and both have frequency |K|³. The coefficients in H₂ and H₃ set units of time independently.

A finite lattice discriminator

A breathing-mode measurement and a frequency ratio distinguish the candidates without fitting an overall stiffness. For the ratio use axial periodic momenta 4π/(Na) and 2π/(Na). At N = 64 the predictions are

Quadratic modelPropagating modes at nonzero KTransverse breathing modeSecond-to-first frequency ratio
Double curl squared3present3.990369
Cotton squared2absent7.971126
Linear TT comparator2 in its constrained sectorabsent1.997591

On an 8³ periodic grid the replay builds the stiffness on an orthonormal basis of all six symmetric tensor components for each of the 511 nonzero wavevectors. B†B/|K|⁴ and C†C/|K|⁶ are idempotent and have traces 3 and 2. The largest residual in these tests is 1.34 × 10⁻¹⁵. This includes oblique momenta and principal-zone faces. The uniform mode has no restoring curl energy and is excluded from the propagating count. Standard-library replay

What do static charges source?

Keep the vector Gauss charge, iKᵢ Eᵢⱼ = ρⱼ, in one nonzero Fourier mode. Minimizing the electric energy gives

2 Hmin = [2|ρ⊥|² + b|ρ∥|²] / |K|² ,
b = 1  for vector Gauss alone,     b = 3/2  when tr E = 0 also.

With K along z, the charges fix E_zx, E_zy and E_zz. The trace constraint adds E_xx = E_yy = −E_zz/2 at minimum energy. This yields the stated coefficient at every orientation. The replay verifies the charge identity to 8.9 × 10⁻¹⁶. The resulting long-range kernel couples to a vector charge. If a separate scalar charge s is assigned to tr E while div E = 0, the minimum is E = sP/2 and Hmin = |s|²/4, independent of |K|. Neither calculation identifies a universal scalar mass density or derives the pressure coupling of the tidal response. Overall vector charge must vanish on the periodic lattice.

How can linear dispersion be obtained?

One local, first-class alternative retains div E = 0 and changes the scalar constraint to tr B(A) = 0. This latter constraint generates E → E + |K|²P f up to a sign. With unit speed, a linear-spin-two comparator has the quadratic Hamiltonian

Hlin = ½ Σ [ E:E − (tr E)²/2 − A:B(A) ] .

The two spatial derivatives inside A:B make the integrated expression local and invariant under vector gradients. For nonzero K, the vector constraint restricts E to its transverse block. Subtracting half the squared trace leaves precisely the TT kinetic energy. The curvature constraint removes the transverse trace of A. On the reduced phase space Hlin = ½(|E_TT|² + |K|²|A_TT|²), with two ω = |K| oscillators. This Hamiltonian and scalar constraint import the linear spin-two structure that the positive rotor alone did not supply. The TT projector contains inverse powers of |K|². Using just the projected quadratic kernel as a microscopic update would therefore require additional local fields or exact constraints.

Positivity of this comparator has a boundary. A unit transverse trace trial A = P/√2 violates tr B = 0. Adding the finite penalty λ(tr B)²/2 gives elastic energy (−|K|²+2λ|K|⁴)/2. An isotropic E = I/√3 plane wave has kinetic energy −1/4 + λ|K|²/6 with the finite penalty λ|div E|²/2. For λ = 10 and the lowest momentum at N = 32, the two trial energies are −0.00445 and −0.18595. Moreover, a uniform trace momentum on a torus obeys both derivative constraints and still has negative quadratic energy. One must fix the global sector or prescribe appropriate asymptotic conditions when making the reduced positivity statement.

A nonnegative alternative with positive energy for every nonzero-momentum mode is Hwave = ½Σ(E:E + Σᵢ ∇ᵢA:∇ᵢA). Its local wave evolution preserves any initial data for which both A and E are transverse and traceless. This gives a classical linear TT simulator with a positive full Hamiltonian, provided the TT sector is selected separately. In canonical quantum variables, imposing restrictions on both coordinates and their conjugate momenta is a reduction by second-class constraints. Finite penalties do not produce the same spectrum. For a normalized xz shear along z, penalties λ(|div E|²+|div A|²)/2 leave ω² = (1+λ|K|²/2)(1+λ/2)|K|². At λ = 10 its frequency falls from 0.5243 to 0.1209 between N = 32 and 128: the unwanted shear stays gapless. Either a demonstrable microscopic mechanism selecting the right constraint and maintaining stability, or a controlled model with different fields, is needed to claim emergent linear spin two. These failures apply to the stated quadratic constructions.

Clock redshift after independent height and gravity calibration

Sections in this chapter

In a blinded experiment, Zheng and colleagues compared five strontium ensembles on a vertical lattice. A gravimeter and the calibrated lattice geometry predict a fractional frequency difference of −10.80 × 10⁻¹⁹ across the endpoints. The clocks measured (−11.96 ± 2.93) × 10⁻¹⁹. The residual is 0.40 combined standard uncertainties. A constant clock rate over this baseline would miss the measurement by 4.08 reported standard uncertainties. We use the sign convention of the paper. Published experiment · Supplementary measurements, Table 1 and section H

Ten measured strontium clock-pair shifts at four heights with uncertainty bars and a line predicted by the independent gravimeter.
The ten pairs share five clocks. The error bars describe the reported pair uncertainties and the line uses the measured local acceleration. Zheng et al. · Download the figure

The plotted intervals are the total one-standard-uncertainty estimates for each pair in Supplementary Table 1. Figure replay

Predicting the endpoints

A separate geoscience group measured the local gravitational acceleration as g = −9.803 m/s². The lattice loading sequence set the array length at 1.00(1) cm. A measured tilt of 5.0(1)° gave an effective vertical extent of 0.99(1) cm in the supplementary analysis, consistent with camera imaging. We use these calibrations directly in Δf/f = gΔh/c². No clock-derived height enters the prediction. With c = 299792458 m/s the expected gradient is −10.9073 × 10⁻¹⁹/cm. Supplementary calibration and endpoint record

Height inputPredicted shiftMeasured shiftMeasured minus predicted
0.99(1) cm effective vertical extent−10.798−11.96 ± 2.93−1.162
1.00(1) cm nominal Table 1 spacing−10.907same endpoint reading−1.053

All shifts in the table are in 10⁻¹⁹. The expected uncertainty from 0.01 cm is 0.109 in these units. Combining it in quadrature with the reported total clock uncertainty gives 2.932, conditional on independent calibration and readout errors. No independent gravimeter uncertainty is supplied here. The reported g is rounded to four significant figures. The second row shows the effect of using the paper's nominal height convention.

A second check uses two disjoint clock pairs from Supplementary Table 1. Clocks 2 and 4 span the longest baseline excluding both endpoints. Their half-centimeter shift of −5.78 ± 2.19 predicts −11.56 at twice that spacing. Clocks 1 and 5 give a residual of −0.40. The pairs share the apparatus and calibrations. For unknown correlation ρ, the residual variance is σ₁₅² + 4σ₂₄² − 4ρσ₁₅σ₂₄. The allowed standard uncertainty runs from 1.45 to 7.31. This check is compatible with height scaling but does not tightly determine it. Supplementary Table 1

Holding back the last seven runs

The authors released the corrected slopes and uncertainties for all 14 runs. In each run the five clocks generate ten pair comparisons. The authors estimated their covariance by jackknife before fitting the run slope. We retain those run-level fit results. The source CSV also contains four grouped height measurements from the same clock readings. Combining those measurements with the slopes as independent observations would double-count the data. Authors' numerical archive · Published covariance method

RunsInverse-variance meanStatistical uncertainty after scatter adjustment
1–7−13.5820.957
8–14, held back−11.1090.989
1–14, replay check−12.3620.734

Entries are in 10⁻¹⁹/cm. The temporal split is retrospective. We inflate each statistical error by √(χ²/dof) when the observed scatter exceeds expectation. The later half differs from the external gravimeter prediction by −0.201 ± 2.689 after adding the published gradient systematic of 2.5 in quadrature. This treats that uncertainty as shared by runs and preserves it when averaging. The later half differs from the earlier half by +2.474 ± 1.376 on statistics alone, conditional on independent run noise and a common additive systematic that cancels in the difference. The processed archive contains no full run-to-run systematic covariance matrix. The published all-run analysis gives −12.4 ± 0.7 (statistical) ± 2.5 (systematic). Its uncorrected gradient and systematic correction were −135.2 and +122.8, respectively, in the same units. The endpoint and run checks summarize the same campaign. Primary analysis and systematic budget

What this checks about a shell

The measured frequency ratio tests a difference of clock potentials along a short terrestrial baseline. In this nearly uniform field, the calibrated integral of g over height reduces to gΔh. An additive constant in the clock potential cancels. A theory with a different source law that reproduces the same terrestrial clock-potential gradient gives the same prediction here. This arrangement supplied neither an enclosed clock compared with an exterior reference across a shell nor independently varied mass distributions at fixed local acceleration. It leaves the shell interior and the relation between the source field and the clock rate open.

Run python3 clocks_data.py with the data file beside it. The file is the authors' deposited Fig3.csv, with original SHA-256 a4384040d5678893b4df15ea0be2980661023305f5009de876179fab1dea632f. The two pair values are transcribed in the script from page 15 of the publisher supplement, SHA-256 111b47f8a3625391178b7d8c5d0753ae8bedbe9f38ea07d6ebdad56cb06f7432. Replay code · Original CSV

What does a clock pulse do to two particles that can meet?

Sections in this chapter

A common translation moves two particles together and preserves the probability that they occupy the same cell. That probability can be read by a coincidence detector without choosing a spatial origin. We made the reference a second quantum particle that can exchange momentum with the walker. Two preparations have identical individual density matrices, identical initial position counts together, and a one-in-four chance of a coincidence. Switching on the same local interaction during the same clock sequence makes the coincidence count rise in one preparation and fall in the other.

The result identifies which part of this candidate clock operation changes the relation between the two particles. It also suggests an independent control. Doubling the reference mass halves the response when the reference carries the phase. The response when the walker carries the phase stays fixed. All contact-pulse outcomes below are model predictions. The single-atom chapter compares a different recoil measurement with experimental data. Free moving reference · Measured photon fringes

Two local controls and one relative measurement

Use two distinguishable particles on a 16-cell ring. The walker occupies the positive y-spin channel of the untilted walk on its axial slice. A tick on this channel is one right shift and the local sine-of-phase energy is sin p. We add a uniform rest energy of two. Give the reference its own hopping band M + J(1 − cos P), with J = 1/M. It has rest energy M and inertial mass M near P = 0. Take M = 4 unless stated otherwise. The selected continuous clock Hamiltonian is H = 2 + sin p + M + J(1 − cos P) + V. The spin choice, the reference band and the contact coupling are explicit inputs. The pulse circuit implements this energy with local gates.

The contact V = gΠ acts when the two particles occupy the same cell, with Π the coincidence projector and g = 1/2. For a clock profile f, weight each one-body hopping matrix element by the average of f at its endpoints, and each onsite energy by f at its site. The two bounded profiles are c(x) = cos(qx) and s(x) = sin(qx)/q with q = π/4. The classical geometric combination c s′ − s c′ is exactly one around the ring. An ordinary spatial translation generated this way would leave Π fixed.

For each profile the checker applies onsite phase gates and nearest-neighbour hopping rotations in a symmetric sequence, then uses their exact inverses in a four-pulse loop. The generator to leading order in the squared pulse angle θ² is B = i[H[c],H[s]] with the order used here. Both particles and the contact are pulsed. The laboratory sets the profiles. The final observable records only their separation. Attaching the pulse controller to the second particle would define a different experiment. Pulse circuit and density-matrix checks

What the interaction contributes

Subtract the generator at g = 0. The remaining operator has a short exact expression, valid at any g for the leading pulse coefficient. Here {A,B} = AB + BA and v denotes the velocity derivative of a one-body band.

B(g) − B(0) = sin(q)/(2q) {V, v_w + v_r}
v_w = cos p,     v_r = J sin P

For a hop from site a to its neighbour b, the cross terms in the commutator contain c(b)s(a) − s(b)c(a) = −sin(q(b−a))/q. Contact energy can sit at either end of that hop. Adding the two possible orderings gives the anticommutator above. The two contact terms commute with each other. The checker compares this expression with the two directly multiplied profile Hamiltonians on a complex two-body state. Their largest component difference was below 6 × 10⁻¹⁶.

The placement of the interaction energy is part of the prediction. For example, assign a fraction α of that energy equally to the two neighbouring clock meters and the rest to the coincidence site. The uniform Hamiltonian and its scattering are unchanged. At the two stated profiles the contact contribution acquires the factor 1 − α(1 − cos q). The factor approaches one for long-wavelength controls. A measurement at two q values could distinguish this symmetric distribution from a strictly onsite one.

Identical individual states, opposite counts

First fix total crystal momentum to zero. Write |r⟩ for the equal superposition of all common translations of a pair at separation r = y − Y. With equal probability prepare (|0⟩ + exp(iφ)|1⟩)/√2 or (|4⟩ − exp(iφ)|5⟩)/√2. Each particle individually has the maximally mixed density matrix for every φ. The two contributions to its adjacent-site coherence cancel. The four recorded separations each have probability 1/4. Both phases give the same total mean energy.

Compare the interaction-on and interaction-off coincidence probabilities for the same initial state. For a weak loop their difference divided by θ² is

D(φ) = g sin(q)/(8q) [sin φ + J cos φ].

At φ = +π/2 and −π/2 this gives +0.056270 and −0.056270. Finite pulse angles 0.12, 0.06 and 0.03 bring the positive-phase estimate from +0.053457 to +0.055568 to +0.056094. Removing the relative coherence while keeping the same initial separation counts gives zero for the interaction contribution at this order.

The table reports actual simulated coincidence probabilities after finite pulses. Each pair of loops uses angles +θ and −θ. The signed difference is the change on switching the contact on at positive phase minus the same change at negative phase. In a finite sequence the uniform-clock approximation can miss even its sign.

Pulse angle and loop pairsPositive phase, g onPositive phase, g offNegative phase, g onNegative phase, g offSigned difference
0.15, four pairs0.321020.314570.157920.16792+0.01646
0.30, four pairs0.252860.270720.018830.02505−0.01164
0.24, eight pairs0.129440.162680.041170.03273−0.04169

For the last row, 3,500 independent ideal preparations at each of the four settings suffice for a 95% lower bound on the chance of identifying the sign. This one-sided variance bound uses the four Bernoulli probabilities in the table. Detector loss, calibration drift and preparation errors would need their own measurements.

Where the phase is carried

A localized version allows the two particles to exchange roles. Put the walker coherently on sites 0 and 1 while the reference is either at site 0 or at site 4, with opposite walker phases in the two branches. The reduced states are independent of φ. Repeat with the reference carrying the coherence and the walker occupying the near or far site. In either preparation the initial coincidence probability is 1/4. The two interaction contributions are

phase on walker:      g sin(q)/(8q) sin φ
phase on reference:  −g sin(q)/(8q M) cos φ.

A reference phase of zero gives −0.014067 at M = 4 and −0.007034 at M = 8. A walker phase of π/2 gives +0.056270 at both masses. An incoherent mixture of the two product branches and their entangled equal superposition have the same leading readout. At this order the detector resolves the local conditional phase. Establishing entanglement would require another measurement.

Calibrating the collision by recoil

The coupling can be checked without clock pulses. Let a packet approach the reference in the zero total-momentum sector with central momentum zero. Both particles start with zero crystal momentum and their group velocities differ by one. The second elastic solution has cos p′ = −15/17 and sin p′ = −8/17. In this reflected branch the reference gains 8/17 units of kinetic energy, exactly the energy lost by the walker. The total crystal momentum stays zero modulo 2π.

The relative-coordinate hopping is (i − J)/2. Matching the two travelling waves at the collision site gives reflection probability g²/(v² + g²) for incident relative speed v, hence 1/5 here. The interaction also supports a localized pair with energy 2 + M + J + sgn(g)√(1 + J² + g²). Its energy lies above the band for repulsion and below it for attraction. Reflection fixes the magnitude of g, and measuring which side hosts the pair fixes its sign. The prediction for the clock readout can then use both independent calibrations. Related lattice scattering treatment

A separate simulation propagates an approaching Gaussian directly with the uniform local Hamiltonian. For packet widths 6, 12 and 24 cells, the reflected fractions are 0.201278, 0.200317 and 0.200079. The conditional reference energy gains are 0.469483, 0.470314 and 0.470520, approaching 8/17 = 0.470588. These numbers concern the hopping model specified above. Scattering and bound-state replay

The three-dimensional bound pair tests whether a composite made with a local interaction follows the same inertial law as its constituents.

Does a moving reference hide the pulse displacement?

Sections in this chapter

Two distinguishable, freely moving copies of the walk can measure their signed separation along y. A translation of both copies leaves every measured separation unchanged, even if its magnitude depends on their total momentum. The earlier single-packet test used the lattice as its position reference. Here the preparation fixes only the separation distribution and total momentum. Either copy alone is equally likely to be found at every site in the periodic box. All calculations below are model predictions. The single-packet pulse test

The same pulses on both copies

Measure position in coarse cells and set the tick and ℏ to one. Each copy uses H = (W† − W)/(2i) and the spatially weighted pulse H[f] = (fH + Hf)/2. Two real patterns fit a periodic lattice exactly. They are c(y) = cos(qy) and s(y) = sin(qy)/q, with q an allowed nonzero wave number. The corresponding continuum geometric bracket would give the same unit shift everywhere because cs′−sc′ = 1. We apply each pattern to both copies using an external spatial phase. We order the loop so its weak action is exp(−iε²B), with B = i[H[c],H[s]] on each copy. Terms acting on different copies commute.

The native H(p) has Pauli components (sin pₓ cos pᵧ cos p_z, sin pᵧ cos p_z, sin p_z). Let M₊ and M₋ be the mean of H(p) and H(p ± qŷ), respectively. A complex mask exp(iqy) changes momentum by q. Combining the conjugate masks into the two real pulses gives the exact finite-box result

B(p) = (M₊² − M₋²)/(2q)
     = F(q) cos²pₓ sin(2pᵧ) cos²p_z / 2,
F(q) = cos²(q/2) sin(q)/q.

All squares in the first line are scalar matrices. The two masks remove the position seam of a linear ramp. At q = π/4 their known factor is F = 0.768468. It tends to one as q tends to zero.

On the sector of total crystal momentum P, the first copy has momentum p and the second has P−p. The joint generator is B(p)+B(P−p). At P = 0 it vanishes for every internal state because B is odd. Changing only the total momentum to (π/2,0,0) gives the internal generator F cos(2pₓ) sin(2pᵧ) cos²p_z / 2. A translation of the whole system still gives zero change in separation.

Total x momentumInternal x carrierRelative displacement per squared pulse angle
000
π/20+0.162455 coarse cells
π/2π/2−0.162455 coarse cells

Each preparation uses amplitudes (1, 2, 3, 2, 1) along each relative coordinate, centered about zero separation, on a 16-cell torus per axis. The site probabilities are the same in all three rows. The normalized overlap C of this profile with a two-cell translate is 10/19. On the infinite coordinate patch the derivative with respect to pᵧ of the joint generator gives the relative velocity. Its envelope average in the last two rows is ±F C²(1+C)/2. The finite-torus replay instead constructs the probability for each signed relative-site outcome and differences its centroid after evolution by the weak generator. The initial packet and the first-order shifts lie away from the cut in the relative coordinate. The replay also applies both ordered pulse pairs directly to two-copy spin states. A measured separation signal would distinguish these pulse dynamics from a common translation. A null at rest alone would allow both. Replay the finite periodic calculation

When the moving reference also operates the clock

A reference that supplies the pulse origin changes the experiment. In one dimension consider a gradient specified by the signed separation r = x_A−x_R. The clock Hamiltonian is H = E_A(p_A)+E_R(p_R). The gradient pulse is K = (rE_A+E_Ar)/2 because the reference sits at zero of its own ramp. This joint operation commutes with total momentum. For scalar branches write v = dE/dp. The weak generator is B = i[H,K] = E_A(v_A−v_R), so its change in separation per squared angle is

∂B/∂p_A − ∂B/∂p_R = v_A(v_A−v_R) + E_A(E_A″+E_R″).

Even conventional relativistic energies E = √(m²+p²) give 1 + m_A/m_R when both packets are at rest. For equal masses the coefficient is two. The reference receives the opposite impulse from the gradient. This is a different control from the preceding common external pattern and requires coupling the actuator to the separation. A separation signal has different implications in the two experiments.

What changing the boost would require

For the uniform clock now take the actual positive tick phase E(p) = arccos(cos pₓ cos pᵧ cos p_z) on a regular momentum patch. Let two noninteracting packets have total H = E₁+E₂, ordinary P = p₁+p₂, mean position R = (x₁+x₂)/2 and separation r = x₁−x₂. The standard boost brackets are {Kᵢ,Pⱼ} = δᵢⱼ H and {Kᵢ,H} = Pᵢ. The first requires any smooth packet-level candidate to take the form Kᵢ = Rᵢ H + Iᵢ(r,p₁,p₂). The second then tests

{Kᵢ,H} = H(v₁+v₂)ᵢ/2 + ∂ᵣIᵢ · (v₁−v₂).

When the packets have the same velocity, every regular relative correction drops out. Set both momenta to (π/4,π/4,0). Then H = 2π/3 and each y velocity is 1/√3. The resulting y bracket is 1.209200, while ordinary total y momentum is π/2 = 1.570796. This excludes a smooth boost improvement for these free packets under the stated translation law. It leaves open extra dynamical fields and interactions that also change H. The standard quantum free boost is the sum of the two symmetrized position-energy products. Wallace, equations 1–6

One explicit change of dynamics clarifies what a moving-pair measurement could decide. Restrict the center motion to a single continuum direction y and write k = (p₁−p₂)/2. Keep the native rest energy as an internal mass M(k) = 2E(k), then prescribe H★(P,k) = √(P²+M(k)²) and K★ = (RᵧH★+H★Rᵧ)/2. On this patch the longitudinal boost brackets hold exactly because H★ ∂H★/∂P = P with the derivative taken in the total longitudinal momentum. For k = (π/4,π/4,0) both prescriptions give rest energy 2π/3. At P = π/2 the native sum is 3π/4 and the prescribed energy is 5π/6. A phase comparison for coherently prepared moving and resting pairs would test their difference of π/12 radians per tick in the moving energy, after calibrating the same rest energy. This construction prescribes the center motion, changes the energy even for widely separated free walkers and uses a continuum momentum patch. It neither supplies finite-depth lattice gates nor establishes the full three-dimensional boost algebra. Relativistic two-body mass construction

A finite-range clock with an improved two-body contact

Sections in this chapter

Can a local Hamiltonian improve both the propagation and the collision of slowly moving clocks? Here a four-component clock retains the three spin coefficients of the six-stage walk. A momentum-dependent mass repairs its leading free dispersion error and shifts seven spurious low-energy modes. A particular onsite spin coupling also suppresses the low-momentum error of the affine clock pulse. This is a proposed continuous-time Hamiltonian. The earlier massive walk calibrated its rest phase and quadratic axial dispersion using tilted gates. The construction below adds finite-range mass hopping and tests a distinct interacting clock. Earlier gate calibration

Correct the dispersion in every direction

Set the cell size and ℏ to one and fix m > 0. Take Hermitian Dirac matrices αₓ, αᵧ, α_z and β, each squaring to the identity and anticommuting with the other three. For momentum k = (x,y,z), define

b(k) = (sin x cos y cos z, sin y cos z, sin z),     tᵢ = 1 − cos kᵢ,
D(k) = 2 Σᵢ tᵢ²/(3m) + 2 Σᵢ<ⱼ tᵢtⱼ/m,
h(k) = α·b(k) + β[m+D(k)],     E² = |b|² + (m+D)².

These trigonometric polynomials require finitely many hopping distances. The two branches have energies ±E. Since |b|² = 1 − ∏ᵢ cos²kᵢ, its quartic error relative to |k|² is −Σᵢ kᵢ⁴/3 − Σᵢ<ⱼ kᵢ²kⱼ². The term 2mD cancels both parts. Thus E² = m²+|k|²+O(|k|⁶), and its free clock-pulse current ∇E²/2 agrees with k through fourth order. On the ray k = a(1,−0.7,0.45), halving a from 0.09 to 0.045 takes the squared-energy error from 1.86×10⁻⁷ to 2.89×10⁻⁹ and the current error from 4.94×10⁻⁶ to 1.54×10⁻⁷ at m = 1.

The vector b is zero precisely at the eight corners with every component 0 or π modulo 2π. At a corner with r components equal to π the added mass is [8r/3 + 4r(r−1)]/m. The seven unwanted corners rise above the rest energy m. In fact D > 0 anywhere except the central zero, so E = m only there. On an axis at m = 1 the exact expression E² = 1+2t+t²/3+4t⁴/9 rises strictly with t = 1−cos p. Momentum-dependent masses and higher-order Wilson terms have precedents. The mixed products above are chosen for the cosine-product dispersion of this particular walk. The coefficients depend on 1/m, so the construction assumes a fixed positive mass. Tanimura, Hagino and Liang, section IV.B.2

A collision whose leading spin error cancels

Use distinguishable copies A and R. Their free Hamiltonian is H₀ = h_A+h_R. At the same lattice site add V = g δ(x_A,x_R) S with S = β_Aβ_R. Let X_A and X_R denote their position operators. For an affine pulse along j, put its interaction energy at the collision site,

Kⱼ = {X_Aⱼ,h_A}/2 + {X_Rⱼ,h_R}/2 + X_Aⱼ V,
H = H₀+V,     v_aⱼ = i[h_a,X_aⱼ].

Braces here denote the anticommutator. At contact X_AⱼV = X_RⱼV, and [V,X_aⱼ] = 0. For the terms containing each h_a one can therefore use X_aⱼV in Kⱼ. Combining i[h_a,X_aⱼV] and i[V,{X_aⱼ,h_a}/2] gives i[{h_a,V},X_aⱼ]/2 = {V,v_aⱼ}/2. This retains the ordering of the spin matrices at both ends of a hop. The full affine bracket on the infinite lattice is

i[H,Kⱼ] = Σₐ ∂ⱼE(kₐ)²/2 + {V,v_Aⱼ+v_Rⱼ}/2.

The replay independently evaluates both orders on an open axial box and checks the contact part to 3×10⁻¹⁴. If all incoming and outgoing momentum components have magnitude ≤ κ ≤ 1, each v_aⱼ equals α_aⱼ plus an error with norm at most 3κ²/2 + 8κ³/(3m). The constant spin matrices anticommute with S. Consequently the contact contribution between low-momentum subspaces has norm bounded by 2|g| times that single-copy error. For a density contact S = I the constant spin matrix survives in the momentum-space kernel. On the positive-positive branch alone the density diagonal vanishes at rest, and the difference in leading powers can still be tested. For equal incoming and outgoing momenta k on both copies the diagonal entries, measured in units g/L³, are 2(m+D)∂ⱼD/E for the scalar contact and 2∂ⱼE for the density contact. At k = a(1,−0.7,0.45), j = x and m = 1, reducing a from 0.10 to 0.05 changes the scalar entry from 0.002690 to 0.000339 and the density entry from 0.198338 to 0.099789.

The doubler can participate in a real collision

First set D = 0. Two positive-energy packets with identical axial momentum p can scatter to momenta p+π and p−π at exactly the same total momentum and energy. On an even periodic lattice these two outgoing wave numbers are equivalent. Since h(p±π) = βh(p)β, a normalized incoming spinor u has an outgoing partner βu. In that channel the contact matrix element is g/L³, and the affine contact contribution is 2(g/L³) cos p sin p/E. At m = 1 and p = π/4 the latter is 0.816497 g/L³. A small low-to-low bracket alone would miss this scattering channel.

With the improved mass the positive-pair detuning for the same momenta is 3.509400 at p = π/4. It tends to 16/(3m) at p = 0. The axial partners can still have equal energy at p = π/2, outside the intended low-momentum sector. At zero total momentum the free mixed-sign branches have total energy zero, while a positive pair has energy 2E(k). A sufficiently low free energy above 2m therefore restricts a positive pair to momenta near the central minimum.

How much high-momentum population remains?

Prepare both copies at zero momentum with positive β spin on an even L³ torus, and let Q count positive-positive states at the seven nonzero corners, at total momentum zero. The initial matrix element to each selected corner is g/L³ for either mass function. Therefore the Q probability begins as 7(g/L³)²t². A finite energy gap does not eliminate the initial mixing.

For the improved clock, let Δ = 16/(3m) be the smallest free energy difference of those corner pairs from 2m. Then Δ‖Qψ(t)‖ ≤ ‖(H₀−2m)ψ(t)‖. The initial plane wave obeys ‖(H−2m)ψ(0)‖ = |g|/√(L³), this norm is conserved under H, and ‖V‖ = |g|. The triangle inequality gives an all-time bound on the selected population,

Pr(Q,t) ≤ min(1, [|g|(1+1/√(L³))/Δ]²).

At L = 4, m = 1 and g = 0.2 this bound is 0.001780. Evolving all 1,024 spin and relative-momentum amplitudes to t = 0.2 on the same torus gives corner probabilities 2.734×10⁻⁶ with D = 0 and 1.083×10⁻⁶ with D present. Both have the predicted short-time coefficient 6.836×10⁻⁵. This bound counts only the specified corners. Other momenta, renormalization by intermediate states and the remaining spacetime commutators require their own tests. The finite-range Hamiltonian and onsite contact establish neither an exact low-energy interacting symmetry nor a quantum-walk realization of gravity. Replay the clock, contact and leakage tests

Virtual recoil at a contact

The improved one-dimensional Hamiltonian has a single low positive-energy minimum. Does removing the other momenta leave the two-body coupling intact? A local contact can transfer any lattice momentum between the two particles, even when the intermediate state cannot escape as an outgoing pair. The calculation below measures how much this changes the low-energy interaction.

Use two distinguishable copies of h(k) = σz sin k + σx m(k) with m(k) = 1 + (2/3)(1−cos k)², in units with lattice spacing, rest mass and ℏ equal to one. Write e(k)² = sin²k + m(k)². It is strictly increasing with t = 1−cos k on 0 ≤ t ≤ 2, since e² = 1 + 2t + t²/3 + 4t⁴/9. At total momentum zero the free pair energies are 2e(k), 0, 0, −2e(k). A low positive pair with energy near 2 therefore has no second positive high-momentum channel at the same energy.

For separation zero let the spin contact be gA, with A = σx ⊗ σx. On an even periodic ring of length L the contact connects any incoming and outgoing relative momenta with matrix element gA/L. Choose the retained channel P as the positive-positive pair at |k| < π/2. Put everything else in Q. This cutoff specifies the matching calculation. Define one-spin projectors Πα(k) = [I + α h(k)/e(k)]/2. For any chosen sector S its contact resolvent is

G_S(z) = (1/L) Σ_(k,α,β in S) Πα(k) ⊗ Πβ(−k) / [z − (α+β)e(k)].
T_Q(z) = [(gA)⁻¹ − G_Q(z)]⁻¹
       = gA + g² A G_Q(z) A + O(g³).

Here T_Q includes every visit to the eliminated states between successive contacts. It is an energy-dependent interaction for the remaining channel. At z=2 the nearest eliminated free level lies 2√34/3−2 ≈ 1.887 away for rings divisible by four. Thus |g|‖G_Q‖ ≤ 0.106 at g=0.2, and the four-by-four inverse also sums a convergent expansion. Feshbach, projection of closed reaction channels (1958)

A density contact appears at second order. Its coefficient in the full two-spin vertex is g² Tr(G_Q)/4, since A²=I. For the high-momentum portion alone, each momentum contributes [1/(z−2e) + 2/z + 1/(z+2e)]/(4L). At z=2 this is positive throughout |k|≥π/2. The open pair at rest is |+x,+x⟩. Other generated spin operators contribute to its matrix element as well.

Eliminated intermediate states, L = 4096Identity coefficient divided by g²Rest matrix element at order g², divided by g²
All band pairs from the cutoff through the zone boundary+0.105899−0.122920
Above plus mixed and negative pairs below the cutoff+0.257974−0.093334

At g=0.2 the exact reduced rest vertex is 0.1963453. The second-order estimate is 0.1962667. The calculation at L=1024 yields 0.1963324. The reduction of the open-channel matrix element and the positive identity coefficient are compatible because this projection also samples the other spin operators. Their split depends on the specified cutoff.

After matching at rest. Use the exact reduced rest vertex as the measured coupling gR. For a free on-shell positive pair with momentum labels (+κ,−κ), the forward matrix element of the matched bare spin vertex is gR [m(κ)/e(κ)]², and the reversed matrix element is gR. Evaluating the full closed-channel inverse at z=2e(κ) gives the following differences.

κ, L = 4096(Exact − matched forward)/κ²(Exact − matched reversed)/κ²
0.098175+0.002892−0.009017
0.049087+0.002949−0.009127
0.024544+0.002963−0.009155
0.012272+0.002967−0.009162

At fixed bare g there is an O(g²) change of the energy vertex even at rest. Matching one open-channel value absorbs that constant. The remaining matrix elements are analytic and even in κ near rest because the eliminated sector is gapped and invariant under momentum reversal. Their corrections to the matched contact begin at O(g²κ²) here. A clock or boost experiment also couples to external operators. Eliminating the same states dresses the clock vertices, preparations and observables. Inferring a boost violation from the generated identity component alone would require an additional relation among those operators or a calculation of the complete readout.

Restoring the retained free loop gives the exact equality T(z) = [T_Q(z)⁻¹ − G_P(z)]⁻¹ wherever the inverses exist. The checker uses a small imaginary energy to evaluate this expression beside a free pole on a 16-site ring. It also inverts the complete 64-dimensional two-body Hamiltonian in that total-momentum sector. The restored contact matrix agrees with the direct contact sum within 6 × 10⁻¹⁷, and the positive-pair diagonal resolvent agrees with the dense inverse within 7 × 10⁻¹⁵. The near-shell table above uses only the regular closed-channel vertex. Open-channel rescattering enters through this final restoration.

Run python3 virtual_contact.py for the table and both checks. The module also supplies a total-momentum contact determinant and a pole-free bracket solver. For L=128, K=0, g=−0.5 it finds a bound-pair pole at 1.945549460383 below the positive-pair threshold of 2.

Replay the calculation

Does a bound pair move according to its rest energy?

Sections in this chapter

This calculation confines both particles to a line. The full three-dimensional calculation tests whether the same conclusion survives motion along three axes.

Two interactions in the same lattice give the same bound pair at rest, including its wavefunction, binding energy and coincidence probability. Set that rest energy to 1.90 in units where each free constituent has rest energy one. When the pair moves, one interaction gives 90.17% of the kinetic response expected for that rest energy. The other gives 96.52%. Measuring the pair at rest cannot settle which moving clock the material supplies.

A frequency and an inertial mass

Let E_b(K) be the energy of the bound pair at total momentum K along one axis. Its rest frequency sets E₀ = E_b(0). Its acceleration under a weak force measures the inverse inertial mass E_b″(0). If the pair shares the limiting speed already fixed by the free constituents, a relativistic dispersion gives E_b(K)² = E₀² + K² in these units. The dimensionless observable R = E₀ E_b″(0) should then be one. This hypothesis can be tested using just the pole of the interacting two-particle spectrum. It avoids choosing a separate clock-density operator for the composite.

Use the axial slice of the improved spin Hamiltonian with m = 1. Its free energy squared agrees with 1 + k² through fourth order. Both models have the same hopping and the same positive and negative one-particle bands. The density contact acts as the identity on the two spins. The mass contact acts as S = β ⊗ β, where β = σₓ on each two-state axial spin. Each interaction acts only at coincidence, with strength g. Three-dimensional clock construction · Eliminating virtual pairs

At zero total momentum, spin conjugation by S interchanges relative momenta p and −p in the free two-body Hamiltonian. The coincident-site Green matrix therefore commutes with S. For the bound branch considered here its local spinor has S eigenvalue +1. Both interactions act identically on this rest eigenstate. At nonzero K the same conjugation takes K to −K, and the two contacts can yield different spectra at a specified K.

The moving spectrum with all four band choices

For relative momentum p use k₁ = K/2 + p and k₂ = K/2 − p. Average the inverse of z − h(k₁) ⊗ I − I ⊗ h(k₂) over the Brillouin zone to obtain the four-by-four local Green matrix G. An isolated pole below the positive-pair continuum satisfies det(S/g − G) = 0 for the mass contact, with S replaced by the identity for the density contact. The calculation retains the positive-positive, negative-negative and two mixed-sign products of the single-particle bands. The pole lies above the mixed-sign continuum at all momenta quoted here. All three rows are solutions of the interacting model at finite g.

Rest energy E₀Strength g for both contactsR for density contactR for mass contactProbability of coincidence at rest
1.900−0.6945050.9016690.9652340.262852
1.975−0.3314370.9654780.9942200.144219
1.990−0.2060920.9842430.9983730.094276

The pole energy and its local spinor were substituted back into the full relative-momentum wavefunction and the original Schrödinger equation. Doubling the momentum grid from 384 to 768 points changed the calibrated strength and E_b(0.3) by less than 10⁻¹⁰. Three steps in K check the curvature extrapolation. A separately implemented four-band resolvent checks the result at rest and in motion.

For the first row at K = 0.3, the predicted energies are 1.921240 for the density contact and 1.922697 for the mass contact. The common-metric prediction is 1.923538. The mass contact improves this particular observable across all three binding strengths. A physical measurement of these moving bound pairs is still open. Bound-state and curvature replay

Move the pair together by one cell

A local change can repair one curvature without changing the rest sector. Allow two particles already on the same cell to hop together to the next cell. Give that hop amplitude −uS/2 and add the onsite term uS at coincidence. In a total-momentum sector this replaces g by g + u(1 − cos K). At K = 0 the whole Hamiltonian is unchanged. For the mass contact, differentiating the bound energy gives an exact relation for its curvature,

R(u) = R(0) + E₀ u (∂E₀/∂g).

The derivative equals the measured contact weight for this even rest branch. It was checked both from its normalized wavefunction and by varying g. At E₀ = 1.90, u = 0.069613716 makes R equal to one. The moving energy at K = 0.3 then misses the relativistic value by −0.0000271. At K = 0.6 the difference is −0.0003811. Keeping the same u and changing only the binding strength to obtain E₀ = 1.975 gives R = 1.014048. The same microscopic adjustment can exactly calibrate one moving clock and overshoot another.

The sine part of the one-particle Hamiltonian comes from the six-stage walk. The improved mass, spin contact and pair hopping are proposed interactions. A universal clock would require a dynamical reason to fix the interactions across different bound states, together with a source coupling for their energy. This two-body calculation provides separate measurements with which to test such a proposal.

Compare the curvatures of three bound clocks

Choose the strength of the joint hop. Each output is the rest energy times the inverse inertial mass. A common relativistic clock gives 1.

Rest energyKinetic response
1.9000.96523
1.9750.99422
1.9900.99837

Does a three-dimensional bound clock have one inertial mass?

Sections in this chapter

A constituent can have the same energy along x, y and z while a bound pair of those constituents responds differently to motion along the three axes. For the finite-range clock tested here, the pair’s measured quantity would be Rⱼ = E₀ ∂²E_b/∂Kⱼ² at zero total momentum. E₀ is its rest frequency and K is the momentum imparted to the entire pair. A relativistic clock with limiting speed one would give Rⱼ = 1 along each axis. These are numerical predictions from a Hamiltonian. Constituent and contact construction · One-dimensional pair calculation

Same clock at rest, three different curvatures

Use two distinguishable copies with mass m = 1. Each has the four-component spin Hamiltonian h(k) = α·b + β(1+D) defined in the preceding clock construction. Its energy squared is 1 − cos²kₓ cos²kᵧ cos²k_z + (1+D)², invariant under permutations of the three axes. A density contact acts on the spins as I. A mass contact acts as S = β⊗β. Both are strictly onsite. We tune the common strength g = −7.99845631 to a rest pole at E₀ = 1.900, just below the free positive-pair threshold 2.

Direction of pair motionR for density contactR for mass contact
x1.5201891.518292
y1.5337941.533438
z1.4382511.364661

Both contacts give the same entire rest wavefunction on this branch. Their moving spectra separate most strongly along z, by 0.073590 in R. The spin eigenvectors know the order of the three shift directions. The local two-body Green matrix contains products of those eigenvectors, so permutation symmetry of the free energy alone cannot ensure a common pair inertia. Each individual axis reflection is still a symmetry. Flipping the sign of that momentum is equivalent to conjugating each constituent by βσⱼ, where σⱼ acts on its two spin states. These symmetries set all off-diagonal entries of the isolated pole’s curvature tensor to zero.

For a concrete moving-frequency comparison at K_z = 0.02 the poles are 1.9001514280 and 1.9001436695 for density and mass contact, respectively. Their common rest frequency supplies no way to distinguish those two predictions.

How the pole was checked

Let p be the relative momentum, k_A = K/2+p and k_R = K/2−p. At fixed K we integrate the free resolvent over the full periodic Brillouin zone. With s,t = ±1 and Π_s = (I+s h/E)/2 this gives the 16-spin coincident-site Green matrix

G(z,K) = ∫ d³p/(2π)³ Σₛ,ₜ [Πₛ(k_A) ⊗ Πₜ(k_R)] / [z−sE(k_A)−tE(k_R)].

All four energy-sign combinations enter. A bound source vector u satisfies [G − C/g]u = 0, where C is either I or S. At rest inversion gives [G,S] = 0. The source we track is odd under interchange of the two species and even under S. Its dominant component is the spin singlet of two positive mass orbitals. This rest source and the wavefunction reconstructed from it solve both contact equations. Its kernel is one-dimensional in the full 16-spin matrix. The next absolute eigenvalue of G−C/g at this energy is 0.000691 for either contact. The mixed-sign continuum at K = 0 has energy zero. The positive-pair continuum starts at 2.

The replay follows all six exchange-odd spin sources when K changes. It computes the second derivative of the simple pole, including its mixing with the other source directions, and separately finds moving poles by solving the energy equation. A direct inversion of 16×16 Hamiltonians on a small three-dimensional grid checks the projector integration to 4×10⁻¹⁶. The Brillouin grids are quadrature meshes for an infinite lattice, so the momentum step can be varied independently of the grid. At E₀ = 1.900 we refined the mesh from 64³ to 80³ and extrapolated the central differences using steps 0.010, 0.005 and 0.0025. The final refinements of either calculation changed the tabulated R by less than 2×10⁻⁷. The refinement differences measure numerical convergence.

Restoring cubic symmetry with local orientation labels

There is a constructive way to give the pair a direction-independent curvature while retaining every free one-body energy. Add one onsite label o for each of the 24 proper cubic rotations. A particle in sector o evolves with the axes and spins of h rotated together. At each site couple the two particles in the coherent normalized combination |O⟩ = Σₒ |o,o⟩/√24, using g |O⟩⟨O| ⊗ C. This explicitly changes the collision rule and increases the local Hilbert space. A free particle in any added sector still has the original energy spectrum.

The Green matrix seen by that interaction is the average of the 24 rotated matrices evaluated at their rotated momenta. Taking the pole after this average guarantees cubic symmetry and hence one quadratic curvature. For E₀ = 1.900 the resulting R is 1.528827 for the density contact and 1.523844 for the mass contact. Cubic symmetry fixes equality between directions. Its value still differs from one. Averaging the three numbers in the table would give a different prediction.

A further finite-range interaction can calibrate this common value at one binding energy. Allow a coincident pair in the matched orientation state to hop as a pair, giving its contact strength the K dependence g(K) = g + c Σⱼ(1−cos Kⱼ). This preserves the calibrated pole at rest and adds cE₀w to R. Here w is the rest probability in the interacting coincident channel, positive for both contacts on the selected source. For a unit source u it is w = (1/g)²/[−u†(∂G/∂z)u]. Using E₀w = 0.265116 gives c = −1.994700 for density contact and −1.975902 for mass contact to set R = 1.

Test those same c values at a second binding energy. Retuning only the onsite g to −7.32156799 gives E₀ = 1.975 and E₀w = 0.154624. Before adding pair hopping the cubic ratios are 1.233683 and 1.232436. After the calibration fixed at 1.900, the second pole gives 0.925254 and 0.926914, respectively. The 96³ to 112³ mesh refinement changes the uncorrected second-pole result by less than 4×10⁻⁷. This is a comparison of two coupling settings with different binding, so it tests transfer of the one-parameter calibration across that family of Hamiltonians. Replay the three-dimensional poles with NumPy

Can a covering measurement detect the shape of the pair?

Sections in this chapter

The ordered three-dimensional pair has two candidate interactions with exactly the same state at rest. A small fixed excess energy selects a different set of allowed momenta for each interaction. The covering result supplied by Aiger, Har-Peled and Žužić helps identify which comparisons preserve that physical difference. Their Theorem 1.1 in the November 27 preprint gives a cover of any three-dimensional convex body by eight translated copies with a common shrink factor below one. The factor can depend on the body. An affine cube needs eight because one smaller copy can contain at most one original corner. Paper, v3

What a self-cover measures

Near rest the filled momentum sublevel has quadratic approximation KᵀRK ≤ 2E₀ΔE, where R is the measured curvature matrix and ΔE is the excess energy. Each positive-definite R gives an ellipsoid. Every invertible affine map carries a cover by translated, uniformly scaled copies to another such cover with the same scale. In particular every ellipsoid has the same optimal four-copy linear scale, √(8/9) ≈ 0.942809. This is a calculation for our quadratic sublevels.

For a unit ball and a covering ball of radius r < 1 centered at t u, each unit boundary point x it covers obeys u·x ≥ (1+t²−r²)/(2t) ≥ √(1−r²). Hence the convex hull of four unit center directions must contain an origin-centered ball of radius √(1−r²). The origin has four positive barycentric coordinates in that tetrahedron. Choose one coordinate a ≤ 1/4. The opposite face has distance d from the origin with (1−a)d ≤ a, so d ≤ 1/3. This proves r² ≥ 8/9. For equality take the four unit directions of a regular tetrahedron and place the centers one third of the way out. Each unit direction has dot product at least 1/3 with one of those four directions, and all four covering balls also contain the origin. Convexity covers the radial segments.

A comparison using the same rods

The two three-dimensional bound-pair calculations give longest-to-shortest semiaxis ratios of 1.03268 for the density contact and 1.06004 for the mass contact at E₀ = 1.90. Both longest axes lie along z and both shortest axes lie along y. The diagonal form follows from separate reflection symmetries. In the spin representation Uⱼ = τ_z ⊗ σⱼ flips the sign of αⱼ and preserves β and the other α matrices. The corresponding coordinate reflection preserves both interactions, so the simple bound branch has no mixed quadratic terms.

An unknown linear calibration of the common rods changes both forms by the same congruence. The generalized eigenvalues of the two forms survive this change. In the model axes they are just the three mass-to-density curvature ratios. One can expand the mass-contact ellipsoid until it contains the density-contact ellipsoid, then do the reverse with the original shapes. The product of those two minimal linear scales is √(max ratio / min ratio) = 1.02649. It also cancels a separate overall normalization of each shell. The 24-orientation collision rule gives 1 for this comparison because each of its quadratic shells is spherical. It still gives incorrect absolute inertia.

To measure the forms, take opposite momentum steps along three coordinate axes and their three pairwise sums for each contact. Use the same rods and extrapolate the second differences toward zero step. The result above is a model prediction. A finite-energy sublevel could have higher-order distortions or lose convexity. A covering bound on a convex body alone supplies neither a physical length scale nor a universal equation of motion. The calculation replays the tetrahedral identities and the two-shape comparison.

What a single recoiling atom does to a photon fringe

Zhang and colleagues trapped one rubidium-87 atom and collected its Rayleigh-scattered light in two opposite directions. The alternatives give the same final internal atomic state and opposite axial momentum kicks. The experimenters varied the atom’s initial motional state, measured its occupation by Raman sideband spectroscopy, and recombined the optical paths to measure a fringe. Figure 4(b) therefore offers an experimental check on one ingredient of the proposed collision experiment. A finite material system can retain information about a momentum transfer and change the interference seen in another system. Zhang et al., Physical Review Letters 135, 230202 (2025)

For balanced optical paths along the axis, a photon with wave number k leaves the atom with a conditional operator exp(±ikX). Tracing out the atom gives the fringe amplitude V = |Tr[ρ exp(2ikX)]|. A thermally occupied harmonic axial mode with frequency νz has position variance (2n̄+1) ℏ/(4πmνz). Its visibility follows as V(n̄) = exp[−2(νr/νz)(2n̄+1)], where hνr = (ℏk)²/(2m). The published caption specifies νz = 36 kHz and the rubidium D₂ transition gives νr = 3.7710 kHz. These inputs fix the axial plane-wave calculation before reading the visibilities. Published Figure 4 · Steck, rubidium-87 D-line data, Table 3

Initial mean occupation n̄Measured fringe visibilityAxial thermal prediction
0.130.8350.768
0.400.7110.686
0.700.6700.604
0.760.6840.589
0.930.5030.549
1.330.4650.464
2.040.4080.345
2.660.2820.266

The table includes all eight digitized marker centers in the published Figure 4(b). The native image resolves about 0.011 phonons and 0.002 visibility over two pixels. The extra digits identify the extraction and the comparison uses the unrounded coordinates. These are fitted fringe measurements read from the figure. The underlying photon counts and their joint covariance were unavailable to this replay. The horizontal and vertical bars in the source represent one standard deviation. Published Figure 4(b)

Cross-check at fixed recoil. Taking the coldest marker as a reference cancels a common multiplicative instrumental contrast. The remaining prediction for the hottest-to-coldest ratio is exp[−4(νr/νz)Δn̄] = 0.347. The two measured contrasts give 0.282/0.835 ≈ 0.338. Moving both vertical coordinates to the opposing ends of their plotted error bars gives 0.308–0.369. Moving the horizontal coordinates across the hot point’s asymmetric error bar and the cold point’s visible disk gives a wider prediction range, 0.244–0.530. These ranges show sensitivity to the coordinates. Turning them into a joint confidence interval would require their covariance.

The absolute comparison is less accurate. The axial calculation produces 0.768 for the coldest point. Its plotted visibility is about 0.835 ± 0.013, above even the calculated ground-state value of 0.811. The largest central residual is +0.095 near occupation 0.76. A constant loss of optical contrast can only lower the calculated values. Quantifying this discrepancy would require the effective axial momentum transfer of the collected optical modes, the trap-frequency calibration uncertainty, and the per-series occupation and visibility calibration. The ratio checks the change across the endpoints and leaves these absolute residuals visible.

A later experiment by the same group changed the width dynamically with a trap-frequency quench. Its independently determined axial frequency was 37.8(3) kHz. The calibrated dimensionless recoil η = 0.316(1) gives a ground-state prediction of exp(−2η²) = 0.81897 ± 0.00104. For the finite-temperature comparison in Figure 3(c), the authors fitted both output-port counts and used interleaved calibration fringes to correct optical imbalance and phase jitter, with independent sideband thermometry for the thermal baseline. Their larger zero-temperature peak of 0.938 (+0.004, −0.008) came from a global Bayesian reconstruction. These two levels of inference have different inputs. Cheng et al., experimental preprint (2026), Figure 3 and supplemental equations S11 and S24

Optical fringe visibility measures one Fourier component of the atom’s position distribution. A classical random optical phase with the same distribution of 2kX gives the same marginal fringe. A marginal fringe by itself cannot certify atom–photon entanglement, identify the carrier of a compensating kick, or establish that a proposed two-body collision implements the same phase. A test of the collision proposal still requires its specified material reference, momentum accounting, and joint or relational readout.

Run python3 reference_data.py for the offline calculation. To audit the digitization, save the linked publisher PDF and run python3 reference_data.py --source paper.pdf. The checker verifies the PDF SHA-256 599aab6511d8165125ecc4b88580f43d792941a56f0836cd5634e4b459f28ed9, decompresses its original figure, and checks the marked pixel locations. Source PDF

Replay the calculation

Programs and transcript

The offline study includes the twenty-four calculation programs and all 55 native Tally checks. Run the supplied replay with the published Tally runtime. The standard replay requires Python. Add NumPy and pass --full to reproduce the three-dimensional momentum integrals as well.

Complete Tally transcript
✓ the homogeneous gate clock and proposed rod scale inside the reference shell  (by cross-pairing plus and minus sides; derived)
✓ the nonlinear finite-grid rest source gives the selected central scalar value  (by cross-pairing plus and minus sides; derived)
✓ the empty edge and corner cells satisfy source-free force balance  (by cross-pairing plus and minus sides; derived)
✓ each axial occupation sources the spring field through its own clock derivative  (by cross-pairing plus and minus sides; derived)
✓ the finite probe lowers its relaxed gap through the inverse central stiffness  (by cross-pairing plus and minus sides; derived)
✓ the radius and external mass are fixed by the same scalar field  (by cross-pairing plus and minus sides; derived)
✓ including the compressed shell reproduces its exterior energy and Newtonian binding formula  (by cross-pairing plus and minus sides; derived)
✓ the equilibrium tangential pressure per unit surface energy  (by cross-pairing plus and minus sides; derived)
✓ the two equilibrium annular clocks have different coordinate rates  (by cross-pairing plus and minus sides; derived)
✓ local rod surveys independently determine both circumference gradients  (by cross-pairing plus and minus sides; derived)
✓ the held-back two-shell curvature and clock comparison fails the unit GR ratio  (by cross-pairing plus and minus sides; derived)
✓ removing the exterior shell restores the vacuum relation  (by cross-pairing plus and minus sides; derived)
✓ the two supported shells leave distinct exterior and total masses  (by cross-pairing plus and minus sides; derived)
✓ dust pairs, dust with a light sheet, and two light sheets have three distinct Einstein responses  (by cross-pairing plus and minus sides; derived)
✓ the attractive static response violates the positive Gram bound at the third setting  (by cross-pairing plus and minus sides; derived)
✓ a constrained repulsive term repairs the static sheet coefficient  (by cross-pairing plus and minus sides; derived)
✓ balanced light beams retain a shear-dependent angular response  (by cross-pairing plus and minus sides; derived)
✓ a bound chain pair misses the reserved momentum response after matching size and clock  (by cross-pairing plus and minus sides; derived)
✓ the two exact dimer tail distributions have distinct adjacent-bin ratios  (by cross-pairing plus and minus sides; derived)
✓ an isolated canonical massive scalar can change its total spatial stress at fixed energy  (by cross-pairing plus and minus sides; derived)
✓ density retardation and material pressure add in the long-wave shell radiation amplitude  (by cross-pairing plus and minus sides; derived)
✓ the endpoint clock pair differs from the independently calibrated prediction by 1.162 in units of ten to the minus nineteen  (by cross-pairing plus and minus sides; derived)
✓ the positive rotor curl and Cotton spectra predict distinct squared frequency ratios  (by cross-pairing plus and minus sides; derived)
✓ the cubic and linear two-polarization spectra differ at the second wave number  (by cross-pairing plus and minus sides; derived)
✓ the two imposed shear signals carry unit combined squared drive amplitude  (by cross-pairing plus and minus sides; derived)
✓ the native squared energy changes with carrier and is constant on the flat plane  (by cross-pairing plus and minus sides; derived)
✓ rotating the transverse carrier from zero to a quarter pi halves the weak displacement  (by cross-pairing plus and minus sides; derived)
✓ the same pulse can leave a packet centered or reverse its displacement  (by cross-pairing plus and minus sides; derived)
✓ the normalized three-site packet keeps half its two-site displacement under the transverse carrier change  (by cross-pairing plus and minus sides; derived)
✓ equal-energy spinors on the flat plane can have a nonzero translation form factor  (by cross-pairing plus and minus sides; derived)
✓ the first shell fixes the incident radial slope at the second shell  (by cross-pairing plus and minus sides; derived)
✓ the second junction reproduces the mass measured by the outer rods  (by cross-pairing plus and minus sides; derived)
✓ the two equilibrium clocks have distinct redshifts relative to infinity  (by cross-pairing plus and minus sides; derived)
✓ adding proper shell energy gives the same mixed clock susceptibility in both orders  (by cross-pairing plus and minus sides; derived)
✓ the explicit ordered two-link pulses cancel the intermediate mask and retain the two endpoints  (by cross-pairing plus and minus sides; derived)
✓ reversing the endpoint profile reverses the commutator and equal endpoints give no displacement link  (by cross-pairing plus and minus sides; derived)
✓ the finite three-dimensional envelope sets the reference clock-loop displacement  (by cross-pairing plus and minus sides; derived)
✓ changing only the x carrier changes the localized packet displacement along y  (by cross-pairing plus and minus sides; derived)
✓ transverse position localization lifts the zero of the sharp-momentum preparation  (by cross-pairing plus and minus sides; derived)
✓ a relative packet with fixed nonzero total momentum has a nonzero signed shift before profile calibration  (by cross-pairing plus and minus sides; derived)
✓ compensated nearby and remote coherences cancel in the marginal while the coincidence population is one quarter  (by cross-pairing plus and minus sides; derived)
✓ opposite conditional phases reverse the interaction part of the walker coincidence count  (by cross-pairing plus and minus sides; derived)
✓ doubling the mobile reference mass halves its separately addressable clock signal  (by cross-pairing plus and minus sides; derived)
✓ the reflected walker loses precisely the energy gained by the finite reference  (by cross-pairing plus and minus sides; derived)
✓ the reflected relative velocity reverses and the reference records eight seventeenths of recoil energy  (by cross-pairing plus and minus sides; derived)
✓ the collision fraction and squared bound-energy offset independently encode the contact strength  (by cross-pairing plus and minus sides; derived)
✓ the onsite mass polynomial supplies both missing fourth-order coefficients in the squared energy  (by cross-pairing plus and minus sides; derived)
✓ the positive pair corner is separated from the rest pair by sixteen thirds  (by cross-pairing plus and minus sides; derived)
✓ the directly squared spin Hamiltonian equals its strictly increasing axial energy polynomial  (by cross-pairing plus and minus sides; derived)
✓ the exact two-cell contact equation gives the same positive-pair bound pole for both rest-spin contacts  (by cross-pairing plus and minus sides; derived)
✓ the two-cell bound pair has a nonzero off-resonant corner probability even after detuning  (by cross-pairing plus and minus sides; derived)
✓ moving an occupied pair together supplies a new kinetic response while every rest-state energy is preserved  (by cross-pairing plus and minus sides; derived)
✓ the normalized native four-component symbol has unit self-overlap  (by cross-pairing plus and minus sides; derived)
✓ equal axis transfers at a diagonal momentum select three different ordered-spin overlaps  (by cross-pairing plus and minus sides; derived)
✓ the anisotropic spin weights factor from the common transfer of the two band spinors  (by cross-pairing plus and minus sides; derived)
Native Tally source
# Static and finite-frequency tests of shell clocks and stress exchange.
ratchet 32 step
import "atom"
let zero=whole(0 trial)
let one=whole(1 trial)
let two=whole(2 trial)
let three=whole(3 trial)
let four=whole(4 trial)
let half=fraction(1 trial,2 trial)
let s=fraction(1 trial,7 trial)
fn lapse(u)
  return share(one+flip(u),one+u)
end
fn area_scale(u)
  return power(one+u,2 trial)
end
check lapse(s)==fraction(3 trial,4 trial) and area_scale(s)==fraction(64 trial,49 trial) "the homogeneous gate clock and proposed rod scale inside the reference shell"
let load=fraction(17 trial,10 trial)*s*area_scale(s)
check load==fraction(544 trial,1715 trial) "the nonlinear finite-grid rest source gives the selected central scalar value"
let edge=share(two*s,whole(5 trial))
let corner=share(s,whole(5 trial))
check whole(6 trial)*edge==two*s+two*corner and whole(6 trial)*corner==three*edge "the empty edge and corner cells satisfy source-free force balance"
let face=whole(5 trial)*s+flip(four*edge)
check face==share(two*load,area_scale(s)) "each axial occupation sources the spring field through its own clock derivative"
let slope=share(two,area_scale(s))
let stiffness=fraction(7 trial,34 trial)
check slope*slope*stiffness==fraction(16807 trial,34816 trial) "the finite probe lowers its relaxed gap through the inverse central stiffness"

let r=fraction(49 trial,16 trial)
let R=r*area_scale(s)
let exterior=two*r*s
check R==four and exterior==fraction(7 trial,8 trial) "the radius and external mass are fixed by the same scalar field"
check lapse(s)+two*r*s*s==exterior and one+flip(share(one,two*R))==exterior "including the compressed shell reproduces its exterior energy and Newtonian binding formula"
check share(one,whole(12 trial))==share(one+flip(lapse(s)),four*lapse(s)) "the equilibrium tangential pressure per unit surface energy"
let d=fraction(1 trial,10 trial)
let a=fraction(1 trial,4 trial)
fn rod_slope(background,z)
  return share(one+background+flip(z),one+background+z)
end
let n1=lapse(d+a)
let n2=lapse(d+half*a)
let s1=rod_slope(d,a)
let s2=rod_slope(d,half*a)
check n1==fraction(13 trial,27 trial) and n2==fraction(31 trial,49 trial) "the two equilibrium annular clocks have different coordinate rates"
check s1==fraction(17 trial,27 trial) and s2==fraction(39 trial,49 trial) "local rod surveys independently determine both circumference gradients"
check share(n2*s1,n1*s2)==fraction(527 trial,507 trial) and s1*n2>s2*n1 "the held-back two-shell curvature and clock comparison fails the unit GR ratio"
check share(lapse(a),rod_slope(zero,a))==one and share(lapse(half*a),rod_slope(zero,half*a))==one "removing the exterior shell restores the vacuum relation"
check fraction(11 trial,10 trial)+flip(fraction(209 trial,192 trial))==fraction(11 trial,960 trial) "the two supported shells leave distinct exterior and total masses"

fn exchange(e,t,f,p)
  return e*f+e*p+t*f
end
let dd=exchange(one,zero,one,zero)
let dl=exchange(one,zero,one,one)
let ll=exchange(one,one,one,one)
check dd==one and dl==two and ll==three "dust pairs, dust with a light sheet, and two light sheets have three distinct Einstein responses"
check dd*ll+flip(dl*dl)==flip(one) and share(dl*dl,dd)>ll "the attractive static response violates the positive Gram bound at the third setting"
check (one+one)*(one+one)+flip(one*one)==ll "a constrained repulsive term repairs the static sheet coefficient"
check two*(one+fraction(9 trial,25 trial))==fraction(68 trial,25 trial) "balanced light beams retain a shear-dependent angular response"

let old_ratio=fraction(9 trial,10 trial)
let new_ratio=fraction(4 trial,5 trial)
check share(new_ratio,old_ratio)==fraction(8 trial,9 trial) "a bound chain pair misses the reserved momentum response after matching size and clock"
check fraction(1 trial,4 trial)*four==one and fraction(1 trial,9 trial)*whole(9 trial)==one "the two exact dimer tail distributions have distinct adjacent-bin ratios"
let wet=whole(3 trial)
let dry=flip(whole(3 trial))
check wet+flip(dry)==whole(6 trial) "an isolated canonical massive scalar can change its total spatial stress at fixed energy"
let low=share(one,three)
check one+low==fraction(4 trial,3 trial) and power(one+low,2 trial)==fraction(16 trial,9 trial) "density retardation and material pressure add in the long-wave shell radiation amplitude"
let obs=flip(fraction(1196 trial,100 trial))
let calc=flip(fraction(10798 trial,1000 trial))
check obs+flip(calc)==flip(fraction(1162 trial,1000 trial)) "the endpoint clock pair differs from the independently calibrated prediction by 1.162 in units of ten to the minus nineteen"

let qsq_ratio=three
check qsq_ratio*qsq_ratio==whole(9 trial) and power(qsq_ratio,3 trial)==whole(27 trial) "the positive rotor curl and Cotton spectra predict distinct squared frequency ratios"
check share(power(qsq_ratio,3 trial),qsq_ratio)==whole(9 trial) "the cubic and linear two-polarization spectra differ at the second wave number"
let polarization=fraction(3 trial,5 trial)
let cross=fraction(4 trial,5 trial)
check polarization*polarization+cross*cross==one "the two imposed shear signals carry unit combined squared drive amplitude"

# The order of two local clock-control pulses and a finite support packet.
fn squared_energy_drop(cos_x_squared,cos_y_squared)
  return one+flip(cos_x_squared*cos_y_squared)
end
fn y_loop_response(cos_x_squared,cos_y_squared)
  return cos_x_squared*(two*cos_y_squared+flip(one))
end
let half_band=fraction(1 trial,2 trial)
check squared_energy_drop(half_band,one)==half and squared_energy_drop(zero,half_band)==one "the native squared energy changes with carrier and is constant on the flat plane"
check y_loop_response(one,one)==one and y_loop_response(half_band,one)==half "rotating the transverse carrier from zero to a quarter pi halves the weak displacement"
check y_loop_response(zero,one)==zero and y_loop_response(one,zero)==flip(one) "the same pulse can leave a packet centered or reverse its displacement"
let envelope_power=one+four+one
let two_site_coherence=share(one,envelope_power)
check y_loop_response(half_band,one)*two_site_coherence==fraction(1 trial,12 trial) "the normalized three-site packet keeps half its two-site displacement under the transverse carrier change"
let cos_difference=fraction(3 trial,5 trial)
let spin_overlap_squared=share(one+cos_difference,two)
check spin_overlap_squared==fraction(4 trial,5 trial) "equal-energy spinors on the flat plane can have a nonzero translation form factor"

# Independent static shell benchmark. Units have G=c=1.
fn add_shell(interior_mass,proper_mass,radius,inside_slope)
  return interior_mass+inside_slope*proper_mass+flip(share(proper_mass*proper_mass,two*radius))
end
let inner_radius=whole(8 trial)
let outer_radius=fraction(224 trial,15 trial)
let inner_rest=two
let outer_rest=fraction(28 trial,15 trial)
let inner_exterior=add_shell(zero,inner_rest,inner_radius,one)
let slope_before=fraction(7 trial,8 trial)
check inner_exterior==fraction(7 trial,4 trial) and slope_before*slope_before==one+flip(share(two*inner_exterior,outer_radius)) "the first shell fixes the incident radial slope at the second shell"
let slope_after=slope_before+flip(share(outer_rest,outer_radius))
let outer_exterior=add_shell(inner_exterior,outer_rest,outer_radius,slope_before)
check outer_exterior==fraction(49 trial,15 trial) and slope_after*slope_after==one+flip(share(two*outer_exterior,outer_radius)) "the second junction reproduces the mass measured by the outer rods"
let inner_rod=one+flip(share(inner_rest,inner_radius))
let exterior_clock_factor=share(slope_after,slope_before)
check inner_rod*exterior_clock_factor==fraction(9 trial,14 trial) and slope_after==fraction(3 trial,4 trial) "the two equilibrium clocks have distinct redshifts relative to infinity"
let work_derivative=flip(share(inner_rod,outer_radius*slope_before))
check work_derivative==flip(fraction(45 trial,784 trial)) "adding proper shell energy gives the same mixed clock susceptibility in both orders"

# Direct two-link commutator on a right-moving spin component.
# D=(T-T†)/2. The weighted matrix is (f D + D f)/2. Only the intervening site joins sites 0 and 2.
fn real_link_order(f_left,f_middle,f_right)
  let d_right=flip(half)
  let left_entry=d_right*share(f_left+f_middle,two)
  let right_entry=d_right*share(f_middle+f_right,two)
  return d_right*right_entry+flip(left_entry*d_right)
end
let endpoint_profile=whole(5 trial)
check real_link_order(one,flip(two),endpoint_profile)==half and real_link_order(one,whole(11 trial),endpoint_profile)==half "the explicit ordered two-link pulses cancel the intermediate mask and retain the two endpoints"
check real_link_order(endpoint_profile,flip(two),one)==flip(half) and real_link_order(two,one,two)==zero "reversing the endpoint profile reverses the commutator and equal endpoints give no displacement link"

# All three coordinates localized with the same five-site envelope 1,2,3,2,1.
let norm_five=two*one+two*four+three*three
let coherence_five=share(two*one*three+two*two,norm_five)
fn compact_echo(coherence,carrier_cosine)
  return share(coherence*(one+coherence)*(one+coherence*carrier_cosine),four)
end
let drift_rest=compact_echo(coherence_five,one)
let drift_quarter=compact_echo(coherence_five,zero)
let drift_half=compact_echo(coherence_five,flip(one))
check coherence_five==fraction(10 trial,19 trial) and drift_rest==fraction(4205 trial,13718 trial) "the finite three-dimensional envelope sets the reference clock-loop displacement"
check drift_quarter==fraction(145 trial,722 trial) and drift_half==fraction(1305 trial,13718 trial) "changing only the x carrier changes the localized packet displacement along y"
check share(drift_half,drift_rest)==fraction(9 trial,29 trial) "transverse position localization lifts the zero of the sharp-momentum preparation"

# Quantum mobile reference and contact readout. Weak coefficients below
# divide out sinc(q), the independently calibrated sinusoidal profile.
let relative_coherence=fraction(10 trial,19 trial)
let opposite_carriers=share(relative_coherence*relative_coherence*(one+relative_coherence),two)
check opposite_carriers==fraction(1450 trial,6859 trial) "a relative packet with fixed nonzero total momentum has a nonzero signed shift before profile calibration"
let conditional_near=share(one,four)
let conditional_far=flip(conditional_near)
check conditional_near+conditional_far==zero and four*conditional_near==one "compensated nearby and remote coherences cancel in the marginal while the coincidence population is one quarter"
let coupling_g=half
let eight_ref=whole(8 trial)
fn walker_contrast(g,phase_sine)
  return share(g*phase_sine,eight_ref)
end
fn reference_contrast(g,phase_cosine,reference_mass)
  return flip(share(g*phase_cosine,eight_ref*reference_mass))
end
check walker_contrast(coupling_g,one)==fraction(1 trial,16 trial) and walker_contrast(coupling_g,flip(one))==flip(fraction(1 trial,16 trial)) "opposite conditional phases reverse the interaction part of the walker coincidence count"
check reference_contrast(coupling_g,one,four)==flip(fraction(1 trial,64 trial)) and reference_contrast(coupling_g,one,eight_ref)==flip(fraction(1 trial,128 trial)) "doubling the mobile reference mass halves its separately addressable clock signal"
let hop_J=share(one,four)
let reflected_cos=flip(fraction(15 trial,17 trial))
let reflected_sin=flip(fraction(8 trial,17 trial))
let reference_gain=hop_J*(one+flip(reflected_cos))
check reflected_cos*reflected_cos+reflected_sin*reflected_sin==one and reflected_sin+reference_gain==zero "the reflected walker loses precisely the energy gained by the finite reference"
check reflected_cos+hop_J*reflected_sin==flip(one) and reference_gain==fraction(8 trial,17 trial) "the reflected relative velocity reverses and the reference records eight seventeenths of recoil energy"
let g2=coupling_g*coupling_g
check share(g2,one+g2)==fraction(1 trial,5 trial) and one+hop_J*hop_J+g2==fraction(21 trial,16 trial) "the collision fraction and squared bound-energy offset independently encode the contact strength"

# Quartic mass correction for the doubled six-stage sine clock, m=1.
let axis_mass_coeff=fraction(2 trial,3 trial)
let mixed_mass_coeff=two
check share(axis_mass_coeff,two)==share(one,three) and share(mixed_mass_coeff,two)==one "the onsite mass polynomial supplies both missing fourth-order coefficients in the squared energy"
fn improved_axial_squared(t)
  let m_prime=one+axis_mass_coeff*t*t
  return two*t+flip(t*t)+m_prime*m_prime
end
let t_pi=two
check improved_axial_squared(t_pi)==fraction(121 trial,9 trial) and two*(fraction(11 trial,3 trial)+flip(one))==fraction(16 trial,3 trial) "the positive pair corner is separated from the rest pair by sixteen thirds"
let t_sample=fraction(2 trial,5 trial)
check improved_axial_squared(t_sample)==one+two*t_sample+share(t_sample*t_sample,three)+fraction(4 trial,9 trial)*power(t_sample,4 trial) "the directly squared spin Hamiltonian equals its strictly increasing axial energy polynomial"

# Two momenta on a two-cell periodic ring: p=0 and pi, total momentum zero.
# Both rest spin products have beta times beta equal to plus one.
let target_rest=fraction(19 trial,10 trial)
let local_green=share(share(one,target_rest+flip(two))+share(one,target_rest+flip(fraction(22 trial,3 trial))),two)
let small_g=flip(fraction(163 trial,830 trial))
check small_g*local_green==one "the exact two-cell contact equation gives the same positive-pair bound pole for both rest-spin contacts"
let corner_ratio=share(target_rest+flip(two),target_rest+flip(fraction(22 trial,3 trial)))
check corner_ratio==fraction(3 trial,163 trial) and share(corner_ratio*corner_ratio,one+corner_ratio*corner_ratio)==fraction(9 trial,26578 trial) "the two-cell bound pair has a nonzero off-resonant corner probability even after detuning"
let joint_hop=fraction(1 trial,10 trial)
fn strength_at_momentum(g,u,cos_k)
  return g+u*(one+flip(cos_k))
end
check strength_at_momentum(small_g,joint_hop,one)==small_g and strength_at_momentum(small_g,joint_hop,flip(one))==small_g+two*joint_hop "moving an occupied pair together supplies a new kinetic response while every rest-state energy is preserved"

# Ordered native spin texture: dot the two four-component walk symbols
# after an axial momentum transfer. Energy alone is axis-permutation invariant.
fn walk_symbol_overlap(cxpair,sxpair,cypair,sypair,czpair,szpair)
  return (cxpair+sxpair)*cypair*czpair+sypair*czpair+szpair
end
let cpair=fraction(9 trial,25 trial)
let spair=fraction(16 trial,25 trial)
let shifted_sines=fraction(7 trial,25 trial)
let texture_x=walk_symbol_overlap(zero,shifted_sines,cpair,spair,cpair,spair)
let texture_y=walk_symbol_overlap(cpair,spair,zero,shifted_sines,cpair,spair)
let texture_z=walk_symbol_overlap(cpair,spair,cpair,spair,zero,shifted_sines)
check walk_symbol_overlap(cpair,spair,cpair,spair,cpair,spair)==one "the normalized native four-component symbol has unit self-overlap"
check texture_x==fraction(14167 trial,15625 trial) and texture_y==fraction(463 trial,625 trial) and texture_z==shifted_sines "equal axis transfers at a diagonal momentum select three different ordered-spin overlaps"
let transfer_drop=one+flip(shifted_sines)
check one+flip(texture_x)==transfer_drop*cpair*cpair and one+flip(texture_y)==transfer_drop*cpair and one+flip(texture_z)==transfer_drop "the anisotropic spin weights factor from the common transfer of the two band spinors"
gates.py
"""Unitary two-stage axial slice of the six-stage walk in a spatially varying scalar."""
from math import acos, cos, sin, sqrt, tan, exp, pi

W0=.8


def clock(u):return (1-u)/(1+u)
def scale(u):return (1+u)**2
def width(u):return W0*clock(u)/scale(u)


def solve_material(w):
    lo,hi=0.,.9
    for _ in range(50):
        mid=(lo+hi)/2
        if width(mid)>w:lo=mid
        else:hi=mid
    return (lo+hi)/2


def fine_shift(a,b,base,sine,sign):
    # Rotate to the local propagation axis, shift unitarily, rotate back at destination.
    p=[c*x+sign*s*y for x,y,c,s in zip(a,b,base,sine)]
    q=[-sign*s*x+c*y for x,y,c,s in zip(a,b,base,sine)]
    p=[p[-1]]+p[:-1];q=q[1:]+[q[0]]
    return ([c*x-sign*s*y for x,y,c,s in zip(p,q,base,sine)],
            [sign*s*x+c*y for x,y,c,s in zip(p,q,base,sine)])


def envelope(y):
    return exp(3*(cos(y-1)-1))*(cos(2*y)+1j*sin(2*y))


def run(n):
    eps=.2;mean_speed=.6;h=2*pi/n
    labels=[];jac=[];base=[];sine=[]
    for j in range(n):
        x=j*h
        y=x
        for _ in range(6):y-=(y+eps*sin(y)-x)/(1+eps*cos(y))
        jt=1+eps*cos(y)
        w=width(solve_material(mean_speed*jt))
        assert abs(w-mean_speed*jt)<2e-15
        t=acos(w)/2
        labels.append(y);jac.append(jt);base.append(cos(t));sine.append(sin(t))
    a=[envelope(y)/sqrt(d) for y,d in zip(labels,jac)];b=[0j]*n
    total=sum(abs(v)**2 for v in a)
    ticks=n//16
    for _ in range(ticks):
        a,b=fine_shift(a,b,base,sine,1)
        a,b=fine_shift(a,b,base,sine,-1)
    time=2*h*ticks
    exact=[envelope(y-mean_speed*time)/sqrt(d) for y,d in zip(labels,jac)]
    norm=sum(abs(x)**2+abs(y)**2 for x,y in zip(a,b))/total
    error=sqrt(sum(abs(x-y)**2+abs(z)**2 for x,y,z in zip(a,exact,b))/total)
    assert abs(norm-1)<1e-12
    return error


def main():
    for u in (0,1/7,.2):
        N,A=clock(u),scale(u)
        for m0 in (.2,.6):
            m=m0*N
            w=width(u)*sqrt(tan(m)/m)
            assert w<1
            k=.0008
            observed=acos(cos(m)*(1-2*w*w*sin(k/2)**2))
            expected=N*sqrt(m0*m0+(W0*k/A)**2)
            assert abs(observed-expected)<1e-12
    assert abs(clock(1/7)-.75)<1e-14 and abs(scale(1/7)-64/49)<1e-14
    errors=[run(n) for n in (128,256,512,1024)]
    print("Fixed-time packet errors:",errors)
    assert all(1.75<a/b<2.25 for a,b in zip(errors,errors[1:]))
    assert errors[-1]<.04


if __name__=="__main__":
    main()
pulse_order.py
"""Order two finite-depth control pulses on the free six-stage walk.

At fixed x momentum and zero z momentum, the two middle y shifts combine
into a single coarse-cell shift. Spin and the added two-state control are
both retained. The localized packet stays away from the periodic seam.
"""
from cmath import exp
from math import acos, ceil, cos, pi, sin, sqrt

SIZE = 128
POSITIONS = tuple(range(-SIZE // 2, SIZE // 2))
UNIFORM = (1.0,) * SIZE
SLOPE = POSITIONS


def spin_x(spin, angle):
    co, si = cos(angle), -1j * sin(angle)
    return [(co * up + si * down, si * up + co * down) for up, down in spin]


def walk(spin, kx, direction):
    """Apply W = exp(-ikx X/2) shift_y exp(-ikx X/2) or its adjoint."""
    tilted = spin_x(spin, direction * kx / 2)
    result = []
    for y in range(SIZE):
        a, b = tilted[(y - direction) % SIZE]
        c, d = tilted[(y + direction) % SIZE]
        result.append(((a - 1j * b + c + 1j * d) / 2,
                       (1j * a + b - 1j * c + d) / 2))
    return spin_x(result, direction * kx / 2)


def combine(a, left, b, right):
    return [(a * u + b * v, a * w + b * z)
            for (u, w), (v, z) in zip(left, right)]


def mask(spin, profile):
    return [(m * a, m * b) for m, (a, b) in zip(profile, spin)]


def energy(spin, kx):
    return combine(0.5j, walk(spin, kx, 1), -0.5j, walk(spin, kx, -1))


def weighted(spin, kx, profile):
    return combine(0.5, mask(energy(spin, kx), profile),
                   0.5, energy(mask(spin, profile), kx))


def stencil_squared(spin, kx):
    """H squared from the independently known cosine-product trace of W."""
    t = cos(kx) ** 2 / 4
    return [tuple((1 - 2*t)*v - t*(spin[(i-2) % SIZE][j] + spin[(i+2) % SIZE][j])
                  for j, v in enumerate(pair)) for i, pair in enumerate(spin)]


def distance(a, b):
    return max(abs(u-v) for pair, other in zip(a, b) for u, v in zip(pair, other))


def check_finite_profile():
    spin = [(exp(0.017j*i*i)/12, exp(-0.027j*(i+3)**2)/14) for i in POSITIONS]
    profile = [sin(6*pi*i/SIZE) + 0.37*cos(10*pi*i/SIZE) for i in POSITIONS]
    for kx in (0.0, pi/4, 1.138):
        assert distance(walk(walk(spin, kx, 1), kx, -1), spin) < 1e-14
        direct = combine(1j, energy(weighted(spin, kx, profile), kx),
                         -1j, weighted(energy(spin, kx), kx, profile))
        reference = combine(0.5j, stencil_squared(mask(spin, profile), kx),
                            -0.5j, mask(stencil_squared(spin, kx), profile))
        assert distance(direct, reference) < 1e-13


# (controlled copy, forward or inverse native walk, pulse angle multiplier)
LAYERS = ((1, 1, -1), (0, -1, -1), (1, -1, 1), (0, 1, 1))


def pulse(copies, kx, profile, theta, inverse=False):
    """Conjugate local copy rotations with a controlled W or inverse W."""
    for label, direction, weight in (reversed(LAYERS) if inverse else LAYERS):
        before = list(copies)
        before[label] = walk(before[label], kx, -direction)
        after = [[], []]
        for (up, down), (u, d), f in zip(before[0], before[1], profile):
            angle = theta * weight * f * (-1 if inverse else 1) / 4
            c, s = cos(angle), -1j * sin(angle)
            after[0].append((c * up + s * u, c * down + s * d))
            after[1].append((s * up + c * u, s * down + c * d))
        after[label] = walk(after[label], kx, direction)
        copies = after
    return copies


def packet(carrier):
    envelope = [1 + cos(pi*y/9) if abs(y) <= 8 else 0 for y in POSITIONS]
    norm = sqrt(sum(a*a for a in envelope))
    wave = [a * exp(1j*carrier*y)/norm for a, y in zip(envelope, POSITIONS)]
    # An arbitrary coherent spin. Either initial control sector has the same bracket.
    spin = [(a/sqrt(2), 1j*a/sqrt(2)) for a in wave]
    return [spin, [(0, 0)] * SIZE], wave


def center(copies):
    probs = [sum(abs(a)**2 + abs(b)**2 for a, b in pair)
             for pair in zip(*copies)]
    assert abs(sum(probs) - 1) < 3e-13
    return sum(y*p for y, p in zip(POSITIONS, probs))


def closed_sequence(start, kx, theta):
    state = pulse(start, kx, UNIFORM, theta, inverse=True)
    state = pulse(state, kx, SLOPE, theta, inverse=True)
    state = pulse(state, kx, UNIFORM, theta)
    return pulse(state, kx, SLOPE, theta)


def loop_displacement(start, kx, theta):
    return center(closed_sequence(start, kx, theta)) - center(start)


def echo_readouts():
    print("kx/pi  ky/pi  analytic     pulse .04    pulse .02    pulse .01")
    for kx, carrier in ((0, 0), (pi/4, 0), (pi/2, 0), (0, pi/2)):
        start, wave = packet(carrier)
        coherence = sum((v.conjugate()*wave[(i+2) % SIZE]).real
                        for i, v in enumerate(wave))
        predicted = cos(kx)**2 * coherence
        measured = []
        for t in (0.04, 0.02, 0.01):
            # Average opposite signs to remove the odd powers of pulse amplitude.
            measured.append((loop_displacement(start, kx, t)
                             + loop_displacement(start, kx, -t)) / (2*t*t))
        print(f"{kx/pi:.2f}   {carrier/pi:.2f}   {predicted: .8f}  "
              + "  ".join(f"{n: .8f}" for n in measured))
        assert abs(measured[-1]-predicted) < 0.0007
        assert abs(measured[-1]-predicted) <= 0.32*abs(measured[-2]-predicted) + 1e-9


def finite_experiment():
    # The sign-paired loops use the actual gates, without extrapolating in angle.
    outcomes = []
    for kx in (0, pi/4, pi/2):
        state, _ = packet(0)
        for _ in range(12):
            state = closed_sequence(state, kx, 0.2)
            state = closed_sequence(state, kx, -0.2)
        mean = center(state)
        probability = [sum(abs(a)**2 + abs(b)**2 for a, b in pair)
                       for pair in zip(*state)]
        variance = sum(p*(y-mean)**2 for y, p in zip(POSITIONS, probability))
        seam_mass = sum(p for y, p in zip(POSITIONS, probability) if abs(y) >= 55)
        assert seam_mass < 1e-14
        print(f"Finite sequence kx/pi={kx/pi:.2f}: mean {mean:.9f}, "
              f"variance {variance:.8f}, outer mass {seam_mass:.2e}")
        outcomes.append((mean, variance))
    (a, v), (b, w), (c, _) = outcomes
    assert a > b > c and a - b > 0.1
    trials = ceil(19*(v+w)/(a-b)**2)
    print(f"Sufficient independent preparations per setting for a 95% "
          f"one-sided sign bound: {trials}")


def clock_phase():
    # Separate axial check for the tilted massless gates used in the shell model.
    w = 4/5
    k = pi/2
    phase = acos(1 - w*w*(1-cos(k)))
    velocity = w*w*sin(k)/sin(phase)
    step = 1e-5
    phase_at = lambda p: acos(1 - w*w*(1-cos(p)))
    direct = (phase_at(k+step)**2 - phase_at(k-step)**2)/(4*step)
    assert abs(phase*velocity-direct) < 1e-10
    print(f"Tilted axial clock: phase times velocity {direct:.8f}, "
          f"continuum {w*w*k:.8f}, fraction {direct/(w*w*k):.8f}")


if __name__ == "__main__":
    check_finite_profile()
    echo_readouts()
    finite_experiment()
    clock_phase()
packet_3d.py
"""Weak displacement of a compact 3D preparation under the six-stage walk.

Coordinates in the sparse dictionary are fine half-cells. Readouts use coarse
cells, and all dictionaries are on the infinite lattice (no numerical seam).
Run with Python 3, using only the standard library.
"""
from cmath import exp
from itertools import product
from math import cos, isclose, pi, sqrt

STAGES = (0, 1, 2, 2, 1, 0)
OFFSETS = (-2, -1, 0, 1, 2)
WEIGHTS = (1, 2, 3, 2, 1)
SPIN = (1 / sqrt(5), 2j / sqrt(5))


def scaled_sum(terms):
    out = {}
    for factor, state in terms:
        for point, (up, down) in state.items():
            a, b = out.get(point, (0j, 0j))
            out[point] = (a + factor * up, b + factor * down)
    return out


def half_shift(state, axis, direction):
    """The two Pauli projectors move one fine site in opposite directions."""
    out = {}
    for point, (a, b) in state.items():
        sa, sb = ((b, a), (-1j*b, 1j*a), (a, -b))[axis]
        for s in (-1, 1):
            dest = list(point)
            dest[axis] += s * direction
            dest = tuple(dest)
            u, v = out.get(dest, (0j, 0j))
            out[dest] = (u + (a + s*sa)/2, v + (b + s*sb)/2)
    return out


def walk(state, direction=1):
    for axis in (STAGES if direction == 1 else reversed(STAGES)):
        state = half_shift(state, axis, direction)
    return state


def hamiltonian(state):
    return scaled_sum(((0.5j, walk(state)), (-0.5j, walk(state, -1))))


def position(state, axis=1):
    return {p: (p[axis]*a/2, p[axis]*b/2) for p, (a, b) in state.items()}


def inner(left, right):
    value = 0j
    for p, (a, b) in left.items():
        u, v = right.get(p, (0j, 0j))
        value += a.conjugate()*u + b.conjugate()*v
    return value


def distance(left, right):
    diff = scaled_sum(((1, left), (-1, right)))
    return sqrt(inner(diff, diff).real)


def packet(kx, spin=SPIN):
    norm = sum(w*w for w in WEIGHTS)**1.5
    amplitudes = dict(zip(OFFSETS, WEIGHTS))
    state = {}
    for x, y, z in product(OFFSETS, repeat=3):
        value = amplitudes[x]*amplitudes[y]*amplitudes[z]*exp(1j*kx*x)/norm
        state[2*x, 2*y, 2*z] = tuple(value*s for s in spin)
    return state


def bracket(state):
    # Explicitly order H and H[Y]={Y,H}/2, retaining the two spin components.
    hs = hamiltonian(state)
    hys = hamiltonian(position(state))
    hhs = hamiltonian(hs)
    weighted = scaled_sum(((0.5, position(hs)), (0.5, hys)))
    weighted_after_h = scaled_sum(((0.5, position(hhs)),
                                    (0.5, hamiltonian(position(hs)))))
    ordered = scaled_sum(((1j, hamiltonian(weighted)), (-1j, weighted_after_h)))
    reduced = scaled_sum(((0.5j, hamiltonian(hys)), (-0.5j, position(hhs))))
    assert distance(ordered, reduced) < 1e-12
    return ordered


def checked_shift(kx, spin=SPIN):
    psi = packet(kx, spin)
    assert isclose(inner(psi, psi).real, 1, abs_tol=1e-14)
    for axis in range(3):
        moment = position(psi, axis)
        assert abs(inner(psi, moment)) < 1e-14
        assert isclose(inner(moment, moment).real, 16/19, abs_tol=1e-14)
    stepped = walk(psi)
    assert all(all(c % 2 == 0 and abs(c) <= 6 for c in point) for point in stepped)
    assert abs(inner(stepped, stepped).real - 1) < 1e-13
    assert distance(psi, walk(stepped, -1)) < 1e-12
    bpsi = bracket(psi)
    assert all(all(c % 2 == 0 and abs(c) <= 8 for c in point) for point in bpsi)
    measured = 2*inner(position(psi), bpsi).imag
    # Independently difference the centroids of normalized tangent states.
    # Their derivatives at zero coincide with those of exp(-i t B) psi.
    step = 1e-5
    centroids = []
    for sign in (-1, 1):
        tilted = scaled_sum(((1, psi), (-1j*sign*step, bpsi)))
        centroids.append(inner(tilted, position(tilted)).real / inner(tilted, tilted).real)
    assert abs((centroids[1] - centroids[0])/(2*step) - measured) < 1e-9
    coherence = sum(a*b for a, b in zip(WEIGHTS, WEIGHTS[2:])) / sum(w*w for w in WEIGHTS)
    predicted = coherence*(1 + coherence*cos(2*kx))*(1 + coherence)/4
    assert abs(measured - predicted) < 1e-12
    return measured, predicted


if __name__ == '__main__':
    print(f'125 coarse sites occupied; position RMS on each axis = {sqrt(16/19):.9f} coarse cells')
    print('Kx      direct six-shift bracket     coherence prediction')
    for label, carrier in (('0', 0), ('pi/4', pi/4), ('pi/2', pi/2)):
        measured, predicted = checked_shift(carrier)
        print(f'{label:4s}    {measured: .9f}                 {predicted: .9f}')
    assert abs(checked_shift(pi/2, (0, 1))[0] - checked_shift(pi/2, (1, 0))[0]) < 1e-12
material_bracket.py
"""Clock-rate commutator and a covariant continuum material. Standard library only."""
from cmath import exp
from math import acos, cos, isclose, pi, prod, sin, sqrt


def dot(a, b):
    return sum(x*y for x, y in zip(a, b))


def phase(k):
    return acos(prod(cos(a) for a in k))


def band_velocity(k):
    omega = phase(k)
    return [sin(k[i])*prod(cos(k[j]) for j in range(3) if j != i)/sin(omega)
            for i in range(3)]


def band_checks():
    y = pi/4
    for q in (pi/4, .01, .0001):
        a, b = (pi/2,y,0), (pi/2,y+q,0)
        # Both energies are exactly pi/2 analytically; spinors are (1,exp(i*y))/sqrt(2).
        assert isclose(phase(a),phase(b),abs_tol=1e-14)
        overlap = (1+exp(-1j*(y+q))*exp(1j*y))/2
        translation = 1j*q*(y+q/2)*overlap
        assert isclose(abs(translation),q*(y+q/2)*cos(q/2))
        print(f'Q={q:.6f}: equal-energy clock commutator 0; '
              f'translation magnitude {abs(translation):.9f}, per Q {abs(translation)/q:.9f}')
    k = (pi/4,pi/4,0)
    assert isclose(phase(k)*band_velocity(k)[0]/k[0],4/(3*sqrt(3)))
    for scale in (.08,.04,.02):
        x,y,z = [scale*t for t in (1.,.7,-.4)]
        exact = phase((x,y,z))*band_velocity((x,y,z))[0]
        cubic = x*(1-(y*y+z*z)/3)
        assert abs(exact-cubic) < .1*scale**5


def solve3(matrix, rhs):
    a = [list(row)+[v] for row,v in zip(matrix,rhs)]
    for i in range(3):
        pivot = max(range(i,3), key=lambda j: abs(a[j][i]))
        a[i],a[pivot] = a[pivot],a[i]
        divisor = a[i][i]
        if abs(divisor) < 1e-12:
            raise ValueError('singular material gradients')
        a[i] = [v/divisor for v in a[i]]
        for j in range(3):
            if j != i:
                factor = a[j][i]
                a[j] = [u-factor*v for u,v in zip(a[j],a[i])]
    return [row[-1] for row in a]


def lagrangian(state):
    # q are the three scalar material labels and the ray phase theta.
    # First four entries are time derivatives, then four rows of spatial derivatives.
    v = state[:4]
    j = [state[4+3*a:7+3*a] for a in range(3)]
    p = state[13:]
    drift = solve3(j,[-x for x in v[:3]])
    gamma = 1/sqrt(1-dot(drift,drift))
    frequency = gamma*(v[3]+dot(drift,p))
    k = [dot(row,p)-v[a]*v[3] for a,row in enumerate(j)]
    strain_trace = sum(dot(row,row)-v[a]**2 for a,row in enumerate(j))
    rho = (strain_trace-1)/2
    y = frequency+phase(k)
    return -rho+y*y  # g=1/2


def shifted(state, increments):
    trial = list(state)
    for i, size in increments:
        trial[i] += size
    return lagrangian(trial)


def first(state, i, step=3e-5):
    def f(m):
        return shifted(state,[(i,m*step)])
    return (f(-2)-8*f(-1)+8*f(1)-f(2))/(12*step)


def velocity_hessian(state, step):
    result = []
    for i in range(4):
        row = []
        for j in range(4):
            mixed = sum(a*b*shifted(state,[(i,a*step),(j,b*step)])
                        for a in (-1,1) for b in (-1,1))
            row.append(mixed/(4*step*step))
        result.append(row)
    return result


def cholesky_diagonal(matrix):
    lower = [[0.]*4 for _ in range(4)]
    for i in range(4):
        for j in range(i+1):
            residual = matrix[i][j]-dot(lower[i][:j],lower[j][:j])
            if i==j:
                assert residual > 0
                lower[i][i] = sqrt(residual)
            else:
                lower[i][j] = residual/lower[j][j]
    return [lower[i][i] for i in range(4)]


def check_material(state):
    # Legendre identities h_pi = qdot; h_gradient = -L_gradient at fixed pi.
    derivatives = [first(state,i) for i in range(16)]
    momenta = derivatives[:4]
    energy_bracket = [-sum(state[a]*derivatives[4+3*a+i] for a in range(4))
                      for i in range(3)]
    shift_density = [sum(momenta[a]*state[4+3*a+i] for a in range(4))
                     for i in range(3)]
    error = max(abs(a-b) for a,b in zip(energy_bracket,shift_density))
    assert error < 1e-9
    return momenta, shift_density, error


def material_checks():
    rest = [0.,0.,0.,-pi/2-.1, 1.,0.,0., 0.,1.,0., 0.,0.,1., pi/2,pi/4,0.]
    mom, shift, _ = check_material(rest)
    n = .2
    assert isclose(-mom[3], n, abs_tol=1e-10)
    velocity = band_velocity(rest[13:])
    for i in range(3):
        total = n*(phase(rest[13:])+.5*n)*velocity[i]
        assert abs(-shift[i]-total)<1e-10
        assert abs(mom[i]-(n*rest[13+i]-total))<1e-10
    print('rest physical total momentum =',tuple(round(-p,9) for p in shift))

    tilted = [.04,-.08,.06,-1.34, 1.03,.04,-.02, .10,.95,.03, .02,-.04,1.02, 1.2,.3,-.4]
    mom, shift, error = check_material(tilted)
    chol = cholesky_diagonal(velocity_hessian(tilted,1e-4))
    refined = cholesky_diagonal(velocity_hessian(tilted,5e-5))
    assert max(abs(a-b) for a,b in zip(chol,refined)) < 2e-6
    print('tilted phase action density =',round(-mom[3],9))
    print('tilted shift-generator density =',tuple(round(p,9) for p in shift))
    print(f'local deformation bracket residual {error:.2g}')
    print('velocity Hessian Cholesky diagonal =',tuple(round(v,6) for v in chol))


if __name__ == '__main__':
    band_checks()
    material_checks()
cesium_band.py
"""Ground-band curvature for the cesium standing wave of Ben Dahan et al. (1996).

Run with python3 cesium_band.py. No dependencies or fitted parameters.
"""
from math import exp


def ground_energy(x, depth, cutoff):
    """E/E_R in the plane-wave basis exp[i k(x+2j)z], -cutoff <= j <= cutoff."""
    diagonal = [(x+2*j)**2 + depth/2 for j in range(-cutoff, cutoff+1)]
    coupling_sq = (depth/4)**2
    low = min(diagonal)-depth/2-1
    high = min(diagonal)
    for _ in range(64):
        mid = (low+high)/2
        # Cholesky pivots of H-mid*I are positive iff mid is below the ground state.
        pivot = diagonal[0]-mid
        for d in diagonal[1:]:
            if pivot <= 0.:
                break
            pivot = d-mid-coupling_sq/pivot
        if pivot > 0.:
            low = mid
        else:
            high = mid
    return (low+high)/2


def band_curvature(x, depth, cutoff, h):
    # Return m_Cs/m* = (1/2) d²(E/E_R)/d(q/k)².
    weights = (-1, 16, -30, 16, -1)
    return sum(w*ground_energy(x+(j-2)*h, depth, cutoff)
               for j,w in enumerate(weights))/(24*h*h)


def broadened_mass(centre, depth, cutoff, h, gaussian_step=.10):
    # The paper convolves mean velocity with a Gaussian in q. Differentiating
    # commutes with convolution, so average curvature before taking the inverse.
    tail = round(6/gaussian_step)
    nodes = [i*gaussian_step for i in range(-tail, tail+1)]
    weights = [exp(-z*z/2) for z in nodes]
    curvature = sum(w*band_curvature(centre+z/18, depth, cutoff, h)
                    for z,w in zip(nodes,weights))/sum(weights)
    return 1/curvature


def figure_readout():
    # Pixel rows in Fig. 4(b), PDF page 4, embedded 1284x804 Fig. 4 bitmap.
    # Tick centers for +2 and -2, measured downward from its top.
    plus_two, minus_two = 76.5, 599.
    pixels_per_mass = (minus_two-plus_two)/4
    zero = (plus_two+minus_two)/2
    print('Fig. 4(b) approximate graphic readings at U0/E_R = 5.7:')
    for label, centre, top, bottom in (('q=0',101.,62.,140.), ('q=k',584.5,532.,638.)):
        observed = (zero-centre)/pixels_per_mass
        half_bar = (bottom-top)/(2*pixels_per_mass)
        print(f'{label}: marker {observed:+.2f}, plotted vertical half-span {half_bar:.2f} m_Cs')


def main():
    figure_readout()
    depth = 5.7
    print('q/k   band mass/m_Cs   Gaussian-averaged response mass/m_Cs')
    for centre in (0., 1.):
        mass = 1/band_curvature(centre, depth, 7, .003)
        smooth = broadened_mass(centre, depth, 7, .003)
        assert abs(mass-1/band_curvature(centre,depth,9,.0015)) < 1e-6
        assert abs(smooth-broadened_mass(centre,depth,9,.0015,.05)) < 1e-6
        print(f'{centre:.0f}     {mass:+.6f}         {smooth:+.6f}')
    assert abs(band_curvature(0.,0.,4,.003)-1) < 1e-8


if __name__ == '__main__':
    main()
cell.py
"""Solve a sourced finite scalar lattice and measure the adiabatic loading of a clock."""
from fractions import Fraction as F
from itertools import product

SITES=tuple(product((-1,0,1), repeat=3))
INDEX={x:i for i,x in enumerate(SITES)}
CENTRE=INDEX[(0,0,0)]
N=len(SITES)
NEIGHBORS=[]
for x in SITES:
    row=[]
    for axis,sign in product(range(3),(-1,1)):
        y=list(x);y[axis]+=sign
        if tuple(y) in INDEX:row.append(INDEX[tuple(y)])
    NEIGHBORS.append(row)


def clock(x):return (1-x)/(1+x)


def solve(a,b):
    # Positive Dirichlet stiffness makes Gaussian elimination possible without row exchanges.
    m=[r.copy()+[v] for r,v in zip(a,b)]
    for i in range(len(b)):
        assert m[i][i]>0
        for j in range(i+1,len(b)):
            s=m[j][i]/m[i][i]
            for k in range(i,len(b)+1):m[j][k]-=s*m[i][k]
    result=[0.]*len(b)
    for i in reversed(range(len(b))):
        result[i]=(m[i][-1]-sum(m[i][j]*result[j] for j in range(i+1,len(b))))/m[i][i]
    return result


def equilibrium(mass,probe):
    mu=[mass if sum(t*t for t in x)==1 else 0 for x in SITES]
    mu[CENTRE]=probe
    u=[0.]*N
    for _ in range(10):
        lap=[6*x-sum(u[j] for j in row) for x,row in zip(u,NEIGHBORS)]
        grad=[z-2*m/(1+x)**2 for z,m,x in zip(lap,mu,u)]
        h=[[0.]*N for _ in u]
        for i in range(N):
            h[i][i]=6+4*mu[i]/(1+u[i])**3
            for j in NEIGHBORS[i]:h[i][j]=-1
        if max(map(abs,grad))<1e-14:break
        u=[x-d for x,d in zip(u,solve(h,grad))]
    else:raise ArithmeticError("Equilibrium did not converge")
    energy=sum(.5*x*z+m*clock(x) for x,z,m in zip(u,lap,mu))
    return u,energy,h


def main():
    s=F(1,7)
    mass=F(17,10)*s*(1+s)**2
    assert mass==F(544,1715) and clock(s)==F(3,4)
    state,base,h=equilibrium(float(mass),0)
    for pos,u in zip(SITES,state):
        predicted=(s,s,2*s/5,s/5)[sum(v*v for v in pos)]
        assert abs(u-float(predicted))<2e-15
    inv=solve(h,[int(i==CENTRE) for i in range(N)])[CENTRE]
    assert abs(inv-7/34)<1e-14
    eps=.0002
    small=equilibrium(float(mass),eps)[1]-base
    twice=equilibrium(float(mass),2*eps)[1]-base
    second=(twice-2*small)/eps**2
    predicted=-float(F(16807,34816))
    assert abs(second-predicted)<.0003
    assert abs((4*small-twice)/(2*eps)-.75)<2e-8
    test=.01
    loaded=equilibrium(float(mass),test)[1]-base
    vacuum=equilibrium(0.,test)[1]
    print("Central scalar",state[CENTRE],"weak-clock rate",clock(state[CENTRE]))
    print("Inverse central stiffness",inv,"relaxed curvature",predicted)
    print("Finite probe (gap 0.01 in spring units) loaded/empty frequency ratio",loaded/vacuum)


if __name__=="__main__":
    main()
shell.py
"""Spherical material shell benchmark. Run with python3 shell.py (standard library)."""
from decimal import Decimal as D, getcontext
from fractions import Fraction as F
from math import isclose, sqrt

getcontext().prec = 55
# Geometrized units G=c=1, R0=1. Energies have units of length.
MU = F(1, 4)
W = F(1, 12)
ETA = F(1, 3)


def number(f):
    return D(f.numerator)/D(f.denominator)


def proper_energy(area_ratio):
    return (3*area_ratio + 13*area_ratio**(-D(1)/3))/64


def static_action(q, psi, chi):
    radius = q*psi**2
    return 2*q*(psi-1)*(chi-1) - chi/psi*proper_energy(radius**2)


def static_adm(radius):
    energy = proper_energy(radius**2)
    return energy-energy**2/(2*radius)


def omitted_equation(r, a, d):
    """Covariant radial and Cartesian transverse components from the metric."""
    psi = 1+a/r
    dp, ddp = -a/r**2, 2*a/r**3
    lapse = (r+d)/(r+a)
    dn, ddn = (a-d)/(r+a)**2, -2*(a-d)/(r+a)**3
    ric_rad = -2*ddp/psi + 4*(dp/psi)**2
    ric_tan = -2*dp/(r*psi) - 2*(dp/psi)**2
    hess_rad = ddn - 2*dp*dn/psi
    hess_tan = dn/r + 2*dp*dn/psi
    return (psi**2*(lapse*ric_rad-hess_rad),
            psi**2*(lapse*ric_tan-hess_tan))


def check_radial_energy():
    radius = D(1)
    step = D('0.000001')
    e0 = proper_energy(radius**2)
    area_pressure = -(proper_energy(1+step)-proper_energy(1-step))/(2*step)
    assert abs(area_pressure/e0-number(W)) < D('1e-12')
    first = (static_adm(radius+step)-static_adm(radius-step))/(2*step)
    second = (static_adm(radius+step)-2*static_adm(radius)+static_adm(radius-step))/step**2
    exact = (1-MU)*(4*ETA*(1+W)-2*W)-MU*(1+2*W)**2
    assert exact == F(89,144)
    assert abs(first) < D('1e-12') and abs(second/e0-number(exact)) < D('1e-10')
    eta_crit = W*(3+8*W+8*W**2)/(2*(1+W))
    assert eta_crit == F(67,468)
    assert (1-MU)**2*exact == F(89,256)
    print(f'radial stiffness R^2 U"/E = {exact}, numerical {second/e0:.10f}')
    print(f'critical dP/dsigma = {eta_crit}; example {ETA}')


def check_junction():
    for radius in (.8, 1., 1.2):
        energy = float(proper_energy(D(str(radius))**2))
        for velocity in (0., .1, -.23):
            adm = energy*sqrt(1+velocity**2)-energy**2/(2*radius)
            left = sqrt(1+velocity**2)-sqrt(1-2*adm/radius+velocity**2)
            assert isclose(left, energy/radius)
    # Independent static extrinsic-curvature jump, P/sigma in G=c=1 units.
    mass = float(static_adm(D(1)))
    lapse = sqrt(1-2*mass)
    w_israel = ((1-mass)/lapse - 1)/(2*(1-lapse))
    assert isclose(w_israel, float(W))
    print(f'junction M/R = {mass:.8f}, interior clock rate {lapse:.8f}')


def check_statics():
    p = 1/(1-MU/2)
    h, q = 2-p, 1/p**2
    a = q*(p-1)
    assert a == F(7,64) and h/p == F(3,4)
    point = list(map(number,(q,p,h)))
    step = D('0.000001')
    for axis in range(3):
        above, below = list(point), list(point)
        above[axis] += step
        below[axis] -= step
        assert abs((static_action(*above)-static_action(*below))/(2*step)) < D('1e-10')
    assert abs(static_action(*point)+static_adm(D(1))) < D('1e-52')
    for r in (1., 2.3, 5.):
        for d in (-float(a), .15):
            radial, transverse = omitted_equation(r,float(a),d)
            residual = (float(a)+d)/r**3
            assert abs(radial+2*residual) < 1e-14
            assert abs(transverse-residual) < 1e-14
    print(f'isotropic radius q={q}, exterior parameter a={a}, p={p}, h={h}')


def causal_limit():
    lo, hi = 0., 1.
    for _ in range(70):
        w = (lo+hi)/2
        if 8*w**3+8*w*w+w-2 < 0:
            lo = w
        else:
            hi = w
    w = (lo+hi)/2
    mu = 4*w/(1+4*w)
    print(f'causal radial threshold w={w:.9f}, mu={mu:.9f}, '
          f'N={1-mu:.9f}, GM/(Rc^2)={mu*(1-mu/2):.9f}')


if __name__ == '__main__':
    check_statics()
    check_junction()
    check_radial_energy()
    causal_limit()
nested.py
"""Exact static scalar shell stations, their material pressure, and two annular clocks."""
from fractions import Fraction as F
from math import sqrt


def rods(u):
    return (1+u)**2


def lapse(u):
    return (1-u)/(1+u)


def radial_slope(offset, coefficient, r):
    return (1+offset-coefficient/r)/(1+offset+coefficient/r)


def shell_material(r,u,ai,ao):
    area_factor=rods(u)
    proper_radius=r*area_factor
    n=lapse(u)
    slope=-2*(ao*ao-ai*ai)/(r*r*n*area_factor)
    mu=(4*(ao-ai)+2*n*slope*r*(1+u))*area_factor/2
    pressure_ratio=-proper_radius*slope/(2*mu)
    return mu,proper_radius,pressure_ratio


def rest_energy(ratio,mu,w,eta):
    # A two-dimensional material with dp/dsigma=eta, in units c=1.
    return mu*((eta-w)*ratio+(1+w)*ratio**(-eta))/(1+eta)


def finite_hessian(f,x,h=1e-4):
    def offset(changes):
        v=x.copy()
        for i,z in changes:v[i]+=z
        return f(v)
    n=len(x);m=[[0.]*n for _ in x];centre=f(x)
    for i in range(n):
        pos,neg=offset([(i,h)]),offset([(i,-h)])
        assert abs((pos-neg)/(2*h))<2e-6
        m[i][i]=(pos+neg-2*centre)/h**2
        for j in range(i):
            m[i][j]=m[j][i]=sum(a*b*offset([(i,a*h),(j,b*h)]) for a in (-1,1) for b in (-1,1))/(4*h*h)
    return m


def pivots(m):
    a=[r.copy() for r in m];out=[]
    for i,row in enumerate(a):
        v=row[i];out.append(v)
        for j in range(i+1,len(a)):
            factor=a[j][i]/v
            for k in range(i+1,len(a)):a[j][k]-=factor*row[k]
    return out


def pair_transfer(mu1, mu2, radius1, radius2):
    """GR branch in areal coordinates, with positive inner and outer slopes."""
    def outside(mass, proper_mass, radius):
        inside_slope = sqrt(1 - 2*mass/radius)
        outside_slope = inside_slope - proper_mass/radius
        if outside_slope <= 0:
            raise ValueError("Both shells must remain on the ordinary static branch")
        return mass + proper_mass*(inside_slope + outside_slope)/2, inside_slope, outside_slope

    inner_mass, _, inner_slope = outside(0, mu1, radius1)
    final_mass, gap_slope, outer_slope = outside(inner_mass, mu2, radius2)
    inner_clock = inner_slope * outer_slope/gap_slope
    return final_mass, inner_clock, outer_slope


def check_pair_transfer():
    # The four one-sided slopes are inferred from the areal mass and junction.
    r1, r2 = F(8), F(224, 15)
    mu1, mu2 = F(2), F(28, 15)
    b1, a2, b2 = F(3, 4), F(7, 8), F(3, 4)
    m1, m2 = r1*(1-b1*b1)/2, r2*(1-b2*b2)/2
    assert (m1, m2) == (F(7,4), F(49,15))
    assert 1-2*m1/r2 == a2*a2 and (r1*(1-b1), r2*(a2-b2)) == (mu1, mu2)
    n1, n2 = b1*b2/a2, b2
    assert (n1, n2) == (F(9,14), F(3,4))
    point = tuple(map(float, (mu1, mu2, r1, r2)))
    totals = pair_transfer(*point)
    assert max(abs(x-y) for x,y in zip(totals, (m2, n1, n2))) < 1e-14

    # Numerically vary each physical shell input, keeping the other three fixed.
    def perturb(index, step):
        args = list(point)
        args[index] += step
        return pair_transfer(*args)

    h = 1e-5
    slopes = []
    for i in range(4):
        plus, minus = perturb(i, h), perturb(i, -h)
        slopes.append(tuple((p-m)/(2*h) for p, m in zip(plus, minus)))

    # Israel pressure: 8*pi*R*p = (1/b + b - 1/a - a)/2.
    work1 = n1 * (1/b1 + b1 - 2)/2
    work2 = n2 * (1/b2 + b2 - 1/a2 - a2)/2
    assert (work1,work2) == (F(3,112), F(11,448))
    assert max(abs(row[0]-expected) for row,expected in
               zip(slopes, (n1,n2,work1,work2))) < 2e-9
    cross = -b1/(r2*a2)
    assert cross == F(-45,784)
    assert max(abs(slopes[1][1]-cross), abs(slopes[0][2]-cross)) < 2e-9
    print("GR shell transfer: exterior mass", m2, "inner and outer clocks", n1, n2)
    print("ADM mass derivatives by input (mu1, mu2, R1, R2):", [row[0] for row in slopes])
    print("Cross responses dN1/dmu2 and dN2/dmu1:", slopes[1][1], slopes[0][2],
          "exact", cross)


def main():
    # c=G=1. Inside a shell ai, outside ao are the 1/r coefficients of u.
    m,R,w=shell_material(F(49,16),F(1,7),F(0),F(7,16))
    assert (m,R,w)==(1,4,F(1,12))
    assert m*lapse(F(1,7))+2*F(7,16)*F(1,7)==F(7,8)
    d,a=F(1,10),F(1,4)
    radii=(F(4,5),F(3));u=tuple(d+a/r for r in radii)
    jumps=(a,F(11,20)-a)
    mats=[shell_material(radii[0],u[0],F(0),a),
          shell_material(radii[1],u[1],a,F(11,20))]
    assert [t[0] for t in mats]==[F(1243,1600),F(781,1200)]
    assert [t[2] for t in mats]==[F(125,517),F(96,539)]
    e=sum(mat[0]*lapse(v)+2*j*v for mat,v,j in zip(mats,u,jumps))
    assert e==F(209,192) and 2*sum(jumps)-e==F(11,960)
    def energy(x):
        r1,r2,z1,z2=x
        field=2*((z1-z2)**2/(1/r1-1/r2)+r2*z2*z2)
        for r,z,(mass,rad,w) in zip((r1,r2),(z1,z2),mats):
            ratio=(r*rods(z)/float(rad))**2
            field+=lapse(z)*rest_energy(ratio,float(mass),float(w),.8)
        return field
    x=list(map(float,(*radii,*u)))
    assert abs(energy(x)-float(e))<1e-12
    stiffness=pivots(finite_hessian(energy,x))
    ratio=(lapse(d+a/2)/lapse(d+a))/(radial_slope(d,a,F(2))/radial_slope(d,a,F(1)))
    assert ratio==F(527,507)
    for r in (1.,1.4,2.):
        # Independent local, measured derivative of areal radius per rod length.
        h=1e-5
        observed=((r+h)*rods(float(d+a/(r+h)))-(r-h)*rods(float(d+a/(r-h))))/(2*h*rods(float(d+a/r)))
        assert abs(observed-float(radial_slope(d,a,r)))<2e-10
    print("Single shell: proper mass 1, areal radius 4, pressure/energy 1/12, total and exterior mass 7/8.")
    print("Two shells: total",e,"exterior",2*sum(jumps),"clock/rod ratio",ratio)
    print("Reduced spherical static-energy pivots at dp/dsigma=0.8:",stiffness)
    assert min(stiffness)>0
    # Stable evaluation of the very small departure from unity at laboratory scale.
    gc=6.67430e-11/299792458**2
    outer=gc*1000/(2*1.0)
    z1,z2=gc*10/(2*.2),gc*10/(2*.4)
    gap=2*outer*(z1-z2)/((1+outer-z2)*(1-outer-z1))
    print("Illustrative laboratory shell shift",2*outer,"nested ratio minus unity",gap)
    assert 6.8e-51<gap<7.0e-51
    check_pair_transfer()


if __name__=="__main__":
    main()
breathing.py
"""Weak-field radiation from a spherical elastic surface; standard library."""
from math import cos, isclose, pi, sin, sqrt


def form(x):
    if abs(x) < .01:
        return 4/3-x*x/5+x**4/105
    return sin(x)/x + (sin(x)/x-cos(x))/x**2


def integrate(function, panels=160):
    """Mean over direction cosine mu in [-1,1], composite Simpson rule."""
    step = 2/panels
    total = function(-1)+function(1)
    for i in range(1,panels):
        total += (4 if i%2 else 2)*function(-1+i*step)
    return total*step/6


def retarded_source(x, amplitude, phase):
    """In M=R=c=1 units return excess above rest mass.
    Use the source through first order in amplitude, evaluated on the moving
    shell. Opposite-amplitude differencing extracts its linear response.
    """
    def direction(mu):
        # theta = Omega*t_emit is implicit even at fixed observer time.
        theta = phase+mu*x
        for _ in range(10):
            theta = phase+mu*x*(1+amplitude*cos(theta))
        speed = -amplitude*x*sin(theta)
        stress = -amplitude*x*x*cos(theta)
        # Subtract the static integrand before summation for numerical precision.
        return (stress+mu*speed)/(1-mu*speed)
    return integrate(direction)


def response(x, phase):
    amplitude = 1e-5
    return (retarded_source(x,amplitude,phase)-retarded_source(x,-amplitude,phase))/(2*amplitude)


def detector_check():
    """Ideal equal-arm, long-wavelength response at the GW170817 merger epoch.

    Arm directions are from LALSuite 7.26, lal/LALDetectors.h (Earth-fixed).
    GWOSC gives 2017-08-17 12:41:04.43 UTC. The optical position is Coulter et al.
    """
    from datetime import datetime, timezone
    from math import radians
    arms = {
        'H1': ((-.22389266154,.79983062746,.55690487831),
               (-.91397818574,.02609403989,-.40492342125)),
        'L1': ((-.95457412153,-.14158077340,-.26218911324),
               (.29774156894,-.48791033647,-.82054461286)),
        'V1': ((-.70045821479,.20848948619,.68256166277),
               (-.05379255368,-.96908180549,.24080451708)),
    }
    def dot(u,v):
        return sum(a*b for a,b in zip(u,v))

    def mix(a,b,x,y):
        return tuple(x*p+y*q for p,q in zip(a,b))

    def patterns(arm_a,arm_b,n,p,q):
        # D=(arm_a arm_a - arm_b arm_b)/2; columns correspond to
        # projections onto an orthonormal triad of sky and two tangent axes.
        an,ap,aq = (dot(arm_a,v) for v in (n,p,q))
        bn,bp,bq = (dot(arm_b,v) for v in (n,p,q))
        longitudinal = (an*an-bn*bn)/2
        breathing = (ap*ap+aq*aq-bp*bp-bq*bq)/2
        plus = (ap*ap-aq*aq-bp*bp+bq*bq)/2
        cross = ap*aq-bp*bq
        assert abs(breathing+longitudinal) < 3e-10
        return breathing, sqrt(plus*plus+cross*cross)

    epoch = datetime(2017,8,17,12,41,4,430000,tzinfo=timezone.utc)
    jd_offset = epoch.timestamp()/86400 + (2440587.5-2451545.)
    centuries = jd_offset/36525
    # Mean Greenwich sidereal angle, using UTC as the UT1 approximation.
    gmst = radians((280.46061837+360.98564736629*jd_offset
                    +.000387933*centuries**2-centuries**3/38710000)%360)
    ra = radians(15*(13+9/60+48.085/3600))
    dec = -radians(23+22/60+53.343/3600)
    angle = ra-gmst
    n = (cos(dec)*cos(angle),cos(dec)*sin(angle),sin(dec))
    p = (-sin(angle),cos(angle),0)
    q = (-sin(dec)*cos(angle),-sin(dec)*sin(angle),cos(dec))
    for label,(a,b) in arms.items():
        breathing, tensor = patterns(a,b,n,p,q)
        rotated = patterns(a,b,n,mix(p,q,cos(.73),sin(.73)),mix(p,q,-sin(.73),cos(.73)))
        assert all(abs(x-y)<1e-12 for x,y in zip((breathing,tensor),rotated))
        print(f'{label}: D:nn={-breathing:+.6f}, F_b={breathing:+.6f}, '
              f'tensor quadrature norm={tensor:.6f}')
    # Unit arms at arbitrary non-right angle in a controlled laboratory setting.
    n,p,q = (1,0,0),(0,1,0),(0,0,1)
    for angle in (.25,pi/4,pi/2):
        a,b = (1,0,0),(cos(angle),sin(angle),0)
        assert abs(patterns(a,b,n,p,q)[0]+sin(angle)**2/2)<1e-14


def main():
    detector_check()
    for eta in (.0025,.0625,.25,1/3,1):
        x = 2*sqrt(eta)
        h = form(x)
        angular = integrate(lambda mu: (3-mu*mu)*cos(x*mu)/2)
        assert abs(angular-h) < 1e-8
        measured = -response(x,0)/x**2
        assert abs(measured-h) < 1e-8
        assert abs(response(x,pi/2)) < 1e-12
        # Independently integrate the far energy flux over a cycle by
        # differentiating the retarded waveform in observer phase.
        dphase, phases = 1e-4, 20
        flux = 0.
        for j in range(phases):
            phase = 2*pi*j/phases
            derivative = (response(x,phase+dphase)-response(x,phase-dphase))/(2*dphase)
            flux += derivative*derivative/phases
        assert isclose(flux/x**4,h*h/2,rel_tol=1e-7)
        print(f'eta={eta:.6f}  x={x:.6f}  H={h:.9f}  retarded H={measured:.9f}  '
              f'power coefficient={flux/x**4:.9f}')
    # Local surface balance from pressure: M xi_ddot = 8 pi R deltaP.
    m, c, r, a, eta = 4., 7., 2., .001, .3
    sigma = m*c*c/(4*pi*r*r)
    delta_p = -2*eta*sigma*a/r
    omega = 2*sqrt(eta)*c/r
    assert isclose(8*pi*r*delta_p/m, -omega**2*a)
    assert isclose(8*pi*r*r*delta_p, -m*r*omega**2*a)
    assert isclose(form(.00001),4/3,rel_tol=1e-10)


if __name__ == '__main__':
    main()
rod.py
"""Calibrate a composite rod, breakup threshold and center-of-mass motion.

Run with Python 3.9+ and the standard library. The chain is analytic.
The unconfined cubic calculation integrates infinite-lattice Fourier modes.
"""
from fractions import Fraction
from math import asinh, cos, isclose, log, pi, sqrt


def check_chain():
    # Dimensionless g=|U|/(4J). Units are a=J0=1 before rescaling.
    lapse = Fraction(4,5)
    scale = Fraction(16,9)
    j0, j1 = 1, 3*lapse/8
    u0, u1 = 3, 2*lapse
    checks = []
    for j,u,w in ((j0,u0,Fraction(5,4)),(j1,u1,Fraction(5,3))):
        g = Fraction(u)/(4*j)
        assert w*w == 1+g*g
        delta = 4*j*(w-1)
        radius2 = 1/(2*g*g)
        curvature = j/w
        checks.append((delta,radius2,curvature,curvature/(delta*radius2)))
        q = w-g  # amplitude ratio per site
        at = lambda n: float(q)**abs(n)
        energy = -4*j*w
        # Independently apply the original relative-coordinate hopping.
        for n in range(-48,49):
            image = -2*j*(at(n-1)+at(n+1)) - (u*at(n) if n==0 else 0)
            assert isclose(image,energy*at(n),abs_tol=1e-14)
        samples = [n for n in range(-48,49)]
        norm = sum(at(n)**2 for n in samples)
        observed = sum(n*n*at(n)**2 for n in samples)/norm
        assert isclose(observed,radius2,abs_tol=1e-13)
        print(f"chain g={g}, P(1)/P(0)={q*q}, C={checks[-1][-1]}")
    old,new = checks
    assert new[0]/old[0] == lapse
    assert new[1]/old[1] == 1/scale**2
    assert new[2]/old[2]/(lapse/scale**2) == Fraction(8,9)
    assert (old[3],new[3]) == (Fraction(9,10),Fraction(4,5))
    assert isclose(asinh(0.75)/asinh(4/3),log(2)/log(3))
    print("RMS and clock calibrations pass; scaled band curvature = 8/9.")


def transverse(grid):
    c = [cos(2*pi*i/grid) for i in range(grid)]
    return [12-4*(a+b) for a in c for b in c]


def cubic(delta, grid):
    # Analytic inverse transform in x at fixed q_y,q_z:
    # f_n = r^|n|/sqrt(A²-16), A=12+delta-4*cos(q_y)-4*cos(q_z).
    t = transverse(grid)
    mean, norm, moment, neighbor = 0.0,0.0,0.0,0.0
    for v in t:
        a = v+delta
        root = sqrt(a*a-16)
        f0 = 1/root
        r = 4/(a+root)
        s = r*r
        mean += f0
        norm += f0*f0*(1+s)/(1-s)
        moment += 2*f0*f0*s*(1+s)/(1-s)**3
        neighbor += 2*f0*f0*r/(1-s)
    u=grid**2/mean
    return u,sqrt(moment/norm),neighbor/norm


def cubic_fourier(delta,grid):
    # Independent three-dimensional Fourier integrals. Differentiating the
    # momentum wavefunction yields the imaged second moment via Parseval.
    c = [cos(2*pi*i/grid) for i in range(grid)]
    transverse_values = transverse(grid)
    integrals = [0.0]*4
    for x in c:
        for v in transverse_values:
            f = 1/(delta+v-4*x)
            f2 = f*f
            integrals[0] += f
            integrals[1] += f2
            integrals[2] += 16*(1-x*x)*f2*f2
            integrals[3] += x*f2
    near,norm,moment,corr = integrals
    return grid**3/near,sqrt(moment/norm),corr/norm


def dispersion_check(delta, interaction, expected, grid=64):
    # Solve the bound-state energy anew with a small dimensionless COM wavevector.
    k = 0.01
    span = 4*cos(k/2)
    t = transverse(grid)
    low,high = delta-0.01,delta+0.01
    for _ in range(48):
        trial = (low+high)/2
        green = sum(1/sqrt((trial+v)**2-span*span) for v in t)/len(t)
        if green > 1/interaction:
            low = trial
        else:
            high = trial
    fitted = 2*(delta-(low+high)/2)/(k*k)
    assert isclose(fitted,expected,rel_tol=1e-5), (fitted,expected)


def main():
    check_chain()
    records=[]
    for delta in (0.5,2.0):
        values=cubic(delta,96)
        for check in (cubic(delta,64),cubic_fourier(delta,64)):
            assert all(isclose(a,b,abs_tol=5e-10) for a,b in zip(values,check))
        u,radius,curvature=values
        dispersion_check(delta,u,curvature)
        invariant = curvature/(delta*radius*radius)
        records.append((delta,radius,curvature,invariant))
        print(f"cubic delta={delta:g}, U/J={u:.8f}, Rx/a={radius:.8f}, "
              f"D/(J*a²)={curvature:.8f}, C={invariant:.8f}")
    old,new=records
    scale=old[1]/new[1]
    observed=old[0]/new[0]*new[2]/old[2]
    score=observed*scale**2
    assert isclose(score,new[3]/old[3],abs_tol=1e-12)
    print(f"calibrated cubic length factor={scale:.8f}; band curvature/prediction={score:.8f}")


if __name__ == "__main__":
    main()
pressure.py
"""Static reciprocal response of thin light sheets and cold matter."""
from fractions import Fraction as F


def stress(energy,xx,yy,xy=0):
    return ((energy,0,0,0),(0,xx,xy,0),(0,xy,yy,0),(0,0,0,0))


def residue(a,b):
    # Both indices raised in the (-+++) convention. Transfer is along z.
    metric=(-1,1,1,1)
    trace=lambda t:sum(metric[i]*t[i][i] for i in range(4))
    contraction=sum(metric[i]*metric[j]*a[i][j]*b[i][j] for i in range(4) for j in range(4))
    return 2*contraction-trace(a)*trace(b)


def stable_kernel(x,y,modes):
    return sum(a*b/stiffness for a,b,stiffness in zip(x,y,modes))


def main():
    dust=stress(1,0,0)
    light=stress(1,F(1,2),F(1,2))
    beamx,beamy=stress(1,1,0),stress(1,0,1)
    tilt=stress(1,F(9,25),F(16,25),F(12,25))
    assert tuple(residue(a,b) for a,b in ((dust,dust),(dust,light),(light,light)))==(1,2,3)
    assert residue(dust,dust)*residue(light,light)-residue(dust,light)**2==-1
    assert residue(beamx,beamx)==4 and residue(beamx,beamy)==2
    assert residue(beamx,tilt)==2+2*F(9,25)
    for t in (dust,light,tilt):assert all(x==0 for x in t[3])
    # Even extra independent attractive channels cannot lower 4 after a fit to 1,2.
    for y in (F(0),F(1),F(-2,3)):
        d=(F(1),0)
        l=(F(2),y)
        k=(F(1),F(5))
        assert stable_kernel(d,l,k)==2
        assert stable_kernel(l,l,k)-4==y*y/5
    print("Normalized dust/dust, dust/light sheet, and light sheet/light sheet:",1,2,3)
    print("After fitting the first two, stable unconstrained reciprocal scalar exchange predicts at least 4.")
    print("Balanced single-axis light sheets, parallel vs perpendicular:",4,2)


if __name__=="__main__":
    main()
constrained.py
"""Constrained static stress exchange. All checks use the Python standard library."""
from fractions import Fraction as F
from math import cos, isclose, pi, sin, sqrt


def add(a, b):
    return [x+y for x, y in zip(a,b)]


def inner(a, b):
    return sum(x*y for x,y in zip(a,b))


def gradient(phi):
    return [phi[(n+1)%len(phi)]-v for n,v in enumerate(phi)]


def divergence(links):
    return [v-links[n-1] for n,v in enumerate(links)]


def centre(data):
    mean = sum(data)/len(data)
    return [v-mean for v in data]


def constrained_flux(density):
    if sum(density) != 0:
        raise ValueError("Periodic Gauss law requires zero net charge")
    # Integrate E_n - E_(n-1) = density_n and minimize over uniform flux.
    links, current = [], 0
    for value in density:
        current += value
        links.append(current)
    return centre(links)


def poisson(density):
    # -D phi is the minimum flux with divergence equal to density.
    links = constrained_flux(density)
    phi, value = [], 0
    for e in links:
        phi.append(value)
        value -= e
    return centre(phi)


def minimum(s, t):
    source = add(s, t)
    phi = poisson(source)
    e = constrained_flux(t)
    grad = gradient(phi)
    assert divergence(e) == t
    assert [-v for v in divergence(grad)] == source
    scalar = inner(grad,grad)/2-inner(source,phi)
    electric = inner(e,e)/2
    return scalar, electric


def bilinear(a, b):
    whole = minimum(add(a[0],b[0]), add(a[1],b[1]))
    one, two = minimum(*a), minimum(*b)
    return tuple(h-x-y for h,x,y in zip(whole,one,two))


def checks():
    # An unnormalized periodic profile, per transverse cell area.
    f = list(map(F,(2,-1,0,3,-4,-1,2,-1)))
    zero = [F(0)]*len(f)
    gram = inner(f, poisson(f))
    modes = ((f,zero), (zero,f))
    for a in range(2):
        for b in range(2):
            scalar, electric = bilinear(modes[a],modes[b])
            assert -scalar/gram == 1
            assert -electric/gram == -int(a==b==1)
            assert -(scalar+electric)/gram == ((1,1),(1,0))[a][b]
    # Compute the four-dimensional contraction afresh for two generic sources.
    eta = (-1,1,1,1)
    for (s1,t1),(s2,t2) in (((F(1),F(2)),(F(3),F(-1))),
                              ((F(-2),F(1)),(F(0),F(3)))):
        a, b = (s1,t1/2,t1/2,0), (s2,t2/2,t2/2,0)
        residue = 2*inner(a,b)-inner(eta,a)*inner(eta,b)
        assert residue == s1*s2+s1*t2+t1*s2
    # Mixed source profiles, including a different lattice translation in each channel.
    shifted = f[2:]+f[:2]
    invf, invg = poisson(f), poisson(shifted)
    scalar, electric = bilinear((f,shifted),(shifted,f))
    assert scalar+electric == -inner(f,invg)-inner(f,invf)-inner(shifted,invg)
    # An arbitrary circulation (the unconstrained flux degree) raises its energy.
    flux = constrained_flux(f)
    extra = [v+F(2,3) for v in flux]
    assert divergence(extra) == f
    assert (inner(extra,extra)-inner(flux,flux))/2 == len(f)*F(2,9)
    # Independent exact inverse of the periodic Laplacian: distance kernel.
    n = len(f)
    kernel = [F(n*n-1,12*n) - F(i*(n-i),2*n) for i in range(n)]
    inverse = [sum(kernel[(i-j)%n]*v for j,v in enumerate(f)) for i in range(n)]
    assert inverse == poisson(f)
    print(f'finite periodic test: <f,L^+f>={gram}, normalized attractive matrix [[1,1],[1,0]]')
    # Three exact nonzero Fourier eigenvectors at distinct finite lattice momenta.
    for pattern, lam in (((1,0,-1,0),2), ((2,-1,-1),3), ((1,-1),4)):
        profile = list(map(F,pattern*4))
        zeros = [F(0)]*len(profile)
        predicted = inner(profile,profile)/lam
        assert inner(profile,poisson(profile)) == predicted
        assert bilinear((profile,zeros),(zeros,profile)) == (-predicted,0)
        assert bilinear((zeros,profile),(zeros,profile)) == (-predicted,predicted)
    print('Fourier lambda=2,3,4: exact matched mixed pole, exact cancellation of pressure-pressure')


def matter_checks():
    # Real free KG field in a flat periodic box, c=hbar=1 and unit amplitude.
    mass = 1.
    for k in (.5,.1,.02):
        w = sqrt(mass**2+k**2)
        samples = []
        dt = dz = 1e-5

        def stress(z, time):
            phase = k*z-w*time
            field = cos(phase)
            ft, fz = w*sin(phase), -k*sin(phase)
            s = (ft*ft+fz*fz+mass*mass*field*field)/2
            momentum = -ft*fz
            pxy = (ft*ft-fz*fz-mass*mass*field*field)/2
            return s, momentum, pxy+fz*fz, 2*pxy

        for j in range(64):
            z, time = j*2*pi/(64*k), .11
            s, mom, pz, t = stress(z,time)
            ahead, behind = stress(z,time+dt), stress(z,time-dt)
            right, left = stress(z+dz,time), stress(z-dz,time)
            deriv_t = [(a-b)/(2*dt) for a,b in zip(ahead,behind)]
            deriv_z = [(a-b)/(2*dz) for a,b in zip(right,left)]
            assert abs(deriv_t[0]+deriv_z[1]) < 2e-8
            assert abs(deriv_t[1]+deriv_z[2]) < 2e-8
            assert abs(deriv_t[3]+(w/k)*deriv_z[3]) < 2e-7
            assert abs(t+mass**2*cos(2*(k*z-w*time))) < 1e-12
            samples.append(t)
        assert abs(sum(samples)/len(samples)) < 1e-12
        print(f'KG k/m={k:.2f}: t is neutral, required |Jz/t|={w/k:.6f}')
    # A homogeneous oscillator keeps its energy while the integrated pressure changes sign.
    values = []
    for time in (0., pi/(4*mass), pi/(2*mass)):
        field, velocity = cos(mass*time), -mass*sin(mass*time)
        energy = (velocity**2+mass**2*field**2)/2
        transverse = velocity**2-mass**2*field**2
        assert isclose(energy,mass**2/2)
        values.append(round(transverse,12))
    assert values == [-1.,0.,1.]


if __name__ == '__main__':
    checks()
    matter_checks()
pressure_wave.py
"""Conserved-source exchange, freely falling tidal readout and a causal ring burst.

Run python3 pressure_wave.py. Units c=1, metric signature -+++. The reported
tidal tensor is divided by 8*pi*G and the metric perturbation by 16*pi*G.
"""
import math


ETA = (-1, 1, 1, 1)


def tensor(rho, mean, plus, cross, ratio):
    return [[rho, 0, 0, ratio*rho],
            [0, mean+plus, cross, 0],
            [0, cross, mean-plus, 0],
            [ratio*rho, 0, 0, ratio**2*rho]]


def trace_reverse(T):
    trace = sum(e*T[i][i] for i, e in enumerate(ETA))
    return [[ETA[i]*ETA[j]*T[i][j] - (ETA[i]*trace/2 if i == j else 0)
             for j in range(4)] for i in range(4)]


def electric(h, q):
    return [[q[0]**2*h[i][j] + q[i]*q[j]*h[0][0]
             - q[0]*q[i]*h[0][j] - q[0]*q[j]*h[i][0]
             for j in range(1, 4)] for i in range(1, 4)]


def angular(E, theta):
    return ((E[0][0]-E[1][1])*math.cos(2*theta)/2
            + E[0][1]*math.sin(2*theta))


def check_symbols():
    rho, p, a, b = 0.7, 1.0, 0.6, 0.8j
    s, t, e, f = 0.35, -0.2, 0.4, -0.15j
    K = 1.25
    print('Omega/K  longitudinal    in-phase plus    quadrature cross')
    for u in (0., .5, .95, .99, 1.01, 1.05):
        om, delta = u*K, 1-u*u
        D = K*K-om*om
        q = [-om, 0., 0., K]
        T = tensor(rho, p, a, b, u)
        probe = tensor(s, t, e, f, u)
        for j in range(4):
            assert abs(sum(q[i]*T[i][j] for i in range(4))) < 1e-14
        h = [[v/D for v in row] for row in trace_reverse(T)]
        xi = (0.25, 0.45j, -0.33, 0.60)
        shifted = [[h[i][j]+1j*(q[i]*xi[j]+q[j]*xi[i]) for j in range(4)] for i in range(4)]
        E = electric(h, q)
        diff = electric(shifted, q)
        assert max(abs(E[i][j]-diff[i][j]) for i in range(3) for j in range(3)) < 1e-12
        # The physical response to complex Fourier amplitudes pairs the
        # source at q with the conjugated probe, corresponding to -q.
        exchange = sum(probe[i][j].conjugate()*h[i][j] for i in range(4) for j in range(4))
        predicted = ((delta*rho*s/2 + rho*t + s*p)/(K*K)
                     + 2*(a*e.conjugate()+b*f.conjugate())/D)
        assert abs(predicted-exchange) < 1e-12
        assert abs(E[2][2]-(p+delta*rho/2)) < 1e-12
        assert abs((E[0][0]+E[1][1])/2-u*u*rho/2) < 1e-12
        assert abs(angular(E, 0)-om*om*a/D) < 1e-12
        assert abs(angular(E, math.pi/4)-om*om*b/D) < 1e-12
        print(f'{u:7.2f} {E[2][2]:13.6f} {angular(E,0).real:16.6f} '
              f'{angular(E,math.pi/4).imag:19.6f}')

    # A retarded scalar plus an unaltered static compensator matches the
    # zero-frequency trace kernel, but leaves a false pure-pressure pole.
    for u in (.99, 1.01):
        D = K*K*(1-u*u)
        T = tensor(0., 1., 0., 0., u)
        h = [[v/D for v in row] for row in trace_reverse(T)]
        gr = sum(T[i][j]*h[i][j] for i in range(4) for j in range(4))
        naive = 2*(1/D-1/(K*K))
        assert abs(gr) < 1e-12
        print(f'At Omega/K={u:.2f}, K^2 pure-pressure exchange: '
              f'spin two {K*K*gr:.3f}, mixed scalar-Gauss extension {K*K*naive:.3f}')


def causal_burst():
    sites, period, cycles, receiver = 256, 16, 4, 20
    length = cycles*period
    alpha = 2*math.pi/period
    # Compact real-space stress profile -Delta_z(delta_0) with unit steps.
    shape = [0.]*sites
    shape[0], shape[1], shape[-1] = 2., -1., -1.
    cosine = [math.cos(alpha*j) for j in range(sites)]
    normalization = sum(s*c for s, c in zip(shape, cosine))
    def component(x):
        return sum(t*c for t, c in zip(x, cosine))/normalization
    old = [[0.]*sites for _ in range(3)]
    cur = [[0.]*sites for _ in range(3)]  # H_pressure, H_plus, H_cross
    largest_pressure_error = largest_mode_error = 0.
    max_after = [0., 0.]
    arrival = None
    factor = length*math.tan(alpha/2)
    for n in range(length+period):
        phase = n*alpha
        drive = (math.cos(phase), 0.6*math.cos(phase), 0.8*math.sin(phase))
        if n >= length:
            drive = (0., 0., 0.)
        new, tidal = [], []
        for field in range(3):
            y, previous = cur[field], old[field]
            lap = [y[(j-1)%sites]-2*y[j]+y[(j+1)%sites] for j in range(sites)]
            following = [2*y[j]-previous[j]+lap[j]+drive[field]*shape[j] for j in range(sites)]
            dtt = [following[j]-2*y[j]+previous[j] for j in range(sites)]
            # Ezz = (dtt-Delta_z)H_pressure; differential arms see -dtt H_TT.
            electric_field = ([v-w for v, w in zip(dtt, lap)] if field == 0
                              else [-v for v in dtt])
            new.append(following)
            tidal.append(electric_field)
        largest_pressure_error = max(largest_pressure_error,
                                     max(abs(v-drive[0]*s) for v, s in zip(tidal[0], shape)))
        if arrival is None and abs(tidal[1][receiver]) > 1e-10:
            arrival = n
        if n >= length:
            measured = (component(tidal[1]), component(tidal[2]))
            predicted = (.6*factor*math.sin(phase), -.8*factor*math.cos(phase))
            for j in (0, 1):
                largest_mode_error = max(largest_mode_error, abs(measured[j]-predicted[j]))
                max_after[j] = max(max_after[j], abs(measured[j]))
        old, cur = cur, new
    assert arrival == receiver-1
    assert largest_pressure_error < 1e-12 and largest_mode_error < 2e-10
    print(f'First tidal signal at site {receiver}: tick {arrival} (distance from drive {receiver-1})')
    print(f'Max pointwise pressure identity error {largest_pressure_error:.3e}')
    print(f'Post-burst modal arm amplitudes {max_after[0]:.6f}, {max_after[1]:.6f}')
    print(f'Max post-burst quadrature error {largest_mode_error:.3e}')


if __name__ == '__main__':
    check_symbols()
    causal_burst()
tensor_rotor.py
"""Spectra and static-charge checks for three linear tensor Hamiltonians.

Run python3 tensor_rotor.py. No dependencies. Spatial units a=1; time is
continuous. All checks use the staggered symbol K_i=2 sin(k_i/2).
"""
from itertools import product
from math import cos, pi, sin, sqrt


I = [[float(i == j) for j in range(3)] for i in range(3)]


def inner(a, b):
    return sum(x*y for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def add(a, b, weight=1.):
    return [[x + weight*y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def outer(a, b):
    return [[x*y for y in b] for x in a]


def mm(a, b):
    return [[sum(x*y for x, y in zip(row, col)) for col in zip(*b)] for row in a]


def trace(a):
    return sum(row[i] for i, row in enumerate(a))


def symbol(k):
    return [2*sin(x/2) for x in k]


def generators(K):
    x, y, z = K
    cross = [[0., -z, y], [z, 0., -x], [-y, x, 0.]]
    def magnetic(a):
        return mm(mm(cross, a), list(zip(*cross)))
    def cotton(a):
        b = magnetic(a)
        # One overall i is dropped in this real Fourier representation.
        return mm(cross, add(b, I, -trace(b)/2))
    return magnetic, cotton


def symmetric_basis():
    for i in range(3):
        for j in range(i, 3):
            a = [[0.]*3 for _ in range(3)]
            a[i][j] = a[j][i] = 1. if i == j else 1/sqrt(2)
            yield a


def max_difference(a, b):
    return max(abs(x-y) for ra, rb in zip(a,b) for x,y in zip(ra,rb))


def check_grid(n=8):
    basis = list(symmetric_basis())
    largest = charge_error = 0.
    count = 0
    for indices in product(range(-n//2, n//2), repeat=3):
        if not any(indices):
            continue
        K = symbol([2*pi*j/n for j in indices])
        K2 = sum(t*t for t in K)
        b, c = generators(K)
        # Check the derivative phase placements: raw forward difference,
        # rephased to its half-cell midpoint, equals the staggered symbol.
        for j, t in zip(indices, K):
            k = 2*pi*j/n
            phase = complex(cos(k/2), -sin(k/2))
            assert abs((complex(cos(k), sin(k))-1)*phase-1j*t) < 1e-14
        for op, scale, modes in ((b, K2**2, 3), (c, K2**3, 2)):
            images = [op(a) for a in basis]
            projector = [[inner(v,w)/scale for w in images] for v in images]
            # Symmetric P²=P and tr P integer determine all six eigenvalues.
            largest = max(largest, max_difference(mm(projector,projector), projector),
                          abs(trace(projector)-modes))
        v = (0.27, -.48, .65)
        gauge = add(outer(v,K), outer(K,v))
        assert inner(b(gauge), b(gauge)) < 1e-22
        assert inner(c(I), c(I)) < 1e-22
        assert abs(inner(b(I),b(I))-2*K2**2) < 1e-11
        # The linear comparator: B is K² on the transverse trace and
        # -K² on TT; its gauge kernel drops out of both integrated energies.
        P = add(I, outer(K,K), -1/K2)
        scalar_charge = .8
        trace_field = [[scalar_charge*x/2 for x in row] for row in P]
        assert abs(trace(trace_field)-scalar_charge) < 1e-12
        assert abs(inner(trace_field,trace_field)/2-scalar_charge**2/4) < 1e-12
        for a in basis:
            cotton_tensor = c(a)
            assert max_difference(cotton_tensor, list(zip(*cotton_tensor))) < 1e-12
            assert abs(trace(cotton_tensor)) < 1e-12
            assert max(abs(sum(K[i]*cotton_tensor[i][j] for i in range(3)))
                       for j in range(3)) < 1e-12
            transverse = mm(mm(P,a),P)
            tt = add(transverse,P,-trace(transverse)/2)
            assert max_difference(b(tt), [[-K2*x for x in row] for row in tt]) < 1e-12
            assert abs(inner(transverse,transverse)-trace(transverse)**2/2-inner(tt,tt)) < 1e-12
        # Static vector charge test. K·E=rho with the irrelevant i removed.
        khat = [x/sqrt(K2) for x in K]
        rho = (.4, -.6, .9)
        longitudinal = sum(x*y for x,y in zip(rho,khat))
        perp = [r-longitudinal*x for r,x in zip(rho,khat)]
        base = add(add(outer(khat,perp),outer(perp,khat)),outer(khat,khat),longitudinal)
        for constrained, e_coeff in ((False,1.),(True,1.5)):
            e = add(base,P,-longitudinal/2 if constrained else 0.)
            e = [[x/sqrt(K2) for x in row] for row in e]
            assert max(abs(sum(K[i]*e[i][j] for i in range(3))-rho[j]) for j in range(3)) < 1e-12
            if constrained:
                assert abs(trace(e)) < 1e-12
            energy2 = (2*sum(x*x for x in perp)+e_coeff*longitudinal**2)/K2
            charge_error = max(charge_error,abs(inner(e,e)-energy2))
        count += 1
    assert largest < 1e-12 and charge_error < 1e-12
    print(f'{count} nonzero modes: B has rank 3, Cotton rank 2; '
          f'largest normalized projector error {largest:.3e}')
    print(f'Vector-charge energy identity maximum error {charge_error:.3e}')


def main():
    check_grid()
    # Ratios for harmonic m=2 relative to m=1 in a periodic length-N box.
    print('N  ratio z=1   ratio z=2   ratio z=3')
    for n in (16,32,64):
        ratio = sin(2*pi/n)/sin(pi/n)
        print(f'{n:2d} {ratio:10.6f} {ratio**2:11.6f} {ratio**3:11.6f}')
    # An unconstrained transverse trace A=P/sqrt(2) is normalized. Its
    # elastic energy is negative at small K despite a finite trace penalty.
    for n in (16,32,128):
        K = 2*sin(pi/n)
        elastic = (-K*K+2*10*K**4)/2
        print(f'N={n}: curvature-constraint-violating trace trial, '
              f'elastic energy including lambda=10 penalty {elastic:+.8f}')
        electric = -0.25+10*K**2/6
        print(f'N={n}: Gauss-violating isotropic E trial, kinetic energy '
              f'including lambda=10 penalty {electric:+.8f}')
    # A local six-component wave equation restricted by hard TT initial data
    # is positive even off that sector. Softening its divergence constraints
    # leaves a longitudinal shear at arbitrarily low frequency.
    for n in (32,64,128):
        K = 2*sin(pi/n)
        omega = K*sqrt((1+10*K**2/2)*(1+10/2))
        print(f'N={n}: positive wave comparator, soft-constraint shear '
              f'omega={omega:.6f}, omega/K={omega/K:.6f}')
    print('On a torus, the uniform trace momentum has energy -1/4 and '
          'satisfies both derivative constraints; fixing the global sector matters.')


if __name__ == '__main__':
    main()
clocks_data.py
"""Reproduce the clock-redshift checks on Zheng et al. (2023), without dependencies."""
import csv
import hashlib
import math
from pathlib import Path


C = 299792458.0
G_LOCAL = -9.803
# All fractional frequencies and gradients quoted below use 10^-19 units.
SLOPE = G_LOCAL * 0.01 / C**2 * 1e19
SYSTEMATIC = 2.5
DATA = Path(__file__).with_name('clocks_data.csv')
CSV_LF_SHA256 = '4bd3925ca24a93ca7a0d28938c64b643dc8bfac6079d8a6feaf6273c33b1dba3'
# Corrected fractional frequency differences and total uncertainties, from
# Supplementary Table 1. Pair (2,4) shares no atoms with endpoints (1,5).
HALF_HEIGHT = (-5.78, 2.19)
ENDPOINT = (-11.96, 2.93)


def run_summary(rows):
    weight = sum(1/e**2 for _, e in rows)
    mean = sum(y/e**2 for y, e in rows)/weight
    chi_sq = sum(((y-mean)/e)**2 for y, e in rows)
    nominal = 1/math.sqrt(weight)
    # The paper inflates the pooled statistical error when reduced chi² > 1.
    # We show the nominal and scatter-adjusted errors separately for each split.
    adjusted = nominal*max(1., math.sqrt(chi_sq/(len(rows)-1)))
    return mean, nominal, adjusted, chi_sq


def main():
    if hashlib.sha256(DATA.read_bytes().replace(b'\r\n', b'\n')).hexdigest() != CSV_LF_SHA256:
        raise ValueError('Expected the Zenodo Fig3.csv, up to standard line endings')
    with DATA.open(newline='') as fin:
        table = list(csv.reader(fin))[2:]  # the header is followed by a units row
    if [int(r[3]) for r in table] != list(range(1, 15)):
        raise ValueError('Unexpected measurement-run indices')
    runs = [(float(r[4]), float(r[5])) for r in table]
    print(f'Independent gradient {SLOPE:.6f} x 10^-19/cm')
    for h in (0.99, 1.00):
        expected = SLOPE*h
        observed, sigma = ENDPOINT
        height_sigma = abs(SLOPE)*0.01
        total = math.hypot(sigma, height_sigma)
        print(f'h={h:.2f} cm: prediction {expected:.6f}, observed {observed:.2f}, '
              f'residual {observed-expected:+.6f}, conditional SD {total:.6f}, '
              f'standardized residual {(observed-expected)/total:+.3f}')
    print(f'Flat-clock endpoint displacement {abs(ENDPOINT[0])/ENDPOINT[1]:.3f} measurement SD')
    y0, e0 = HALF_HEIGHT
    y1, e1 = ENDPOINT
    print(f'Disjoint clock pairs: prediction {2*y0:.2f}, residual {y1-2*y0:+.2f}; '
          f'allowed SD [{abs(e1-2*e0):.2f}, {e1+2*e0:.2f}] for any correlation')
    print('run subset    mean       nominal SD    adjusted SD      chi squared')
    for label, rows in (('1-7', runs[:7]), ('8-14', runs[7:]), ('1-14', runs)):
        m, e, a, chi = run_summary(rows)
        print(f'{label:9s} {m:10.6f} {e:13.6f} {a:14.6f} {chi:16.6f}')
    early, _, e_early, _ = run_summary(runs[:7])
    late, _, e_late, _ = run_summary(runs[7:])
    print(f'Late minus early {late-early:+.6f}, conditional statistical SD '
          f'{math.hypot(e_early,e_late):.6f}')
    print(f'Late minus gravimeter {late-SLOPE:+.6f}, conditional total SD '
          f'{math.hypot(e_late,SYSTEMATIC):.6f}')


if __name__ == '__main__':
    main()
contact_reference.py
"""Read the separation of two mobile particles after spatial clock pulses.

Every gate is onsite or joins nearest neighbours on the physical lattice.
The square array stores the two-particle wavefunction, with walker position
as its first index and reference position as its second. All momenta and
energies use one cell, one time unit and hbar=1.
"""
from cmath import exp
from math import ceil, cos, pi, sin, sqrt

LENGTH = 16
MASS = 4.0
J = 1/MASS
G = 0.5
Q = pi/4
COSINE = [cos(Q*j) for j in range(LENGTH)]
SINE = [sin(Q*j)/Q for j in range(LENGTH)]


def inner(a, b):
    return sum(x.conjugate()*y for x, y in zip(a, b))


def coincident(a):
    return [v if i//LENGTH == i % LENGTH else 0 for i, v in enumerate(a)]


def contact_probability(a):
    return sum(abs(a[i*LENGTH+i])**2 for i in range(LENGTH))


def branch(separation, phase):
    a = [0j] * LENGTH**2
    for ref in range(LENGTH):
        a[((ref+separation) % LENGTH)*LENGTH+ref] = 1/sqrt(2*LENGTH)
        a[((ref+separation+1) % LENGTH)*LENGTH+ref] = exp(1j*phase)/sqrt(2*LENGTH)
    return a


def preparation(phase):
    # Equal mixing cancels the phase dependence in both one-body density matrices.
    return (branch(0, phase), branch(4, phase+pi))


class ProfileHamiltonian:
    def __init__(self, profile, contact, mass=MASS):
        hopping = 1/mass
        self.diagonal = []
        self.groups = [[] for _ in range(4)]
        for y in range(LENGTH):
            yp = (y+1) % LENGTH
            for r in range(LENGTH):
                rp = (r+1) % LENGTH
                i = y*LENGTH+r
                d = 2*profile[y]+(mass+hopping)*profile[r]
                self.diagonal.append(d + (contact*profile[r] if y == r else 0))
                walker_link = 0.25j*(profile[y]+profile[yp])
                ref_link = -0.25*hopping*(profile[r]+profile[rp])
                self.groups[y % 2].append((i, yp*LENGTH+r, walker_link))
                self.groups[2+r % 2].append((i, y*LENGTH+rp, ref_link))

    def apply(self, state):
        result = [d*a for d, a in zip(self.diagonal, state)]
        for group in self.groups:
            for i, j, h in group:
                result[j] += h*state[i]
                result[i] += h.conjugate()*state[j]
        return result

    def pulse(self, state, angle):
        # A symmetric finite-depth pulse. Negative angle gives its exact inverse.
        phases = [exp(-0.5j*angle*d) for d in self.diagonal]
        a = [p*x for p, x in zip(phases, state)]
        for group, scale in ((0,.5),(1,.5),(2,.5),(3,1),(2,.5),(1,.5),(0,.5)):
            for i, j, h in self.groups[group]:
                mag = abs(h)
                if mag:
                    c, s = cos(scale*angle*mag), -1j*sin(scale*angle*mag)/mag
                    x, y = a[i], a[j]
                    a[i], a[j] = c*x+s*h.conjugate()*y, c*y+s*h*x
        return [p*x for p, x in zip(phases, a)]


def generator(c, s, state):
    cs = c.apply(s.apply(state))
    sc = s.apply(c.apply(state))
    return [1j*(a-b) for a,b in zip(cs,sc)]


def response(state, generator_state):
    # d<P_contact>/da for exp(-i a B).
    return 2*inner(coincident(state), generator_state).imag


def loop(c, s, state, t):
    for pulse, angle in ((c,-t),(s,-t),(c,t),(s,t)):
        state = pulse.pulse(state, angle)
    assert abs(inner(state,state).real-1) < 1e-12
    return state


def check_marginals():
    for phase in (pi/2,-pi/2,0):
        states = preparation(phase)
        for i in range(LENGTH):
            for j in range(LENGTH):
                walker = sum(s[i*LENGTH+k]*s[j*LENGTH+k].conjugate()
                             for s in states for k in range(LENGTH))/2
                ref = sum(s[k*LENGTH+i]*s[k*LENGTH+j].conjugate()
                          for s in states for k in range(LENGTH))/2
                expected = 1/LENGTH if i == j else 0
                assert max(abs(walker-expected),abs(ref-expected)) < 1e-14
        relative = [sum(abs(s[((k+r) % LENGTH)*LENGTH+k])**2
                        for s in states for k in range(LENGTH))/2 for r in range(LENGTH)]
        assert all(abs(n-(.25 if r in (0,1,4,5) else 0)) < 1e-14
                   for r,n in enumerate(relative))
        uniform = ProfileHamiltonian([1]*LENGTH,G)
        mean_energy = sum(inner(s,uniform.apply(s)).real for s in states)/2
        assert abs(mean_energy-(2+MASS+J+G/4)) < 1e-13


def velocity_sum(a):
    out = [0j]*len(a)
    for y in range(LENGTH):
        for r in range(LENGTH):
            i=y*LENGTH+r
            out[i] = (a[((y+1)%LENGTH)*LENGTH+r]+a[((y-1)%LENGTH)*LENGTH+r])/2
            out[i] += J*(a[y*LENGTH+(r+1)%LENGTH]-a[y*LENGTH+(r-1)%LENGTH])/(2j)
    return out


def contact_generator(state):
    va = velocity_sum(state)
    pv = coincident(va)
    vp = velocity_sum(coincident(state))
    return [G*sin(Q)/(2*Q)*(x+y) for x,y in zip(pv,vp)]


def verify_interaction():
    free = ProfileHamiltonian(COSINE,0), ProfileHamiltonian(SINE,0)
    coupled = ProfileHamiltonian(COSINE,G), ProfileHamiltonian(SINE,G)
    state = [exp(0.013j*i*i)/LENGTH for i in range(LENGTH**2)]
    direct = [b-a for a,b in zip(generator(*free,state),generator(*coupled,state))]
    error = max(abs(a-b) for a,b in zip(direct,contact_generator(state)))
    assert error < 1e-12
    print(f"Native two-body commutator versus local contact formula: {error:.2e}")

    for phase in (pi/2,-pi/2):
        states = preparation(phase)
        predicted = G*sin(Q)/Q*(sin(phase)+J*cos(phase))/8
        exact = sum(response(a,contact_generator(a)) for a in states)/2
        assert abs(exact-predicted) < 1e-13
        def probability(hamiltonians, t):
            return sum(contact_probability(loop(*hamiltonians,a,t)) for a in states)/2
        estimates = []
        for t in (0.12,0.06,0.03):
            contrast = sum(probability(coupled,u)-probability(free,u) for u in (t,-t))/2
            estimates.append(contrast/t**2)
        print(f"phase/pi={phase/pi:+.1f}: exact {exact:+.9f}, finite estimates",
              " ".join(f"{e:+.9f}" for e in estimates))
        assert abs(estimates[-1]-exact) < .0004
        assert abs(estimates[-1]-exact) < .31*abs(estimates[-2]-exact)

    # Dephasing removes the signal without changing the contact population.
    dephased = []
    for r in (0,1,4,5):
        a = [0j]*LENGTH**2
        for j in range(LENGTH):a[((j+r)%LENGTH)*LENGTH+j]=1/sqrt(LENGTH)
        dephased.append(a)
    assert max(abs(response(a,contact_generator(a))) for a in dephased)<1e-14




def finite_counts():
    # Four independent Bernoulli settings: the +/- phase at g on and g off.
    # Record the entire contrast, since its sign can differ from the weak limit.
    for angle, pairs, sign in ((.15,4,1),(.30,4,-1),(.24,8,-1)):
        probabilities = []
        for phase in (pi/2,-pi/2):
            for g in (G,0):
                c = ProfileHamiltonian(COSINE,g)
                s = ProfileHamiltonian(SINE,g)
                total = 0
                for state in preparation(phase):
                    for _ in range(pairs):
                        state = loop(c,s,state,angle)
                        state = loop(c,s,state,-angle)
                    total += contact_probability(state)/2
                probabilities.append(total)
        a,b,c,d = probabilities
        difference = (a-b)-(c-d)
        assert sign*difference > .01
        variance = sum(p*(1-p) for p in probabilities)
        n = ceil(19*variance/difference**2)
        print(f"Finite counts: angle={angle}, pairs={pairs}, " 
              + " ".join(f"{p:.8f}" for p in probabilities)
              + f", contrast {difference:+.8f}, sufficient shots per setting {n}")


def localized_branches(phase, coherent_reference):
    # Near and far branches have opposite phases on the same pair of sites.
    # Exchanging walker and reference puts the coherence entirely on the reference.
    states = []
    for location, sign in ((0,1), (4,-1)):
        a = [0j]*LENGTH**2
        for position, amp in ((0,1), (1,sign*exp(1j*phase))):
            y, r = ((location, position) if coherent_reference else (position, location))
            a[y*LENGTH+r] = amp/sqrt(2)
        states.append(a)
    return states


def verify_localized():
    for mass in (4.,8.):
        free = ProfileHamiltonian(COSINE,0,mass), ProfileHamiltonian(SINE,0,mass)
        coupled = ProfileHamiltonian(COSINE,G,mass), ProfileHamiltonian(SINE,G,mass)
        def delta(state):
            return response(state, generator(*coupled,state))-response(state,generator(*free,state))
        for on_ref in (False,True):
            phases = (0,pi) if on_ref else (pi/2,-pi/2)
            for phase in phases:
                a,b = localized_branches(phase,on_ref)
                expected = G*sin(Q)/(8*Q)*(-cos(phase)/mass if on_ref else sin(phase))
                mixed = (delta(a)+delta(b))/2
                # Both local states have equal weights on two orthogonal basis states.
                # A coherent superposition of these orthogonal product branches is entangled.
                pure = [(x+1j*y)/sqrt(2) for x,y in zip(a,b)]
                for i in (0,1,4):
                    for j in (0,1,4):
                        dw = sum(pure[i*LENGTH+k]*pure[j*LENGTH+k].conjugate()
                                 for k in range(LENGTH))
                        dr = sum(pure[k*LENGTH+i]*pure[k*LENGTH+j].conjugate()
                                 for k in range(LENGTH))
                        sw = (0,4) if on_ref else (0,1)
                        sr = (0,1) if on_ref else (0,4)
                        assert abs(dw-(.5 if i==j and i in sw else 0)) < 1e-14
                        assert abs(dr-(.5 if i==j and i in sr else 0)) < 1e-14
                assert max(abs(mixed-expected),abs(delta(pure)-expected)) < 1e-13
                t=.012
                observed = sum(contact_probability(loop(*coupled,pure,u))
                               -contact_probability(loop(*free,pure,u))
                               for u in (-t,t))/(2*t*t)
                assert abs(observed-expected)<.00015
                label = 'reference' if on_ref else 'walker'
                print(f"Localized {label}, mass {mass:.0f}, phase/pi={phase/pi:+.1f}: "
                      f"contact coefficient {expected:+.8f}, finite {observed:+.8f}")


if __name__ == "__main__":
    check_marginals()
    verify_interaction()
    verify_localized()
    finite_counts()
reference_scattering.py
"""Elastic recoil and signed contact spectroscopy on the K=0 two-body band.

The rest energy is removed during time propagation. In relative coordinate
the nearest-neighbour hopping is (i-J)/2 and the contact is a real onsite g.
"""
from cmath import exp
from math import atan, cos, exp as real_exp, pi, sin, sqrt

J = 0.25
G = 0.5
HOP = (1j-J)/2
BASE = 2+4+J


def action(a, interaction):
    b = [HOP*x+HOP.conjugate()*y
         for x,y in zip([a[-1]]+a[:-1],a[1:]+[a[0]])]
    mid = len(a)//2
    b[mid] += interaction*a[mid]
    return b


def energy(p):
    return BASE+sin(p)-J*cos(p)


def norm(a):
    return sum(abs(x)**2 for x in a)


def evolve(a, interaction, steps, dt, order=17):
    # Taylor propagation. The norm of the reduced Hamiltonian is at most
    # sqrt(1+J^2)+|g|, so the truncation is controlled uniformly in box size.
    for _ in range(steps):
        result = a[:]
        term = a
        for n in range(1,order+1):
            term = [(-1j*dt/n)*z for z in action(term,interaction)]
            result = [x+y for x,y in zip(result,term)]
        a = result
    assert abs(norm(a)-1) < 2e-10
    return a


def scattering(width, interaction=G):
    length = 32*width
    x = range(-length//2,length//2)
    a = [real_exp(-(j+6*width)**2/(4*width**2)) for j in x]
    n = sqrt(norm(a))
    a = evolve([z/n for z in a],interaction,18*width,2/3)
    # After 12 widths of propagation both outgoing packets separate from contact.
    mid = length//2
    left = a[:mid]
    prob = norm(left)
    cos_p = sum((x.conjugate()*y).real for x,y in zip(left,left[1:]))/prob
    return prob, J*(1-cos_p)


def bound_state(interaction):
    scale = sqrt(1+J**2)
    energy_shift = (1 if interaction > 0 else -1)*sqrt(scale**2+interaction**2)
    # Remove the hopping phase, then solve the recurrence away from contact.
    t = abs(HOP)
    decay = (energy_shift-interaction)/(2*t)
    link_phase = HOP/t
    sites = range(-96,97)
    a = [link_phase**r * decay**abs(r) for r in sites]
    ref = action(a,interaction)
    error = max(abs(x-energy_shift*y) for x,y in zip(ref[1:-1],a[1:-1]))
    assert abs(decay)<1 and error < 1e-12
    return BASE+energy_shift


def main():
    other = -pi + 2*atan(J)
    incoming_speed = 1.0
    outgoing_speed = cos(other)+J*sin(other)
    assert abs(energy(other)-energy(0))<1e-14 and abs(outgoing_speed+1)<1e-14
    assert abs(cos(other)+15/17)<1e-14 and abs(sin(other)+8/17)<1e-14
    probability = G**2/(G**2+incoming_speed**2)
    recoil = J*(1-cos(other))
    print(f"Plane waves: reflection {probability:.9f}, reference energy gain {recoil:.9f}")
    # As a separate direct check, impose matching at the defect for an incoming
    # right-moving unit wave, reflected r*exp(i other*x), and transmitted t.
    for g in (G,-G):
        r = g/(1j*incoming_speed-g)
        t = 1+r
        left = exp(0j)+r*exp(-1j*other)
        right = t
        residual = HOP*left+HOP.conjugate()*right+g*t-(energy(0)-BASE)*t
        assert abs(residual)<1e-14
        assert abs(abs(r)**2-probability)<1e-14
        assert abs(abs(t)**2+abs(r)**2-1)<1e-14
        print(f"Signed bound energy, g={g:+.1f}: {bound_state(g):.9f}")
    last_error = 1
    for width in (6,12,24):
        p, e = scattering(width)
        error = abs(p-probability)+abs(e-recoil)
        print(f"Packet width {width}: reflected probability {p:.8f}, "
              f"conditional reference energy gain {e:.8f}")
        assert error < last_error
        last_error = error
    assert last_error < .0005


if __name__ == "__main__":
    main()
free_reference.py
"""Two free walks, periodic clock pulses, and a mobile position reference.

Run with Python 3 and the standard library. All angular momenta below are
crystal momenta in radians per coarse cell. Position is in coarse cells.
"""
from cmath import exp
from itertools import product
from math import acos, cos, isclose, pi, sin, sqrt

LENGTH = 16
STEP = 2                       # the two masks carry ±2 momentum bins
MOMENTA = tuple(2*pi*j/LENGTH for j in range(LENGTH))
Q = MOMENTA[STEP]
WEIGHTS = (1, 2, 3, 2, 1)
POINTS = tuple(range(-2, 3))
SPIN = (0.5, 0.5j, -0.5j, -0.5)
FORM = cos(Q/2)**2*sin(Q)/Q


def native(k):
    x, y, z = (MOMENTA[j] for j in k)
    return sin(x)*cos(y)*cos(z), sin(y)*cos(z), sin(z)


def weak(k):
    x, y, z = (MOMENTA[j] for j in k)
    return FORM*cos(x)**2*sin(2*y)*cos(z)**2/2


def pauli_action(a, b, vec):
    x, y, z = vec
    return z*a + (x-1j*y)*b, (x+1j*y)*a - z*b


def on_spin(spin, which, vector):
    pairs = ((0, 2), (1, 3)) if which == 0 else ((0, 1), (2, 3))
    out = [0j]*4
    for i, j in pairs:
        out[i], out[j] = pauli_action(spin[i], spin[j], vector)
    return out


def modulate(state, sine):
    """Apply the sum of the two independently weighted native Hamiltonians."""
    out = {}
    for pair, spin in state.items():
        for which, initial in enumerate(pair):
            old = native(initial)
            for sign in (-1, 1):
                final = (initial[0], (initial[1]+sign*STEP) % LENGTH, initial[2])
                new = native(final)
                vector = [(v+w)/2 for v, w in zip(old, new)]
                # Fourier coefficient of sin(qy)/q or cos(qy).
                factor = sign/(2j*Q) if sine else 0.5
                dest = (final, pair[1]) if which == 0 else (pair[0], final)
                accum = out.setdefault(dest, [0j]*4)
                for j, value in enumerate(on_spin(spin, which, vector)):
                    accum[j] += factor*value
    return out


def check_pulse_order():
    # Test distinct entangled and product spin inputs and intermediate momenta.
    largest = 0.
    for seed, spin in product(range(35), (SPIN, (0j, 1., 0j, 0j))):
        pair = tuple(tuple((a*seed+b) % LENGTH for a, b in seq)
                     for seq in (((3, 4), (5, 1), (1, 2)), ((2, 1), (7, 3), (3, 0))))
        state = {pair: spin}
        cs = modulate(modulate(state, True), False)
        sc = modulate(modulate(state, False), True)
        target = sum(weak(k) for k in pair)
        for dest in cs.keys() | sc.keys():
            left, right = cs.get(dest, (0j,)*4), sc.get(dest, (0j,)*4)
            for j in range(4):
                result = 1j*(left[j]-right[j])
                expected = target*spin[j] if dest == pair else 0j
                largest = max(largest, abs(result-expected))
    assert largest < 2e-14
    return largest


def fourier_profile(carrier):
    norm = sqrt(LENGTH*sum(w*w for w in WEIGHTS))
    return [sum(w*exp(-1j*(k-carrier)*r) for r, w in zip(POINTS, WEIGHTS))/norm
            for k in MOMENTA]


def relative_centroid(total_x, carrier, t):
    """Finite-ring relative-position readout after evolution by the weak generator."""
    x_weight = [abs(z)**2 for z in fourier_profile(carrier)]
    z_weight = [abs(z)**2 for z in fourier_profile(0)]
    y_amplitudes = fourier_profile(0)
    inverse = [[exp(1j*k*r)/sqrt(LENGTH) for k in MOMENTA] for r in range(LENGTH)]
    probabilities = [0.]*LENGTH
    for x, z in product(range(LENGTH), repeat=2):
        amplitudes = []
        for y in range(LENGTH):
            p = (x, y, z)
            other = ((total_x-x) % LENGTH, -y % LENGTH, -z % LENGTH)
            b = weak(p)+weak(other)
            amplitudes.append(y_amplitudes[y]*exp(-1j*t*b))
        for r, row in enumerate(inverse):
            value = sum(a*v for a, v in zip(amplitudes, row))
            probabilities[r] += x_weight[x]*z_weight[z]*abs(value)**2
    assert abs(sum(probabilities)-1) < 3e-13
    # The initial relative packet and the first-order stencil avoid the cut.
    return sum((r if r < LENGTH//2 else r-LENGTH)*p for r, p in enumerate(probabilities))


def check_fibers():
    coherence = sum(a*b for a, b in zip(WEIGHTS, WEIGHTS[2:])) / sum(w*w for w in WEIGHTS)
    predicted = FORM*coherence**2*(1+coherence)/2
    step = 1e-4
    for total, carrier, target in ((0, 0., 0.), (LENGTH//4, 0., predicted),
                                    (LENGTH//4, pi/2, -predicted)):
        plus = relative_centroid(total, carrier, step)
        minus = relative_centroid(total, carrier, -step)
        readout = (plus-minus)/(2*step)
        assert abs(readout-target) < 1e-9
        print(f'P_x={MOMENTA[total]:.6f}  K_x={carrier:.6f}: '
              f'relative centroid derivative {readout:+.9f}, analytic {target:+.9f}')
    for p in product(range(LENGTH), repeat=3):
        other = tuple(-j % LENGTH for j in p)
        assert abs(weak(p)+weak(other)) < 1e-15


def true_phase(x, y, z=0.):
    return acos(cos(x)*cos(y)*cos(z))


def check_alternatives():
    # Finite difference the relative velocity of a reference-attached actuator.
    def relative_generator(p, k, mass_a, mass_r):
        ea, er = sqrt(mass_a**2+p*p), sqrt(mass_r**2+k*k)
        return ea*(p/ea-k/er)

    for ma, mr in ((1., 1.), (1., 4.)):
        d = 1e-5
        read = (relative_generator(d, -d, ma, mr) -
                relative_generator(-d, d, ma, mr))/(2*d)
        assert abs(read - (1+ma/mr)) < 1e-9
        print(f'reference-attached, m_A/m_R={ma/mr:g}: {read:.6f}')

    # Regular equal-velocity counterexample on the positive tick-phase branch.
    a = pi/4
    d = 1e-5
    gradient = (true_phase(a, a+d)-true_phase(a, a-d))/(2*d)
    center_current = 2*true_phase(a, a)*gradient
    assert abs(center_current-2*pi/(3*sqrt(3))) < 1e-9
    print(f'co-moving packets: boost bracket {center_current:.9f}, ordinary momentum {2*a:.9f}')

    # Same internal carrier and total momentum, but a different moving energy.
    p, qx, qy = pi/2, pi/4, pi/4
    mass = 2*true_phase(qx, qy)
    free = true_phase(qx, p/2+qy) + true_phase(-qx, p/2-qy)
    imposed = sqrt(p*p+mass*mass)
    assert isclose(mass, 2*pi/3) and isclose(free, 3*pi/4)
    assert isclose(imposed, 5*pi/6) and isclose(imposed-free, pi/12)
    d = 1e-5
    current = imposed*(sqrt((p+d)**2+mass**2)-sqrt((p-d)**2+mass**2))/(2*d)
    assert abs(current-p) < 1e-9
    print(f'pair moving energy: native {free:.9f}, imposed {imposed:.9f}, gap {imposed-free:.9f}')


if __name__ == '__main__':
    print(f'periodic 16-cell torus, q=pi/4, finite-profile factor {FORM:.9f}')
    print(f'largest explicit two-copy ordered-pulse error {check_pulse_order():.2g}')
    check_fibers()
    check_alternatives()
improved_contact.py
"""Replay the three-dimensional massive clock, contact boost and corner leakage.

Only Python's standard library is needed. Momentum is in inverse coarse cells,
energy in inverse time, and the worked examples use mass one.
"""
from itertools import product
from math import ceil, cos, isclose, pi, sin, sqrt


def symbol(k, improved=True, mass=1.):
    x, y, z = k
    t = [2*sin(s/2)**2 for s in k]     # stable form of 1-cos(s)
    diag = sum(s*s for s in t)
    mixed = t[0]*t[1] + t[1]*t[2] + t[0]*t[2]
    d = (2*diag/3 + 2*mixed)/mass if improved else 0.
    return (sin(x)*cos(y)*cos(z), sin(y)*cos(z), sin(z), mass+d)


def velocity(k, j, improved=True, mass=1.):
    x, y, z = k
    sx, sy, sz = map(sin, k)
    cx, cy, cz = map(cos, k)
    b_derivs = ((cx*cy*cz, 0., 0.), (-sx*sy*cz, cy*cz, 0.),
                (-sx*cy*sz, -sy*sz, cz))
    t = [2*sin(s/2)**2 for s in k]
    dd = sin(k[j])*(4*t[j]/3 + 2*sum(t[i] for i in range(3) if i != j))/mass
    return (*b_derivs[j], dd if improved else 0.)


def dot(a, b):
    return sum(x.conjugate()*y for x, y in zip(a, b))


def length(a):
    return sqrt(dot(a, a).real)


def dirac(v, u):
    x, y, z, m = v
    a, b, c, d = u
    return (m*a + z*c + (x-1j*y)*d, m*b + (x+1j*y)*c - z*d,
            z*a + (x-1j*y)*b - m*c, (x+1j*y)*a - z*b - m*d)


def positive(v):
    x, y, z, m = v
    e = length(v)
    u = (e+m, 0., z, x+1j*y)
    return tuple(a/length(u) for a in u)


def act(spin, v, which):
    out = [0j]*16
    for j in range(4):
        ids = range(j, 16, 4) if which == 0 else range(4*j, 4*j+4)
        vals = dirac(v, [spin[i] for i in ids])
        for i, a in zip(ids, vals):
            out[i] = a
    return out


BETA = (1, 1, -1, -1)
SIGN = tuple(a*b for a, b in product(BETA, repeat=2))


def scalar_contact(u):
    return [s*a for s, a in zip(SIGN, u)]


def pair_velocity(u, k, j, improved):
    v = velocity(k, j, improved)
    return [a+b for a, b in zip(act(u, v, 0), act(u, v, 1))]


def bands():
    for k in product((0., pi), repeat=3):
        vec = symbol(k)
        assert length(vec[:3]) < 3e-15
        corners = sum(s != 0 for s in k)
        assert isclose(length(vec), 1+8*corners/3+4*corners*(corners-1))
    for scale in (.18, .09, .045):
        k = tuple(scale*s for s in (1., -.7, .45))
        row = []
        for improved in (False, True):
            v = symbol(k, improved)
            en = length(v)
            u = positive(v)
            assert length([z-en*a for z, a in zip(dirac(v, u), u)]) < 1e-14
            defect = abs(dot(v[:3], v[:3])+(v[3]-1)*(v[3]+1)-dot(k,k))
            current = [dot(v, velocity(k, j, improved)) for j in range(3)]
            row.extend((defect, length([a-b for a, b in zip(current, k)])))
            for j in range(3):
                d = 2e-6
                kp, km = list(k), list(k)
                kp[j] += d
                km[j] -= d
                finite = (length(symbol(kp, improved))**2-length(symbol(km, improved))**2)/(4*d)
                assert abs(finite-current[j]) < 2e-10
        print(f'k scale {scale:.3f}: bare E²/current errors {row[0]:.4g} {row[1]:.4g}; '
              f'improved {row[2]:.4g} {row[3]:.4g}')
        if scale != .18:
            assert 58 < old[2]/row[2] < 68 and 29 < old[3]/row[3] < 35
        old = row
    for n in range(101):
        p = pi*n/100
        t = 1-cos(p)
        assert isclose(length(symbol((p,0,0)))**2, 1+2*t+t*t/3+4*t**4/9)


def matrix_elements():
    p = pi/4
    k = (p, 0., 0.)
    out = (p-pi, 0., 0.)
    u = positive(symbol(k, False))
    z = tuple(b*a for b, a in zip(BETA, u))
    assert length([a-length(symbol(k, False))*b
                   for a, b in zip(dirac(symbol(out,False), z), z)]) < 1e-12
    initial = [a*b for a, b in product(u, repeat=2)]
    final = [a*b for a, b in product(z, repeat=2)]
    vs = scalar_contact(pair_velocity(initial, k, 0, False))
    sv = pair_velocity(scalar_contact(initial), out, 0, False)
    anomaly = dot(final, [(a+b)/2 for a, b in zip(vs, sv)])
    assert abs(dot(final, scalar_contact(initial))-1) < 1e-13
    assert abs(anomaly-2*sin(p)*cos(p)/length(symbol(k,False))) < 1e-13
    detuning = 2*(length(symbol(out))-length(symbol(k)))
    assert abs(detuning-3.50940015100523) < 1e-12
    print(f'bare resonant scalar contact in units g/L³: 1; boost anomaly {anomaly.real:.9f}')
    print(f'improved positive-pair detuning at p=pi/4: {detuning:.9f}')
    for p in (.2, .1, .05):
        k = (p, -.7*p, .45*p)
        v, vel = symbol(k), velocity(k, 0)
        u = positive(v)
        initial = [a*b for a, b in product(u, repeat=2)]
        va = pair_velocity(initial, k, 0, True)
        vs = scalar_contact(va)
        sv = pair_velocity(scalar_contact(initial), k, 0, True)
        diag = dot(initial, [(a+b)/2 for a, b in zip(vs, sv)]).real
        dens = dot(initial, va).real
        assert abs(diag - 2*v[3]*vel[3]/length(v)) < 1e-13
        assert abs(dens - 2*dot(v, vel)/length(v)) < 1e-13
        print(f'positive branch at scale {p:.2f}: scalar {diag:.8f}, density {dens:.8f}')


def squared_norm(blocks):
    return sum(dot(u, u).real for u in blocks)


def corner_leakage():
    size, g = 4, .2
    configs = list(product(range(size), repeat=3))
    volume = len(configs)
    corners = [i for i, n in enumerate(configs) if i and all(s in (0, size//2) for s in n)]
    pp = (0, 1, 4, 5)
    def occupation(psi):
        return sum(abs(psi[i][j])**2 for i in corners for j in pp)
    for improved in (False, True):
        symbols = []
        for n in configs:
            k = tuple(2*pi*s/size for s in n)
            symbols.append((symbol(k, improved), symbol(tuple(-s for s in k), improved)))
        def hamiltonian(psi):
            contact = [g*s*sum(block[j] for block in psi)/volume for j, s in enumerate(SIGN)]
            result = []
            for block, (a, b) in zip(psi, symbols):
                left, right = act(block, a, 0), act(block, b, 1)
                result.append([x+y+c for x, y, c in zip(left, right, contact)])
            return result
        initial = [[0j]*16 for _ in configs]
        initial[0][0] = 1.
        rate = occupation(hamiltonian(initial))
        assert abs(rate-7*(g/volume)**2) < 1e-17
        end = .2
        steps = ceil(end*(2*max(length(a) for a, _ in symbols)+abs(g)))
        psi = initial
        for _ in range(steps):
            term = psi
            total = [row[:] for row in psi]
            for order in range(1, 17):
                factor = -1j*end/(steps*order)
                term = [[factor*x for x in row] for row in hamiltonian(term)]
                for row, add in zip(total, term):
                    for j, value in enumerate(add):
                        row[j] += value
            psi = total
        assert abs(squared_norm(psi)-1) < 5e-14
        prob = occupation(psi)
        print(f'4³ torus, g={g}, t={end}, improved={improved}: '
              f'corner probability {prob:.9g}, short-time coefficient {rate:.9g}')
        if improved:
            bound = (abs(g)*(1+1/sqrt(volume))/(16/3))**2
            assert 0 < prob < bound
            print(f'all-time improved corner probability bound {bound:.9g}')

def affine_identity():
    # Open axial section of the actual improved symbol. Test the interaction
    # identity by retaining the full [H,K] in a finite 2-particle position box.
    size, g = 5, .61
    configs = list(product(range(size), repeat=2))
    basis = {pt: i for i, pt in enumerate(configs)}
    rng_state = [[complex(sin(.71*(i+3*j)), cos(.31*(2*i+j))) for j in range(16)]
                 for i in range(len(configs))]
    stencil = {0: (0,0,0,2.), 1: (.5j,0,0,-2/3), -1: (-.5j,0,0,-2/3),
               2: (0,0,0,1/6), -2: (0,0,0,1/6)}
    def apply(state, mode, contact=False):
        result = [[0j]*16 for _ in configs]
        for pt, block in zip(configs, state):
            if (contact or mode == 'V') and pt[0] == pt[1]:
                weight = g*pt[0] if mode == 'K' else g
                result[basis[pt]] = [a+weight*b for a, b in
                                    zip(result[basis[pt]], scalar_contact(block))]
            if mode == 'V':
                continue
            for which, src in enumerate(pt):
                for jump, coeff in stencil.items():
                    dst = src+jump
                    if not 0 <= dst < size:
                        continue
                    target = (dst, pt[1]) if which == 0 else (pt[0], dst)
                    out = result[basis[target]]
                    factor = {'H': 1., 'K': (src+dst)/2, 'v': -1j*jump}[mode]
                    for j, a in enumerate(act(block, coeff, which)):
                        out[j] += factor*a
        return result
    def comm(contact):
        hk = apply(apply(rng_state,'K',contact),'H',contact)
        kh = apply(apply(rng_state,'H',contact),'K',contact)
        return [[1j*(a-b) for a,b in zip(u,v)] for u,v in zip(hk,kh)]
    full, free = comm(True), comm(False)
    vs = apply(apply(rng_state,'v'),'V')
    sv = apply(apply(rng_state,'V'),'v')
    residual = max(abs(a-b-(c+d)/2) for blocks in zip(full, free, vs, sv)
                   for a,b,c,d in zip(*blocks))
    assert residual < 1e-12
    print(f'independent full-affine interaction identity residual {residual:.2g}')


if __name__ == '__main__':
    bands()
    matrix_elements()
    affine_identity()
    corner_leakage()
virtual_contact.py
"""Exact finite-ring K=0 contact resolvent, units m=a=hbar=1. Python stdlib only."""
from math import cos, hypot, pi, sin, sqrt


def band(k):
    s = sin(k)
    m = 1 + (2/3)*(1-cos(k))**2
    return m, s, hypot(m, s)


def loops(length, z):
    """Return contact loops for high momenta, other low bands, open low ++.

    Each loop stores G00, G11=G22, G33 and G03=G12 in the sigma_x basis.
    The k and -k terms cancel entries with an odd number of sigma_z factors.
    """
    parts = [[0.0]*4 for _ in range(3)]
    for j in range(-length//2, length//2):
        k = 2*pi*j / length
        m, s, e = band(k)
        r, t = m/e, s/e
        for a in (-1, 1):
            for b in (-1, 1):
                if 4*abs(j) >= length:
                    group = 0
                elif a == b == 1:
                    group = 2
                else:
                    group = 1
                denominator = z-(a+b)*e
                if denominator == 0:
                    if group != 2:
                        raise ValueError("closed channel at a free pole")
                    # At a real open free pole the reduced vertex is still
                    # well-defined. Flag the open loop so it cannot be used.
                    parts[group] = [float("nan")]*4
                    continue
                scale = 1/(4*length*denominator)
                entries = ((1+a*r)*(1+b*r), (1+a*r)*(1-b*r),
                           (1-a*r)*(1-b*r), -a*b*t*t)
                for i, value in enumerate(entries):
                    parts[group][i] += scale*value
    return parts


def add(*arrays):
    return [sum(entries) for entries in zip(*arrays)]


def trace_weight(loop):
    a, c, d, _ = loop
    return (a+2*c+d)/4


def loop_matrix(loop):
    a, c, d, b = loop
    return [[a,0,0,b], [0,c,b,0], [0,b,c,0], [b,0,0,d]]


def solve(matrix, rhs):
    a = [list(row) + [v] for row, v in zip(matrix, rhs)]
    for i in range(len(a)):
        p = max(range(i,len(a)), key=lambda j: abs(a[j][i]))
        a[i], a[p] = a[p], a[i]
        pivot = a[i][i]
        if abs(pivot) < 1e-14:
            raise ValueError("singular resolvent")
        a[i] = [x/pivot for x in a[i]]
        for j, row in enumerate(a):
            if j != i:
                factor = row[i]
                a[j] = [x-factor*y for x,y in zip(row,a[i])]
    return [row[-1] for row in a]


def minus(a,b):
    return [[v-w for v,w in zip(x,y)] for x,y in zip(a,b)]


def inverse(a):
    n = len(a)
    return list(zip(*(solve(a,[float(i==j) for i in range(n)]) for j in range(n))))


def vertex(g, loop):
    bare_inverse = [[(1 if i in (0,3) else -1)/g if i==j else 0
                     for j in range(4)] for i in range(4)]
    return inverse(minus(bare_inverse,loop_matrix(loop)))


def pair(k):
    m,s,e = band(k)
    c = sqrt((1+m/e)/2)
    d = s/(2*c*e)
    return [c*c, -c*d, c*d, -d*d]


def matrix_element(left, matrix, right):
    return sum(a.conjugate()*m*b for a,row in zip(left,matrix)
               for m,b in zip(row,right))


def finite_ring_check(length=16, g=0.2):
    # Compare a dense full-Hamiltonian inverse at one complex energy to both
    # the contact T matrix and its two consecutive eliminations.
    q = 2*pi/length
    z = 2*band(q)[2] + 0.07j
    high, other, low = loops(length, z)
    reduced = vertex(g, add(high,other))
    restored = inverse(minus(inverse(reduced),loop_matrix(low)))
    full = vertex(g, add(high,other,low))
    error_t = max(abs(a-b) for x,y in zip(restored,full) for a,b in zip(x,y))

    n = 4*length
    mat = [[0j]*n for _ in range(n)]
    for j in range(length):
        m,s,_ = band(2*pi*j/length)
        free = ((2*m,-s,s,0),(-s,0,0,s),(s,0,0,-s),(0,s,-s,-2*m))
        for a in range(4):
            row = mat[4*j+a]
            row[4*j+a] = z
            for b in range(4):
                row[4*j+b] -= free[a][b]
            sign = 1 if a in (0,3) else -1
            for l in range(length):
                row[4*l+a] -= sign*g/length
    u = pair(q)
    rhs = [0j]*n
    rhs[4:8] = u
    dense = solve(mat,rhs)
    exact = sum(x*y for x,y in zip(u,dense[4:8]))
    free_pole = 1/(z-2*band(q)[2])
    compressed = free_pole + free_pole**2*matrix_element(u,restored,u)/length
    assert error_t < 1e-12 and abs(exact-compressed) < 1e-10
    print(f"Restored contact T error {error_t:.3g}, dense resolvent error {abs(exact-compressed):.3g}")


def pair_spectrum(length, total_k, relative_offset=0.0):
    """Precompute free poles and their contact spectral weights for any K.

    p=2*pi*j/L+relative_offset; k1=K/2+p, k2=K/2-p. Fixed relative_offset=0
    is the smooth equal-twist family. For an untwisted finite ring at an
    allowed K, use relative_offset=-K/2 (equivalent modulo 2*pi/L).
    """
    if length <= 0:
        raise ValueError("length must be positive")
    spectrum = []
    for j in range(length):
        p = 2*pi*j/length + relative_offset
        m1,s1,e1 = band(total_k/2+p)
        m2,s2,e2 = band(total_k/2-p)
        for a in (-1,1):
            u,v,w = (1+a*m1/e1)/2, a*s1/(2*e1), (1-a*m1/e1)/2
            for b in (-1,1):
                x,y,z = (1+b*m2/e2)/2, b*s2/(2*e2), (1-b*m2/e2)/2
                upper = (u*x, u*y, v*x, v*y, u*z, v*y, v*z, w*x, w*y, w*z)
                spectrum.append((a*e1+b*e2, tuple(t/length for t in upper)))
    return spectrum


def contact_denominator(spectrum, z, g):
    """det[I - g (sigma_x tensor sigma_x) G_K(z)] away from free poles."""
    total = [0.0]*10
    for pole, weights in spectrum:
        if z == pole:
            raise ValueError("free pole in contact denominator")
        inv = 1/(z-pole)
        for i in range(10):
            total[i] += weights[i]*inv
    mat = [[0.0]*4 for _ in range(4)]
    index = 0
    signs = (1,-1,-1,1)
    for i in range(4):
        for j in range(i,4):
            value = total[index]
            mat[i][j] = (i==j)-g*signs[i]*value
            mat[j][i] = (i==j)-g*signs[j]*value
            index += 1
    det = 1.0
    for i in range(4):
        p = max(range(i,4), key=lambda j: abs(mat[j][i]))
        if mat[p][i] == 0:
            return 0.0
        if p != i:
            mat[i],mat[p] = mat[p],mat[i]
            det = -det
        pivot = mat[i][i]
        det *= pivot
        for j in range(i+1,4):
            ratio = mat[j][i]/pivot
            for k in range(i+1,4):
                mat[j][k] -= ratio*mat[i][k]
    return det


def bound_pair_energy(spectrum, g, lower, upper, tolerance=1e-12):
    """Bisect a real, pole-free bracket containing one simple bound root."""
    if lower >= upper or tolerance <= 0 or any(lower <= e <= upper for e,_ in spectrum):
        raise ValueError("ordered bracket outside the free poles and positive tolerance required")
    f_lo = contact_denominator(spectrum,lower,g)
    f_hi = contact_denominator(spectrum,upper,g)
    if f_lo == 0:
        return lower
    if f_hi == 0:
        return upper
    if f_lo*f_hi > 0:
        raise ValueError("bracket must enclose a sign-changing root")
    while upper-lower > tolerance:
        mid = (lower+upper)/2
        if mid in (lower,upper):
            break
        f_mid = contact_denominator(spectrum,mid,g)
        if f_mid == 0:
            return mid
        if (f_mid > 0) == (f_lo > 0):
            lower, f_lo = mid, f_mid
        else:
            upper = mid
    return (lower+upper)/2


def main():
    g = 0.2
    for length in (256,1024,4096):
        high, other, _ = loops(length,2.)
        closed = add(high,other)
        rest = vertex(g, closed)[0][0]
        print(f"L={length} high trace/4={trace_weight(high):+.9f} high rest={high[0]:+.9f}"
              f" closed trace/4={trace_weight(closed):+.9f} closed rest={closed[0]:+.9f}"
              f" matched g={rest:.9f}")
    assert abs(rest-0.196345325) < 1e-8
    for k_index in (64,32,16,8):
        k = 2*pi*k_index/length
        m,_,e = band(k)
        high, other, _ = loops(length,2*e)
        t = vertex(g,add(high,other))
        forward = matrix_element(pair(k),t,pair(k))-rest*(m/e)**2
        backward = matrix_element(pair(-k),t,pair(k))-rest
        print(f"k={k:.7f} residual/k^2 forward={forward/k**2:+.8f}"
              f" backward={backward/k**2:+.8f}")
    assert abs(forward/k**2) < 0.03 and abs(backward/k**2) < 0.03
    finite_ring_check()
    spectrum = pair_spectrum(128,0.0)
    bound = bound_pair_energy(spectrum,-0.5,1.5,1.9999)
    assert abs(contact_denominator(spectrum,bound,-0.5)) < 1e-9
    print(f"Attractive bound pole L=128, K=0, g=-0.5: {bound:.12f}")


if __name__ == "__main__":
    main()
moving_bound.py
"""Moving bound pair in two local, rest-gap-matched spin contacts.

Integrate the relative-momentum resolvent in the Brillouin zone. In the gap
between mixed-sign bands and the positive two-particle continuum the Green
matrix is real and has no poles. Units set both constituent rest masses and
their small-momentum limiting speed to one.
"""
from math import cos, pi, sin, sqrt

I = ((1,0),(0,1))
X = ((0,1),(1,0))
Z = ((1,0),(0,-1))


def kron(a,b):
    return [[a[i//2][j//2]*b[i%2][j%2] for j in range(4)] for i in range(4)]


BASIS = [kron(a,b) for a in (I,X,Z) for b in (I,X,Z)]
CONTACTS = {"density":kron(I,I), "mass":kron(X,X)}


def band(p):
    t = 1-cos(p)
    mass = 1+(2/3)*t*t
    s = sin(p)
    e = sqrt(s*s+mass*mass)
    return e,mass/e,s/e


def sample(K,n):
    modes=[]
    for j in range(n):
        p = 2*pi*j/n
        a,x,z = band(K/2+p)
        b,y,w = band(K/2-p)
        modes.append((a+b,a-b,x,z,y,w))
    return modes


def green(modes,energy):
    coef=[0.0]*9
    for plus,minus,x,z,y,w in modes:
        pp,mm = 1/(energy-plus),1/(energy+plus)
        pm,mp = 1/(energy-minus),1/(energy+minus)
        c0,c1,c2,c12 = pp+mm+pm+mp, pp-mm+pm-mp, pp-mm-pm+mp, pp+mm-pm-mp
        coef[0]+=c0
        coef[1]+=c2*y
        coef[2]+=c2*w
        coef[3]+=c1*x
        coef[4]+=c12*x*y
        coef[5]+=c12*x*w
        coef[6]+=c1*z
        coef[7]+=c12*z*y
        coef[8]+=c12*z*w
    return [[sum(c*b[i][j] for c,b in zip(coef,BASIS))/(4*len(modes))
             for j in range(4)] for i in range(4)]


def determinant(matrix):
    a=[row[:] for row in matrix]
    d=1.
    for i in range(len(a)):
        pivot=max(range(i,len(a)),key=lambda j:abs(a[j][i]))
        if a[pivot][i]==0:return 0.
        if pivot!=i:
            a[i],a[pivot]=a[pivot],a[i]
            d=-d
        factor=a[i][i]
        d*=factor
        for j in range(i+1,len(a)):
            m=a[j][i]/factor
            for k in range(i+1,len(a)):
                a[j][k]-=m*a[i][k]
    return d


def kernel(green_matrix,contact,g):
    return [[contact[i][j]/g-green_matrix[i][j] for j in range(4)] for i in range(4)]


def root(fun,lo,hi):
    sign=fun(lo)
    assert sign*fun(hi)<0, (lo,hi)
    for _ in range(51):
        mid=(lo+hi)/2
        value=fun(mid)
        if value==0:return mid
        if sign*value<0:hi=mid
        else:lo=mid
    return (lo+hi)/2


def calibrate(z0,contact,n):
    block=green(sample(0,n),z0)
    def f(g):return determinant(kernel(block,contact,g))
    prev=-.001
    for i in range(1,151):
        now=-i/50
        if f(prev)*f(now)<0:return root(f,now,prev)
        prev=now
    raise ValueError("No weak attractive pole at the requested rest energy")


def moving(K,z0,contact,g,n):
    modes=sample(K,n)
    # Follow the shallow bound state below the positive continuum threshold.
    delta=2-z0
    edge=min(m[0] for m in modes)
    lo,hi=edge-2.5*delta, edge-.12*delta
    assert lo>max(abs(m[1]) for m in modes)
    return root(lambda z:determinant(kernel(green(modes,z),contact,g)),lo,hi)


def multiply(a,v):
    return [sum(x*y for x,y in zip(row,v)) for row in a]


def amplitudes(modes,z,contact,g):
    k=kernel(green(modes,z),contact,g)
    # A nonzero column of the adjugate supplies the null contact spinor.
    candidates=[]
    for i in range(4):
        col=[(-1)**(i+j)*determinant([[k[r][c] for c in range(4) if c!=j]
                                      for r in range(4) if r!=i]) for j in range(4)]
        candidates.append(col)
    chi=max(candidates,key=lambda v:sum(x*x for x in v))
    norm=sqrt(sum(v*v for v in chi))
    chi=[v/norm for v in chi]
    assert max(map(abs,multiply(k,chi)))<3e-10
    states=[]
    for plus,minus,x,z1,y,z2 in modes:
        projected=[0.]*4
        for a,b,energy in ((1,1,plus),(1,-1,minus),(-1,1,-minus),(-1,-1,-plus)):
            A=((1+a*z1,a*x),(a*x,1-a*z1))
            B=((1+b*z2,b*y),(b*y,1-b*z2))
            v=multiply(kron(A,B),chi)
            for i in range(4):projected[i]+=v[i]/(4*(z-energy))
        states.append(projected)
    source=multiply(contact,[g*sum(v[j] for v in states)/len(states) for j in range(4)])
    assert max(abs(x-y) for x,y in zip(source,chi))<3e-10
    worst=0.
    weights=[]
    for (plus,minus,x,z1,y,z2),v in zip(modes,states):
        a,b=(plus+minus)/2,(plus-minus)/2
        h=[[a*(x*BASIS[3][i][j]+z1*BASIS[6][i][j])
            +b*(y*BASIS[1][i][j]+z2*BASIS[2][i][j]) for j in range(4)] for i in range(4)]
        hv=multiply(h,v)
        worst=max(worst,max(abs(v[i]*z-hv[i]-source[i]) for i in range(4)))
        weights.append(sum(t*t for t in v))
    assert worst<3e-9
    n=len(modes)
    high=sum(w for j,w in enumerate(weights) if n//4<=j<=3*n//4)/sum(weights)
    at_zero=[sum(v[j] for v in states) for j in range(4)]
    on_site=sum(a*b for a,b in zip(at_zero,multiply(contact,at_zero)))/(n*sum(weights))
    even=multiply(CONTACTS["mass"],chi)
    assert max(abs(a-b) for a,b in zip(even,chi))<3e-9
    return high,on_site


def curvature(z0,contact,g,n,pair_hop=0.):
    estimates=[]
    for h in (.06,.03,.015):
        gh=g+pair_hop*(1-cos(h))
        estimates.append(2*z0*(moving(h,z0,contact,gh,n)-z0)/h**2)
    result=estimates[2]+(estimates[2]-estimates[1])/3
    previous=estimates[1]+(estimates[1]-estimates[0])/3
    assert abs(result-previous)<3e-5
    return result


def run(z0,kind,n=384):
    contact=CONTACTS[kind]
    g=calibrate(z0,contact,n)
    assert abs(moving(0,z0,contact,g,n)-z0)<2e-12
    curv=curvature(z0,contact,g,n)
    k=.3
    energy=moving(k,z0,contact,g,n)
    high,weight=amplitudes(sample(0,n),z0,contact,g)
    print(f"rest {z0:.3f}, {kind:7s}, g={g:+.9f}, E E''={curv:.9f}, "
          f"E(0.3)={energy:.9f}, metric={sqrt(z0*z0+k*k):.9f}, high weight={high:.8f}, contact={weight:.9f}")
    return g,curv,energy



def contact_weight(z,kind,g,n):
    # The source normalization gives the actual onsite spin expectation.
    # Check its value independently by differentiating the bound energy in g.
    S=CONTACTS["mass"]
    # Rest parity makes the local Green matrix commute with S.
    G0=green(sample(0,n),z)
    assert max(abs(sum(S[i][l]*G0[l][j]-G0[i][l]*S[l][j] for l in range(4)))
               for i in range(4) for j in range(4))<1e-12
    vals=[]
    for eps in (.001,.0005):
        e1=moving(0,z,CONTACTS[kind],g+eps,n)
        e2=moving(0,z,CONTACTS[kind],g-eps,n)
        vals.append((e1-e2)/(2*eps))
    assert abs(vals[0]-vals[1])<2e-6
    derivative=(4*vals[1]-vals[0])/3
    _,expectation=amplitudes(sample(0,n),z,CONTACTS[kind],g)
    assert abs(derivative-expectation)<2e-8
    return expectation


def finite_range_repair():
    n=384
    kind="mass"
    contact=CONTACTS[kind]
    z=1.9
    g=calibrate(z,contact,n)
    weight=contact_weight(z,kind,g,n)
    initial=curvature(z,contact,g,n)
    u=(1-initial)/(z*weight)
    repaired=curvature(z,contact,g,n,u)
    assert abs(repaired-1)<2e-5
    print(f"Rest contact {weight:.9f}, pair hopping {u:.9f}, repaired E E'' {repaired:.9f}")
    for k in (.3,.6):
        actual=moving(k,z,contact,g+u*(1-cos(k)),n)
        print(f"Calibration held out K={k}: energy {actual:.9f}, "
              f"metric {sqrt(z*z+k*k):.9f}, difference {actual-sqrt(z*z+k*k):+.9f}")
    other=1.975
    g2=calibrate(other,contact,n)
    test=curvature(other,contact,g2,n,u)
    print(f"Held-out rest energy {other} with the same pair hopping: E E'' {test:.9f}")
    assert abs(test-1)>1e-3


if __name__=="__main__":
    for z in (1.9,1.975,1.99):
        for kind in CONTACTS:
            result=run(z,kind)
            g2=calibrate(z,CONTACTS[kind],768)
            e2=moving(.3,z,CONTACTS[kind],g2,768)
            assert abs(result[0]-g2)<1e-10 and abs(result[2]-e2)<1e-10
    finite_range_repair()
    from virtual_contact import pair_spectrum, bound_pair_energy
    for momentum in (0.,.04):
        direct=bound_pair_energy(pair_spectrum(128,momentum),-.5,1.8,1.99)
        independent=moving(momentum,1.94555,CONTACTS["mass"],-.5,128)
        assert abs(independent-direct)<2e-10
    print("Independent four-band pole check passed at rest and in motion.")
bound_3d.py
"""Three-dimensional bound-pair curvature on the full Brillouin torus.

Optional dependency: NumPy. Run python bound_3d.py for converged quadrature.
Use python bound_3d.py 16 for a quick check. No fitting libraries are used.
"""
import sys
import numpy as np

REST = 1.90
I2 = np.eye(2)
X = np.array([[0, 1], [1, 0]])
Y = np.array([[0, -1j], [1j, 0]])
Z = np.diag([1., -1.])
GAMMA = [np.eye(4)] + [np.kron(X, a) for a in (X, Y, Z)] + [np.kron(Z, I2)]
PAIRS = [(i, j) for i in range(4) for j in range(i+1, 4)]
BASIS = np.zeros((16, len(PAIRS)))
for col, (a, b) in enumerate(PAIRS):
    BASIS[4*a+b, col] = 1/np.sqrt(2)
    BASIS[4*b+a, col] = -1/np.sqrt(2)
FULL_TENSORS = np.array([np.kron(a, b) for a in GAMMA for b in GAMMA])
TENSORS = np.array([BASIS.T @ t @ BASIS for t in FULL_TENSORS])
BETA_PAIR = TENSORS[-1].real
IDENTITY = np.eye(6)


def mode(k, shape):
    x, y, z = k
    t = [2*np.sin(a/2)**2 for a in k]
    b = [np.sin(x)*np.cos(y)*np.cos(z), np.sin(y)*np.cos(z), np.sin(z)]
    m = 1+2*sum(a*a for a in t)/3+2*(t[0]*t[1]+t[0]*t[2]+t[1]*t[2])
    e = np.sqrt(sum(a*a for a in b)+m*m)
    basis = np.stack([np.broadcast_to(a/e, shape).ravel() for a in (*b, m)], axis=1)
    return e.ravel(), basis


class Torus:
    def __init__(self, size, rest=REST):
        self.rest = rest
        self.size = size
        self.grid = tuple(np.asarray(axis) for axis in
                          np.ogrid[0:size:1, 0:size:1, 0:size:1])

    def green(self, energy, axis=0, momentum=0., derivative=False, full=False):
        # The four signed spectral projectors span all sixteen physical spin states.
        # Integrate them first, then restrict the coincident source to exchange-odd.
        moments = np.zeros((5, 5))
        n = self.size
        for lo in range(0, n, 8):
            k = [self.grid[0][lo:lo+8], self.grid[1], self.grid[2]]
            k = [p*(2*np.pi/n) for p in k]
            shape = np.broadcast_shapes(*(p.shape for p in k))
            shift = [momentum/2 if i == axis else 0. for i in range(3)]
            ea, a = mode([p+s for p, s in zip(k, shift)], shape)
            eb, b = mode([-p+s for p, s in zip(k, shift)], shape)
            w = []
            for s, t in ((1,1), (1,-1), (-1,1), (-1,-1)):
                den = energy-s*ea-t*eb
                w.append(-.25/den**2 if derivative else .25/den)
            pp, pm, mp, mm = w
            const = pp+pm+mp+mm
            first = pp+pm-mp-mm
            second = pp-pm+mp-mm
            cross = pp-pm-mp+mm
            moments[0,0] += np.sum(const)
            moments[1:,0] += np.sum(first[:,None]*a, axis=0)
            moments[0,1:] += np.sum(second[:,None]*b, axis=0)
            moments[1:,1:] += a.T @ (cross[:,None]*b)
        g = np.tensordot(moments.ravel()/n**3, FULL_TENSORS if full else TENSORS, axes=1)
        assert np.max(abs(g-g.conj().T)) < 1e-12
        return g


def rest_calibration(torus):
    green = torus.green(torus.rest)
    germ = green[np.ix_((0,5),(0,5))]
    ev, vec = np.linalg.eigh(germ)
    # Choose the negative pole with largest positive-mass-orbital coincidence amplitude.
    root = np.argmax(abs(vec[0])**2)
    lam = ev[root]
    state = np.zeros(6,dtype=complex)
    state[[0,5]] = vec[:,root]
    assert lam < 0 and abs(state[0])**2 > .97
    assert np.linalg.norm(green@state-lam*state) < 1e-12
    d_energy = (state.conj() @ torus.green(torus.rest, derivative=True) @ state).real
    assert d_energy < 0
    return green, lam, state, d_energy


def row(torus, spacing, axis, calibrated):
    plus = torus.green(torus.rest, axis, spacing)
    return extract_curvature(torus.rest, spacing, plus, calibrated)


def extract_curvature(rest, spacing, plus, calibrated):
    green0, lam, state, d_energy = calibrated
    minus = BETA_PAIR @ plus @ BETA_PAIR     # exact inversion on a symmetric torus
    slope = (plus-minus)/(2*spacing)
    curve = (plus+minus-2*green0)/spacing**2
    results = []
    for contact in (IDENTITY, BETA_PAIR):
        pole_matrix = green0-lam*contact
        eigenvalues, vectors = np.linalg.eigh(pole_matrix)
        kept = abs(eigenvalues)>1e-9
        assert np.sum(~kept) == 1
        gaps = eigenvalues[kept]
        overlaps = vectors[:,kept].conj().T @ slope @ state
        pole_curve = (state.conj() @ curve @ state).real - 2*np.sum(abs(overlaps)**2/gaps)
        results.append(-rest*pole_curve/d_energy)
    return np.array(results)


def moving_root(torus, axis, momentum, contact, calibrated):
    _, lam, state, _ = calibrated
    energy = torus.rest
    for _ in range(3):
        vals, vecs = np.linalg.eigh(torus.green(energy, axis, momentum)-lam*contact)
        j = np.argmax(abs(vecs.conj().T @ state)**2)
        slope = (vecs[:,j].conj() @ torus.green(energy, axis, momentum, derivative=True)
                 @ vecs[:,j]).real
        energy -= vals[j]/slope
    residual = min(abs(np.linalg.eigvalsh(torus.green(energy, axis, momentum)-lam*contact)))
    assert residual < 1e-12
    return energy


def rotations():
    # The 24 proper cubic rotations, generated by quarter-turns about x and z.
    turns = [(np.array([[1,0,0],[0,0,-1],[0,1,0]]), (I2-1j*X)/np.sqrt(2)),
             (np.array([[0,-1,0],[1,0,0],[0,0,1]]), (I2-1j*Z)/np.sqrt(2))]
    queue = [(np.eye(3,dtype=int), I2)]
    seen = set()
    for r, u in queue:
        key = tuple(r.ravel())
        if key in seen:
            continue
        seen.add(key)
        for t, v in turns:
            queue.append((t@r, v@u))
        u4 = np.kron(I2,u)
        yield r, BASIS.T@np.kron(u4,u4)@BASIS
    assert len(seen) == 24


ROTATIONS = list(rotations())


def average_channels(positive, axis=2):
    # For K along lab axis i select U_R G(R^-1 K) U_R†.
    total = np.zeros((6,6), dtype=complex)
    for r, u in ROTATIONS:
        direction = r[axis,:]
        j = np.argmax(abs(direction))
        g = positive[j]
        if direction[j] < 0:
            g = BETA_PAIR@g@BETA_PAIR
        total += u@g@u.conj().T
    return total/len(ROTATIONS)


def calculate(n, rest=REST, detailed=False):
    torus = Torus(n,rest)
    cal = rest_calibration(torus)
    green, lam, state, d_energy = cal
    weight = lam**2/(-d_energy)
    full = torus.green(rest,full=True)
    full_gaps = [np.sort(abs(np.linalg.eigvalsh(full-lam*contact)))[1]
                 for contact in (np.eye(16),FULL_TENSORS[-1])]
    assert min(full_gaps) > 1e-5
    print(f'E0={rest:.3f}, mesh={n}, g={1/lam:.10f}, E0*contact={rest*weight:.9f}, '
          f'next full inverse-kernel gap={min(full_gaps):.7f}')
    results = []
    orient_rest = average_channels([green]*3)
    assert np.linalg.norm(orient_rest@state-lam*state) < 1e-12
    oriented_cal = (orient_rest,lam,state,d_energy)
    # Richardson elimination of the leading step-squared error.
    for step in (.01,.005,.0025):
        plus = [torus.green(rest,j,step) for j in range(3)]
        row_ = [extract_curvature(rest,step,g,cal) for g in plus]
        avg = average_channels(plus)
        for j in (0,1):
            values = extract_curvature(rest,step,average_channels(plus,j),oriented_cal)
            assert np.max(abs(values-extract_curvature(rest,step,avg,oriented_cal))) < 5e-8
        row_.append(extract_curvature(rest,step,avg,oriented_cal))
        results.append(np.array(row_))
    coarse = (4*results[1]-results[0])/3
    fine = (4*results[2]-results[1])/3
    print('  refinement of extrapolated curvatures:',f'{np.max(abs(fine-coarse)):.2g}')
    for name,pair in zip(('x','y','z','cubic'),fine):
        print(f'  {name}: R_density={pair[0]:.9f}, R_mass={pair[1]:.9f}')
    if detailed:
        # Locate actual moving poles independently of the curvature formula.
        steps = (.012,.006)
        for j,axis in enumerate('xyz'):
            for i,contact in enumerate((IDENTITY,BETA_PAIR)):
                energies = [moving_root(torus,j,k,contact,cal) for k in steps]
                raw = [2*rest*(e-rest)/k**2 for e,k in zip(energies,steps)]
                cross = (4*raw[1]-raw[0])/3
                assert abs(cross-fine[j,i]) < 3e-6
                print(f'    {axis} contact {i}, E(.012)={energies[0]:.10f}, '
                      f'E(.006)={energies[1]:.10f}, independent R={cross:.8f}')
    return fine,rest*weight


def independent_green():
    # Invert the unrestricted 16 by 16 Hamiltonian directly on a small grid.
    n = 5
    torus = Torus(n)
    ktotal = .117
    full = np.zeros((16,16),complex)
    for index in np.ndindex(n,n,n):
        p = 2*np.pi*np.array(index)/n
        halves = np.array((0,ktotal/2,0))
        pair = []
        for k in (p+halves,-p+halves):
            en, basis = mode(k,())
            pair.append(en[0]*sum(a*b for a,b in zip(basis[0],GAMMA[1:])))
        h = np.kron(pair[0],GAMMA[0])+np.kron(GAMMA[0],pair[1])
        full += np.linalg.inv(REST*np.eye(16)-h)
    err = np.max(abs(full/n**3-torus.green(REST,1,ktotal,full=True)))
    assert err < 1e-14
    print(f'independent full Green matrix direct-inversion residual {err:.2g}')


if __name__ == '__main__':
    independent_green()
    sizes = [int(x) for x in sys.argv[1:]] or [16,32,48,64,80]
    results = [calculate(n,detailed=(n == sizes[0])) for n in sizes]
    if len(sys.argv) == 1:
        assert np.max(abs(results[-1][0]-results[-2][0])) < 2e-6
        held = [calculate(n,1.975) for n in (64,96,112)]
        print('held-out mesh difference in R:', np.max(abs(held[-1][0]-held[-2][0])))
        train, weight_train = results[-1]
        test, weight_test = held[-1]
        c = (1-train[-1])/weight_train
        print('onsite pair-hop calibration c (density, mass):', c)
        print('held-out ratios after this correction:', test[-1]+weight_test*c)
pair_shapes.py
"""Exact covering controls and relative shapes of two calculated quadratic energy sublevels."""
from fractions import Fraction
from itertools import product
from math import sqrt


def relative_shapes(density, mass):
    eigenvalues = [m / d for d, m in zip(density, mass)]
    return sqrt(max(eigenvalues)), 1 / sqrt(min(eigenvalues))


def main():
    # The four regular-tetrahedron directions are the even sign triples / sqrt(3).
    signs = [s for s in product((-1, 1), repeat=3) if s[0]*s[1]*s[2] == 1]
    gram = [[Fraction(sum(x*y for x, y in zip(a, b)), 3) for b in signs] for a in signs]
    assert all(gram[i][i] == 1 for i in range(4))
    assert all(gram[i][j] == Fraction(-1, 3) for i in range(4) for j in range(i))
    inradius = -gram[0][1]
    radius_squared = 1 - inradius**2
    assert radius_squared == Fraction(8, 9)
    # Finest ordered-model curvatures at E0=1.900, in the same rods.
    density = (1.52018924, 1.53379403, 1.43825053)
    mass = (1.51829182, 1.53343829, 1.36466062)
    scales = relative_shapes(density, mass)
    disparity = scales[0] * scales[1]
    assert abs(disparity - 1.02649) < 0.00001
    print(f"Four-copy radius squared {radius_squared}; mutual shape ratio {disparity:.8f}")
    for name, curvatures in (("density", density), ("mass", mass)):
        print(f"{name} longest/shortest semiaxis {sqrt(max(curvatures)/min(curvatures)):.8f}")
    # Recalibrating any one axis in both models preserves all relative eigenvalues.
    common = (2.0, 0.7, 1.3)
    adjusted = [tuple(x*s*s for x,s in zip(form,common)) for form in (density,mass)]
    assert all(abs(a-b) < 1e-14 for a,b in zip(scales, relative_shapes(*adjusted)))
    cubic = relative_shapes([1.52882750]*3, [1.52384400]*3)
    assert abs(cubic[0]*cubic[1]-1) < 1e-14


if __name__ == "__main__":
    main()
reference_data.py
"""Replay the numerical reading of Zhang et al., PRL 135, 230202, Fig. 4(b).

Run without arguments for the independent recoil calculation. With --source PATH,
also verify the original PDF and the plotted marker pixels. Python 3, stdlib only.
"""
import argparse
from hashlib import sha256
from math import exp
from pathlib import Path
import re
import zlib


PAPER_SHA = "599aab6511d8165125ecc4b88580f43d792941a56f0836cd5634e4b459f28ed9"
PIXEL_SHA = "a4cdb298beaa94192b500b8f9484793e3fc72b6c2367f519213b78a980b02e28"
RECOIL_KHZ = 3.7710
TRAP_KHZ = 36.0
# Coordinates in original pixels (x right, y down). Two central disks overlap.
# Columns are Fig. 4(b) marker centers, read to roughly +/-2 pixels.
MARKERS = ((1028, 111), (1076, 247), (1131, 292), (1142, 277),
           (1172, 476), (1244, 518), (1371, 581), (1482, 719))
X_ZERO, X_FOUR = 1004.5, 1723.5
Y_POINT_TWO, Y_POINT_NINE = 809.5, 39.5
# Vertical endpoints of the coldest and hottest reported one-sigma bars.
COLD_Y_BAR = (96, 125)
HOT_Y_BAR = (696, 742)
# At the coldest point the marker obscures any horizontal bar shorter than its
# diameter. Use the full disk outline as a reading envelope for that endpoint.
COLD_X_ENVELOPE = (1017, 1038)
HOT_X_BAR = (1310, 1622)


def occupation(x):
    return 4 * (x - X_ZERO) / (X_FOUR - X_ZERO)


def fringe(y):
    return 0.2 + 0.7 * (Y_POINT_TWO - y) / (Y_POINT_TWO - Y_POINT_NINE)


def thermal(n, recoil_over_trap):
    return exp(-2 * recoil_over_trap * (2 * n + 1))


def contrast_ratio(cold, hot):
    return exp(-4 * RECOIL_KHZ * (hot - cold) / TRAP_KHZ)


def verify_source(path):
    pdf = path.read_bytes()
    if sha256(pdf).hexdigest() != PAPER_SHA:
        raise ValueError("This extraction uses the cited byte-exact publisher PDF.")
    # In this specific PDF object 64 is a FlateDecode RGB image without a
    # predictor. Restrict parsing to the pinned file and verify its pixel hash.
    stream = re.search(rb"(?:\r|\n)64 0 obj\s*<<[^>]*>>\s*stream(?:\r\n|\n|\r)", pdf)
    if stream is None:
        raise ValueError("Figure 4 stream was not found.")
    pixels = zlib.decompress(pdf[stream.end():])
    assert len(pixels) == 1752 * 904 * 3 and sha256(pixels).hexdigest() == PIXEL_SHA

    def red(x, y):
        start = 3 * (1752 * y + x)
        r, g, b = pixels[start:start + 3]
        return r - g > 96 and r - b > 70 and g < 150

    for x, y in MARKERS:
        # Some marker pixels are occluded by the drawn curve. Confirm that a
        # neighborhood of each transcribed center is filled, not just a line.
        assert sum(red(i, j) for i in range(x-5, x+6) for j in range(y-5, y+6)) >= 60
    # Edge checks allow the antialiasing of the printed error bars.
    for (x, y), y_bar, x_bar in (
        (MARKERS[0], COLD_Y_BAR, COLD_X_ENVELOPE),
        (MARKERS[-1], HOT_Y_BAR, HOT_X_BAR),
    ):
        for edge_x, edge_y in [(x, v) for v in y_bar] + [(v, y) for v in x_bar]:
            assert any(red(i, j) for i in range(edge_x-2, edge_x+3)
                       for j in range(edge_y-2, edge_y+3))
    print("Verified original PRL PDF, Figure 4 RGB stream and marker/error-bar pixels.")


def report():
    print("Fig 4(b)    occupation  measured V  predicted V  measured - predicted")
    points = [(occupation(x), fringe(y)) for x, y in MARKERS]
    eta_squared = RECOIL_KHZ / TRAP_KHZ
    for i, (n, v) in enumerate(points, 1):
        predicted = thermal(n, eta_squared)
        print(f"{i:8d}    {n:10.3f}  {v:10.3f}  {predicted:11.3f}  {v-predicted:+.3f}")

    cold, hot = points[0], points[-1]
    measured = hot[1] / cold[1]
    predicted = contrast_ratio(cold[0], hot[0])
    measured_low = fringe(HOT_Y_BAR[1]) / fringe(COLD_Y_BAR[0])
    measured_high = fringe(HOT_Y_BAR[0]) / fringe(COLD_Y_BAR[1])
    predicted_low = contrast_ratio(occupation(COLD_X_ENVELOPE[0]), occupation(HOT_X_BAR[1]))
    predicted_high = contrast_ratio(occupation(COLD_X_ENVELOPE[1]), occupation(HOT_X_BAR[0]))
    print(f"Hot/cold measured {measured:.4f}, vertical bar envelope [{measured_low:.3f}, {measured_high:.3f}]")
    print(f"Hot/cold predicted {predicted:.4f}, horizontal envelope [{predicted_low:.3f}, {predicted_high:.3f}]")
    print(f"36 kHz unsqueezed zero-temperature visibility {thermal(0, eta_squared):.4f}")
    eta, u_eta = 0.316, 0.001  # Cheng et al., 2026 preprint, Eq. S11
    v0 = thermal(0, eta**2)
    print(f"2026 calibrated eta reference {v0:.5f} +/- {4*eta*v0*u_eta:.5f}")
    assert measured_low < predicted < measured_high and predicted_low < measured < predicted_high
    assert 0.06 < cold[1] - thermal(cold[0], eta_squared) < 0.08


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source", type=Path, help="verify the cited publisher PDF")
    args = parser.parse_args()
    if args.source:
        verify_source(args.source)
    report()
replay.py
"""Replay the shell clock and gravitational stress study using standard Python and a pinned Tally runtime."""
import argparse
import hashlib
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from zipfile import ZipFile

ROOT = Path(__file__).resolve().parent
RUNTIME_SHA = "61cebdbf05b33b1ebeac92de12a750940c0995986374ecbdca12ac79658b6cff"
ATOM_SHA = "4c08a122480cb2d6c1efb48b9e868b5b45432d78dc40b339dbe9db7ebdacf02d"


def checked(path, expected):
    data = path.read_bytes()
    if hashlib.sha256(data).hexdigest() != expected:
        raise ValueError(f"SHA-256 mismatch for {path.name}")
    return data


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("runtime", type=Path, help="published Tally 0.3.0 runtime ZIP")
    parser.add_argument("--full", action="store_true", help="also run the three-dimensional bound-pair integrals with NumPy")
    args = parser.parse_args()
    checked(args.runtime, RUNTIME_SHA)
    lib = ROOT / "lib/atom.tly"
    if not lib.is_file():
        lib = ROOT.parent / "walk-clock-recoil/tally/lib/atom.tly"
    atom = checked(lib, ATOM_SHA)
    python = [sys.executable, "-E", "-s", "-B", "-X", "utf8"]
    for script in ("gates", "pulse_order", "packet_3d", "material_bracket", "cesium_band", "cell", "shell", "nested", "breathing", "rod", "pressure", "constrained", "pressure_wave", "tensor_rotor", "clocks_data", "contact_reference", "reference_scattering", "free_reference",
                   "improved_contact", "virtual_contact", "moving_bound", "pair_shapes", "reference_data"):
        subprocess.run([*python, str(ROOT / (script + ".py"))], check=True)

    if args.full:
        import os
        environment = dict(os.environ, OPENBLAS_NUM_THREADS="1")
        subprocess.run([sys.executable, "-B", str(ROOT / "bound_3d.py")], env=environment, check=True)

    with tempfile.TemporaryDirectory() as work_path:
        work = Path(work_path)
        with ZipFile(args.runtime) as runtime:
            runtime.extractall(work)
        tally = work / "Tally-0.3.0"
        (tally / "lib/atom.tly").write_bytes(atom)
        shutil.copyfile(ROOT / "clocks.tly", work / "clocks.tly")
        result = subprocess.run([*python, str(tally / "tally.py"), "clocks.tly"], cwd=work,
                                stdout=subprocess.PIPE, check=True)
        actual = result.stdout.decode("utf-8").splitlines()
        expected = (ROOT / "clocks.out").read_text(encoding="utf-8").splitlines()
        if actual != expected or sum(line.startswith("✓") for line in actual) != 55:
            raise ValueError("Tally output differs from the 55 published checks")
    count = "twenty-four" if args.full else "twenty-three standard-library"
    print(f"All {count} calculations and the complete 55-assertion Tally transcript passed.")


if __name__ == "__main__":
    main()
clock_plot.py
"""Plot Zheng et al. (2023), Supplementary Table 1, with its total error bars.

Optional figure build: python3 clock_plot.py (matplotlib and Pillow).
Data checks in clocks_data.py require only the standard library.
"""
from io import BytesIO
from pathlib import Path

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from PIL import Image

from clocks_data import ENDPOINT, HALF_HEIGHT, SLOPE


# Pair ordering within each set is top-to-bottom at the same nominal spacing.
# Corrected fractional frequency and total uncertainty, both in 1e-19 units.
PAIR_GROUPS = (
    (0.25, ((-2.71, 1.98), (-4.68, 1.99), (-2.04, 1.96), (-2.52, 2.02))),
    (0.50, ((-7.23, 2.18), HALF_HEIGHT, (-6.22, 2.19))),
    (0.75, ((-7.91, 2.52), (-8.90, 2.50))),
    (1.00, (ENDPOINT,)),
)


def main():
    fg, secondary, teal, grid = '#1d2831', '#455664', '#006f6e', '#e3e8ea'
    with plt.rc_context({'font.size': 9, 'text.color': fg, 'axes.labelcolor': fg,
                         'xtick.color': secondary, 'ytick.color': secondary}):
        fig, ax = plt.subplots(figsize=(4.20, 3.78), dpi=100)
        fig.subplots_adjust(left=.16, right=.97, top=.75, bottom=.26)
        fig.text(.07, .94, 'Clock redshift over one centimetre', fontsize=13.8,
                 weight='bold', ha='left')
        fig.text(.07, .86, 'Fractional frequency shift  (×10⁻¹⁹)', fontsize=10)
        ax.plot([0, 1.04], [0, SLOPE*1.04], color=fg, lw=1.6,
                label='Gravimeter prediction', zorder=2)
        for i, (height, values) in enumerate(PAIR_GROUPS):
            for j, (v, err) in enumerate(values):
                x = height + .021*(j-(len(values)-1)/2)
                ax.errorbar(x, v, yerr=err, fmt='o', ms=4.2, color=teal, lw=1.2,
                            capsize=2, zorder=3,
                            label='Clock pair ±1σ' if (i, j) == (0, 0) else None)
        ax.set(xlim=(0, 1.07), ylim=(-16, 2), yticks=[-15,-10,-5,0],
               xticks=[0,.25,.50,.75,1.0], xticklabels=['0','0.25','0.50','0.75','1.00'],
               xlabel='Nominal height difference (cm)')
        ax.grid(axis='y', color=grid, lw=.8)
        ax.tick_params(length=0, pad=5)
        for spine in ax.spines.values():
            spine.set_visible(False)
        ax.legend(loc='lower left', frameon=False, handlelength=1.65,
                  borderpad=0, fontsize=8.3, labelspacing=.3)
        fig.text(.07, .090, 'Shared clocks correlate the ten pairs. Symbols at each',
                 fontsize=8.4, color=secondary)
        fig.text(.07, .047, 'height are spread for visibility. Zheng et al., Table S1 (2023).',
                 fontsize=8.4, color=secondary)
        output = BytesIO()
        fig.savefig(output, format='png', facecolor='white')
        plt.close(fig)
    output.seek(0)
    with Image.open(output) as raster:
        raster.convert('RGB').quantize(colors=128, dither=Image.Dither.NONE).save(
            Path(__file__).with_name('clock_redshift.png'), optimize=True)


if __name__ == '__main__':
    main()
Back to contents ↑

Independent research by Anthony Michael Collado.
Clocks, shell mass and stress · 1 December 2026

Bonds and gravity → · Study sources (ZIP) ↓