Skip to content

Can one collision rule give two pairs the same inertia?

A local hopping rule calibrated on one bound pair restores the leading inertia of another. Clock pulses, stronger binding and a rubidium free-fall measurement test what survives that repair.

What changed in the theory?

The proposal is that a microscopic local evolution could produce matter, clocks and the spacetime they measure. In the previous experiment, two interactions gave bound pairs of the same rest energy but different inertias. Here, translating neighboring constituents together during a collision repairs the leading motion for both pairs, using information from one contact.

The clock itself is a stricter test. Local pulses can leave a resting pair internally excited even when its motion has the correct curvature. A clock that samples the two constituents over three cells reduces the excitation by roughly two orders of magnitude in squared response. Other pulse shapes still test parts of the spacetime symmetry that this experiment leaves open.

The observed comparison uses real rubidium interferometer shots in Earth’s field. Relating them to a lattice pair requires an isotope and field calibration. The self-gravitating gas and dust cloud show how responsive matter and a gravitational field behave once a field law is supplied. The microscopic origin of that field law and its universally conserved source remains open. State of the theory

Which collision hops let two different clocks move together?

Sections in this chapter

Two interactions in the ordered three-dimensional walk give exactly the same bound pair at rest. When it moves, the density contact and the mass contact give different energy currents. We calibrated a hopping rule on the density pair and kept its coefficients fixed for the mass pair. Along z at momentum 0.05, the two forward clock responses change from 1.44301 and 1.36786 to 1.00506 and 1.00504. The common-metric target is one in units fixed by the constituent clock. This is a calculation on the specified lattice Hamiltonian. Original pair construction · Earlier finite-range and moving-source tests

What an ordinary pair hop can change

When both walkers occupy site x, let a bond translate them together to x+eⱼ, with its Hermitian conjugate taking them back. It acts only at coincidence. In the center-of-mass momentum fiber an even bond and its onsite counterterm add 2(1−cos Kⱼ)Mⱼ, with Mⱼ Hermitian. The entire two-body Hamiltonian at K=0 is preserved. Write z=1.900 for the rest energy, u for the unit spinor at coincidence, and w=0.13953493 for the probability of coincidence. The equal-rest pairs share z, u and w. For an isolated pole the change of Rⱼ=z∂²E/∂Kⱼ² at rest is exactly 2zw u†Mⱼu for either contact. The same result applies to any even finite-range displacement, with its second derivative in place of 2Mⱼ.

The bare z responses are 1.43825053 for density and 1.36466063 for mass. Making the first one equal to one leaves the second at 0.92641010. Even the best common additive correction to these two numbers must miss one target by at least 0.03679495. This argument allows arbitrary fixed off-diagonal entries in Mⱼ. A term with a first derivative in K can change which internal states the moving pair visits and requires a separate calculation.

A hop that changes the internal state

Use the six-dimensional exchange-antisymmetric coincidence space of the published calculation. G(E,K) is the projected free resolvent, including all positive and negative one-body branches. The physical coincidence amplitude solves (G⁻¹−gC)u=0, with C=I for density or C=β⊗β for mass. Here G is invertible near the selected pole. At rest Cu=u for either contact, and u†∂ₑ(G⁻¹)u=1/w. Inversion acts as β⊗β. All derivatives below are evaluated at (z,0). Define the additional interaction by

vⱼ = [∂ⱼ G⁻¹]u
Jⱼ = vⱼu† + uvⱼ†
mⱼ = [u†(∂ⱼ² G⁻¹)u + 1/(zw)]/2
ΔV(K) = Σⱼ [sin Kⱼ Jⱼ + 2(1−cos Kⱼ)mⱼ I].

The vector vⱼ is odd under inversion and orthogonal to u. Consequently Jⱼu=vⱼ. In the pole kernel P=G⁻¹−gC−ΔV the derivative (∂ⱼP)u vanishes for both contacts. The first derivative of the unit coincidence spinor may be set to zero with a smooth phase. The usual second-order terms involving other coincidence states then vanish. Implicit differentiation gives E″ⱼ=−w[u†(∂ⱼ² G⁻¹)u−2mⱼ]=1/z. Coordinate reflections remove the off-diagonal quadratic terms. Each such reflection is represented on either one-body orbital and spin space by βσⱼ. The added bonds transform by the same representation because u at rest has definite reflection parity.

These are time-independent, nearest-neighbor pair bonds. In the convention V(K)=Σ Tₛ exp(iK·s), their forward matrices are T₊ⱼ=−mⱼI+Jⱼ/(2i), the reverse matrices are T₊ⱼ†, and their onsite term is 2ΣmⱼI. For the 64³ integral, (mₓ,mᵧ,m_z)=(−0.979714,−1.006464,−0.774101) and (|vₓ|,|vᵧ|,|v_z|)=(0.115874,0.050194,0.722392). The replay constructs the matrices from the density calibration, with no mass-contact coefficients. A separately refitted even bond could match each interaction's quadratic response, using mⱼ=(1−Rⱼ)/(2zw). That prescription needs each interaction's measured curvature.

There is a stronger prediction for these two contacts. They differ only on inversion-odd coincidence states. The corrected bound spinor has zero odd amplitude at first order in K. Its odd amplitude first can occur at third order, since inversion also excludes its even powers along a fixed line through rest. Eliminating the gapped odd block of the inverse kernel therefore changes the simple pole between these two contacts first at order |K|⁶. More explicitly, on the even solution the coupling into the odd block is O(|K|³) and its return contributes its squared magnitude. At K_z=0.05 the mass pair's absolute probability of odd coincidence drops from 5.01×10⁻⁶ to 2.92×10⁻¹⁰. Doubling K_z from 0.025 to 0.05 multiplies the remaining energy difference by about 65. The leading sixth power predicts a factor of 64 as K tends to zero.

What survives at finite momentum?

The forward energy-current test is F=E(dE/dk)/k along K=k n, for unit direction n. Symmetric energy sourcing with the established translation generator requires F=1 for the common dispersion E=√(z²+k²). Along an oblique direction F measures the projection onto n. We compute it by independently solving the microscopic pole at k and k±0.00004. All entries use walk units.

Held-out direction and kNearest bonds, densityNearest bonds, massRange-two bonds, densityRange-two bonds, mass
z, 0.0501.0050551.0050421.0001071.000094
z, 0.1001.0215741.0213421.0018841.001650
body diagonal, 0.0401.0106781.0106641.0003741.000360
body diagonal, 0.0801.0479671.0476881.0068961.006616

The range-two version adds a scalar Σᵢ≤ⱼ cᵢⱼ sᵢsⱼ, where sᵢ=2(1−cos Kᵢ). This uses axis hops of up to two cells and face-diagonal hops. To calibrate it, evaluate the density inverse-kernel eigenvalue at the target E=√(z²+|K|²) on the three axes and the three face diagonals, with each active component 0.008, 0.016 and 0.032. A scalar addend subtracts directly from that eigenvalue. Extrapolating its quartic coefficient at rest determines the six numbers. In order xx, yy, zz, xy, xz, yz they are approximately (−4.5704,−4.5096,−1.8692,−19.0918,−12.3185,−12.3523). Reflection symmetry makes these the six independent quartic terms. In the exact derivative limit this cancels the quartic energy error for both contacts. The body diagonal was held out entirely. All mass-contact results were held out. The model still differs from the target at finite momentum, and these coefficients were calibrated at one binding energy.

Direct pole differences on the three axes give corrected rest R within 0.000001 of one. Changing the relative-momentum integration mesh from 48³ to 64³ changes the finite-momentum table by less than 0.000001. This is numerical refinement of a model calculation. Larger momenta can probe other bands or strong changes from the range-two stencil; its calibration controls the neighborhood of this pole.

How to couple a local clock to the new bond

Assign half the energy of each added pair bond to each of its endpoints. At clock momentum q=K_f−K_i the additional energy vertex between coincident states is exactly [ΔV(K_f)+ΔV(K_i)]/2. For normalized bound eigenstates multiply this matrix on the left and right by their physical coincidence amplitudes. Reversing K gives an especially simple check. When K_f=−K_i the explicit sine terms cancel from this endpoint vertex, even though they have changed the moving eigenstates. A uniform lapse couples to the whole repaired Hamiltonian.

The calculation fixes the forward current and the equilibrium dispersion to the stated orders. Finite-q clock matrix elements also depend on how the energy is assigned to bonds. Sudden pulses may excite other pair states. A universal symmetry of all bands, and a field law for gravity, would require further conditions.

Run python collision_transport.py --size 32 with NumPy. Use --size 64 --fine for the table and the independent rest-curvature checks. The code accepts the bundled bound_3d.py or the original sibling study. design(torus) returns the three J matrices and nearest-neighbor scalars. symbol constructs the added potential and vertex gives its endpoint energy insertion. Calling d['quartic']=quartic_design(torus,d) also enables variant='range2'.

Compare the moving-pair responses

A common inertial response gives 1. Each value comes from a moving two-body pole on the 64³ momentum mesh. The density contact supplied the calibration.

Density 1.000107 · Mass 1.000094.

What did the two rubidium isotopes do in free fall?

Sections in this chapter

Two bound pairs in the walk can have the same energy at rest and respond differently to equal forces. An atom interferometer lets us ask a sharper experimental question. If the two rubidium isotopes sampled different amounts of that response in Earth's field, how much difference would the measurement allow?

Recovering the phases from 1,481 shots

Asenbaum and colleagues launched rubidium-85 and rubidium-87 together. Laser pulses split and recombined each isotope's matter waves. The measured quantity in Figure 3 is the phase of rubidium-85 minus the phase of rubidium-87 for each shot. The left panel preserves all 1,481 individual points. Their colors encode momentum transfer of 4, 8 or 12 photon recoils. Filled and hollow markers distinguish the initial laser beamsplitter direction. The histogram at right averages over additional switches. Experiment · Figure 3 and Table I

We read the native vector marker positions from the authors' Figure 3 source, calibrated the vertical axis against the −0.05 and +0.05 radian ticks, and rounded the extracted phases to the nearest microradian for storage. That rounding describes how we read the drawing. Individual shot scatter is 14–25 milliradians. The source bundle supplies six sufficient-statistic rows containing the shot count, sum and sum of squares. Its optional figure audit reproduces every row from the pinned original. Authors' figure source

Momentum transferShots, down / upMean down / up (mrad)Equal-direction mean (mrad, 1σ)
4 recoils244 / 243−11.077 / +3.409−3.834 ± 0.630
8 recoils244 / 260−9.558 / +4.268−2.645 ± 0.688
12 recoils245 / 245−4.359 / +4.235−0.062 ± 0.985

The reversal matters. Recoil-sensitive parasitic paths change sign relative to the acceleration signal when the beamsplitter reverses. Within each order we weight the two directions equally, even when their shot counts differ. We propagate their two empirical standard errors and fit the three resulting means with inverse-variance weights. The model allows a common phase offset b.

mean phase at order n = b + n k g T² η
η = 2(a₈₅ − a₈₇)/(a₈₅ + a₈₇)
k = 2π/(780 nm), T = 0.955 s, g ≈ 9.81 m/s².

The fitted offset is −5.767 mrad. The uncorrected differential acceleration is (6.117 ± 1.952) × 10⁻¹² in units of g, with χ² = 0.597 for one degree of freedom. As a retrospective check, fitting only the two outer orders predicts −1.948 ± 0.585 mrad at eight recoils. The measured −2.645 ± 0.688 mrad lies 0.77 combined standard deviations away.

Table I independently supplies the apparatus corrections. The kinematic correction is +1.5 and the magnetic-gradient correction is −5.9, both in units of 10⁻¹². The stated systematic uncertainties from kinematics, AC Stark shift, magnetic gradient, pulse timing and blackbody radiation combine in quadrature to 3.4 in the same units. Applying them to our fit gives (1.72 ± 1.95 statistical ± 3.4 systematic) × 10⁻¹². The collaboration obtained (1.6 ± 1.8 statistical ± 3.4 systematic) × 10⁻¹². The figure releases differential phases. It omits the per-shot uncertainties, fringe-direction and imaging-order labels needed to reproduce the authors' full weighting. The reconstruction imports their independently calibrated apparatus corrections. Experimental calibration and uncertainty budget

Which claim about the walk does this test?

The walk calculation gives an acceleration contrast of 5.251% of the mean along the model's z axis, for two particular composites interacting through their scalar field. A terrestrial comparison needs a map from those two contacts to isotope composition, a fraction of Earth's vertical acceleration supplied by this interaction, and an orientation. The walk currently supplies none of those three assignments.

For a concrete conditional test, let f be the fraction of the common vertical acceleration supplied by this sector. Let D be the signed difference in participation between the isotopes, including the orientation factor, normalized to one for a full one-to-one assignment aligned along the model axis. Assume the remaining acceleration is common and the anomalous contrast scales linearly. On the near-zero phase branch calibrated by the experiment, the result is

η = f D × 0.05251
−1.14 × 10⁻¹⁰ < f D < 1.79 × 10⁻¹⁰   (approximate 95% interval).

The interval combines our statistical error and the paper's systematic error as independent Gaussian uncertainties. Isotopes with the same participation give D = 0 regardless of the model's internal contrast. The measurement therefore constrains an isotope-dependent coupling to the terrestrial field. It supplies no composition-independent limit on the contact interaction in the walk.

A full-strength assignment also requires following the trajectories and phase branches. In an idealized phase-only measurement at orders 4, 8 and 12, changing η by 2.18 × 10⁻⁸ adds whole turns to all three phases. Extrapolating one fitted branch cannot settle every large-phase alias. Conversely, if co-launched atoms really fell with a 5.251% difference in terrestrial g, their centers would separate by about 0.94 m over the 1.910 s pulse sequence. That trajectory estimate illustrates what a large assignment would demand of the apparatus. It is separate from the local statistical interval.

Run python3 fall_measurement.py to reproduce the statistics offline. To audit the six moment rows, download the cited arXiv v2 source archive, install PyMuPDF 1.26.5, and pass the archive to python3 fall_measurement.py --from-figure PATH. The check verifies the SHA-256 digests of the source archive and original figure before reading the markers.

What fraction of the walk’s differential acceleration could appear here?

The slider represents the signed product of the terrestrial field fraction and the isotope-response contrast, in units of 10⁻¹⁰. The mapping assumes aligned accelerations on the measured small-phase branch. Zero predicts equal free fall.

Predicted Eötvös parameter 0.00 × 10⁻¹².

Does the same hopping rule work at a new binding energy?

Sections in this chapter

The first transport rule was calibrated on a pair with rest energy 1.90. To test its transfer, vary the flat contact strength so that the pair binds at a different energy, and leave the hopping coefficients fixed. Rest energy and one-body speed are in the same units across the tests. The observable R equals the rest energy times the curvature of the exact moving pole; the target is one.

At rest energy 1.75, the original one-energy fit gives R along z of 1.191530 for the density contact and 1.184728 for mass. At 1.94 it gives 0.966124 and 0.965597. A calibration that transfers between two contacts at one binding energy therefore does not automatically transfer between binding energies.

How to use three rest preparations

Let u be the measured unit even coincidence spinor, Z its coincidence probability, E its rest energy and G the free coincidence Green matrix. In this example the even spinor lives in a two-dimensional real subspace, and the odd channel has four components. A local hopping can couple those two subspaces through its term J sin K. The target for that map is (∂G⁻¹/∂K)u at zero momentum. The even term 2M(1−cos K) has a second target,

u† M u = [u† (∂²G⁻¹/∂K²) u + 1/(E Z)] / 2 .

These derivatives come from the specified microscopic free kernel. The training uses rest energies 1.68, 1.81 and 1.90. A least-squares fit for the odd map and a fit for the three real independent entries of the even two-by-two matrix give one fixed set of bonds per axis. The replay reinserts the leftover odd mixing into each contact’s inverse pole kernel before predicting its curvature. No moving mass-contact response is used to set a coefficient. Rest measurements alone would not supply the required Green-matrix derivatives in a new physical material.

Held-out rest energyOne-energy z response, density / massThree-energy z response, density / massLargest error across all axes and contacts
1.611.428927 / 1.4056181.003407 / 1.0033730.3612%
1.751.191530 / 1.1847280.999540 / 0.9995360.0464%
1.861.043106 / 1.0425881.000206 / 1.0002050.0206%
1.940.966124 / 0.9655970.999592 / 0.9995760.0424%

The fine replay uses a 48³ mesh. It calculates derivatives of the inverse kernel and separately solves for moving poles at two small nonzero momenta at held-out energies 1.75 and 1.94. The extrapolated moving energies agree with the predicted z curvature to 0.00001.

A price paid outside the calibration

The three rest spinors are nearly parallel. Distinguishing their quadratic measurements requires an even hopping matrix with operator norm as large as 1250.5 in the walk units. Discarding singular values less than one thousandth of the largest shrinks that norm to 48.03; the odd map has maximum norm 36.96 in both versions. The truncated fit gives a worst error of 0.873% across the two contacts and three axes at E=1.75, and 3.46% at E=1.61. This is a tradeoff between a stable set of coefficients and accuracy on increasingly different preparations. A direct spectral test makes the cost physical. At total momentum (0,π,0), restrict the full Hamiltonian to two trial pairs occupying one site in the upper or lower orbitals. The free on-site energies are +20 and −20. Add gI and four times the fitted even hopping along y; the sine hopping vanishes here. The Rayleigh minimum of this two-state matrix bounds the bottom of the full spectrum from above. For both contacts at rest energy 1.90 the full fit therefore has a level at or below −5029.9 on the 48³ mesh. The truncated fit still gives a level at or below −194.4 and one at or above +187.2, compared with an original operator norm below 75. This check is specific to the three-energy fit. The whole-spectrum chapter examines the separate, one-binding repair. The signed two-walker model alone cannot identify a physical vacuum instability.

Pair-hopping corrections to broken moving-frame invariance also occur in nuclear lattice calculations. The distinct test here is the shared correction across the specified contacts and untrained binding energies. Li and colleagues on restoring Galilean invariance on the lattice · Run the transfer test · Inspect spectral changes at larger momenta

Can a repaired pair stay at rest through a local clock cycle?

Sections in this chapter

The two contact interactions now give the same leading inertia at the selected binding energy. A second experiment asks what happens inside one resting pair. Apply four weak pulses of area θ, using cosine and sine spatial patterns with wave number q and reversing their signs to close the cycle. If the cycle acts as a uniform spatial translation, it must leave the entire resting state unchanged. The leading probability to leave the state is θ⁴ Var(B), where B is the Hermitian commutator of the two pulse generators. Inversion makes its expectation zero at rest. The quantity reported here is Var(B)/q² as q tends to zero. First clock experiment · Repair to the collision

Repeat both pulses on the complete wavefunction

Write S for the map embedding a six-component antisymmetric coincidence spinor as a constant across relative momenta. Its adjoint averages over relative momenta and extracts the coincidence amplitude. Let v = S†b for the normalized resting bound state b of energy E. Write V for the original contact, h₁ and h₂ for the independent walkers, and H for their interacting sum at zero total momentum. The source of the resting wave is S Vv. Both contacts give the same b and source.

Half of each bond's energy goes to each endpoint. At rest an added odd pair hop contributes qJ/2 to the outgoing energy vertex at small q. A spatial divergence added to the energy density contributes iqW, where W is Hermitian and odd under inversion. Its sum over space vanishes. The analytic first-order changes to B|b⟩/q are

odd pair hopping J          (H + E) S Jv / 2
energy redistribution W     i(H − E) S Wv .

