Skip to content

What does a pair clock actually measure?

Breaking a pair and watching a pair clock tick give different frequency measurements. Two cold-atom experiments show which signals can be compared with the native model, and a three-dimensional spin rotation gives a direct test of its pair clock.

Which modulation can interrogate the pair?

Sections in this chapter

Changing the depth of a lattice can break apart an ordinary repulsively bound pair. The three sharp pair lines of the native model have a different selection rule. A spatially patterned spin rotation connects them directly. The rule follows from a symmetry of the entire many-particle Hamiltonian.

What ordinary dissociation measures

For two bosons in a one-dimensional nearest-neighbor Hubbard lattice, fix the total dimensionless wave number K. Write the relative-coordinate Hamiltonian as H=T+uP, where P=|0⟩⟨0| selects coincidence and the effective nearest-neighbor hopping is 2J cos(K/2). The unbound band extends from −W to W with W=4|J cos(K/2)|. With u≠0 the bound line is at E_b=sgn(u)√(u²+W²), with onsite weight Z=|u/E_b|. The onsite resolvent is 1/[√(z²−W²)−u], using the root asymptotic to z at infinity. Its continuum density in energy is

ρ_c(E) = √(W²−E²) / [π(u²+W²−E²)],     |E|<W .

Its integral is 1−Z. If |b⟩ is the bound eigenstate and |f⟩ an orthogonal energy eigenstate, a weak uniform modulation of both hopping and contact gives an exact matrix element. Choose ⟨0|b⟩=√Z.

δH = αT + δu P
⟨f|δH|b⟩ = (δu−αu) √Z ⟨f|0⟩ .

Thus the integrated inelastic squared matrix element is (δu−αu)² Z(1−Z). At fixed K with complete detection the ideal weak dissociation spectrum is proportional to the onsite addition continuum shifted to transition energy. Its mean gap is |E_b| because ρ_c is even. For 0<|u|<W the density has two maxima away from the band center. An observed loss peak in a mixture of momenta with a finite pulse, a trap and subsequent time evolution needs its own detection model. If the modulation simply scales H, all inelastic matrix elements vanish. At K=π the onsite state is itself an eigenstate and Z=1. These controls distinguish the drive, its initial state and its accessible transitions. Winkler and colleagues, Nature (2006)

A hidden spin rotation on the three-dimensional lattice

The native hopping symbol, in units of ε and with lattice spacing absorbed in the components of k, is

h(k) = sin kₓ cos kᵧ cos k_z σₓ + sin kᵧ cos k_z σᵧ + sin k_z σ_z .

Independent real multipliers on these three components preserve the following symmetry. On an even periodic lattice define three site signs χ_i(n) and their wave vectors Q_i by χ_i(n)=exp(i Q_i·n).

iχ_i(n)Q_i/π
x(−1)^(nₓ+n_z)(1,0,1)
y(−1)^(nₓ+nᵧ+n_z)(1,1,1)
z(−1)^nᵧ(0,1,0)

Direct substitution gives h(k+Q_i)=σ_i h(k) σ_i. Consequently the many-particle charges J_i=Σ_n χ_i(n) a†_n σ_i a_n/2 commute with the hopping as well as every scalar onsite potential or occupation-dependent contact. They satisfy [J_x,J_y]=iJ_z and its cyclic permutations since χ_xχ_y=χ_z. Exact spin symmetries with wave-vector-shifted generators also occur in persistent spin-helix systems. The wave vectors and pair selection rules here follow from the three-dimensional hopping above. Bernevig, Orenstein and Zhang, Physical Review Letters (2006)

There is an explicit site rotation g_n=(iσ_x)^(nᵧ mod 2)(iσ_z)^((nₓ+n_z) mod 2). It obeys g_n σ_i g_n†=χ_i(n)σ_i. In the rotated frame every individual hopping matrix is spin-scalar, because it commutes with all three uniform spin generators there. Scalar phases still matter. A loop using a z bond and a yz diagonal has the spin-link product σ_z σ_y σ_z σ_y=−I, so the scalar motion retains a π flux. Multiplying each native bond by its own spin-independent amplitude preserves this reduction, even for an inhomogeneous modulation.

The protected pair on axis A has onsite spin (I⊗σ_A)|singlet⟩ and staggered material wave vector K_A. For all three preparations, K_A+Q_A=(0,0,π) modulo reciprocal vectors. Rotating the native D_A into the new frame therefore gives the same spatial pair wavefunction times a Cartesian spin-one vector |A⟩. This explains their flat degeneracy. If coupling to a metric preserves the same spin symmetry, its energy shifts within a given spatial triplet must also be equal. An orientation-dependent pair tide requires an additional coupling that breaks this symmetry. The Pauli index may be an encoded internal state tied to material labels. This internal rotation is distinct from a rotation of the spacetime coordinates. A generally covariant action may couple its quadrupole to curvature and still break the internal symmetry. Only invariance of the coupling under the three internal rotations would force equal shifts.

Interconverting the clock states

Uniform changes of u, E₀ and each component hopping leave a protected pure pair in its line up to an overall phase. The statement holds at any drive strength and for every time profile that keeps these parameters spatially uniform. A dissociation scan of such a pair can give zero counts while the addition line has unit weight.

For an x-to-y comparison, apply a staggered spin-dependent energy ℏΩ(t)J_z using alternating y planes. In the rotating spin frame this is an ordinary spin rotation. In native coordinates Q_z=K_y−K_x modulo reciprocal vectors. It sends D_x to iD_y and D_y to −iD_x when applied as a generator. The evolution leaves the two-state subspace exactly invariant under the flat Hamiltonian. For constant drive duration t and a homogeneous diagonal splitting ℏδ, the transition probability is

P(x→y) = Ω²/[Ω²+δ²/4] × sin²(t√[Ω²+δ²/4]) .

At resonance a pulse area π/4 prepares an equal real superposition. Free evolution then gives ⟨J_z⟩=sin[(E_x−E_y)t/ℏ] for the sharp lines. Counting the two individual spin populations with their appropriate site signs measures the signed phase. The pair populations in the Cartesian basis alone would give an even Ramsey fringe after a reverse rotation. Choosing other material patterns gives the other axes.

A site with one atom in each of two internal states in the same lowest orbital already realizes Cartesian |z⟩ up to phase. A patterned rotation can prepare the other Cartesian orientations. For the extended sharp line an alternative source is a single coherent auxiliary molecule: a local conversion term g Σ_n b†_(n,A) m_n plus its adjoint maps a molecular wavefunction of wave vector K_A onto D_A, provided b† creates just the required normalized onsite spin triplet. Resonant conversion is then two-level in the uniform matched idealization. A spatially incoherent distribution of molecular centers populates multiple momenta. Molecular association/dissociation and spatially resolved optical-lattice spin flips have each been demonstrated. The native three-dimensional hopping, the required spin channel, phase pattern and calibrated readout remain apparatus requirements. Syassen and colleagues · Weitenberg and colleagues

What changes for a finite packet

For a common normalized onsite envelope f, the flat motion remains identical across the three gauge-rotated spins even as the pair separates. The free spin-reference visibility is unity in the model when all separations enter the readout. A readout restricted to atoms still sharing a site must account for its selection. The full addition energy centroid stays 2E₀+u. Its variance is the momentum average of

ε² [(1−cos p_z) + (1−cos pᵧ cos p_z)/2 + (1−cos pₓ cos pᵧ cos p_z)/4] ,

where p is the envelope wave vector relative to the protected momentum and the averaging measure is |f̂(p)|². This expression uses the unit native hopping multipliers. It follows by summing distinct outgoing bonds from each onsite pair: each unordered bond contributes 2|t_rs|² |f(r)−f(s)|². A single localized pair has variance 7ε²/4 and can still supply the common spin reference.

Suppose a weak orientation-dependent shift λ_A P applies only while a pair is coincident. In the rotated spin frame the two branches see H_flat+λ_A P. To first order their measured phase is (λ_x−λ_y) t_eff/ℏ with

t_eff = ∫₀ᵗ ⟨P(s)⟩_flat ds .

Site-resolved coincidence measurements in a separate flat run determine this exposure. Starting at a single site gives a uniform-in-time bound when the contact is strong. The norm of (H−2E₀−u)ψ is fixed at √7 ε/2. Writing H−2E₀−u=T−u(1−P) and using ||T||≤2ε gives 1−⟨P⟩≤[(2+√7/2) ε/u]². At |u|=20ε the exposure is at least 97.2% of the interrogation time. The homogeneous model gives a stronger bound. In each total-momentum fiber the three global π rotations about the patterned spin axes commute with H and with each other for two particles. They preserve total momentum since twice each pattern wave vector is reciprocal. The three onsite triplets have distinct triples of rotation signs. Thus the contact projector has rank one in the sector of a chosen Cartesian triplet. Its normalized contact vector has kinetic variance r_K² from the formula above. The sign (−1)^(z₁+z₂) flips every kinetic hop and fixes the contact vector, so its free spectral density is even.

For |u|>B=2ε the rank-one contact in each sector creates an isolated line outside the free band, at an energy of magnitude at least |u| relative to 2E₀. For u positive this follows by the variational bound E≥u and rank-one interlacing. The argument for negative u uses −H. Write μ for the normalized free spectral measure of the contact vector and G for the μ-average of (E−x)⁻¹. The line's weight is Z=G²/⟨(E−x)⁻²⟩. Evenness gives |G|≥1/|E|. Bounding the variance of (E−x)⁻¹ about 1/E and pairing x with −x then gives

Z⁻¹−1 ≤ c_K = r_K² (u²+B²)/(u²−B²)² .

When every c_K≤1, the contact survival amplitude in this sector has magnitude at least 2Z−1. The escape probability is bounded by 4c_K/(1+c_K)². This expression is concave on that interval. A localized pair averages all total momenta, so replacing r_K² with 7ε²/4 still gives an upper bound on escape. At |u|=20ε the resulting time exposure is at least 98.21%. This estimate assumes uniform parameters and full native hopping. A separate coincidence measurement also works when those assumptions fail.

The signed spin signal rejects every common one-particle perturbation to first order. In the rotated frame, the unperturbed real Cartesian superposition has a one-particle density of the form ρ_space(s)⊗I₂/2 throughout the interrogation. Since the flat evolution conserves J_z, the first variation of its expectation under any one-particle drive dΓ(b(s)) integrates the expectation of i[dΓ(b(s)),J_z]/ℏ. Tracing over spin gives zero, including for nonlocal, time-dependent spin-dependent hopping. A scalar contact commutes with J_z. A weak quadrupole contact can produce the signed linear response above. For two particles an upper bound on all higher terms of a common one-particle drive is exp(2a)−1−2a, where a is its time-integrated two-particle operator norm divided by ℏ. This bound follows by the nested-commutator series in the flat interaction picture and ||J_z||≤1. Preparation errors, losses, higher-order spin effects and orientation-dependent two-body strain still require controls.

A weak patterned spin pulse with relative amplitude profile w(r) transfers the fraction |Σ|f|²w|²/Σ|f|²|w|² of its transferred weight into the matched envelope. For a centered, wide Gaussian density of rms width s and an alignment error δq, the standing modulation w=cos(δq·r) gives sech(s²|δq|²) in the continuum-envelope approximation. Finite pulse area and spatial fidelity enter separately. A scalar contact Bragg perturbation with complex Fourier component q also maps an initial sharp D_A onto the onsite addition vector of the same spin at K_A+q. In the weak-drive limit momentum-resolved detection can recover its addition measure relative to the known initial energy. Real standing waves excite both signs of q, which must be resolved or modeled.

When a scalar perturbation respects the hidden spin for every applied field, the three preparations with a common spatial envelope are related by a unitary that commutes with the Hamiltonian. Their complete spectra, including profiles through a common spin-insensitive detection window, are equal. A split under matched preparation and detection would falsify that symmetry of the coupling. In contrast, the signed Ramsey signal for a general common one-particle perturbation has the specific first-order rejection derived above. A uniform off-diagonal tide carries a site-dependent sign in the hidden-spin basis. A delocalized packet averages that sign away in this readout. The diagonal frequency comparison alone does not determine the full tidal tensor.

How much time does a localized pair spend together?

Choose an interaction energy and an interrogation time. The homogeneous native model gives a lower bound on the time contributing to the pair signal.

Guaranteed contact fraction 98.21%
Minimum effective interrogation time 0.982 s

The bound assumes a pair initially on one site and the hopping and contact terms specified above. A coincidence measurement can determine the exposure directly.

Which sites stay dark, and what turns them on?

Sections in this chapter

The hidden spin symmetry gives a direct laboratory test of the underlying hopping amplitudes. A particle starts at a single site. Half the site parity classes have exactly zero arrival probability at every time. Putting a second, mobile particle on one route can turn on a specified coincidence that is forbidden in free flight.

A lattice with a measured phase around a loop

The native autonomous hopping is ε times a Pauli matrix with coefficient sin(kₓ)cos(kᵧ)cos(k_z), sin(kᵧ)cos(k_z), or sin(k_z), respectively. Energy offsets are common phases in a sector of fixed particle number. In position space the three groups connect body diagonals, yz face diagonals, and z edges. Their magnitudes are ε/8, ε/4 and ε/2. For a site labeled (x,y,z), change the internal basis by the unitary

g(x,y,z) = (iσ_x)^[y mod 2] (iσ_z)^[(x+z) mod 2] .

Every transformed hopping matrix is a real signed number times the spin identity. The two hidden spin components thus experience the same scalar hopping and the same contact interaction. Around a parallelogram formed from different bond groups, multiplying the four hopping phases gives −1. This follows directly by anticommuting the two different Pauli matrices before the change of basis. A rephasing of a single site cancels from this product. Measuring interference around a closed path tests the sign. Engineering the full model requires the particular three groups of bonds and amplitudes in addition to the loop phase.

