Skip to content

Can the walk’s clocks source gravity?

Reversing two local clock pulses excites a bound pair at rest. Three interferometers provide an independent measurement of what a tensor wave must reproduce.

What the model explains

The proposal is that a microscopic local evolution could give rise to matter, clocks and the spacetime they measure. The walk supplies bound states with a measurable dispersion and an internal response to local clock pulses. A separate lattice model propagates two tensor polarizations. Joining these results requires the same matter that reads a clock to supply a conserved gravitational source.

The clock test exposes a failure of that join. A common local change to the energy density reduces unwanted internal excitation for two contacts. A moving pair still generates the wrong spatial shift. The nonlinear constraint calculation states what a successful replacement must reproduce. The wave calculation uses an independently specified gravitational coupling. The three-detector comparison measures an actual strain record.

Geometry supplies a second check with fewer assumptions. The three-dimensional covering theorem applies directly to the filled convex hull of walk endpoints. Counting at a fixed shrink factor lets the detector distinguish readout intervals. One shift versus seven · State of the theory

Can reversing two clock pulses excite a pair at rest?

Sections in this chapter

A spatial translation can give a moving momentum state a phase. A pair with zero total momentum is unchanged, including its internal state. In the ordered three-dimensional walk, four weak local clock pulses in a closed sequence leave the rest pair with zero mean phase but a nonzero probability of internal excitation. At wave number q = 0.05 the coefficient of that loss is 0.021896 per fourth power of the pulse area. It comes entirely from the contact interaction. Restricting every intermediate state to the original bound band would miss the effect.

Apply the two lapse patterns to the constituents

Use the published Hamiltonian H = h_A+h_R+V with distinguishable walkers, h from the ordered three-dimensional Clifford model, and onsite V = g δcoincidence U. The density contact uses U = I, the mass contact U = β⊗β. Both have rest energy 1.900 and the same normalized rest wavefunction. Use the same endpoint energy coupling as in the earlier finite-wavelength source test. A hopping term samples the average of the lapse at its two ends and a collision samples its own cell. In cell units with ℏ = 1, the positive Fourier component of the local clock energy is

A(q) = {exp(iq Z_A),h_A}/2 + {exp(iq Z_R),h_R}/2 + exp(iq Z_A)V.
A(−q) = A(q)†,                  A(0) = H.
C = [A(q)+A(−q)]/2,            S = [A(q)−A(−q)]/(2i).
B = i[C,S] = [A(−q)A(q) − A(q)A(−q)]/2.

Braces denote the anticommutator. C and S are the generators for cosine and sine lapse patterns along z. Here the local energy is assigned separately to each constituent; a single center-of-mass lapse multiplying the total Hamiltonian would be a different control. Local constituent energy

Apply the loop exp(−iθC) exp(−iθS) exp(iθC) exp(iθS), with the rightmost operation first. The common pulse area is θ. The loop acts as 1+iθ²B+O(θ³). Comparing the return amplitude with an unpulsed copy measures the phase θ²⟨B⟩ to leading order. Testing survival in the initial state measures θ⁴ Var(B) to leading order. B preserves total crystal momentum, so loss at this order changes the internal state. It may include other bound states or continuum states. A geometric normal-deformation bracket in a flat background would generate the uniform shift fixed by cos(qz)∂z sin(qz)−sin(qz)∂z cos(qz) = q. With the stated sign and speed-one normalization this would give B = qPz, with no internal loss at any momentum. Teitelboim on the hypersurface-deformation algebra

The unprojected and band-restricted loops give different answers

For incoming bound state ψ of momentum K, form both complete intermediate states χ± = A(±q)ψ. The sudden commutator phase coefficient is exactly (‖χ₊‖²−‖χ₋‖²)/2. The replay applies each constituent hopping to its own momentum and each contact to the full coincident 16-spin amplitude. It sums over all relative momenta. Applying the second pulse without truncating those states gives Bψ and its norm. No fitted transition matrix or high-energy cutoff is used.

For comparison, project χ± onto the original isolated band at K±q. The corresponding phase coefficient replaces each norm squared by |⟨ψ(K±q)|A(±q)|ψ(K)⟩|². These off-diagonal energies are recalculated at the actual incoming and outgoing momenta. An elastic matrix element from symmetric momenta −q/2 and +q/2 alone cannot provide them.

KzqFull ⟨B⟩/q, densityBand only, densityFull ⟨B⟩/q, massBand only, massUniform shift
0.050.050.0721810.0717390.0684250.0680230.050000
0.100.100.1461080.1325130.1380830.1312970.100000
0.100.050.1459300.1446430.1378960.1368140.100000
0.100.0250.1458860.1455910.1378490.1375940.100000

A superposition of opposite momenta acquires a relative phase of 2θ²⟨B⟩ by inversion. At |K| = 0.10 and q = 0.05 that coefficient is 0.014593 for the density contact and 0.013790 for the mass contact, compared with 0.010000 for the uniform shift. Reversing the loop reverses the leading phase. A band-restricted operation assumes that the pulse protocol suppresses transitions to other states, for example by spectral filtering. The measured action of a particular slow pulse also depends on its envelope, virtual energy shifts and the available gaps. The sudden calculation assumes signed control pulses with the unperturbed evolution removed or compensated.

The local energy continuity equation itself passes. Define the bond current from the change of endpoint energy, so i[H,A(q)] = 2i sin(q/2) J(q), with any longer hop counted across every intervening cell face. Between two eigenstates, the current is their energy difference times the energy matrix element divided by 2 sin(q/2). The explicit H acting on the complete intermediate state reproduces this identity. For K = 0.10 to 0.15 it gives 0.184212 for density and 0.173490 for mass in the smooth real-overlap convention. In the forward limit both loop means divided by q tend to E(K)∂E/∂K: the intraband form factor has midpoint value E + O(q²) in magnitude, and the other-band amplitudes vanish linearly with q. At K = 0.10 the forward values are 0.145871 and 0.137833. A conserved energy current therefore does not establish a common generator of spatial translations. Earlier symmetric-source test

Why the collision is visible at rest

Inversion makes B odd, hence ⟨B⟩ = 0 at rest. The projected band at K = 0 contains a single isolated state in this channel, so its commutator annihilates that state. In the complete microscopic calculation either contact gives Var(B)/q² equal to 8.74180, 8.75838 and 8.76253 at q = 0.10, 0.05 and 0.025, respectively.

The free cancellation is exact. A one-body contribution at momentum p is [(h(p+q)+h(p))²−(h(p−q)+h(p))²]/8, with q along z. Each square is scalar in spin by the Clifford algebra. Inversion makes their difference odd in p. The two free contributions at p and −p consequently cancel on the entire total-momentum-zero fiber. The contact-contact commutator also vanishes. The two remaining terms have an instructive separation. When the contact acts first its output is the same coincident source v for either interaction. The difference of the following hopping terms has zero average over relative momentum, since shifting the periodic hopping symbol leaves its integral unchanged. Its position-space amplitude therefore vanishes at coincidence. The term in which the contact acts last is supported only at coincidence. Changing I to β⊗β preserves its norm there. These two components are orthogonal, which explains the equal total loss at rest for the two contacts.

The signal persists at long wavelength. At final relative momentum zero the contact-first component is (sin q)/2 times [αz v + v αzᵀ], where αz is the z-direction Dirac matrix and v is represented as a four-by-four matrix in the two constituent indices. The ++ and −− orbital-singlet coefficients of v have unequal magnitudes, with over 97% of the coincident source weight in ++. The displayed spin sum is nonzero. Its smooth neighborhood gives a positive limit of Var(B)/q². A uniform translation gives zero for every q and every common shift speed.

One can also shift the energy origin by c per pair and couple half that shift to each local constituent number. At rest for the density contact and q = 0.05, Var(B)/q² becomes 8.758385 − 2.146802c + 0.773076c². This dependence is quadratic because the two number-density patterns commute, so B itself is affine in c. Solving once more at the minimizing c = 1.388481 gives 7.267989, above zero. This test permits a common constant frequency origin with that number coupling. Changing the microscopic local energy assignment, adding degrees of freedom of a moving or gravitating medium, or using different dressed observables would require new pulse generators and a fresh closure test.

Replay the internal-state readout

The 64³ integration resolves the Brillouin torus of the ordered pair. Refinement from 56³ changes the three quoted rest variances divided by q² by less than 0.000002. A separate eight-cell-per-axis torus uses the physical one-particle momentum grid, two-particle wavefunctions and four finite-duration unitary pulses. At its own commensurate q = π/2 and its own rest-matched coupling, the independent commutator predicts loss/θ⁴ of 3.82220 in the weak limit. Direct evolution gives 3.99090, 3.86475 and 3.83286 as θ decreases through 0.0100, 0.0050 and 0.0025. The two calculations check the pulse ordering and normalization at identical finite volume.

Run python lapse_loop.py 40 --unitary --origin with NumPy for all controls. Use --fine for the 64³ grid. The only other files needed are the published bound-pair and form-factor helpers. The experiment tests one proposed matter generator before adding gravitational dynamics. Replay the lapse commutator

How often does the clock loop excite a resting pair?

Choose one of the computed wave numbers and set the area of each of the four weak pulses. The predicted loss is θ⁴ Var(B) to leading order in θ. Both contact models give the same total at rest.

Leading excitation probability 1.36850 × 10⁻⁷ per loop.

Where does the clock loop put the excitation energy?

Sections in this chapter

The sudden lapse loop deposits the same total excitation probability in two rest pairs. Their energy distributions differ. With a Gaussian energy acceptance of width 10 in model units, 59.69% of the deposited weight passes for the density contact and 78.42% for the mass contact. At width 1 the fractions are about 1% for each. An ideal probe tuned exactly to zero energy transfer has no accessible internal final state. This distinction matters when a fast pulse calculation is compared with a slow detector. Pulse sequence and energy assignment

Read the spectrum of the deposited state

Let |b⟩ be the simple exchange-odd pair pole of energy E_b = 1.900 at zero total momentum. At q = 0.05 the commutator B from the preceding chapter creates a rest-frame internal excitation vector u = B|b⟩/q, orthogonal to the input. If H is the full two-walker Hamiltonian with its contact retained, define the deposited spectral measure and its Gaussian acceptance by

dμ(Δ) = ⟨u| dP(H−E_b; Δ) |u⟩,
W(τ) = ∫ exp(−τ²Δ²) dμ(Δ).

Here dP is the spectral projection and Δ is the signed final energy minus E_b. W(0) is the total deposited weight per q²θ⁴ in the weak sudden loop. The acceptance drops to 1/e at |Δ| = 1/τ. It can describe an energy analysis of the deposited state. It also gives the leading transition probability per squared area of a separate weak drive proportional to B/q with a unit-area Gaussian time envelope of standard deviation τ. Its Fourier amplitude is exp(−τ²Δ²/2). Generating that effective operator and resolving its spectrum are separate experimental assumptions. Four individual finite-duration cosine and sine pulses sample their own intermediate energies and time orderings; their slow-pulse loss cannot be inferred by multiplying the sudden loss by this one filter.

Time scale τW, densityW, massAccepted density fractionAccepted mass fraction
08.7583858.75838511
0.15.2275336.8683550.5968600.784203
0.51.3080681.3031500.1493500.148789
10.08987220.08789110.01026130.0100351
20.000732050.000365270.000083580.00004171
40.000098170.000056600.000011210.00000646

The input and deposited norm agree for the two contacts. The deposited amplitudes that end at coincidence can differ in sign, and the final Hamiltonian acts differently there. On the odd coincident orbital spinor β⊗β acts as minus the identity, so the two effective interaction strengths have opposite signs. The table integrates a common energy window with no fit or assumed density of states.

A gap survives in the full model

At zero total momentum the free pair at relative momentum p has only three distinct signed energies: −2e(p), 0 and +2e(p), where e² = |b(p)|² + M(p)² and M ≥ 1 is the one-body mass term. An interacting pole inside (0,2) must solve the coincident Green-function equation. For any unit inversion-odd coincident spinor d, the two β mass terms cancel. The remaining free Hamiltonian H_f connects opposite orbital parity at fixed p. Hence ⟨d|H_f|d⟩ = 0 and ‖H_f d‖ ≤ 2|b|. In particular its positive and negative signed-energy weights at each p agree.

For G(E), the coincident resolvent of H_f, the three free energies give the following expression just below threshold. The brackets average over the Brillouin zone.

⟨d|G(2−)|d⟩ = (1/2) [1 − ⟨ ‖H_f d‖² / (4(e²−1)) ⟩].

The integrand is at most 1. On seven eighths of the zone at least one cos pᵢ is nonpositive. There M ≥ 5/3 and |b| ≤ 1, so the integrand is at most 9/25. The threshold Green operator thus exceeds or equals (7/25) times the identity on the odd coincident space. G decreases with E throughout (0,2); both inverse contact strengths in this sector are approximately +0.12502 or −0.12502, below 7/25. Neither interaction creates an odd pole in this interval. A wave with no coincident amplitude would be free and has no eigenvalue there either.

Every energy in the deposited state therefore satisfies |Δ| ≥ 0.100. This gives the conservative bound W(τ) ≤ W(0) exp(−0.01τ²) and proves disappearance of the zero-frequency response. The actual suppression is stronger over the tabulated range because most of the excited weight lies well away from its nearest allowed energy.

Compute the full spectral weight

The z-directed perturbation of the rest pole selects a single odd coincident spin channel by reflection and exchange symmetry. For every equal-energy free shell the code verifies that the coincident projection of both the source and its contact partner stays in this channel. Within each shell only the projections of these two vectors are needed; vectors orthogonal to both do not contribute. The resulting exact finite-mesh Hamiltonian acting on the generated states has the form diag(L) + g_eff D D†, where L contains signed free energy gaps relative to E_b and D is the normalized coincident spinor expressed in the shell basis. Every relative momentum, including high-energy modes, contributes.

The table uses a 64³ mesh. Refining from 40³ to 64³ changes the largest quoted accepted fraction by less than 0.0000004. A Chebyshev interpolation of the Gaussian on a containing spectral interval has an analytic absolute weight-error bound below 2 × 10⁻¹⁸ in exact arithmetic. Floating-point error is separate. Diagonalizing the full 432-dimensional spin and momentum matrix on a 3³ mesh independently reproduces all six filtered weights there within 2 × 10⁻¹⁵.

Run python loop_spectrum.py 64 with NumPy. The helper rest_spectrum(mesh, q, contact, steps) returns signed energy gaps and unnormalized weights from Lanczos quadrature. Its q = 0 option uses the analytic derivative of the hopping symbol and gives the limit B|b⟩/q. Individual finite-step quadrature nodes can be used to calculate moments; locating an eigenstate in a gap requires a separate pole check. Replay the spectral calculation

Can a different local clock coupling protect the pair at rest?

Sections in this chapter

The cell-by-cell energy determines what a spatially patterned clock pulse does. Its sum fixes the flat Hamiltonian. This leaves room to change the response to a nonuniform pulse while preserving the original energies. We fit one finite-range prescription to the rest excitations of both contacts. It lowers their long-wavelength loss to 39.21% of the original value for the density contact and 50.58% for the mass contact on a finer validation grid. The moving pairs still give different phases for the same proposed spatial translation.

Change the pulse Hamiltonian locally

Let hₓ be the constituent hopping and collision energy assigned to cell x in the original endpoint prescription, with H = Σₓ hₓ. Write ad_H O = [H,O]. Replace hₓ by

h′ₓ = p(ad_H²/80²) hₓ,        p(x) = 1 + c₁x + ⋯ + c_d xᵈ.

The scale 80 is in model energy units and fixes the numerical convention for the coefficients. Even powers of the commutator preserve Hermiticity. Since [H,H] = 0, the new cell energies still sum exactly to H. Each commutator only brings in Hamiltonian terms whose supports intersect the existing operator. All original hoppings span at most two coordinate cells in any direction and the contact is onsite. A degree-three prescription uses at most six nested commutators and its support fits within 14 coordinate cells of the assigned center, including the original hopping endpoints. This local law generally needs spin and interaction terms beyond a simple reweighting of the original bonds.

Between exact energy eigenstates of energies Eᵢ and E_f the clock-energy matrix element is multiplied by p([(E_f−Eᵢ)/80]²). Thus every elastic matrix element, even at finite momentum transfer, is preserved exactly. This prescription changes what the apparatus drives. It differs from accepting only certain final energies after applying the original loop. Original finite-wavelength vertex · Energy analysis of the original excitation

Fit the rest loss, then freeze the coefficients

For a rest pair |b⟩ of energy E_b = 1.900, the long-wavelength defect vector is u = lim B(q)|b⟩/q, where B = i[H[cos(qz)],H[sin(qz)]]. To see how it changes, expand the energy Fourier component as H+iqD+O(q²). The limiting commutator is i[H,D]. Improving the density replaces D by p(ad_H²/80²)D and therefore gives

u′ = p([(H−E_b)/80]²) u.
Rest loss fraction = ‖u′‖²/‖u‖².

For each degree we minimize the mean of that fraction for the two contacts, with equal weights. Training uses the analytic q→0 source on a 24³ momentum mesh. A 32-step Lanczos quadrature integrates the training moments because the squared cubic has degree at most 12 in the signed energy gap. Once determined, the same polynomial is used for both contact Hamiltonians and every validation mesh. “Same” means the same functional rule and coefficients applied to each actual interacting H.

DegreeDensity-contact loss fraction, 64³Mass-contact loss fraction, 64³
10.5254160.633973
20.4172950.552040
30.3921150.505821

The fitted joint cubic is p(x) = 1 − 86.96842194x + 627.12759591x² − 935.88423846x³. Refining the validation grid from 36³ to 64³ changes the cubic loss fractions by less than 0.000002. Training on a single contact gives a transfer test. The density-trained cubic yields fractions of 0.364443 for density and 0.566524 for mass. The mass-trained cubic yields 0.356098 for mass but 2.08367 for density. Minimizing loss on one internal spectrum can more than double it on another.

These are weighted fits, so they allow large gain where little rest-state weight lies. At signed energy gap 60 the joint cubic multiplies a matrix element by −16.06. A more restrictive prescription p(x) = (1−x/4)³ stays between zero and one for all transition gaps allowed by this two-particle Hamiltonian, whose norm is below 80 in the unshifted convention. At degree three it retains 98.51% of the density loss and 99.38% of the mass loss. In the rest-defect channel the preceding spectral calculation establishes |E_f−E_b| ≥ 0.100. On its bounded spectrum, taking higher powers of this bounded polynomial can suppress that particular leakage arbitrarily strongly at the price of increasing range. No fixed modest range or broad experimental success follows from that limiting argument.

Apply both improved pulses at finite wavelength

At finite q the first pulse creates a superposition of many internal energies. Filtering the final defect vector would generally give the wrong answer for the changed apparatus. We apply the improved operator to both legs of each product B = [A(−q)A(q)−A(q)A(−q)]/2. For the second leg the code expands each nested commutator binomially, acting with the incoming Hamiltonian on the right and the outgoing Hamiltonian on the left. On a periodic n³ box q = 2π/n transfers exactly one grid momentum.

Cells per axisqDensity-contact loss fractionMass-contact loss fraction
160.3926990.536450.39633
240.2617990.441670.44347
320.1963500.416460.46779

Each ratio compares the changed and original pulses at the same finite volume, with g fixed by the same rest pole within that volume. Both wavelength and volume change between rows. To isolate volume dependence, keep q = 2π/24 fixed and double the box from 24 to 48 cells per axis. The density fraction changes from 0.441669 to 0.441635 and the mass fraction from 0.443470 to 0.443356. A separate 3³ test diagonalizes the three full 432-dimensional Hamiltonian blocks, multiplies each individual transition matrix element by the cubic, and reproduces the binomial two-leg calculation. The zero-wave-number result also agrees with a separate direct application of the polynomial to all 16 spin components at each relative momentum.

What cannot change with this prescription?

The forward diagonal matrix element of the limiting commutator is unchanged since p(0) = 1. For the bound band it remains E(K)∂E/∂K. Equivalently, the intraband lapse vertex near zero transfer gains a factor 1+O(q²), and other-band amplitudes still start at order q. The geometric benchmark is a common translation with coefficient K on the same rods. At K = 0.10 the forward values are 0.145871 and 0.137833 for density and mass. Applying the improved pulses at q = 0.0125 gives 0.145880 and 0.137836 on a separate 40³ mesh, already close to the distinct forward limits. Neither fitting away some rest excitations nor preserving elastic form factors supplies the missing common translation generator. The construction tests local matter-clock couplings with a fixed unperturbed H. A theory with dynamical geometry would need its own full set of generators.

Run python energy_improvement.py --fine --finite with NumPy to repeat the fitting, the independent state-vector checks and the finite-periodic-box pulses. Replay the counterterm calculation

Which local lattice can carry two gravitational waves and a Newtonian field?

Sections in this chapter

A periodic cube with six spatial metric components per cell can carry two tensor waves and a constrained Newtonian potential. Its local Hamiltonian specifies both their dynamics and which matter sources it accepts. Adding energy at one site without the corresponding current produces an immediate, calculable constraint violation. The earlier tensor-rotor calculation obtained quadratic or cubic wave dispersion from positive rotor energies. The construction here obtains linear dispersion at long wavelengths by supplying the lapse, shift, and quadratic Einstein Hamiltonian explicitly. These are additional microscopic inputs for the walk. Earlier rotor and pressure calculations

A difference operator that sees the edge of the frequency band

Use continuous time, lattice spacing a, signal speed c = 1, and flat signature (−,+,+,+). Put the lapse perturbation n, the density ρ and the three diagonal metric components hᵢᵢ on vertices. Put the shift Nᵢ and current jᵢ on links directed along i. An off-diagonal hᵢⱼ occupies the center of the face in directions i and j. Its momentum πᵢⱼ and applied stress Sᵢⱼ have the same location. Each field component still has one value per cell.

Dᵢ takes the difference of the two neighboring values straddling its output, divided by a. Acting on site values gives a link derivative. Acting along that link again gives the backward difference on the site grid. The same rule toggles a half-cell displacement along i for every component. Differences commute and periodic sums obey integration by parts. With each Fourier amplitude referred to its physical position, the symbol is iQᵢ, where Qᵢ = 2 sin(kᵢa/2)/a. Consequently Δ = Σᵢ Dᵢ² is the nearest-neighbor Laplacian and the only zero of −Δ in the first Brillouin zone is the uniform mode. A pattern alternating at every site has maximal axial frequency.