The two different energy signs distinguish a change to the Hamiltonian from a change in how a clock couples to that Hamiltonian. For the unmodified pulses the complete vector is D S Vv + S V S†D b, with D the half-sum of the derivatives of the two one-particle symbols along the pulse axis (each derivative is taken with respect to that constituent's momentum). At zero total momentum the purely free commutator vanishes pointwise. The program also multiplies the finite-q vertices in their two orders, arranges their products by how many contacts occur, and verifies second-order convergence of the entire vector.

At 48 samples per relative-momentum axis, the original loss coefficient is 8.763898 for both contacts. Coefficients trained on a 24³ grid give 5.635249 for density and 4.353232 for mass after repairing their motion. Allowing one shared coincidence-local W, fitted jointly on the smaller grid, lowers these to 3.459441 and 3.465795. These are coefficients of the weak-pulse probability, in the walk's units.

A lower bound for any repair acting only at coincidence

The model has an orbital parity operator β₁β₂. In the odd sector the two separate mass terms cancel on a constant coincidence spinor. Applying H to that spinor produces a constant odd part and an even part that depends on momentum. Thus the zero-mean, odd-orbital part of B|b⟩/q is independent of every admissible J and W above. The statement covers arbitrarily long translations of a coincident pair with a differentiable hopping symbol at zero. It assumes inversion symmetry, the specified one-particle kernel, the same flat rest Hamiltonian and a redistribution acting only at coincidence.

For a z-directed pulse the surviving harmonics are −sin x cos y sin z, −sin y sin z and cos z. They are mutually orthogonal and have mean squares 1/8, 1/4 and 1/2 over the Brillouin torus. Multiply each by the spinor (αⱼ¹+αⱼ²) S Vv / 2 and sum their squared norms with those weights. On the 48³ mesh this gives a protected contribution 3.337557. The replay verifies this number independently by projecting each full microscopic result and subtracting its momentum mean.

There is a physical way to change the protected component. Give the energy polarization access to configurations where the two constituents occupy different sites. A single such operator works for both contacts. Separated constituents and the common energy polarization · Complete microscopic calculation

How far must the clock coupling reach inside a bound pair?

Sections in this chapter

On the ordered walk, two interactions have the same normalized bound state at rest energy 1.90. A collision hop brings their moving energy responses close together. A long-wavelength clock pulse still moves amplitude out of the selected rest state. Giving the clock access to constituent separations of up to three lattice steps reduces the squared leakage slope from 5.6351 to 0.05563 for the density contact and from 4.3531 to 0.05576 for the mass contact. One operator produced both results on a finer mesh than the one used to choose it. The total Hamiltonian, including its collision hop and dispersions, is exactly preserved. Original pair Hamiltonian · Earlier clock-pulse construction

A clock vertex with a finite spatial range

Use the same z-directed two-pulse energy-density loop as the rest-clock calculation. Write L_C for its leakage amplitude divided by the transferred momentum q as q tends to zero, with the collision repair already in place. Its squared norm sums all sixteen spin amplitudes and averages over the whole relative-momentum torus. It is a response coefficient. A transition probability also depends on the pulse normalization and q.

Let u be the normalized spinor of the coincident pair, frozen at calibration. For each anchor X, construct a two-constituent cloud F_X from amplitudes f_ab(r) with Manhattan distance |r|₁ ≤ R. Give half the amplitude to |X+r,a; X,b⟩ and half to |X,a; X−r,b⟩. Exchange antisymmetry and inversion oddness require f(−r)=−f(r)ᵀ=−β f(r) βᵀ, where β is the one-constituent inversion matrix. The even coincident seed |u_X⟩ has both constituents at X. A Hermitian operator acting on this pair is

W_X = −i ( |F_X⟩⟨u_X| − |u_X⟩⟨F_X| ).

An anchor difference of these operators changes the energy-density vertex by i sin(q) W in our Fourier convention. Its sum over all sites vanishes by translation. The two endpoint choices give a multiplier cos(K_z r_z/2) for the cloud in a center-of-mass momentum fiber K along z. This defines the operator also between moving states. The replay checks its Hermiticity between K_z=−0.43 and +0.27 and its exact zero at equal momenta. At rest the reverse term in W annihilates the even bound state b by inversion. If v is b's coincidence spinor, the change in leakage is therefore

L_C → L_C + (H_C − E) F , F = ⟨u|v⟩ Fourier[f].

H_C is the full two-particle Hamiltonian in the rest fiber. At each range we choose a single set of coefficients minimizing the sum of the two squared norms. The replay fits in separation space using the exact finite hopping stencil, then evaluates both norms directly in momentum space. The calibration uses this specific rest state, axis and both interactions. Applying the resulting density to new states requires no spectral projector or measurement of their energies.

Maximum separation RIndependent complex amplitudesDensity, 24³ → 40³Mass, 24³ → 40³Density, 36³ → 56³Mass, 36³ → 56³
Original repaired vertex05.6351194.3531315.6348244.352772
043.4593643.4657173.4594633.465775
1341.9920041.9967871.9920721.996804
21240.7224660.7230350.7225060.723016
33140.0556300.0557640.0556490.055737

Entries are squared leakage slopes on the second mesh. Within each column pair the density coefficients, coincidence seed and collision-hop coefficients are fixed on the first mesh. The contact strength on each mesh uses the original prescription of setting the rest energy to 1.90. Increasing the mesh changes the discretization of the Brillouin-zone integrals. The held-out check tests numerical transfer at fixed binding and does not provide an independent material measurement.

Why one cloud can cancel two different leakage vectors

There is an exact rest-frame solution if spatial range is unrestricted and the collision repair uses the derivative of the contact Green matrix. The derivation depends on the two constituent spectra and the signs of these particular contacts.

At each relative momentum p put A=h(p)⊗I, B=I⊗h(−p), H=A+B and V=A−B. The two factors commute and A²=B²=e(p)²I. Hence HV=VH=0. The derivative D of the free two-body Hamiltonian with respect to total momentum K_z at rest is one half of ∂V/∂p_z. Differentiating HVH=0 gives HDH=0. With R₀=(E−H)⁻¹ this implies

R₀D + DR₀ − E R₀DR₀ = D/E.

Multiplying on both sides by E−H verifies the identity directly. The free energies are −2e, 0 and +2e, with e≥1, so at E=1.90 the inverse is bounded by 10 throughout the Brillouin zone.

Let Π extract the six antisymmetric coincidence amplitudes, and Π† embed them as a constant spinor over relative momentum. Write P=Π†Π and G=ΠR₀Π†. The common bound state has the form b=R₀s for a constant s=Π†s₀, and v=Πb=Gs₀. Take the linear collision hopping matrix J such that Jv=(∂_{K_z} G⁻¹)v at fixed E, and put j=Π†Jv/2. The derivative of the inverse gives Jv=−G⁻¹ΠR₀Db. In the odd sector the density contact has sign + and the mass contact has sign −. With common strength g the two rest Hamiltonians there are H±gP. Expanding the pulse product to first order yields

L± = L₀ ± gP(Db+j), L₀ = Ds+(H+E)j.

The mean of the two cancellation equations fixes F=R₀L₀ uniquely. Their difference asks for P(Db+j+F)=0. Using R₀(H+E)=2ER₀−I and the value of Jv, the remaining expression is

P(Db+j+F*) = P[(DR₀+R₀D−ER₀DR₀)s] = P D s / E = 0.

The last equality follows because D is a derivative of a periodic trigonometric polynomial, s is constant, and Π takes the momentum average. The cancellation holds on the full Brillouin zone and on each uniformly sampled mesh here. The exact-derivative replay checks both full residuals independently. The larger squared residual is below 3×10⁻²⁵ on all four meshes.

F specifies an odd cloud through the same Hermitian construction. Its Fourier coefficients decay exponentially in relative separation. Indeed the free symbol is a finite trigonometric polynomial and E−H is invertible on a compact real torus, so the inverse is analytic in some open strip around that torus. Truncating F then gives finite-range clock assignments with arbitrarily small error for the exact derivative. The explicit radius-three operator above comes from a finite fit using the implemented finite-difference repair. It costs additional local couplings, and the table quantifies the remaining error.

How accurately must the collision repair be known?

The two-vertex cancellation also has a check independent of the range fit. For measured or approximate amplitudes define L₀=(L₊+L₋)/2, Δ=(L₊−L₋)/2, and A₀=H−E. Let U embed the four odd onsite spinors isometrically, so UU† agrees with P in this sector. Put d=U†Δ−gU†A₀⁻¹L₀ and C=gU†A₀⁻¹. Writing w=L₀+A₀F, the mean squared error for any common cloud is ‖w‖²+‖d+Cw‖². Its minimum is d†(I+CC†)⁻¹d. The replay evaluates this four-by-four formula and independently applies both full Hamiltonians to the minimizing cloud.

A finite-difference collision repair calibrated on 24³ has a minimum mean squared error of 2.4×10⁻¹⁹ on its own mesh and 7.7×10⁻⁹ on 40³. Calibrating on 36³ and holding fixed to 56³ gives 1.7×10⁻¹² on the latter mesh. The exact-derivative result explains why going beyond onsite pairs can keep reducing this error. The tested observable is one long-wavelength loop at rest. A common response at finite transfer, other energies or with dynamical gravity requires further equations.

Run python extended_clock.py for the first two numerical columns or python extended_clock.py --fine for the last two. The script uses NumPy and the accompanying rest-clock and collision-transport modules.

Can both interactions share the entire moving bound state?

Sections in this chapter

Choose the relativistic band energy E★(K)=√(1.90²+|K|²) as an input. An inverse calculation asks whether one change to the pair hopping can give two different contact interactions that energy and the same microscopic wavefunction throughout a small momentum window. There is a constructive answer. It is more restrictive than getting the same fitted curvature at rest, and it makes the cost of imposing the desired answer explicit.

Let G(E,K) be the six-dimensional free coincidence Green matrix, u the unit even coincidence spinor of the original resting pole and g its contact strength. Take a momentum where the target lies in a gap of the free two-walker spectrum and G is invertible. Define

y(K) = G(E★,K)⁻¹ u − g u
V(K) = y u† + u y† − (u†y) u u† .

Since G is Hermitian there, u†y is real. V is Hermitian, V(0)=0, and V(K)u=y. For either original contact C=I or β₁β₂ one has Cu=u. Therefore [G⁻¹−gC−V]u=0 for both. The full normalized wavefunction is obtained by applying the free two-particle resolvent to the coincidence source G⁻¹u. Its normalization follows from −∂G/∂E and is identical for both interactions. The code checks the full normalized wave and its coincidence amplitude, including an oblique momentum. One can bound the mixed-sign continuum edge by 11 times the sum of the absolute components of K in these units. For every reported test the target energy exceeds this bound and lies below the two-positive-particle threshold of at least two. Each matrix inversion is performed at the specified energy. The construction guarantees an eigenvector. Resolving it as a unique spectroscopic line also requires separation from other interacting poles. The original resting pole is simple, which gives this separation in a neighborhood of rest by continuity. The projector onto the explicit eigenvector still commutes with the Hamiltonian at a degeneracy.

What four cells of hopping can approximate

An exact inverse obtained separately at each momentum need not have finite range. Along the z axis, write x=2(1−cos K). Interpolate the inversion-even part of V divided by x and the inversion-odd part divided by sin K. Polynomials of degree d−1 give a Hermitian hopping stencil extending at most d cells. For each d the coefficients come from d interior Chebyshev points spanning 0<|K|<0.13. Independent moving-pole solves for both contacts test five other momenta, including the endpoint.

Maximum hop along zLargest absolute pole-energy errorLargest odd coincidence amplitude
14.30 × 10⁻⁵4.54 × 10⁻⁴
21.17 × 10⁻⁶1.31 × 10⁻⁵
35.33 × 10⁻⁸7.75 × 10⁻⁷
43.31 × 10⁻⁹6.15 × 10⁻⁸

These are axial interpolation tests on a 48³ integration mesh. Extrapolating the fitted coefficients across the Brillouin zone can produce unphysical bands. Whole-spectrum audit

One energy vertex for two Hamiltonians

Let Pᵢ and P𝒇 project onto the exact shared pole at the incoming and outgoing momenta. Fix its phase by the same u. The two microscopic endpoint energy vertices R differ only by a coincidence operator proportional to I−β₁β₂. That difference annihilates Pᵢ from the right and P𝒇 from the left. Consequently the following addition to R is identical for the two contacts. Subtract (1−P𝒇)RPᵢ and P𝒇R(1−Pᵢ), then replace the one remaining band-to-band matrix element by any specified Hermitian band vertex that agrees with the energy at zero transfer. At zero transfer the addition vanishes because the flat Hamiltonian already preserves P.

For an oblique pulse in the replay the original first-leg unprojected wave is exactly the same for both contacts. Its squared amplitude outside the shared band is 0.002207 on the 48³ mesh. This comparison checks the microscopic incoming spin wave and both constituent hoppings. The common addition removes that component. It uses spectral projectors on a gapped momentum window. A globally finite-range rule achieving this exact cancellation has not been constructed.

Choosing the positive midpoint energy √(1.90²+|(K𝒇+Kᵢ)/2|²) for the band vertex makes the opposite-transfer clock loop equal to K·q for every pair of transfers that stays in the window. Squaring the two amplitudes and subtracting cancels both the mass and the q² terms. The next chapter tests independently shaped clock patterns. The positive midpoint rule gives a measurable discrepancy there. One calibrated band and one family of pulses therefore leave the full spatial deformation algebra undecided. Independent lapse patterns · Microscopic inverse and pulse replay

Do two different lapse profiles generate the right translation?

Sections in this chapter

A cosine and sine at the same wavelength can give the exact spatial shift even when two unrelated clock pulses give the wrong answer. For a relativistic positive scalar band in one dimension, a simple midpoint vertex passes that first test at every wavelength. It misses the shift by 5.2% on a pair of different Fourier modes. A two-component Dirac particle with a local first derivative gives the exact answer for every pair of modes. Projecting away its negative-energy intermediate states changes the result even between positive-energy external states.

This continuum calculation supplies target amplitudes for testing a microscopic pair. A signed Dirac particle has been specified independently of the two-body walk. The geometric comparison uses the spatial displacement generated by the commutator of two normal deformations of a flat slice. Teitelboim, How commutators of constraints reflect the spacetime structure90096-1) · Dirac, The quantum theory of the electron

A same-wavelength test that misses an error

Let H[f] couple the energy to the real lapse f(x), and let D[w]={w(x),p}/2 generate a spatial shift. Use p=−i∂ₓ, c=ℏ=1, and the convention i[H[f],H[g]]=D[f g′−g f′]. A Fourier mode q of the scalar lapse sends |k⟩ to |k+q⟩ with amplitude E(k+q/2), where E(k)=√(m²+k²). The symmetric midpoint makes the operator Hermitian for every real f.

For f=cos(qx) and g=sin(qx), the two paths that return to k give [E(k+q/2)²−E(k−q/2)²]/2=qk. The two paths ending at k±2q cancel. Thus the scalar vertex passes this test exactly for all real q and k in the continuum.

For different modes, compare HᵣH_q and H_qHᵣ at k+q+r. Suppressing the common factor i, the scalar model predicts

E(k+q+r/2) E(k+q/2) − E(k+r+q/2) E(k+r/2).

Spatial translation requires (q−r)[k+(q+r)/2]. For m=1, k=0.5, q=1.5, r=0.5, the two answers are 1.422010710 and 1.500000000. This counterexample tests the specified scalar midpoint coupling. Other positive-band energy vertices require their own calculation.

A local matrix vertex that passes every two-lapse test

Choose h(k)=αk+βm, where α=σₓ and β=σ_z, and H[f]={f,h(p)}/2. Its Fourier vertex is exactly h((k_final+k_initial)/2), since the momentum dependence is linear. For any two endpoints a,b,

h(a)h(b)=(ab+m²)I + m(a−b)αβ.

In the two possible paths the separation a−b between vertex midpoints is always (q+r)/2. Subtracting the products cancels every spin-dependent term. The scalar difference is exactly (q−r)[k+(q+r)/2]I. Bilinearity proves the normal-normal relation for arbitrary finite Fourier profiles, and on smooth periodic test functions by the differential-operator identity. The proof uses the continuum derivative, with unbounded Fourier momentum.

Now prepare positive-energy spinors at both endpoints. The exact translation acquires the overlap ⟨u₊(k+q+r)|u₊(k)⟩. At each step the signed matrix element from (a,s) to (b,t) is [(sE(a)+tE(b))/2]⟨u_t(b)|u_s(a)⟩. Inserting a complete set between the two pulses gives the following mode test.

Paths through the intermediate stateContribution
Positive sign1.403454263
Negative sign−0.001371711
Sum, also the projected spatial translation1.402082552

The contribution is a virtual intermediate amplitude in an operator product. This calculation makes no prediction of real antiparticle production. A positive external preparation is consistent with the complete intermediate-state sum.

Independent finite-profile and boundary checks

The replay applies both operators to a five-momentum packet. The real first profile has a constant and harmonics 1, 4 and 7, and the second has a constant and harmonics 2, 3 and 6. Their phases differ. It separately constructs f g′−g f′ by Fourier convolution and compares the full outgoing vectors. The relative norm error is 3.4487% for the scalar midpoint vertex and 5.2×10⁻¹⁶ for the signed matrix vertex. For a positive external packet, retaining only positive intermediate spinors leaves 0.19905% relative error. Adding the negative intermediate contribution restores the full answer to roundoff.

The grid uses momenta k=j/4 for |j|≤28. Every leg of every path used in the quoted packet fits within that interval. Moving the input to the cutoff and deleting paths that leave the grid gives an absolute cosine–sine residual of 31.5078125. A hard truncation or a lattice Bloch symbol must therefore be tested with its own boundary and derivative rules.

There is also a separate mixed bracket. Write H[g]=αD[g]+βmg on the fixed spatial frame. Direct differentiation gives

i[D[f],H[g]] − H[f g′] = −α D[g f′].

The replay recovers this entire remainder. On the profiles above its norm is 79.27% of ‖H[f g′]ψ‖. A transformation of the metric or frame is required when representing general changes of slice. The normal-normal benchmark alone establishes neither that transformation nor the constraint algebra of dynamical gravity.

Run python lapse_algebra.py with standard Python. The replay checks Hermiticity, three pure cosine–sine wavelengths, different individual modes, the two arbitrary real profiles, both intermediate signs and the Fourier boundary control.

What happens to the repaired clock away from its calibration?

Sections in this chapter

The six-coefficient range-two repair produces six deeply negative pair energies at the corner of the momentum zone. Their energies run from about −914 to −874 in units where the clock at rest has energy +1.90. The original Hamiltonian has no level below −35 at that corner. A longer but finite hopping rule eliminates these deep deviations throughout the zone while retaining the same quadratic and quartic behavior near rest.

Counting states without following the clock pole

The audit includes all sixteen onsite spin states and all four combinations of one-body energy signs. We extend each new six-dimensional bond matrix by zero on the ten exchange-symmetric coincidence states. The original interaction gC still acts on all sixteen. A different extension on the ten extra channels could add levels. The six-dimensional trial space used below already suffices to establish the deeply shifted energies.

At each total momentum K, G(E,K) is the integrated free two-particle resolvent projected onto coincidence. In a gap its derivative is negative definite. For invertible onsite interaction V(K), the increase in the number of negative eigenvalues of G(E,K)−V(K)⁻¹ between two energies counts all discrete states between those energies, with multiplicity. This avoids selecting states by overlap with the original clock. A direct 1,024-dimensional matrix diagonalization on a 4³ periodic relative-momentum torus independently checks the counts and lowest energies for all three Hamiltonians and both contacts. Lattice finite-rank spectral method

The global one-body bound is |E₁|≤√(33²+1), from the known mass and ordered spin terms. Thus the original two-body operator has norm at most 2√(33²+1)+|g|<75. At K=(π,π,π) the free norm is exactly 34. To see the sharper bound, write xᵢ for the cosines of one constituent's three momenta. Its partner has cosines −xᵢ. Their positive mass terms sum to 18+(4/3)Σxᵢ²+4Σᵢ<ⱼxᵢxⱼ. Both have squared kinetic spin coefficient 1−Πxᵢ² ≤ Σ(1−xᵢ²). Using √(m²+b²)≤m+b²/(2m) and m≥1 bounds the energy sum by 34, attained at constituent momenta 0 and (π,π,π).

Corner HamiltonianNumber below −35Lowest energyHighest energy below −35
Original0——
Nearest collision bonds1−40.0675−40.0675
Range-two collision bonds6−914.4431−874.4430

The table applies to either contact. Their middle levels can differ. The results are from 48³ cubature. The deepest range-two energy differs by 0.0006 from the 40³ result. The gap below −35 for the original is independently checked using a controlled integration error. Approximate (−35−34x)⁻¹ on [−1,1] by its degree-23 Chebyshev series. Its tail is bounded by (2/√69)r²⁴/(1−r) with r=(35−√69)/34. Each matrix polynomial in H_free/34 of that degree integrates exactly on the 48³ periodic mesh, since H_free has frequencies at most two per coordinate. Twice the uniform tail bounds the difference between the mesh and integral by 0.00674. The measured inverse-kernel eigenvalues at −35 lie at least 0.0482 from zero and have the same sign count as at minus infinity. The margin exceeds both the quadrature bound and numerical roundoff in this check.

There is also a variational explanation. On the six-dimensional space of states localized at coincidence, the free onsite block is 10(βₐ+βᵣ). At the corner all sine bonds vanish. The most negative trial expectation is already −39.04 for the nearest bonds. Even the largest eigenvalue of the range-two trial block is below −874. The min–max principle puts at least six true levels below −870. There are exactly six below −75 because the correction acts on only six coincidence states and the original Hamiltonian is bounded below by −75. These are isolated states in the signed two-walker Hamiltonian. A many-body ground state or vacuum instability would depend on the field quantization, occupancy and accessible transitions.

The positive clock also loses its protecting gap