Exact zeros in the one-particle distribution

Let Hₖᵢₙ denote the hopping Hamiltonian, and Cᵢ the average of the forward and backward unit shifts on axis i. Anticommutation eliminates the cross terms when the Hamiltonian is squared.

Hₖᵢₙ² / ε² = I − Cₓ² Cᵧ² C_z² .

Every displacement in an even power consequently has three even coordinates. An odd power has the parity of exactly one of the three bond groups. The operator exponential converges in norm, so from the origin only parity classes (0,0,0), (1,1,1), (0,1,1) and (0,0,1) can be reached, for every input spin. The result holds on the infinite lattice and on even periodic cubes; a homogeneous energy offset changes no count. It applies to this autonomous Hamiltonian. For example, the site (1,2,2) has identically zero amplitude. The two shortest paths through (1,1,1) and (0,1,1) cancel there.

A mobile particle marks one path

Start with one hidden-spin-up particle at (0,0,0) and one hidden-spin-down particle at b=(1,1,1). Resolve their internal states at the end and ask for the first at d=(1,2,2) and the second still at b. In the hidden basis each spin population is conserved, so we can follow the two species separately while retaining their Bose statistics. For u=0 this event is impossible at all times. With onsite contact energy u, the first nonzero Hamiltonian power for the joint transition is the third. Two hopping events must take the first particle to d. Between them only the path through b has a contact. The two particles travel under the full Hamiltonian, including motion of the second particle; at this leading order there are no hops left over to move it away and back.

|⟨d,b| H³ |0,b⟩| = |u| ε²/32
P(d,b;t) = u² ε⁴ t⁶/(36864 ℏ⁶) + higher powers of t .

Both expressions assume a cube large enough to keep the specified shortest paths distinct. The numerical test uses a six-site box in each direction with periodic boundaries and u=ε. At t=ℏ/ε the probability of this particular joint event is between 0.0000124341 and 0.0000124342. At t=2ℏ/ε a conservative interval is 0.0000250 to 0.0000383. The first interval corresponds to about twelve events per million ideal preparations. The program evaluates integer Hamiltonian powers and bounds the rest of the propagator with its operator norm. A free-run measurement of the same output tests for sign errors, stray hopping and readout background before using it as an interaction signal.

A scalar interaction can open this spatial interference channel while the three global hidden-spin generators remain exactly conserved. The symmetry acts jointly on spin and lattice position in the original basis. Identifying it with the rotation of a physical gyroscope, or with a universal gravitational interaction, would require a microscopic coupling and a measurement of how the material axes transform.

Which pair frequency did the experiment measure?

Sections in this chapter

Winkler and colleagues prepared rubidium-87 atom pairs in an optical lattice and measured how many remained together after driving the lattice. Changing the drive frequency produced a broad loss dip. The result gives a direct test of the energy scale for breaking up a repulsively bound pair. Winkler et al., Nature 441 (2006)

The rubidium pair-survival dip is centered at 1.592 kHz. On seven shallower settings the hopping model more closely tracks the measured loss-center frequencies after a three-point calibration.
Measured centers and survival probabilities from Winkler and colleagues. The curves and the comparison using the three deepest calibration settings were calculated for this study. Original measurement · Download the figure

Counting the surviving pairs

The apparatus used a lattice spacing of 415.22 nm and repulsive interactions with scattering length approximately 100 Bohr radii. The preparation began with chemically bound molecules on lattice sites. A magnetic-field sweep converted them into atom pairs. During spectroscopy the experimenters modulated the depth of one horizontal lattice. A final sweep converted doubly occupied sites back into molecules, removed remaining free atoms and provided a count of the surviving pairs. The lead author's thesis gives a drive duration of 40 ms and a depth-modulation amplitude of 1–4 recoil energies across the different settings. The initial states sampled a distribution of center-of-mass momenta. Original experimental account and Fig. 4 · Winkler thesis, section 3.5

The 18 plotted survival measurements near an axial depth of six recoil energies give a dip center of 1.592 kHz and a full width at half maximum of 1.395 kHz. We fitted an unweighted Gaussian with a free baseline and amplitude. Independently sampling the Gaussian drawn by the authors gives 1.593 kHz and 1.391 kHz. The Gaussian summarizes this finite-drive readout. Its width includes the range of accessible final energies and experimental broadening. An absorption line for adding a pair from the vacuum has different initial states, final states and weights.

An independent calculation of the hopping scale

Write the axial depth as s in units of the recoil energy. For an isolated sinusoidal lattice the lowest Bloch band follows from a tridiagonal matrix. Its diagonal elements are (q+2n)²+s/2, and the two neighboring off-diagonals equal −s/4. The calculation uses the measured spacing and atomic mass to convert the recoil energy to frequency. A quarter of the band width defines J for our nearest-neighbor comparison. At s=9.99 the calculation gives J/h=64.0 Hz, close to the roughly 63 Hz reported at s=10. Here h is Planck's constant. Lattice calibration and tunneling scale

At center-of-mass wave number K, the scalar one-dimensional Bose–Hubbard dimer lies an energy √[U²+16J² cos²(Ka/2)] above the midpoint of the two-particle scattering continuum. The uniform average of this expression over K gives one simple estimate of the drive resonance. It assumes equally populated momenta and the continuum midpoint. The apparatus can reweight momenta and continuum energies, and a finite drive can saturate the loss. Winkler's thesis also compares the measured resonances to this midpoint construction. Analytical pair dispersion · Comparison to the midpoint, Fig. 3.22

How much does the calibration matter?

We independently calculated U from the three separable lowest-band Wannier orbitals, using the contact interaction 4πℏ²aₛ/m. For each axis the checker integrates the fourth power of the normalized, well-centered Wannier orbital. The source accounts give two relevant transverse scales. The thesis describes the transverse lattice as approximately 30 recoil energies for spectroscopy. The preprint describes the effective one-dimensional configuration with transverse depth 35. We ran both settings without fitting a frequency scale to the data. Thesis apparatus description · Preprint geometry

Input for contact and hoppingDepths comparedRMS error for U/hRMS error for the uniform-momentum estimate
Wannier orbitals, transverse depth 30All 10101 Hz62 Hz
Wannier orbitals, transverse depth 35All 10178 Hz193 Hz
Authors' plotted U/h curve and calculated axial JAll 10128 Hz131 Hz
Contact scale calibrated on the three deepest settingsSeven shallower settings147 Hz51 Hz

For the last row, three measurements near depths 12, 14 and 16 set one constant multiplier, 0.9100, on the authors' plotted U/h curve. We kept both that multiplier and the calculated J fixed at the seven remaining depths. The comparison is a retrospective split of one experiment. The RMS errors describe the plotted center positions and do not include calibration covariances. The changing ranking across transverse depths shows why interpreting a loss dip as a direct estimate of the microscopic contact energy requires independent calibration.

What the public data establish

The two-particle measurements demonstrate a frequency-dependent breakup process whose energy scale changes with the lattice depth. They did not prepare the three spin-correlated pair channels of the proposed clock, compare their complete pair-addition spectra or apply a measured gravitational tide. A claimed value for their differential tidal coefficient cannot be extracted from these data.

The table contains 18 survival points, ten resonance centers, the displayed error limits and the theoretical U/h ordinate at those ten depths. The thesis identifies the error limits as 95% confidence intervals for the authors' Gaussian center fits. We calibrated coordinates against the labeled ticks of the authors' original Fig. 4 vector file. Marker placement and rounding during export limit coordinate accuracy to approximately 0.02 recoil energies in depth and a few hertz in frequency. No shot counts or unpublished numerical archive are assumed. The checker verifies the arXiv source archive and figure checksums and can reconstruct the numerical table using the Python standard library. The original paper and artwork remain with their authors and publisher. The figure in this study is a new plot of the attributed numerical measurements and our recalculation. Original figure source, arXiv v1

What an experimental pair clock actually measures

Sections in this chapter

Hartke and colleagues placed two potassium-40 atoms in each occupied well of a deep optical lattice. The atoms formed spin singlets. Their clock encoded two excitations of vertical motion, shared either one per atom or both on one atom in an exchange-symmetric state. The researchers drove interactions magnetically, converted one motional component to molecules and counted the other by fluorescence. This compares two states of a pair already present. The native bosonic proposal prepares a pair from the vacuum with specified total crystal momentum. These preparations address different spectra. Hartke et al., Nature (2022) · Experimental methods and Hamiltonian

Recovering the frequencies from the measured populations

The first two source workbooks include bright-site counts at 58 times near the recoil gap and 33 times near the molecular regime, along with a separate series of six calibrated interaction drives. The archived table preserves all of these measured points and their spreads. For the Ramsey traces the calculation fits an offset plus a sinusoid. Three separated sampling windows in the slow trace share a frequency and phase, with an independent offset and positive amplitude in each window to allow the contrast to decay. We give each point equal weight. The reported population spreads come from two or three repetitions, and three tabulated slow-trace spreads vanish. The descriptive residuals below are in bright sites. Figure 2 source workbook · Figure 3 source workbook

MeasurementTabulated pointsFrequency from these countsReported pair frequencyRMS count residual
Near zero interaction58140.772 Hz140.76 ± 0.03 Hz6.29
Near molecular binding3334.341 kHz36.00 ± 0.03 kHz13.76

The slow fit searches 115–165 Hz, with the early window resolving the frequency region before the long delays sharpen the fit. The fast fit searches 2–100 kHz over the tabulated 1–97 μs window. Its separate publisher-supplied fit curve has peaks about 27.78 μs apart, or 36.0 kHz. The 33 plotted counts and our undamped fit therefore do not independently recover the stated fast frequency to its quoted precision. The tabulated spread, contrast changes, and fitting protocol matter when using a few oscillations to calibrate a clock. The study also reported 0.300(10) s of bare Ramsey coherence near the recoil gap. Longer echo and continuously driven coherence times use different control sequences and filter a static applied signal differently. Ramsey protocol and observable

What is calibrated by changing the interaction?

At weak interaction the two relative oscillator configurations acquire energy shifts U and U/2. Their combinations form the recoil eigenstates. In that basis the off-diagonal matrix element is U/4, so a resonant sinusoidal interaction change of amplitude ΔU predicts a Rabi frequency ΔU/(4h) in the rotating-wave regime. The six measured drive frequencies range from 1.774 to 47.422 Hz. A least-squares line through the origin gives measured frequency equal to 0.9439 times the calculated drive frequency. The individual ratios range from 0.882 to 0.961. The experimental calculation of the horizontal axis uses measured trap frequencies, the magnetic modulation and scattering properties. Fitted frequency error bars by themselves omit uncertainty in that calibration. This measurement tests access to a two-body transition matrix element by modulating a real interaction. It does not determine the absolute vacuum-to-pair addition energy or a gravitational coupling.

A trap-shape check at three depths

At the same tabulated field of 209.0937721 G, close to the scattering zero, the experiment measured a pair gap at three trap depths. We used the first value alone to calibrate a one-dimensional sinusoidal potential of fixed spatial period and predicted the remaining two. The trap frequency column gives cycles per second, with angular frequency ωz=2π times that value. Errors in the measured-gap column are the published sinusoidal fit errors.

Axial frequency ωz/(2π)Measured gap in HzFixed-period well prediction in Hz
25.09 ± 0.04 kHz140.76154 ± 0.03232140.76154, calibration
38.50 ± 0.01 kHz138.30458 ± 0.07232140.13231
51.8 ± 0.1 kHz137.37842 ± 0.08452139.83403

The model uses a common recoil frequency r and the sinusoidal depth V in units of recoil energy, with ωz/(2π)=2r√V. It computes the three lowest energies of the single-particle zero-crystal-momentum Hamiltonian by Fourier expansion and tridiagonal eigenvalue bracketing. At these deep settings the splitting tested is 2E₁−E₂−E₀. Calibrating the first depth gives r=138.98469 Hz. The numerical answer is stable on increasing the Fourier cutoff from 60 to 76 on each side.

Doubling the confinement frequency changes the measured gap by 3.383 Hz, about 2.40%. The fixed-period model predicts a change of 0.928 Hz. The two stronger confinements therefore give direct checks on transferring a one-depth calibration. The experimental trap combines two reflected beams, and the quoted vertical frequency and its relation to a single ideal sinusoid are inputs to this comparison. The gap data establish that the pair frequency is much less sensitive to depth than the single-particle level spacing. They leave the source of the remaining depth dependence unidentified.

Changing optical depth alters both harmonic curvature and higher-order coefficients in the trap potential. A weak gravitational tide added while the optical depth is held fixed is a different perturbation. For the ideal harmonic orbitals the two recoil eigenstates have equal sums of one-particle second moments despite different contact amplitudes. An absolute pair energy, an optical-drive matrix element, and a material mass quadrupole require their own measurement models. The published experiment had no switched gravitational source.

The offline table contains numerical cells from the authors’ two source workbooks. The calibration checker refits the two traces, tests the six drive settings, and recomputes the three trap-depth predictions. Its optional --fetch mode verifies both original workbook fingerprints, compares every archived table entry, and checks the independent fit curve.

Which mass distribution would a tidal field see?

Sections in this chapter

The potassium clock measures a frequency associated with two atoms sharing a trap. The large difference between their common and relative motion raises a precise question. Would a gravity gradient split those motions? A harmonic calculation gives a null result. The first nonzero change of the recoil gap depends on the shape of the confining potential. Hartke et al., Nature (2022)

Conditional pair size and total mass