The canonical field and its sources

Write α = 16πG and I for the three-dimensional identity. The physical action is the cell-volume sum of (π:ḣ − ℋ)/α, integrated over time. A colon between symmetric tensors denotes contraction over both indices, counting the two equal off-diagonal entries. The trace of h is hₜ and the trace of π is πₜ. Define the linear spatial scalar curvature R and Einstein tensor G³ by

R = DᵢDⱼ hᵢⱼ − Δhₜ
2 G³ᵢⱼ = DᵢDₖ hₖⱼ + DⱼDₖ hₖᵢ − Δhᵢⱼ − DᵢDⱼ hₜ − δᵢⱼ R .

The local Hamiltonian density, including a prescribed source, is

ℋ = π:π − πₜ²/2 + h:G³(h)/2
    − n R − 2 Nᵢ Dⱼ πᵢⱼ + α (nρ − Nᵢjᵢ − h:S/2).

The spacetime perturbations are h₀₀ = −2n and h₀ᵢ = Nᵢ. The source term follows by coupling hμν Tμν/2 with the source indices raised in the action, with T⁰⁰ = ρ, T⁰ⁱ = jᵢ and Tⁱʲ = Sᵢⱼ. Varying lapse and shift gives four constraints. Varying π and h gives the evolution.

C = R − αρ = 0                         Mᵢ = −2 Dⱼπᵢⱼ − αjᵢ = 0
ḣᵢⱼ = 2πᵢⱼ − δᵢⱼ πₜ + DᵢNⱼ + DⱼNᵢ
π̇ᵢⱼ = −G³ᵢⱼ + (DᵢDⱼ − δᵢⱼΔ)n + αSᵢⱼ/2 .

The lapse and shift have no wave oscillators here. The first-class property follows directly from the stencils. The scalar curvature of a symmetrized gradient vanishes and the divergence of (DᵢDⱼ − δᵢⱼΔ)n vanishes. The scalar and vector constraint brackets therefore commute at this order. The physical transverse wave energy is positive even though the unreduced momentum quadratic form has a negative trace direction. This construction presupposes exact constraints. A material that merely gives violations a finite energy cost requires a further stability argument. Constraint-preserving linear gravity discretizations precede this study. Arnowitt, Deser and Misner · Di Bartolo, Gambini and Pullin · Meier on staggered constraint transport

What happens if a collision supplies the wrong current?

Direct substitution gives two local identities, valid even when the initial constraints have errors.

Ċ  = −Dᵢ Mᵢ − α(ρ̇ + Dᵢjᵢ)
Ṁᵢ = −α(j̇ᵢ + DⱼSᵢⱼ).

Thus conserved initial data and a symmetric source satisfying both continuity equations keep the constraints exactly. A unit excess in the time derivative of the density at a single site gives an excess −α there in Ċ. The source must use the same staggered divergence as the field. Merely conserving energy after summing over the box does not fix a bad local current.

The checker separately constructs all ten spacetime Einstein components from arbitrary metric fields and their first three time derivatives. At every site it checks the off-shell identity −∂ₜG₀ν + DᵢGᵢν = 0, and verifies that G vanishes on an arbitrary pure gauge hμν = Dμξν + Dνξμ. It then builds the spacetime metric from independent random canonical data and the Hamilton equations. These reproduce 2G₀₀ = R, G₀ᵢ = Dⱼπᵢⱼ and 2Gᵢⱼ = αSᵢⱼ. All these residuals vanish exactly on the chosen integer and half-integer test arrays. A directional finite difference of the quadratic Hamiltonian checks its canonical gradient independently. With α = 4 the deliberately injected unit density defect gives a residual of magnitude 4.

This is a way to reject a candidate microscopic source. The isolated moving pair previously failed a necessary long-wavelength equality between its energy flux and its translation momentum. Accepting a prescribed conserved source in these equations supplies no proof that an interacting walk produces it.

Two propagating tensor polarizations

At any nonzero Q there are twelve spatial phase-space coordinates. Four independent first-class constraints and their four gauge directions leave two canonical pairs. A vacuum representative has h and π transverse and traceless. In this sector G³ = −Δh/2, π = ḣ/2, and the Hamiltonian sum reduces to π:π + Σᵢ(Dᵢh):(Dᵢh)/4. Each polarization obeys ḧ = Δh with ω² = |Q|². The term helicity ±2 describes the rotationally invariant continuum limit. At finite spacing the wave vector, transverse subspace, and dispersion refer to the cubic grid.

The numerical rank check includes every one of the 511 nonzero momenta on an 8³ grid, including all zone-edge modes. A separate local evolution initializes both polarizations at mode (1,2,−1), with a nonzero conjugate momentum and different polarization phases. Its frequency is 1.780891034 in lattice units. The code integrates the full equations without subtracting any unwanted polarization or constraint error. At time 1.2 it compares all six metric components to the independent oscillator solution.

Time stepLargest displacement errorLargest constraint errorRelative energy change
0.040.000311039.1 × 10⁻¹⁵0.000830
0.020.000077731.0 × 10⁻¹⁴0.000208

Even with exactly two polarizations, the short-wave frequencies depend on direction. The modes (3,0,0) and (2,2,1) have equal continuum wave-number length. On the same grid their frequencies are 1.847759 and 2.141445. The two polarizations at each of these momenta remain degenerate. The spatial discretization approaches the usual isotropic wave speed for wavelengths much larger than a.

What sources the potential read by a slow clock?

For static cold matter take Nᵢ = πᵢⱼ = 0, n = Φ and hᵢⱼ = −2Φδᵢⱼ. The Hamiltonian constraint reduces to ΔΦ = 4πGρ and the entire spatial evolution equation is satisfied. The clock reads the lapse 1 + Φ. Its static tidal tensor is R₀ᵢ₀ⱼ = DᵢDⱼΦ. A conserved static stress also enters the clock equation. Taking the trace of π̇ = 0 and using R = αρ gives

Δn = 4πG (ρ + tr S).

There is an exact pressure-only control. Take a compact scalar f, subtract its arbitrary constant mode, and choose Sᵢⱼ = (δᵢⱼΔ − DᵢDⱼ)f with ρ = j = 0. Its divergence vanishes. The field hᵢⱼ = πᵢⱼ = Nᵢ = 0 with n = αf/2 satisfies all equations. These signed source perturbations would need supporting stresses or a physical background in matter.

On a 16³ periodic grid the total linear scalar curvature sums to zero. Place a unit density excess at the origin and use a compensating uniform density −1/4096. Fix the mean potential to zero and choose 4πG = 1. Inverting the grid Laplacian gives Φ(0) = −0.238630319. A direct sum of the outward differences over the boundary of the central 5³ cube gives 0.969482421875, equal to the enclosed excess 1 − 125/4096. The largest residual across the constraints, Poisson equation, and canonical time derivatives is 3.1 × 10⁻¹⁶. An isolated positive mass requires different boundary conditions or a different background.

Where the radiation energy enters

A vacuum tensor wave of amplitude ε has a positive quadratic canonical energy of order ε². Its linear Hamiltonian constraint has no term of that order. On the periodic grid, inserting the wave energy alone as an extra positive ρ would immediately contradict the integrated scalar constraint. A calculation of how gravity sources itself requires quadratic constraint terms, consistent matter backreaction, and appropriate background or boundary conditions. An asymptotically flat system can instead use its boundary flux to define the total mass. Closed spaces also have known nonlinear integrability restrictions. These facts delimit the linear replay. Deser on consistent self-coupling · Fischer and Marsden on linearization stability

Run python tensor_lattice.py with NumPy. The script constructs the local stencils directly. Only the independent static Poisson inversion uses a Fourier transform to produce a solution for checking in real space.

What does a third interferometer measure about polarization?

Sections in this chapter

Hanford, Livingston and Virgo recorded the same black-hole merger, GW170814. The difference in arrival time between three sites narrows the source to two possible directions. A reflection through the plane of the detector baselines preserves both time differences. The interferometers’ arms point in different directions, however. The measured amplitudes and phases distinguish the two timing solutions. LIGO–Virgo discovery paper · GWOSC calibrated strain, DOI 10.7935/K5MP519B

Finding both directions from the strain

We filtered the three noise-subtracted strain records with the same nonspinning binary waveform, choosing detector-frame masses of 33 and 28 solar masses. Each interferometer received its own measured noise weighting. Within the same 120 ms window we located each site's strongest match, interpolating the squared amplitude around its peak. Hanford followed Livingston by 8.385 ms, and Virgo followed Livingston by 14.701 ms. Assuming a plane wave traveling at light speed, these two differences give two sky positions. No sky coordinate from the collaboration enters this first calculation.

Position from the three peak timesRight ascensionDeclinationTensor null amplitude
Southern solution45.82°−42.44°2.50
Reflected solution51.68°−10.70°6.00

A tensor wave has two transverse strains, conventionally called plus and cross. For either sky position, the known arms and noise levels determine three detector responses to each strain. The cross product of those two three-component response vectors gives a unit vector perpendicular to both. Its dot product with the complex measured amplitudes is what would remain if any combination of the two predicted responses were removed. The table gives its magnitude in matched-filter signal-to-noise units. Both directions reproduce the timing. The relative strains fit the southern direction more closely. The weak Virgo signal limits the accuracy of single-site peak timing. LAL detector positions and responses

A fixed-sky comparison and its limits

The collaboration’s full tensor-wave analysis placed its most likely direction at 47.75°, −44.95°. That position and its exact timing reflection at 53.82°, −8.75° give the same 8.436 ms and 13.835 ms delays. Shifting each record by those delays and using the loudest Livingston match gives single-site amplitudes of 9.59, 12.77 and 4.46. The collaboration obtained 9.7, 14.8 and 4.8 with its fitted waveforms. Discovery paper, sections IV–V

Assumed detector responsesPublished tensor skySame-delay reflection
Two transverse tensor strains0.955.67
Two vector strains10.955.14
One scalar breathing strain6.505.65

The same calculation can hold out Virgo’s complex amplitude. Taking the two LIGO measurements as input gives a tensor prediction of −1.79 + 2.90i at Virgo for the southern direction and +2.12 − 0.20i for its reflection. Virgo measured −2.54 + 3.66i in the common filter convention. The amplitude is withheld in this calculation; the collaboration’s sky position used the full network.

At the published sky, the tensor null retains 0.33% of the squared network filter amplitude. At the reflected sky it retains 11.69%. Two neighboring mass choices, 31 + 26 and 35 + 30 solar masses, also give the smaller tensor residual to the south. As a noise comparison, 78 off-event windows with the same Livingston peak-selection rule give middle 80% intervals of 0.51–2.84 and 0.47–2.30 for the two fixed tensor directions. They share strain records and a noise estimate.

These residuals assume one waveform shape with arbitrary complex amplitudes for each allowed polarization. The fixed-sky comparison reuses a tensor-conditioned position. The collaboration obtained its polarization odds by integrating over source parameters and directions under explicit pure-polarization hypotheses. This simpler exercise establishes what the detector projections contribute to a directional comparison. A three-site network has only one tensor null for a specified direction; it cannot separate arbitrary mixtures of all polarizations. The walk would have to predict how a wave strains physical arms before its tensor modes could enter this test. The assumed propagation speed is a separate input.

Reproducing the calculation

Run python3 network_polarization.py to reconstruct the timing solutions, response vectors and residuals from the included complex amplitudes. To regenerate those amplitudes, run python3 network_polarization.py --from-strain DIR with NumPy, SciPy and LALSuite installed. This option downloads or reuses the three checksum-pinned 32-second records at 4096 Hz. It filters 30–300 Hz with IMRPhenomD, using a Tukey window on the record and a mean noise spectrum from two-second Hann windows outside the event. The code includes the detector tensors, the filter normalizations and the selection windows. GWOSC data and calibration notes · IMRPhenomD waveforms, Husa et al. · Khan et al.

Can a mechanical quadrupole give energy to a tensor wave and take it back?

Sections in this chapter

A single mechanical oscillator and a finite box of gravitational-wave modes can exchange energy through a reciprocal, positive-energy Hamiltonian. Release the oscillator with the field initially still. At a fixed time, 0.13641 units of energy appear in the transverse tensor modes out of an initial 0.72. Conversely, an initially displaced tensor mode drives the oscillator, with a strength that depends on its polarization. A separate calculation in unbounded space predicts the energy radiated by a smooth finite pulse.

A local conserved source with a measured quadrupole

Use c = 1. Let S be a fixed symmetric trace-free tensor with S:S = 1. The mass-normalized mechanical coordinate Q has unit inertia and bare frequency Ω. Let W be a unit-integral isotropic Gaussian in space, with Fourier transform W(k) = exp(−σ²k²/2). Specify the following signed perturbations about a supporting material background. All stress indices below are raised.

δT⁰⁰ =  Q Sᵢⱼ ∂ᵢ∂ⱼW/2
δT⁰ⁱ = −Q̇ Sᵢⱼ ∂ⱼW/2
δTⁱʲ =  Q̈ Sᵢⱼ W/2 .

Differentiation gives ∂μδTμν = 0 for any history Q(t). On unbounded space, two integrations by parts give zero perturbed mass, zero dipole, and ∫(xᵢxⱼ − δᵢⱼr²/3)δT⁰⁰ d³x = QSᵢⱼ. Independent Gaussian quadrature checks these moments. This source specifies a collective material displacement to first order. Its signed density perturbation alone need not be nonnegative. The oscillator Hamiltonian and its inertia are additional physical inputs.

The linear tensor coupling is half the contraction of the metric perturbation with the stress. In transverse traceless (TT) gauge it gives Q̈∫W h:S d³x/4, equivalent under time integration by parts to −Q∫W E:S d³x/2, where the measurable tidal tensor is Eᵢⱼ = R₀ᵢ₀ⱼ = −ḧᵀᵀᵢⱼ/2. This ties the quadrupole to curvature and gives the same vertex for emission and absorption. The leading quadrupole radiation formula also follows from the graviton emission calculation of Goldberger and Rothstein. Their Eq. 31

Count the real modes once

Put the Gaussian in a periodic cube using its periodized profile. For every unordered pair of opposite nonzero wave vectors use real sine and cosine spatial modes normalized to unit squared integral. At each wave vector the two TT polarization tensors ε have ε:ε = 1. For a unit spatial mode with coordinate x, the metric amplitude is √(32πG) εx. The radiation-sector Lagrangian is

L = (Q̇² − Ω²Q²)/2 + Σα (ẋα² − kα²xα²)/2 + Q̇ Σα gα ẋα .

A complex traveling mode normalized by 1/√V has g = −√(2πG/V) W(k)(ε:S), with the usual reality condition relating opposite wave vectors. In the real basis the cosine coupling is √2 times this value and the sine coupling is zero because the centered Gaussian is even. Modes perpendicular to the source polarization can also have zero coupling. The calculation fixes the homogeneous shape of the box and omits k = 0. The integrated spatial stress could drive that homogeneous shape if it were dynamical. In infinite space the radiated energy spectrum has a factor k⁶ and vanishes at zero frequency.

The kinetic energy is positive precisely when Σg² < 1, as follows by completing the square in the field velocities. The total energy is the sum of the bare mechanical energy, the positive bare field energy, and the cross term Q̇ Σgẋ. The two equations of motion are Q̈ + Ω²Q = −Σgẍ and ẍα + kα²xα = −gαQ̈. Specifying just the radiation sector leaves the longitudinal field and static self-energy matching outside this calculation.

Free release and reciprocal excitation

Choose L = 4π, Ω = 1.2, σ = 0.6, G = 0.15 and S = diag(1,−1,0)/√2 in the stated normalized units. Release Q = 1, with every field displacement and every velocity zero. No drive acts afterward. Two calculations propagate to time 6. One diagonalizes exact normal modes after combining degenerate field frequencies. The other integrates the individual cosine polarizations in canonical position and momentum using a symplectic time step.

Largest wave-vector label lengthCosine polarization coordinatesΣg²Mechanical energyTensor-mode energyInteraction energy
69240.03568130.592328300.13639268−0.00872098
82,1080.03873340.592311580.13641352−0.00872510

The three energy terms sum to 0.72000000 in each row. At the larger cutoff, the full-coordinate evolution with time step 0.005 agrees with the normal-mode energy components within 0.0000041, and halving the step reduces the error by a factor of four. Energy in the nonzero box modes can return at later times. This finite-time transfer alone does not establish irreversible damping.

For the converse experiment give an axial cosine mode at k = 1 the whole initial energy 0.72, again with all velocities zero. A plus-polarized mode transfers 0.00376421 to the oscillator by time 6. The cross-polarized mode produces zero mechanical motion. A separate reciprocity check begins at zero displacement and exchanges a unit canonical impulse on Q with a unit canonical impulse on the plus mode. The displacement of the other coordinate in each case is −0.06804380 in the program's polarization convention. The two results agree within 10⁻¹². For velocity coupling an impulse changes canonical momentum, so an arbitrary prescribed bare velocity would be a different test.

Radiation from a finite pulse

In unbounded space let P = I − nnᵀ for a radiation direction n and let ΛS = PSP − P tr(PSP)/2. Its squared norm is S:S − 2|Sn|² + (nᵀSn)²/2. The spherical averages of nᵢnⱼ and nᵢnⱼnₖnₗ give ⟨|ΛS|²⟩ = (2/5) S:S. Direct quadrature over the sphere and an independent sum over two real polarization tensors reproduce 0.400000000000 for this unit tensor.

For prescribed finite motion starting and ending at rest, each real mode retains energy g²k⁴|Q̃(k)|²/2. Summing directions and frequencies gives

E_rad = G(S:S)/(5π) ∫₀∞ ω⁶ |W(ω)|² |Q̃(ω)|² dω .

Here Q̃(ω) = ∫Q(t) exp(iωt) dt. For steady Q = A cos Ωt the mean power is G(S:S)Ω⁶A²|W(Ω)|²/10, or 0.02667107 for A = 1 and the parameters above. The finite-width form factor follows from this particular source profile.

For the pulse Q(t) = exp[−t²/(2T²)] cos Ωt with T = 3, multiplication by W(ω) in frequency space gives a smoothed time-domain quadrupole. With v = T² + σ² its amplitude is (T/√v) exp[−Ω²T²σ²/(2v)], its envelope is exp[−t²/(2v)], and its carrier is ΩT²/v. Integrating the square of its third derivative in time with coefficient G(S:S)/5 gives 0.187829098677. Integrating each emitted mode over frequency and solid angle gives the same energy within 10⁻¹². A discretely sampled outgoing spectrum in successively larger periodic boxes gives a third check.

Box length divided by 2πEnergy deposited by the prescribed pulse
20.185704315616
40.187829110286
80.187829098677

Prescribing the pulse history means a drive supplies the emitted energy. Only the earlier free-release experiment includes the mechanical backreaction self-consistently. Both calculations assume the linearized tensor action, its value of G, and the mechanical quadrupole vertex. They do not infer those inputs from the underlying walk or evolve the full nonlinear Einstein–matter system.

Run python quadrupole_exchange.py with NumPy to reproduce the source moments, finite-box transfers, reciprocal readouts and continuum pulse energy.

Can the energy of a gravitational wave change the volume of a closed space?

Sections in this chapter

On a flat conformal three-torus, a nonzero transverse, traceless gravitational-wave momentum requires an initially expanding or contracting geometry. Holding the physical volume fixed determines the magnitude of that expansion. Two seeds with the same mean squared wave momentum but different polarizations give different conformal geometries and different expansion rates. This calculation solves the nonlinear vacuum Einstein initial-value constraints. It starts at the instant when the first-order wave displacement vanishes and its conjugate momentum is nonzero.

The constraint that sees the wave energy

Use a periodic coordinate box of side 2π with c = 1. Its spatial metric is γᵢⱼ = ψ⁴δᵢⱼ, with ψ positive. Let K be the spatially constant trace of the extrinsic curvature. Specify a divergence-free, trace-free tensor à with respect to the flat conformal metric. The physical contravariant extrinsic curvature is

Kⁱʲ = ψ⁻¹⁰ Ãⁱʲ + (K/3)γⁱʲ .

The power −10 ensures that the flat transverse seed solves the physical vacuum momentum constraint ∇ⱼKⁱʲ − ∇ⁱK = 0. The spatial scalar curvature is R = −8ψ⁻⁵Δψ. The vacuum Hamiltonian constraint R + K² − KᵢⱼKⁱʲ = 0 becomes

Δψ + (Ã:Ã)ψ⁻⁷/8 − K²ψ⁵/12 = 0,          ⟨ψ⁶⟩ = 1.

Angle brackets denote a coordinate average over the torus. The second equation sets the physical volume to its reference value on this initial slice. The conformal method and its closed-space, constant-mean-curvature problem are established results. York on conformal gravitational data · Isenberg on closed CMC constraints

Integration over the box eliminates Δψ exactly. Thus

K² = (3/2) ⟨(Ã:Ã)ψ⁻⁷⟩ / ⟨ψ⁵⟩ .

Every nonzero seed has a positive numerator and denominator. For this conformally flat vacuum construction there is no K = 0 solution containing such a wave. In the linear lattice calculation the trace-free momentum carried positive quadratic energy but disappeared from the linear scalar constraint. Here its squared norm explicitly sources the geometry. The first-order data also need a homogeneous trace momentum of order of the wave amplitude for a consistent nearby closed solution. Closed-space linearization stability

Take the conventional sign Kᵢⱼ = −½ ℒₙγᵢⱼ with unit future normal n. Initially, the normal volume expansion θ = −K and the volume expansion rate per spatial dimension H = −K/3. The constraint supplies two signs. Reversing time changes the sign of the whole extrinsic curvature, including its transverse part. Changing K alone exchanges the expansion and contraction branches while holding the specified conformal seed fixed. This is a statement about one initial instant.

A standing wave produces a second spatial harmonic

Choose Ãˣˣ = −Ãʸʸ = a cos(kz), with other components zero. It has Ã:Ã = a²[1 + cos(2kz)]. Its leading constant part fixes K² = 3a²/2. Its oscillating part sources the conformal factor at twice the seed wave number. Write x = a²/k² and c₂ = cos(2kz). At small x,

ψ = 1 + x c₂/32 + O(x²),            H² = a²/6 + O(a⁴/k²).

For example, the local order-x equation for ψ has second derivative −a²c₂/8, and the volume condition sets its constant correction to zero. At the next order the volume condition sets the constant term in ψ to −5x²/4096. Solving the twice- and four-times-frequency equations gives the order-x² correction −3x²c₂/256 − 7x²cos(4kz)/8192 in addition to that constant. Substitution into the integrated constraint gives a second independent check,