At rest the full calculation gives four positive poles between 1.67 and 1.98, approximately 1.900000, 1.906045, 1.907989 and 1.909264. Only the first belongs to the coincidence sector used by the condensate clock in its narrow interval. There are seven pre-existing negative poles between −1.67 and −0.01, the closest to zero being −0.05572. All repairs vanish at rest. At K_z=0.10 and 0.15 the original and both repairs continue to give four full-spin poles in (1.67,1.98) and zero in (−1.98,−1.67).

At every total momentum the mixed-sign free continuum contains zero, since two equal momenta have equal one-body energies. At K_z=0.225 this continuum extends to at least 2.09362. One witness uses relative momentum (π,π,π/2) in the two constituent energies. At the same K the positive same-sign continuum starts no higher than 2.01262, obtained at relative momentum zero. The continuous ranges overlap. The negative ranges follow by sign reversal. Thus no gap between the mixed- and same-sign continua can protect the positive clock there. A finite-rank interaction at coincidence leaves these continua in place. Widely separated relative wave packets still realize the free energies. This overlap leaves open embedded eigenstates with extra protection, and the precise momentum at which any particular pole merges.

A bounded finite-range alternative

Write s=Σsin²(Kᵢ/2)/3. For the fitted range-two matrix, the verified coefficient bounds give

||ΔV(K)|| ≤ 2.6√s + 12.1s + 1380s².

The first coefficient follows by Cauchy–Schwarz on the three sine bonds. The second uses the largest |mⱼ|. The third uses 144 times the largest absolute entry of the symmetric quartic coefficient matrix, in which cross coefficients are halved.

One option is to multiply the entire added potential by (1−s)¹²⁸(1+128s). It preserves the fitted energy through fourth order and annihilates the correction at the corner. Maximizing tᵃ(1+t)exp(−t) with t=128s bounds the total operator change by 0.402 at every momentum. Its maximum common-translation distance is 131 cells, measured in axis steps.

A shorter option uses the following polynomial, with the value at s=0 defined by continuity.

F(s) = [sin(16 arcsin√s)/(16√s)]²
w(s) = F(s)² [6−8F(s)+3F(s)²].

F is the normalized Fejér kernel. The identity F=[1−T₁₆(1−2s)]/(512s) gives a degree-15 polynomial. It lies between zero and min(1,1/(256s)). The second polynomial is increasing on this interval, with w(1)=0 as a function of s at the zone corner and 1−w(s)=O(s³) near rest. Its degree is 60. The original range-two stencil therefore becomes a finite rule of at most 62 common translation steps. To bound its size, maximize sᵃw for a=1/2,1,2. With t=256s the dimensionless upper factors are 1.097, 1.380 and 6. For t≥1 these follow by maximizing tᵃ⁻²(6−8/t+3/t²), and for t≤1 each is bounded by one. Substitution in the norm inequality gives a uniform perturbation below 0.370.

Consequently, for each K the spectrum of the 62-step Hamiltonian lies within 0.370 of the original spectrum, and conversely. This follows from the self-adjoint resolvent bound under a bounded perturbation. At the corner the two Hamiltonians agree exactly. Additional shallow edge states are possible within the bound. Along z at K=0.05 the shorter stencil gives forward clock responses of about 1.00014 and 1.00013. At K=0.10 they are about 1.00390 and 1.00364. The compact cutoff is an additional design choice. It costs hopping range and still cannot separate overlapping free continua.

Run python band_audit.py --size 24 for the default replay and --size 48 for the displayed energies. NumPy, collision_transport.py and the released bound_3d.py are required.

Does finer lattice spacing restore a common limiting speed?

Sections in this chapter

A continuum explanation makes a testable demand. Decrease the spatial spacing a while keeping the physical rest mass of each walker at 1, its small-momentum speed at 1, and the bound-pair rest energy at 1.90. The on-site contact strength is recalibrated from that same pair energy at every spacing. Everything else in this test follows the original ordered one-body symbol. We apply this test to the original contact Hamiltonians.

In lattice units the vector part b(k) is unchanged and the mass term is a+w(k), with w the original quartic regulator. Physical wave number is p=k/a and physical energy is lattice energy divided by a. At fixed physical p, b(ap)/a tends to p and w(ap)/a tends to zero. An individual walker therefore acquires the continuum dispersion √(1+|p|²). A composite explores many relative momenta even when its center is stationary. Original pair kernel

What happens to the measured pair

R is the rest energy times the second derivative of the moving pole energy. A pair with the common relativistic speed would give R=1 along every axis. The low-momentum column is the expectation of exp(−|p|²/8) for the normalized internal wave, with p in physical units. It is a smooth measure of how much a detector of fixed resolution can see.

SpacingR along z, density / massR along x, densityMixed signed-band occupationLow-momentum overlap
11.43825 / 1.364661.520190.04410.8834
1/42.82469 / 2.731214.252460.49950.2717
1/163.25623 / 3.248245.154600.67760.0418
1/643.29893 / 3.298435.204520.68690.00955

The two contacts approach one another along the sampled trajectory. Their responses depart strongly from the one-body speed, and the x and z responses differ. In the most refined calculation the detector sees under one percent of unit overlap. Agreement between species can coexist with a failure to recover the geometry already calibrated by the individual walkers.

Why probability remains in the high-momentum sector

In the two even coincidence orbitals take s₊ and s₋ to be the sum and difference of the upper and lower local spin singlets, normalized by √2. At rest s₊ has no projection on the mixed-sign free pair sectors at any relative momentum. In this basis the diagonal and off-diagonal entries of the free coincidence Green matrix can be computed without constructing a 16-by-16 matrix. For lattice energy z, one-body energy e and lattice mass m=a+w they are the torus averages of

G₊₊ = z/(z²−4e²),     G₊₋ = 2m/(z²−4e²),
G₋₋ = (m/e)² z/(z²−4e²) + (1−(m/e)²)/z .

The independent full signed-projector integration reproduces these entries. Put e₀²=|b|²+w² and define A=⟨1/(4e₀²)⟩, D=⟨w/(2e₀²)⟩ and C=⟨|b|²/e₀²⟩. These integrals exist in three dimensions. At z=1.90a the large diagonal term is C/z. Eliminating s₋ gives a small Green eigenvalue −z L+o(z), where L=A+D²/C. Its local singlet is s₊+(z D/C)s₋ to first order. The small s₋ amplitude is divided by z in the mixed-sector wavefunction, leaving finite probability there.

The predicted limiting mixed-sector occupation is D²/(CL)=0.686408. The coincidence probability divided by a² tends to 1.90² L=0.430292. These are independently integrated constants of the zero-mass regulator. The fine replay uses 32 Gauss–Legendre nodes on each half-axis after a change of variables that resolves the shrinking physical momentum region. The calculation does not identify a universal numerical limit of the directional curvatures; the table gives the actual finite-cutoff results.

This particular tuning of a point contact supplies one bound energy and leaves short-distance structure uncontrolled. Other regulator trajectories, finite-size interactions or a dynamical mediator impose different physics. Reproduce the cutoff sweep

Which density ripples can grow under their own gravity?

Sections in this chapter

At the same density and gravitational coupling, a ripple with axial wavenumber 0.076 oscillates in the original pair gas. After the nearest-neighbor collision repair it grows, with an e-folding time of about 1,398 walk time units. Both calculations allow the ripple itself to make the gravitational potential. The two species also support a second, oscillating mode in which their density fluctuations oppose each other.

Ingredients of the test

Consider dilute, homogeneous condensates of two distinguishable bosonic pair species, one with the density contact and one with the mass contact. Each condensed pair occupies its separately conserved, isolated bound band at zero momentum. The pair densities are nᵢ per cubic cell. We assume negligible direct interactions between dimers, zero temperature, and the same weak scalar coupling to the endpoint energy of both bands. Use walk units with cell length, the constituent limiting speed and ℏ set to one. Impose the continuum Newtonian field equation Δφ=4πG δρ on the perturbations. The mean density is compensated, as in a periodic Jeans analysis. This is a supplied instantaneous attraction. It omits relativistic metric dynamics, collisions, expansion and depletion. In the one-component parabolic, point-source limit the competition between the free wave energy and Newtonian attraction reproduces quantum Jeans dispersion. Hu, Barkana and Gruzinov, 2000 · Earlier isolated-pair gravitational release

For each wavevector q we compute three microscopic inputs. The gap εᵢ=Eᵢ(q)−z comes from the full interacting pair pole, with common z=1.900. The energy matrix element fᵢ connects that pair at rest to the moving bound state. It includes both constituents' endpoint energies, the onsite contact, and half the added pair bond at each of its endpoints. The separate number matrix element νᵢ is the mean of the two constituent number insertions. It converts the predicted band modulation to a readout of actual constituent counts. The same sideband phase is used for both insertions. At q=0 the checks give fᵢ=z and νᵢ=1. At q_z=0.076 the corrected f values are 1.89838799 and 1.89838698, and the two ν values are about 0.997787. These finite-size effects enter every row below.

Two frequencies and a density threshold

For a standing ripple choose the real linear sideband amplitude of species i to be √(εᵢ/nᵢ) yᵢ. A common factor cancels from relative contrasts. Solving Poisson for the instantaneous source and substituting in the two amplitude equations gives

ÿᵢ = −Σⱼ Dᵢⱼ yⱼ
Dᵢⱼ = εᵢ² δᵢⱼ − (8πG/|q|²) vᵢvⱼ
vᵢ = √(nᵢεᵢ) fᵢ
ncrit/n = |q|² / [8πG Σᵢ nᵢ fᵢ² / εᵢ].

The displayed phases make fᵢ real. At a fixed mixture, one eigenvalue of D becomes negative when ncrit/n falls below one. Its square root in magnitude is the growth rate Γ. The positive rank-one subtraction can destabilize only one mode. The upper eigenmode has opposite-sign species amplitudes. An exactly compensated mode arises for equal gaps. With distinct gaps, the upper mode can retain a small gravitational source.

Set the total density to 0.01 and 4πG=0.00014929289984. This sets the Jeans wavenumber of ideal parabolic point pairs, with E=z+q²/(2z), to 0.080. The same coupling is used for all microscopic predictions. The density fraction listed is the fraction of dimers with density contact. Frequencies are inverse walk time. The composition bias is 2(δ_D−δ_M)/(δ_D+δ_M) in the lower mode, where δᵢ is the fractional constituent count modulation proportional to νᵢ√(εᵢ/nᵢ)yᵢ.

Direction, wavenumber, density fractionPair HamiltonianLower modeUpper frequencyCritical / actual densityComposition bias
z, 0.050, 50%OriginalGrows at 0.0017680.0009230.2141+3.0308%
z, 0.050, 50%RepairedGrows at 0.0015510.0006590.1531+0.00031%
z, 0.076, 50%OriginalOscillates at 0.0007600.0021391.1454−6.9080%
z, 0.076, 50%RepairedGrows at 0.0007150.0015280.8204−0.00148%
Body diagonal, 0.065, 25%OriginalGrows at 0.0012150.0016720.6502−0.5454%
Body diagonal, 0.065, 25%RepairedGrows at 0.0012650.0011280.4426+0.00041%

The oblique mixture and both mass-contact bands were held out of the transport calibration. The threshold switch also survives two changes to this calculation. Taking the point-source approximation f=z gives the respective critical ratios 1.1438 and 0.8190. Replacing the continuum Poisson denominator by 4Σ sin²(qⱼ/2) gives 1.1449 and 0.8200 while retaining the full form factors.

As q→0 in a fixed direction, εᵢ≈Rᵢq²/(2z), fᵢ→z and νᵢ→1. Then Γ²→4πG z Σ nᵢRᵢ. The ratio of the two growing fractional count modulations tends to R_D/R_M. In the original z direction this gives a 5.25% bias. The finite wavenumber 0.025 gives 5.1224%. The repaired limit is zero and its 0.025 bias is below 0.0001%. Finite-wave kinetic pressure and the energy and number form factors can all affect composition away from this limit.

Evolving the field with the matter

A separate time-domain check retains each condensate's uniform state Aᵢ and its symmetric combination Bᵢ of the ±q sidebands. It evolves their complex amplitudes with the potential recomputed from all species at every time step. The energy density relative to the condensate is Σ nᵢεᵢ|Bᵢ|²−(4πG/q²)|ρ_q|², with ρ_q=√2 Σ nᵢ fᵢ Re(Aᵢ*Bᵢ). This finite-mode truncation retains exact normalization and the source's nonlinear dependence on the amplitudes. Higher harmonics enter the full model beyond linear order.

Initially only the density-contact species has a small real B=0.00003. This excites both modes. For the repaired equal mixture at q_z=0.05, after 1,418.25 time units the two fractional count Fourier coefficients are 0.00010939 and 0.00008423. They agree with the growing-plus-oscillating linear solution to relative error below 0.00000001. The maximum final norm error is 10⁻¹⁵, and the energy difference divided by the initial kinetic perturbation energy is below 2×10⁻¹².

The calculation projects collective motion onto one band per species. For the wavevectors tested, all free same-sign continua lie outside (1.87,1.93). A bound on the derivative of the one-body energy also excludes the mixed-sign continuum there. On the quadrature meshes the decreasing eigenvalues of G(E,q)−V(q)⁻¹ cross zero just once throughout that interval for each interaction. This puts the other exchange-allowed excitations at least 0.027 from these poles, above the displayed collective frequencies. Static polarization of the omitted states and short-range dimer interactions would require a larger many-body model. These are predictions for the assumed gas and coupling.

Run python collective_gravity.py --size 32 with NumPy. Use --size 64 --extra to reproduce the table and the longer-wavelength comparison. Changing 48³ to 64³ changes the displayed growth and oscillation rates by less than 10⁻⁸ in walk units.

Can an evolving cloud change the signal from its own boundary?

Sections in this chapter

Two spherical dust clouds start at rest with the same outer radius and the same total gravitational mass. Their outermost shells follow identical trajectories and they have the same Schwarzschild vacuum exterior. Yet a central observer receives different signals from these shells. At the same reading of the central clock, redistributing matter inside the cloud changes the observed pulse period by 1.24% and the angular-diameter distance by 0.17%. The signals passed through different evolving interiors.

This is a numerical experiment in nonlinear Einstein gravity. The matter has no pressure, the clocks travel with it, and photons follow the calculated geometry. No external force holds the source in place. The code also evolves a passive tracer on a fixed comparison spacetime so the effect of sourcing the geometry can be isolated.

Two clouds with matched initial motion

Use units G = c = 1 and set the initial outer areal radius to one. A shell label r is fixed by its initial circumference 2πr. Dust proper time t is zero on the initial slice, all areal velocities vanish, and the total mass is 0.05. Prescribe the enclosed gravitational mass by

M(r) = 0.05 r³ [1 + A r²(1−r²)²],      0 ≤ r ≤ 1 .

A = 0 gives the homogeneous control. A = 3 redistributes mass inside the same boundary. Both have a regular center, positive initial density, and M(1) = 0.05. They match to vacuum at r = 1 with zero pressure. A jump in dust density at the surface is allowed. The boundary energy and trajectory agree at every proper time before the single-stream solution fails. The interior spatial rods on the initial slice already depend on the density through the constraint.

Write R(t,r) for areal radius, J = ∂ᵣR, and Γ² = 1 + 2E(r). The spherical Einstein–dust equations in comoving proper time give

ds² = −dt² + (J/Γ)² dr² + R² dΩ²
M′ = 4πρ R²J,        Ṁ = 0
Ṙ² = 2M/R + 2E,       R̈ = −M/R²
E(r) = −M(r)/r        from the initial rest condition.

The enclosed mass can equivalently be measured from the geometry as R[1 − gᵃᵇ(∂ₐR)(∂ᵦR)]/2. This is the Misner–Sharp mass. The integral of proper rest mass includes the different measure 4πR²J dr/Γ. It is conserved too. Spherical symmetry removes propagating tensor waves, while density, geodesic motion and the gravitating geometry still evolve together. Bondi’s dust equations · Misner and Sharp’s spherical mass and dynamics

Evolve the source instead of prescribing a density history

The numerical evolution updates R, Ṙ, J, J̇ and the local proper density. Define D = 4πρ. At every Runge–Kutta evaluation the code integrates the current DR²J outward from the center to obtain M. This mass acts back through the radial acceleration and the relative acceleration of neighboring shells. The density changes with their local expansion.

R̈ = −M/R²,        J̈ = (2M/R³ − D)J
Ḋ = −D(2Ṙ/R + J̇/J).

The independent exact solution uses τ(r) = √[r³/(8M)] with its finite central limit. Solve t = τ(η + sin η) on 0 ≤ η < π. Then R = r(1 + cos η)/2. Differentiating at fixed t supplies J for the reference solution. The live numerical evolution does not use this solution or assume that each enclosed M remains constant.

At central time 2.8 the following absolute errors compare the evolved matter and geometry with the independent solution. The two ray columns compare light traced through the interpolated numerical history with light traced through the exact geometry.

Radial cells and time stepsLargest R errorLargest 4πρ errorLargest density-integral vs geometric mass discrepancyOuter period-ratio errorOuter angular-distance error
328.94 × 10⁻⁵1.09 × 10⁻⁵1.22 × 10⁻⁸3.76 × 10⁻⁴3.27 × 10⁻⁴
641.13 × 10⁻⁵6.86 × 10⁻⁷8.13 × 10⁻¹⁰7.60 × 10⁻⁵7.58 × 10⁻⁵
1281.42 × 10⁻⁶4.30 × 10⁻⁸5.24 × 10⁻¹¹1.65 × 10⁻⁵1.82 × 10⁻⁵

At the finest resolution the proper rest mass of the redistributed cloud is 0.05169560, with an absolute drift of 3.1 × 10⁻¹¹. Its exterior gravitational mass is 0.05. The calculation matches the two clouds by this exterior mass, their initial areal radii, and their initial areal velocities. A comparison requiring equal proper rest masses would use different input profiles.

Two ways of checking the central observer’s measurements

Trace a radial past light ray from the central clock at t = 2.8 to a specified comoving emitter. Let w = 1 + z be the ratio of received pulse period to emitted pulse period. With central w = 1, the equations are dt/dr = −J/Γ and d ln w/dr = J̇/Γ. The central angular-diameter distance Dₐ equals the emitting shell’s areal radius at emission. Operationally it is the ratio of a calibrated small transverse length at the source to its angle on the sky. Identical dust clock rates in their local rest frames are sufficient for the pulse comparison. Mustapha et al. on area distance and redshift in dust spacetimes

CloudEmitter’s initial areal radiusEmission proper timeReceived / emitted periodAngular-diameter distance
Homogeneous0.552.3450220.9221830.470519
Redistributed0.552.3909770.8829000.427435
Homogeneous1.001.9361280.8735310.903137
Redistributed1.001.9511200.8626720.901577

All four period ratios describe blueshifts. At the inner marker the active redistribution changes the period by 4.26% and the angular distance by 9.16%. At the boundary the two emitters are on the same areal trajectory. The central observer’s equal reception times select different emission events.

Two independent calculations check these interpretations. First, trace neighboring light pulses to the same emitter and take the ratio of the observer’s and emitter’s proper-time separations. It agrees with direct frequency transport within 8.0 × 10⁻¹¹. Second, integrate angular focusing along the exact ray. With affine parameter λ increasing into the past and unit frequency at the observer, the radial central pencil has zero optical shear and obeys d²Dₐ/dλ² = −4πρ w²Dₐ, starting with Dₐ = 0 and dDₐ/dλ = 1. Its endpoint agrees with the independent emitting-sphere radius within 6.5 × 10⁻¹¹.

A passive density redistribution can ride the homogeneous dust worldlines. Assign the tracer the same initial proper-density profile as the redistributed cloud and dilute it with the unchanged comoving volume. Its clocks and rays then give the homogeneous rows. Using this tracer as an active Ricci source only in the focusing equation gives Dₐ = 0.896218 at the boundary, whereas the fixed geometry gives 0.903137. Their disagreement of 0.77% detects the inconsistent mixture. Changing the density as a gravitational source requires changing the geometry and the motion together.

Where the dust description fails

A shell crossing occurs when J vanishes at positive R while M′ is nonzero. The proper density then diverges. At fixed time,

J = (1 + cos η)/2 + [rτ′/(2τ)] tan(η/2)(η + sin η).

For τ′ < 0, the positive first term decreases and the magnitude of the negative second term increases until focusing. Each such shell has one crossing root. Here τ′ < 0 only for 0 < r < 1/√3. Scanning this interval at two resolutions and refining the minimum gives a first crossing at r ≈ 0.44936 and t ≈ 3.889214. The areal radius is still 0.13589 and 2M/R is approximately 0.09253, well below the trapping threshold. The earliest formal shell-focusing time is 4.133039. Hellaby and Lake on shell crossing