Let ℓ=√(ℏ/mω) be the axial oscillator length. Write |A⟩=|1,1⟩ and |B⟩=(|2,0⟩+|0,2⟩)/√2 using each atom's oscillator occupation. The exchange-symmetric parts describe the spatial states of a spin-singlet pair. The two superpositions (|B⟩±|A⟩)/√2 put the two oscillator quanta fully in the center-of-mass mode or fully in the relative mode. Their reduced one-particle states are identical. In either state, measuring one atom gives occupation 0, 1 or 2 with probabilities 1/4, 1/2 and 1/4. The phase distinguishing the states belongs to the pair.

There is a large change in separation. The mean square of x₁−x₂ is ℓ² in the excited center-of-mass state and 5ℓ² in the excited relative state. With R=(x₁+x₂)/2, the sum 2⟨R²⟩+⟨(x₁−x₂)²⟩/2 equals 3ℓ² for both. A minimal Newtonian tide couples to the second moment of the entire mass distribution. Assigning the relative separation alone as its quadrupole would predict a shift that the harmonic model forbids.

A pair-sensitive measurement at nonzero wave number can distinguish these states. Define the unnormalized density intensity I(q)=⟨|exp(iqx₁)+exp(iqx₂)|²⟩ and z=(qℓ)². Measuring single-atom positions alone gives equal profiles for the two superpositions. Measuring both positions in the same trial also gives their correlation. The predicted difference is

I_COM(q)−I_rel(q) = 2 exp(−z/2)(2z−z²/2).

It is 3 exp(−1/2) at qℓ=1 and zero at qℓ=2. This follows by evaluating the characteristic function of the harmonic relative oscillator in occupations 0 and 2. The figure of merit is the repeatable change upon preparing the other state. Such a measurement would constrain conditional size. A gravitational measurement would still require its own source field and energy calibration.

What a real source could couple to

Consider instead the one-body Fourier operator exp(iqx₁)+exp(iqx₂), projected on the |A⟩, |B⟩ subspace. Its off-diagonal matrix element vanishes because one operation cannot change the occupations of both atoms. Its diagonal difference is

F_B(q)−F_A(q) = exp(−z/4) z²/8 .

Consequently the uniform and quadratic terms have identical matrix elements on the two states, and a quadratic tidal perturbation acts as a multiple of the identity on the entire pair subspace. This conclusion includes coherent superpositions. A fourth spatial derivative of the imposed potential can give a differential signal. In the center-of-mass and relative-motion basis the same Fourier difference appears in an off-diagonal matrix element. Coherence and population measurements access different matrix elements of the same operator.

Curvature added independently of the light field

The optical confinement itself contains a quartic term. At zero interaction the positive recoil gap is Δ=2e₁−e₀−e₂ in terms of the one-atom trap energies. To leading order for a deep sinusoidal lattice well of depth V₀ and wave number k, the potential is mω²x²/2−V₀k⁴x⁴/3 with ω²=2V₀k²/m. The difference of the quartic moments gives Δ=V₀k⁴ℓ⁴=ℏ²k²/(2m).

Hold the light field fixed and apply an additional weak Hessian G=∂²Φ/∂x². It changes ω² to ω²+G while leaving the optical quartic coefficient fixed. To this order the gap becomes Δ(G)=Δ(0)/(1+G/ω²). Changing the lattice intensity changes both coefficients together. These two operations have distinct derivatives even when the unperturbed frequency has been precisely measured.

For a numerical scale, use ω/(2π)=25.09 kHz and Δ(0)/h=140.76 Hz from the potassium clock. Suppose an additional local axial Hessian were independently calibrated to 205 Eötvös, the order of the separately measured Birmingham field modulation. The ideal sinusoidal-well expression gives an ordinary clock change of about −1.16×10⁻¹⁵ Hz. The angular frequency in the denominator includes 2π. This estimate refers to the small residual conventional shift in the harmonic-null potassium model. The two experiments did not apply that field to that clock. The optical-depth comparison in the experimental chapter provides a check on the accuracy of this ideal well. Potassium pair clock · Measured gravity-gradient scale

Two traps with equal gaps and opposite curvature slopes

The ambiguity can be exhibited without attaching an arbitrary gravitational charge to either atom. Work in units ℏω=ℓ=1 before adding the curvature g=G/ω². Give the atoms the same harmonic well plus Bx⁴+Cx⁶. The pair-gap matrix elements of the quadratic, quartic and sextic terms are respectively zero, −3 and −45/2. If the measured unperturbed gap is δ, the combination B=−δ/3, C=0 reproduces it to first order. The combination B=−5δ/3, C=8δ/45 gives the same gap. Under the added curvature the quartic contribution scales as (1+g)⁻¹ and the sextic contribution as (1+g)⁻³ᐟ². The two predicted slopes are −δ and +δ.

For an independent numerical check, use a common box with walls at seven oscillator lengths, solve the one-dimensional Schrödinger equation and fit B in each well to the same gap 0.003. On an 840-cell grid the two gaps agree to better than 2×10⁻⁹. Their derivatives with respect to g are −0.00299 and +0.00315. A second grid preserves both signs. The finite walls keep the full potential bounded below, including in the example with a negative quartic coefficient. This is a pair of calibration examples. The measured potassium apparatus would require its actual beam geometry and independent control of the added curvature.

A measurement with independently varied, calibrated harmonic curvature at fixed lattice intensity would determine this conventional susceptibility. A pair measurement in a genuine gravitational field would then be needed to separate that contribution from any extra two-particle coupling to spacetime curvature.

Can short Ramsey measurements recover a full spectral centroid?

Sections in this chapter

A breakup experiment counts a transition to a detectable final state. A pair-addition spectrum also includes the weight that stays in the original line. The hidden-spin protocol in this study measures a particular differential shift directly. For a general prepared state, a separate interference measurement can recover its full energy centroid to a quantified accuracy using just two evolution times.

Two times and a known energy interval

Let p(E) denote the normalized spectral weights of the prepared state, measured relative to a calibrated reference energy. Suppose |E|≤B for every populated state. Prepare a coherent reference arm and a signal arm, let the signal evolve, and measure both quadratures of C(t)=∫exp(−iEt/ℏ)p(E)dE. If pair number differs between the arms, a physical phase reference and a coherent particle reservoir are required. An internal ancilla can instead compare two evolutions at fixed particle number if its reference evolution is known. Counting surviving pairs alone does not supply these complex amplitudes.

Set S(t)=−Im C(t). The two-time estimate and its error bound are

μ₂(t) = ℏ[8 S(t)−S(2t)]/(6t)
|μ₂(t)−⟨E⟩| ≤ B⁵ t⁴/(30 ℏ⁴).

For a single energy let x=Et/ℏ. The derivative of x−[8sin(x)−sin(2x)]/6 is 2(1−cos x)²/3. Integrating and using 1−cos x≤x²/2 proves the bound, then averaging preserves it. This estimate includes unresolved lines because the reference sees the whole prepared state. Missing particles, unequal readout contrast across final states, and uncertainty in B require separate calibration.

If individual quadrature readouts have outcomes ±1 with unit contrast, N independent trials at the two times have an estimator standard deviation at most 3ℏ/(2t√N) when allocated in the ratio 8:1. Short interrogation suppresses the deterministic error and increases sampling noise. The reference energy should be subtracted before applying the bandwidth bound. In the native two-boson sector at u≥0 the simple choice of reference 2E₀+u/2 gives B≤2ε+u/2 by the norm bounds on the hopping and contact. A known narrower state-specific energy interval improves the estimate.

Why two time samples are still insufficient for an unrestricted spectrum

Take a positive distribution with support at dimensionless energies π/6, −π/3 and π/2 and relative weights 1, 1 and (√3−1)/2. Reflect all three energies to obtain a second distribution with the same weights. Their two complex amplitudes C(t) and C(2t) agree exactly. Their cosines agree by reflection, and their weighted sines vanish at both times. All energies satisfy |Et/ℏ|≤π/2. Their centroids differ by a positive amount about 0.0434ℏ/t. Finite, phase-resolved samples therefore give a bounded estimate under the bandwidth assumption. They do not identify an arbitrary spectral distribution or its centroid exactly. The example is an identifiability test on the class of spectral measures; it makes no assumption that these three artificial lines describe either atom experiment.

Which spin transport keeps an onsite pair sharp?

Sections in this chapter

The native model carries a two-component spinor along each hopping bond. Its exact three-class degeneracy changes in a calculable way if that transport is altered. The following test works on a finite connected bipartite graph. It includes a cubic lattice with the native axial and diagonal links, whose endpoints always have opposite z parity.

A sum of squared mismatches

Orient each undirected bond n→m once. Give it a real nonzero hopping coefficient t_mn and a spin matrix U_mn in SU(2). Reverse hopping uses the Hermitian adjoint. A minus sign or a central spin-link phase −I is allowed. A general electromagnetic link phase would give the pair its own doubled phase and needs a separate treatment. The onsite one-particle energy E₀ and two-particle contact energy u are uniform and spin independent.

Specify an onsite two-boson state by complex symmetric 2×2 matrices T_n with Σ tr(T_n†T_n)=1. Its creation operator is Σ T_n,ab a†_na a†_nb/√2. Hopping can only put the two particles on distinct endpoints of a bond. On the bond n→m the separated spin amplitude, in endpoint order m,n, is √2 t_mn [U_mn T_n + T_m U_mn*]. The two terms describe the two possible initial sites. Distinct bonds end in orthogonal configurations. The cancellation criterion is therefore

T_m = −U_mn T_n U_mnᵀ   on every bond.

Choose the bipartite sign s_m=−s_n on adjacent vertices and write T_n=s_n X_n. Congruence by U is a real three-dimensional rotation R(U) in the Cartesian triplet basis. Writing x_n for the three complex coordinates of X_n gives the exact energy centroid and variance in this prepared state.

⟨H⟩ = 2E₀+u
Var(H) = 2 Σ_{n→m} t_mn² ||x_m − R(U_mn)x_n||² .

The norm uses the full complex spin vector. The factor two comes from the normalized bosonic creation operators. A pure onsite energy eigenstate exists precisely when the variance vanishes. The formula applies to the complete pair-addition spectrum. Losses, finite sampling and any frequency window enter the experimental measurement separately.

Transport around closed paths

Fix a root and a spanning tree. A state of zero variance is determined by transporting its root spin along the tree. Each remaining edge closes a loop. The product W of its link matrices in path order, with inverses on reversed links, must fix the root vector under R(W). A local change of spin basis conjugates every root loop by the same rotation, so the dimension of their common fixed space is independent of basis.

Every nonidentity rotation in SO(3) fixes one axis. There are exactly three possible dimensions for the space of sharp onsite pair preparations. It has dimension three when every root loop lies in the SU(2) center, dimension one when the rotations have precisely one common fixed direction, and dimension zero when they have none. An axis carried to its negative fails the condition for a fixed vector. In particular, two half-turns about orthogonal axes commute in SO(3) and have no common fixed vector. The native π-flux loop has W=−I, which drops out of U X Uᵀ and preserves all three pairs.

A finite spectroscopy witness

Take six sites in a two-by-three ladder. Choose the three vertical rungs and the two bottom horizontal bonds as the tree; set their links to I. The two top links then encode the two independent loop rotations. Give every bond unit hopping magnitude |t|. A central sign on a top link leaves three sharp channels. Two quarter-turns about z leave only the z channel. A quarter-turn about z on one top link and a quarter-turn about x on the other leave none.

In the last example the equal-amplitude staggered x, y and z inputs have variances (2/3, 4/3, 2/3)t². Allowing an arbitrary spin texture across the six sites reduces the minimum but cannot restore a sharp line. The accompanying checker constructs the 18×18 real quadratic form in the variance above. Exact rational elimination brackets its lowest eigenvalue between (673/4096)t² and (1347/8192)t². Independent two-particle spinor hopping reproduces the same variance formula for nonuniform hopping weights and arbitrary complex textures. All three examples have the same energy centroid. The distinction is in the oscillator-strength distribution across energies.

How to interpret a measured loop

The link matrices are directly meaningful for a synthetic spin transport calibrated on the bonds. To interpret them geometrically, one must specify a spatial metric, its orthonormal frames and a physical spin that follows its parallel transport. The spatial Levi-Civita connection is constrained by metric compatibility and zero torsion. Its small-loop rotations measure spatial rotational curvature. A freely tunable internal spin matrix, an externally driven pulse and the temporal tidal curvature entering geodesic deviation implement distinct operations. A connection built from the metric supplies the additional identification, which can then be checked with both one-particle transport and pair spectra.

Reading the loop back from the spectrum

Choose a spanning tree and prepare the same unit vector v at its root, transported along the tree, with equal probability on all V sites. One remaining link, of hopping amplitude t, closes a loop with net rotation of angle θ about axis n. Its contribution to the energy variance is 4|t|²(1−cos θ)(1−|n·v|²)/V. Varying that hopping while holding the other link matrices fixed isolates its contribution. Summing three Cartesian input variances then gives 8|t|²(1−cos θ)/V for the isolated link. Measurements along additional diagonal axes can recover the axis projector. The orientation sign and the central spinor sign are invisible to this spin-one measurement. This is a proposed loop calibration using energy-distribution widths.

A pair carried around a genuinely curved space

Sections in this chapter

A synthetic spin rotation on a bond is a useful control. To ask whether an actual spatial metric can produce the same obstruction, specify a metric and transport its vectors around the lattice paths. A static space with positive uniform curvature supplies an exactly calculable example.

Two closed paths through native bonds

Give the spatial slice the geometry of a three-sphere of radius R. Choose a small patch and identify the material directions at its center with an orthonormal tangent frame. The native graph has hop directions b₁=(1,1,1), b₂=(0,1,1), b₃=(0,0,1) in units of the unstrained site spacing a. Map the reference sites in the patch to the sphere by following the geodesic whose initial tangent points to each site. Use the short great-circle arc for every link. These choices specify the embedding and bond path.