K² / (3a²/2) = 1 − 7x/64 + 33x²/512 + O(x³).

At the zero-strain instant the earlier linear Hamiltonian assigns the transverse perturbation a spatially averaged quadratic canonical energy density ⟨Ã:Ã⟩/(16πG) to leading order. The leading constraint then gives 3H² = 8πG times that energy density. This identification belongs to the chosen weak-field background and slice. Here G enters the normalization of the canonical energy. The vacuum constraint itself cannot measure G.

Solving for the geometry at fixed volume

A periodic spectral solve treats the values of ψ and K² as simultaneous unknowns. The wave number is k = 1 in the table. The coefficient ψ₂ is the cosine coefficient of ψ at wave number 2. Solves with 32 and 48 points agree within 10⁻¹¹ on K² and within 10⁻¹² on ψ₂.

Seed amplitude aSolved K²Initial expansion magnitude per dimensionSolved ψ₂Leading ψ₂
0.050.00374897610.020409630.00007805190.0000781250
0.200.05974353470.081474970.00123162060.0012500000
0.600.52241963020.240928670.00995917550.0112500000

At a = 0.6 the homogeneous leading estimate for K² is 0.54. The full constraint gives a value 3.26% lower. A polarization control isolates the role of the spatial pattern. Set Ãˣˣ = −Ãʸʸ = a cos(kz)/√2 and Ãˣʸ = Ãʸˣ = a sin(kz)/√2. Now Ã:Ã = a² everywhere, with precisely the same mean conformal seed norm as the standing wave. The exact solution has ψ = 1 and K² = 3a²/2, confirmed numerically at 0.54. The extrinsic curvature still varies in space. A spatially homogeneous ψ need not imply spatially homogeneous initial data.

An independent check using the physical tensors

The checker evaluates the spectral solution on a different grid, shifted away from every original sample in the 64-point check. It builds γᵢⱼ, its inverse and Kⁱʲ there. Fourth-order centered first differences give the Christoffel symbols directly from γ and then the Ricci tensor from the Christoffel symbols. The code contracts the vacuum Hamiltonian and momentum constraints using these physical tensors, independently of the conformal reduction. The fields are constant in x and y, and all three tensor directions enter the contractions.

Verification points along zLargest Hamiltonian residualLargest momentum residual
644.96 × 10⁻⁵6.38 × 10⁻⁷
1283.14 × 10⁻⁶4.05 × 10⁻⁸
2561.97 × 10⁻⁷2.55 × 10⁻⁹

These are absolute residuals at a = 0.6 in the box units. Refining by a factor of two reduces each residual by approximately sixteen. The full physical trace differs from prescribed K by at most 2.3 × 10⁻¹⁶. Adding an unbalanced longitudinal shear of amplitude 0.01 produces a measured momentum residual of 0.009999, confirming sensitivity to that failure.

The box has no outer boundary at which to define an isolated ADM mass. The calculation supplies nonlinear continuum initial data, with spatial symmetry and conformal free data chosen explicitly. Evolution of the waves, a nonlinear constraint-preserving lattice time update, and a derivation of the Einstein constraints from the underlying walk would require additional dynamics.

Run python wave_weight.py with NumPy to reproduce the three standing-wave solutions, both signs of K, the independent tensor residuals and the polarization control.

What must gravity and matter agree on when two local clocks change order?

Sections in this chapter

Push a spatial slice forward in two places, first with a lapse N and then with a lapse M. Reverse their order. A common spacetime predicts that the difference, to second order, is a sideways relabeling of the slice. Every field must undergo the same relabeling. Here we compute both sides on configurations that need not satisfy the field equations. Testing only solutions would hide terms proportional to constraints.

What we assume

Start with a smooth positive three-metric h, its conjugate momentum density P, a scalar φ and its momentum density p on a periodic three-torus. The metric and these canonical variables are inputs. Take the spatially covariant, parity-even trial Hamiltonian density

H = A (Pij P^ij − w P²)/√h − B √h R + Λ√h + √h F(s,y,φ)
s = p²/(2 det h)                 y = h^ij ∂iφ ∂jφ / 2 .

Here h in √h denotes the determinant and P in the trace term denotes the trace hᵢⱼPⁱʲ. Fix the time unit by asking for the ordinary hypersurface shift βⁱ = hⁱʲ(N∂ⱼM − M∂ⱼN). The canonical generator D of that shift integrates Pⁱʲ times the Lie derivative of hᵢⱼ and p times βⁱ∂ᵢφ. Periodicity removes the boundary terms.

The bracket that tests those assumptions

Antisymmetrizing the two lapse variations cancels terms with undifferentiated NM, including the potential and Λ. Integrating the two derivatives of the metric variation in the curvature term by parts gives

{H[N],H[M]} = AB D_gravity[β]
             + 2AB(1 − 2w) ∫ √h βⁱ ∂ᵢ(P/√h)
             + ∫ F_s F_y p βⁱ ∂ᵢφ .

For arbitrary slices and fields, the normalized common shift requires w = 1/2, AB = 1 and F_s F_y = 1 within this ansatz. Those conditions leave the gravitational coupling (the ratio of the two gravitational coefficients), the cosmological term and the scalar potential undetermined. Restricting the slices to constant mean curvature sets the trace-gradient term to zero and changes what the test can identify. Higher derivatives, additional modes and other choices of canonical variables fall outside this derivation. Hojman, Kuchař and Teitelboim on reconstructing geometrodynamics · Bellorín and Restuccia on the role of the trace constraint

Independent numerical measurement

The replay constructs smooth nonflat three-metrics, inhomogeneous momenta and scalar fields. It measures each bracket as a symmetric directional difference of the full nonlinear Hamiltonian, including the Ricci scalar reconstructed from the metric. A separate calculation Lie-drags the fields. A conformal metric with known scalar curvature tests the curvature implementation. Grid sizes are 10, 16 and 24 per axis.

At 24³, the canonical and nonlinear scalar models both give +0.126639971 for the common shift. Changing the trace weight to 0.43 produces a discrepancy of −0.005057780. Reducing the scalar gradient stiffness to 0.62 produces −0.032162157. A fit on two independent configurations recovers AB = 0.949000 and AB(1−2w) = 0.075920. Its prediction on a third differs from the direct calculation by 1.6 × 10⁻¹¹ or less.

The walk’s collision density can now be compared with a specific requirement. Even if its deposited internal excitation could be eliminated, its moving-pair clock bracket must generate the spatial shift of that same metric. Pair clock experiment · Independent replay

How much matter physics does a common spacetime determine?

Sections in this chapter

Suppose the homogeneous scalar experiment gives an energy density g(s), where s is the squared canonical momentum divided by twice the metric determinant. With a spatial gradient, set y = |∇φ|²/2. The closure condition derived in the metric calculation is F_s F_y = 1. We can use the measured edge F(s,0) = g(s) to predict some gradient experiments. We hold φ fixed throughout this reconstruction. Derivation of the condition

A prediction from homogeneous data

Along the characteristic issuing from an initial s₀, F_s stays equal to g′(s₀). Integrating the characteristic gives

s = s₀ + y / g′(s₀)²
F(s,y) = g(s₀) + 2y / g′(s₀).

These formulas require a nonzero slope and a unique characteristic reaching the measured edge. For g(s) = √(1+2s) − 1 they give F = √((1+2s)(1+2y)) − 1 throughout s ≥ y ≥ 0. The calculation inverts the first equation numerically and checks three predictions against the closed form.

Two theories indistinguishable by every homogeneous calibration

Take a covariant scalar Lagrangian P(X), with X = (φ̇² − |∇φ|²)/2 in a local inertial frame. Let P₀(X) = X. Set P₁(X) = X for X ≥ 0 and, for X < 0, add half the integral from X to zero of (u−X) exp(u+1/u) du. The added function and all of its derivatives vanish at zero. Both actions are smooth and agree for every homogeneous velocity. They remain locally hyperbolic over the comparison domain. For X < 0 the derivative P₁′ exceeds 1/2 and P₁″ = exp(X+1/X)/2. Also P₁′+2XP₁″ ≥ 1 − (1+2/e)/2 > 0.

A static gradient of magnitude √2 probes X = −1. A small perturbation moving along the gradient has speed squared 1 + 2X P″/P′. A transverse perturbation travels at unit speed. The standard scalar gives unit speed in both directions. The second action predicts longitudinal speed 0.927144 and transverse speed 1. Its static energy density is 0.989279 in units where the standard scalar gives 1. Both actions preserve the common matter–gravity constraint algebra. The replay computes that speed both from the analytic derivatives and from a finite-difference Hessian, and tests F_s F_y after an independent numerical Legendre transform.

For the walk this gives a measurement design. Homogeneous clock rates can constrain part of the continuation into a gradient; a calibrated gradient plus a longitudinal and transverse pulse can distinguish completions that agree on all those rates. The example uses smooth actions. Requiring a globally analytic action would rule out this particular pair. Run the reconstruction

Can finite spatial samples describe two ways of advancing a clock?

Sections in this chapter

Consider a one-dimensional ring with site values φᵢ, their canonical momenta pᵢ and spacing a. Give each site a kinetic term and distribute each nearest-neighbor gradient term equally over its endpoints. Direct differentiation of the quadratic Hamiltonian gives the following exact bracket of two lapse changes, using the field normalization in which the site variables form canonical pairs.

βᵢ₊½ = (NᵢMᵢ₊₁ − MᵢNᵢ₊₁)/a
D[β] = Σ βᵢ₊½ (pᵢ + pᵢ₊₁)(φᵢ₊₁ − φᵢ)/(2a).

This first bracket looks promising. But compose the resulting shifts supported on two neighboring edges. At unit spacing the matrix commutator maps site 2 into site 0 with coefficient 1/4. Every original edge shift has zero in that matrix element. Thus this fixed-site family already fails the next algebra test. The obstruction is specific to the stated generators.

A finite construction that survives the path test

Put a massless scalar on prescribed flat 1+1 spacetime. Its two traveling components depend on U = X + T and U = X − T, respectively. Sample a trigonometric polynomial with 2m+1 real coefficients at 2m+1 distinct periodic nodes. The evaluation matrix V(U) is invertible. A finite move from nodes U to U′ transports sample values by V(U′) V(U)⁻¹. Intermediate evaluations cancel exactly in either order. The replay moves two distinct chiral records through two finite paths and compares the resulting samples.

For an infinitesimal displacement v the matrix is Aᵥ = diag(v) V′ V⁻¹. The derivatives of this matrix with respect to the moving nodes cancel its commutator. Replacing the full differentiation matrix with a three-node quadratic interpolant breaks the cancellation. For the smooth test signal, the maximum path defects are 0.17472, 0.05950 and 0.01542 at 15, 31 and 63 nodes. Full trigonometric sampling stays within 3 × 10⁻¹² on the same signals. The construction trades exact transport on a finite band for a dense spatial operation.

On a bent slice, compute the unit normal from the node derivatives of (T,X). Two normal displacements give a tangential displacement even at finite spacing in the tested scheme, because differentiating a unit normal gives a tangent. The resulting coefficient contains discrete differences of a product. Replacing it by the usual continuum product-rule expression gives errors 0.004585, 0.001983 and 0.000558. This separates failure of a fixed stencil from what can be recovered by allowing the sampling locations to move.

The physical gap is the dynamical metric. These nodes sample a spacetime supplied in advance. Turning nodes, clocks, matter and metric into local dynamical degrees of freedom while retaining the same path independence remains open. Replay both paths · Nonlinear metric bracket

How many smaller copies cover a walk observed between ticks?

Sections in this chapter

One elementary shift of the six-stage walk has six possible endpoints when the detector does not record the starting stage. Their convex hull is an octahedron. Six copies at two-thirds scale cover it, and five smaller copies cannot. Wait one more complete cycle before reading the detector and the answer at the same two-thirds scale becomes eight. Six copies of this second body still suffice if they are allowed to be larger. Nothing about the walk gates changed. The readout interval determines the body and the resolution determines the count.

What the three-dimensional theorem proves

Aiger, Har-Peled and Žužić prove in their November 27 preprint that a compact convex set with nonempty interior in three dimensions can be covered by eight translates of a common positive contraction of itself. The ratio is strictly below one. It need not be supplied by an experiment, and the theorem states no numerical ratio such as two-thirds. A cover allows overlap. Finite point clouds, probability weights, spin phases, and time evolution require separate inputs. Theorem 1.1 and version record

The authors handle affine cubes directly. For other bodies they put the central symmetral (K−K)/2 in John's position. Two opposite illumination directions cover the boundary outside a shadow curve. A mean-width bound gives a direction for which that curve has length strictly below 12 in the symmetral norm, so it splits into six arcs of length below 2. Each arc fits in one smaller homothet. The strict inequality matters when taking polytope limits. The paper transfers the shadow-length bound to the limiting body and then constructs its cover. It leaves open whether every non-affine-cube admits seven smaller copies at some scale. The arXiv record on December 1 listed v3 as current and included the authors’ Lean formalization. The calculations below verify this walk example independently. Proof, §§3.4–4 · Authors’ formalization notes

Preparing the detector at an unknown stage

The native optical cycle shifts by one fine link along x, y, z, z, y, x. Start at the origin with an unpolarized two-state input, choose one of the six starting stages with equal classical probability, and measure position after exactly 6n + 1 elementary shifts. Keep coherent interference between routes within each run. Pool the six starting stages only after computing the separate position probabilities. The earlier full-tick result used a detector synchronized to complete cycles. The six shifts and full-tick position readout

Put a = 2n. Each window contains a shifts along two axes and a + 1 along the remaining axis. For a fixed starting stage the endpoints are contained in the corresponding rectangular box. Every corner of that box is occupied. Reaching it forces the sign of each shift and leaves only one amplitude path. Equal adjacent axes preserve the chosen sign, and successive different Pauli axes have nonzero overlap. When n ≥ 1 each corner-bearing path has 4n axis changes. Its conditional probability is 1/(2·16ⁿ). Two of the six starting stages give the specified extra axis, so the probability of a named outer vertex is 1/(6·16ⁿ). For n = 0 the six axial endpoints each have probability 1/6 directly.

Let Cₐ = [−a,a]³ and let O be the octahedron |x|+|y|+|z| ≤ 1. A fixed-phase box is Cₐ plus the unit segment along the extra axis. Taking the convex hull of all three boxes gives

Kₐ = Cₐ + O,                 hₖ(u) = a ||u||₁ + ||u||∞ .

Here hₖ is the maximum projection in direction u. For a > 0 the 24 vertices are all sign choices and permutations of (a+1,a,a). The face centroids and intervening continuum need not themselves be detector hits.

A six-copy construction

For a = 0 use six octahedra centered at ±eᵢ/3, each at scale 2/3. Given x in O, write m = max |xᵢ| and s = Σ|xᵢ|. Select the matching signed axis where m is attained. If m ≥ 1/3, the distance to the chosen center is s − 1/3 ≤ 2/3. If m < 1/3, the distance is s + 1/3 − 2m ≤ m + 1/3 < 2/3. Distinct unit axial vertices have pairwise distance 2 in the octahedron norm. Each contracted octahedron has diameter below 2, so every smaller-copy cover needs at least six.

For a ≥ 2 the six signed axes also supply a cover. Choose the center distance t and scale λ₆ as follows.

t = (3a+1)/[3(2a+1)],                 λ₆ = 1 − 1/[3(2a+1)] .

A point belongs to Kₐ if the absolute coordinates in every subset of size b sum to at most ba + 1. This follows equivalently by summing the excess of each |xᵢ| above a. Choose the axis with largest absolute coordinate m and translate toward it by t. If m ≥ t, a subset including this axis gains slack t, sufficient for contraction by λ₆. For a subset omitting the largest coordinate, its b entries sum to at most ba + b/(b+1). Append the largest coordinate and use the (b+1)-coordinate bound. Its slack of at least 1/(b+1) suffices for b = 1 or 2. If m < t, the translated point is already within the central cube of half-width λ₆a.

The centroid (a+1/3)(1,1,1) lies on the outer triangular face. Translating a copy along any coordinate axis leaves its other two coordinates unchanged. Their sum forces scale at least (2a+2/3)/(2a+1) = λ₆. Thus the six-axis construction has the best scale available to centers restricted to these axes. The minimum scale over arbitrary six translations is a separate optimization.

Why seven copies fail at the chosen resolution

An improved placement uses eight centers (±d,±d,±d). In each octant set λ = (a+1)/(2a+1) and d = aλ. For a point with nonnegative coordinates, membership in the copy centered at (d,d,d) requires each signed sum over k coordinates to be at most λ(ka+1) after translation. With p positive signs, p ≥ 1, the unshifted sum is bounded by pa+1. Translation changes that bound to pa+1+(k−2p)d. Since 2d ≥ a, its maximum is reached at p = 1 and equals λ(ka+1). For p = 0 the bound kd also suffices. Reflection covers the other seven octants. This gives scale 3/5 after seven shifts and 5/9 after thirteen.

How small could eight arbitrarily placed copies be? Suppose λ < a/(a+1). Two outer vertices from different sign triples differ by at least 2a along some axis, exceeding the width of one copy there. Eight copies must therefore divide among the eight triples, one per triple, and each covers all three vertices of its own triple. The absolute value of each center coordinate is then at least (1−λ)(a+1), since one of those vertices reaches a+1 in that coordinate. A copy covering the origin must also have the sum of its absolute center coordinates at most λ(3a+1). Combining the bounds gives λ ≥ 3(a+1)/(6a+4). Above the assumed threshold this lower bound already holds for a ≥ 2. Thus the best possible eight-copy scale lies between 9/16 and 3/5 at seven shifts and between 15/28 and 5/9 at thirteen. These are bounds on an optimization over all translations.

Now mark the eight points (a+1/3)(±1,±1,±1). Each is the centroid of its three outer vertices. Distinct marks differ in some coordinate by 2(a+1/3). A translate of λKₐ has width 2λ(a+1) along every axis. Consequently, any cover using at most seven copies must have λ ≥ (a+1/3)/(a+1). For a ≥ 2 this lower bound exceeds 2/3. Together the two estimates give the exact count eight at fixed two-thirds scale.

Elementary shiftsOccupied sitesOuter verticesScale for six axis-centered copiesAchieved scale with eight copiesMinimum count at scale 2/3
1662/32/3 suffices with six6
7562414/153/58
131802426/275/98

The replay propagates the actual two-component amplitudes with Gaussian-integer arithmetic before forming probabilities. It checks every occupied point against the body and verifies the probability of every claimed vertex. A second test treats the entire continuous body. In the symmetry chamber x ≥ y ≥ z ≥ 0, the defining upper bounds are x ≤ a+1, x+y ≤ 2a+1 and x+y+z ≤ 3a+1. The program enumerates its vertices by intersections of rational planes and checks every signed facet of the assigned translated copy there. Convexity extends the certificate to the full chamber, and signed permutations cover all chambers.

What observing the vertices would establish

In seven stages each of the 24 extreme sites occurs with probability 1/96 in the stated preparation. Observing all of them certifies that their eight triangular-face centroids belong to the convex hull. With independent shots the chance of missing at least one extreme site is at most 24(95/96)ᴹ. A total of 590 shots suffices to make this upper bound at most 5%. The corresponding sufficient count at thirteen stages is 9,480 shots. These are prospective bounds assuming exact site resolution, known outer step limits and uniform classical release phase.

A geometric cover can be iterated. At seven stages two levels of the eight-copy construction give at most 64 copies at scale 4/9, while two levels of the six-axis construction give at most 36 at scale 196/225. These are bounding regions that may overlap or extend outside the parent body. Their multiplicities do not specify eight outgoing walk channels, independent detector outcomes or probability weights. The measured-position hull, the full-tick group-velocity ball, and a field constrained by the deposited energy each require their own physical readout.

Run python convex_cover.py with the Python standard library to reproduce the coherent endpoint probabilities, the polytope certificates and the shot guarantees.

Change the detector’s readout interval

Central section through the three-dimensional endpoint hull. Each view is normalized to its own axial extent.

At seven shifts, eight copies cover the hull at two-thirds scale. Eight copies already suffice at 3/5 scale. Six axial copies suffice at 14/15 scale.

Calculations and native transcript

The standalone archive contains eleven calculations, both inherited pair kernels, the detector instrument, the clock control and 21 exact native Tally checks. Run python replay.py TALLY.zip with the pinned Tally runtime. Add --full with NumPy installed to repeat the lattice and spectral calculations. The GW170814 chapter gives the additional dependencies and strain-file checksums for reproducing the detector inputs.