At the first-crossing label, 0.05 proper-time units before the crossing J is 0.04959 and 4πρ is 42.08. Ten times closer, J is 0.00521 and 4πρ is 467.40. The reported light rays lie on the regular part of the solution. A continuation through crossing needs matter physics beyond single-stream dust.

Run python live_collapse.py with the Python standard library. The cloud profiles and units are chosen for this comparison. Dust, Einstein coupling, and photon propagation are specified physical laws here. A derivation from the interacting walk would have to supply those laws and identify the physical clock and source.

Calculations and native transcript

The standalone archive contains eleven calculations, the inherited pair kernels, both instruments and 21 exact native Tally checks. Run python replay.py TALLY.zip with the pinned runtime. Add --full with NumPy installed to repeat the microscopic tests. The rubidium chapter gives the primary-source archive and checksum for recovering all 1,481 shots from the authors’ vector figure.

Native Tally transcript
✓ virtual odd channels split the two equal-rest kinetic coefficients  (by cross-pairing plus and minus sides; derived)
✓ an even hopping fit recovers the first target coefficient  (by cross-pairing plus and minus sides; derived)
✓ transferring only the even hopping misses the second target  (by cross-pairing plus and minus sides; derived)
✓ the same odd and even hopping restores both target coefficients  (by cross-pairing plus and minus sides; derived)
✓ a residual cubic odd coupling gives sixth-order splitting  (by cross-pairing plus and minus sides; derived)
✓ the scalar midpoint energy gives the correct opposite-transfer clock loop  (by cross-pairing plus and minus sides; derived)
✓ the signed linear Dirac product gives the exact mixed-mode shift coefficient  (by cross-pairing plus and minus sides; derived)
✓ the spin commutator terms cancel between the two transfer orders  (by cross-pairing plus and minus sides; derived)
✓ independent Fourier harmonics of the z-velocity carry total mean-square weight seven eighths  (by cross-pairing plus and minus sides; derived)
✓ the three torus weights follow by independent sine and cosine averages  (by cross-pairing plus and minus sides; derived)
✓ two real contact coefficients give their exact squared norm  (by cross-pairing plus and minus sides; derived)
✓ opposite signed sector intensities recover the diagonal spectral weights  (by cross-pairing plus and minus sides; derived)
✓ a single symmetric contact matrix sends the prescribed local state to its inverse-kernel source  (by cross-pairing plus and minus sides; derived)
✓ eliminating the mixed band adds a positive contribution to the cutoff residue  (by cross-pairing plus and minus sides; derived)
✓ the limiting normalized mixed-band weight follows from the same residue  (by cross-pairing plus and minus sides; derived)
✓ only the in-phase density mode softens for two identical components  (by cross-pairing plus and minus sides; derived)
✓ crossing the Jeans threshold leaves a positive relative-density mode  (by cross-pairing plus and minus sides; derived)
✓ a bounded polynomial window vanishes at the zone edge and starts quadratically in its argument  (by cross-pairing plus and minus sides; derived)
✓ the zero-curvature dust energy equation recovers the enclosed gravitational mass  (by cross-pairing plus and minus sides; derived)
✓ the six direction and recoil groups contain all 1481 rubidium shots  (by cross-pairing plus and minus sides; derived)
✓ the held-out recoil order is at the midpoint of the two training orders  (by cross-pairing plus and minus sides; derived)
Native Tally source
# Exact rational controls for mobile contacts, shared bands and self-gravitating matter.
ratchet 32 step
import "atom"
let zero=whole(0 trial)
let one=whole(1 trial)
let two=whole(2 trial)
let three=whole(3 trial)
let four=whole(4 trial)
let half=fraction(1 trial,2 trial)
let fourth=fraction(1 trial,4 trial)
let densitygap=two
let massgap=flip(one)
let stiffness=fraction(3 trial,8 trial)
let mix=half
fn curvature_term(even,odd,gap)
  return even+share(odd*odd,gap)
end
let cd=curvature_term(stiffness,mix,densitygap)
let cm=curvature_term(stiffness,mix,massgap)
check cd==half and cm==fraction(1 trial,8 trial) "virtual odd channels split the two equal-rest kinetic coefficients"
let trained=fourth+flip(cd)
check cd+trained==fourth "an even hopping fit recovers the first target coefficient"
check cm+trained==flip(fraction(1 trial,8 trial)) "transferring only the even hopping misses the second target"
let common=stiffness+flip(fraction(1 trial,8 trial))
check curvature_term(common,mix+flip(half),densitygap)==fourth and curvature_term(common,mix+flip(half),massgap)==fourth "the same odd and even hopping restores both target coefficients"
let k=fraction(1 trial,8 trial)
let q=fraction(1 trial,4 trial)
fn cube(x)
  return x*x*x
end
fn split(x)
  let a=cube(x)
  return share(a*a,densitygap)+flip(share(a*a,massgap))
end
check split(two*k)==whole(64 trial)*split(k) "a residual cubic odd coupling gives sixth-order splitting"
fn midpoint_square(x,p)
  return four+(x+share(p,two))*(x+share(p,two))
end
check share(midpoint_square(k,q)+flip(midpoint_square(k,flip(q))),two)==k*q "the scalar midpoint energy gives the correct opposite-transfer clock loop"
let p=half
let r=fraction(1 trial,8 trial)
let left=(k+p+share(r,two))*(k+share(p,two))
let right=(k+r+share(p,two))*(k+share(r,two))
check left+flip(right)==(p+flip(r))*(k+share(p+r,two)) "the signed linear Dirac product gives the exact mixed-mode shift coefficient"
check (k+p+share(r,two))+flip(k+share(p,two))==(k+r+share(p,two))+flip(k+share(r,two)) "the spin commutator terms cancel between the two transfer orders"
let wxx=fraction(1 trial,8 trial)
let wyy=fraction(1 trial,4 trial)
let wzz=half
check wxx+wyy+wzz==fraction(7 trial,8 trial) "independent Fourier harmonics of the z-velocity carry total mean-square weight seven eighths"
check wxx==half*half*half and wyy==half*half and wzz==half "the three torus weights follow by independent sine and cosine averages"
let u=half
let v=fraction(3 trial,4 trial)
let gram=u*u+v*v
check gram==fraction(13 trial,16 trial) "two real contact coefficients give their exact squared norm"
let pos=half*(u+v)*(u+v)
let neg=half*(u+flip(v))*(u+flip(v))
check pos+neg==gram "opposite signed sector intensities recover the diagonal spectral weights"
let ua=fraction(3 trial,5 trial)
let ub=fraction(4 trial,5 trial)
let ya=half
let yb=flip(fourth)
let uy=ua*ya+ub*yb
let m11=two*ua*ya+flip(uy*ua*ua)
let m12=ua*yb+ub*ya+flip(uy*ua*ub)
let m22=two*ub*yb+flip(uy*ub*ub)
check m11*ua+m12*ub==ya and m12*ua+m22*ub==yb "a single symmetric contact matrix sends the prescribed local state to its inverse-kernel source"
let D=fraction(1 trial,3 trial)
let C=fraction(2 trial,3 trial)
let A=fraction(1 trial,8 trial)
let L=A+share(D*D,C)
check L==fraction(7 trial,24 trial) "eliminating the mixed band adds a positive contribution to the cutoff residue"
check share(D*D,C*L)==fraction(4 trial,7 trial) "the limiting normalized mixed-band weight follows from the same residue"
let grav=fraction(3 trial,4 trial)
let kinetic=one
let occ=half
let diag=kinetic+flip(grav*occ)
let off=flip(grav*occ)
check diag+off==fraction(1 trial,4 trial) and diag+flip(off)==one "only the in-phase density mode softens for two identical components"
let strong=fraction(5 trial,4 trial)
let d2=kinetic+flip(strong*occ)
let f2=flip(strong*occ)
check d2+f2==flip(fourth) and d2+flip(f2)==one "crossing the Jeans threshold leaves a positive relative-density mode"
fn envelope_value(s)
  return (one+flip(s))*(one+s)
end
check envelope_value(zero)==one and envelope_value(one)==zero and one+flip(envelope_value(fourth))==fraction(1 trial,16 trial) "a bounded polynomial window vanishes at the zone edge and starts quadratically in its argument"
let areal=two
let mass=fraction(1 trial,8 trial)
let speed2=share(two*mass,areal)
check speed2==fraction(1 trial,8 trial) and share(areal*speed2,two)==mass "the zero-curvature dust energy equation recovers the enclosed gravitational mass"
let shots=whole(244 trial)+whole(243 trial)+whole(244 trial)+whole(260 trial)+whole(245 trial)+whole(245 trial)
check shots==whole(1481 trial) "the six direction and recoil groups contain all 1481 rubidium shots"
let scale=whole(4 trial)+whole(12 trial)
check share(scale,two)==whole(8 trial) "the held-out recoil order is at the midpoint of the two training orders"
collision_transport.py
"""Local translation of a coincident pair; build coefficients and solve the actual 3D poles.

Requires NumPy and the released bound_3d.py. A torus is periodic integration
over relative momentum, not a finite apparatus limiting the COM momentum.
"""
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, IDENTITY, BETA_PAIR, TENSORS,
                      mode, extract_curvature, BASIS, X, Y, Z)

CONTACTS = {'density': IDENTITY, 'mass': BETA_PAIR}
P_ODD = (IDENTITY-BETA_PAIR)/2


def hermitian(a):
    return (a + a.conj().T)/2


def design(torus, spacing=.004):
    """Fit the ordered equal-rest pole. J[j], m[j], even[j] describe three axes.

    J is the odd bond matrix; m is the even scalar in the common repair.
    even is the even-only scalar calibrated on density. Matrices use the
    six-component orthonormal coincidence basis exported by bound_3d.py.
    """
    cal = rest_calibration(torus)
    green0, lam, u, green_e = cal
    inv0 = np.linalg.inv(green0)
    weight = lam**2 / (-green_e)
    assert np.min(np.abs(np.linalg.eigvalsh(green0))) > 1e-4
    first, second, base = [], [], []
    for j in range(3):
        data = []
        for h in (spacing, spacing/2):
            gp = torus.green(torus.rest, j, h)
            pp = np.linalg.inv(gp)
            pm = BETA_PAIR @ pp @ BETA_PAIR
            data.append(((pp-pm) @ u/(2*h),
                         np.vdot(u, (pp+pm-2*inv0)@u).real/h**2,
                         extract_curvature(torus.rest, h, gp, cal)))
        v, crv, before = [(4*b-a)/3 for a,b in zip(*data)]
        assert np.linalg.norm(v-P_ODD@v) < 1e-10
        v = P_ODD@v
        J = np.outer(v, u.conj()) + np.outer(u, v.conj())
        assert np.linalg.norm(J@u-v) < 1e-12
        first.append(J)
        second.append((crv+1/(torus.rest*weight))/2)
        base.append(before)
    base = np.array(base)
    even = (1-base[:,0])/(2*torus.rest*weight)
    return dict(cal=cal, J=np.array(first), m=np.array(second), even=even,
                base=base, weight=weight, rest=torus.rest)


def symbol(d, k, variant='common'):
    """Added Hermitian coincidence-space potential at the given 3-vector k."""
    k = np.asarray(k)
    if variant == 'bare':
        return np.zeros_like(IDENTITY)
    if variant not in ('even','common','range2'):
        raise ValueError(variant)
    factors = 4*np.sin(k/2)**2
    if variant == 'even':
        return (factors@d['even'])*IDENTITY
    scalar = factors@d['m']
    if variant == 'range2':
        scalar += factors@d['quartic']@factors
    return scalar*IDENTITY + np.tensordot(np.sin(k), d['J'], axes=1)


def vertex(d, k_final, k_initial, variant='common'):
    """Endpoint energy density of the added bond, SOLELY on coincidence."""
    return (symbol(d,k_final,variant)+symbol(d,k_initial,variant))/2


class Fiber:
    """Precompute free signed energies at fixed total momentum, including oblique k."""
    def __init__(self, torus, k):
        n = torus.size
        k = np.asarray(k, dtype=float)
        self.n = n
        grid = [p*(2*np.pi/n) for p in torus.grid]
        shape = (n,n,n)
        a, self.ua = mode([p+s/2 for p,s in zip(grid,k)], shape)
        b, self.ub = mode([-p+s/2 for p,s in zip(grid,k)], shape)
        self.e = [a+b, a-b, -a+b, -a-b]

    def green(self,z,derivative=False):
        den = [z-e for e in self.e]
        assert min(np.min(np.abs(a)) for a in den) > .01
        pp,pm,mp,mm = [(-.25/a**2 if derivative else .25/a) for a in den]
        moments = np.empty((5,5))
        moments[0,0] = (pp+pm+mp+mm).sum()
        moments[1:,0] = (pp+pm-mp-mm) @ self.ua
        moments[0,1:] = (pp-pm+mp-mm) @ self.ub
        moments[1:,1:] = self.ua.T @ ((pp-pm-mp+mm)[:,None]*self.ub)
        return hermitian(np.tensordot(moments.ravel()/self.n**3,TENSORS,axes=1))


def pole(fiber,d,k,contact,variant='common',extra=0.):
    """Return pole energy, unit coincidence spinor, and normalized coincidence weight."""
    _,lam,u0,_ = d['cal']
    V = contact/lam + symbol(d,k,variant) + extra*IDENTITY
    energy = np.hypot(d['rest'], np.linalg.norm(k))
    for _ in range(9):
        inv = np.linalg.inv(fiber.green(energy))
        vals,vecs = np.linalg.eigh(hermitian(inv-V))
        target = np.argmax(abs(vecs.conj().T@u0)**2)
        u = vecs[:,target]
        assert abs(np.vdot(u0,u)) > .95
        source = inv@u
        slope = -np.vdot(source,fiber.green(energy,derivative=True)@source).real
        assert slope>0
        if abs(vals[target]) < 2e-13:
            return energy,u,1/slope
        energy -= vals[target]/slope
    raise ArithmeticError('bound-state pole did not converge')


def quartic_design(torus,d):
    """Fit six quartic coefficients on density; a symmetric matrix includes cross terms twice."""
    u0=d['cal'][2]
    inv_lam=1/d['cal'][1]
    result=np.zeros((3,3))
    for axes in [(0,),(1,),(2,),(0,1),(0,2),(1,2)]:
        direction=np.sum(np.eye(3)[list(axes)],axis=0)
        data=[]
        for h in (.008,.016,.032):
            k=h*direction
            q=4*np.sin(h/2)**2
            target=np.hypot(d['rest'],np.linalg.norm(k))
            inv=np.linalg.inv(Fiber(torus,k).green(target))
            vals,vecs=np.linalg.eigh(hermitian(inv-inv_lam*IDENTITY-symbol(d,k)))
            j=np.argmax(abs(vecs.conj().T@u0)**2)
            assert abs(np.vdot(u0,vecs[:,j]))>.97
            data.append((q,vals[j]/q))
        (x,a),(y,b),(z,c)=data
        left=(b-a)/(y-x)
        right=(c-b)/(z-y)
        coefficient=left-(right-left)*(x+y)/(z-x)
        i,j=axes[0],axes[-1]
        if i==j:
            result[i,i]=coefficient
        else:
            result[i,j]=result[j,i]=(coefficient-result[i,i]-result[j,j])/2
    return result


def readout(torus,d,khat,k,variant,extra=0.,delta=.00004):
    """Finite-k forward clock flux E dE/dK / K and odd-coincidence probability."""
    ks = np.array([k-delta,k,k+delta])
    energies=[]; odd=[]
    for ki in ks:
        vec = ki*khat
        fiber = Fiber(torus,vec)
        row=[]
        for contact in CONTACTS.values():
            energy,u,w = pole(fiber,d,vec,contact,variant,extra)
            row.append(energy)
            if ki == k:
                odd.append(w*np.linalg.norm(P_ODD@u)**2)
        energies.append(row)
    energies=np.array(energies)
    flux=energies[1]*(energies[2]-energies[0])/(2*delta*k)
    return energies[1], flux, np.array(odd)


def symmetry_check(d):
    k=np.array([.037,-.021,.052])
    end=np.array([.023,.014,-.011])
    M=d['m']
    # Rebuild the nearest-neighbor bond from its actual matrix elements.
    onsite=2*sum(M)*IDENTITY
    def from_bonds(momentum):
        value=onsite.astype(complex)
        for j in range(3):
            plus=-M[j]*IDENTITY+d['J'][j]/(2j)
            t=plus*np.exp(1j*momentum[j])
            value += t+t.conj().T
        return value
    assert np.max(abs((from_bonds(k)+from_bonds(end))/2-vertex(d,k,end)))<2e-14
    for j,sigma in enumerate((X,Y,Z)):
        flip=np.kron(Z,sigma)
        r=BASIS.T@np.kron(flip,flip)@BASIS
        reflected=k.copy()
        reflected[j]*=-1
        assert np.max(abs(r@symbol(d,k)@r.conj().T-symbol(d,reflected)))<2e-11


def run(n, fine=False):
    torus=Torus(n)
    d=design(torus)
    z=d['rest']
    weight=d['weight']
    symmetry_check(d)
    u=d['cal'][2]
    print(f'mesh {n}, z={z}, contact probability {weight:.10f}')
    print('axis Rbare(density,mass) even-density m-common norm(Ju)')
    for j,axis in enumerate('xyz'):
        print(axis, *(f'{x:.9f}' for x in (*d['base'][j],d['even'][j],d['m'][j],
                                             np.linalg.norm(d['J'][j]@u))))
    assert np.allclose(vertex(d,[.1,0,0],[-.1,0,0]),4*np.sin(.05)**2*d['m'][0]*IDENTITY)
    k=.07
    assert np.max(abs(Fiber(torus,[0,0,k]).green(z)-torus.green(z,2,k)))<1e-12
    even_rest=d['base'] + 2*z*weight*d['even'][:,None]
    assert np.allclose(even_rest[:,0],1)
    d['quartic']=quartic_design(torus,d)
    print('range-two c_ii, then cross coefficients c_xy,c_xz,c_yz')
    print(*(f'{x:.7f}' for x in (*d['quartic'].diagonal(), *(2*d['quartic'][i,j]
                                    for i,j in [(0,1),(0,2),(1,2)]))))
    results={}
    for axis,unit,values in [('z',np.array([0.,0.,1.]),(.025,.05,.10)),
                             ('xyz',np.ones(3)/np.sqrt(3),(.04,.08))]:
        for kt in values:
            variants=('bare','even','common','range2') if axis=='z' and kt==.05 else ('common','range2')
            for variant in variants:
                e,f,odd=readout(torus,d,unit,kt,variant)
                results[axis,kt,variant]=(e,f,odd)
                print(f'{axis} k={kt:.3f} {variant}: E={e[0]:.12f},{e[1]:.12f}'
                      f'  E*v/k={f[0]:.9f},{f[1]:.9f}'
                      f'  P(odd contact)={odd[0]:.5e},{odd[1]:.5e}')
    a,b=[results['z',k,'common'] for k in (.025,.05)]
    print('doubling .025 to .05: odd contact factors',b[2]/a[2],
          ' energy-split factor',np.diff(b[0])[0]/np.diff(a[0])[0])
    assert np.all((b[2]/a[2] > 45) & (b[2]/a[2] < 85))
    corrected=results['xyz',.08,'range2'][1]
    assert np.max(abs(corrected-1)) < .008
    assert np.max(abs(corrected-1)) < .2*np.max(abs(results['xyz',.08,'common'][1]-1))
    if fine:
        # Independent three-point difference of direct pole energies for the
        # curvature rather than differentiating the inverse kernel.
        for j in range(3):
            direct=[]
            unit=np.eye(3)[j]
            for k in (.008,.004):
                vec=k*unit
                fiber=Fiber(torus,vec)
                energies=np.array([pole(fiber,d,vec,c)[0] for c in CONTACTS.values()])
                direct.append(2*z*(energies-z)/k**2)
            result=(4*direct[1]-direct[0])/3
            print('direct common R', 'xyz'[j], result)
            assert np.max(abs(result-1))<5e-6
    return d,results


if __name__ == '__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--size',type=int,default=32)
    parser.add_argument('--fine',action='store_true',help='direct curvature checks on all axes')
    args=parser.parse_args()
    run(args.size,args.fine)
fall_measurement.py
"""Replay the three-order rubidium free-fall fit from Figure 3 of Asenbaum et al."""
import argparse
import hashlib
import io
import math
from pathlib import Path
import statistics
import tarfile

SOURCE_URL = "https://arxiv.org/src/2005.11624v2"
SOURCE_SHA = "e61b7ef455e146bc7139f4e5e226977514f6358b14b623e0678498b8301171a6"
FIGURE = "epdatafigunblindedv3.pdf"
FIGURE_SHA = "c37ba618dfb9d6366bfad017f381ffc157e44437e7ef8142d0401e6b7b621ca9"