Consider the quadrilateral with reference vertices 0, b, b+d, d, 0. Its image lies in a totally geodesic two-sphere. Parallel transport around it fixes the normal to the tangent plane spanned by b and d. Within the plane it rotates by the oriented spherical area divided by R². An independent computation uses the exact short-arc transport rule on the unit sphere: for an initial tangent v, the final vector at q is v−(p+q)(v·q)/(1+p·q). Composing these maps and independently adding the two spherical triangle areas give the same angle magnitude.

The b₁,b₂ loop has fixed axis proportional to (0,−1,1). The b₂,b₃ loop has fixed axis (1,0,0). At a/R=0.1 their rotation angles are 0.0141185 and 0.00999165 radians. Both loops start at the same vertex. Since their fixed axes have zero intersection as vector spaces, the graph has no nonzero parallel triplet on any connected patch containing both loops. Even a small positive curvature destroys the exact, purely onsite eigenvector in this particular transport model. A nonzero energy variance in a chosen preparation does not imply a change of its complete frequency centroid.

Which gravitational assumption enters?

Here we explicitly identify the triplet with a physical tangent-vector representation and use the spin lift of the torsion-free metric connection on the links. The original flat dispersion and the potassium data do not impose that identification. A material pseudospin carried by fixed local labels can instead keep a trivial internal connection. This comparison exhibits two well-defined extensions with the same flat clock and different curved responses.

For further separation, use the product spacetime with line element −c²dt² plus the round spatial metric. Its time-space tidal components R₀ᵢ₀ⱼ vanish in the static frame. The spatial loop rotations above remain. This is a prescribed geometry with spatial curvature; a theory predicting the geometry from material energy would need a field equation and a source. The Birmingham experiment measured a different quantity, a laboratory gradient of relative acceleration. It supplies neither the rotation angles in this example nor a measurement of the triplet's linewidth.

Programs and transcript

The offline study archive contains eight calculation programs, data tables from the two cold-atom experiments, a plotting script and 20 native Tally assertions. The replay compares the full Tally transcript. Both experimental chapters link to the original sources and give instructions for independent reconstruction.

Complete Tally transcript
✓ a pi flux cancels the shortest free amplitude at the selected detector  (by cross-pairing plus and minus sides; derived)
✓ one mobile spectator activates the cubic-time joint amplitude  (by cross-pairing plus and minus sides; derived)
✓ the first probability coefficient for the contact-assisted coincidence  (by cross-pairing plus and minus sides; derived)
✓ the uniform lower bound on contact exposure exceeds 98.21 percent  (by cross-pairing plus and minus sides; derived)
✓ common scaling of hopping and contact gives no Hubbard dimer dissociation amplitude  (by cross-pairing plus and minus sides; derived)
✓ an incoherent breakup scan loses the entire exact protected line at Z equal one  (by cross-pairing plus and minus sides; derived)
✓ a uniform harmonic tide shifts both pair levels equally at first order  (by cross-pairing plus and minus sides; derived)
✓ quartic and sextic moments in the recoil doublet  (by cross-pairing plus and minus sides; derived)
✓ equal recoil gaps admit opposite slopes when a separate curvature is applied  (by cross-pairing plus and minus sides; derived)
✓ relative pair-correlation contrast has a finite-wavevector null at q ell equal two  (by cross-pairing plus and minus sides; derived)
✓ the common one-body form-factor doublet first differs at fourth order in q  (by cross-pairing plus and minus sides; derived)
✓ compensating center-of-mass and relative widths preserve the whole mass moment  (by cross-pairing plus and minus sides; derived)
✓ two pulse durations remove the cubic spectral bias  (by cross-pairing plus and minus sides; derived)
✓ eight-to-one shot allocation minimizes the upper bound on Ramsey sampling variance  (by cross-pairing plus and minus sides; derived)
✓ shallow and deep rubidium breakup centers lie on opposite sides of the plotted contact curve  (by cross-pairing plus and minus sides; derived)
✓ at the common zero crossing two deeper traps have independently measured smaller gaps  (by cross-pairing plus and minus sides; derived)
✓ two calibrated loops give different widths to transverse and parallel triplets  (by cross-pairing plus and minus sides; derived)
✓ three Cartesian input widths determine the cosine of an isolated right-angle loop  (by cross-pairing plus and minus sides; derived)
✓ the rational matrix bracket resolves a positive minimum over all prepared onsite textures  (by cross-pairing plus and minus sides; derived)
✓ the two native geodesic loops rotate about independent axes  (by cross-pairing plus and minus sides; derived)
Native Tally source
# Native Tally checks on the measured operator, exact dark routes and pair clocks.
ratchet 32 step
import "atom"
let zero=whole(0 trial)
let one=whole(1 trial)
let two=whole(2 trial)
let three=whole(3 trial)
let four=whole(4 trial)
let eight=whole(8 trial)
let half=fraction(1 trial,2 trial)

# Two two-hop paths to (1,2,2), in units epsilon/8. Only the first has an intermediate contact.
let first=one*two
let second=flip(two)*one
let contact=eight
check first+second==zero and first*second<zero "a pi flux cancels the shortest free amplitude at the selected detector"
let cubic=first*contact
check cubic==whole(16 trial) and share(cubic,whole(6 trial)*power(eight,3 trial))==fraction(1 trial,192 trial) "one mobile spectator activates the cubic-time joint amplitude"
check power(fraction(1 trial,192 trial),2 trial)==fraction(1 trial,36864 trial) "the first probability coefficient for the contact-assisted coincidence"

# Variance bound for a localized pair; free support |T| <= 2 epsilon and u=20 epsilon.
let u=whole(20 trial)
let band=two
let r2=fraction(7 trial,4 trial)
let coeff=share(r2*(u*u+band*band),power(u*u+flip(band*band),2 trial))
let exposure=one+flip(share(four*coeff,power(one+coeff,2 trial)))
check coeff>zero and coeff<one and exposure>fraction(9821276 trial,10000000 trial) and exposure<fraction(9821277 trial,10000000 trial) "the uniform lower bound on contact exposure exceeds 98.21 percent"
let reservoir=whole(5 trial)
let scale=fraction(3 trial,7 trial)
let mismatch=scale*reservoir+flip(scale*reservoir)
check mismatch==zero "common scaling of hopping and contact gives no Hubbard dimer dissociation amplitude"
let Z=fraction(3 trial,5 trial)
check Z*(one+flip(Z))==fraction(6 trial,25 trial) and one*(one+flip(one))==zero "an incoherent breakup scan loses the entire exact protected line at Z equal one"

# One and two body form factors on harmonic occupations zero, one and two.
let c0=half
let c1=fraction(3 trial,2 trial)
let c2=fraction(5 trial,2 trial)
check two*c1==c0+c2 "a uniform harmonic tide shifts both pair levels equally at first order"
let fourth=two*fraction(15 trial,4 trial)+flip(fraction(3 trial,4 trial))+flip(fraction(39 trial,4 trial))
let sixth=two*fraction(105 trial,8 trial)+flip(fraction(15 trial,8 trial))+flip(fraction(375 trial,8 trial))
check fourth==flip(three) and sixth==flip(fraction(45 trial,2 trial)) "quartic and sextic moments in the recoil doublet"
let b0=flip(fraction(1 trial,3 trial))
let b1=flip(fraction(5 trial,3 trial))
let sextic=fraction(8 trial,45 trial)
let delta0=fourth*b0
let delta1=fourth*b1+sixth*sextic
let slope1=flip(fourth*b1)+flip(fraction(3 trial,2 trial)*sixth*sextic)
check delta0==one and delta1==one and slope1==one and flip(delta0)==flip(one) "equal recoil gaps admit opposite slopes when a separate curvature is applied"
fn corr(z)
  return four*z+flip(z*z)
end
check corr(one)==three and corr(four)==zero "relative pair-correlation contrast has a finite-wavevector null at q ell equal two"
let z=one
let formA=two+flip(z)
let formB=two+flip(z)+share(z*z,eight)
check formB+flip(formA)==fraction(1 trial,8 trial) "the common one-body form-factor doublet first differs at fourth order in q"
check fraction(5 trial,2 trial)+half==three and half+fraction(5 trial,2 trial)==three "compensating center-of-mass and relative widths preserve the whole mass moment"

# The five-point derivative has the nonnegative exact kernel 2(1-cos x)^2/3.
let cosx=fraction(3 trial,5 trial)
let cos2=two*cosx*cosx+flip(one)
let derivative=one+flip(share(eight*cosx+flip(two*cos2),whole(6 trial)))
check derivative==fraction(2 trial,3 trial)*power(one+flip(cosx),2 trial) "two pulse durations remove the cubic spectral bias"
let shot=share(share(whole(64 trial),eight)+one,whole(36 trial))*whole(9 trial)
check shot==fraction(9 trial,4 trial) "eight-to-one shot allocation minimizes the upper bound on Ramsey sampling variance"

# Independently digitized resonance controls, in millionths of a kilohertz.
let first_peak=whole(1462247 trial)
let first_u=whole(1332736 trial)
let last_peak=whole(1844482 trial)
let last_u=whole(2085238 trial)
check first_peak+flip(first_u)==whole(129511 trial) and last_peak+flip(last_u)==flip(whole(240756 trial)) "shallow and deep rubidium breakup centers lie on opposite sides of the plotted contact curve"
# Published potassium workbook, equal magnetic field, values in 10^-7 Hz.
let low=whole(1407615409 trial)
let mid=whole(1383045826 trial)
let high=whole(1373784238 trial)
check low+flip(mid)==whole(24569583 trial) and low+flip(high)==whole(33831171 trial) "at the common zero crossing two deeper traps have independently measured smaller gaps"

# Two orthogonal closed paths, each inducing a quarter turn on a Cartesian triplet.
let sites=whole(6 trial)
let mismatch_sq=two
let one_loop=share(two*mismatch_sq,sites)
check one_loop==fraction(2 trial,3 trial) and two*one_loop==fraction(4 trial,3 trial) "two calibrated loops give different widths to transverse and parallel triplets"
let sum_width=zero+one_loop+one_loop
check sum_width==share(eight,sites) "three Cartesian input widths determine the cosine of an isolated right-angle loop"
let min_l=fraction(673 trial,4096 trial)
let min_h=fraction(1347 trial,8192 trial)
check min_h+flip(min_l)==fraction(1 trial,8192 trial) and min_l>fraction(16 trial,100 trial) "the rational matrix bracket resolves a positive minimum over all prepared onsite textures"
# Native primitive loops have tangent-area normals (0,-1,1) and (1,0,0).
let dot_axes=zero*one+flip(one)*zero+one*zero
check dot_axes==zero and zero*zero+flip(one)*flip(one)+one*one==two "the two native geodesic loops rotate about independent axes"
probe.py
"""Check the patterned spin charges, finite packet moments and phase exposure."""
from itertools import product
from math import cos, exp, pi, sin, sqrt

I = [[1,0],[0,1]]
S = ([[0,1],[1,0]], [[0,-1j],[1j,0]], [[1,0],[0,-1]])
Q = ((1,0,1), (1,1,1), (0,1,0))
K = ((1,0,0), (1,1,0), (0,1,1))


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


def kron(a,b):
    return [[a[i][k]*b[j][l] for k in range(len(a)) for l in range(len(b))]
            for i in range(len(a)) for j in range(len(b))]


def scale(x,a):
    return [[x*q for q in row] for row in a]


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


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


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


def adj(a):
    return [[v.conjugate() for v in col] for col in zip(*a)]


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


def signs(n):
    return [(-1)**sum(x*y for x,y in zip(n,q)) for q in Q]


def gauge(n):
    gx = scale(1j,S[0]) if n[1]%2 else I
    gz = scale(1j,S[2]) if (n[0]+n[2])%2 else I
    return mm(gx,gz)


def hopping(k):
    x,y,z = k
    dx,dy,dz = sin(x)*cos(y)*cos(z), sin(y)*cos(z), sin(z)
    return [[dz,complex(dx,-dy)],[complex(dx,dy),-dz]]


def test_charges():
    for n in product(range(2),repeat=3):
        g = gauge(n)
        chi = signs(n)
        assert chi[0]*chi[1] == chi[2]
        for j in range(3):
            assert maxdiff(mm(mm(g,S[j]),adj(g)),scale(chi[j],S[j])) == 0
            assert tuple((q+k)%2 for q,k in zip(Q[j],K[j])) == (0,0,1)
        for delta in product((-1,0,1),repeat=3):
            x,y,z=delta
            if z==0 or (x!=0 and y==0):
                continue
            j = 0 if x else (1 if y else 2)
            step = tuple(r+d for r,d in zip(n,delta))
            link = mm(mm(adj(gauge(step)),S[j]),g)
            assert link[0][1] == link[1][0] == 0 and link[0][0] == link[1][1]
    loop=mm(mm(S[2],S[1]),mm(S[2],S[1]))
    assert maxdiff(loop,scale(-1,I))==0
    for k in ((.21,.43,-.35),(1.2,-2.14,.912),(-1.3,-.88,2.77)):
        for j in range(3):
            shifted=tuple(v+pi*q for v,q in zip(k,Q[j]))
            assert maxdiff(hopping(shifted),mm(mm(S[j],hopping(k)),S[j]))<1e-14