Native Tally transcript
✓ the oblique transverse polarization axis has unit norm  (by cross-pairing plus and minus sides; derived)
✓ the polarization axis is transverse to momentum (3,4,0)  (by cross-pairing plus and minus sides; derived)
✓ the plus tensor has zero three-dimensional trace  (by cross-pairing plus and minus sides; derived)
✓ contracting the plus tensor with the momentum gives zero  (by cross-pairing plus and minus sides; derived)
✓ the plus polarization has squared tensor norm two  (by cross-pairing plus and minus sides; derived)
✓ the cross xz and yz entries give the same tensor norm  (by cross-pairing plus and minus sides; derived)
✓ a constant-norm transverse wave gives K squared equal to 0.54 in the normalized torus  (by cross-pairing plus and minus sides; derived)
✓ the homogeneous conformal Hamiltonian constraint cancels pointwise  (by cross-pairing plus and minus sides; derived)
✓ normalized Einstein kinetic and curvature coefficients give a common shift without a trace gradient  (by cross-pairing plus and minus sides; derived)
✓ changing the trace weight to 0.43 leaves a trace anomaly  (by cross-pairing plus and minus sides; derived)
✓ changing only gradient stiffness leaves a species-dependent shift  (by cross-pairing plus and minus sides; derived)
✓ nonlinear scalar reciprocal Hamiltonian slopes close the bracket  (by cross-pairing plus and minus sides; derived)
✓ the same nonlinear scalar has energy two at these gradient and momentum values  (by cross-pairing plus and minus sides; derived)
✓ the two-level clock commutator gives unit excitation amplitude in the control  (by cross-pairing plus and minus sides; derived)
✓ a normalized polynomial in the squared gap cancels that control transition  (by cross-pairing plus and minus sides; derived)
✓ the same energy improvement preserves matrix elements at zero gap  (by cross-pairing plus and minus sides; derived)
✓ two adjacent edge shifts generate a two-site transition  (by cross-pairing plus and minus sides; derived)
✓ seven-step face centroids obstruct two-to-one covering below seven ninths  (by cross-pairing plus and minus sides; derived)
✓ at seven shifts eight copies reach three fifths and need at least nine sixteenths  (by cross-pairing plus and minus sides; derived)
✓ a seven-stage extreme endpoint carries one part in ninety-six for uniform release phase  (by cross-pairing plus and minus sides; derived)
✓ the odd-channel rest gap sets the squared-gap exponent in energy-window suppression  (by cross-pairing plus and minus sides; derived)
Native Tally source
# Exact controls for tensor clocks and the convex body of walk endpoints.
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 eight=whole(8 trial)
let half=fraction(1 trial,2 trial)
let x=fraction(4 trial,5 trial)
let y=flip(fraction(3 trial,5 trial))
check x*x+y*y==one "the oblique transverse polarization axis has unit norm"
check three*x+four*y==zero "the polarization axis is transverse to momentum (3,4,0)"
let plus_xx=x*x
let plus_xy=x*y
let plus_yy=y*y
check plus_xx+plus_yy+flip(one)==zero "the plus tensor has zero three-dimensional trace"
check three*plus_xx+four*plus_xy==zero and three*plus_xy+four*plus_yy==zero "contracting the plus tensor with the momentum gives zero"
check plus_xx*plus_xx+two*plus_xy*plus_xy+plus_yy*plus_yy+one==two "the plus polarization has squared tensor norm two"
check two*(x*x+y*y)==two "the cross xz and yz entries give the same tensor norm"
let amp=fraction(3 trial,5 trial)
let traceKsq=share(three,two)*amp*amp
check traceKsq==fraction(27 trial,50 trial) "a constant-norm transverse wave gives K squared equal to 0.54 in the normalized torus"
check share(traceKsq,whole(12 trial))==share(amp*amp,eight) "the homogeneous conformal Hamiltonian constraint cancels pointwise"
let ka=fraction(8 trial,5 trial)
let kb=fraction(5 trial,8 trial)
check ka*kb==one and one+flip(two*half)==zero "normalized Einstein kinetic and curvature coefficients give a common shift without a trace gradient"
let trace_weight=fraction(43 trial,100 trial)
check one+flip(two*trace_weight)==fraction(7 trial,50 trial) "changing the trace weight to 0.43 leaves a trace anomaly"
let slow=fraction(31 trial,50 trial)
check one*slow==slow and slow+fraction(19 trial,50 trial)==one "changing only gradient stiffness leaves a species-dependent shift"
let root_s=two
let root_y=fraction(3 trial,2 trial)
check share(root_y,root_s)*share(root_s,root_y)==one "nonlinear scalar reciprocal Hamiltonian slopes close the bracket"
check root_s*root_y+flip(one)==two "the same nonlinear scalar has energy two at these gradient and momentum values"
let delta=two
let offdiag=half
check delta*offdiag==one "the two-level clock commutator gives unit excitation amplitude in the control"
check one+flip(share(delta*delta,four))==zero "a normalized polynomial in the squared gap cancels that control transition"
check one+flip(share(zero,four))==one "the same energy improvement preserves matrix elements at zero gap"
check half*half==fraction(1 trial,4 trial) "two adjacent edge shifts generate a two-site transition"
let shrink=fraction(2 trial,3 trial)
let a=two
let mark=a+fraction(1 trial,3 trial)
check share(mark,a+one)==fraction(7 trial,9 trial) "seven-step face centroids obstruct two-to-one covering below seven ninths"
check share(a+one,two*a+one)==fraction(3 trial,5 trial) and share(three*(a+one),whole(6 trial)*a+four)==fraction(9 trial,16 trial) "at seven shifts eight copies reach three fifths and need at least nine sixteenths"
check share(one,whole(6 trial))*share(one,whole(16 trial))==fraction(1 trial,96 trial) "a seven-stage extreme endpoint carries one part in ninety-six for uniform release phase"
let gap=fraction(1 trial,10 trial)
check gap*gap==fraction(1 trial,100 trial) "the odd-channel rest gap sets the squared-gap exponent in energy-window suppression"
lapse_loop.py
"""Sine-cosine local-energy commutator on the normalized 3D pair pole. Requires NumPy."""
import argparse
from pathlib import Path
import sys
import numpy as np

HERE=Path(__file__).resolve().parent
if not (HERE/'bound_3d.py').exists():
    sys.path.insert(0,str(HERE.parent/'shell-clocks'))
from bound_3d import Torus, rest_calibration, BASIS, BETA_PAIR, GAMMA, IDENTITY
if not (HERE/'form_factor.py').is_file():
    sys.path.insert(0,str(HERE.parent/'pair-inertia'))
from form_factor import block, bound, wave


def push(k,d,incoming,contact_amplitude,h_at,origin=0.):
    """Output at relative momentum p after rho(d) maps total momentum k to k+d."""
    fa=h_at(1,(k+d)/2)[0]
    ia=h_at(1,(k-d)/2)[0]
    fb=h_at(-1,(k+d)/2)[0]
    ib=h_at(-1,(k-d)/2)[0]
    # The constituent receiving momentum d has its initial relative momentum shifted.
    from_a,from_b=incoming(-d/2),incoming(d/2)
    result=((fa+ia)@from_a+from_b@(fb+ib).swapaxes(1,2))/2+contact_amplitude
    if origin:
        result+=(origin/2)*(from_a+from_b)
    return result


class Pair:
    def __init__(self,torus,cal,k,contact):
        energy,src=bound(torus,cal,2,k,contact)
        self.energy=energy
        self.source=(BASIS@src).reshape(4,4)
        self.k=k


def spinwave(pair,offset,h_at):
    a,e=h_at(1,offset+pair.k/2)
    b,f=h_at(-1,-offset+pair.k/2)
    return wave(pair.source,pair.energy,a,e,b,f)


def evaluate(torus,cal,k,q,contact,second_action=False,include_band=True,origin=0.):
    """All relative momenta and all 16 spins enter before any pole projection."""
    n=torus.size
    directions=(q,-q)
    initial=Pair(torus,cal,k,contact)
    final=[Pair(torus,cal,k+d,contact) for d in directions] if include_band else []
    norms=np.zeros(2)
    contact_means=np.zeros((2,4,4),complex)
    projected=np.zeros(2,complex)
    # A branch source in the published resolvent is V|psi>, constant over p.
    def chunks():
        for lo in range(0,n,2):
            p=[a*(2*np.pi/n) for a in (torus.grid[0][lo:lo+2],*torus.grid[1:])]
            h_cache={}
            def h_at(sign,offset):
                key=sign,round(offset,11)
                if key not in h_cache:
                    h_cache[key]=block([sign*p[0],sign*p[1],sign*p[2]+offset])
                return h_cache[key]
            psi_cache={}
            def psi(offset):
                key=round(offset,11)
                if key not in psi_cache:
                    psi_cache[key]=spinwave(initial,offset,h_at)
                return psi_cache[key]
            first_cache={}
            def first(d,offset):
                key=round(d,11),round(offset,11)
                if key not in first_cache:
                    sym=lambda s: psi(offset+s)
                    hshift=lambda sign,s: h_at(sign,s+sign*offset)
                    first_cache[key]=push(k,d,sym,initial.source,hshift,origin)
                return first_cache[key]
            yield h_at,psi,first

    for h_at,psi,first in chunks():
        for j,d in enumerate(directions):
            out=first(d,0.)
            norms[j]+=np.vdot(out,out).real
            contact_means[j]+=out.sum(axis=0)
            if include_band:
                projected[j]+=np.vdot(spinwave(final[j],0.,h_at),out)
    norms/=n**3
    contact_means/=n**3
    projected/=n**3
    if np.min(norms-abs(projected)**2)<-2e-7:
        raise ArithmeticError('projection exceeded complete norm')
    full=(norms[0]-norms[1])/2
    band=(abs(projected[0])**2-abs(projected[1])**2)/2
    if not second_action:
        return full,band,float('nan'),projected
    # Contact in the intermediate momentum fiber acts on the entire coincident spinor.
    g=1/cal[1]
    if np.array_equal(contact,IDENTITY):
        kicks=g*contact_means
    else:
        beta=GAMMA[-1]
        kicks=g*beta@contact_means@beta.T
    expectation=0j
    current=0j
    bnorm=0.
    for h_at,psi,first in chunks():
        products=[]
        if include_band and k>0.:
            chi=first(q,0.)
            ha=h_at(1,(k+q)/2)[0]
            hb=h_at(-1,(k+q)/2)[0]
            dh=ha@chi+chi@hb.swapaxes(1,2)+kicks[0]-initial.energy*chi
            current+=np.vdot(spinwave(final[0],0.,h_at),dh)/(2*np.sin(q/2))
        for j,d in enumerate(directions):
            incoming=lambda offset: first(d,offset)
            products.append(push(k+d,-d,incoming,kicks[j],h_at,origin))
        bpsi=(products[0]-products[1])/2
        expectation+=np.vdot(psi(0.),bpsi)
        bnorm+=np.vdot(bpsi,bpsi).real
    if include_band and k>0.:
        predicted=(final[0].energy-initial.energy)*projected[0]/(2*np.sin(q/2))
        assert abs(current/n**3-predicted)<3e-7
        print(f'  endpoint continuity current K={k:g} to {k+q:g}: {predicted.real:.9f}',flush=True)
    expectation/=n**3
    variance=bnorm/n**3-abs(expectation)**2
    # quadratures of shifted integration variables coincide in the continuum.
    assert abs(expectation-full)<(3e-4 if n<=32 else 2e-5)
    assert variance>=-1e-12
    return full,band,variance,projected


def finite_torus_loop():
    """Independent finite-duration test in physical momenta (K,k_A), no intermediate projection."""
    n=8
    stride=2
    q=stride*2*np.pi/n
    torus=Torus(n)
    cal=rest_calibration(torus)
    c=IDENTITY
    rest=Pair(torus,cal,0.,c)
    _,_,variance,_=evaluate(torus,cal,0.,q,c,True,False)
    k,x,y,z=[i*2*np.pi/n for i in np.ogrid[0:n,0:n,0:n,0:n]]
    def symbol(arr):
        h,_=block(arr)
        return h.reshape(*np.broadcast_shapes(*(s.shape for s in arr)),4,4)
    ha=symbol((x,y,z))
    hb=symbol((-x,-y,k-z)).swapaxes(-1,-2)
    s=np.zeros((n,n,n,n,4,4),complex)
    spin=rest.source
    h1,a=block((x,y,z))
    h2,b=block((-x,-y,-z))
    s[0]=wave(spin,rest.energy,h1,a,h2,b).reshape(n,n,n,4,4)/np.sqrt(n**3)
    assert abs(np.linalg.norm(s)-1)<1e-12
    a_links={}
    b_links={}
    for step in (stride,-stride):
        a_links[step]=(ha+np.roll(ha,step,axis=3))/2
        b_links[step]=(hb+np.roll(hb,step,axis=0))/2
    def hopping(state,step):
        shifted=np.roll(state,step,axis=0)
        return a_links[step]@np.roll(shifted,step,axis=3)+shifted@b_links[step]
    def contact(state,step):
        mean=state.mean(axis=(1,2,3),keepdims=True)/cal[1]
        return np.broadcast_to(np.roll(mean,step,axis=0),state.shape)
    def vertex(state,step):
        return hopping(state,step)+contact(state,step)
    def pulse(state,kind,factor):
        result=state.copy()
        term=state.copy()
        for j in range(1,32):
            plus,minus=vertex(term,stride),vertex(term,-stride)
            h=(plus+minus)/2 if kind=='cos' else (plus-minus)/(2j)
            term=(factor/j)*h
            result+=term
            if np.linalg.norm(term)<1e-16:
                return result
        raise ArithmeticError('finite pulse did not converge')
    bstate=(vertex(vertex(s,stride),-stride)-vertex(vertex(s,-stride),stride))/2
    free=(hopping(hopping(s,stride),-stride)-hopping(hopping(s,-stride),stride))/2
    contact_first=(hopping(contact(s,stride),-stride)-hopping(contact(s,-stride),stride))/2
    contact_last=(contact(hopping(s,stride),-stride)-contact(hopping(s,-stride),stride))/2
    assert np.linalg.norm(free)<1e-12
    assert np.linalg.norm(contact_first.mean(axis=(1,2,3)))<1e-12
    assert abs(np.vdot(contact_first,contact_last))<1e-12
    assert np.linalg.norm(bstate-contact_first-contact_last)<1e-12
    direct=np.vdot(bstate,bstate).real-abs(np.vdot(s,bstate))**2
    assert abs(direct-variance)<2e-10
    print(f'independent eight-cell torus, q=pi/2: Var(B)={direct:.9f}')
    errors=[]
    for angle in (.01,.005,.0025):
        out=s
        for kind,sign in (('sin',1),('cos',1),('sin',-1),('cos',-1)):
            out=pulse(out,kind,sign*1j*angle)
        assert abs(np.linalg.norm(out)-1)<4e-13
        lost=out-np.vdot(s,out)*s
        rate=np.vdot(lost,lost).real/angle**4
        errors.append(abs(rate-direct))
        print(f'  area {angle:g}: measured loss/area^4={rate:.9f}')
    assert errors[2]<errors[1]<errors[0] and errors[2]<direct*.01


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('mesh',type=int,nargs='?',default=40)
    parser.add_argument('--origin',action='store_true',help='minimize rest loss over a common energy offset')
    parser.add_argument('--unitary',action='store_true',help='also run independent finite-duration eight-cell control')
    parser.add_argument('--fine',action='store_true',help='use 64 cubed instead of the default mesh')
    args=parser.parse_args()
    if args.unitary:
        finite_torus_loop()
    size=64 if args.fine else args.mesh
    torus=Torus(size)
    cal=rest_calibration(torus)
    if args.origin:
        q=.05
        variance=[evaluate(torus,cal,0.,q,IDENTITY,True,False,offset)[2]/q**2
                  for offset in (-1.,0.,1.)]
        slope=(variance[2]-variance[0])/2
        curve=(variance[2]+variance[0])/2-variance[1]
        optimum=-slope/(2*curve)
        floor=variance[1]+slope*optimum/2
        independent=evaluate(torus,cal,0.,q,IDENTITY,True,False,optimum)[2]/q**2
        assert curve>0 and floor>0 and abs(independent-floor)<2e-8
        print(f'rest loss/q^2 polynomial: {variance[1]:.9f} + offset*({slope:.9f}) + '
              f'offset^2*({curve:.9f}); min at {optimum:.9f}, floor={floor:.9f}',flush=True)
    for name,c in (('density',IDENTITY),('mass',BETA_PAIR)):
        print(f'{name} contact, size={size}, g={1/cal[1]:.9f}',flush=True)
        for k,q in ((0.,.10),(0.,.05),(0.,.025),(.05,.05),(.10,.10),(.10,.05),(.10,.025)):
            full,band,variance,vertex=evaluate(torus,cal,k,q,c,second_action=(k==0 or (k==.10 and q==.05)))
            extra=f' Var(B)/q^2={variance/q**2:.9f}' if np.isfinite(variance) else ''
            print(f'  K={k:.3f} q={q:.3f} full B/q={full/q:.9f} band B/q={band/q:.9f}'
                  f'{extra} |Fplus|={abs(vertex[0]):.9f}',flush=True)
            if k==0.:
                assert max(abs(full),abs(band))<2e-11
        step=.0002
        e0=Pair(torus,cal,.10,c).energy
        em,ep=[Pair(torus,cal,.10+s,c).energy for s in (-step,step)]
        print(f'  K=.100 forward E dE/dK={e0*(ep-em)/(2*step):.9f}',flush=True)


if __name__=='__main__':
    main()
loop_spectrum.py
"""Energy-resolved survival defect of the rest-pair lapse loop. NumPy only."""
import argparse
from math import exp, pi, sinh
import numpy as np
from lapse_loop import Torus, rest_calibration, Pair, IDENTITY, BETA_PAIR, GAMMA, block, wave


def source(n,q,contact):
    torus=Torus(n)
    cal=rest_calibration(torus)
    pole=Pair(torus,cal,0.,contact)
    p=[k*(2*np.pi/n) for k in torus.grid]
    def symbol(sign,shift):
        return block([sign*p[0],sign*p[1],sign*p[2]+shift])
    a,e=symbol(1,0.)
    b,eb=symbol(-1,0.)
    assert np.max(abs(e-eb))<2e-13
    if q:
        da=(symbol(1,q)[0]-symbol(1,-q)[0])/(4*q)
        db=((symbol(-1,q)[0]-symbol(-1,-q)[0])/(4*q)).swapaxes(1,2)
    else:
        def half_derivative(k):
            x,y,z=k
            tx,ty,tz=[2*np.sin(t/2)**2 for t in k]
            ds=(-np.sin(x)*np.cos(y)*np.sin(z),-np.sin(y)*np.sin(z),np.cos(z),
                np.sin(z)*(4*tz/3+2*(tx+ty)))
            out=np.stack(np.broadcast_arrays(*ds),axis=-1).reshape(-1,4)
            return (out@np.array(GAMMA[1:]).reshape(4,16)).reshape(-1,4,4)/2
        da=half_derivative(p)
        db=half_derivative([-x for x in p]).swapaxes(1,2)
    v=pole.source
    psi=wave(v,pole.energy,a,e,b,eb)
    # Exact contact-first / contact-last rest vector at energy origin zero.
    first=da@v+v@db
    coincident=(da@psi+psi@db).mean(axis=0)
    beta=GAMMA[-1]
    strength=1/cal[1]
    if np.array_equal(contact,BETA_PAIR):
        last=strength*beta@coincident@beta.T
    else:
        last=strength*coincident
    assert np.linalg.norm(first.mean(axis=0))<1e-12
    assert np.linalg.norm(beta@coincident@beta.T+coincident)<1e-12
    d=coincident/np.linalg.norm(coincident)
    u=first+last
    assert abs(np.vdot(psi,u)/n**3)<1e-12
    return e,a,b,pole.energy,strength,d,u


def sectors(vec,a,b):
    spin_a=a@vec
    spin_b=vec@b.swapaxes(1,2)
    both=spin_a@b.swapaxes(1,2)
    return ((vec+spin_a+spin_b+both)/4,(vec-both)/2,(vec-spin_a-spin_b+both)/4)


def compressed(n,q,contact):
    e,a,b,e0,g,d,u=source(n,q,contact)
    # At K=0 the free bands have only three energies +2e, 0, -2e.
    # Within each energy eigenspace the cyclic span needs only P_E d and P_E u.
    # Bin by permutation/reflection classes, not by floating-point closeness.
    ijk=np.indices((n,n,n))
    folded=np.sort(np.minimum(ijk,n-ijk),axis=0).reshape(3,-1)
    index=folded[0]*n**2+folded[1]*n+folded[2]
    _,labels=np.unique(index,return_inverse=True)
    label_count=labels.max()+1
    ones=np.ones_like(labels)
    ea=np.bincount(labels,weights=e)/np.bincount(labels)
    norm=n**3
    dvec=[];uvec=[];energies=[]
    ps=sectors(u,a/e[:,None,None],b/e[:,None,None])
    ds=sectors(d,a/e[:,None,None],b/e[:,None,None])
    for step,us,dd in zip((1,0,-1),ps,ds):
        group=labels if step else 0*ones
        count=label_count if step else 1
        # The coincident sector is one-dimensional on these reflected spin textures.
        # Verify it for both generated vectors in every free energy class.
        for arr in (us,dd):
            pooled=np.zeros((count,4,4),complex)
            np.add.at(pooled,group,arr/norm)
            component=pooled.reshape(count,16)@d.conj().ravel()
            assert np.max(abs(pooled-component[:,None,None]*d))<2e-12
        ua=np.bincount(group,weights=np.sum(abs(us)**2,axis=(1,2)))/norm
        db=np.bincount(group,weights=np.sum(abs(dd)**2,axis=(1,2)))/norm
        prod=np.sum(dd.conj()*us,axis=(1,2))
        cross=(np.bincount(group,weights=prod.real)+1j*np.bincount(group,weights=prod.imag))/norm
        dlen=np.sqrt(db)
        parallel=np.divide(cross,dlen,out=np.zeros_like(cross),where=dlen>1e-18)
        rem=ua-abs(parallel)**2
        assert rem.min()>-3e-13
        dvec.extend(np.column_stack((dlen,0*dlen)).ravel())
        uvec.extend(np.column_stack((parallel,np.sqrt(np.maximum(rem,0)))).ravel())
        energies.extend(np.repeat(2*step*ea if step else [0.],2))
    sign=1 if np.array_equal(contact,IDENTITY) else -1
    D=np.array(dvec);U=np.array(uvec);L=np.array(energies)
    assert abs(np.vdot(D,D)-1)<2e-12
    assert abs(np.vdot(U,U)-np.vdot(u,u)/norm)<2e-11
    return L-e0,D,U,g*sign


def rest_spectrum(mesh,q,contact,steps):
    """Signed Ritz gaps (H-Eb) and absolute Gauss weights with sum ||B(q)|b>/q||².

    q=0 uses the exact derivative. Use BETA_PAIR or IDENTITY as contact; smooth
    polynomial moments through degree 2*steps-1 are exact in exact arithmetic.
    A Ritz node inside a gap need not be a physical eigenstate.
    """
    if steps<1:
        raise ValueError('steps must be positive')
    L,D,U,g=compressed(mesh,q,contact)
    norm=np.linalg.norm(U)
    v=U/norm
    prev=np.zeros_like(v)
    diag=[];off=[]
    b=0.
    for j in range(steps):
        w=L*v+g*D*np.vdot(D,v)-b*prev
        a=np.vdot(v,w).real
        diag.append(a)
        w-=a*v
        b=np.linalg.norm(w)
        if b<1e-13 or j+1==steps:
            break
        off.append(b)
        prev,v=v,w/b
    tridiag=np.diag(diag)+np.diag(off,1)+np.diag(off,-1)
    gaps,vectors=np.linalg.eigh(tridiag)
    weights=norm**2*abs(vectors[0])**2
    assert abs(sum(weights)-norm**2)<1e-11
    return gaps,weights