# order n, initial beam direction (-1 down, +1 up), count,
# sum of phase differences in microradians, sum of squares in microradians squared
MOMENTS = (
    (4, -1, 244, -2702784, 75960537736),
    (4, 1, 243, 828487, 50654447667),
    (8, -1, 244, -2332247, 77695001229),
    (8, 1, 260, 1109761, 69168401729),
    (12, -1, 245, -1067877, 154257480273),
    (12, 1, 245, 1037667, 86715548019),
)
K = 2 * math.pi / 780e-9
T = 0.955
G = 9.81
MODEL = 0.05251


def recovered_moments(archive_path):
    """Audit the six integer rows from the pinned arXiv source, using PyMuPDF 1.26.5."""
    import pymupdf

    source = archive_path.read_bytes()
    if hashlib.sha256(source).hexdigest() != SOURCE_SHA:
        raise ValueError("Unexpected arXiv source checksum")
    with tarfile.open(fileobj=io.BytesIO(source), mode="r:*") as archive:
        members = [m for m in archive if Path(m.name).name == FIGURE and m.isfile()]
        if len(members) != 1:
            raise ValueError("Expected one Figure 3 vector graphic")
        figure = archive.extractfile(members[0]).read()
    if hashlib.sha256(figure).hexdigest() != FIGURE_SHA:
        raise ValueError("Unexpected Figure 3 checksum")

    colors = {(1.0, 0.0, 0.0): 4, (0.0, 0.0, 0.0): 8, (0.0, 0.0, 1.0): 12}
    groups = {(order, direction): [] for order in (4, 8, 12) for direction in (-1, 1)}
    with pymupdf.open(stream=figure, filetype="pdf") as document:
        drawings = document[0].get_drawings()
        zero = drawings[1575]["rect"].y0
        points_per_rad = (drawings[1578]["rect"].y0 - drawings[1593]["rect"].y0) / 0.1
        for marker in drawings[94:1575]:
            if marker["type"] not in ("f", "s"):
                raise ValueError("Unexpected marker type")
            hollow = marker["type"] == "s"
            order = colors[marker["color"] if hollow else marker["fill"]]
            rightmost = marker["items"][0][1]
            assert abs(rightmost.x - marker["rect"].x1) < 0.002
            micro_rad = round((zero - rightmost.y) / points_per_rad * 1e6)
            groups[order, -1 if hollow else 1].append(micro_rad)
    return tuple((n, d, len(v), sum(v), sum(i*i for i in v))
                 for (n, d), v in sorted(groups.items()))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--from-figure", type=Path, metavar="ARXIV_SOURCE_TAR",
                        help=f"audit the group summaries against the archive at {SOURCE_URL}")
    args = parser.parse_args()
    if args.from_figure:
        assert recovered_moments(args.from_figure) == MOMENTS
        print("All 1,481 vector markers reproduce the six stored moment rows.")

    samples = {}
    for order, direction, count, phase_sum, square_sum in MOMENTS:
        mean = phase_sum / count * 1e-6
        var_mean = (square_sum - phase_sum**2 / count) / ((count-1)*count) * 1e-12
        samples[order, direction] = (mean, var_mean)
    assert sum(row[2] for row in MOMENTS) == 1481
    means, weights = {}, {}
    for order in (4, 8, 12):
        down, up = samples[order, -1], samples[order, 1]
        means[order] = (down[0] + up[0]) / 2
        weights[order] = 4 / (down[1] + up[1])
        print(f"order {order:2}: {means[order]*1000:+.4f} +/- "
              f"{1000/math.sqrt(weights[order]):.4f} mrad")

    total_weight = sum(weights.values())
    xbar = sum(n*w for n, w in weights.items()) / total_weight
    ybar = sum(means[n]*w for n, w in weights.items()) / total_weight
    sxx = sum(w*(n-xbar)**2 for n, w in weights.items())
    slope = sum(w*(n-xbar)*(means[n]-ybar) for n, w in weights.items()) / sxx
    intercept = ybar - slope*xbar
    chi_sq = sum(w*(means[n]-intercept-slope*n)**2 for n, w in weights.items())
    middle_prediction = (means[4] + means[12]) / 2
    prediction_variance = (1/weights[4] + 1/weights[12]) / 4
    holdout = (means[8]-middle_prediction) / math.sqrt(1/weights[8]+prediction_variance)

    scale = 1e12 / (K*G*T**2)
    raw, stat = slope*scale, scale/math.sqrt(sxx)
    correction = 1.5-5.9
    systematic = 3.4
    corrected = raw + correction
    joint_sigma = math.hypot(stat, systematic)
    radius = statistics.NormalDist().inv_cdf(0.975)*joint_sigma
    lo, hi = ((corrected+x)*1e-12/MODEL for x in (-radius, radius))

    print(f"free intercept {intercept*1000:+.4f} mrad; chi^2(1)={chi_sq:.4f}")
    print(f"endpoint prediction for order 8: {middle_prediction*1000:+.4f} +/- "
          f"{1000*math.sqrt(prediction_variance):.4f} mrad; discrepancy {holdout:+.3f} sigma")
    print(f"eta before correction: ({raw:.4f} +/- {stat:.4f} stat) e-12")
    print(f"eta after correction: ({corrected:.4f} +/- {stat:.4f} stat "
          f"+/- {systematic:.1f} syst) e-12")
    print(f"conditional 95% fD interval: [{lo:.4e}, {hi:.4e}]")
    print(f"ideal four-recoil phase-alias spacing: {2*math.pi/(4*K*G*T**2):.4e}")
    print(f"trajectory illustration for a full model contrast: "
          f"{0.5*MODEL*G*(2*T)**2:.3f} m")
    assert abs(raw-6.1174) < 0.001 and abs(stat-1.9520) < 0.001
    assert abs(chi_sq - holdout**2) < 1e-10
    assert 1.70 < corrected < 1.73 and -1.15e-10 < lo < -1.12e-10 < hi < 1.81e-10


if __name__ == "__main__":
    main()
binding_transfer.py
"""Can the same collision hopping coefficients predict inertia at a new binding energy?"""
from pathlib import Path
import argparse
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, IDENTITY, BETA_PAIR
from collision_transport import hermitian, Fiber


EVEN=[0,5]
ODD=np.flatnonzero(np.diag(BETA_PAIR)<0)


class RestPole:
    def __init__(self,n,energy):
        self.torus=Torus(n,energy)
        self.energy=energy
        green,lam,u,de=rest_calibration(self.torus)
        self.inv=np.linalg.inv(green)
        self.g=1/lam
        self.weight=-lam**2/de
        self.u=u if u[0].real>=0 else -u
        self.first=[]
        self.second=[]
        for axis in range(3):
            values=[]
            for h in (.004,.002):
                plus=np.linalg.inv(self.torus.green(energy,axis,h))
                minus=BETA_PAIR@plus@BETA_PAIR
                values.append(((plus-minus)@self.u/(2*h),
                               np.vdot(self.u,(plus+minus-2*self.inv)@self.u).real/h**2))
            self.first.append((4*values[1][0]-values[0][0])/3)
            self.second.append((4*values[1][1]-values[0][1])/3)
        self.first=np.array(self.first)
        self.second=np.array(self.second)

    def curvature(self,J,M,axis,contact):
        # The energy-dependent inverse kernel is a six-dimensional Schur complement.
        P=hermitian(self.inv-self.g*contact)
        field=self.first[axis]-J[axis]@self.u
        assert np.linalg.norm(field[[0,5]])<2e-8
        mixing=2*np.vdot(field[ODD],np.linalg.solve(P[np.ix_(ODD,ODD)],field[ODD])).real
        bare=self.second[axis]-2*np.vdot(self.u,M[axis]@self.u).real
        return -self.energy*self.weight*(bare-mixing)

    def moving(self,J,M,axis,k,contact):
        momentum=k*np.eye(3)[axis]
        V=self.g*contact+np.sin(k)*J[axis]+4*np.sin(k/2)**2*M[axis]
        fiber=Fiber(self.torus,momentum)
        energy=np.hypot(self.energy,k)
        for _ in range(8):
            inv=np.linalg.inv(fiber.green(energy))
            vals,v=np.linalg.eigh(hermitian(inv-V))
            j=np.argmax(abs(v.conj().T@self.u))
            if abs(vals[j])<4e-13:return energy
            x=inv@v[:,j]
            derivative=-np.vdot(x,fiber.green(energy,derivative=True)@x).real
            energy-=vals[j]/derivative
        raise ArithmeticError('moving pole failed to converge')


def coefficients(rows,cutoff=1e-12):
    # A two-column even sector gives the general odd/even Hermitian hopping for
    # these first derivatives. Only the even 2-by-2 block of M enters the curvature.
    vectors=np.stack([r.u[EVEN] for r in rows]).real
    quadratic=np.array([[a*a,2*a*b,b*b] for a,b in vectors])
    J=np.zeros((3,6,6),complex)
    M=np.zeros_like(J)
    for axis in range(3):
        targets=np.stack([r.first[axis][ODD] for r in rows])
        oddmap=np.linalg.lstsq(vectors,targets,rcond=cutoff)[0].T
        J[axis][np.ix_(ODD,EVEN)]=oddmap
        J[axis]+=J[axis].conj().T.copy()
        inputs=[(r.second[axis]+1/(r.energy*r.weight))/2 for r in rows]
        m11,m12,m22=np.linalg.lstsq(quadratic,inputs,rcond=cutoff)[0]
        M[axis][np.ix_(EVEN,EVEN)]=[[m11,m12],[m12,m22]]
    return J,M


def single(row):
    J=[]
    M=[]
    for axis,f in enumerate(row.first):
        J.append(np.outer(f,row.u.conj())+np.outer(row.u,f.conj()))
        m=(row.second[axis]+1/(row.energy*row.weight))/2
        M.append(m*IDENTITY)
    return np.array(J),np.array(M)


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--fine',action='store_true')
    n=48 if parser.parse_args().fine else 32
    train=(1.68,1.81,1.90)
    held=(1.61,1.75,1.86,1.94)
    data={e:RestPole(n,e) for e in (*train,*held)}
    basic=single(data[1.90])
    learned=coefficients([data[e] for e in train])
    bounded=coefficients([data[e] for e in train],cutoff=1e-3)
    print('training rest energies',train,'mesh',n)
    print('truncated-fit operator norms J,M:',*[max(np.linalg.norm(m,2) for m in cols) for cols in bounded])
    print('largest multi-energy operator norms J,M:',*[max(np.linalg.norm(m,2) for m in cols) for cols in learned])
    # Restrict the full Hamiltonian at K=(0,pi,0) to two normalized onsite
    # even-orbital trial states. This gives bounds independently of any pole fit.
    for name,pair in [('three-energy',learned),('truncated',bounded)]:
        M=pair[1][1][np.ix_(EVEN,EVEN)]
        block=np.diag([20.,-20.])+data[1.90].g*np.eye(2)+4*M
        limits=np.linalg.eigvalsh(block)
        print(f'{name} variational trial energies at y zone face: {limits}',flush=True)
        assert limits[0]<(-4900 if name=='three-energy' else -180)
        if name=='truncated':assert limits[1]>180
    for e in (*train,*held):
        row=data[e]
        results=[]
        for J,M in (basic,learned,bounded):
            values=np.array([[row.curvature(J,M,j,c) for c in (IDENTITY,BETA_PAIR)] for j in range(3)])
            results.append(values)
        print(f'E_rest={e:.3f}: one-calibration z {results[0][2]}, three-calibration z {results[1][2]}, '
              f'max three-axis target error {np.max(abs(results[1]-1)):.7f}; truncated {np.max(abs(results[2]-1)):.7f}',flush=True)
        if e in (1.75,1.94):
            J,M=learned
            for contact,expected in zip((IDENTITY,BETA_PAIR),results[1][2]):
                ratios=[]
                for k in (.006,.003):
                    energy=row.moving(J,M,2,k,contact)
                    ratios.append(2*e*(energy-e)/k**2)
                direct=(4*ratios[1]-ratios[0])/3
                assert abs(direct-expected)<1e-5,(direct,expected)
    assert np.max(abs(np.array([data[1.90].curvature(*basic,j,IDENTITY) for j in range(3)])-1))<2e-8


if __name__=='__main__':
    main()
rest_clock.py
"""Unprojected rest clock loop for a hopping bound pair. All relative momenta are retained."""
from pathlib import Path
import argparse
import sys
import numpy as np

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


def inner(f,g):
    return np.vdot(f,g)/len(f)


def norm2(f):
    return inner(f,f).real


def embed(x):
    return (BASIS@x).reshape(4,4)


def local(f):
    return BASIS.conj().T@f.mean(axis=0).reshape(16)


def free(ha,hb,f):
    return ha@f+f@hb.swapaxes(-1,-2)


def derivative(p,axis):
    x,y,z=p
    sx,sy,sz=np.sin(x),np.sin(y),np.sin(z)
    cx,cy,cz=np.cos(x),np.cos(y),np.cos(z)
    zero=np.zeros_like(x+y+z)
    db=((cx*cy*cz,zero,zero),(-sx*sy*cz,cy*cz,zero),
        (-sx*cy*sz,-sy*sz,cz))[axis]
    ts=[1-cx,1-cy,1-cz]
    dm=np.sin(p[axis])*(4*ts[axis]/3+2*sum(v for j,v in enumerate(ts) if j!=axis))
    c=np.stack(np.broadcast_arrays(*db,dm),axis=-1).reshape(-1,4)
    return (c@np.array(GAMMA[1:]).reshape(4,16)).reshape(-1,4,4)


class RestClock:
    def __init__(self,n,d,axis=2):
        self.n,self.d,self.axis=n,d,axis
        torus=Torus(n)
        _,self.lam,u,ge=rest_calibration(torus)
        self.energy=torus.rest
        self.v=self.lam*u/np.sqrt(-ge)
        self.source=embed(u/np.sqrt(-ge))
        self.p=tuple(k*(2*np.pi/n) for k in torus.grid)
        self.ha,e=block(self.p)
        self.hb,f=block([-k for k in self.p])
        self.psi=wave(self.source,self.energy,self.ha,e,self.hb,f)
        np.testing.assert_allclose(local(self.psi),self.v,atol=2e-12)
        assert abs(norm2(self.psi)-1)<2e-11
        self.da=derivative(self.p,axis)/2
        self.db=derivative([-v for v in self.p],axis)/2

    def h(self,contact,f):
        return free(self.ha,self.hb,f)+embed(contact@local(f)/self.lam)

    def leak(self,contact,repaired=True):
        # The free-free commutator is identically zero at rest.
        direct=free(self.da,self.db,self.source)
        hit=embed(contact@local(free(self.da,self.db,self.psi))/self.lam)
        if not repaired:
            return direct+hit
        j=self.d['J'][self.axis]@self.v/2
        return direct+hit+free(self.ha,self.hb,embed(j))+embed(contact@j/self.lam+self.energy*j)

    def finite(self,q,contact,repaired=True,W=None):
        # Split the full product into hopping-contact, contact-hopping, and contact-contact.
        # Integrating each first-leg hopping over its receiving momentum gives the same
        # anticommutator that acts on a constant spinor on the return leg.
        sums=[]
        for sign in (1,-1):
            step=sign*q
            vec=np.eye(3)[self.axis]*step
            ha,_=block([k+s for k,s in zip(self.p,vec)])
            hb,_=block([-k+s for k,s in zip(self.p,vec)])
            a,b=(self.ha+ha)/2,(self.hb+hb)/2
            V=contact/self.lam
            if repaired:V=V+vertex(self.d,vec,np.zeros(3))
            if W is not None:V=V+1j*np.sin(step)*W
            kick=V@self.v
            local_first=local(free(a,b,self.psi))+kick
            sums.append(free(a,b,embed(kick))+embed(V.conj().T@local_first))
        return (sums[0]-sums[1])/(2*q)

    def floor(self):
        # The functions d(b_j)/dk_i have zero mean, are orthogonal, and their
        # squared torus norms are rational numbers (one per independent sine/cosine).
        weights=((1/8,0,0),(1/8,1/4,0),(1/8,1/4,1/2))[self.axis]
        moments=[]
        for alpha in GAMMA[1:4]:
            f=(alpha@self.source+self.source@alpha.T)/2
            moments.append(np.vdot(f,f).real)
        return np.dot(weights,moments)

    def odd_fluctuation(self,f):
        beta=GAMMA[-1]
        odd=(f-beta@f@beta.T)/2
        return odd-odd.mean(axis=0)


def fit_polarization(clock):
    # W v spans the four odd contact spinors. H−E maps them to the leading
    # change in the microscopic clock loop while leaving the flat energy fixed.
    odd=np.eye(6,dtype=complex)[:,np.diag(BETA_PAIR)<0]
    gram=np.zeros((4,4),complex)
    rhs=np.zeros(4,complex)
    for c in (IDENTITY,BETA_PAIR):
        columns=[]
        for j in odd.T:
            field=embed(j)
            columns.append(1j*(free(clock.ha,clock.hb,field)+embed(c@j/clock.lam-clock.energy*j)))
        b=clock.leak(c)
        gram+=np.array([[inner(u,v) for v in columns] for u in columns])
        rhs+=np.array([inner(u,b) for u in columns])
    w=-odd@np.linalg.solve(gram,rhs)
    W=(np.outer(w,clock.v.conj())+np.outer(clock.v,w.conj()))/np.vdot(clock.v,clock.v)
    np.testing.assert_allclose(W@clock.v,w,atol=1e-12)
    np.testing.assert_allclose(BETA_PAIR@W@BETA_PAIR,-W,atol=1e-12)
    return W


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--fine',action='store_true')
    args=parser.parse_args()
    train_size=24
    fit=design(Torus(train_size))
    train=RestClock(train_size,fit)
    W=fit_polarization(train)
    n=48 if args.fine else 32
    clock=RestClock(n,fit)
    for label,c in [('density',IDENTITY),('mass',BETA_PAIR)]:
        initial=clock.leak(c,False)
        repaired=clock.leak(c)
        w=W@clock.v
        added=1j*(free(clock.ha,clock.hb,embed(w))+embed(c@w/clock.lam-clock.energy*w))
        lowered=repaired+added
        floor=clock.floor()
        for f in (initial,repaired,lowered):
            assert abs(inner(clock.psi,f))<2e-10
            assert abs(norm2(clock.odd_fluctuation(f))-floor)<2e-10
        print(f'{label} mesh {n}: initial={norm2(initial):.9f} repaired={norm2(repaired):.9f} '
              f'common polarization={norm2(lowered):.9f} protected contribution={floor:.9f}',flush=True)
        for do_repair,pol,target in ((False,None,initial),(True,None,repaired),(True,W,lowered)):
            coarse=clock.finite(.10,c,do_repair,pol)
            fine=clock.finite(.05,c,do_repair,pol)
            err=np.sqrt(norm2(fine-target))
            assert err < .27*np.sqrt(norm2(coarse-target))
            assert np.sqrt(norm2((4*fine-coarse)/3-target))<1e-4
        print(f'  endpoint finite-q checks converged; norm of W={np.linalg.norm(W,2):.7f}',flush=True)


if __name__=='__main__':
    main()
extended_clock.py
"""Finite-range two-particle energy polarizations and the unrestricted common-fit floor."""
import argparse
from itertools import product
import numpy as np
from rest_clock import (RestClock, norm2, embed, local, free, design, Torus,
                        GAMMA, BASIS, IDENTITY, BETA_PAIR)

CONTACTS = (IDENTITY,BETA_PAIR)
BETA = GAMMA[-1]
PARITY = np.real(np.diag(BETA)).astype(int)
ODD = np.eye(6)[:,np.diag(BETA_PAIR)<0]
FFT_AXES = (0,1,2)


def inverse_free(clock,f):
    """Inverse of H_free-E over all four energy-sign channels."""
    ha,hb=clock.ha,clock.hb
    ea=np.sqrt(np.einsum('nij,nji->n',ha,ha).real/4)
    eb=np.sqrt(np.einsum('nij,nji->n',hb,hb).real/4)
    identity=np.eye(4)
    out=np.zeros_like(clock.psi)
    for s in (-1,1):
        left=(identity+s*ha/ea[:,None,None])/2
        for t in (-1,1):
            right=(identity+t*hb/eb[:,None,None])/2
            gap=s*ea+t*eb-clock.energy
            out+=(left@f@right.swapaxes(-1,-2))/gap[:,None,None]
    return out