class Fiber:
    """Distinguishable-coordinate representation restricted by the symmetric input."""
    def __init__(self,total,L=4):
        self.L = L
        self.grid = list(product(range(L),repeat=3))
        self.index = {k:i for i,k in enumerate(self.grid)}
        self.total = tuple(t%L for t in total)
        self.dim = len(self.grid)
        self.blocks = []
        for k in self.grid:
            p = [2*pi*x/L for x in k]
            pp = [2*pi*(t-x)/L for t,x in zip(total,k)]
            self.blocks.append(add(kron(hopping(p),I),kron(I,hopping(pp))))

    def start(self,a):
        v = mv(kron(I,S[a]),[0,1/sqrt(2),-1/sqrt(2),0])
        return [[z/sqrt(self.dim) for z in v] for k in self.grid]

    def contact_vec(self,state):
        return [s/self.dim for s in map(sum,zip(*state))]

    def probability(self,state):
        v = self.contact_vec(state)
        return self.dim*inner(v,v).real

    def H(self,state,u):
        center = [u*x for x in self.contact_vec(state)]
        return [[x+y for x,y in zip(mv(block,v),center)]
                for block,v in zip(self.blocks,state)]

    def step(self,state,u,dt):
        result = [v.copy() for v in state]
        term = state
        for n in range(1,13):
            term = [[(-1j*dt/n)*z for z in row] for row in self.H(term,u)]
            result = [[a+b for a,b in zip(l,r)] for l,r in zip(result,term)]
        return result

    def charge_z(self,state):
        shift = [q*self.L//2 for q in Q[2]]
        Lz,Rz = kron(S[2],I),kron(I,S[2])
        out = []
        for i,k in enumerate(self.grid):
            ki = self.index[tuple((x-q)%self.L for x,q in zip(k,shift))]
            out.append([(a+b)/2 for a,b in zip(mv(Lz,state[ki]),mv(Rz,state[i]))])
        return out


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


def energy_variance(p):
    x,y,z = p
    return 1-cos(z)+(1-cos(y)*cos(z))/2+(1-cos(x)*cos(y)*cos(z))/4


def test_finite_packets():
    L=4
    for a in range(3):
        for p in [(0,0,0),(0,1,0),(1,2,-1)]:
            k = [p0+L*q//2 for p0,q in zip(p,K[a])]
            fiber = Fiber(k,L)
            start = fiber.start(a)
            action = fiber.H(start,0.)
            answer = energy_variance([2*pi*j/L for j in p])
            assert abs(overlap(action,action).real-answer)<2e-14
    mean_square = sum(energy_variance([2*pi*j/L for j in k])
                      for k in product(range(L),repeat=3))/L**3
    assert abs(mean_square-7/4)<1e-14
    bound = 1-((2+sqrt(7)/2)/20)**2
    assert .9723<bound<.9725
    return bound


def test_phase():
    # A finite wavepacket component is deliberately off the protected point, so
    # its common spatial state develops a substantial non-contact amplitude.
    L,p = 4,(0,1,0)
    fibers = [Fiber([L*q//2+n for q,n in zip(K[a],p)],L) for a in (0,1)]
    dt,steps,u = .04,20,1.3
    def propagate(delta):
        a,b = (f.start(j) for j,f in enumerate(fibers))
        probabilities = [fibers[0].probability(a)]
        for _ in range(steps):
            a = fibers[0].step(a,u+delta/2,dt)
            b = fibers[1].step(b,u-delta/2,dt)
            probabilities.append(fibers[0].probability(a))
        # J_z connects total momenta differing by pi e_y. Cross term of the
        # normalized equal superposition is the signed staggered magnetization.
        coherence = overlap(b,fibers[0].charge_z(a))
        assert abs(overlap(a,a).real-1)<1e-12
        return coherence,probabilities
    flat,probs = propagate(0)
    assert abs(flat-1j)<1e-12 and min(probs)<.8
    integral = dt/3*(probs[0]+probs[-1]+4*sum(probs[1:-1:2])+2*sum(probs[2:-1:2]))
    change = .0002
    sample,_ = propagate(change)
    opposite,_ = propagate(-change)
    slope = (sample.real-opposite.real)/(2*change)
    assert abs(slope-integral)<2e-7
    return integral,slope,min(probs)


def test_dissociation():
    # Evaluate the one-dimensional contact resolvent discontinuity using
    # E=W cos(theta), avoiding both endpoint singularities.
    for u,W in ((3.,4.),(-2.,1.5),(1.,2.)):
        Eb = sqrt(u*u+W*W)
        Z = abs(u)/Eb
        n=2000
        weights,energies = [],[]
        for j in range(n):
            angle = pi*(j+.5)/n
            s = (W*sin(angle))**2
            weights.append(s/((u*u+s)*n))
            energies.append(W*cos(angle))
        assert abs(sum(weights)-(1-Z))<2e-14
        assert abs(sum(g*(Eb-E) for E,g in zip(energies,weights))/sum(weights)-Eb)<3e-14
        alpha,du = .13,-.27
        # Infinite-chain exact normalized bound state, truncated only after
        # the endpoints are exponentially small. Direct variation and projection.
        U = abs(u)
        ratio = (U-Eb)/W * (1 if u>0 else -1)
        bound=[sqrt(Z)*ratio**abs(j) for j in range(-200,201)]
        bound_E = Eb*(1 if u>0 else -1)
        out=[]
        for i,z in enumerate(bound):
            hop = -W/2*((bound[i-1] if i else 0)+(bound[i+1] if i+1<len(bound) else 0))
            contact=z if i==200 else 0
            assert abs(hop+u*contact-bound_E*z)<1e-14
            out.append(alpha*hop+du*contact)
        assert abs(inner(out,out)-abs(inner(bound,out))**2-(du-alpha*u)**2*Z*(1-Z))<1e-14


def test_isolated_weight():
    B,u = 2.,20.
    def c_of(r2):
        return r2*(u*u+B*B)/(u*u-B*B)**2
    def escape(c):
        return 4*c/(1+c)**2
    for p in [(0,0,0),(0,1,0),(0,0,2),(1,1,1)]:
        a,L = 0,4
        f = Fiber([L*q//2+n for q,n in zip(K[a],p)],L)
        v = f.start(a)
        term = v
        moments=[]
        for n in range(25):
            moment=overlap(v,term)
            assert abs(moment.imag)<1e-12*2**n
            moments.append(moment.real)
            if n%2:
                assert abs(moment)<1e-13*2**n
            term=f.H(term,0.)
        # Neumann expansion at E>=20 has geometric remainder <=(1/10)^25/18.
        def resolvent(E):
            return sum(mu/E**(j+1) for j,mu in enumerate(moments))
        lo,hi=u,u+B
        for _ in range(55):
            mid=(lo+hi)/2
            if u*resolvent(mid)>1:lo=mid
            else:hi=mid
        E=(lo+hi)/2
        norm=sum((j+1)*mu/E**(j+2) for j,mu in enumerate(moments))
        Z=1/(u*u*norm)
        assert abs(u*resolvent(E)-1)<1e-13
        assert 1/Z-1<=c_of(moments[2])+1e-13
        assert 4*Z*(1-Z)<=escape(c_of(moments[2]))+1e-13
    answer=1-escape(c_of(7/4))
    assert .98212<answer<.98214
    return answer


def test_one_particle_rejection():
    # A two-site, two-spin symmetric spatial pair with a zero-dipole triplet.
    # Choose a common pulse with genuinely spin-dependent nonlocal matrix elements.
    from random import Random
    rng=Random(139)
    random=[[complex(rng.uniform(-1,1),rng.uniform(-1,1)) for _ in range(4)] for _ in range(4)]
    b=scale(.5,add(random,adj(random)))
    id4=kron(I,I)
    drive=add(kron(b,id4),kron(id4,b))
    j=scale(.5,kron(I,S[2]))
    total_j=add(kron(j,id4),kron(id4,j))
    mot=kron([[.1,.5],[.5,-.4]],I)
    H0=add(kron(mot,id4),kron(id4,mot))
    for k in range(16):
        if (k//4)//2==(k%4)//2:
            H0[k][k]+=1.7
    cart=[mv(kron(I,s),[0,1/sqrt(2),-1/sqrt(2),0]) for s in S]
    spin=[(a+c)/sqrt(2) for a,c in zip(cart[0],cart[1])]
    spatial=[[1,complex(.2,.3)],[complex(.2,.3),-.4]]
    norm=sqrt(sum(abs(z)**2 for row in spatial for z in row))
    start=[spatial[i//2][j//2]*spin[2*(i%2)+j%2]/norm for i,j in product(range(4),repeat=2)]
    def readout(eta):
        H=add(H0,scale(eta,drive))
        out=start.copy()
        term=start.copy()
        for k in range(1,45):
            term=[-.7j*v/k for v in mv(H,term)]
            out=[x+y for x,y in zip(out,term)]
        assert abs(inner(out,out)-1)<1e-13
        return inner(out,mv(total_j,out)).real
    eta=.001
    flat,plus,minus=readout(0),readout(eta),readout(-eta)
    first=(plus-minus)/(2*eta)
    curvature=(plus+minus-2*flat)/eta**2
    # Second-order contamination is deliberately nonzero for the chosen drive.
    assert abs(flat)<1e-14 and abs(first)<1e-6 and abs(curvature)>.005
    return first,curvature


if __name__ == "__main__":
    test_charges()
    bound=test_finite_packets()
    gate,phase,minimum=test_phase()
    test_dissociation()
    print("Three exact spin charges, scalar hopping links and pi-flux loop: passed")
    print("Finite packet variance and scalar Hubbard oscillator strengths: passed")
    print(f"Flat staggered-spin visibility 1, minimum contact {minimum:.7f}")
    print(f"Weak phase slope {phase:.9f}, integrated flat coincidence {gate:.9f} in a 0.8 exposure")
    print(f"Uniform localized-pair exposure bound for |u|/epsilon=20: {bound:.8f}")
    print(f"Rank-one bound from the even spectral measure: {test_isolated_weight():.8f}")
    slope2,curv = test_one_particle_rejection()
    print(f"Common one-body drive test: finite-difference slope {slope2:.3g}, second derivative {curv:.6f}")
flux.py
"""Exact signed graph and two-particle Taylor moments for the native hopping."""
from collections import defaultdict
from fractions import Fraction as F
from itertools import product
from math import factorial, sqrt

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


def mm(A,B):return tuple(tuple(sum(x*y for x,y in zip(row,col)) for col in zip(*B)) for row in A)
def scale(s,A):return tuple(tuple(s*x for x in row) for row in A)
def adj(A):return tuple(tuple(x.conjugate() for x in col) for col in zip(*A))


def gauge(pos):
    x,y,z=pos
    return mm(scale(1j,X) if y%2 else I,scale(1j,Z) if (x+z)%2 else I)


def graph(L):
    sites=list(product(range(L),repeat=3))
    lookup={p:i for i,p in enumerate(sites)}
    bonds=[]
    for sx,sy,sz in product((1,-1),repeat=3):bonds.append(((sx,sy,sz),scale(1j*sx,X)))
    for sy,sz in product((1,-1),repeat=2):bonds.append(((0,sy,sz),scale(2j*sy,Y)))
    for sz in (1,-1):bonds.append(((0,0,sz),scale(4j*sz,Z)))
    links=[]
    for p in sites:
        out={}
        for d,mat in bonds:
            target=tuple((a+b)%L for a,b in zip(p,d))
            turn=mm(adj(gauge(target)),mm(mat,gauge(p)))
            weight=int(turn[0][0].real)
            assert turn==scale(weight,I) and abs(weight) in (1,2,4)
            out[lookup[target]]=weight
        links.append(out)
    assert all(links[y][x]==v for x,row in enumerate(links) for y,v in row.items())
    return sites,lookup,links


def flux_test():
    sites,idx,links=graph(6)
    zero=idx[(0,0,0)]
    moves=[(1,1,1),(0,1,1),(0,0,1)]
    for i,b in enumerate(moves):
        for d in moves[:i]:
            along_b,along_d=idx[b],idx[d]
            both=idx[tuple(u+v for u,v in zip(b,d))]
            assert links[zero][along_b]*links[along_b][both]==-links[zero][along_d]*links[along_d][both]
    norm=lambda p: tuple(x%2 for x in p)
    sectors={(0,0,0),(1,1,1),(0,1,1),(0,0,1)}
    state={zero:1}
    for t in range(1,13):
        new=defaultdict(int)
        for i,v in state.items():
            for j,h in links[i].items():new[j]+=h*v
        state={i:v for i,v in new.items() if v}
        assert all(norm(sites[i]) in sectors for i in state)
        if t%2==0:assert all(norm(sites[i])==(0,0,0) for i in state)
    return sites,idx,links


def two_particle_moments(idx,links,N=20):
    # Hidden spin distinguishes the two components. H is stored in integer units epsilon/8.
    V=len(links)
    p=idx[(0,0,0)];b=idx[(1,1,1)];d=idx[(1,2,2)]
    def step(state):
        new=defaultdict(int)
        for i,v in state.items():
            x,y=divmod(i,V)
            for nx,h in links[x].items():new[nx*V+y]+=h*v
            for ny,h in links[y].items():new[x*V+ny]+=h*v
            if x==y:new[i]+=8*v
        return {i:v for i,v in new.items() if v}
    def overlap(a,b):
        if len(a)>len(b):a,b=b,a
        return sum(v*b.get(i,0) for i,v in a.items())
    initial,final={p*V+b:1},{d*V+b:1}
    m=[overlap(final,initial)]
    for _ in range((N+1)//2):
        initial=step(initial)
        m.append(overlap(final,initial))
        final=step(final)
        m.append(overlap(final,initial))
    assert m[:3]==[0,0,0] and abs(m[3])==16
    return m[:N+1]


def bounds(m,t):
    # Entire tail bounded in norm by the exponential tail, ||H/epsilon||<=3.
    real,imag=F(0),F(0)
    for n,value in enumerate(m):
        a=F(value)*F(t,8)**n/factorial(n)
        if n%4==0:real+=a
        if n%4==1:imag-=a
        if n%4==2:real-=a
        if n%4==3:imag+=a
    begin=len(m)
    tail=F(3*t)**begin/factorial(begin)/(1-F(3*t,begin+1))
    # Integer-safe check on each conservative probability range printed below.
    amp=sqrt(float(real*real+imag*imag))
    return max(0,amp-float(tail))**2,(amp+float(tail))**2


def main():
    sites,idx,links=flux_test()
    m=two_particle_moments(idx,links)
    print("Three pi-flux plaquettes and four excluded parity classes verified.")
    print("Scaled contact-assisted matrix element of H cubed:",m[3])
    for t in (1,2):
        lo,hi=bounds(m,t)
        assert lo>0 and hi-lo<.001
        print(f"tau={t}, one specified joint output probability in [{lo:.10g}, {hi:.10g}]")
    print("First integer matrix moments:",m[:8])


if __name__=="__main__":
    main()
echo.py
"""Two-time spectral centroid bound and an exact nonuniqueness witness."""
from cmath import exp
from math import cos, pi, sin, sqrt


def correlation(x,w,t):
    return sum(a*exp(-1j*e*t) for e,a in zip(x,w))/sum(w)


def main():
    a=(sqrt(3)-1)/2
    energies=[pi/6,-pi/3,pi/2]
    weights=[1.,1.,a]
    reflected=[-x for x in energies]
    for t in (1,2):
        assert abs(correlation(energies,weights,t)-correlation(reflected,weights,t))<5e-16
    gap=2*sum(x*w for x,w in zip(energies,weights))/sum(weights)
    assert .043<gap<.045
    for i in range(-400,401):
        x=i/60
        f=(8*sin(x)-sin(2*x))/6
        assert abs(f-x)<=abs(x)**5/30+2e-15
        assert abs(1-(8*cos(x)-2*cos(2*x))/6-2*(1-cos(x))**2/3)<1e-14
    values=[-1.6,-.35,.8,1.9]
    prob=[.14,.28,.48,.10]
    mean=sum(x*w for x,w in zip(values,prob))
    for t in [.1,.2,.4]:
        answer=(-8*correlation(values,prob,t).imag+correlation(values,prob,2*t).imag)/(6*t)
        assert abs(answer-mean)<=max(map(abs,values))**5*t**4/30
    print("Indistinguishable correlations at two times, centroid difference:",gap)
    print("Bounded estimator, pointwise derivative and finite-distribution checks passed.")


if __name__=="__main__":
    main()
curvature.py
"""Pair density, finite-q correlations and fixed-trap curvature calibration."""
from math import exp, pi, sqrt


def anharmonic_gap(B, C, g, cells):
    # Energies in hbar*omega, length in the zero-field oscillator length.
    # Dirichlet walls at ±7 are identical in both calibrated wells.
    boundary = 7.
    dx = 2*boundary/cells
    hop = -.5/dx**2
    sites = [-boundary+j*dx for j in range(1,cells)]
    diagonal = [-2*hop+.5*(1+g)*y*y+B*y**4+C*y**6 for y in sites]

    def count(energy):
        pivot, below = diagonal[0]-energy,0
        below += pivot < 0
        for v in diagonal[1:]:
            if abs(pivot)<1e-20:
                pivot = -1e-20
            pivot = v-energy-hop*hop/pivot
            below += pivot<0
        return below

    def eigen(n):
        low, high = -.5,4.
        assert count(low)==0 and count(high)>n
        for _ in range(47):
            mid = (low+high)/2
            if count(mid)>n:
                high=mid
            else:
                low=mid
        return (low+high)/2
    return 2*eigen(1)-eigen(0)-eigen(2)


def matched_well(C,cells,delta=.003):
    lo,hi = -.018,.002
    # Stay on the central-well branch for C=0 (no remote minima inside the walls).
    if C==0:lo=-.003
    assert anharmonic_gap(lo,C,0,cells)>delta>anharmonic_gap(hi,C,0,cells)
    for _ in range(30):
        mid = (lo+hi)/2
        if anharmonic_gap(mid,C,0,cells)>delta:lo=mid
        else:hi=mid
    B=(lo+hi)/2
    step=.001
    gap=anharmonic_gap(B,C,0,cells)
    slope=(anharmonic_gap(B,C,step,cells)-anharmonic_gap(B,C,-step,cells))/(2*step)
    return B,gap,slope


def moments():
    # Dimensionless powers of x/ell obtained directly with oscillator ladder operators.
    def moment(n,power):
        vector={n:1.}
        for _ in range(power):
            out={}
            for level,c in vector.items():
                out[level+1]=out.get(level+1,0.)+c*sqrt((level+1)/2)
                if level:
                    out[level-1]=out.get(level-1,0.)+c*sqrt(level/2)
            vector=out
        return vector.get(n,0.)
    for p,want in [(2,0),(4,-3),(6,-45/2)]:
        got=2*moment(1,p)-moment(0,p)-moment(2,p)
        assert abs(got-want)<1e-12
    # Normalized COM and relative pair states in the single-particle oscillator basis.
    A={(1,1):1.}
    B={(2,0):1/sqrt(2),(0,2):1/sqrt(2)}
    states=[{(i,j):(A.get((i,j),0)+sign*B.get((i,j),0))/sqrt(2)
             for i in range(3) for j in range(3)} for sign in (-1,1)]
    def reduced(s):
        return [sum(s[i,j]*s[k,j] for j in range(3)) for i in range(3) for k in range(3)]
    assert reduced(states[0])==reduced(states[1])
    # Relative-coordinate intensity and one-body diagonal/off-diagonal responses.
    def diff_correlation(z):return 2*exp(-z/2)*(2*z-z*z/2)
    assert diff_correlation(4)==0 and diff_correlation(1)>1.81
    z=1.
    F_B=exp(-z/4)*(2-z+z*z/8)
    F_A=exp(-z/4)*(2-z)
    assert abs(F_B-F_A-exp(-z/4)*z*z/8)<1e-15


def main():
    moments()
    delta=.003
    results=[]
    for cells in (420,840):
        pair=[matched_well(C,cells,delta) for C in (0.,8*delta/45)]
        assert all(abs(gap-delta)<2e-9 for B,gap,slope in pair)
        assert pair[0][2]<-.002 and pair[1][2]>.001
        results.append(pair)
    # The leading central-difference grid error is quadratic in the spacing.
    extrap=[(4*results[1][i][2]-results[0][i][2])/3 for i in range(2)]
    assert max(abs(extrap[i]-results[1][i][2]) for i in range(2))<.00015
    fz,fr,G=25090.,140.76,205e-9
    shift=-fr*G/(2*pi*fz)**2
    assert -1.17e-15<shift<-1.15e-15
    print("Both fitted gaps on 840-cell grid:",[round(x[1],10) for x in results[1]])
    print("Fitted quartic coefficients:",[round(x[0],8) for x in results[1]])
    print("Curvature slopes, 420 / 840 cells:",[[round(x[2],8) for x in p] for p in results])
    print("Leading ideal recoil-clock change at an illustrative 205 E:",shift,"Hz")


if __name__=="__main__":
    main()
winkler.py
"""Read the authors' EPS plotting coordinates and replay their spectroscopic controls."""
import argparse
import csv
from io import BytesIO, StringIO
from hashlib import sha256
from pathlib import Path
from statistics import mean
from math import cos, exp, log, pi, sqrt
from tarfile import open as open_tar
from urllib.request import urlopen


HERE = Path(__file__).resolve().parent
DATA = HERE / 'winkler-figure4.csv'
SOURCE = 'https://arxiv.org/src/cond-mat/0605196v1'
SOURCE_SHA = '3e17a2e477200480360e08a7a8dfe51a6cd5f14af40eeda45dce6c223a36802f'
EPS_SHA = 'ecc88c55d4e363f64a6a0ce3e104881680ee11f3ac79e02c3d28b0563b1e2e19'
NAMES = ['series', 'x', 'y', 'lower_kHz', 'upper_kHz', 'published_U_over_h_kHz']


def checked(data, digest):
    if sha256(data).hexdigest() != digest:
        raise ValueError('Source file checksum mismatch')
    return data


def interpolate(xs, x):
    for (x1,y1),(x2,y2) in zip(xs,xs[1:]):
        if x1 <= x <= x2:
            return y1+(y2-y1)*(x-x1)/(x2-x1)
    raise ValueError('Coordinate outside the interpolated range')


def extract(eps):
    page = checked(eps, EPS_SHA).decode('latin1').split('%%EndPageSetup',1)[1]
    objects = page.split('@rax')[1:]

    def vertices(i):
        return [(float(t[-3]),float(t[-2])) for line in objects[i].splitlines()
                if (t:=line.split()) and t[-1] in ('m','C','l','L','c')]

    def circle(i):
        assert '0.00 0.99 0.95 0.00 k' in objects[i] and objects[i].count(' C')==4
        x1,y1,x2,y2 = map(float,next(l for l in objects[i].splitlines()
                                  if l.endswith(' @E')).split()[:4])
        return (x1+x2)/2,(y1+y2)/2

    def axis(ticks, idx, labels):
        xs = [vertices(i)[0][idx] for i in ticks]
        xavg,yavg = mean(xs),mean(labels)
        slope = sum((x-xavg)*(y-yavg) for x,y in zip(xs,labels))/sum((x-xavg)**2 for x in xs)
        f = lambda x: yavg+slope*(x-xavg)
        assert max(abs(f(x)-y) for x,y in zip(xs,labels)) < .007
        return f

    ax=axis((69,71,73,75),0,(0,1,2,3))
    ay=axis((77,79,82,85,88,91),1,(0,.2,.4,.6,.8,1))
    bx=axis((3,5,7,9),0,(0,5,10,15))
    by=axis((11,13,16,18,21,23),1,(0,.5,1,1.5,2,2.5))

    rows=[]
    def add(series,*numbers):
        rows.append([series]+[f'{x:.6f}' for x in numbers]+['']*(5-len(numbers)))

    for i in range(94,112):
        x,y=circle(i)
        add('survival',ax(x),ay(y))
    drawn=[(ax(x),ay(y)) for x,y in vertices(112)]
    _,center,sigma,_,_=gaussian_fit(drawn)
    assert abs(center-1.59287)<.00002
    assert abs(2*sqrt(2*log(2))*sigma-1.39127)<.00002
    curve=sorted((bx(x),by(y)) for x,y in vertices(38))
    bars=vertices(27)
    assert len(bars)==60
    errorbars=[]
    for i in range(0,len(bars),6):
        x,y=bars[i+4]
        ex,ey=bars[i+5]
        assert abs(bx(x)-bx(ex))<.001
        errorbars.append((bx(x),min(by(y),by(ey)),max(by(y),by(ey))))
    for x,y in sorted(circle(i) for i in range(40,50)):
        depth,freq=bx(x),by(y)
        xb,lo,hi=min(errorbars,key=lambda b:abs(b[0]-depth))
        assert abs(xb-depth)<.025 and abs(freq-(lo+hi)/2)<.004
        add('resonance',depth,freq,lo,hi,interpolate(curve,depth))
    f=StringIO()
    w=csv.writer(f,lineterminator='\n');w.writerow(NAMES);w.writerows(rows)
    return f.getvalue().encode()


def gaussian_fit(points):
    """Least squares over center and log width; baseline and amplitude solved linearly."""
    x,y=zip(*points)
    def fit(mu,sigma):
        p=[exp(-.5*((t-mu)/sigma)**2) for t in x]
        p0,y0=mean(p),mean(y)
        amp=sum((v-p0)*(d-y0) for v,d in zip(p,y))/sum((v-p0)**2 for v in p)
        b=y0-amp*p0
        residual=sum((b+amp*z-w)**2 for z,w in zip(p,y))
        return residual,mu,sigma,b,amp
    mu,ls,step_mu,step_ls=1.6,log(.6),.2,.2
    for _ in range(9):
        r=min(fit(mu+i*step_mu,exp(ls+j*step_ls)) for i in range(-3,4) for j in range(-3,4))
        _,mu,sigma,_,_=r;ls=log(sigma);step_mu/=3;step_ls/=3
    return r


def energy(q,depth,cut=9):
    """Lowest eigenvalue of the sinusoidal-lattice plane-wave tridiagonal (recoil units)."""
    diag=[(q+2*i)**2+depth/2 for i in range(-cut,cut+1)]
    off2=(depth/4)**2
    lo,hi=0.,min(diag)+1e-8
    for _ in range(54):
        mid=(lo+hi)/2
        d=diag[0]-mid
        count=int(d<0)
        for t in diag[1:]:
            if abs(d)<1e-20:d=-1e-20
            d=t-mid-off2/d
            count+=int(d<0)
        if count:hi=mid
        else:lo=mid
    return (lo+hi)/2


def wannier_overlap(depth, mesh=21, cut=6):
    """Integral |w|^4 in the dimensionless coordinate kL*x; positive Bloch gauge."""
    # Odd symmetric q mesh, localized at the potential minimum. Fourier convolution
    # integrates the quartic exactly on the finite periodic mesh.
    coeff=[0.0]*((2*cut+1)*mesh)
    off=-depth/4
    for j in range(-(mesh//2),mesh//2+1):
        q=2*j/mesh
        e=energy(q,depth,cut)
        diag=[(q+2*n)**2+depth/2-e+.02 for n in range(-cut,cut+1)]
        dl=diag[:]
        for k in range(1,len(dl)):
            dl[k]-=off**2/dl[k-1]
        v=[float(n==cut) for n in range(len(dl))]
        for _ in range(7):
            for k in range(1,len(dl)):
                v[k]-=off*v[k-1]/dl[k-1]
            v[-1]/=dl[-1]
            for k in range(len(dl)-2,-1,-1):
                v[k]=(v[k]-off*v[k+1])/dl[k]
            norm=sqrt(sum(x*x for x in v));v=[x/norm for x in v]
        resid=max(abs((diag[k]-.02)*x+off*((v[k-1] if k else 0)+(v[k+1] if k+1<len(v) else 0))) for k,x in enumerate(v))
        assert resid<2e-10
        for n,x in enumerate(v):
            coeff[n*mesh+j+mesh//2]=x/(mesh*sqrt(pi))
    assert abs(mesh*pi*sum(x*x for x in coeff)-1)<1e-12
    conv=[0.]*(2*len(coeff)-1)
    for i,x in enumerate(coeff):
        for j,y in enumerate(coeff):
            conv[i+j]+=x*y
    return mesh*pi*sum(x*x for x in conv)

def compare(rows):
    dip=[(float(r['x']),float(r['y'])) for r in rows if r['series']=='survival']
    _,center,sigma,b,amp=gaussian_fit(dip)
    h=6.62607015e-34
    m=86.9091805291*1.66053906892e-27
    a=415.22e-9
    recoil_kHz=h/(8*m*a*a)/1000
    data=[]
    for r in rows:
        if r['series']!='resonance':continue
        depth,obs,lo,hi,u=map(float,[r[k] for k in NAMES[1:]])
        j=recoil_kHz*(energy(1,depth)-energy(0,depth))/4
        def center_model(n):
            return mean(sqrt(u*u+(4*j*cos(pi*(i+.5)/(2*n)))**2) for i in range(n))
        model=center_model(64)
        assert abs(model-center_model(128))<1e-12
        data.append((depth,obs,lo,hi,u,j,model))
    assert len(dip)==18 and len(data)==10
    rms=lambda vals:sqrt(mean(v*v for v in vals))
    print(f'Dip fit from 18 points: center {center:.5f} kHz, FWHM {2*sqrt(2*log(2))*sigma:.5f} kHz, survival floor {b+amp:.4f}.')
    print('depth  observed  lower95  upper95   U/h      J/h   uniform-K (frequencies kHz)')
    for row in data:print(' '.join(f'{z:8.4f}' for z in row))
    for nm,ds in [('all',data),('shallow',data[:4]),('deep',data[-4:])]:
        er_u=rms([z[1]-z[4] for z in ds]);er_k=rms([z[1]-z[6] for z in ds])
        print(nm, 'RMS vs U/h and uniform-K gap (kHz):',f'{er_u:.6f}, {er_k:.6f}')
    comparisons = scale_controls(data,recoil_kHz,a)
    assert abs(center-1.59229)<.00005 and abs(2*sqrt(2*log(2))*sigma-1.39462)<.0001
    assert rms([r[1]-r[4] for r in data])>.12
    return data,comparisons


def midpoint(u,j):
    return mean(sqrt(u*u+(4*j*cos(pi*(k+.5)/128))**2) for k in range(64))


def scale_controls(data,recoil_kHz,a):
    # as=100 Bohr, 87Rb. Bare single-band contact, no fit to spectral positions.
    prefactor=8*pi*(pi/a)*(100*5.29177210544e-11)*recoil_kHz
    alpha=sum(r[4]*r[1] for r in data[-3:])/sum(r[4]**2 for r in data[-3:])
    assert abs(alpha-.9100268)<.00001
    print(f'Three-deepest-point contact scale: {alpha:.6f}')
    reference=(.101021,.061742),(.177843,.193349),(.146552,.051468)
    overlaps=[wannier_overlap(r[0]) for r in data]
    assert abs(overlaps[0]-wannier_overlap(data[0][0],31,8))<1e-6
    assert abs(wannier_overlap(35)-wannier_overlap(35,31,8))<1e-6
    outputs={}
    for index,key in enumerate(('30 Er transverse','35 Er transverse','deep-calibrated')):
        use=data if index<2 else data[:-3]
        transverse=wannier_overlap(30 if index==0 else 35) if index<2 else 0
        predictions=[]
        for i,row in enumerate(use):
            u=(prefactor*transverse**2*overlaps[i] if index<2 else alpha*row[4])
            predictions.append((row[0],row[1],u,midpoint(u,row[5])))
        errors=tuple(sqrt(mean((p[1]-p[j])**2 for p in predictions)) for j in (2,3))
        assert all(abs(p-q)<.000005 for p,q in zip(errors,reference[index]))
        print(key, f'RMS against U/h and uniform-K gap (kHz): {errors[0]:.6f}, {errors[1]:.6f}')
        outputs[key]=predictions
    return outputs


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--fetch',action='store_true',help='check original arXiv source and extract Fig. 4')
    args=parser.parse_args()
    if args.fetch:
        with urlopen(SOURCE,timeout=60) as f:raw=checked(f.read(),SOURCE_SHA)
        with open_tar(fileobj=BytesIO(raw),mode='r:gz') as f:
            eps=f.extractfile('figure4.eps').read()
        if extract(eps)!=DATA.read_bytes():raise ValueError('Extracted table changed')
    with DATA.open(newline='') as f:compare(list(csv.DictReader(f)))


if __name__=='__main__':
    main()
calibration.py
"""Refit Hartke et al. source data and test a fixed-period optical-well calibration."""
import argparse
import csv
from hashlib import sha256
from io import BytesIO, StringIO
from math import cos, pi, sin, sqrt
from pathlib import Path
from statistics import mean
from urllib.request import urlopen
import xml.etree.ElementTree as ET
from zipfile import ZipFile

ROOT = Path(__file__).resolve().parent
DATA = ROOT / "pair_clock.csv"
MEDIA = ("https://media.springernature.com/full/springer-static/esm/"
         "art%3A10.1038%2Fs41586-021-04205-8/MediaObjects/41586_2021_4205_MOESM")
HASHES = [
    "ed84ec255ab0568d013bc608fcb3671bf755e867d17586a08736e909dfc73c44",
    "5fd8adb4c55b806a3ab6c2a7d828624c9b37826560b4485653d46483a2bf58e0",
]
TAG = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}"
SETS = [
    ("drive_Hz", 0, 3), ("slow_ms", 1, 1), ("fast_us", 1, 3),
    ("25.09kHz", 1, 7), ("38.50kHz", 1, 9), ("51.80kHz", 1, 11),
]


def extract(inputs):
    output = StringIO()
    writer = csv.writer(output, lineterminator="\n")
    writer.writerow(["series","x","y","spread","drive_mG"])
    for label, book, sheet in SETS:
        with ZipFile(BytesIO(inputs[book])) as archive:
            root = ET.fromstring(archive.read(f"xl/worksheets/sheet{sheet}.xml"))
        for row in root.iter(TAG+"row"):
            # Column A is the source dataframe index. Columns B-E contain data.
            cells = {c.get("r").rstrip("0123456789"): c.findtext(TAG+"v")
                     for c in row.findall(TAG+"c") if c.get("t") != "s"}
            if cells.get("B") is not None:
                writer.writerow([label, cells["B"], cells["C"], cells["D"], cells.get("E","")])
    return output.getvalue().encode()


def fetch():
    inputs = []
    for i, expected in enumerate(HASHES,1):
        with urlopen(f"{MEDIA}{i}_ESM.xlsx",timeout=40) as response:
            data = response.read()
        if sha256(data).hexdigest() != expected:
            raise ValueError(f"Source Data Fig. {i+1} fingerprint changed")
        inputs.append(data)
    # Independently identify the frequency of the *plotted fit curve*. Its densely
    # sampled points differ from the 33 observations passed to our estimator.
    with ZipFile(BytesIO(inputs[1])) as archive:
        root = ET.fromstring(archive.read("xl/worksheets/sheet4.xml"))
    curve = []
    for row in root.iter(TAG+"row"):
        vals = {c.get("r").rstrip("0123456789"): c.findtext(TAG+"v")
                for c in row.findall(TAG+"c") if c.get("t") != "s"}
        if vals.get("B") is not None:
            curve.append((float(vals["B"]),float(vals["C"])))
    peaks=[t for i,(t,y) in enumerate(curve[1:-1],1)
           if curve[i-1][1] < y > curve[i+1][1]]
    rate=(len(peaks)-1)*1e6/(peaks[-1]-peaks[0])
    assert len(peaks)==4 and 35950<rate<36050
    print(f"Publisher fast-fit curve: {rate:.2f} Hz from peak spacings")
    if extract(inputs) != DATA.read_bytes():
        raise ValueError("Offline data do not reproduce the source workbook cells")


def golden(objective, low, high, loops=32):
    ratio = (sqrt(5)-1)/2
    left, right = high-ratio*(high-low), low+ratio*(high-low)
    lv, rv = objective(left), objective(right)
    for _ in range(loops):
        if lv < rv:
            high, right, rv = right, left, lv
            left = high-ratio*(high-low)
            lv = objective(left)
        else:
            low, left, lv = left, right, rv
            right = low+ratio*(high-low)
            rv = objective(right)
    return (low+high)/2


def fit_fringe(data, slow):
    # Compare like phases in all three windows, allowing offset and contrast to drift.
    windows = {}
    for x,y,_ in data:
        t = x * (1e-3 if slow else 1e-6)
        windows.setdefault(int(t>0.1)+int(t>0.3),[]).append((t,y))
    def profile(frequency):
        stats = []
        for window in windows.values():
            y0 = mean(y for _,y in window)
            c = [cos(2*pi*frequency*t) for t,_ in window]
            s = [sin(2*pi*frequency*t) for t,_ in window]
            c0,s0=mean(c),mean(s)
            c=[v-c0 for v in c];s=[v-s0 for v in s]
            y=[v-y0 for _,v in window]
            stats.append((sum(v*v for v in y),sum(v*v for v in c),sum(v*v for v in s),
                          sum(a*b for a,b in zip(s,c)),sum(a*b for a,b in zip(y,c)),
                          sum(a*b for a,b in zip(y,s))))
        def phase_error(phase):
            co,si=cos(phase),sin(phase)
            score=0.
            for yy,cc,ss,cs,yc,ys in stats:
                xy=yc*co+ys*si
                xx=cc*co*co+ss*si*si+2*cs*co*si
                score+=yy-max(0.,xy)**2/max(1e-16,xx)
            return score
        d=2*pi/24
        seed=min((j*d for j in range(24)),key=phase_error)
        return phase_error(golden(phase_error, seed-d, seed+d,18))
    low,step,count = (115.,.12,418) if slow else (2000.,100.,980)
    guesses=[low+i*step for i in range(count)]
    seed=min(guesses,key=profile)
    frequency=golden(profile,seed-step,seed+step)
    return frequency,sqrt(profile(frequency)/len(data))


def recoil_gap(r, axial_hz, cutoff=60):
    # q=0 Fourier modes exp(2 i n y) for -d²/dy² + V sin²(y).
    # Implied V uses measured harmonic frequency 2 r sqrt(V). All energies in ER.
    depth=(axial_hz/(2*r))**2
    diagonal=[4*n*n+depth/2 for n in range(-cutoff,cutoff+1)]
    off2=(depth/4)**2
    def sturm_count(x):
        pivot=diagonal[0]-x;count=int(pivot<0)
        for val in diagonal[1:]:
            if abs(pivot)<1e-18:pivot=-1e-18
            pivot=val-x-off2/pivot
            count+=int(pivot<0)
        return count
    def level(k):
        a,b=0.,(2*k+3)*sqrt(depth)
        for _ in range(52):
            mid=(a+b)/2
            if sturm_count(mid)<=k:a=mid
            else:b=mid
        return (a+b)/2
    e0,e1,e2=[level(k) for k in range(3)]
    return r*(2*e1-e2-e0)


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--fetch",action="store_true",help="verify the original two source workbooks")
    if parser.parse_args().fetch:fetch()
    rows={}
    with DATA.open() as f:
        for record in csv.DictReader(f):
            rows.setdefault(record["series"],[]).append(tuple(float(record[k]) for k in ("x","y","spread")))
    assert [len(rows[t]) for t,_,_ in SETS]==[6,58,33,8,5,5]
    for label,slow in [("slow_ms",True),("fast_us",False)]:
        freq,rmse=fit_fringe(rows[label],slow)
        print(f"{label} common-phase fit: {freq:.6f} Hz, RMS {rmse:.3f} bright sites")
        assert (140.5<freq<141.0) if slow else (34e3<freq<38e3)
    drive=rows["drive_Hz"]
    slope=sum(x*y for x,y,_ in drive)/sum(x*x for x,_,_ in drive)
    ratios=[y/x for x,y,_ in drive]
    print(f"Drive slope through origin {slope:.6f}; measured/predicted range {min(ratios):.4f} to {max(ratios):.4f}")
    assert .93<slope<.96
    zero=209.0937721
    gaps=[next((y,err) for x,y,err in rows[key] if abs(x-zero)<1e-6)
          for key in ["25.09kHz","38.50kHz","51.80kHz"]]
    axial=[25090,38500,51800]
    bare=golden(lambda r:(recoil_gap(r,axial[0])-gaps[0][0])**2,130,145)
    predicted=[recoil_gap(bare,v) for v in axial]
    assert max(abs(recoil_gap(bare,v,76)-p) for v,p in zip(axial,predicted))<1e-7
    predicted_pert=[bare*(1+9*bare/(4*v)) for v in axial]
    assert max(abs(a-b) for a,b in zip(predicted,predicted_pert))<.08
    assert abs(predicted[0]-gaps[0][0])<.0001 and predicted[-1]-gaps[-1][0]>2.4
    for v,(y,s),p in zip(axial,gaps,predicted):
        print(f"Axial {v/1000:g} kHz: measured {y:.5f} +/- {s:.5f} Hz, calibrated single-sinusoid {p:.5f} Hz")
    print(f"Single-depth inferred recoil frequency {bare:.6f} Hz.")


if __name__=="__main__":
    main()
transport.py
"""Onsite pairs and spin transport on a bipartite graph, with exact rank checks."""
from fractions import Fraction as F
from math import sqrt,pi,sin,cos
from random import Random

ID = [[1,0],[0,1]]
PAULI = ([[0,1],[1,0]],[[0,-1j],[1j,0]],[[1,0],[0,-1]])
ROOT = 1
V = 6
TREE = [(0,1),(1,2),(0,3),(1,4),(2,5)]
CLOSE = [(3,4),(4,5)]


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


def T(a):
    return [list(row) for row in zip(*a)]


def adj(a):
    return [[z.conjugate() for z in col] for col in zip(*a)]


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


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


def times(k,a):
    return [[k*x for x in l] for l in a]


def turn(axis,angle):
    return plus(times(cos(angle/2),ID),times(-1j*sin(angle/2),PAULI[axis]))


def congruence(U,x):
    return mm(mm(U,x),T(U))


# Normalized Cartesian spin-one tensors (I x sigma_a)|singlet>.
singlet = [[0,1/sqrt(2)],[-1/sqrt(2),0]]
BASIS = [mm(singlet,T(s)) for s in PAULI]


def projected(U):
    vals=[[dot(a,congruence(U,b)) for b in BASIS] for a in BASIS]
    assert max(abs(x.imag) for r in vals for x in r)<1e-14
    return [[x.real for x in r] for r in vals]


def edge_list(which):
    X,Z=turn(0,pi/2),turn(2,pi/2)
    if which==3:
        closes=(times(-1,ID),ID)
    elif which==1:
        closes=(Z,times(-1,Z))
    elif which==0:
        closes=(Z,X)
    else:
        raise ValueError(which)
    return [(v,w,ID) for v,w in TREE]+[(v,w,U) for (v,w),U in zip(CLOSE,closes)]


def sign(n):
    return (-1)**(n%3+n//3)


def ferr(rows):
    return max(abs(v-round(v)) for row in rows for v in row)


def kinetic_second_moment(links):
    # This is the exact Gram matrix of the separated-pair amplitudes in
    # staggered Cartesian coordinates. Edges are oriented from v to w.
    rows=[]
    for v,w,U in links:
        R=projected(U)
        assert ferr(R)<1e-14
        for a in range(3):
            r=[0]*(3*V)
            r[3*w+a]=1
            for b in range(3):
                r[3*v+b]=-round(R[a][b])
            rows.append(r)
    return times(2,mm(T(rows),rows))


def rank(A):
    a=[[F(x) for x in r] for r in A];m=len(a);i=0
    for j in range(len(a[0])):
        pivot=next((k for k in range(i,m) if a[k][j]),None)
        if pivot is None:continue
        a[i],a[pivot]=a[pivot],a[i]
        for k in range(i+1,m):
            factor=a[k][j]/a[i][j]
            for l in range(j,len(a[0])):
                a[k][l]-=factor*a[i][l]
        i+=1
    return i


def positive_above(A,cut):
    # Positive exact LDL pivots prove all eigenvalues exceed the cut.
    a=[[F(x)-(cut if i==j else 0) for j,x in enumerate(row)] for i,row in enumerate(A)]
    for i in range(len(a)):
        if a[i][i]<=0:return False
        for k in range(i+1,len(a)):
            q=a[k][i]/a[i][i]
            for j in range(i+1,len(a)):
                a[k][j]-=q*a[i][j]
    return True


def independent_fock(links):
    # Sum all first-coordinate and second-coordinate spinor hopping paths in the
    # ordered 12 x 12 one-particle product basis, including both particle orders.
    rng=Random(72);vectors=[[complex(rng.random()-.5,rng.random()-.5) for j in range(3)]
                             for v in range(V)]
    norm=sqrt(sum(abs(z)**2 for v in vectors for z in v))
    vectors=[[z/norm for z in v] for v in vectors]
    dim=2*V
    H=[[0j]*dim for _ in range(dim)]
    state=[[0j]*dim for _ in range(dim)]
    weights=[1.0,1.3,-.67,1.2,.71,-1.,.88]
    direct=0
    for (n,m,U),t in zip(links,weights):
        for a in range(2):
            for b in range(2):
                H[2*m+a][2*n+b]=t*U[a][b]
                H[2*n+b][2*m+a]=t*U[a][b].conjugate()
        R=projected(U)
        direct+=2*t*t*sum(abs(vectors[m][j]-sum(x*y for x,y in zip(R[j],vectors[n])))**2
                          for j in range(3))
    for n,v in enumerate(vectors):
        for a in range(2):
            for b in range(2):
                state[2*n+a][2*n+b]=sign(n)*sum(v[j]*BASIS[j][a][b] for j in range(3))
    hopped=plus(mm(H,state),mm(state,T(H)))
    assert abs(dot(state,state)-1)<1e-14 and abs(dot(state,hopped))<1e-14
    assert abs(dot(hopped,hopped).real-direct)<1e-13


def main():
    for dim in [3,1,0]:
        links=edge_list(dim)
        A=kinetic_second_moment(links)
        assert 3*V-rank(A)==dim
        independent_fock(links)
        if dim==0:
            lo,hi=F(0),F(2)
            for _ in range(14):
                middle=(lo+hi)/2
                if positive_above(A,middle):lo=middle
                else:hi=middle
            assert lo>0
            print(f"Two orthogonal quarter-turn loops: minimum variance in [{lo}, {hi}] hopping²")
            variances=[sum(A[3*r+j][3*s+j] for r in range(V) for s in range(V))/V for j in range(3)]
            assert all(abs(a-b)<1e-14 for a,b in zip(variances,(2/3,4/3,2/3)))
    # Commuting SO(3) rotations can nevertheless have no common fixed vector:
    # distinct orthogonal half-turns, unlike rotations around one shared axis.
    X,Z=projected(turn(0,pi)),projected(turn(2,pi))
    assert max(abs(a-b) for ra,rb in zip(mm(X,Z),mm(Z,X)) for a,b in zip(ra,rb))<1e-14
    constraints=[[round(a)-(i==j) for j,a in enumerate(row)] for W in (X,Z) for i,row in enumerate(W)]
    assert rank(constraints)==3
    print("Triplet kernel dimensions 3, 1, 0; exact ranks and independent spinor hopping checks passed.")


if __name__=="__main__":
    main()
sphere.py
"""Exact great-circle transport on the unit three-sphere for two native loops."""
from math import acos, atan2, cos, pi, sin, sqrt


def dot(a,b):return sum(u*v for u,v in zip(a,b))
def plus(a,b):return tuple(u+v for u,v in zip(a,b))
def times(a,s):return tuple(s*u for u in a)
def unit(a):return times(a,1/sqrt(dot(a,a)))


def embed(w):
    theta=sqrt(dot(w,w))
    return (cos(theta),*(times(w,sin(theta)/theta) if theta else w))


def parallel(p,q,v):
    """Levi-Civita transport of a tangent vector along the short great-circle arc."""
    assert abs(dot(p,v))<2e-14
    return plus(v,times(plus(p,q),-dot(q,v)/(1+dot(p,q))))


def area(a,b,c):
    x,y,z=dot(a,b),dot(b,c),dot(c,a)
    gram=1+2*x*y*z-x*x-y*y-z*z
    return 2*atan2(sqrt(max(0,gram)),1+x+y+z)


def loop(b,d,angle):
    seq=[embed(times(v,angle)) for v in [(0,0,0),b,plus(b,d),d,(0,0,0)]]
    columns=[]
    for i in range(3):
        v=(0.,*(float(j==i) for j in range(3)))
        for p,q in zip(seq,seq[1:]):v=parallel(p,q,v)
        columns.append(v[1:])
    normal=unit((b[1]*d[2]-b[2]*d[1],b[2]*d[0]-b[0]*d[2],b[0]*d[1]-b[1]*d[0]))
    def rotate(v):
        return tuple(sum(v[i]*columns[i][j] for i in range(3)) for j in range(3))
    assert max(abs(u-v) for u,v in zip(rotate(normal),normal))<1e-14
    for i in range(3):
        for j in range(3):
            assert abs(dot(columns[i],columns[j])-(i==j))<1e-14
    theta=acos(max(-1,min(1,(sum(columns[i][i] for i in range(3))-1)/2)))
    expected=area(*seq[:3])+area(seq[0],seq[2],seq[3])
    assert abs(theta-expected)<1e-10
    return theta,normal


def main():
    a,b,c=(1,1,1),(0,1,1),(0,0,1)
    for step in (.1,.2):
        t1,n1=loop(a,b,step);t2,n2=loop(b,c,step)
        assert abs(dot(n1,n2))<1e-14 and min(t1,t2)>0
        print(f"a/R={step}: two angles {t1:.9g}, {t2:.9g} rad; orthogonal fixed axes")
    # At small arcs the angles approach the flat tangent areas / R squared.
    x=loop(a,b,.05)[0]
    assert abs(x/(.05**2)-sqrt(2))<.003
    print("Both geodesic loops agree with their oriented spherical area magnitudes.")


if __name__=="__main__":
    main()
replay.py
"""Replay the pair spectroscopy study using standard Python and a pinned Tally runtime."""
import argparse
import hashlib
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from zipfile import ZipFile

ROOT = Path(__file__).resolve().parent
RUNTIME_SHA = "1fb281c0ef55314ec68de024ac27da152ff00739607cbbdc408eeee82ab5b193"
ATOM_SHA = "4c08a122480cb2d6c1efb48b9e868b5b45432d78dc40b339dbe9db7ebdacf02d"


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


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("runtime", type=Path, help="published Tally 0.3.0 runtime ZIP")
    args = parser.parse_args()
    checked(args.runtime, RUNTIME_SHA)
    lib = ROOT / "lib/atom.tly"
    if not lib.is_file():
        lib = ROOT.parent / "walk-clock-recoil/tally/lib/atom.tly"
    atom = checked(lib, ATOM_SHA)
    python = [sys.executable, "-E", "-s", "-B", "-X", "utf8"]
    for script in ("probe", "flux", "echo", "curvature", "winkler", "calibration", "transport", "sphere"):
        subprocess.run([*python, str(ROOT / (script + ".py"))], check=True)

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


if __name__ == "__main__":
    main()
plot_winkler.py
"""Rebuild the figure for Winkler spectroscopy with Matplotlib and Pillow."""
import contextlib
import csv
from io import BytesIO, StringIO
from math import exp
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from PIL import Image
import winkler


def main():
    root=Path(__file__).resolve().parent
    with winkler.DATA.open(newline='') as f:rows=list(csv.DictReader(f))
    points=[(float(r['x']),float(r['y'])) for r in rows if r['series']=='survival']
    with contextlib.redirect_stdout(StringIO()):
        data,models=winkler.compare(rows)
    _,mu,sigma,b,amp=winkler.gaussian_fit(points)
    fig,axes=plt.subplots(2,1,figsize=(6,6.4),dpi=160)
    fig.subplots_adjust(left=.155,right=.965,top=.949,bottom=.092,hspace=.62)
    plt.rcParams.update({'font.family':'DejaVu Sans'})
    blue,orange,slate='#195a80','#a44614','#53656b'
    for ax in axes:
        ax.spines[['right','top']].set_visible(False)
        ax.tick_params(labelsize=10)
        ax.grid(axis='y',color='#d9dfdf',linewidth=.6)
        ax.set_axisbelow(True)
    ax=axes[0]
    ax.set_title('Pair survival at fixed lattice depth',loc='left',size=13,weight='semibold',pad=8)
    grid=[i*3.55/300 for i in range(301)]
    ax.plot(grid,[b+amp*exp(-.5*((t-mu)/sigma)**2) for t in grid],color=blue,lw=1.6,label='Gaussian fit')
    ax.scatter(*zip(*points),s=25,facecolor='white',edgecolor=blue,lw=1,zorder=3,label='Measured')
    ax.set(xlim=(0,3.55),ylim=(.15,1.1))
    ax.set_xlabel('Drive frequency (kHz)',size=11);ax.set_ylabel('Normalized pair count',size=11)
    h,l=ax.get_legend_handles_labels()
    ax.legend([h[1],h[0]],[l[1],l[0]],frameon=False,ncol=2,loc='lower center',fontsize=9,bbox_to_anchor=(.50,-.04),handlelength=1.4,columnspacing=1.2)
    ax=axes[1]
    ax.set_title('Resonances at the seven reserved depths',loc='left',size=13,weight='semibold',pad=8)
    held=models['deep-calibrated']
    depths=[r[0] for r in held];obs=[r[1] for r in held]
    err=[[r[1]-r[2] for r in data[:-3]],[r[3]-r[1] for r in data[:-3]]]
    ax.errorbar(depths,obs,yerr=err,fmt='o',ms=4.8,elinewidth=1.1,capsize=2.5,color='#263538',
                label='Measured, 95% fit interval',zorder=3)
    ax.plot(depths,[r[2] for r in held],lw=1.5,color=slate,ls='--',label='Contact only')
    ax.plot(depths,[r[3] for r in held],lw=1.8,color=orange,label='With pair dispersion')
    ax.set(xlim=(3.7,10.3),ylim=(1.04,1.85),xticks=[4,5,6,7,8,9,10])
    ax.set_xlabel('Axial lattice depth (recoil energies)',size=11);ax.set_ylabel('Center frequency (kHz)',size=11)
    ax.legend(loc='lower right',frameon=False,fontsize=8.5,handlelength=1.9,labelspacing=.3)
    stream=BytesIO();fig.savefig(stream,format='png',facecolor='white');plt.close(fig)
    stream.seek(0)
    with Image.open(stream) as im:
        assert im.size==(960,1024)
        im.convert('RGB').quantize(colors=128,method=Image.Quantize.MEDIANCUT).save(root/'winkler-resonances.png',optimize=True)


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

Independent research by Anthony Michael Collado.
Pair spectroscopy and clock readout · 1 December 2026

The pair-clock proposal → · Study sources (ZIP) ↓