def gaussian_weights(L,D,U,g,taus):
    scale=80.
    assert (max(abs(L))+abs(g))/scale<1
    tau_max=max(taus)
    count=int(16*scale*tau_max)+80
    angles=(np.arange(count)+.5)*(pi/count)
    # Chebyshev interpolation at first-kind nodes, using the mirrored FFT.
    coeff=[]
    for tau in taus:
        y=np.exp(-(tau*scale*np.cos(angles))**2)
        cc=(np.fft.rfft(np.r_[y,y[::-1]])[:count]*np.exp(-.5j*pi*np.arange(count)/count)).real/count
        cc[0]/=2
        coeff.append(cc)
    def apply(x):
        return (L*x+g*D*np.vdot(D,x))/scale
    prev=U
    curr=apply(U)
    moments=[np.vdot(U,prev).real,np.vdot(U,curr).real]
    for _ in range(2,count):
        prev,curr=curr,2*apply(curr)-prev
        moments.append(np.vdot(U,curr).real)
    # Bernstein ellipse: bound on Gaussian analytic continuation is exp[(tau R sinh eta)^2].
    eta=4/(tau_max*scale)
    exponent=(tau_max*scale*sinh(eta))**2-(count-1)*eta
    err=4*np.vdot(U,U).real*exp(exponent)/(exp(eta)-1)
    assert err<1e-12
    return np.array(coeff)@moments,err


def independent(n,q,contact,taus):
    # Direct full diagonalization of all relative momenta and all 16 spins.
    e,a,b,e0,g,d,u=source(n,q,contact)
    count=n**3
    c=np.eye(16) if np.array_equal(contact,IDENTITY) else np.kron(GAMMA[-1],GAMMA[-1])
    h=np.tile(g*c/count,(count,count)).astype(complex)
    for j in range(count):
        s=slice(16*j,16*j+16)
        h[s,s]+=np.kron(a[j],np.eye(4))+np.kron(np.eye(4),b[j])
    values,vecs=np.linalg.eigh(h)
    weights=abs(vecs.conj().T@u.ravel())**2/count
    return np.array([weights@np.exp(-(tau*(values-e0))**2) for tau in taus])


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('mesh',type=int,nargs='?',default=28)
    parser.add_argument('--fine',action='store_true',help='use 48 cubed')
    args=parser.parse_args()
    taus=(0.,.1,.5,1.,2.,4.)
    for name,c in (('density',IDENTITY),('mass',BETA_PAIR)):
        small=gaussian_weights(*compressed(3,.05,c),taus)[0]
        direct=independent(3,.05,c,taus)
        assert np.max(abs(small-direct))<5e-10
        print(f'{name} direct 432-spin-momentum check {max(abs(small-direct)):.2g}',flush=True)
        n=48 if args.fine else args.mesh
        L,D,U,g=compressed(n,.05,c)
        at_edge=abs(L-.1)<1e-10  # zero residue at the free +2 edge: gap +0.1
        assert np.sum(D[at_edge]**2)<1e-20
        green_at_edge=np.sum(D[~at_edge]**2/(.1-L[~at_edge]))
        assert green_at_edge>7/25 and 1/g<7/25
        print(f'  endpoint odd Green {green_at_edge:.9f}, inverse coupling {1/g:.9f}')
        vals,bound=gaussian_weights(L,D,U,g,taus)
        print(f'{name} mesh={n}, uniform polynomial error below {bound:.2g}',flush=True)
        for t,v in zip(taus,vals):
            print(f'  tau={t:.1f} W={v:.10f}, fraction={v/vals[0]:.10f}',flush=True)


if __name__=='__main__':
    main()
energy_improvement.py
"""Finite-range alternatives to the local energy density of the ordered 3D pair."""
import argparse
from math import comb,pi
import numpy as np
from loop_spectrum import (source, compressed, rest_spectrum, IDENTITY, BETA_PAIR,
                           GAMMA, Torus, rest_calibration, Pair, block, wave)

SCALE=80.
CONTACTS=(IDENTITY,BETA_PAIR)
NAMES=('density','mass')


def fit(spectra,degree):
    x=np.concatenate([(gaps/SCALE)**2 for gaps,_ in spectra])
    w=np.concatenate([weights/weights.sum() for _,weights in spectra])
    powers=np.column_stack([x**j for j in range(1,degree+1)])
    coeff,*_=np.linalg.lstsq(np.sqrt(w)[:,None]*powers,-np.sqrt(w),rcond=None)
    return np.r_[1.,coeff]


def evaluate(comp,coeff):
    L,D,U,g=comp
    def centered(v):
        return (L*v+g*D*np.vdot(D,v))/SCALE
    y=coeff[-1]*U
    for a in coeff[-2::-1]:
        y=centered(centered(y))+a*U
    return np.vdot(y,y).real/np.vdot(U,U).real


def full_forward(n,c,coeff):
    e,a,b,e0,g,d,u=source(n,0.,c)
    bt=b.swapaxes(1,2)
    beta=GAMMA[-1]
    def centered(v):
        mean=v.mean(axis=0)
        if np.array_equal(c,BETA_PAIR):
            mean=beta@mean@beta.T
        return (a@v+v@bt+g*mean-e0*v)/SCALE
    y=coeff[-1]*u
    for x in coeff[-2::-1]:
        y=centered(centered(y))+x*u
    return np.vdot(y,y).real/np.vdot(u,u).real