def unrestricted(clock,leaks):
    """Least loss over every common odd cloud, independent of finite cluster fitting."""
    avg=(leaks[0]+leaks[1])/2
    diff=(leaks[0]-leaks[1])/2
    np.testing.assert_allclose(diff,np.broadcast_to(embed(local(diff)),diff.shape),atol=2e-11)
    u=inverse_free(clock,avg)
    np.testing.assert_allclose(free(clock.ha,clock.hb,u)-clock.energy*u,avg,atol=3e-12)
    g=1/clock.lam
    d=ODD.T@(local(diff)-g*local(u))
    rows=np.array([inverse_free(clock,embed(col)).ravel() for col in ODD.T])
    gram=g*g*(rows.conj()@rows.T)/len(u)
    y=np.linalg.solve(np.eye(len(d))+gram,d)
    f=inverse_free(clock,-avg-g*(y@rows).reshape(u.shape))
    residuals=np.array([norm2(l+clock.h(c,f)-clock.energy*f) for l,c in zip(leaks,CONTACTS)])
    floor=np.vdot(d,y).real
    assert abs(np.mean(residuals)-floor)<3e-10
    return np.linalg.norm(d),floor,residuals

def analytic_repair(clock):
    """Jv for the exact rest derivative, independent of finite differences of the pole."""
    dpsi=free(clock.da,clock.db,clock.psi)
    rdpsi=-inverse_free(clock,dpsi)
    columns=[local(-inverse_free(clock,embed(e))) for e in np.eye(6)]
    green=np.column_stack(columns)
    return -np.linalg.solve(green,local(rdpsi))


def exact_cloud(clock):
    h=clock
    du=free(h.da,h.db,h.source)
    j=embed(analytic_repair(h)/2)
    s=du+free(h.ha,h.hb,j)+h.energy*j
    f=-inverse_free(h,s)
    dpsi=free(h.da,h.db,h.psi)
    anti=embed((local(dpsi)+local(np.broadcast_to(j,dpsi.shape)))/h.lam)
    errors=[]
    for sign,contact in zip((1,-1),CONTACTS):
        errors.append(norm2(s+sign*anti+h.h(contact,f)-h.energy*f))
    assert max(errors)<2e-24
    return f,errors


def real_field(f,n):
    return np.fft.ifftn(f.reshape(n,n,n,4,4),axes=FFT_AXES)


def sample_real(field,offset):
    return field[tuple(v%field.shape[0] for v in offset)]


def positions(radius):
    return [p for p in product(range(-radius,radius+1),repeat=3) if sum(map(abs,p))<=radius]


def basis_clouds(radius):
    zero=(0,0,0)
    basis=[{zero:embed(col).copy()} for col in ODD.T]
    for r in positions(radius):
        if r<=zero:
            continue
        neg=tuple(-i for i in r)
        for i in range(4):
            for j in range(i,4):
                z=np.zeros((4,4),dtype=complex)
                z[i,j]=1
                z[j,i]=PARITY[i]*PARITY[j]
                z/=np.sqrt(2*np.vdot(z,z).real)
                basis.append({r:z,neg:-z.T})
    return basis


def stencils(clock):
    # Both single-particle Bloch symbols have no Fourier components beyond Manhattan 3.
    a,b=(real_field(h,clock.n) for h in (clock.ha,clock.hb))
    shifts={}
    for r in positions(3):
        av,bv=sample_real(a,r),sample_real(b,r)
        if max(np.max(abs(av)),np.max(abs(bv)))>2e-12:
            shifts[r]=(av,bv)
    for arr in (a,b):
        tail=arr.copy()
        for r in shifts:
            tail[r]=0.
        assert np.max(abs(tail))<2e-12
    return shifts


def fit_cloud(clock,leaks,radius,u):
    """Fit one normalized finite-range F to both contacts, retaining all sixteen components."""
    overlap=np.vdot(u,clock.v)
    avg=real_field((leaks[0]+leaks[1])/2,clock.n)
    diff_at_zero=(leaks[0]-leaks[1]).mean(axis=0)/2
    shifts=stencils(clock)
    basis=basis_clouds(radius)
    outputs=sorted({tuple(a+b for a,b in zip(r,s))
                    for r in positions(radius) for s in shifts})
    ix={r:i for i,r in enumerate(outputs)}
    zero=(0,0,0)
    mat=np.zeros((len(outputs)+1,16,len(basis)),complex)
    for j,b in enumerate(basis):
        for r,z in b.items():
            mat[ix[r],:,j]-=(clock.energy*z).ravel()
            if r==zero:
                mat[-1,:,j]+=(z/clock.lam).ravel()
            for s,(av,bv) in shifts.items():
                dest=tuple(a+d for a,d in zip(r,s))
                mat[ix[dest],:,j]+=(av@z+z@bv.T).ravel()
    target=np.array([sample_real(avg,r) for r in outputs]+[diff_at_zero]).ravel()
    mat=overlap*mat.reshape(-1,len(basis))
    coeff,_,rank,_=np.linalg.lstsq(mat,-target,rcond=2e-13)
    assert rank==len(coeff)
    f={}
    for a,b in zip(coeff,basis):
        for r,z in b.items():
            f[r]=f.get(r,0)+a*z
    return f,len(coeff)


def evaluate(clock,leaks,f,u):
    n=clock.n
    real=np.zeros((n,n,n,4,4),complex)
    for r,z in f.items():
        real[r]=z
    momentum=np.fft.fftn(real,axes=FFT_AXES).reshape(-1,4,4)
    for r,z in f.items():
        other=f[tuple(-x for x in r)]
        np.testing.assert_allclose(other,-z.T,atol=1e-12)
        np.testing.assert_allclose(other,-BETA@z@BETA,atol=1e-12)
    assert abs(np.vdot(momentum,clock.psi)/len(momentum))<1e-11
    hit=np.vdot(u,clock.v)*momentum
    return np.array([norm2(l+clock.h(c,hit)-clock.energy*hit) for l,c in zip(leaks,CONTACTS)])



def check_two_fiber_vertex(f,u):
    """Check Hermiticity and zero total energy for an endpoint-anchored local two-body vertex."""
    offsets=list(f)
    seed=np.zeros((len(offsets),4,4),complex)
    seed[offsets.index((0,0,0))]=embed(u)
    seed=seed.ravel()

    def moved_cloud(k):
        return np.array([z*np.cos(k*r[2]/2) for r,z in f.items()]).ravel()

    def change(ko,ki,state):
        outgoing=moved_cloud(ko)
        incoming=moved_cloud(ki)
        return np.sin(ko-ki)*(outgoing*np.vdot(seed,state)-seed*np.vdot(incoming,state))

    ki,ko=-0.43,0.27
    incoming=seed+0.38j*moved_cloud(ki)
    outgoing=0.19j*seed+moved_cloud(ko)
    forward=np.vdot(outgoing,change(ko,ki,incoming))
    backward=np.vdot(incoming,change(ki,ko,outgoing))
    assert abs(forward)>1e-5
    assert abs(forward-backward.conjugate())<2e-12
    assert not np.any(change(ki,ki,incoming))


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--fine",action="store_true",help="train at 36 cubed and test at 56 cubed")
    args=parser.parse_args()
    train,test=(36,56) if args.fine else (24,40)
    d=design(Torus(train))
    r=RestClock(train,d)
    u=r.v/np.linalg.norm(r.v)
    ref=[r.leak(c) for c in CONTACTS]
    common,errors=exact_cloud(r)
    print(f"ideal J at training mesh: exact unrestricted residual norm squared {max(errors):.3g}")
    print("training frozen finite-difference repair compatibility and unrestricted mean-square floor",unrestricted(r,ref)[:2])
    spectra=[]
    for radius in (0,1,2,3):
        f,num=fit_cloud(r,ref,radius,u)
        check_two_fiber_vertex(f,u)
        train_res=evaluate(r,ref,f,u)
        spectra.append((radius,f,num,train_res))
    del r,ref,common
    r=RestClock(test,d)
    ref=[r.leak(c) for c in CONTACTS]
    raw=np.array([norm2(a) for a in ref])
    print(f"untouched test mesh {test}^3 baseline: density={raw[0]:.10g} mass={raw[1]:.10g}")
    for radius,f,num,train_res in spectra:
        held=evaluate(r,ref,f,u)
        print(f"R={radius} complex cloud amplitudes={num}: training {train_res[0]:.9g}, {train_res[1]:.9g};"
              f" held-out {held[0]:.9g}, {held[1]:.9g}")
        if radius==0:
            floor=held
    assert np.all(held<floor/2)
    _,errors=exact_cloud(r)
    print(f"independent ideal derivative mesh {test}: exact unrestricted squared residual {max(errors):.3g}")
    print("frozen repair on held-out mesh: incompatibility and unrestricted mean-square floor",unrestricted(r,ref)[:2])


if __name__=="__main__":
    main()
common_band.py
"""Inverse construction of a band shared by two microscopic contacts."""
from pathlib import Path
import argparse
import sys
import numpy as np
from numpy.polynomial import chebyshev as cheb

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


def local_matrix(y,u):
    # Minimal Hermitian extension with prescribed action on the even rest spinor.
    b=np.outer(y,u.conj())
    return b+b.conj().T-np.vdot(u,y).real*np.outer(u,u.conj())


class Designer:
    def __init__(self,n):
        self.torus=Torus(n)
        _,lam,self.u,_=rest_calibration(self.torus)
        self.g=1/lam

    def exact(self,k):
        k=np.asarray(k)
        energy=np.hypot(self.torus.rest,np.linalg.norm(k))
        fiber=Fiber(self.torus,k)
        green=fiber.green(energy)
        source=np.linalg.solve(green,self.u)
        y=source-self.g*self.u
        V=local_matrix(y,self.u)
        for c in (IDENTITY,BETA_PAIR):
            assert np.linalg.norm(green@((V+self.g*c)@self.u)-self.u)<2e-13
        return V


class AxialStencil:
    def __init__(self,model,degree,kmax=.13):
        self.xmax=4*np.sin(kmax/2)**2
        t=np.cos(np.pi*(np.arange(degree)+.5)/degree)
        x=self.xmax*(t+1)/2
        k=2*np.arcsin(np.sqrt(x)/2)
        even=[]
        odd=[]
        for z,s in zip(k,x):
            V=model.exact([0.,0.,z])
            P=BETA_PAIR@V@BETA_PAIR
            even.append(((V+P)/(2*s)).ravel())
            odd.append(((V-P)/(2*np.sin(z))).ravel())
        self.even=cheb.chebfit(t,even,degree-1)
        self.odd=cheb.chebfit(t,odd,degree-1)

    def at(self,k):
        x=4*np.sin(k/2)**2
        t=2*x/self.xmax-1
        return (x*cheb.chebval(t,self.even)+np.sin(k)*cheb.chebval(t,self.odd)).reshape(6,6)


def measure(model,vec,V,c):
    fiber=Fiber(model.torus,np.asarray(vec))
    z=np.hypot(model.torus.rest,np.linalg.norm(vec))
    for _ in range(10):
        inv=np.linalg.inv(fiber.green(z))
        vals,vecs=np.linalg.eigh(hermitian(inv-model.g*c-V))
        j=np.argmax(abs(vecs.conj().T@model.u))
        u=vecs[:,j]
        delta=vals[j]
        if abs(delta)<3e-13:
            return z,np.linalg.norm((IDENTITY-BETA_PAIR)@u)/2
        source=inv@u
        derivative=-np.vdot(source,fiber.green(z,derivative=True)@source).real
        z-=delta/derivative
    raise ArithmeticError('moving pole failed to converge')


def record(model,k):
    fiber=Fiber(model.torus,k)
    z=np.hypot(model.torus.rest,np.linalg.norm(k))
    G=fiber.green(z)
    src=np.linalg.solve(G,model.u)
    scale=np.sqrt(-np.vdot(src,fiber.green(z,True)@src).real)
    source=(BASIS@(src/scale)).reshape(4,4)
    p=[v*(2*np.pi/model.torus.size) for v in model.torus.grid]
    def fields(offset):
        a,e=block([v+o+d/2 for v,o,d in zip(p,offset,k)])
        b,f=block([-v-o+d/2 for v,o,d in zip(p,offset,k)])
        return a,b,e,f
    def state(offset):
        a,b,e,f=fields(offset)
        return wave(source,z,a,e,b,f)
    b=state(np.zeros(3))
    assert abs(np.vdot(b,b).real/len(b)-1)<2e-12
    np.testing.assert_allclose(BASIS.T@b.mean(axis=0).ravel(),model.u/scale,atol=2e-12)
    return z,model.u/scale,state,fields


def pulse_test(model,ki,kf):
    # Endpoint vertex acting on the actual normalized shared pole in all 16 spins.
    ki,kf=np.asarray(ki),np.asarray(kf)
    q=kf-ki
    _,cv,initial,_=record(model,ki)
    target=record(model,kf)[2](np.zeros(3))
    p=[v*(2*np.pi/model.torus.size) for v in model.torus.grid]
    def hs(sign,shift):
        return block([sign*v+d for v,d in zip(p,shift)])[0]
    a=(hs(1,kf/2)+hs(1,(ki-q)/2))/2
    b=(hs(-1,kf/2)+hs(-1,(ki-q)/2))/2
    kinetic=a@initial(-q/2)+initial(q/2)@b.swapaxes(-1,-2)
    mid=(model.exact(ki)+model.exact(kf))/2
    raw=[]
    for c in (IDENTITY,BETA_PAIR):
        phi=kinetic+(BASIS@((model.g*c+mid)@cv)).reshape(4,4)
        raw.append(phi)
    assert np.max(abs(raw[0]-raw[1]))<3e-13
    f=np.vdot(target,raw[0])/len(target)
    rejected=raw[0]-f*target
    loss=np.vdot(rejected,rejected).real/len(rejected)
    wanted=np.hypot(model.torus.rest,np.linalg.norm((ki+kf)/2))
    ans=raw[1]-rejected+(wanted-f)*target
    assert np.max(abs(ans-wanted*target))<2e-13
    return f,loss


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--fine',action='store_true')
    n=48 if parser.parse_args().fine else 32
    model=Designer(n)
    for k in ([0.,0.,.115],[.039,-.042,.051]):
        v=model.exact(k)
        masses=[measure(model,k,v,c) for c in (IDENTITY,BETA_PAIR)]
        wanted=np.hypot(model.torus.rest,np.linalg.norm(k))
        assert max(abs(z-wanted)+o for z,o in masses)<1e-10
    for degree in (1,2,3,4):
        stencil=AxialStencil(model,degree)
        errors=[];odds=[]
        for z in (.018,.053,.086,.117,.13):
            k=[0.,0.,z]
            e=np.hypot(model.torus.rest,z)
            for c in (IDENTITY,BETA_PAIR):
                obs,odd=measure(model,k,stencil.at(z),c)
                errors.append(abs(obs-e));odds.append(odd)
        print(f'range {degree} axial cells: max held-out energy error {max(errors):.8g}; '
              f'max odd coincidence amplitude {max(odds):.8g}',flush=True)
        if degree==4:assert max(errors)<2e-6 and max(odds)<1e-5
    k=np.array([.008,-.011,.036]);q=np.array([.012,.013,.047])
    f,loss=pulse_test(model,k,k+q)
    reverse,_=pulse_test(model,k+q,k)
    assert abs(f-reverse.conjugate())<(4e-6 if n==32 else 2e-8)
    print(f'common unprojected pulse amplitude {f.real:.9f}, internal norm outside band {loss:.8g}')
    eplus=model.torus.rest**2+np.dot(k+q/2,k+q/2)
    eminus=model.torus.rest**2+np.dot(k-q/2,k-q/2)
    assert abs((eplus-eminus)/2-np.dot(q,k))<1e-15


if __name__=='__main__':
    main()
lapse_algebra.py
"""Compare two-lapse brackets in a scalar band, a signed Dirac field and its positive subspace."""
from collections import defaultdict
from math import atan2, cos, sin, sqrt

MASS = 1.0
STEP = 0.25
LIMIT = 28


def spin(k, sign=1):
    theta = atan2(k, MASS) / 2
    return (cos(theta), sin(theta)) if sign == 1 else (-sin(theta), cos(theta))


def project(states, sign):
    keep = {}
    for j, (a, b) in states.items():
        x, y = spin(STEP*j, sign)
        val = x*a+y*b
        keep[j] = (x*val, y*val)
    return keep


def real_profile(constant, positive):
    modes = {0: complex(constant)}
    for j, a in positive.items():
        modes[j] = a
        modes[-j] = complex(a).conjugate()
    return modes


def derivative(modes):
    return {j: 1j*j*STEP*a for j, a in modes.items()}


def multiply(a, b):
    c = defaultdict(complex)
    for j, x in a.items():
        for k, y in b.items():
            c[j+k] += x*y
    return c


def subtract_modes(a, b):
    return {j: a.get(j, 0)-b.get(j, 0) for j in a.keys() | b.keys()}


def vertex(kind, modes, states):
    """Spectral derivative with an explicitly finite momentum cutoff."""
    out = {}
    for j, (x, y) in states.items():
        for transfer, coeff in modes.items():
            dest = j+transfer
            if abs(dest) > LIMIT:
                continue
            mid = STEP*(j+dest)/2
            if kind == "dirac":
                a, b = MASS*x+mid*y, mid*x-MASS*y
            elif kind == "scalar":
                energy = sqrt(MASS**2+mid**2)
                a, b = energy*x, energy*y
            elif kind == "shift":
                a, b = mid*x, mid*y
            else:
                raise ValueError(kind)
            u, v = out.get(dest, (0j, 0j))
            out[dest] = (u+coeff*a, v+coeff*b)
    return out


def combine(a, b, x=1, y=-1):
    out = {}
    for j in a.keys() | b.keys():
        z, w = a.get(j, (0j, 0j))
        s, t = b.get(j, (0j, 0j))
        out[j] = (x*z+y*s, x*w+y*t)
    return out


def dot(a, b):
    return sum(a[j][0].conjugate()*b[j][0] + a[j][1].conjugate()*b[j][1]
               for j in a.keys() & b.keys())


def norm(a):
    return sqrt(max(0, dot(a, a).real))


def loop(kind, f, g, src, mid_sign=None, other=None):
    """i[H[f],H[g]] or mixed i[D[f],H[g]], optionally resolving intermediate sign."""
    left = other or kind
    first_g = vertex(kind, g, src)
    first_f = vertex(left, f, src)
    if mid_sign is not None:
        first_g = project(first_g, mid_sign)
        first_f = project(first_f, mid_sign)
    return combine(vertex(left, f, first_g), vertex(kind, g, first_f), 1j, -1j)


def single_modes(k, q, r):
    energy = lambda p: sqrt(MASS**2+p*p)
    scalar = energy(k+q+r/2)*energy(k+q/2)-energy(k+r+q/2)*energy(k+r/2)
    shift = (q-r)*(k+(q+r)/2)
    start, end = spin(k), spin(k+q+r)
    overlap = sum(x*y for x,y in zip(start,end))

    def via(s, a, b):
        mid = spin(k+a,s)
        a0 = (energy(k)+s*energy(k+a))/2
        a1 = (s*energy(k+a)+energy(k+a+b))/2
        return (a0*a1*sum(x*y for x,y in zip(mid,start))*
                sum(x*y for x,y in zip(end,mid)))

    plus, minus = [via(s,q,r)-via(s,r,q) for s in (1,-1)]
    assert abs(plus+minus-shift*overlap)<1e-13
    print(f"mixed q={q:g}, r={r:g}, k={k:g}: scalar={scalar:.9f} shift={shift:.9f}")
    print(f"external positive spinors: positive intermediate={plus:.9f}, negative={minus:.9f}, "
          f"signed target={shift*overlap:.9f}")
    return abs(scalar-shift), abs(minus)


def main():
    e0, e1 = single_modes(.5, 1.5, .5)
    assert e0 > .005 and e1 > .001
    f = real_profile(.35, {1:.31+.19j, 4:.12-.28j, 7:-.09+.16j})
    g = real_profile(-.22, {2:-.23+.07j, 3:.39-.14j, 6:.06+.21j})
    w = subtract_modes(multiply(f,derivative(g)),multiply(g,derivative(f)))
    src = {j:(complex(cos(j+.2),sin(j*.8)),complex(.3*sin(j),cos(j+.1)))
           for j in (-7,-3,0,2,6)}
    probe = {j:(complex(.2*j,1),complex(1,.13*j)) for j in (-5,0,2,6,9)}
    assert max(map(abs,src))+max(map(abs,f))+max(map(abs,g)) <= LIMIT
    for kind in ("scalar","dirac","shift"):
        h1 = dot(probe,vertex(kind,f,src))
        h2 = dot(vertex(kind,f,probe),src)
        assert abs(h1-h2)<2e-13

    for j in (1,3,7):
        cc, ss = real_profile(0,{j:.5}), real_profile(0,{j:-.5j})
        target = vertex("shift",{0:j*STEP},src)
        for kind in ("scalar","dirac"):
            assert norm(combine(loop(kind,cc,ss,src),target))<1e-13

    dst = vertex("shift",w,src)
    for kind in ("dirac","scalar"):
        error = norm(combine(loop(kind,f,g,src),dst))/norm(dst)
        print(f"finite Fourier profiles: {kind} relative bracket error {error:.10g}")
        assert error<1e-13 if kind=="dirac" else error>.001

    external = project(src,1)
    target = project(vertex("shift",w,external),1)
    pos = project(loop("dirac",f,g,external,1),1)
    neg = project(loop("dirac",f,g,external,-1),1)
    missing = norm(combine(pos,target))/norm(target)
    assert norm(combine(combine(pos,neg,1,1),target))<1e-13
    print(f"external positive packet: positive-only relative error {missing:.10g}, "
          f"negative intermediate norm / target {norm(neg)/norm(target):.10g}")
    assert missing>.0001

    mixed = loop("dirac",f,g,src,other="shift")
    normal = vertex("dirac",multiply(f,derivative(g)),src)
    correction = {j:(-y,-x) for j,(x,y) in vertex("shift",multiply(g,derivative(f)),src).items()}
    assert norm(combine(combine(mixed,normal),correction))<2e-13
    print(f"fixed-frame shift-normal remainder / H[f g'] {norm(correction)/norm(normal):.10g}")
    edge = {LIMIT: (1+0j,0j)}
    edge_error=norm(combine(loop("dirac",cc,ss,edge),vertex("shift",{0:7*STEP},edge)))
    assert edge_error>1
    print(f"edge packet: cutoff-induced cosine/sine residual {edge_error:.9g}")


if __name__ == "__main__":
    main()
band_audit.py
"""Audit all 16 coincidence spin channels of the corrected 3D pair across momentum."""
from pathlib import Path
import argparse
import sys
import numpy as np
from collision_transport import (Torus, BASIS, CONTACTS, design, quartic_design, symbol, 
                                 Fiber, hermitian, pole)
from bound_3d import FULL_TENSORS, mode, GAMMA

I16=np.eye(16)
C16={'density':I16,'mass':FULL_TENSORS[-1]}


class FullFiber(Fiber):
    """All four energy signs and all sixteen spins; no bound-pole starting vector."""
    def green16(self,energy):
        moments=np.zeros((5,5))
        n=self.n
        for sign,t,e in zip((1,1,-1,-1),(1,-1,1,-1),self.e):
            weight=.25/(energy-e)
            moments[0,0]+=weight.sum()
            moments[1:,0]+=sign*(weight@self.ua)
            moments[0,1:]+=t*(weight@self.ub)
            moments[1:,1:]+=sign*t*self.ua.T@(weight[:,None]*self.ub)
        return hermitian(np.tensordot(moments.ravel()/n**3,FULL_TENSORS,axes=1))


def potential(d,k,kind,variant):
    g=1/d['cal'][1]
    return (g*C16[kind]+BASIS@symbol(d,k,variant)@BASIS.T)


def inertia(fiber,vinv,e):
    return int(np.count_nonzero(np.linalg.eigvalsh(fiber.green16(e)-vinv)<0))


def root(fiber,vinv,lo,hi,start):
    """Quantile by monotone inertia of G(E)-V^-1 in a known free gap."""
    for _ in range(34):
        mid=(lo+hi)/2
        if inertia(fiber,vinv,mid)>start:
            hi=mid
        else:
            lo=mid
    return (lo+hi)/2


def energy(p):
    p=np.asarray(p)
    en,_=mode(p,())
    return float(en[0])


def corner(torus,d):
    k=np.full(3,np.pi)
    fiber=FullFiber(torus,k)
    free_neg=float(np.min(fiber.e[3]))
    assert free_neg>=-35 and abs(free_neg+34)<.005
    onsite=10*(np.kron(GAMMA[-1],GAMMA[0])+np.kron(GAMMA[0],GAMMA[-1]))
    for variant in ('bare','common','range2'):
        for kind in C16:
            v=potential(d,k,kind,variant)
            inv=np.linalg.inv(v)
            trial=np.linalg.eigvalsh(BASIS.T@(onsite+v)@BASIS)
            # -35 is strictly below all four continua by the analytical bound.
            n_start=inertia(fiber,inv,-1100.)
            n_end=inertia(fiber,inv,-35.)
            num=n_end-n_start
            low=root(fiber,inv,-1100.,-35.,n_start) if num else 0
            high=root(fiber,inv,-1100.,-35.,n_end-1) if num>1 else low
            print(f'corner {variant:6} {kind:7}: N(E<−35)={num}, '
                  f'extrema {low:.6f},{high:.6f}, trial {trial[0]:.4f} to {trial[-1]:.4f}')
            if variant=='range2':
                assert num==6 and high < -800 and trial[-1]<-800
            if variant=='common':
                assert num>=1 and low < -39
    return free_neg


def certify_corner(d):
    # At corner, ||Hfree(p)|| <= 34 analytically. A truncated Chebyshev
    # expansion integrates exactly on this grid through polynomial degree m.
    n=48; degree=(n-1)//2
    k=np.full(3,np.pi)
    matrix=FullFiber(Torus(n),k).green16(-35.)
    ratio=(35-np.sqrt(69))/34
    twice_tail=4/np.sqrt(69)*ratio**(degree+1)/(1-ratio)
    margins=[]
    for kind in C16:
        inv=np.linalg.inv(potential(d,k,kind,'bare'))
        ev=np.linalg.eigvalsh(matrix-inv)
        margins.append(min(abs(ev)))
        assert min(abs(ev))>twice_tail+.0001
        assert sum(ev<0)==sum(np.linalg.eigvalsh(-inv)<0)
    print(f'bare corner no levels below -35: quadrature error <= {twice_tail:.7f},'
          f' smallest inverse-kernel margin {min(margins):.7f}')


def axial(torus,d):
    # Explicit continuum-overlap witnesses, independent of any integration mesh.
    p=np.array([np.pi,np.pi,np.pi/2])
    for q in (.20,.225,.25):
        half=np.array([0.,0.,q/2])
        mixed=abs(energy(p+half)-energy(p-half))
        same=2*energy(half)
        print(f'Kz={q:g}: mixed continuum reaches at least {mixed:.8f}, '
              f'positive same-sign continuum starts no higher than {same:.8f}')
        if q>=.225:
            assert mixed>same
    # Within rigorously separated subwindows count ALL discrete poles, including
    # those with no overlap whatsoever with the tracked rest bound-pair source.
    for q in (0.,.10,.15):
        k=np.array([0.,0.,q])
        f=FullFiber(torus,k)
        lo=1.67
        hi=1.98
        assert np.hypot(1.,32/3)*q < lo < hi<2.
        for kind in C16:
            numbers=[]
            for variant in ('bare','common','range2'):
                inv=np.linalg.inv(potential(d,k,kind,variant))
                ng=inertia(f,inv,hi)-inertia(f,inv,lo)
                neg=inertia(f,inv,-lo)-inertia(f,inv,-hi)
                numbers.append((ng,neg))
            print(f'Kz={q:.2f} {kind}: counts in (1.67,1.98), (−1.98,−1.67): {numbers}')


def window(s,L):
    return (1-s)**L*(1+L*s)


def short_window(s):
    if s==0:
        return 1.
    if s==1:
        return 0.
    f=(np.sin(16*np.arcsin(np.sqrt(s)))/(16*np.sqrt(s)))**2
    return f*f*(6-8*f+3*f*f)


def bounded_completion(torus,d,L=128):
    # For q_j=4sin²(K_j/2), sum q_j=12s. The J_j link even to odd.
    # Bound their sum by Cauchy-Schwarz, with each ||J_j||=||J_j u||.
    jnorm=np.array([np.linalg.norm(J,2) for J in d['J']])
    coefficients=[np.sqrt(12)*np.linalg.norm(jnorm),
                  12*np.max(abs(d['m'])),144*np.max(abs(d['quartic']))]
    terms=[]
    for power,C in zip((.5,1,2),coefficients):
        t=(power+np.sqrt(power**2+4*power))/2
        terms.append(C*t**power*(1+t)*np.exp(-t)/L**power)
    limit=sum(terms)
    assert limit<.42
    # Rational upward envelopes tolerate numerical quadrature/refinement errors.
    assert coefficients[0]<2.6 and coefficients[1]<12.1 and coefficients[2]<1380
    crude=0.
    for a,C in ((.5,2.6),(1.,12.1),(2.,1380.)):
        t=(a+np.sqrt(a*a+4*a))/2
        crude+=C*t**a*(1+t)*np.exp(-t)/L**a
    print(f'L={L} uniform perturbation norm <= {limit:.6f}; rounded envelope {crude:.6f}')
    assert crude<.41
    assert window(1,L)==0 and window(0,L)==1
    for direction,q in ((np.array([0.,0.,1.]),.05),(np.array([0.,0.,1.]),.10),
                        (np.ones(3)/np.sqrt(3),.08)):
        E=[]
        short=[]
        eps=.00004
        for momentum in (q-eps,q,q+eps):
            k=direction*momentum
            s=sum(np.sin(k/2)**2)/3
            w=window(s,L)
            damped={**d,**{key:w*d[key] for key in ('J','m','quartic')}}
            f=Fiber(torus,k)
            E.append(np.array([pole(f,damped,k,c,'range2')[0] for c in CONTACTS.values()]))
            damped={**d,**{key:short_window(s)*d[key] for key in ('J','m','quartic')}}
            short.append(np.array([pole(f,damped,k,c,'range2')[0] for c in CONTACTS.values()]))
        current=E[1]*(E[2]-E[0])/(2*eps*q)
        compact=short[1]*(short[2]-short[0])/(2*eps*q)
        print(f'taper q={q:.3f}: E*v/k={current[0]:.7f},{current[1]:.7f}; '
              f'62-cell stencil {compact[0]:.7f},{compact[1]:.7f}')
    constants=[]
    for a in (.5,1.):
        # Max of t^a h(1/t) on t>=1. Max on t<=1 is at most 1.
        t=max(np.roots([6*(a-2),-8*(a-3),3*(a-4)]))
        constants.append(max(1.,t**(a-2)*(6-8/t+3/t**2)))
    limit2=2.6*constants[0]/16+12.1*constants[1]/256+1380*6/16**4
    print(f'62-cell stencil: global perturbation norm <= {limit2:.6f}')
    assert limit2<.371 and short_window(0)==1 and short_window(1)==0


def dense_control(d):
    # A true 4 x 4 x 4 periodic box at corner K, with all 16 spins at every p.
    n=4
    k=np.full(3,np.pi)
    pts=n**3
    fiber=FullFiber(Torus(n),k)
    free=[]
    for p in np.ndindex(n,n,n):
        rel=np.array(p)*2*np.pi/n
        a,ua=mode(rel+k/2,())
        b,ub=mode(-rel+k/2,())
        ha=a[0]*np.tensordot(ua[0],GAMMA[1:],axes=1)
        hb=b[0]*np.tensordot(ub[0],GAMMA[1:],axes=1)
        free.append(np.kron(ha,GAMMA[0])+np.kron(GAMMA[0],hb))
    for variant in ('bare','common','range2'):
        for kind in C16:
            v=potential(d,k,kind,variant)
            # V acts at relative position zero; Fourier transform gives V / n³.
            H=np.tile(v/pts,(pts,pts)).astype(complex)
            for i,b in enumerate(free):
                sl=slice(16*i,16*i+16)
                H[sl,sl]+=b
            direct=np.linalg.eigvalsh(H)
            v_inv=np.linalg.inv(v)
            start=inertia(fiber,v_inv,-1100.)
            count=inertia(fiber,v_inv,-35.)-start
            assert np.count_nonzero(direct<-35.)==count
            if count:
                low=root(fiber,v_inv,-1100.,-35.,start)
                assert abs(direct[0]-low)<1e-7
    print('independent 1024 x 1024 dense torus: six spectra checked')


def run(n):
    torus=Torus(n)
    d=design(torus)
    d['quartic']=quartic_design(torus,d)
    print(f'mesh {n}, g={1/d["cal"][1]:.9f}')
    # Rigorous starting point below the full spectrum for every corner scan.
    for variant in ('bare','common','range2'):
        for kind in C16:
            assert 2*np.sqrt(33.**2+1)+np.linalg.norm(
                potential(d,np.full(3,np.pi),kind,variant),2)<1100
    axial(torus,d)
    f0=FullFiber(torus,np.zeros(3))
    for kind in C16:
        inv=np.linalg.inv(potential(d,np.zeros(3),kind,'bare'))
        for lo,hi in ((.01,1.67),(-1.67,-.01),(1.67,1.98)):
            a=inertia(f0,inv,lo); b=inertia(f0,inv,hi)
            levels=[root(f0,inv,lo,hi,j) for j in range(a,b)]
            print(f'rest {kind} {lo:g}..{hi:g}:',np.round(levels,6))
    free_min=corner(torus,d)
    dense_control(d)
    certify_corner(d)
    bounded_completion(torus,d)
    print(f'sampled free minimum at corner {free_min:.8f}')
    return d


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--size',type=int,default=24)
    args=parser.parse_args()
    run(args.size)
cutoff_flow.py
"""Remove the lattice cutoff while holding the one-body mass, speed and pair energy fixed."""
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 BASIS, BETA_PAIR, GAMMA, IDENTITY, TENSORS, Torus, extract_curvature


def symbol(momentum, spacing):
    x,y,z = momentum
    t = [2*np.sin(k/2)**2 for k in momentum]
    regulator = 2*sum(v*v for v in t)/3 + 2*(t[0]*t[1]+t[1]*t[2]+t[0]*t[2])
    coeff = np.stack(np.broadcast_arrays(np.sin(x)*np.cos(y)*np.cos(z),
                        np.sin(y)*np.cos(z),np.sin(z),spacing+regulator), axis=-1).reshape(-1,4)
    energy = np.linalg.norm(coeff,axis=1)
    return energy,coeff/energy[:,None]


class Cutoff:
    def __init__(self,a,order,rest_ratio=1.9):
        self.a = a
        self.rest = a*rest_ratio
        # Resolve the diminishing physical-momentum interval |k| ~ a without
        # sampling a different physical box at every cutoff.
        nodes, weights = np.polynomial.legendre.leggauss(order)
        tmax = np.arcsinh(np.pi/a)
        t = (nodes+1)*tmax/2
        k = a*np.sinh(t)
        w = weights*tmax/2*a*np.cosh(t)/(2*np.pi)
        self.nodes = np.r_[-k[::-1],k]
        self.weights = np.r_[w[::-1],w]
        assert abs(self.weights.sum()-1)<2e-13

    def chunks(self):
        k, w = self.nodes,self.weights
        for i in range(0,len(k),4):
            momenta=(k[i:i+4,None,None],k[None,:,None],k[None,None,:])
            weights=(w[i:i+4,None,None]*w[None,:,None]*w[None,None,:]).ravel()
            yield momenta,weights

    def green(self,energy,axis=2,momentum=0.,derivative=False):
        moments=np.zeros((5,5))
        for p,w in self.chunks():
            shift=[momentum/2 if j==axis else 0. for j in range(3)]
            e,u=symbol([v+d for v,d in zip(p,shift)],self.a)
            f,v=symbol([-v+d for v,d in zip(p,shift)],self.a)
            sectors=[]
            for s,t in ((1,1),(1,-1),(-1,1),(-1,-1)):
                den=energy-s*e-t*f
                sectors.append(-.25*w/den**2 if derivative else .25*w/den)
            pp,pm,mp,mm=sectors
            moments[0,0]+=np.sum(pp+pm+mp+mm)
            moments[1:,0]+=(pp+pm-mp-mm)@u
            moments[0,1:]+=(pp-pm+mp-mm)@v
            moments[1:,1:]+=u.T@((pp-pm-mp+mm)[:,None]*v)
        return np.tensordot(moments.ravel(),TENSORS,axes=1)

    def calibrate(self,previous):
        green=self.green(self.rest)
        loc=[0,5]
        ev,vec=np.linalg.eigh(green[np.ix_(loc,loc)])
        j=np.argmax(abs(vec.conj().T@previous[loc]))
        state=np.zeros(6,dtype=complex)
        state[loc]=vec[:,j]
        assert np.linalg.norm(green@state-ev[j]*state)<2e-11
        dE=(state.conj()@self.green(self.rest,derivative=True)@state).real
        return green,ev[j],state,dE

    def occupations(self,state,dE,physical_width=2.):
        # The coefficients of the wave at the pole are the four free signed
        # pair projectors acting on its common, normalized coincident source.
        plus=(state[0]+state[5])/np.sqrt(2)
        minus=(state[0]-state[5])/np.sqrt(2)
        occupations=np.zeros(3)
        low=0.
        for p,w in self.chunks():
            e,v=symbol(p,self.a)
            # Exact even singlet projectors avoid subtracting nearly equal
            # mixed-band terms when the bare mass in lattice units is tiny.
            m=v[:,3]
            norms=(abs(plus+m*minus)**2/2,
                   abs(minus)**2*np.sum(v[:,:3]**2,axis=1),
                   abs(plus-m*minus)**2/2)
            gaussian=np.exp(-sum(k*k for k in p)/(2*(self.a*physical_width)**2)).ravel()
            for j,(norm,den) in enumerate(zip(norms,(self.rest-2*e,self.rest,self.rest+2*e))):
                measure=w*norm/(den**2*(-dE))
                occupations[j]+=measure.sum()
                low+=np.dot(measure,gaussian)
        assert abs(occupations.sum()-1)<2e-8
        return occupations,low

    def asymptote(self):
        # UV constants of the zero-lattice-mass regulator. The s+ local spin
        # singlet has no mixed-band projection at any momentum.
        A=D=C=0.
        for p,w in self.chunks():
            e,v=symbol(p,0.)
            A+=np.dot(w,1/(4*e**2))
            D+=np.dot(w,v[:,3]/(2*e))
            C+=np.dot(w,1-v[:,3]**2)
        L=A+D**2/C
        return L,D**2/(C*L)

    def even_matrix(self):
        e0=self.rest
        hp=hm=cross=0.
        for p,w in self.chunks():
            e,v=symbol(p,self.a)
            m=e*v[:,3]
            den=e0**2-4*e**2
            hp+=np.dot(w,e0/den)
            cross+=np.dot(w,2*m/den)
            hm+=np.dot(w,v[:,3]**2*e0/den+(1-v[:,3]**2)/e0)
        return np.array([[hp,cross],[cross,hm]])

    def row(self,previous):
        cal=self.calibrate(previous)
        g,lam,state,dE=cal
        rotate=np.array([[1.,1.],[1.,-1.]])/np.sqrt(2)
        np.testing.assert_allclose(rotate.T@g[np.ix_([0,5],[0,5])]@rotate,
                                   self.even_matrix(),atol=2e-12)
        steps=self.a*np.array([.008,.004])
        rows=[]
        for axis in (0,1,2):
            values=[extract_curvature(self.rest,k,self.green(self.rest,axis,k),cal) for k in steps]
            rows.append((4*values[1]-values[0])/3)
        occ,low=self.occupations(state,dE)
        return state,np.array(rows),lam**2/(-dE),occ,low,lam


def sweep(order,scales):
    state=np.eye(6)[0]
    rows=[]
    for a in scales:
        kernel=Cutoff(a,order)
        state,R,coincidence,occupation,low,lam=kernel.row(state)
        print(f'a={a:g} Rz={R[2,0]:.8f}/{R[2,1]:.8f} Rx={R[0,0]:.7f}/{R[0,1]:.7f} '
              f'contact={coincidence:.7f} (++,+-,- -)={occupation} low={low:.7f} '
              f'lambda={lam:.8g} upper={abs(state[0])**2:.5f}',flush=True)
        rows.append((R,coincidence,occupation,low,lam))
    return rows


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--fine',action='store_true',help='use 32 Gauss nodes per half-axis')
    parser.add_argument('--order',type=int,help='override the number of nodes per half-axis')
    args=parser.parse_args()
    order=args.order or (32 if args.fine else 20)
    scales=[1.,.75,.5,.375,.25,.125,.0625,.03125,.015625]
    result=sweep(order,scales)
    reference=Torus(48)
    rest=reference.green(reference.rest)
    np.testing.assert_allclose(Cutoff(1,order).green(reference.rest),rest,atol=2e-7)
    L,mixed=Cutoff(.25,max(28,order)).asymptote()
    print(f'limiting contact probability / a²={1.9**2*L:.8f}, mixed-band occupation={mixed:.8f}')
    assert abs(result[-1][1]/scales[-1]**2-1.9**2*L)<.02
    assert abs(result[-1][2][1]-mixed)<.02
    assert result[-1][3]<.02 and result[0][3]>.85
    assert result[-1][0][2,0]>3 and result[-1][0][0,0]>5
collective_gravity.py
"""Two dilute condensates sourcing their shared, constrained Newtonian potential.

NumPy; both published single-pair kernels are imported unmodified.
"""
from pathlib import Path
import argparse
import sys
import numpy as np

HERE = Path(__file__).resolve().parent
if not (HERE/'form_factor.py').exists():
    sys.path.insert(0,str(HERE.parent/'pair-inertia'))