def finite_loop(n,c,coeff,stride=1):
    """Both improved generators, without projecting their intermediate states.

    On an n cubed torus choose q=2pi/n along z, so momentum kicks shift the
    physical constituent-A momentum by exactly one index. Total K=0 initially.
    """
    t=Torus(n)
    cal=rest_calibration(t)
    pair=Pair(t,cal,0.,c)
    energy=pair.energy
    g=1/cal[1]
    q=stride*2*pi/n
    p=[k*(2*pi/n) for k in t.grid]
    ha,ea=block(p)
    hb={}
    for step in (0,-1,1):
        hb[step]=block([-p[0],-p[1],-p[2]+step*q])[0].swapaxes(1,2)
    b0,eb=block([-k for k in p])
    psi=wave(pair.source,energy,ha,ea,b0,eb)
    def shift(v,j):
        return np.roll(v.reshape(n,n,n,4,4),j*stride,axis=2).reshape(-1,4,4)
    def collision(v):
        m=v.mean(axis=0)
        return g*(m if np.array_equal(c,IDENTITY) else GAMMA[-1]@m@GAMMA[-1].T)
    def centered(v,k):
        return (ha@v+v@hb[k]+collision(v)-energy*v)/SCALE
    hak={i:(ha+shift(ha,i))/2 for i in (-1,1)}
    def vertex(v,kin,kout):
        j=kout-kin
        return hak[j]@shift(v,j)+v@((hb[kin]+hb[kout])/2)+collision(v)
    def complete(d):
        base=vertex(psi,0,d)
        first=coeff[-1]*base
        for a in coeff[-2::-1]:
            first=centered(centered(first,d),d)+a*base
        # The second leg is applied to a noneigenstate. Expand ad_H binomially
        # and use Horner evaluation for the left powers of the outgoing H.
        powers=[]
        v=first
        highest=2*(len(coeff)-1)
        for j in range(highest+1):
            powers.append(vertex(v,d,0))
            if j<highest:
                v=centered(v,d)
        result=np.zeros_like(psi)
        for r in range(highest,-1,-1):
            if r<highest:
                result=centered(result,0)
            for l in range(highest-r+1):
                if (r+l)%2==0:
                    result+=((-1)**l*comb(r+l,l)*coeff[(r+l)//2])*powers[l]
        return result
    u=(complete(1)-complete(-1))/(2*q)
    assert abs(np.vdot(psi,u)/n**3)<1e-8
    return np.vdot(u,u).real/n**3


def finite_dense(c,coeff):
    """Three-cubed independent check: filter both vertices in exact energy eigenbases."""
    n=3
    count=n**3
    q=2*pi/n
    cal=rest_calibration(Torus(n))
    kgrid=np.array(list(np.ndindex(n,n,n)))
    p=[kgrid[:,j]*q for j in range(3)]
    A=block(p)[0]
    B={i:block([-p[0],-p[1],-p[2]+i*q])[0] for i in (-1,0,1)}
    spin_c=np.eye(16) if np.array_equal(c,IDENTITY) else np.kron(GAMMA[-1],GAMMA[-1])
    onsite=np.tile(spin_c/(count*cal[1]),(count,count)).astype(complex)
    one=np.eye(4)
    def eigensystem(k):
        h=onsite.copy()
        for i in range(count):
            sl=slice(16*i,16*i+16)
            h[sl,sl]+=np.kron(A[i],one)+np.kron(one,B[k][i])
        return np.linalg.eigh(h)
    e0,v0=eigensystem(0)
    j=np.argmin(abs(e0-1.9))
    assert abs(e0[j]-1.9)<1e-12
    terms=[]
    for step in (1,-1):
        a=onsite.copy()
        for i,(x,y,z) in enumerate(kgrid):
            k=np.ravel_multi_index((x,y,(z+step)%n),(n,n,n))
            src=slice(16*i,16*i+16)
            dest=slice(16*k,16*k+16)
            a[dest,src]+=np.kron((A[k]+A[i])/2,one)
            a[src,src]+=np.kron(one,(B[step][i]+B[0][i])/2)
        ef,vf=eigensystem(step)
        gaps=ef[:,None]-e0[None,:]
        filtered=(vf.conj().T@a@v0)*np.polynomial.polynomial.polyval((gaps/SCALE)**2,coeff)
        terms.append(filtered.conj().T@filtered[:,j])
    u=(terms[0]-terms[1])/(2*q)
    return np.vdot(u,u).real-abs(u[j])**2


def moving_phase(n,k,q,c,coeff):
    """Complete one-pulse norms for a moving initial eigenstate at arbitrary q."""
    t=Torus(n)
    cal=rest_calibration(t)
    pair=Pair(t,cal,k,c)
    p=[v*(2*pi/n) for v in t.grid]
    def symbol(sign,offset):
        return block([sign*p[0],sign*p[1],sign*p[2]+offset])
    def local(v):
        m=v.mean(axis=0)
        return (m if np.array_equal(c,IDENTITY) else GAMMA[-1]@m@GAMMA[-1].T)/cal[1]
    result=[]
    for d in (q,-q):
        hf,ef=symbol(1,(k+d)/2)
        bf,ff=symbol(-1,(k+d)/2)
        hi,ei=symbol(1,(k-d)/2)
        bi,fi=symbol(-1,(k-d)/2)
        a=wave(pair.source,pair.energy,hi,ei,bf,ff)
        b=wave(pair.source,pair.energy,hf,ef,bi,fi)
        outgoing=((hf+hi)@a+b@(bf+bi).swapaxes(1,2))/2+pair.source
        def centered(v):
            return (hf@v+v@bf.swapaxes(1,2)+local(v)-pair.energy*v)/SCALE
        y=coeff[-1]*outgoing
        for coef in coeff[-2::-1]:
            y=centered(centered(y))+coef*outgoing
        result.append(np.vdot(y,y).real/n**3)
    return (result[0]-result[1])/(2*q)


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--fine',action='store_true',help='validate at 64 cubed instead of 36 cubed')
    parser.add_argument('--finite',action='store_true',help='also evaluate the full finite-q loop on periodic boxes')
    args=parser.parse_args()
    train=24
    test=64 if args.fine else 36
    spectra=[rest_spectrum(train,0.,c,32) for c in CONTACTS]
    checks=[compressed(test,0.,c) for c in CONTACTS]
    fits=[]
    for degree in (1,2,3):
        coeff=fit(spectra,degree)
        fits.append(coeff)
        ratios=[evaluate(data,coeff) for data in checks]
        print(f'degree {degree}, p(x) coefficients {coeff.tolist()}; test loss fractions {ratios}',flush=True)
    for name,spec in zip(NAMES,spectra):
        coeff=fit([spec],3)
        print(f'train {name} only; held-out density and mass loss fractions',
              [evaluate(data,coeff) for data in checks],flush=True)
    for data in checks:
        fractions=[evaluate(data,poly) for poly in fits]
        assert 0<fractions[2]<fractions[1]<fractions[0]<1
    coeff=fits[-1]
    safe=np.array([1.,-.75,3/16,-1/64])  # (1 - (Delta/160)^2)^3
    print('bounded comparison fractions:',[evaluate(data,safe) for data in checks])
    print('joint cubic amplitude factor at gap 60:',np.polynomial.polynomial.polyval((60/SCALE)**2,coeff))
    for name,c in zip(NAMES,CONTACTS):
        comp=compressed(18,0.,c)
        raw=full_forward(18,c,coeff)
        gaps,weights=rest_spectrum(18,0.,c,20)
        profile=np.polynomial.polynomial.polyval((gaps/SCALE)**2,coeff)
        ritz=np.sum(weights*profile**2)/weights.sum()
        assert max(abs(raw-ritz),abs(raw-evaluate(comp,coeff)))<2e-10
        print(f'{name} direct full-state and Ritz check: {raw:.10f}, {ritz:.10f}',flush=True)
    if args.finite:
        for name,c in zip(NAMES,CONTACTS):
            direct=finite_loop(3,c,coeff)
            dense=finite_dense(c,coeff)
            assert abs(direct-dense)<1e-9
            print(f'{name} finite-q 432-dimensional energy-eigenbasis error: {direct-dense:.3g}')
        for n in (16,24,32):
            for name,c in zip(NAMES,CONTACTS):
                raw=finite_loop(n,c,np.array([1.]))
                improved=finite_loop(n,c,coeff)
                print(f'finite {n} cubed q={2*pi/n:.7f} {name}: unmodified {raw:.8f}, '
                      f'improved {improved:.8f}, fraction={improved/raw:.8f}',flush=True)
        if args.fine:
            for name,c in zip(NAMES,CONTACTS):
                raw=finite_loop(48,c,np.array([1.]),stride=2)
                changed=finite_loop(48,c,coeff,stride=2)
                print(f'fixed q=2pi/24, 48 cubed {name}: fraction {changed/raw:.9f}',flush=True)
        for name,c in zip(NAMES,CONTACTS):
            for q in (.05,.025,.0125):
                ph=moving_phase(40,.10,q,c,coeff)
                print(f'moving {name} K=.10 q={q:g}: improved <B>/q={ph:.9f}',flush=True)


if __name__=='__main__':
    main()
tensor_lattice.py
"""Staggered linearized ADM on a periodic cubic spatial grid. Python 3 + NumPy."""
from itertools import product
import numpy as np

AX = range(3)
FOUR = range(4)
ETA = (-1, 1, 1, 1)
ALPHA = 4.0  # 16 pi G: the static Poisson coefficient 4 pi G is one
RNG = np.random.default_rng(20261201)


def bit(i):
    return 1 << i


def derivatives(field, mask, *axes):
    """The input lives on half-grid mask; each derivative toggles one bit (a=1)."""
    for i in axes:
        if mask & bit(i):
            field = field - np.roll(field, 1, axis=i)
        else:
            field = np.roll(field, -1, axis=i) - field
        mask ^= bit(i)
    return field


def symmetric(rows, n):
    raw = RNG.integers(-3, 4, size=(rows, rows, n, n, n))
    return raw + raw.swapaxes(0, 1)


def mat(f):
    return np.array([[f(i, j) for j in AX] for i in AX])


def trace(t):
    return sum(t[i, i] for i in AX)


def div_tensor(t):
    return np.array([sum(derivatives(t[i, j], bit(i)^bit(j), j) for j in AX)
                     for i in AX])


def div_vector(v):
    return sum(derivatives(v[i], bit(i), i) for i in AX)


def lap(f, mask=0):
    return sum(derivatives(f, mask, i, i) for i in AX)


def hessian_trace_adjusted(f):
    lf = lap(f)
    return mat(lambda i, j: derivatives(f, 0, i, j) - (i == j)*lf)


def spatial_curvature(h):
    div = div_tensor(h)
    tr = trace(h)
    scalar = div_vector(div) - lap(tr)
    def twice_einstein(i, j):
        return (derivatives(div[j], bit(j), i) + derivatives(div[i], bit(i), j)
                - lap(h[i, j], bit(i)^bit(j)) - derivatives(tr, 0, i, j)
                - (i == j)*scalar)
    return scalar, mat(twice_einstein)/2


def sym_grad(v):
    return mat(lambda i, j: derivatives(v[j], bit(j), i) + derivatives(v[i], bit(i), j))


def kinetic(p):
    tr = trace(p)
    return mat(lambda i, j: 2*p[i, j] - (i == j)*tr)


def canonical_rhs(h, p, lapse, shift, stress):
    _, g3 = spatial_curvature(h)
    return kinetic(p)+sym_grad(shift), -g3+hessian_trace_adjusted(lapse)+ALPHA*stress/2


def constraints(h, p, density, current):
    scalar, _ = spatial_curvature(h)
    return scalar - ALPHA*density, -2*div_tensor(p) - ALPHA*current


def spatial_mask(a):
    return 0 if a == 0 else bit(a-1)


def spacetime_einstein(jets):
    """Independent covariant G_ab using flat signature -+++; jets = h, hdot, hddot."""
    def dd(a, b, mu, nu):
        spatial = tuple(d-1 for d in (mu, nu) if d)
        order = 2-len(spatial)
        return derivatives(jets[order][a, b], spatial_mask(a)^spatial_mask(b), *spatial)

    def wave(a, b):
        return sum(ETA[c]*dd(a, b, c, c) for c in FOUR)

    scalar = sum(ETA[c]*ETA[d]*dd(c, d, c, d) for c in FOUR for d in FOUR)
    scalar -= sum(ETA[c]*wave(c, c) for c in FOUR)
    def comp(a, b):
        r = sum(ETA[c]*(dd(c, b, a, c)+dd(c, a, b, c)-dd(c, c, a, b)) for c in FOUR)
        return (r-wave(a, b)-(a == b)*ETA[a]*scalar)/2
    return np.array([[comp(a, b) for b in FOUR] for a in FOUR])


def peak(*fields):
    return max(float(np.max(np.abs(f))) for f in fields)


def check_bianchi(n=4):
    jets = [symmetric(4, n) for _ in range(4)]
    g = spacetime_einstein(jets[:3])
    dg = spacetime_einstein(jets[1:])
    residuals = [-dg[0, b]+sum(derivatives(g[a, b], spatial_mask(a)^spatial_mask(b), a-1)
                              for a in (1, 2, 3)) for b in FOUR]
    vectors = RNG.integers(-3, 4, size=(4, 4, n, n, n))
    def dx(t, a, b):
        if a == 0:
            return vectors[t+1, b]
        return derivatives(vectors[t, b], spatial_mask(b), a-1)
    gauge = [np.array([[dx(t, a, b)+dx(t, b, a) for b in FOUR] for a in FOUR])
             for t in range(3)]
    result = peak(*residuals, spacetime_einstein(gauge))
    assert result == 0
    return result


def check_canonical(n=4):
    h, p, stress = [symmetric(3, n) for _ in range(3)]
    lapse, rho = RNG.integers(-3, 4, size=(2, n, n, n))
    shift, current, dshift = RNG.integers(-3, 4, size=(3, 3, n, n, n))
    dh, dp = canonical_rhs(h, p, lapse, shift, stress)
    _, momentum = constraints(h, p, rho, current)
    drho, dj = -div_vector(current), -div_tensor(stress)
    dc, dm = constraints(dh, dp, drho, dj)
    # Arbitrary initial data: the homogeneous constraint law holds even off shell.
    assert peak(dc+div_vector(momentum), dm) == 0
    # Residual from adding a unit of unbalanced local energy / current derivative.
    bad_rho = drho.copy()
    bad_rho[0, 0, 0] += 1
    bad_c, _ = constraints(dh, dp, bad_rho, dj)
    assert peak(bad_c+div_vector(momentum)) == ALPHA
    jets = np.zeros((3, 4, 4, n, n, n))
    jets[0, 0, 0] = -2*lapse
    for t, vec in enumerate((shift, dshift)):
        jets[t, 0, 1:] = jets[t, 1:, 0] = vec
    jets[:, 1:, 1:] = [h, dh, kinetic(dp)+sym_grad(dshift)]
    g = spacetime_einstein(jets)
    r, _ = spatial_curvature(h)
    assert peak(2*g[0, 0]-r, g[0, 1:]-div_tensor(p), 2*g[1:, 1:]-ALPHA*stress) == 0

    # Quadratic Hamiltonian directional gradient with all fields varied on their own grids.
    def energy(x, y):
        scalar, g3 = spatial_curvature(x)
        return (np.sum(y*y)-np.sum(trace(y)**2)/2 + np.sum(x*g3)/2
                - np.sum(lapse*scalar)-2*np.sum(shift*div_tensor(y))
                - ALPHA*np.sum(x*stress)/2)
    a, b = symmetric(3, n), symmetric(3, n)
    finite = (energy(h+a, p+b)-energy(h-a, p-b))/2
    assert finite == np.sum(b*dh)-np.sum(a*dp)
    return peak(bad_c+div_vector(momentum))


def modes(n=8):
    pairs = [(i,j) for i in AX for j in range(i,3)]
    axis = 2*np.sin(np.pi*np.fft.fftfreq(n))
    count = 0
    for k in product(axis, repeat=3):
        q = np.array(k)
        if np.linalg.norm(q) == 0:
            continue
        div = np.array([[(i == a)*q[b]+(b != a)*(i == b)*q[a] for a,b in pairs]
                        for i in AX])
        tr = np.array([a == b for a,b in pairs])
        q2 = q@q
        r = np.array([(q2 if a == b else 0)-(1 if a == b else 2)*q[a]*q[b]
                      for a,b in pairs])
        assert np.linalg.matrix_rank(div) == 3 and np.linalg.norm(r)>0
        assert np.linalg.matrix_rank(np.vstack([div,tr])) == 4
        count += 1
    assert count==n**3-1
    # Same Euclidean wave-number length, two orientations of the cubic grid.
    same_length = ((3,0,0),(2,2,1))
    freq = [np.linalg.norm(2*np.sin(np.pi*np.array(m)/n)) for m in same_length]
    assert freq[0] < freq[1]
    return count, freq


def check_waves(n=8):
    labels=np.array([1, 2, -1])
    k=2*np.pi*labels/n
    q=2*np.sin(k/2)
    u=np.cross(q,[0.,0.,1.])
    u/=np.linalg.norm(u)
    v=np.cross(q,u)/np.linalg.norm(q)
    pols=[np.outer(u,u)-np.outer(v,v), np.outer(u,v)+np.outer(v,u)]
    coords=np.indices((n,)*3)
    def field(pol, angle):
        def comp(i,j):
            mask=bit(i)^bit(j)
            arg=sum(k[d]*(coords[d]+0.5*bool(mask & bit(d))) for d in AX)
            return pol[i,j]*np.cos(arg+angle)
        return mat(comp)
    h=field(pols[0],0) + .4*field(pols[1],.3)
    p=field(pols[1],.7)/3
    r,g=spatial_curvature(h)
    q2=q@q
    residual=peak(r,div_tensor(h),trace(h),2*g-q2*h)
    assert residual<2e-13
    # Strang kick-drift-kick using the full local gravity RHS, without a TT projection.
    # Initial data deliberately mix both oscillators with different initial phases.
    def trajectory(dt,steps):
        x,y=h.copy(),p.copy()
        for _ in range(steps):
            y-=dt/2*spatial_curvature(x)[1]
            x+=dt*kinetic(y)
            y-=dt/2*spatial_curvature(x)[1]
        omega=np.sqrt(q2)
        exact=h*np.cos(omega*dt*steps)+2*p/omega*np.sin(omega*dt*steps)
        e0=np.sum(p*p)+np.sum(h*g)/2
        e1=np.sum(y*y)-np.sum(trace(y)**2)/2+np.sum(x*spatial_curvature(x)[1])/2
        assert e0>0
        return peak(x-exact), peak(div_tensor(y),spatial_curvature(x)[0]), abs(e1/e0-1)
    coarse, fine=trajectory(.04,30), trajectory(.02,60)
    assert 3.8<coarse[0]/fine[0]<4.2 and fine[1]<2e-12
    return np.sqrt(q2), coarse, fine


def static_source(n=16):
    rho=np.full((n,)*3,-1/n**3)
    rho[0,0,0]+=1
    q=2*np.sin(np.pi*np.fft.fftfreq(n))
    q2=sum(x*x for x in np.ix_(q,q,q))
    kernel=np.zeros_like(q2)
    kernel[q2>0]=-1/q2[q2>0]
    phi=np.fft.ifftn(kernel*np.fft.fftn(rho)).real
    h=mat(lambda i,j:-2*(i==j)*phi)
    zero=np.zeros_like(h)
    dh,dp=canonical_rhs(h,zero,phi,zero[0],zero)
    c,m=constraints(h,zero,rho,zero[0])
    residual=peak(dh,dp,c,m,lap(phi)-rho)
    assert residual<1e-12
    # Sum outward normal gradients over the six faces of a 5^3 cube.
    rad=2
    flux=0.
    for i in AX:
        grad=derivatives(phi,0,i)
        transverse=[j for j in AX if j!=i]
        for x,y in product(range(-rad,rad+1),repeat=2):
            pos=[0]*3
            pos[transverse[0]],pos[transverse[1]]=x,y
            pos[i]=rad
            flux+=grad[tuple(pos)]
            pos[i]=-rad-1
            flux-=grad[tuple(pos)]
    expected=1-(2*rad+1)**3/n**3
    assert abs(flux-expected)<1e-12 and phi[0,0,0]<0
    # A divergence-free transverse stress with no density.
    # Specify the stress from a compact scalar f: S_ij=(delta_ij Lap-D_i D_j)f.
    source=zero[0,0].copy()
    source[1,2,0]=1
    source-=np.mean(source)
    stress=-hessian_trace_adjusted(source)
    lapse=ALPHA*source/2  # Delta n = ALPHA*tr(S)/4
    _,dp=canonical_rhs(zero,zero,lapse,zero[0],stress)
    assert peak(div_tensor(stress),dp,lap(lapse)-ALPHA*trace(stress)/4)<1e-12
    return phi[0,0,0], flux, residual


def main():
    print("Bianchi and pure-gauge identities max residual",check_bianchi())
    print("Canonical Hamiltonian gradient and constraint identities pass. Unit injected source defect",check_canonical())
    count, freq=modes()
    print("Nonzero 8^3 momenta with two TT amplitudes",count)
    print(f"Equal-length (3,0,0) and (2,2,1) frequencies {freq[0]:.10f}, {freq[1]:.10f}")
    omega,coarse,fine=check_waves()
    print(f"Oblique TT frequency {omega:.12f}")
    for dt,data in ((.04,coarse),(.02,fine)):
        print(f"dt {dt:.2f} displacement error {data[0]:.10g}, constraint {data[1]:.3g}, relative energy drift {data[2]:.3g}")
    phi,flux,error=static_source()
    print(f"Newtonian central potential {phi:.12f}, outward flux {flux:.12f}, canonical residual {error:.3g}")


if __name__=="__main__":
    main()
network_polarization.py
"""GW170814 three-site polarization projections. Default uses frozen filter statistics."""
import argparse
from hashlib import sha256
from math import asin, atan2, cos, degrees, pi, radians, sin, sqrt
from pathlib import Path
from urllib.request import urlopen

# Earth-fixed coordinates (metres) and upper triangles of the dimensionless response
# tensors, in Hanford, Livingston, Virgo order. Signs follow LAL's calibrated arms.
SITES = (
    ((-2161414.92636, -3834695.17889, 4600350.22664),
     (-.3926140964, -.07761341333, -.24738904834, .31952407956, .22799783945, .07309003174)),
    ((-74276.0447238, -5496283.71971, 3224257.01744),
     (.41128087044, .14021027088, .24729458988, -.10900568962, -.18161563575, -.30227515101)),
    ((4546374.099, 842989.697626, 4378576.96241),
     (.24387404323, -.09908378124, -.23257622123, -.44782584906, .18783310056, .20395180583)),
)
C_LIGHT = 299792458
GMST = 2.1069911633280825  # radians, LAL at GPS 1186741861.53
SKY_RA, SKY_DEC = 47.75, -44.95  # rounded collaboration maximum under its tensor model
STRAIN_BASE = "https://dcc.ligo.org/public/0146/P1700341/001/"
SHA = (
    "83c965394a55108091c689c1c458fa18410dbbe4fee32364d905e0562471262d",
    "6f18a52d8e2466dbb092ad8be503943d83dee8a24bf0c5b11b93aa943cdd430f",
    "b3b00c0feba1d0325f3568f9b908510bdd2f9bce5bd45e2c93acb677fc7f74d2",
)
# (detector-frame solar masses; relative filter sensitivities; three complex data)
FILTERS = (
    ((33, 28), (.7704872009, 1., .2959552981),
     (8.99096383-3.32458103j, -9.44824868+8.58617363j, -2.53983568+3.66434072j)),
    ((31, 26), (.7629674488, 1., .2946010733),
     (-4.24131485-8.37497967j, 8.61143832+7.86294126j, 4.11397132+1.03630722j)),
    ((35, 30), (.7755986376, 1., .2981250956),
     (2.93852993+8.42863832j, -8.15056934-8.02792036j, -3.32966049-2.96057840j)),
)
PEAK_DELAYS = (.00838512586, .01470144625)
PEAK_DATA = (9.13960908-2.90041434j, -10.03895340+7.90796850j, -4.25513131+1.74949373j)


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


def cross(a, b):
    return (a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0])


def unit(v):
    scale = sqrt(dot(v, v))
    return tuple(x/scale for x in v)


def direction(ra, dec):
    phi, lat = radians(ra)-GMST, radians(dec)
    return (cos(phi)*cos(lat), sin(phi)*cos(lat), sin(lat))


def coordinates(n):
    return degrees(atan2(n[1], n[0])+GMST) % 360, degrees(asin(n[2]))


def baselines():
    return [tuple((a-b)/C_LIGHT for a, b in zip(SITES[i][0], SITES[1][0])) for i in (0, 2)]


def timing_pair(h_minus_l, v_minus_l):
    a, b = baselines()
    aa, ab, bb = dot(a, a), dot(a, b), dot(b, b)
    det = aa*bb-ab*ab
    ca = (-bb*h_minus_l+ab*v_minus_l)/det
    cb = (ab*h_minus_l-aa*v_minus_l)/det
    plane = tuple(ca*x+cb*y for x, y in zip(a, b))
    height = sqrt(1-dot(plane, plane))
    normal = unit(cross(a, b))
    return sorted([tuple(x+s*height*y for x, y in zip(plane, normal)) for s in (-1, 1)],
                  key=lambda n: coordinates(n)[1])


def antenna(n):
    p = unit(cross((0, 0, 1), n))
    q = cross(n, p)
    rows = []
    for _, (xx, xy, xz, yy, yz, zz) in SITES:
        tensor = ((xx, xy, xz), (xy, yy, yz), (xz, yz, zz))
        def product(a, b):
            return sum(x*dot(row, b) for x, row in zip(a, tensor))
        pp, qq = product(p, p), product(q, q)
        rows.append((pp-qq, 2*product(p, q), 2*product(p, n), 2*product(q, n), pp+qq))
    return rows


def project(direction_vector, sensitivity, data):
    response = antenna(direction_vector)
    columns = [tuple(s*r[k] for s, r in zip(sensitivity, response)) for k in range(5)]
    # For rank two, a unit vector perpendicular to both real antenna columns
    # annihilates both arbitrary complex amplitudes. For rank one, remove its projection.
    tnull = unit(cross(*columns[:2]))
    vnull = unit(cross(*columns[2:4]))
    breath = unit(columns[4])
    total = sum(abs(z)**2 for z in data)
    return abs(dot(tnull, data)), abs(dot(vnull, data)), sqrt(max(0, total-abs(dot(breath, data))**2))


def replay():
    n = direction(SKY_RA, SKY_DEC)
    dt = [-dot(b, n) for b in baselines()]
    south, north = timing_pair(*dt)
    assert max(abs(x-y) for x, y in zip(south, n)) < 1e-10
    for v in (south, north):
        assert max(abs(-dot(b, v)-d) for b, d in zip(baselines(), dt)) < 1e-12
    print("Fixed delays H-L and V-L (ms):", *(f"{v*1000:.5f}" for v in dt))
    for masses, sensitivity, strain in FILTERS:
        left, right = (project(d, sensitivity, strain) for d in (south, north))
        assert left[0] < 1.52 and right[0] > 5.2
        print("Masses", masses, "tensor residuals", f"{left[0]:.5f}", f"{right[0]:.5f}")
        if masses == (33, 28):
            assert abs(left[0]-.94915975) < 1e-6 and abs(right[0]-5.66717107) < 1e-6
            print("Tensor/vector/scalar:", [round(v, 5) for v in left], [round(v, 5) for v in right])
            for sky, fit in ((south, left), (north, right)):
                antenna_rows = antenna(sky)
                matrix = [tuple(s*r[k] for s, r in zip(sensitivity, antenna_rows)) for k in (0, 1)]
                weights = unit(cross(*matrix))
                virgo = -(weights[0]*strain[0]+weights[1]*strain[1])/weights[2]
                assert abs(abs(weights[2]*(strain[2]-virgo))-fit[0]) < 1e-8
                print(f"Virgo from the two LIGO amplitudes: {virgo:.3f}; observed {strain[2]:.3f}")
    print("Independent peak-time solutions:")
    for d, expected in zip(timing_pair(*PEAK_DELAYS), (2.50016, 5.99940)):
        result = project(d, FILTERS[0][1], PEAK_DATA)[0]
        assert abs(result-expected) < .00002
        print("RA and dec (deg), tensor residual:", *(f"{a:.5f}" for a in (*coordinates(d), result)))


def raw_check(folder):
    """Regenerate the compressed statistics and fixed-window background from GWOSC."""
    import numpy as np
    import lal
    import lalsimulation as ls
    from scipy.signal import periodogram, windows

    folder.mkdir(exist_ok=True, parents=True)
    records = []
    for site, pin in zip("HLV", SHA):
        name = f"{site}-{site}1_LOSC_CLN_4_V1-1186741845-32.txt.gz"
        path = folder/name
        if not path.exists():
            with urlopen(STRAIN_BASE+name, timeout=60) as response:
                data = response.read()
            if sha256(data).hexdigest() != pin:
                raise ValueError(f"Unexpected download for {name}")
            path.write_bytes(data)
        if sha256(path.read_bytes()).hexdigest() != pin:
            raise ValueError(f"Different strain file at {path}")
        records.append(np.loadtxt(path))
    fs, duration = 4096, 32
    count = fs*duration
    frequency = np.fft.rfftfreq(count, 1/fs)
    keep = np.flatnonzero((frequency>=30) & (frequency<=300))
    frequency = frequency[keep]
    spectra, noises = [], []
    for data in records:
        spectra.append(np.fft.rfft(windows.tukey(count, alpha=.12)*data)[keep]/fs)
        pieces = []
        for start in range(31):
            if 14 <= start <= 18:
                continue
            bins, spectrum = periodogram(data[start*fs:(start+2)*fs], fs, window="hann")
            pieces.append(spectrum)
        noises.append(np.interp(frequency, bins, np.mean(pieces, axis=0)))
    n = direction(SKY_RA, SKY_DEC)
    delay_h, delay_v = [-dot(b, n) for b in baselines()]
    delays = np.array([delay_h, 0., delay_v])
    sample_times = np.arange(count)/fs
    for masses, sensitivities, frozen in FILTERS:
        h, _ = ls.SimInspiralChooseFDWaveform(
            masses[0]*lal.MSUN_SI, masses[1]*lal.MSUN_SI, 0., 0., 0., 0., 0., 0.,
            1e8*lal.PC_SI, 0., 0., 0., 0., 0., 1/duration, 25., 512., 30.,
            lal.CreateDict(), ls.IMRPhenomD)
        template = h.data.data[keep]
        norms, aligned, unshifted, products = [], [], [], []
        for spectrum, noise, delay in zip(spectra, noises, delays):
            norm = np.sqrt(4/duration * np.sum(abs(template)**2/noise))
            norms.append(norm)
            coefficients = 4/duration * spectrum*np.conjugate(template)/noise/norm
            products.append(coefficients)
            bins = np.zeros(count, dtype=complex)
            bins[keep] = coefficients
            unshifted.append(np.fft.ifft(bins)*count)
            bins[keep] *= np.exp(2j*np.pi*frequency*delay)
            aligned.append(np.fft.ifft(bins)*count)
        aligned = np.asarray(aligned)
        ratios = np.array(norms)/norms[1]
        on = np.flatnonzero((sample_times>16.48) & (sample_times<16.57))
        tick = on[np.argmax(abs(aligned[1, on]))]
        measured = aligned[:, tick]
        assert np.allclose(ratios, sensitivities, rtol=2e-6)
        assert np.allclose(measured, frozen, rtol=2e-5, atol=2e-5)
        print("Raw strain agrees for masses", masses, "site SNRs", np.abs(measured).round(3))
        if masses != (33, 28):
            continue
        times, independent_data = [], []
        for signal, coeff in zip(unshifted, products):
            lo, hi = int(16.48*fs), int(16.60*fs)
            mid = lo + np.argmax(np.abs(signal[lo:hi]))
            left, center, right = np.abs(signal[mid-1:mid+2])**2
            t = (mid+.5*(left-right)/(left-2*center+right))/fs
            times.append(t)
            independent_data.append(np.sum(coeff*np.exp(2j*np.pi*frequency*t)))
        assert np.allclose(np.array(times)[[0, 2]]-times[1], PEAK_DELAYS, atol=2e-8, rtol=0)
        assert np.allclose(independent_data, PEAK_DATA, rtol=2e-5)
        for sky in timing_pair(delay_h, delay_v):
            off = []
            for mid in np.r_[np.arange(3,13.01,.25),np.arange(20,29.01,.25)]:
                window = np.arange(int((mid-.045)*fs), int((mid+.045)*fs)+1)
                j = window[np.argmax(abs(aligned[1, window]))]
                off.append(project(sky, ratios, aligned[:,j])[0])
            print("78 control windows, 10th/50th/90th percentile null:",
                  np.percentile(off, (10, 50, 90)).round(4))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--from-strain", type=Path, help="cache and analyze the three checksum-pinned GWOSC files")
    args = parser.parse_args()
    replay()
    if args.from_strain:
        raw_check(args.from_strain)
quadrupole_exchange.py
"""Exchange between one mechanical quadrupole and transverse tensor modes (NumPy)."""
from itertools import product
import numpy as np

G, SIGMA, OMEGA = .15, .6, 1.2
LBOX = 4*np.pi
S = np.diag([1.,-1.,0.])/np.sqrt(2)


def transverse(n):
    p=np.eye(3)-np.outer(n,n)
    transverse_stress=p@S@p
    return transverse_stress-p*np.trace(transverse_stress)/2


def polarizations(n):
    seed=np.eye(3)[np.argmin(np.abs(n))]
    u=np.cross(n,seed)
    u/=np.linalg.norm(u)
    v=np.cross(n,u)
    return (np.outer(u,u)-np.outer(v,v))/np.sqrt(2),(np.outer(u,v)+np.outer(v,u))/np.sqrt(2)


def angular_check():
    nodes,weights=np.polynomial.legendre.leggauss(12)
    total=0.
    for mu,w in zip(nodes,weights):
        s=np.sqrt(1-mu**2)
        for az in np.arange(24)*2*np.pi/24:
            n=np.array([s*np.cos(az),s*np.sin(az),mu])
            proj=transverse(n)
            power=np.sum(proj**2)
            assert abs(power-sum(np.sum(e*S)**2 for e in polarizations(n)))<2e-15
            total+=w*power/48
    assert abs(total-.4*np.sum(S**2))<2e-15
    return total


def discrete_modes(cut):
    labels=[]; magnitudes=[]; couplings=[]
    v=LBOX**3
    for triple in product(range(-cut,cut+1),repeat=3):
        m=np.array(triple)
        first_nonzero=next((x for x in triple if x),0)
        if first_nonzero<=0:
            continue
        norm2=m@m
        if norm2>cut**2:
            continue
        k=2*np.pi*np.sqrt(norm2)/LBOX
        W=np.exp(-SIGMA**2*k**2/2)
        for pol,e in enumerate(polarizations(m/np.sqrt(norm2))):
            g=-np.sqrt(4*np.pi*G/v)*W*np.sum(e*S)
            labels.append((*triple,pol))
            magnitudes.append(k)
            couplings.append(g)
    return labels,np.asarray(magnitudes),np.asarray(couplings)


def velocities(p,g):
    v=np.empty_like(p)
    v[0]=(p[0]-g@p[1:])/(1-g@g)
    v[1:]=p[1:]-g*v[0]
    return v


def evolve(y,p,g,w,t,steps):
    dt=t/steps
    y,p=y.copy(),p.copy()
    w2=w*w
    for _ in range(steps):
        p-=dt*w2*y/2
        y+=dt*velocities(p,g)
        p-=dt*w2*y/2
    return y,velocities(p,g)


def energies(y,v,g,w):
    return np.array([.5*(v[0]**2+(w[0]*y[0])**2),
                     .5*(v[1:]@v[1:]+(w[1:]*y[1:])@(w[1:]*y[1:])),
                     v[0]*(g@v[1:])])


def normal_release(k,g,t):
    # At equal bare frequency only the combination parallel to g couples.
    shells,inv=np.unique(k,return_inverse=True)
    b=np.sqrt(np.bincount(inv,weights=g*g))
    mass=np.eye(len(b)+1)
    mass[1:,0]=mass[0,1:]=b
    stiffness=np.diag(np.r_[OMEGA,shells]**2)
    d,u=np.linalg.eigh(mass)
    assert min(d)>0
    im=(u*d**(-.5))@u.T
    sm=(u*d**.5)@u.T
    q,v=np.linalg.eigh(im@stiffness@im)
    f=np.sqrt(q)
    initial=v.T@sm[:,0]
    y=im@v@(np.cos(f*t)*initial)
    dy=im@v@(-f*np.sin(f*t)*initial)
    return energies(y,dy,b,np.r_[OMEGA,shells])


def box_test(cut=8):
    labels,k,g=discrete_modes(cut)
    assert g@g<1
    w=np.r_[OMEGA,k]
    z=np.zeros_like(w)
    tc=6.
    mech=z.copy(); mech[0]=1.
    exact=normal_release(k,g,tc)
    for steps in (600,1200):
        y,v=evolve(mech,z,g,w,tc,steps)
        e=energies(y,v,g,w)
        error=np.max(abs(e-exact))
        if steps==600:
            coarse=error
        else:
            assert 3.8<coarse/error<4.2
    assert abs(sum(exact)-OMEGA**2/2)<1e-12 and exact[1]>.05
    # True initial field displacement with zero velocity in every degree of freedom.
    j=1+labels.index((0,0,2,0))
    j_dark=1+labels.index((0,0,2,1))
    incoming=z.copy(); incoming[j]=OMEGA/w[j]
    y,v=evolve(incoming,z,g,w,tc,1200)
    absorption=energies(y,v,g,w)[0]
    incoming_dark=z.copy(); incoming_dark[j_dark]=OMEGA/w[j_dark]
    y,v=evolve(incoming_dark,z,g,w,tc,1200)
    assert absorption>1e-5 and abs(y[0])+abs(v[0])<1e-14
    # Impulses specify canonical momentum rather than bare velocity.
    pj=z.copy(); pj[j]=1.
    out,_=evolve(z,mech,g,w,tc,1200)
    back,_=evolve(z,pj,g,w,tc,1200)
    assert abs(out[j]-back[0])<1e-12
    return len(g),g@g,exact,error,absorption,out[j]


def fourier_q(k,width):
    return width*np.sqrt(np.pi/2)*(np.exp(-.5*width**2*(k-OMEGA)**2)
                                 +np.exp(-.5*width**2*(k+OMEGA)**2))


def packet_box(nper,width):
    # Full list of signed k uses the complex convention, with the reality factor.
    kmax=4.5
    k=np.arange(-int(kmax*nper),int(kmax*nper)+1)/nper
    x,y,z=np.ix_(k,k,k)
    k2=x*x+y*y+z*z
    safe=np.where(k2==0,1,k2)
    # STF unit S=diag(1,-1,0)/sqrt(2). Contract projector explicitly.
    tt=1-(x*x+y*y)/safe+(x*x-y*y)**2/(4*safe**2)
    weight=tt*np.exp(-SIGMA**2*k2)*k2**2*fourier_q(np.sqrt(k2),width)**2
    return np.pi*G*np.sum(np.where(k2<=kmax**2,weight,0))/(2*np.pi*nper)**3


def packet_test(angular):
    width=3.
    nodes,weights=np.polynomial.legendre.leggauss(100)
    k=3*(nodes+1)
    f=fourier_q(k,width)
    # Start with one-half g^2 k^4 |Qhat|^2 per real mode, then integrate its density.
    e_modes=(np.pi*G/(2*np.pi)**3)*4*np.pi*angular*np.sum(3*weights*np.exp(-SIGMA**2*k*k)*k**6*f**2)
    variance=width**2+SIGMA**2
    nu=OMEGA*width**2/variance
    amp=width/np.sqrt(variance)*np.exp(-OMEGA**2*width**2*SIGMA**2/(2*variance))
    t=np.linspace(-10*np.sqrt(variance),10*np.sqrt(variance),4097)
    d=-t/variance+1j*nu
    q3=(amp*(d**3-3*d/variance)*np.exp(-t*t/(2*variance)+1j*nu*t)).real
    e_time=G/5*np.sum(q3*q3)*(t[1]-t[0])
    assert abs(e_modes-e_time)<1e-12
    sums=[packet_box(n,width) for n in (2,4,8)]
    assert abs(sums[-1]-e_time)<1e-11 and abs(sums[0]-e_time)>1e-5
    return e_time,sums


def source_check():
    k=np.array([.3,-1.7,.8])
    sd=S@k
    # Suppress the common W(k)/2. Use time derivatives of a freely chosen history.
    q,dq,ddq=.7,-.8,1.3
    rho=-q*(k@sd)
    drho=-dq*(k@sd)
    j=-1j*dq*sd
    dj=-1j*ddq*sd
    stress=ddq*S
    assert abs(drho+1j*k@j)<1e-15 and np.max(abs(dj+1j*k@stress))<1e-15
    # Compute mass moments from the differentiated Gaussian (Gauss-Hermite quadrature).
    nodes,weights=np.polynomial.hermite.hermgauss(5)
    monopole=0.
    dipole=np.zeros(3)
    quadrupole=np.zeros((3,3))
    for ix in product(range(len(nodes)),repeat=3):
        v=np.sqrt(2)*SIGMA*nodes[list(ix)]
        prob=np.prod(weights[list(ix)])/np.pi**1.5
        dm=prob*q*(v@S@v)/(2*SIGMA**4)
        monopole+=dm
        dipole+=dm*v
        quadrupole+=dm*(np.outer(v,v)-np.eye(3)*(v@v)/3)
    assert max(abs(monopole),np.max(abs(dipole)),np.max(abs(quadrupole-q*S)))<1e-14


def main():
    source_check()
    ang=angular_check()
    print(f"angular TT mean {ang:.12f}")
    for cut in (6,8):
        size,coupling,e,error,absorb,recip=box_test(cut)
        print(f"cut={cut} cosine polarization coordinates={size}, sum(g^2)={coupling:.9f}")
        print(f"release t=6: mechanical={e[0]:.10f}, field={e[1]:.10f}, interaction={e[2]:+.10f}, total={sum(e):.10f}, Verlet max error={error:.3g}")
        print(f"axial mode preparation transfers mechanical energy={absorb:.9f}; reciprocal unit-impulse displacements={recip:+.9f}")
    power=G*OMEGA**6*np.exp(-SIGMA**2*OMEGA**2)/10
    energy,sums=packet_test(ang)
    print(f"monochromatic mean power={power:.10f}; continuum packet energy={energy:.12f}")
    print("periodic packet energy at L/(2*pi)=2,4,8:",*(f"{e:.12f}" for e in sums))


if __name__=="__main__":
    main()
wave_weight.py
"""Vacuum Einstein CMC initial data on a cubic three-torus. Requires NumPy."""
import numpy as np

AX = range(3)
K_WAVE = 1  # box periods 2*pi in all directions, c=1


def conformal_tensor(z, a, quadrature=False):
    """Contravariant TT seed referred to the flat conformal metric."""
    scale = a/np.sqrt(2) if quadrature else a
    tensor = np.zeros((len(z), 3, 3))
    tensor[:, 0, 0] = scale*np.cos(K_WAVE*z)
    tensor[:, 1, 1] = -tensor[:, 0, 0]
    if quadrature:
        tensor[:, 0, 1] = tensor[:, 1, 0] = scale*np.sin(K_WAVE*z)
    return tensor


def solve(a, n=48, quadrature=False):
    """Solve simultaneously for a positive conformal factor and K squared."""
    z = 2*np.pi*np.arange(n)/n
    seed = conformal_tensor(z,a,quadrature)
    seed2 = np.sum(seed**2,axis=(1,2))
    freq = np.fft.fftfreq(n,1/n)
    lap = np.fft.ifft(-freq[:,None]**2*np.fft.fft(np.eye(n),axis=0),axis=0).real
    psi = np.ones(n)
    k2 = 1.5*np.mean(seed2)
    def residual(p,s):
        return np.r_[lap@p + seed2*p**(-7)/8 - s*p**5/12, np.mean(p**6)-1]
    for _ in range(12):
        error = residual(psi,k2)
        if max(abs(error)) < 3e-13:
            break
        jac = np.empty((n+1,n+1))
        jac[:-1,:-1] = lap + np.diag(-7*seed2*psi**(-8)/8 - 5*k2*psi**4/12)
        jac[:-1,-1] = -psi**5/12
        jac[-1,:-1] = 6*psi**5/n
        jac[-1,-1] = 0
        delta = np.linalg.solve(jac,-error)
        psi += delta[:-1]
        k2 += delta[-1]
        assert min(psi)>0 and k2>=0
    else:
        raise ArithmeticError("nonlinear spectral solve did not converge")
    expected = 1.5*np.mean(seed2*psi**(-7))/np.mean(psi**5)
    assert abs(k2-expected) < 1e-11
    return psi,k2


def interpolate(psi,z):
    """Independently sample the periodic interpolant at staggered verification points."""
    n=len(psi)
    modes=np.fft.fftfreq(n,1/n)
    return (np.exp(1j*np.outer(z,modes))@(np.fft.fft(psi)/n)).real


def physical_constraints(psi_seed, k2, a, n, quadrature=False, defect=0, sign=-1):
    """Reconstruct physical tensors, finite-difference Christoffels and contract Ricci."""
    z=2*np.pi*(np.arange(n)+0.375)/n
    dz=2*np.pi/n
    psi=interpolate(psi_seed,z)
    metric=psi[:,None,None]**4*np.eye(3)[None,:,:]
    inverse=np.linalg.inv(metric)
    mean=sign*np.sqrt(k2)
    extrinsic=psi[:,None,None]**(-10)*conformal_tensor(z,a,quadrature) + mean*inverse/3
    # Deliberately non-conserved shear for the detector-sensitivity check.
    extrinsic[:,0,2]+=defect*np.sin(z)
    extrinsic[:,2,0]+=defect*np.sin(z)
    def diff(x,i):
        if i!=2:
            return np.zeros_like(x)
        return (np.roll(x,2,axis=0)-8*np.roll(x,1,axis=0)+8*np.roll(x,-1,axis=0)
                -np.roll(x,-2,axis=0))/(12*dz)
    metric_grad=[diff(metric,i) for i in AX]
    christ=np.zeros((n,3,3,3))
    for k in AX:
        for i in AX:
            for j in AX:
                christ[:,k,i,j]=sum(inverse[:,k,l]*(metric_grad[i][:,l,j]+metric_grad[j][:,l,i]
                                   -metric_grad[l][:,i,j])/2 for l in AX)
    ricci=np.zeros_like(metric)
    for i in AX:
        for j in AX:
            for k in AX:
                ricci[:,i,j]+=diff(christ[:,k,i,j],k)-diff(christ[:,k,i,k],j)
                for l in AX:
                    ricci[:,i,j]+=(christ[:,k,k,l]*christ[:,l,i,j]
                                  -christ[:,k,j,l]*christ[:,l,i,k])
    scalar=np.einsum("nij,nij->n",inverse,ricci)
    physical_trace=np.einsum("nij,nij->n",metric,extrinsic)
    fully_lowered=metric@extrinsic@metric
    norm=np.einsum("nij,nij->n",extrinsic,fully_lowered)
    ham=scalar+physical_trace**2-norm
    mom=np.zeros((n,3))
    for i in AX:
        for j in AX:
            mom[:,i]+=diff(extrinsic[:,i,j],j)-inverse[:,i,j]*diff(physical_trace,j)
            for l in AX:
                mom[:,i]+=(christ[:,i,j,l]*extrinsic[:,l,j]
                          +christ[:,j,j,l]*extrinsic[:,i,l])
    return np.max(np.abs(ham)),np.max(np.abs(mom)),np.max(abs(physical_trace-mean))


def observables(p,k2):
    z=2*np.pi*np.arange(len(p))/len(p)
    coeff=2*np.mean((p-1)*np.cos(2*K_WAVE*z))
    return np.sqrt(k2)/3,coeff


def main():
    for a in (.05,.2,.6):
        p,s=solve(a)
        ref,rs=solve(a,32)
        h,mode=observables(p,s)
        assert abs(s-rs)<1e-11 and abs(mode-observables(ref,rs)[1])<1e-12
        assert abs(np.mean(p**6)-1)<2e-13
        leading=a*a/(32*K_WAVE**2)
        ratio=s/(1.5*a*a)
        small_prediction=1-7*a*a/(64*K_WAVE**2)
        if a<=.2:
            refined=small_prediction+33*(a/K_WAVE)**4/512
            assert abs(ratio-refined)<abs(ratio-small_prediction)/10
            harmonic2=leading-3*(a/K_WAVE)**4/256
            assert abs(mode-harmonic2)<abs(mode-leading)/10
        print(f"a={a:.2f} K^2={s:.12f} |H|={h:.9f} "
              f"psi_2k={mode:.10f} leading={leading:.10f} K^2/leading={ratio:.9f}")
    p,s=solve(.6)
    errors=[]
    for n in (64,128,256):
        ec,em,et=physical_constraints(p,s,.6,n)
        errors.append(ec)
        print(f"direct tensors n={n}: max Hamiltonian={ec:.4g} momentum={em:.4g} trace error={et:.3g}")
        assert em<1e-5 and et<2e-15
    assert min(errors[0]/errors[1],errors[1]/errors[2])>14 and errors[-1]<3e-7
    ec,em,_=physical_constraints(p,s,.6,256,sign=1)
    assert ec<3e-7 and em<1e-7
    _,bad,_=physical_constraints(p,s,.6,256,defect=.01)
    assert bad>.009
    a=.6
    p,s=solve(a,quadrature=True)
    ec,em,_=physical_constraints(p,s,a,128,quadrature=True)
    assert np.max(abs(p-1))<1e-12 and abs(s-1.5*a*a)<1e-12
    assert max(ec,em)<1e-10
    print(f"same mean TT seed norm, quadrature: psi error={max(abs(p-1)):.3g} "
          f"K^2={s:.9f}; imposed spurious longitudinal shear momentum defect={bad:.6g}")


if __name__=="__main__":
    main()
constraint_closure.py
"""Off-shell normal-deformation brackets on a nonlinear three-dimensional spatial metric."""
import numpy as np


class Slice:
    def __init__(self,n,phase):
        self.n=n
        self.k=np.fft.fftfreq(n,1/n)
        # Real periodic fields. Remove the single even-grid Nyquist derivative.
        if n%2==0:self.k[n//2]=0.
        x,y,z=np.meshgrid(*(3*[2*np.pi*np.arange(n)/n]),indexing="ij")
        sin,cos=np.sin,np.cos
        p=phase
        g=np.zeros(x.shape+(3,3))
        g[...,0,0]=1+.13*cos(y+z+p)+.08*sin(x)
        g[...,1,1]=1+.14*sin(x+y-p)
        g[...,2,2]=1+.11*cos(y)+.07*sin(2*z+p)
        g[...,0,1]=g[...,1,0]=.075*cos(x-y)
        g[...,1,2]=g[...,2,1]=.055*sin(x+z+p)
        g[...,2,0]=g[...,0,2]=.04*cos(z-y)
        self.g=g
        mom=np.zeros_like(g)
        mom[...,0,0]=.5*cos(x+p)+.24*sin(y)
        mom[...,1,1]=.4*cos(x)-.3*sin(x+y+z)
        mom[...,2,2]=.26*sin(z+p)+.2*cos(x-y)
        mom[...,0,1]=mom[...,1,0]=.15*sin(x-y+p)
        mom[...,1,2]=mom[...,2,1]=.12*cos(x+z)
        mom[...,2,0]=mom[...,0,2]=.10*sin(y-z)
        self.P=mom
        self.field=.5*sin(x+y)+.31*cos(x-z+p)+.16*sin(z)
        self.p=.55+.19*cos(y)+.12*sin(x-z)
        self.lapse=1+.30*cos(x+y)+.18*sin(z+p)+.11*cos(x)
        self.second=.30*sin(x+y+p)+.27*cos(y+z)+.18*sin(x)
        self.inv=np.linalg.inv(g)
        self.root=np.sqrt(np.linalg.det(g))
        self.dg=self.gradient(g)
        self.df=self.gradient(self.field)
        self.trace=np.einsum('...ij,...ij->...',g,mom)

    def gradient(self,x):
        outs=[]
        for axis in range(3):
            shape=[1]*x.ndim
            shape[axis]=self.n
            k=self.k.reshape(shape)
            outs.append(np.fft.ifft(1j*k*np.fft.fft(x,axis=axis),axis=axis).real)
        return np.stack(outs,axis=3)

    def curvature(self,g,inv):
        # d[...,i,j,k] = partial_i g_jk; Γ[...,i,j,k] = Γ^i_jk.
        d=self.gradient(g)
        lower=d.swapaxes(-3,-2)+d.swapaxes(-3,-1)-d
        connection=.5*np.einsum('...ia,...ajk->...ijk',inv,lower)
        dc=self.gradient(connection)
        ricci=np.einsum('...kkij->...ij',dc)-np.einsum('...jkik->...ij',dc)
        ricci+=np.einsum('...kkl,...lij->...ij',connection,connection)
        ricci-=np.einsum('...kjl,...lik->...ij',connection,connection)
        return np.einsum('...ij,...ij->...',inv,ricci)

    def matter(self,s,y,model):
        if model=="canonical":return s+y,np.ones_like(s),np.ones_like(s)
        if model=="slow":return s+.62*y,np.ones_like(s),np.full_like(s,.62)
        # A nonlinear covariant scalar with tension 1; background gradients change its wave speeds.
        ratio=np.sqrt((1+2*y)/(1+2*s))
        return np.sqrt((1+2*s)*(1+2*y))-1,ratio,1/ratio

    def energy(self,g,field,lapse,A,B,weight,model,cosm=.037):
        inv=np.linalg.inv(g)
        root=np.sqrt(np.linalg.det(g))
        low=g@self.P@g
        tr=np.einsum('...ij,...ij->...',g,self.P)
        pp=np.einsum('...ij,...ij->...',low,self.P)
        gravity=A*(pp-weight*tr*tr)/root-B*root*self.curvature(g,inv)+cosm*root
        df=self.gradient(field)
        y=.5*np.einsum('...i,...ij,...j->...',df,inv,df)
        F=self.matter(.5*(self.p/root)**2,y,model)[0]
        potential=.17*field**2+.053*field**4
        return np.mean(lapse*(gravity+root*(F+potential)))

    def bracket(self,A,B,weight,model,eps=1e-5):
        g,P,N,M=self.g,self.P,self.lapse,self.second
        root=self.root
        low=g@P@g
        v=2*A*(low-weight*self.trace[...,None,None]*g)/root[...,None,None]
        y=.5*np.einsum('...i,...ij,...j->...',self.df,self.inv,self.df)
        _,Fs,Fy=self.matter(.5*(self.p/root)**2,y,model)
        u=Fs*self.p/root
        # {H[N],H[M]} from directional changes of the actual Hamiltonian functional.
        # Neither curvature variation nor the expected momentum constraint is used here.
        def direction(test,step):
            dg=eps*step[...,None,None]*v
            df=eps*step*u
            return (self.energy(g+dg,self.field+df,test,A,B,weight,model)-
                    self.energy(g-dg,self.field-df,test,A,B,weight,model))/(2*eps)
        raw=direction(N,M)-direction(M,N)
        lower=N[...,None]*self.gradient(M)-M[...,None]*self.gradient(N)
        beta=np.einsum('...ij,...j->...i',self.inv,lower)
        dbeta=self.gradient(beta)
        lie=np.einsum('...k,...kij->...ij',beta,self.dg)
        stretch=np.einsum('...kj,...ik->...ij',g,dbeta)
        lie+=stretch+stretch.swapaxes(-2,-1)
        gravity=np.mean(np.einsum('...ij,...ij->...',P,lie))
        current=self.p*np.einsum('...i,...i->...',beta,self.df)
        matter=current.mean()
        trace_gradient=self.gradient(self.trace/root)
        anomaly=2*np.mean(root*np.einsum('...i,...i->...',beta,trace_gradient))
        prediction=A*B*(gravity+(1-2*weight)*anomaly)+np.mean(Fs*Fy*current)
        return raw,gravity,matter,anomaly,prediction


def main():
    for n in (10,16,24):
        state=Slice(n,.41)
        if n==24:
            coords=2*np.pi*np.arange(n)/n
            x,y,z=np.meshgrid(coords,coords,coords,indexing="ij")
            wave=.03*np.cos(x+y)+.02*np.sin(z)
            conformal=1+wave
            g=conformal[...,None,None]**4*np.eye(3)
            laplace=-.06*np.cos(x+y)-.02*np.sin(z)
            expected=-8*laplace/conformal**5
            assert np.max(abs(state.curvature(g,np.linalg.inv(g))-expected))<3e-9
        for label,A,B,w,model in [('Einstein + scalar',1.6,.625,.5,'canonical'),
                                 ('Einstein + nonlinear scalar',.8,1.25,.5,'DBI'),
                                 ('deformed trace',1.6,.625,.43,'canonical'),
                                 ('unequal speeds',1.6,.625,.5,'slow')]:
            raw,dg,dm,trace,pred=state.bracket(A,B,w,model)
            err=raw-pred
            print(f'n={n} {label}: bracket={raw:+.9f}, common shift={dg+dm:+.9f}, '
                  f'defect={raw-dg-dm:+.9f}, analytic residual={err:+.3g}')
            if n==24:
                assert abs(err)<1e-7
                if model=='slow' or w!=.5:assert abs(raw-dg-dm)>.0001
    # Fit the single common coefficient and the trace anomaly on two preparations,
    # then compare a third phase using the unsimplified numerical functional.
    rows=[]
    for phase in (.13,.89,1.7):
        raw,dg,dm,trace,_=Slice(20,phase).bracket(1.3,.73,.46,'DBI')
        rows.append((raw-dm,dg,trace))
    fit=np.linalg.solve([r[1:] for r in rows[:2]],[r[0] for r in rows[:2]])
    expect=1.3*.73
    np.testing.assert_allclose(fit,[expect,expect*(1-2*.46)],atol=2e-6)
    held=rows[2]
    assert abs(held[0]-np.dot(held[1:],fit))<2e-7
    print('Fit AB and AB(1-2lambda):',fit,'held-out residual:',held[0]-np.dot(held[1:],fit))


if __name__=="__main__":
    main()
matter_response.py
"""What normal-deformation closure predicts from a homogeneous scalar calibration."""
from math import exp, sqrt


def bump(x):
    return exp(x+1/x) if x<0 else 0.


def integrate(func,a,b,n=800):
    if a==b:return 0.
    h=(b-a)/n
    return h*(func(a)+func(b)+4*sum(func(a+j*h) for j in range(1,n,2))+
              2*sum(func(a+j*h) for j in range(2,n,2)))/3


def pressure(x,coefficient):
    if x>=0:return x,1.,0.
    return (x+coefficient*integrate(lambda u:(u-x)*bump(u),x,0.),
            1-coefficient*integrate(bump,x,0.),coefficient*bump(x))


def hamiltonian(s,y,coefficient):
    momentum=sqrt(2*s)
    # P_X is positive and monotone in X. At fixed gradient this map is one-to-one.
    low,high=0.,2*momentum+1.
    for _ in range(58):
        v=(low+high)/2
        x=v*v/2-y
        _,px,_=pressure(x,coefficient)
        if v*px>momentum:high=v
        else:low=v
    value,px,_=pressure(v*v/2-y,coefficient)
    return momentum*v-value


def reconstruct(s,y):
    # g(s)=sqrt(1+2s)-1 is measured on the homogeneous edge y=0.
    # No spatial-gradient value of the target function enters the root search.
    lo,hi=0.,s
    if y>s:raise ValueError('This characteristic misses the measured edge.')
    for _ in range(58):
        t=(hi+lo)/2
        slope=1/sqrt(1+2*t)
        if t+y/slope**2>s:hi=t
        else:lo=t
    g=sqrt(1+2*t)-1
    return g+2*y/slope


def main():
    for s,y in ((.8,.15),(1.2,.51),(2.,.4)):
        f=reconstruct(s,y)
        exact=sqrt((1+2*s)*(1+2*y))-1
        assert abs(f-exact)<2e-14
        print(f'homogeneous data continued to (s,y)=({s},{y}): H={f:.9f}')
    for s in (.05,.5,1.8):
        assert abs(hamiltonian(s,0.,.5)-s)<2e-12
    for s,y in ((.25,.1),(.1,1.),(.6,1.3)):
        for alpha in (0.,.5):
            eps=1e-5
            fs=(hamiltonian(s+eps,y,alpha)-hamiltonian(s-eps,y,alpha))/(2*eps)
            fy=(hamiltonian(s,y+eps,alpha)-hamiltonian(s,y-eps,alpha))/(2*eps)
            assert abs(fs*fy-1)<2e-8
    for alpha in (0.,.5):
        val,px,pxx=pressure(-1.,alpha)
        parallel=sqrt(1-2*pxx/px)
        print(f'alpha={alpha:g} on a static gradient |grad phi|=sqrt(2): '
              f'energy density={-val:.9f} parallel speed={parallel:.9f} transverse=1')
        # Independent check from the Hessian of P(dotphi^2/2-gradphi^2/2).
        step=1e-4
        grad=sqrt(2.)
        def action(v,d):return pressure((v*v-d*d)/2,alpha)[0]
        temporal=(action(step,grad)-2*action(0,grad)+action(-step,grad))/step**2
        spatial=(action(0,grad+step)-2*action(0,grad)+action(0,grad-step))/step**2
        assert abs(sqrt(-spatial/temporal)-parallel)<2e-6


if __name__=="__main__":
    main()
moving_samples.py
"""Fixed-site shift obstruction and transport on finite moving spacetime samples."""
from math import pi
import numpy as np


def edge_shift(beta,spacing=1.):
    """Shift that follows from the site kinetic term and an edge-averaged lapse."""
    n=len(beta)
    matrix=np.zeros((n,n))
    for j in range(n):
        k=(j+1)%n
        for row in (j,k):
            matrix[row,j]-=beta[j]/(2*spacing)
            matrix[row,k]+=beta[j]/(2*spacing)
    return matrix


def basis(nodes,derivative=0):
    m=np.arange(1,(len(nodes)+1)//2)
    angle=nodes[:,None]*m+derivative*pi/2
    constant=np.full((len(nodes),1),float(derivative==0))
    return np.column_stack((constant,np.cos(angle)*m**derivative,np.sin(angle)*m**derivative))


def spectral(nodes):
    return np.linalg.solve(basis(nodes).T,basis(nodes,1).T).T


def local(nodes):
    """Three-node quadratic derivative for nonuniform periodic coordinates."""
    n=len(nodes)
    dm=nodes-np.roll(nodes,1)
    dm[0]+=2*pi
    dp=np.roll(dm,-1)
    D=np.zeros((n,n))
    ii=np.arange(n)
    D[ii,(ii-1)%n]=-dp/(dm*(dm+dp))
    D[ii,ii]=(dp-dm)/(dm*dp)
    D[ii,(ii+1)%n]=dm/(dp*(dm+dp))
    return D


def curvature(nodes,v,w,derivative,eps=1e-6):
    d=derivative(nodes)
    Av=v[:,None]*d
    Aw=w[:,None]*d
    if derivative is spectral:
        dd=np.linalg.solve(basis(nodes).T,basis(nodes,2).T).T
        delta_v=v[:,None]*dd-d@Av
        delta_w=w[:,None]*dd-d@Aw
        if len(nodes)<=31:
            finite=(spectral(nodes+eps*v)-spectral(nodes-eps*v))/(2*eps)
            assert np.max(abs(finite-delta_v))<3e-7
    else:
        delta_v=(derivative(nodes+eps*v)-derivative(nodes-eps*v))/(2*eps)
        delta_w=(derivative(nodes+eps*w)-derivative(nodes-eps*w))/(2*eps)
    return w[:,None]*delta_v-v[:,None]*delta_w+Aw@Av-Av@Aw


def normal(T,X,sigma,D):
    # The unwrapped spatial embedding has winding one.
    dT=D@T
    dX=1+D@(X-sigma)
    e=np.sqrt(dX*dX-dT*dT)
    return np.column_stack((dX/e,dT/e)),np.column_stack((dT/e,dX/e)),e


def minkowski(a,b):
    return -a[:,0]*b[:,0]+a[:,1]*b[:,1]


def local_lapse_test(n):
    sigma=2*pi*np.arange(n)/n
    T=.16*np.sin(sigma)+.04*np.sin(2*sigma)
    X=sigma+.09*np.cos(2*sigma)
    D=local(sigma)
    N=1+.22*np.cos(2*sigma)
    M=.33*np.sin(sigma)-.14*np.cos(3*sigma)
    norm,tan,e=normal(T,X,sigma,D)
    def step(A,B,eps):
        TN=T+eps*A*norm[:,0]
        XN=X+eps*A*norm[:,1]
        return B[:,None]*normal(TN,XN,sigma,D)[0]
    eps=2e-6
    measured=(step(N,M,eps)-step(N,M,-eps)-step(M,N,eps)+step(M,N,-eps))/(2*eps)
    beta=(N*minkowski(norm,D@(M[:,None]*norm))-M*minkowski(norm,D@(N[:,None]*norm)))/e**2
    continuum=(M*(D@N)-N*(D@M))/e**2
    assert np.max(abs(measured-beta[:,None]*e[:,None]*tan))<3e-9
    return np.max(abs(beta-continuum))


def main():
    v,w=np.eye(9)[:2]
    first,second=edge_shift(v),edge_shift(w)
    bracket=first@second-second@first
    assert bracket[0,2]==.25
    assert max(abs(edge_shift(b)[0,2]) for b in np.eye(9))==0
    print('Fixed sites: commutator coefficient from site 2 to site 0:',bracket[0,2])
    errors=[]
    for n in (15,31,63):
        x=2*pi*np.arange(n)/n
        nodes=x+.08*np.sin(x)
        v=.6*np.cos(2*x)+.1
        w=.4*np.sin(x)-.15*np.cos(3*x)
        wave=np.sin(2*nodes)-.3*np.cos(nodes)
        curv_local=curvature(nodes,v,w,local)
        curv_full=curvature(nodes,v,w,spectral)
        err=np.max(abs(curv_local@wave))
        spectral_err=np.max(abs(curv_full@wave))
        assert spectral_err<5e-8
        lapse_err=local_lapse_test(n)
        errors.append((err,lapse_err))
        print(f'n={n}: local sampling path defect {err:.7g}; full sampling {spectral_err:.3g}; '
              f'discrete vs ordinary normal shift {lapse_err:.7g}')
    assert errors[1][0]<errors[0][0]/2.5 and errors[2][0]<errors[1][0]/3
    assert errors[2][1]<errors[1][1]/3
    # Finite deformations of two chiral massless waves on a prescribed flat spacetime.
    n=21
    x=2*pi*np.arange(n)/n
    t=.11*np.sin(x)
    X=x+.06*np.cos(2*x)
    rng=np.random.default_rng(216)
    for sign in (-1,1):
        U=X+sign*t
        U1=U+.03*np.cos(3*x)
        U2=U+.05*np.sin(x)
        dest=U1+U2-U
        coeff=rng.standard_normal(n)
        data=basis(U)@coeff
        def transfer(a,b,f):
            return basis(b)@np.linalg.solve(basis(a),f)
        one=transfer(U1,dest,transfer(U,U1,data))
        two=transfer(U2,dest,transfer(U,U2,data))
        assert np.max(abs(one-two))<2e-12
        assert np.max(abs(one-basis(dest)@coeff))<2e-12
    print('Both chiral records agree around finite moving-node paths.')


if __name__=="__main__":
    main()
convex_cover.py
"""Exact covers of phase-unresolved readout windows in the six-stage Pauli walk."""
from collections import defaultdict
from fractions import Fraction as F
from itertools import combinations, product
from math import ceil, log, log1p

CYCLE=(0,1,2,2,1,0)
AXES=range(3)
NORMALS=[p for p in product((-1,0,1),repeat=3) if any(p)]


def projected_twice(axis,s,spin):
    """Apply I+s sigma_axis to a Gaussian-integer spinor, in real/imag pairs."""
    r,i,u,v=spin
    if axis==0:
        return (r+s*u,i+s*v,u+s*r,v+s*i)
    if axis==1:
        return (r+s*v,i-s*u,u-s*i,v+s*r)
    return ((1+s)*r,(1+s)*i,(1-s)*u,(1-s)*v)


def run(steps):
    probability=defaultdict(int)
    for start in range(6):
        for spin in ((1,0,0,0),(0,0,1,0)):
            states={(0,0,0):spin}
            for t in range(steps):
                axis=CYCLE[(start+t)%6]
                out=defaultdict(lambda:[0,0,0,0])
                for point,values in states.items():
                    for s in (-1,1):
                        shifted=list(point)
                        shifted[axis]+=s
                        amp=projected_twice(axis,s,values)
                        for j in range(4):
                            out[tuple(shifted)][j]+=amp[j]
                states={p:v for p,v in out.items() if any(v)}
            for p,v in states.items():
                probability[p]+=sum(c*c for c in v)
    total=12*4**steps
    assert sum(probability.values())==total
    return {p:F(weight,total) for p,weight in probability.items()}


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


def det(rows):
    a,b,c=rows
    return (a[0]*(b[1]*c[2]-b[2]*c[1])-a[1]*(b[0]*c[2]-b[2]*c[0])
            +a[2]*(b[0]*c[1]-b[1]*c[0]))


def intersection(rows):
    A,rhs=zip(*rows)
    d=det(A)
    if not d:
        return None
    cols=list(zip(*A))
    result=[]
    for i in AXES:
        changed=cols.copy()
        changed[i]=rhs
        result.append(F(det(changed),d))  # determinant unchanged by transposition
    return tuple(result)


def chamber(a):
    rows=[((-1,1,0),0),((0,-1,1),0),((0,0,-1),0),
          ((1,0,0),a+1),((1,1,0),2*a+1),((1,1,1),3*a+1)]
    verts=set()
    for chosen in combinations(rows,3):
        v=intersection(chosen)
        if v is not None and all(dot(row,v)<=b for row,b in rows):
            verts.add(v)
    return verts


def gauge(v,a):
    # Each nonzero signed subset inequality: n.v <= a |n|_1 + 1.
    return max(F(dot(n,v),a*sum(abs(i) for i in n)+1) for n in NORMALS)


def shifted(x,c):
    return tuple(i-j for i,j in zip(x,c))


def check_cover(a):
    verts=chamber(a)
    six=1-F(1,3*(2*a+1))
    t=F(3*a+1,3*(2*a+1))
    axis=(t,0,0)
    # Every signed permutation of this chamber uses its own corresponding center.
    assert max(gauge(shifted(x,axis),a) for x in verts)==six
    centroid=(a+F(1,3),)*3
    assert gauge(centroid,a)==1 and 2*centroid[0]/(2*a+1)==six
    eighth=F(a+1,2*a+1)
    cube=(a*eighth,)*3
    assert max(gauge(shifted(x,cube),a) for x in verts)<=eighth
    seven_min=F(3*a+1,3*(a+1))
    if a:
        assert F(3*(a+1),6*a+4)<=eighth<=F(2,3)<seven_min
        assert max(gauge(shifted(x,cube),a) for x in verts)==eighth
    return six,eighth,seven_min


def verify(n):
    a=2*n
    sites=run(6*n+1)
    corners=set()
    for axis in AXES:
        lengths=[a]*3
        lengths[axis]+=1
        for sign in product((-1,1),repeat=3):
            corners.add(tuple(k*s for k,s in zip(lengths,sign)))
    assert all(gauge(p,a)<=1 for p in sites) and corners<=set(sites)
    probability=F(1,6*16**n)
    assert all(sites[p]==probability for p in corners)
    six,eight,seven_min=check_cover(a)
    print(f"{6*n+1} stages: {len(sites)} occupied sites, {len(corners)} vertices,"
          f" probability each {probability}, six-axis scale {six}")
    if a:
        print(f"  eight-copy scale between {F(3*(a+1),6*a+4)} and {eight}, seven-copy scale at least {seven_min}")
        count=ceil(log(len(corners)/.05)/-log1p(-float(probability)))
        # Exact rational check that 24(1-p)^M <= .05 first passes here.
        assert len(corners)*(1-probability)**count<=F(1,20)<len(corners)*(1-probability)**(count-1)
        print(f"  minimum shots meeting 95% union-bound guarantee: {count}")


if __name__=="__main__":
    for n in (0,1,2):
        verify(n)
form_factor.py
"""Energy-density form factor of the ordered 3D pair in a symmetric moving frame.

NumPy is optional outside this replay. The smooth Brillouin torus is integrated
by periodic cubature; its mesh is not a finite apparatus limiting q.
"""
from pathlib import Path
import sys
import numpy as np

if not (Path(__file__).parent/'bound_3d.py').exists():
    sys.path.insert(0,str(Path(__file__).resolve().parent.parent/'shell-clocks'))
from bound_3d import Torus, rest_calibration, BASIS, BETA_PAIR, GAMMA, IDENTITY

Z0 = 1.90
G = np.array(GAMMA[1:])


def block(k):
    x,y,z = k
    t = [2*np.sin(p/2)**2 for p in (x,y,z)]
    m = 1+2*sum(s*s for s in t)/3+2*(t[0]*t[1]+t[1]*t[2]+t[2]*t[0])
    coeff = np.stack(np.broadcast_arrays(np.sin(x)*np.cos(y)*np.cos(z),
                        np.sin(y)*np.cos(z),np.sin(z),m),axis=-1).reshape(-1,4)
    e = np.sqrt(np.sum(coeff*coeff,axis=1))
    return (coeff@G.reshape(4,16)).reshape(-1,4,4), e


def wave(source,z,ha,a,hb,b):
    # Closed-form resolvent in the four signed-energy sectors, acting on 4x4 spins.
    wpp = .25/(z-a-b)
    wpm = .25/(z-a+b)
    wmp = .25/(z+a-b)
    wmm = .25/(z+a+b)
    ma = ha@source
    bt = hb.swapaxes(1,2)
    mb = source@bt
    def times(s,u):
        return s[:,None,None]*u
    return (times(wpp+wpm+wmp+wmm,source)
            +times((wpp+wpm-wmp-wmm)/a,ma)
            +times((wpp-wpm+wmp-wmm)/b,mb)
            +times((wpp-wpm-wmp+wmm)/(a*b),ma@bt))


def bound(torus, cal, axis, k, contact):
    _,lam,u0,_ = cal
    energy = Z0
    for _ in range(8):
        g = torus.green(energy,axis,k)
        vals,u = np.linalg.eigh(g-lam*contact)
        j = np.argmax(abs(u.conj().T@u0))
        v = u[:,j]
        ge = torus.green(energy,axis,k,derivative=True)
        nz = -(v.conj()@ge@v).real
        step = vals[j]/nz
        if abs(step)<2e-13:
            break
        energy += step
    assert abs(step) < 2e-11
    v = v*np.exp(-1j*np.angle(u0.conj()@v))
    return energy,v/np.sqrt(nz)


def run_axis(torus,cal,axis,q,contact):
    n = torus.size
    energy,src_f = bound(torus,cal,axis,q/2,contact)
    src_i = BETA_PAIR @ src_f         # inversion on the chosen rest-even simple pole
    u_f,u_i = [(BASIS@v).reshape(4,4) for v in (src_f,src_i)]
    _,lam,_,_ = cal
    interaction = lam*(src_f.conj()@contact@src_i)
    one = mid = num = spincheck = 0j
    no_i = no_f = 0.
    grid = np.ogrid[0:n,0:n,0:n]
    for lo in range(0,n,3):
        k = [p*2*np.pi/n for p in (grid[0][lo:lo+3],grid[1],grid[2])]
        half = [q/2 if j==axis else 0 for j in range(3)]
        ha0,a0 = block([p-s for p,s in zip(k,half)])
        ha1,a1 = block([p+s for p,s in zip(k,half)])
        hb,b = block([-p for p in k])
        wi = wave(u_i,energy,ha0,a0,hb,b)
        wf = wave(u_f,energy,ha1,a1,hb,b)
        # Exchange-odd identical propagators imply equal contributions from the
        # two labelled copies, so their sum uses (ha0+ha1) without 1/2 here.
        one += np.vdot(wf,(ha0+ha1)@wi)
        center_h,_ = block(k)
        mid += 2*np.vdot(wf,center_h@wi)
        num += np.vdot(wf,wi)
        spincheck += np.vdot(wf,wi@hb.swapaxes(1,2))
        no_i += np.vdot(wi,wi).real
        no_f += np.vdot(wf,wf).real
    one /= n**3
    mid /= n**3
    num /= n**3
    spincheck /= n**3
    assert max(abs(no_i/n**3-1),abs(no_f/n**3-1)) < (4e-4 if n<=32 else 2e-5)
    total = one+interaction
    # Binding equation for each leg, using the spectator energy insertion twice.
    residual = abs(total-(2*energy*num-2*spincheck-interaction))
    assert residual < (1e-4 if n<=32 else 2e-5)
    assert abs(total.imag) < 1e-10
    return np.array([total.real,one.real,interaction.real,(mid+interaction).real,num.real])


def local_vertex_check():
    # Recover the nonzero real-space hopping matrices by an exact-length DFT
    # (all symbol frequencies fit from -2 to +2). Rebuild both density vertices
    # by assigning every individual bond to its ends or to its midpoint.
    n=5
    axes=np.ogrid[0:n,0:n,0:n]
    h,_=block([p*(2*np.pi/n) for p in axes])
    hops=np.fft.ifftn(h.reshape(n,n,n,4,4),axes=(0,1,2))
    k=np.array([.31,-.23,.19])
    q=np.array([.11,.07,-.12])
    end=np.zeros((4,4),complex)
    middle=end.copy()
    for pos in np.ndindex(n,n,n):
        delta=np.array([j if j<=2 else j-n for j in pos])
        bare=hops[pos]*np.exp(-1j*(k@delta))
        end+=bare*(1+np.exp(-1j*(q@delta)))/2
        middle+=bare*np.exp(-.5j*(q@delta))
    a,ea=block(k)
    b,eb=block(k+q)
    c,_=block(k+q/2)
    assert np.max(abs(end-(a[0]+b[0])/2)) < 1e-13
    assert np.max(abs(middle-c[0])) < 1e-13
    spin=np.arange(16).reshape(4,4)+1j
    z=1.83
    explicit=np.linalg.solve(z*np.eye(16)-np.kron(a[0],np.eye(4))-
                             np.kron(np.eye(4),b[0]),spin.ravel())
    assert np.max(abs(wave(spin,z,a,ea,b,eb).ravel()-explicit)) < 2e-12


def main():
    n = int(sys.argv[1]) if len(sys.argv)>1 else 48
    axes = sys.argv[2] if len(sys.argv)>2 else 'z'
    qs = [float(q) for q in sys.argv[3:]] or [.2,.05,.025]
    torus = Torus(n)
    cal=rest_calibration(torus)
    # First four columns use F(0)=Z0; the normalized number form factor uses 1.
    normalizers = np.array([Z0,Z0,Z0,Z0,1.])
    print('columns: endpoint F, free contribution, contact contribution, midpoint F, number')
    for axis in ('xyz'.index(name) for name in axes):
        slopes = []
        for label,contact in (('density',IDENTITY),('mass',BETA_PAIR)):
            base=run_axis(torus,cal,axis,0.,contact)
            assert abs(base[0]-Z0) < 1e-11 and abs(base[3]-Z0) < 1e-11
            print(f'axis {"xyz"[axis]}, {label}, q=0: '+str(np.round(base,10)),flush=True)
            radii=[]
            for q in qs:
                value=run_axis(torus,cal,axis,q,contact)
                radius=-2*(value-base)/(normalizers*q*q)
                radii.append(radius)
                print(f'  q={q:.5f}: {np.round(value,9)}',flush=True)
            if len(qs)>=2 and abs(qs[-2]-2*qs[-1])<1e-12:
                slope=(4*radii[-1]-radii[-2])/3
                slopes.append(slope)
                print('  directional second moments:',np.round(slope,8),flush=True)
        if len(slopes) == 2:
            delta=slopes[1]-slopes[0]
            print('  mass minus density:',np.round(delta,8),flush=True)
            assert abs(delta[0]-delta[3]) < 2e-6


if __name__=='__main__':
    local_vertex_check()
    main()
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)
replay.py
"""Replay the tensor-clocks calculations and compare the native Tally transcript."""
import argparse
from hashlib import sha256
from io import BytesIO
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from zipfile import ZipFile

ROOT = Path(__file__).resolve().parent
RELEASES = {
    "6f3e168661968c1ff3e32d0390de7ba79fd72ef452b6fd44efce7012df2263ee": 184,
    "72fecb20c9f83442bcf85a0cf68b6aa1104d2edef829fd27e0ea149eae2cbe41": 192,
}
ATOM_SHA = "4c08a122480cb2d6c1efb48b9e868b5b45432d78dc40b339dbe9db7ebdacf02d"
NATIVE_CHECKS = 21
STANDARD = (("matter_response", ()), ("network_polarization", ()), ("convex_cover", ()))
NUMERICAL = (
    ("tensor_lattice", ()),
    ("lapse_loop", ("--fine", "--origin", "--unitary")),
    ("loop_spectrum", ("--fine",)),
    ("energy_improvement", ("--fine", "--finite")),
    ("constraint_closure", ()),
    ("moving_samples", ()),
    ("wave_weight", ()),
    ("quadrupole_exchange", ()),
)


def check_native(runtime):
    archive = runtime.read_bytes()
    release = RELEASES.get(sha256(archive).hexdigest())
    if release is None:
        raise ValueError(f"{runtime.name} does not match the SHA-256 of Tally release 184 or 192")
    atom = ROOT/"lib/atom.tly"
    if not atom.is_file():
        atom = ROOT.parent/"walk-clock-recoil/tally/lib/atom.tly"
    library = atom.read_bytes()
    if sha256(library).hexdigest() != ATOM_SHA:
        raise ValueError(f"Unexpected SHA-256 for {atom}")
    expected = (ROOT/"tensor.out").read_text(encoding="utf-8").splitlines()
    if sum(row.startswith("✓") for row in expected) != NATIVE_CHECKS:
        raise ValueError("The reference transcript has an unexpected number of checks")
    with tempfile.TemporaryDirectory() as temp:
        work = Path(temp)
        with ZipFile(BytesIO(archive)) as bundle:
            bundle.extractall(work)
        tally = work/"Tally-0.3.0"
        (tally/"lib/atom.tly").write_bytes(library)
        shutil.copyfile(ROOT/"tensor.tly", work/"tensor.tly")
        result = subprocess.run(
            [sys.executable, "-B", str(tally/"tally.py"), "tensor.tly"], cwd=work,
            env=dict(os.environ, PYTHONIOENCODING="utf-8"), stdout=subprocess.PIPE,
            encoding="utf-8", check=True,
        )
        if result.stdout.splitlines() != expected:
            raise ValueError(f"Tally release {release} output differs from tensor.out")
    print(f"Tally release {release} matched all {NATIVE_CHECKS} native checks.", flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("runtime", type=Path, help="published Tally release 184 or 192 ZIP")
    parser.add_argument("--full", action="store_true", help="include all eight NumPy calculations and the publication mesh settings")
    args = parser.parse_args()
    check_native(args.runtime)
    programs = STANDARD + (NUMERICAL if args.full else ())
    env = dict(os.environ, OPENBLAS_NUM_THREADS="1", OMP_NUM_THREADS="1", MKL_NUM_THREADS="1")
    for name, options in programs:
        print(f"Running {name}.py {' '.join(options)}".rstrip(), flush=True)
        subprocess.run([sys.executable, "-B", str(ROOT/(name+".py")), *options],
                       cwd=ROOT, env=env, check=True)
    print(f"Passed {len(programs)} calculation programs and all {NATIVE_CHECKS} native Tally checks.")


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

Independent research by Anthony Michael Collado.
Clock pulses, tensor waves and detector strain · 1 December 2026

Forces between bound pairs → · Study sources (ZIP) ↓