from collision_transport import (Torus, BASIS, CONTACTS, design, symbol,
                                 vertex, Fiber, pole)
from form_factor import block, wave

N_TOTAL = .01
K_REFERENCE = .08
Z = 1.90
# Fix the point-energy, parabolic common-metric Jeans wavenumber to 0.08.
FOUR_PI_G = K_REFERENCE**4/(4*Z**3*N_TOTAL)


def vertices(torus,d,k,variant):
    """Rest-to-moving endpoint energy and number per constituent, in common real phase."""
    n=torus.size
    k=np.asarray(k)
    z=d['rest']
    _,lam,u0,_=d['cal']
    w0=d['weight']
    u0=np.sqrt(w0)*u0
    fiber=Fiber(torus,k)
    final=[]
    # The free ++ continuum is >=2, the -- continuum <=-2. The mixed sign
    # continuum is bounded by the Lipschitz constant of the one-body energy.
    max_mixed=np.linalg.norm(k,ord=1)*np.hypot(1.,32/3)
    assert max_mixed < z-.03 < z+.03 < 2.
    green_edges=[fiber.green(z+offset) for offset in (-.03,.03)]
    for contact in CONTACTS.values():
        e,u,w=pole(fiber,d,k,contact,variant)
        u=np.sqrt(w)*u*np.exp(-1j*np.angle(np.vdot(u0,u)))
        v=contact/lam + symbol(d,k,variant)
        # Every eigenvalue of G(E)-V^-1 decreases strictly between free poles.
        edge=[np.linalg.eigvalsh(g-np.linalg.inv(v)) for g in green_edges]
        assert min(np.min(abs(a)) for a in edge)>1e-4
        assert np.count_nonzero(edge[1]<0)-np.count_nonzero(edge[0]<0)==1
        s0=(BASIS@(contact@u0/lam)).reshape(4,4)
        sf=(BASIS@(v@u)).reshape(4,4)
        f_contact=np.vdot(u,(contact/lam+vertex(d,k,np.zeros(3),variant))@u0)
        final.append((e,s0,sf,f_contact))
    accum=np.zeros((2,4),dtype=complex)
    grid=torus.grid
    for lo in range(0,n,3):
        p=[g*(2*np.pi/n) for g in (grid[0][lo:lo+3],grid[1],grid[2])]
        ha,a=block(p)
        hb,b=block([-t for t in p])
        haf,af=block([t+s for t,s in zip(p,k)])
        for i,(e,s0,sf,_) in enumerate(final):
            wi=wave(s0,z,ha,a,hb,b)
            wf=wave(sf,e,haf,af,hb,b)
            accum[i]+= [np.vdot(wf,(haf+ha)@wi), np.vdot(wf,wi),
                        np.vdot(wi,wi),np.vdot(wf,wf)]
    accum/=n**3
    for i,(_,_,_,v) in enumerate(final):
        accum[i,0]+=v
    assert np.max(abs(accum.imag))<2e-10
    assert np.max(abs(accum[:,2:].real-1))<5e-4
    return (np.array([p[0]-z for p in final]),accum[:,0].real,
            accum[:,1].real)


def modes(data,k,fractions):
    gap,f,number=data
    density=N_TOTAL*np.array(fractions)
    v=np.sqrt(density*gap)*f
    D=np.diag(gap**2)-(2*FOUR_PI_G/k**2)*np.outer(v,v)
    eigen,U=np.linalg.eigh(D)
    # Choose the sign of each mode so density contact's ripple starts positive.
    U=U*np.where(U[0]>=0,1.,-1.)
    contrast=number[:,None]*np.sqrt(gap/density)[:,None]*U
    bias=2*(contrast[0,0]-contrast[1,0])/(contrast[0,0]+contrast[1,0])
    charge=v*U[:,1]
    relative_charge=abs(sum(charge))/sum(abs(charge))
    critical=1/((2*FOUR_PI_G/k**2)*np.sum(density*f*f/gap))
    assert bool(eigen[0]<0)==bool(critical<1)
    assert eigen[1]>0 and U[0,1]*U[1,1]<0
    return eigen,U,bias,relative_charge,critical


def evolve(data,k,fractions):
    """Self-consistent nonlinear three-COM-mode check, retaining the ±q potential."""
    gap,f,num=data
    density=N_TOTAL*np.array(fractions)
    eigen,U,_,_,_=modes(data,k,fractions)
    assert eigen[0]<0
    t=2.2/np.sqrt(-eigen[0])
    # A and B multiply the zero-momentum state and the even ±q combination.
    B0=np.array([.00003,0])
    fields=np.array([np.sqrt(1-B0**2),B0],dtype=complex)
    def potential(state):
        A,B=state
        rho=np.sqrt(2)*np.sum(density*f*(A.conj()*B).real)
        return -FOUR_PI_G*rho/k**2,rho
    def rhs(state):
        A,B=state
        phi,_=potential(state)
        drive=np.sqrt(2)*f*phi
        return -1j*np.array([drive*B,gap*B+drive*A])
    def energy(state):
        phi,rho=potential(state)
        return np.sum(density*gap*np.abs(state[1])**2)+phi*rho
    e0=energy(fields)
    norm0=np.sum(abs(fields)**2,axis=0)
    steps=320
    dt=t/steps
    for _ in range(steps):
        a=rhs(fields)
        b=rhs(fields+dt*a/2)
        c=rhs(fields+dt*b/2)
        dv=rhs(fields+dt*c)
        fields+=dt*(a+2*b+2*c+dv)/6
    scale=np.sqrt(gap/density)
    coeff=U.T@(B0/scale)
    linear=scale*(U@(coeff*np.array([np.cosh(t*np.sqrt(-eigen[0])),
                                     np.cos(t*np.sqrt(eigen[1]))])))
    measured=np.sqrt(2)*num*(fields[0].conj()*fields[1]).real
    prediction=np.sqrt(2)*num*linear
    err=np.max(abs(measured-prediction))/np.max(abs(prediction))
    drift=abs(energy(fields)-e0)/(np.sum(density*gap*B0**2))
    norm=np.max(abs(np.sum(abs(fields)**2,axis=0)-norm0))
    assert err<1e-6 and drift<1e-8 and norm<2e-13
    return t,measured,err,drift,norm


def run(n, extra=False):
    torus=Torus(n,Z)
    d=design(torus)
    print(f'mesh {n}, total density {N_TOTAL}, 4piG {FOUR_PI_G:.12g}')
    at0=vertices(torus,d,np.zeros(3),'common')
    assert np.max(abs(at0[0]))<1e-10 and np.max(abs(at0[1]-Z))<1e-10
    assert np.max(abs(at0[2]-1))<1e-10
    cases=[('z',np.array([0.,0.,1.]),.05,(.5,.5)),
           ('z',np.array([0.,0.,1.]),.076,(.5,.5)),
           ('xyz',np.ones(3)/np.sqrt(3),.065,(.25,.75))]
    if extra:
        cases.append(('z',np.array([0.,0.,1.]),.025,(.5,.5)))
    for axis,unit,k,fractions in cases:
        for variant in ('bare','common'):
            data=vertices(torus,d,k*unit,variant)
            eigen,vec,bias,charge,crit=modes(data,k,fractions)
            low=np.sign(eigen[0])*np.sqrt(abs(eigen[0]))
            print(f'{axis} {k:g} {fractions} {variant}:'
                  f' eps={data[0][0]:.10g},{data[0][1]:.10g}'
                  f' F={data[1][0]:.8f},{data[1][1]:.8f}'
                  f' N={data[2][0]:.8f},{data[2][1]:.8f}')
            print(f'  signed-low/high {low:.10g},{np.sqrt(eigen[1]):.10g},'
                  f' bias={bias:.7f}, relCharge={charge:.7f}, ncrit/n={crit:.7f}')
            if axis=='z' and k==.076:
                _,_,_,_,point_crit=modes((data[0],np.full(2,Z),data[2]),k,fractions)
                rod_factor=np.sum(4*np.sin(k*unit/2)**2)/k**2
                print(f'  ncrit/n for point energy {point_crit:.7f}; for lattice Poisson {crit*rod_factor:.7f}')
                assert (point_crit<1)==(crit<1)==(crit*rod_factor<1)
            if axis=='z' and k==.05:
                t,nmod,err,drift,norm=evolve(data,k,fractions)
                print(f'  time={t:.7f} fractional Fourier densities={nmod},'
                      f' relative error={err:.3g}, H drift={drift:.3g}, norm={norm:.3g}')


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--size',type=int,default=32)
    parser.add_argument('--extra',action='store_true',help='include a longer wavelength')
    args=parser.parse_args()
    run(args.size,args.extra)
live_collapse.py
"""Spherical pressureless Einstein-matter evolution and two clock-ray readouts. Standard library."""
from math import cos, exp, pi, sin, sqrt, tan

MASS=.05
RECEPTION=2.8


def profile(r, contrast):
    """M/r^3, its derivative, and 4*pi*initial proper density."""
    u=r*r
    f=1+contrast*u*(1-u)**2
    df=2*contrast*r*(1-u)*(1-3*u)
    return MASS*f, MASS*df, MASS*(3*f+r*df)


def shell(t,r,contrast):
    m3,dm3,d0=profile(r,contrast)
    tau=1/sqrt(8*m3)
    if not 0<=t<pi*tau:
        raise ValueError("outside the pre-focusing collapse branch")
    eta=t/tau/2
    for _ in range(24):
        d=(eta+sin(eta)-t/tau)/(1+cos(eta))
        eta-=d
        if abs(d)<2e-15:
            break
    s=(1+cos(eta))/2
    b=-r*dm3/(2*m3)
    f=eta+sin(eta)
    u=tan(eta/2)
    j=s+b*u*f/2
    dj=(-sin(eta)/2+b*((1+u*u)*f/2+u*(1+cos(eta)))/2)/(2*tau*s)
    v=-r*u/(2*tau)
    gamma=sqrt(1-2*m3*r*r)
    return r*s,v,j,dj,gamma,s


def fields(t,r,contrast):
    radius,v,j,dj,gamma,s=shell(t,r,contrast)
    if j<=0:
        raise ValueError("a dust shell has already crossed")
    density=profile(r,contrast)[2]/(s*s*j)
    return radius,v,j,dj,gamma,density


def midpoint_integrals(f,h):
    """Cumulative Simpson integration, including separate half-panel rules at odd nodes."""
    n=len(f)-1
    assert n%2==0
    mass=[0.]*(n+1)
    for i in range(0,n,2):
        mass[i+1]=mass[i]+h*(5*f[i]+8*f[i+1]-f[i+2])/12
        mass[i+2]=mass[i]+h*(f[i]+4*f[i+1]+f[i+2])/3
    return mass


def live_mesh(n,steps,end):
    """Update matter and geometry together; rebuild enclosed mass from current density every RHS."""
    rs=[i/n for i in range(n+1)]
    init=[profile(r,3)[2] for r in rs]
    y=[(1.,0.,1.,0.,d) for d in init]  # R/r, Rdot/r, R', Rdot', 4*pi*rho
    def masses(state):
        return midpoint_integrals([d*(r*s)**2*j for r,(s,v,j,w,d) in zip(rs,state)],1/n)
    initial_mass=masses(y)
    gamma=[sqrt(1-2*m/r) if r else 1. for r,m in zip(rs,initial_mass)]
    def baryon(state):
        return midpoint_integrals([d*(r*s)**2*j/g for r,g,(s,v,j,w,d) in zip(rs,gamma,state)],1/n)[-1]
    initial_baryon=baryon(y)
    def rate(state):
        mf=masses(state)
        ans=[]
        for r,m,(s,v,j,w,d) in zip(rs,mf,state):
            curvature=m/(r*s)**3 if r else d/3
            ans.append((v,-curvature*s,w,(2*curvature-d)*j,-d*(2*v/s+w/j)))
        return ans
    def advance(state,rates,dt):
        return [tuple(a+dt*b for a,b in zip(row,dr)) for row,dr in zip(state,rates)]
    dt=end/steps
    history=[y]
    for _ in range(steps):
        k1=rate(y)
        k2=rate(advance(y,k1,dt/2))
        k3=rate(advance(y,k2,dt/2))
        k4=rate(advance(y,k3,dt))
        y=[tuple(a+dt*(b+2*c+2*d+e)/6 for a,b,c,d,e in zip(*rows))
           for rows in zip(y,k1,k2,k3,k4)]
        history.append(y)
    mf=masses(y)
    radius_error=ms_error=density_error=0.
    for r,m,g,(s,v,j,w,d) in zip(rs,mf,gamma,y):
        radius,_,_,_,_,exact_d=fields(end,r,3)
        radius_error=max(radius_error,abs(r*s-radius))
        ms_error=max(ms_error,abs(m-(r*s/2)*(1+(r*v)**2-g*g)))
        density_error=max(density_error,abs(d-exact_d))
    # Bilinearly interpolate the time-evolved geometry and dust onto the past light cone.
    def numerical_fields(t,r,contrast):
        ix,it=min(int(r*n),n-1),min(int(t/dt),steps-1)
        u,v=r*n-ix,t/dt-it
        def value(component):
            return sum(wr*wt*history[row][col][component]
                       for col,wr in ((ix,1-u),(ix+1,u))
                       for row,wt in ((it,1-v),(it+1,v)))
        g=(1-u)*gamma[ix]+u*gamma[ix+1]
        return r*value(0),r*value(1),value(2),value(3),g,value(4)
    te,ratio,da,_=cone(end,1.,3,n*2,geometry=numerical_fields)
    _,exact_ratio,exact_da,_=cone(end,1.,3)
    return (radius_error,density_error,ms_error,abs(baryon(y)-initial_baryon),
            initial_baryon,abs(ratio-exact_ratio),abs(da-exact_da))


def rk4(fun,x,y,h):
    def stage(vec,f,step):
        return tuple(v+step*d for v,d in zip(vec,f))
    k1=fun(x,y)
    k2=fun(x+h/2,stage(y,k1,h/2))
    k3=fun(x+h/2,stage(y,k2,h/2))
    k4=fun(x+h,stage(y,k3,h))
    return tuple(v+h*(a+2*b+2*c+d)/6 for v,a,b,c,d in zip(y,k1,k2,k3,k4))


def cone(tobs,emitter,contrast,n=160,focusing_contrast=None,geometry=fields):
    """Past-directed null ray and Sachs angular-distance initial-value problem."""
    def rate(r,state):
        t,logw,dist,slope=state
        radius,_,j,dj,gamma,d=geometry(t,r,contrast)
        if focusing_contrast is not None:
            # Passive comoving density on the chosen geometry; an intentionally mismatched optical source.
            scale=radius/r if r else fields(t,1e-8,contrast)[0]/1e-8
            d=profile(r,focusing_contrast)[2]/(scale**2*j)
        w=exp(logw)
        return -j/gamma,dj/gamma,slope*j/(gamma*w),-d*w*dist*j/gamma
    state=(tobs,0.,0.,1.)
    h=emitter/n
    for i in range(n):
        state=rk4(rate,i*h,state,h)
    t,logw,dist,slope=state
    return t,exp(logw),dist,geometry(t,emitter,contrast)[0]


def crossing_at(r):
    m3,dm3,_=profile(r,3)
    tau=1/sqrt(8*m3)
    b=r*dm3/(2*m3)
    if b<=0:
        return pi*tau
    lo,hi=0.,pi
    for _ in range(52):
        eta=(lo+hi)/2
        if (1+cos(eta))>b*tan(eta/2)*(eta+sin(eta)):
            lo=eta
        else:
            hi=eta
    return tau*(eta+sin(eta))


def first_crossing():
    # The mean inside density rises only on 0<r<1/sqrt(3); there each shell has a unique crossing root.
    results=[]
    for n in (256,1024):
        grid=[i/n/sqrt(3) for i in range(n+1)]
        vals=[crossing_at(r) for r in grid]
        loc=[i for i in range(1,n) if vals[i-1]>vals[i]<vals[i+1]]
        assert len(loc)==1
        i=loc[0]
        lo,hi=grid[i-1],grid[i+1]
        for _ in range(44):
            l=(2*lo+hi)/3
            r=(lo+2*hi)/3
            if crossing_at(l)<crossing_at(r):
                hi=r
            else:
                lo=l
        r=(lo+hi)/2
        results.append((r,crossing_at(r)))
    assert abs(results[0][1]-results[1][1])<2e-13
    return results[-1]


def main():
    for contrast in (0,3):
        print("homogeneous" if contrast==0 else "redistributed")
        for r in (.55,1.):
            t,w,d,areal=cone(RECEPTION,r,contrast)
            h=1e-4
            dt=(cone(RECEPTION+h,r,contrast)[0]-cone(RECEPTION-h,r,contrast)[0])/(2*h)
            assert abs(1/dt-w)<3e-9 and abs(d-areal)<2e-9
            print(f"  r={r:.2f} emission={t:.9f} period ratio={w:.9f} D_A={d:.9f} "
                  f"Sachs error={abs(d-areal):.3g} neighboring-ray error={abs(1/dt-w):.3g}")
    t,w,d,areal=cone(RECEPTION,1.,0,focusing_contrast=3)
    print(f"mismatched passive density in Sachs equation: D_A={d:.9f}, areal={areal:.9f}")
    assert abs(d-areal)>.001
    r,t=first_crossing()
    # Avoid evaluating a singular density exactly at J=0.
    before=fields(t-1e-5,r,3)
    # The formal Jacobian alone brackets the loss of rank; no post-crossing density is evolved.
    after=shell(t+1e-5,r,3)
    m=profile(r,3)[0]*r**3
    first_focus=pi/sqrt(8*profile(1/sqrt(3),3)[0])
    assert before[2]>0>after[2] and before[0]>2*m and t<first_focus
    print(f"first crossing r={r:.8f} time={t:.9f} R={before[0]+1e-5*before[1]:.8f}"
          f"  2M/R={2*m/before[0]:.7f} earliest focusing time={first_focus:.9f}")
    for rem in (.05,.005):
        radius,v,j,dj,gamma,d=fields(t-rem,r,3)
        print(f"  time before crossing {rem}: R'={j:.8f}, 4*pi*rho={d:.6f}")
    tests=[live_mesh(n,n,RECEPTION) for n in (32,64,128)]
    for n,test in zip((32,64,128),tests):
        print(f"live grid {n}: R error={test[0]:.4g} density error={test[1]:.4g} "
              f"Misner-Sharp mismatch={test[2]:.4g} proper-mass drift={test[3]:.4g} rest mass={test[4]:.9f}"
              f" numerical-ray period and distance errors={test[5]:.3g},{test[6]:.3g}")
    assert tests[-1][0]<tests[0][0]/10 and tests[-1][1]<tests[0][1]/10
    assert tests[-1][2]<1e-8 and tests[-1][3]<1e-8
    for i in (5,6):
        assert tests[-1][i]<tests[0][i]/8 and tests[-1][i]<8e-5


if __name__=="__main__":
    main()
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 pair-transport study and compare all native Tally checks."""
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,
    "47745797b8be634dbbb667c2bc2417a34f86ce2b73db8051a64fbbb65543fe16": 195,
    "72fecb20c9f83442bcf85a0cf68b6aa1104d2edef829fd27e0ea149eae2cbe41": 192,
}
ATOM_SHA = "4c08a122480cb2d6c1efb48b9e868b5b45432d78dc40b339dbe9db7ebdacf02d"
NATIVE_CHECKS = 21

STANDARD = (
    ("fall_measurement", ()),
    ("live_collapse", ()),
    ("lapse_algebra", ()),
)
NUMERICAL = (
    ("collision_transport", ("--size", "64", "--fine")),
    ("rest_clock", ("--fine",)),
    ("extended_clock", ("--fine",)),
    ("binding_transfer", ("--fine",)),
    ("cutoff_flow", ("--fine",)),
    ("common_band", ("--fine",)),
    ("collective_gravity", ("--size", "64", "--extra")),
    ("band_audit", ("--size", "48")),
)


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 a pinned Tally runtime ZIP")
    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 / "transport.out").read_text(encoding="utf-8").splitlines()
    if len(expected) != NATIVE_CHECKS or not all(row.startswith("✓") for row in expected):
        raise ValueError("The reference transcript must contain all 21 native checks")
    with tempfile.TemporaryDirectory() as dirname:
        work = Path(dirname)
        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 / "transport.tly", work / "transport.tly")
        result = subprocess.run(
            [sys.executable, "-B", str(tally / "tally.py"), "transport.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 transport.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="path to a pinned Tally release ZIP")
    parser.add_argument("--full", action="store_true", help="run eight additional NumPy calculations at publication 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("Running", name + ".py", *options, 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.
Composite transport and free fall · 1 December 2026

Clock pulses on a resting bound pair → · Study sources (ZIP) ↓