Skip to content

Can one-particle counts predict what two particles do?

Changing the relative phase of two sources changes where a single walker is detected. A phase applied only when two walkers meet leaves every one-particle count unchanged. The pair experiment can distinguish the two collision rules.

The same two sites, two different detector counts

Split a single excitation equally between two sites, one coarse cell above and one below the origin. Change the relative phase between the two inputs while keeping their intensities fixed. After the six-stage walk has run for N ticks, count final positions in two opposite circular cones. Exclude the origin and accept every other radius. This models a snapshot of the walk, as in an array of output ports. A screen that absorbs a particle at its first crossing implements a different measurement.

The half-angle of each cone is arctan(1/4), about 14.04°. A position r lies in the pair around direction d when 17(r·d)² ≥ 16|r|²|d|². We compare a face-diagonal pair around (1,1,0) with a body-diagonal pair around (1,1,1). The apertures have the same solid angle. Original walk and velocity distribution

Launch at the two sitesFace pair, 3 ticksFace pair, long-time limitBody pair, long-time limit
Equal incoherent mixture35/5122.19934%1.30756%
Equal amplitudes, in phase17/1283.89573%1.30756%
Equal amplitudes, opposite phase1/2560.50294%1.30756%

The long-time count at the face detector changes by a factor of 7.746. The body detector gives an independent brightness check in that limit. The limit takes time to emerge. At three ticks the in-phase and opposite-phase body probabilities are 81/8192 and 13/8192. At twelve ticks they are about 1.185% and 1.105%. Comparing two positive counts at the same detector cancels a fixed common efficiency in their ratio.

Why the phase matters

Write a,b,d for the absolute components of a unit direction. Under a one-site launch the limiting angular density is 1/[2π²(a+b)(b+d)(d+a)]. In momentum space the coherent two-site launch weights this by an interference term involving cos(2kz − φ), where φ is the controlled relative phase. The sine term integrates to zero in an antipodal pair. Under uniform momentum the tangent components are independent Cauchy variables. On a given ray, multiplying their radial integrand by cos(2kz) amounts to applying 1 + d ∂/∂d to it. Integrating gives the angular multiplier 1 + gz cos φ, with

gz = 1 − d/(a + d) − d/(b + d).

This multiplier is 1 + cos φ on the exact face diagonal and one on the exact body diagonal. The three coordinate versions of g sum to zero. Consequently its integral vanishes on the body aperture, which is invariant under coordinate permutations. Within the face aperture the calculation gives P(φ) ≈ 0.02199336 + 0.01696391 cos φ. The source visibility can be calibrated independently. For source weights p and 1 − p, the modulation scales by 2√[p(1 − p)] times the modulus of their mutual coherence, with its phase included in φ.

Antipodal detection also removes sensitivity to the shared input spin state. The Fourier kernel of the free walk has the form K(r) = aI + b·σ with real coefficients, scalar part even under inversion and vector part odd. Combining the effects at r and −r for the balanced sources cancels the spin-vector part. The exact finite simulation checks the full two-by-two detector matrix. The result requires matched antipodal efficiencies and a common spin preparation at the two inputs. Ordinary coherent linear optics already predicts this phase scan.

A two-particle measurement can distinguish the update rules

Send one identical boson from each of the same two sites, both in the positive z spin state. Compare the free walk with an update that also multiplies its amplitude by eig when both particles occupy the same coarse site after a tick. The phase applies to all spin pairs. This rule is unitary, local and translation invariant. Every experiment with zero or one particle agrees exactly between the two models for every value of g. Site-resolved two-particle counts can determine whether this particular interaction is present. Earlier work on quantum walks with contact interactions

The free case has an independent calibration. For one-particle output modes A, B from the two input sites and a detector mask D, measure the single-source probabilities pA, pB. Phase scans determine the complex overlap q = ⟨A|D|B⟩. Two distinguishable noninteracting arrivals both enter the mask with probability pApB. Indistinguishable noninteracting bosons add |q|² by exchange. For the face pair after three ticks these probabilities are 1225/262144 and 1157/131072. The inputs occupy orthogonal spatial modes, and the detector resolves both particles even when they arrive at the same output.

An exact two-tick test

Only the contact after the first tick can change position probabilities at the second. Separate the histories at that first tick into those arriving on different sites and those meeting on one site. Restricted to a final event, their amplitudes add with relative phase g. The real-space replay propagates both particles and both spins, adds the amplitudes, then squares. It yields these two probabilities for bosons.

Event at tick twoAny contact phaseFree walkπ contact
Both particles at the same site, anywhere(203 + 115 cos g)/81923.88184%1.07422%
Both in the body-diagonal detector pair(401 − 320 cos g)/2621440.03090%0.27504%

The two counts move in opposite directions and must yield the same cos g. Neither count distinguishes g from −g. For 1,000 independently prepared pairs with ideal number resolution and unit efficiency, classify 22 or more same-site events as the free case. The exact binomial probabilities of a wrong classification are 0.1103% for the free walk and 0.1594% for the π contact. Loss, background, partial distinguishability and unequal site efficiencies enter an actual likelihood. This comparison specifies two candidate interactions and the measurement that separates them. An observed discrepancy alone would not select the π interaction.

Which additive charges survive a collision?

There is an exact consequence for the theory’s energy proposal. Take a homogeneous, bounded one-particle Hermitian observable F on the infinite lattice, and suppose the same sum of F over particles is conserved on the one- and two-boson sectors. For the onsite phase above, whenever g is different from zero modulo 2π, the only such observable is a constant multiple of particle number. This statement permits arbitrarily long-range hopping in F. Its restriction is that the conserved quantity must be a sum of independent single-particle observables.

The one-particle sector requires F to commute with the free tick W. Free two-particle propagation then commutes with the sum Q = F ⊗ I + I ⊗ F. The contact is I + (eig − 1)P, where P projects onto particles sharing one site. Conservation therefore requires [P,Q] = 0. Put two bosons with spinor u at site x. Any offsite block Fyx creates a separated pair with amplitude proportional to Fyxu. Since the spinor is arbitrary, all offsite blocks must vanish. Translation symmetry leaves one constant spin matrix. The three axial walks rotate around the three Pauli axes, so only a scalar spin matrix commutes with all of them.

For the proposed signed charge F = (W† − W)/(2i), with eigenvalue sin Ω on the positive-eigenphase convention, we can quantify the failure. Its onsite block is zero. Its axial positive-z hop has magnitude 1/2 for spin up, and the onsite block of F² is (7/8)I. On a normalized pair at one site, the norm of the component that Q sends to separated sites is √7/2. For the full two-particle tick Ug the exact operator norm of the change in Q is √14 |sin(g/2)| in walk units.

Derivation of the exact norm

Since PQP = 0, the square of the leakage norm is the norm of PQ²P on the same-site spin triplets. At pair-center momentum K, its constant term is 7I/4. Its remaining terms are −(cos Kx cos Ky cos Kz) σx⊗σx/4, −(cos Ky cos Kz) σy⊗σy/2, and −cos Kz σz⊗σz. Their norms bound the sum by 7/2. The symmetric spin state (↑↓ + ↓↑)/√2 attains this bound at K = (0,π,0), and arbitrarily broad wave packets approximate it on the infinite lattice. Multiplying the square root by |eig − 1| gives the stated result.

If the theory requires sin Ω to remain exactly additive for isolated interacting walkers, it selects the free value g = 0 in this family. If it allows interaction energy or a material field carrying the missing charge, that additional degree of freedom needs its own dynamics and detector signature. The charge result leaves that possibility open. Earlier energy and scattering analysis

What do measured quantum walks say about the angular distribution?

A four-step optical walk put 61.01% of its measured probability in four narrow wedges around the horizontal and vertical lattice axes. We recovered this number from Jeong and colleagues’ published position histogram. Their two-dimensional gate sequence predicts 59.375% at four steps. The six-stage walk predicts 36.639% at the same tick count for this projected measurement. The two walks do share a prediction for the angle at large tick count. Jeong et al., Nature Communications (2013), Fig. 6

One angular gate, two different clocks

For a detected displacement (x, y), accept the event when 4 min(|x|, |y|) ≤ max(|x|, |y|). The origin contributes to the denominator only. Jeong’s apparatus made two polarization-controlled shifts per step, each preceded by a Hadamard coin. Arrival times resolved the lattice sites. Leaving the entangled partner’s polarization unselected prepared the maximally mixed input. The six-stage walk uses the same localized, unpolarized preparation with a different sequence of shifts.

The optical walk has cos Ω = cos kx cos ky. Its two group-velocity components have ratio tan ky/tan kx, just as in the three-dimensional walk after projection onto the xy plane. For a localized input, the two tangent variables are independent standard Cauchy variables. Integrating their joint density in polar coordinates gives the projected angular density g(φ) = log|cot φ| / [π² cos(2φ)], with its continuous value 1/π² at a diagonal. The four wedges together approach 49.1087% in both walks. A uniform planar angle would give 31.1917%. Losing the third coordinate leaves the three-dimensional face-to-body diagonal ratio unmeasured.

Reading the optical data

The authors normalized corrected photon coincidences at each step. Their public vector figure contains the resulting bar heights. We recovered each height using its four vertical edges and estimated the perspective from the three sets of parallel edges. Against a direct four-step Hadamard calculation, every probability in the theory panel agrees within 0.00000181. For the measured panel the four-edge spread in the summed wedge probability is 0.610121–0.610149. This measures the consistency of the graphical reconstruction. The source supplies no per-site event totals from which to compute a photon-counting confidence interval. The measured origin fraction is 0.03239. Original manuscript and vector-figure source

Running the same detector on individual atoms

Young and colleagues released the paired fluorescence measurements from a continuous-time strontium walk. At 5.0 ms we located the brightest site in each 29 × 29 image and kept shots above the authors’ 4.5-photon threshold in both frames. Of 14,000 trials, 7,622 passed. Measuring each atom’s displacement from its own loading site put 1,994 in the four wedges, or 26.16% (95% Wilson counting interval 25.19–27.16%). Nineteen retained atoms returned to the origin and 252 ended on the field edge. Lowering the threshold to 4.0 photons gives 27.52%, and raising it to 5.0 gives 25.47%. These counts use lattice indices on the apparatus’s slightly nonsquare lattice. Young et al., Science (2022) · Original fluorescence arrays and analysis notebook

These atoms evolve by continuous tunneling. Their two measured late-time tunneling rates are 178.1(1.1) and 148.3(1.1) Hz in units of energy divided by Planck’s constant. Using the authors’ fitted effective times to account for the intensity servo, a flat coherent 29 × 29 lattice predicts 21.06% at 5.0 ms. That calculation omits the fitted fringe contrast, imaging background and spatial potential. The data test the angular counting procedure under another Hamiltonian. Tunneling calibration and imaging model

Recovering the third coordinate in a new measurement

A programmable two-dimensional apparatus could replace the paired z shifts of the six-stage walk by the polarization rotation exp(−iκσz). This implements the walk at one chosen value of its third momentum coordinate. At four ticks a point input gives only the five third-coordinate displacements −4, −2, 0, 2 and 4. Five settings κ = πℓ/5 (ℓ = 0,…,4) suffice. In general the known parity leaves N+1 possible positions; undoing the known phase of the first position gives an ordinary discrete Fourier transform. A coherent source on the two sites z = ±1 requires N+2 settings. Nine settings across a full circle also suffice for the four-tick point input without using parity. Recover both output polarization amplitudes against one phase reference across the settings. An inverse discrete Fourier transform yields the position amplitudes at each (x, y). Repeat for both input polarizations and average their probabilities. Averaging intensities over κ alone yields only the projected histogram. The offline checker compares the reconstructed complex amplitudes with direct spatial propagation for ticks one through four, for both input spins and three source preparations. A local two-particle interaction exchanges third-axis momentum between particles. Independent one-particle retarder settings preserve each chosen momentum and would require additional coherent coupling to simulate that interaction.

Projected angles also lose a distinction the three-dimensional detector sees. The two coherent launches have momentum weights 1 ± cos(2kz). The limiting four-wedge test depends only on the ratio tan ky/tan kx, so integrating over kz gives the same 49.109% for either phase. The three-dimensional apertures retain the phase signal.

A quantum gate for balanced energy transport

Sections in this chapter

An elementary gate can move two equal energy deposits in opposite directions while preserving both linear gravitational Gauss constraints. A neutral control can put that motion in a coherent superposition with staying at the origin. The same gate gives a nonzero, exactly calculable residual in the transverse gravitational wave equation. These two tests distinguish consistent source transport from gravitational force dynamics.

Why an isolated hop fails the local test

Use unit fine spacing and tick duration. Write the scalar and vector constraints as $C[h]=DiDjhij−D2hii=wρ,Mi[π]=−2Djπij=wji. C[h]=D_iD_jh_{ij}-D^2h_{ii}=w\rho,\qquad M_i[\pi]=-2D_j\pi_{ij}=wj_i. Onthestaggeredcubiclattice, On the staggered cubic lattice, D_i f(x)=f(x+e_i/2)-f(x-e_i/2).Thediagonalmetricanditsmomentumliveatvertices,andvectorcurrentsliveonlinks.Summationbypartsgives. The diagonal metric and its momentum live at vertices, and vector currents live on links. Summation by parts gives ∑C[δh]=∑xiC[δh]=0,∑δMi=∑x×δM=0 \sum C[\delta h]=\sum x_i C[\delta h]=0,\qquad \sum\delta M_i=\sum \mathbf x\times\delta\mathbf M=0 forafinitechangeofthefields.Symmetryof for a finite change of the fields. Symmetry of \pigivestheangularmomentumidentity.Accordinglyafinite−supportoperationpreservingthescalarconstraintcannottakeenergy gives the angular momentum identity. Accordingly a finite-support operation preserving the scalar constraint cannot take energy \epsilonfromtheoriginto from the origin to r e_xwithallothersourcesfixed.Itsenergydipolewouldchangeby with all other sources fixed. Its energy dipole would change by r\epsilon$. This argument also works for an arbitrary quantum gate on the physical subspace. Pair the constraint with the coordinate function on a box containing its support and a full collar. The resulting gravitational operator is supported in the collar and commutes with the gate. A compensating energy displacement, boundary exchange, or an evolution changing an already extended gravitational field can supply the missing dipole. Propagation of an isolated dressed mass in such a system lies outside this local selection rule. Related dipole restrictions appear in rank-two gauge theories. Pretko, 2017

The six-stage source

For an integer radius r≥1r\geq1, put Qr(x)=ε(r−|x|)+Q_r(x)=\epsilon(r-|x|)_+ on the xx axis and zero elsewhere. Its second staggered difference equals ε(δ−r+δr−2δ0)\epsilon(\delta_{-r}+\delta_{r}-2\delta_0). A finite clock cycles through s=0,…,5s=0,\ldots,5. For the moving branch take fs=(0,0,0,1,1,0)f_s=(0,0,0,1,1,0), and put f=0f=0 on the idle branch. Define us=fs+1−fsu_s=f_{s+1}-f_s. In the following equations jsj_s labels the link current in the half tick following stage ss: $ρs=2εδ0+fsDx2Qr,jx,s=−usDxQr,τxx,s=(us−us−1)Qr. \rho_s=2\epsilon\delta_0+f_sD_x^2Q_r,\qquad j_{x,s}=-u_sD_xQ_r,\qquad \tau_{xx,s}=(u_s-u_{s-1})Q_r . Allothercomponentsvanish.Eachendpointreceives All other components vanish. Each endpoint receives \epsilon;everytraversedlinkcarries; every traversed link carries +\epsilonontherightor on the right or -\epsilonontheleftduringtheoutwardtick.Thestressessupplythelaunch,stop,andreturnimpulses.Bothconservationlawsholdateverysiteandstage: on the left during the outward tick. The stresses supply the launch, stop, and return impulses. Both conservation laws hold at every site and stage: ρs+1−ρs+Dxjx,s=0,jx,s−jx,s−1+Dxτxx,s=0. \rho_{s+1}-\rho_s+D_xj_{x,s}=0,\qquad j_{x,s}-j_{x,s-1}+D_x\tau_{xx,s}=0. Acompactgravitationaldressingis A compact gravitational dressing is hs=wfsQr2diag(1,−1,−1),πs=wusQr2diag(1,0,0). h_s={w f_sQ_r\over2}\operatorname{diag}(1,-1,-1),\qquad \pi_s={w u_sQ_r\over2}\operatorname{diag}(1,0,0). Itsatisfies It satisfies C[h_s]=w(\rho_s-\rho_{\rm ref}),, M[\pi_s]=wj_s,and, and h_{s+1}-h_s=2\pi_s-I\operatorname{tr}\pi_swith with \rho_{\rm ref}=2\epsilon\delta_0$. The reference configuration has the same positive total energy in every branch. Absolute Gauss constraints require its common initial gravitational field or compensating boundary/background data.

Coherent realization

The matter block has an idle/moving qubit bb and a six-state clock. Its orthogonal configurations can be encoded in occupation registers at the center and endpoints, with directed link channels during flight. The density, outgoing half-tick current and stress above are diagonal observables in this basis. The clock sets a reversible schedule for the assigned stresses. A derived microscopic support material or autonomous free-walker Hamiltonian would be an additional input.

Let Wb,sW_{b,s} translate the gravitational canonical variables by the corresponding pair (hs,πs)(h_s,\pi_s). Define $U=∑b,s|b,s+1⟩⟨b,s|⊗Wb,s+1Wb,s†. U=\sum_{b,s}|b,s+1\rangle\langle b,s|\otimes W_{b,s+1}W_{b,s}^{\dagger}. Itisafiniteblockunitaryforfixed It is a finite block unitary for fixed r.Theproductofsuccessivedressingstelescopes,includingallWeylphases,so. The product of successive dressings telescopes, including all Weyl phases, so U^6=I.Eachtransitionchangesthescalarandvectorgravitationalconstraintsbyexactlythechangesofthecorrespondingmatterobservables.Thus. Each transition changes the scalar and vector gravitational constraints by exactly the changes of the corresponding matter observables. Thus Ucommuteswithbothjointconstraintsortheirexponentiatedversions.Conjugationby commutes with both joint constraints or their exponentiated versions. Conjugation by Ushiftseverydiagonalmatterobservablebyonestage,liftingbothconservationlawstooperatoridentities.Atstagezerothetwobrancheshaveidenticalsources.Preparethecontrolin shifts every diagonal matter observable by one stage, lifting both conservation laws to operator identities. At stage zero the two branches have identical sources. Prepare the control in (|0\rangle+|1\rangle)/\sqrt2$. At stage three one branch has two deposits at the endpoints and its metric displacement. The other has both at the center. The gravitational scalar constraint takes different values on these branches, so their conditional gravitational states are distinguishable in a physical state.

For r=1,ε=2,w=1r=1,\epsilon=2,w=1, the shifts are integers. The checker uses seven-state gravitational qudits with Z|x⟩=ζx|x⟩Z|x\rangle=\zeta^x|x\rangle, X|x⟩=|x+1⟩X|x\rangle=|x+1\rangle, ζ=e2πi/7\zeta=e^{2\pi i/7}, and W=XhZπW=X^hZ^\pi. It enumerates both branches, all stages and all 737^3 coordinate configurations on the three affected central qudits. It checks all seven scalar and six vector stabilizers overlapping those qudits and every phase of U6U^6. Factors on untouched qudits commute with this block. Those stabilizer tests are modulo seven. Separate real-space tests verify the underlying source and constraint identities over the rationals.

The native derivative and a failing gravitational test

At transfer ll the alternating walk has native derivative di=Fiqid_i=F_i q_i, where qi=2sin(li/2)q_i=2\sin(l_i/2) and Fi=cos(li/2)cosli∏j>icos(2lj)F_i=\cos(l_i/2)\cos l_i\prod_{j>i}\cos(2l_j). Set L0=∏iFiL_0=\prod_iF_i, Lx=FyFzL_x=F_yF_z. Applying L02L_0^2 to ρ\rho, L0LxL_0L_x to jxj_x, and Lx2L_x^2 to QrQ_r in the stress and dressings preserves both Ward identities and both Gauss laws with the native derivative. Each filter is a finite average. The radius-two control moves two fine sites per outgoing tick, the axial distance of the free two-step walk. The block's locally assigned conserved energy and impulse schedule are separate assumptions; matching that axial speed and derivative does not identify its matter energy with the native walk charge sinΩ\sin\Omega. Project derivation of the free walk stress and filters

At wavevector (0,0,π/3)(0,0,\pi/3), the unnormalized plus amplitude is H=hxx−hyyH=h_{xx}-h_{yy}. For unit coupling and wave speed, the nearest-time-step linear wave equation would require $R=Hs+1−2Hs+Hs−1+dz2Hs−(τxx,s−τyy,s)=0. R=H_{s+1}-2H_s+H_{s-1}+d_z^2 H_s-(\tau_{xx,s}-\tau_{yy,s})=0. Timeaccelerationcancelstheassignedstressexactly.Thespatialrestoringforceleaves Time acceleration cancels the assigned stress exactly. The spatial restoring force leaves R=d_z^2 f_s\widehat Q_r,withthecorrespondingfilterincludedin, with the corresponding filter included in \widehat Q_r.For. For r=1,\epsilon=2,f_s=1,thecenteredresidualis, the centered residual is 2.Thenativeresidualis. The native residual is 9/512,since, since d_z^2=3/16and and L_x^2=3/64$. The plus amplitude is transverse and traceless on this axis, so changing lapse, shift, or spatial gauge cannot remove the residual. A radiative gravitational response or additional transverse support stress would have to account for it. The gate alone leaves the choice of a microscopic response open.

Retarded field evolution for one split and return

The compact dressing can be used as initial data for an independent test of the linear Fierz–Pauli dynamics. Start the relative geometry with h0=π−1/2=0h_0=\pi_{-1/2}=0. Run the moving branch once, with f3=f4=1f_3=f_4=1 and fn=0f_n=0 at every other tick. Use the same matter stress and choose zero lapse and shift perturbations. Define vi=Djhijv_i=D_jh_{ij}, h=hiih=h_{ii} and the linear spatial Einstein tensor $Eij=12[−D2hij−DiDjh+Divj+Djvi−δijC[h]]. E_{ij}=\tfrac12[-D^2h_{ij}-D_iD_jh+D_iv_j+D_jv_i-\delta_{ij}C[h]]. Thefiniteupdateis The finite update is πn+1/2=πn−1/2−cT2E[hn]+w2τn,hn+1=hn+2πn+1/2−Itrπn+1/2. \pi_{n+1/2}=\pi_{n-1/2}-c_T^2E[h_n]+\tfrac w2\tau_n,\qquad h_{n+1}=h_n+2\pi_{n+1/2}-I\operatorname{tr}\pi_{n+1/2}. Everystepusesonlythedifferencestencilandcanonicalfieldsinitsfiniteneighborhood.Commutingdifferencesgive Every step uses only the difference stencil and canonical fields in its finite neighborhood. Commuting differences give D_jE_{ij}=0.Thus. Thus M_{n+1/2}-M_{n-1/2}=-wD_j\tau_{ij,n}=w(j_{i,n}-j_{i,n-1}).Directsubstitutiongives. Direct substitution gives C_{n+1}-C_n=-D_i M_{i,n+1/2}$. These identities propagate both constraints from the initial slice. The difference between the retarded field and the compact dressing satisfies homogeneous scalar and vector constraints at every stage (compare momenta at the same half tick). The TT projection is used only to read out a mode after evolution.

The same kick and drift are canonical shears of a noncompact quantized linear field. The stress acts conditionally on the finite source register. The update preserves the joint constraint subspace. Away from this subspace the scalar constraint error changes by the divergence of the vector error. The earlier finite-qudit gate commutes with both stabilizers individually and returns after six ticks; the retarded field carries a signal beyond that cycle. Here the spatial Einstein tensor and its coefficient are supplied dynamics.

### A near-source curvature and a transverse pulse

Take r=1,ε=2,w=1,cT=1/2r=1,\epsilon=2,w=1,c_T=1/2. For both stencils the TT dispersion of this time integrator is 4sin2(ω/2)=cT2|d|24\sin^2(\omega/2)=c_T^2|\mathbf d|^2. The centered three-dimensional stencil has |d|2≤12|\mathbf d|^2\le12 and the native stencil |d|2≤1/4|\mathbf d|^2\le1/4. The selected speed puts every nonzero radiative mode strictly inside the leapfrog stability interval 0<cT2|d|2<40<c_T^2|\mathbf d|^2<4. Zero-derivative and gauge modes have separate evolution. This parameter choice demonstrates a stable update and does not calibrate the speed of gravity to the photon walk.

The checker advances all six tensor components on the open centered lattice through ten slices. It verifies the spatial Bianchi identity and both source constraints everywhere at each step. The scalar curvature at the central vertex during separation is −4-4, and it returns to zero with the matter. At a detector three sites along zz, outside the matter support, the local spatial curvature contrast 2(Rxzxz−Ryzyz)2(R_{xzxz}-R_{yzyz}) is zero through n=4n=4, equals −1/8-1/8 at n=5n=5, and equals 21/6421/64 at n=7n=7. The finite stencil gives a finite domain of dependence. The delay of this lattice observable is distinct from a continuum time-of-flight measurement.

For k=(0,0,π/3)\mathbf k=(0,0,\pi/3) let g=cT2dz2g=c_T^2d_z^2 and let BB be the Fourier component of wQ1wQ_1 after any native filtering. The unnormalized plus amplitude satisfies $Hn+1=(2−g)Hn−Hn−1+B(fn+1−2fn+fn−1). H_{n+1}=(2-g)H_n-H_{n-1}+B(f_{n+1}-2f_n+f_{n-1}). Afterthelastkickitsconservedpositiveoscillatorinvariantis After the last kick its conserved positive oscillator invariant is I=12[(H6−H5)2+gH6H5]=12B2g2(4−g). \mathcal I=\tfrac12[(H_6-H_5)^2+gH_6H_5] =\tfrac12B^2g^2(4-g). Thisfollowsbyapplyingtherecurrencetothefournonzerokicksat This follows by applying the recurrence to the four nonzero kicks at n=2,3,4,5.Forthecenteredupdate,. For the centered update, (B,g)=(2,1/4)gives gives (H_5,H_6)=(-11/8,-61/32)and and \mathcal I=15/32.Forthenativeupdate,. For the native update, (B,g)=(3/32,3/64)gives gives \mathcal I=20493/536870912.Thecheckerobtainsthesesamevaluesbyevolvingtheunprojectedfield.Itchecksthenativecaseonasix−siteperiodiccubethatcontainsthespecifiedmode.Onthistorusthefilteredcentralcurvatureduringseparationis. The checker obtains these same values by evolving the unprojected field. It checks the native case on a six-site periodic cube that contains the specified mode. On this torus the filtered central curvature during separation is -33/4096.Bothpolarizationsvanishalongthe. Both polarizations vanish along the xsourceaxis.Atthe source axis. At the z$ mode the free TT pulse remains after all matter changes and impulses have ended. The quoted invariant refers to a particular Fourier normalization. Total radiated energy in physical units needs the field normalization, volume convention and physical values of the source and coupling.

Holding the scalar and vector source coupling ww fixed also tests the normalization of the stress kick. Replacing wτ/2w\tau/2 by βτ/2\beta\tau/2 leaves vector error (β−w)(jn−jn−1)(\beta-w)(j_n-j_{n-1}) when starting on the constraints. Doubling just this term during the first launch produces twice the required momentum source in both implementations. This fixes the coefficient for a kick proportional to the specified stress. A separately divergence-free stress addition can change the TT response while obeying the same Ward identities.

Run the standard-library checker with python3 gravity.py. It tests both transport radii, both derivatives, the finite-qudit unitary, the local retarded update, and the reported amplitudes.

Calculations and transcript

The native Tally program records 16 assertions. The offline study archive includes the source texts, Python checks, Tally program, recorded transcript and replay instructions.

Complete Tally transcript
✓ a two-site phase scan modulates a face direction and leaves a body direction fixed  (by cross-pairing plus and minus sides; derived)
✓ the three directional modulations cancel under coordinate permutation  (by cross-pairing plus and minus sides; derived)
✓ three-tick antipodal face counts from the exact direct and cross terms  (by cross-pairing plus and minus sides; derived)
✓ single-particle fringes predict the passive boson pair coincidence  (by cross-pairing plus and minus sides; derived)
✓ contact-path interference changes the two-tick body coincidence  (by cross-pairing plus and minus sides; derived)
✓ all-site bunching discriminates a passive walk from a pi contact  (by cross-pairing plus and minus sides; derived)
✓ a quarter-turn contact removes the real interference term  (by cross-pairing plus and minus sides; derived)
✓ a nontrivial rational contact phase interpolates both detector probabilities  (by cross-pairing plus and minus sides; derived)
✓ the fourteen hopping blocks of the sine charge give an onsite square of seven eighths  (by cross-pairing plus and minus sides; derived)
✓ a symmetric onsite pair at center momentum zero-pi-zero saturates the squared leakage bound  (by cross-pairing plus and minus sides; derived)
✓ the squared two-boson norm of charge drift at cos g equal to three fifths  (by cross-pairing plus and minus sides; derived)
✓ four explicit leapfrog impulses reproduce the centered release invariant  (by cross-pairing plus and minus sides; derived)
✓ four native filtered impulses reproduce the release invariant  (by cross-pairing plus and minus sides; derived)
✓ a transverse mode with no projected source remains dark  (by cross-pairing plus and minus sides; derived)
✓ the centered causal field retains a transverse mode after one split and return  (by cross-pairing plus and minus sides; derived)
✓ the filtered native derivative retains a smaller nonzero transverse mode  (by cross-pairing plus and minus sides; derived)
Native Tally source
# Native controls for phase-switched sources, pair coincidences, and the conserved charge test.
ratchet 16 step
import "atom"
let zero = whole(0 trial)
let one = whole(1 trial)
let two = whole(2 trial)
let four = whole(4 trial)
let half = fraction(1 trial,2 trial)
fn layer(a,b,d)
  return one+flip(share(d,a+d))+flip(share(d,b+d))
end
check layer(one,one,zero)==one and layer(one,one,one)==zero "a two-site phase scan modulates a face direction and leaves a body direction fixed"
check layer(one,two,four)+layer(two,four,one)+layer(four,one,two)==zero "the three directional modulations cancel under coordinate permutation"
let one_a = fraction(35 trial,512 trial)
let fringe = fraction(33 trial,512 trial)
check one_a+fringe==fraction(17 trial,128 trial) and one_a+flip(fringe)==fraction(1 trial,256 trial) "three-tick antipodal face counts from the exact direct and cross terms"
check one_a*one_a+fringe*fringe==fraction(1157 trial,131072 trial) "single-particle fringes predict the passive boson pair coincidence"
fn born(off,on,cross,cosine)
  return off+on+two*cross*cosine
end
fn body(c)
  return born(fraction(209 trial,262144 trial),fraction(3 trial,4096 trial),flip(fraction(5 trial,8192 trial)),c)
end
fn bunched(c)
  return born(fraction(167 trial,16384 trial),fraction(239 trial,16384 trial),fraction(115 trial,16384 trial),c)
end
check body(one)==fraction(81 trial,262144 trial) and body(flip(one))==fraction(721 trial,262144 trial) "contact-path interference changes the two-tick body coincidence"
check bunched(one)==fraction(159 trial,4096 trial) and bunched(flip(one))==fraction(11 trial,1024 trial) "all-site bunching discriminates a passive walk from a pi contact"
check bunched(zero)==fraction(203 trial,8192 trial) and body(zero)==fraction(401 trial,262144 trial) "a quarter-turn contact removes the real interference term"
let calibrated = fraction(3 trial,5 trial)
check bunched(calibrated)==fraction(17 trial,512 trial) and body(calibrated)==fraction(209 trial,262144 trial) "a nontrivial rational contact phase interpolates both detector probabilities"
let hopp_x = fraction(1 trial,8 trial)
let hopp_y = fraction(1 trial,4 trial)
let hopp_z = half
let moment = whole(8 trial)*hopp_x*hopp_x+four*hopp_y*hopp_y+two*hopp_z*hopp_z
check moment==fraction(7 trial,8 trial) "the fourteen hopping blocks of the sine charge give an onsite square of seven eighths"
let triplet = two*moment+fraction(1 trial,4 trial)+half+one
check triplet==fraction(7 trial,2 trial) "a symmetric onsite pair at center momentum zero-pi-zero saturates the squared leakage bound"
check two*(one+flip(calibrated))*triplet==fraction(14 trial,5 trial) "the squared two-boson norm of charge drift at cos g equal to three fifths"
fn oscillator(b,g)
  return share(b*b*g*g*(four+flip(g)),two)
end
fn field_tick(previous,current,g,impulse)
  return (two+flip(g))*current + flip(previous) + impulse
end
fn released(b,g)
  let h3 = field_tick(zero,zero,g,b)
  let h4 = field_tick(zero,h3,g,flip(b))
  let h5 = field_tick(h3,h4,g,flip(b))
  let h6 = field_tick(h4,h5,g,b)
  let slope = h6+flip(h5)
  return share(slope*slope+g*h6*h5,two)
end
check released(two,fraction(1 trial,4 trial))==oscillator(two,fraction(1 trial,4 trial)) "four explicit leapfrog impulses reproduce the centered release invariant"
check released(fraction(3 trial,32 trial),fraction(3 trial,64 trial))==oscillator(fraction(3 trial,32 trial),fraction(3 trial,64 trial)) "four native filtered impulses reproduce the release invariant"
check released(zero,fraction(1 trial,4 trial))==zero "a transverse mode with no projected source remains dark"
check oscillator(two,fraction(1 trial,4 trial))==fraction(15 trial,32 trial) "the centered causal field retains a transverse mode after one split and return"
check oscillator(fraction(3 trial,32 trial),fraction(3 trial,64 trial))==fraction(20493 trial,536870912 trial) "the filtered native derivative retains a smaller nonzero transverse mode"

Python checks and replay

aperture.py
"""Certified weak-limit counts in two antipodal circular detector apertures.

The source is either incoherent or an in-phase/antiphase superposition at
coarse sites +/-e_z, with the same spinor at both sites. Antipodal acceptance
eliminates the spin dependence. Each aperture includes all nonzero radii.
The half-angle is atan(1/4). Run with Python 3 and its standard library.
"""

from fractions import Fraction
from math import isqrt


SCALE = 10**32


class Interval:
    """An outward-rounded interval with integer endpoints in units of 1/SCALE."""

    def __init__(self, lo, hi):
        self.lo, self.hi = lo, hi

    @classmethod
    def exact(cls, x):
        x = Fraction(x) * SCALE
        return cls(x.numerator // x.denominator, -(-x.numerator // x.denominator))

    def __add__(a, b):
        return Interval(a.lo + b.lo, a.hi + b.hi)

    def __sub__(a, b):
        return Interval(a.lo - b.hi, a.hi - b.lo)

    def __mul__(a, b):
        vals = (a.lo * b.lo, a.lo * b.hi, a.hi * b.lo, a.hi * b.hi)
        return Interval(min(vals) // SCALE, -(-max(vals) // SCALE))

    def __truediv__(a, b):
        assert b.lo > 0
        reciprocal = Interval(SCALE**2 // b.hi, -(-SCALE**2 // b.lo))
        return a * reciprocal

    def sqrt(a):
        assert a.lo >= 0
        return Interval(isqrt(a.lo * SCALE), isqrt(a.hi * SCALE) + 1)

    def hull(a, b):
        return Interval(min(a.lo, b.lo), max(a.hi, b.hi))


num = Interval.exact
ZERO, ONE, TWO = num(0), num(1), num(2)
QUARTER = num(Fraction(1, 4))
ROOT2, ROOT3, ROOT6 = (num(n).sqrt() for n in (2, 3, 6))


def atan_inverse(q):
    """Alternating arctangent series at 1/q."""
    partial = sum(Fraction((-1)**j, (2 * j + 1) * q**(2 * j + 1)) for j in range(24))
    following = Fraction(1, 49 * q**49)
    return num(partial).hull(num(partial + following))


PI = num(16) * atan_inverse(5) - num(4) * atan_inverse(239)


def sin_cos(x):
    """Enclose both values for 0 <= x <= pi/2 with alternating Taylor series."""
    out = []
    neg_x2 = ZERO - x * x
    for degree, start in ((1, x), (0, ONE)):
        total = term = start
        for j in range(1, 25):
            k = degree + 2 * j
            term = term * neg_x2 / num(k * (k - 1))
            total = total + term
        k = degree + 50
        following = term * neg_x2 / num(k * (k - 1))
        out.append(total.hull(total + following))
    return out


def gauss_nodes(length, panels):
    """Positive 4-point Gauss-Legendre rule on each equal panel."""
    offset = TWO * num(Fraction(6, 5)).sqrt()
    nodes = [((num(3) + offset) / num(7)).sqrt(),
             ((num(3) - offset) / num(7)).sqrt()]
    weights = [(num(18) - num(30).sqrt()) / num(36),
               (num(18) + num(30).sqrt()) / num(36)]
    half_width = length / num(2 * panels)
    for i in range(panels):
        center = half_width * num(2 * i + 1)
        for node, weight in zip(nodes, weights):
            delta = half_width * node
            yield center - delta, weight * half_width
            yield center + delta, weight * half_width


def cap_pair(orientation, radial_panels=24, angular_panels=120):
    """Average angular law and signed interference correction, integrated."""
    face = orientation == 'face'
    repeats = 8 if face else 12  # wedge symmetries and diametrically opposite cap
    angle = PI / num(2 if face else 3)
    angular = []
    for phi, weight in gauss_nodes(angle, angular_panels):
        s, c = sin_cos(phi)
        if face:
            angular.append((c / ROOT2, ZERO - c / ROOT2, s, weight))
        else:
            p, q = c / ROOT6, s / ROOT2
            angular.append((TWO * p, q - p, ZERO - p - q, weight))

    neutral = correction = ZERO
    base = ONE / (ROOT2 if face else ROOT3)
    for t, radial_weight in gauss_nodes(QUARTER, radial_panels):
        left = radial_weight * t
        for dx, dy, dz, angular_weight in angular:
            # w = n_center + t e_phi. Its normalization cancels between
            # the spherical area and the degree -3 directional density.
            a, b = base + t * dx, base + t * dy
            d = t * dz if face else base + t * dz
            ad, bd = a + d, b + d
            point = left * angular_weight / ((a + b) * ad * bd)
            neutral = neutral + point
            if face:
                g = ONE - d / ad - d / bd
                correction = correction + point * g

    factor = num(repeats) / (TWO * PI * PI)
    neutral, correction = factor * neutral, factor * correction
    # In a body-diagonal cone, coordinate permutations preserve the aperture.
    # Since g_x + g_y + g_z = 0 identically, its correction is exactly zero.
    results = [neutral, neutral + correction, neutral - correction]

    # Analytic quadrature bound for each of the three complete integrands.
    # For real t,phi in a wedge, each pair sum in the denominator exceeds
    # 1/2. Vary one variable in a complex disk of radius 1/8. A pair sum
    # moves by at most sqrt(2)/8 in t, or sqrt(2)*cosh(1/8)/32 in phi.
    # Each denominator then has modulus >0.32, |d|<1.4 and |1 +/- g|<11.
    # Including t/(2*pi^2), the modulus of the integrand is <8. Cauchy's
    # estimate bounds its eighth derivative by 8! * 8 / (1/8)^8.
    # The 4-point Gauss remainder after this cancellation has coefficient
    # 1/[(2*4+1)*binom(8,4)^2] = 1/44100. Positive weights sum to interval
    # length, so the two one-dimensional composite error bounds add.
    max_angle = Fraction(11, 7) if face else Fraction(22, 21)
    radius = Fraction(1, 8)
    width_t = Fraction(1, 4 * radial_panels)
    width_phi = max_angle / angular_panels
    error = (repeats * Fraction(1, 4) * max_angle * Fraction(8, 44100)
             * ((width_t / radius)**8 + (width_phi / radius)**8))
    pad = num(error).hi
    return [Interval(v.lo - pad, v.hi + pad) for v in results]


def decimal_bounds(v, digits=11):
    unit = SCALE // 10**digits
    lo, hi = v.lo // unit, -(-v.hi // unit)
    def render(x):
        return f"{x // 10**digits}.{x % 10**digits:0{digits}d}"
    return f"[{render(lo)}, {render(hi)}]"


def main():
    face = cap_pair('face')
    body = cap_pair('body')
    print("Antipodal circular-aperture probabilities, half-angle atan(1/4)")
    print("preparation     face-diagonal pair                   body-diagonal pair"
          "                   face / body")
    for name, f, b in zip(("incoherent", "in-phase", "antiphase"), face, body):
        assert f.hi - f.lo < SCALE // 10**10
        assert b.hi - b.lo < SCALE // 10**10
        print(f"{name:12}  {decimal_bounds(f)}  {decimal_bounds(b)}  {decimal_bounds(f/b, 8)}")
    assert face[1].lo > face[0].hi > face[2].hi
    assert face[1].lo > body[1].hi and face[2].hi < body[2].lo
    # Point-aperture controls follow by setting d=0 (face) or a=b=d (body).
    for a, b, d, expected in ((1, 1, 0, 1), (1, 1, 1, 0)):
        assert 1 - Fraction(d, a + d) - Fraction(d, b + d) == expected
    print("Point-aperture factors (in-phase, antiphase): face (2,0), body (1,1).")


if __name__ == "__main__":
    main()
charge.py
"""Check the bare sine-of-eigenphase charge in the one- and two-boson walk."""
from fractions import Fraction
from contact import Z, add, mul, norm, kernel


def conjugate(value):
    return value[0], -value[1]


def blocks():
    # Denominator 32 for F=(W^dagger-W)/(2i). K below gives 16 W.
    k = {(r,out,spin):amp for spin,col in kernel().items() for r,out,amp in col}
    sites = {r for r,out,spin in k}
    f = {}
    for r in sites:
        back = tuple(-x for x in r)
        for out in (0,1):
            for spin in (0,1):
                a = k.get((r,out,spin),Z)
                b = conjugate(k.get((back,spin,out),Z))
                f[r,out,spin] = mul((0,1),(a[0]-b[0],a[1]-b[1]))
    return sites,f


def main():
    sites,f = blocks()
    assert f[(0,0,1),0,0] == (0,16)
    assert (0,0,0) not in sites
    for spin in (0,1):
        diagonal = sum(norm(f[r,out,spin]) for r in sites for out in (0,1))
        assert Fraction(diagonal,32**2) == Fraction(7,8)
    # P Q² P acts on a pair at the same site. Evaluate the K=(0,pi,0)
    # center-momentum symbol on triplet |up down>+|down up> (unnormalized).
    for i in (0,1):
        for j in (0,1):
            acc = (0,0)
            for r in sites:
                sign = 1 if r[1]%2==0 else -1
                val = add(mul(f[r,i,0],f[r,j,1]),mul(f[r,i,1],f[r,j,0]))
                acc = add(acc,(2*sign*val[0],2*sign*val[1]))
            assert acc[1]==0
            spin = int(i!=j)
            diag = Fraction(7,4)*spin + Fraction(acc[0],32**2)
            assert diag == Fraction(7,2)*spin
    print("Sine charge: nearest z-up hop modulus 1/2, onsite squared moment 7/8.")
    print("The projected Q² center-momentum symbol attains 7/2 on the symmetric triplet.")


if __name__ == "__main__":
    main()
contact.py
"""Exact two-tick scattering complement to the one-particle aperture measurements.

The two walkers start at (0,0,-1) and (0,0,1) with identical +z spin.
At each complete tick a contact phase multiplies every bunched position
configuration. A final diagonal phase leaves position probabilities invariant.
All amplitudes are pairs of integers for their real and imaginary parts.
"""
from fractions import Fraction
from math import comb
from counts import ORIGIN, STAGES, step, in_pair

Z = (0,0)
def add(a,b):
    return a[0]+b[0], a[1]+b[1]

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

def norm(a):
    return a[0]**2+a[1]**2

def kernel():
    table = {}
    for spin in (0,1):
        col = {ORIGIN:(1,0,0,0) if spin==0 else (0,0,1,0)}
        for axis in STAGES:
            col = step(col,axis)
        for site,values in col.items():
            pos = tuple(v//2 for v in site)
            for out in (0,1):
                value = tuple(values[2*out:2*out+2])
                if value != Z:
                    table.setdefault(spin,[]).append((pos,out,value))
    return table

def propagate(state,table,which):
    out = {}
    for (p,s,q,t),weight in state.items():
        old,spin = (p,s) if which==0 else (q,t)
        for delta,sp,amplitude in table[spin]:
            dest = tuple(x+y for x,y in zip(old,delta))
            key = (dest,sp,q,t) if which==0 else (p,s,dest,sp)
            out[key] = add(out.get(key,Z),mul(weight,amplitude))
    return {key:v for key,v in out.items() if v != Z}

def two_ticks(table,phase,exchange,keep=None):
    left,right = (0,0,-1),(0,0,1)
    state = {(left,0,right,0):(1,0)}
    if exchange:
        state[right,0,left,0] = (1,0)
    for tick in range(2):
        for which in (0,1):
            state = propagate(state,table,which)
        if tick==0:
            if keep is not None:
                state = {key:v for key,v in state.items() if (key[0]==key[2])==keep}
            real,imag,scale = phase
            assert real*real+imag*imag==scale*scale
            state = {key:mul((real,imag) if key[0]==key[2] else (scale,0),v) for key,v in state.items()}
    denominator = (2 if exchange else 1)*16**8*phase[2]**2
    if keep is None:
        assert sum(map(norm,state.values())) == denominator
    if exchange:
        assert all(state.get((q,t,p,s))==v for (p,s,q,t),v in state.items())
    return state,denominator

def history_gram(table):
    off,den = two_ticks(table,(1,0,1),True,False)
    on,_ = two_ticks(table,(1,0,1),True,True)
    result = {}
    for name in ("body","same"):
        values = [0]*4
        for key in off.keys()|on.keys():
            p,s,q,t = key
            if name=="body":
                if not (in_pair(p,(1,1,1)) and in_pair(q,(1,1,1))):
                    continue
            elif p!=q:
                continue
            a,b = off.get(key,Z),on.get(key,Z)
            cross = mul((a[0],-a[1]),b)
            for i,term in enumerate((norm(a),norm(b),*cross)):
                values[i] += term
        result[name] = tuple(Fraction(v,den) for v in values)
    return result


def lower_tail(p,n,cut):
    a,d = p.numerator,p.denominator
    return Fraction(sum(comb(n,k)*a**k*(d-a)**(n-k) for k in range(cut)),d**n)


def main():
    table = kernel()
    print('Postselected free-path and contact-path Gram matrices:', history_gram(table))
    errors = lower_tail(Fraction(159,4096),1000,22),1-lower_tail(Fraction(11,1024),1000,22)
    assert all(v < Fraction(1,500) for v in errors)
    print('Ideal same-site test errors:', *(float(v) for v in errors))
    configs = (("distinguishable",(1,0,1),False),("free bosons",(1,0,1),True),("pi",(-1,0,1),True),("pi/2",(0,1,1),True),("minus pi/2",(0,-1,1),True),("3+4i over 5",(3,4,5),True))
    for label,sign,exchange in configs:
        state,denom = two_ticks(table,sign,exchange)
        both = {"body":0,"face":0,"same site":0,"z=1":0}
        for (p,s,q,t),v in state.items():
            weight = norm(v)
            for name,d in (("face",(1,1,0)),("body",(1,1,1))):
                if in_pair(p,d) and in_pair(q,d):
                    both[name] += weight
            both["same site"] += weight*(p==q)
            both["z=1"] += weight*(p[2]==q[2]==1)
        probs = {k:Fraction(v,denom) for k,v in both.items()}
        if exchange:
            cosine = Fraction(sign[0],sign[2])
            assert probs["body"] == (401-320*cosine)/262144
            assert probs["same site"] == (203+115*cosine)/8192
            assert probs["z=1"] == (13-cosine)/128
        else:
            assert probs["body"] == Fraction(81,262144)
            assert probs["same site"] == Fraction(159,8192)
        print(label,probs)

if __name__ == "__main__":
    main()
counts.py
"""Exact finite detector probabilities for two coherent sources in the six-stage walk."""
import argparse
from fractions import Fraction
from pathlib import Path
import sys

# In the download, walk.py is the previously published integer-amplitude replay.
ROOT = Path(__file__).resolve().parent
walk_dir = ROOT / "prior"
if not (walk_dir / "walk.py").is_file():
    walk_dir = ROOT.parent / "convex-fronts"
sys.path.insert(0, str(walk_dir))
from walk import ORIGIN, STAGES, ZERO, step


def in_pair(r, direction):
    """Two antipodal cones of half-angle arctan(1/4), excluding the origin."""
    radius2 = sum(v*v for v in r)
    dot = sum(v*w for v, w in zip(r, direction))
    return radius2 != 0 and 17*dot*dot >= 16*radius2*sum(w*w for w in direction)


def inner(a, b):
    """Real and imaginary parts of the complex inner product of integer spinors."""
    return (sum(x*y for x,y in zip(a,b)),
            sum(a[i]*b[i+1]-a[i+1]*b[i] for i in (0,2)))


def shifted(state, dz):
    return {(x//2,y//2,z//2+dz):value for (x,y,z),value in state.items()}


def detector(n, a, b, sites):
    # a and b are the two translated source kernels, each with both spin inputs.
    norm = 16**(2*n)
    aa, bb, ab = [[0]*8 for _ in range(3)]
    for site in sites:
        av = [col.get(site, ZERO) for col in a]
        bv = [col.get(site, ZERO) for col in b]
        for matrix, left, right in ((aa,av,av),(bb,bv,bv),(ab,av,bv)):
            for i in (0,1):
                for j in (0,1):
                    re,im = inner(left[i], right[j])
                    idx = 4*i+2*j
                    matrix[idx] += re
                    matrix[idx+1] += im
    # Inversion-paired aperture: total direct response and cross response are scalar in spin.
    total = [x+y for x,y in zip(aa,bb)]
    for matrix in (total,ab):
        assert matrix[:2] == matrix[6:] and matrix[2:6] == [0]*4
    pa,pb,qr,qi = [Fraction(v,norm) for v in (aa[0],bb[0],ab[0],ab[1])]
    incoherent = (pa+pb)/2
    exchange = qr**2+qi**2
    return dict(a=pa,b=pb,mix=incoherent,plus=incoherent+qr,minus=incoherent-qr,
                cross_im=qi,delayed=pa*pb,overlap=pa*pb+exchange)


def measure(n, up, down):
    a,b = [[shifted(col,dz) for col in (up,down)] for dz in (-1,1)]
    sites = set().union(*(c.keys() for c in a+b))
    full = detector(n,a,b,sites)
    assert all(full[k] == 1 for k in ("a","b","mix","plus","minus","delayed","overlap"))
    assert full["cross_im"] == 0
    rows = {}
    for name,direction in (("face",(1,1,0)),("body",(1,1,1))):
        rows[name] = detector(n,a,b,[r for r in sites if in_pair(r,direction)])
    return rows


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("ticks",type=int,nargs="*",default=[3,4,8,12])
    times = set(parser.parse_args().ticks)
    if not times or min(times)<1:
        parser.error("tick counts must be positive")
    up,down = {ORIGIN:(1,0,0,0)}, {ORIGIN:(0,0,1,0)}
    for n in range(1,max(times)+1):
        for axis in STAGES:
            up,down = step(up,axis),step(down,axis)
        if n in times:
            for name,row in measure(n,up,down).items():
                if n==3 and name=="face":
                    assert (row["plus"],row["minus"],row["overlap"]) == (Fraction(17,128),Fraction(1,256),Fraction(1157,131072))
                print(n,name," ".join(f"{key}={float(value):.9f}" for key,value in row.items()))
                if n<=4:
                    print("  exact", ", ".join(f"{k}={v}" for k,v in row.items()))


if __name__ == "__main__":
    main()
gravity.py
"""Finite-support transport of a coupled scalar and vector Gauss source.

Python 3 standard library. Coordinates are twice the fine-site coordinates.
Sparse maps omit zero coefficients; all stencils use integer or rational arithmetic.
"""

from fractions import Fraction
from itertools import product

PERIOD = (0, 0, 0, 1, 1, 0)
ENERGY = 2
ORIGIN = (0, 0, 0)
UNIT = {ORIGIN: 1}


def add(*fields):
    result = {}
    for field in fields:
        for location, value in field.items():
            result[location] = result.get(location, 0) + value
    return {p: v for p, v in result.items() if v}


def times(field, factor):
    return {p: factor * v for p, v in field.items() if factor * v}


def sub(first, second):
    return add(first, times(second, -1))


def stencil(field, axis, terms):
    """Apply sum c*f(x+s) at all sites, pairing each field with its stagger."""
    parts = []
    for offset, coefficient in terms:
        shifted = {}
        for point, value in field.items():
            dest = list(point)
            dest[axis] -= offset
            shifted[tuple(dest)] = coefficient * value
        parts.append(shifted)
    return add(*parts)


def centered(field, axis):
    return stencil(field, axis, [(1, 1), (-1, -1)])


def average(field, axis, radius):
    half = Fraction(1, 2)
    return stencil(field, axis, [(radius, half), (-radius, half)])


def native(field, axis):
    quarter = Fraction(1, 4)
    field = stencil(field, axis, [(4, quarter), (-4, -quarter)])
    for j in range(axis + 1, 3):
        field = average(field, j, 4)
    return field


def filters(field, axes):
    for i in axes:
        field = average(average(field, i, 1), i, 2)
        for j in range(i + 1, 3):
            field = average(field, j, 4)
    return field


def diagonal_curvature(diagonal, derivative):
    trace = add(*diagonal)
    return add(*(derivative(derivative(sub(diagonal[i], trace), i), i)
                 for i in range(3)))


def phase_values(branch, stage):
    def f(t):
        return branch * PERIOD[t % len(PERIOD)]
    return f(stage), f(stage + 1) - f(stage), f(stage) - f(stage - 1)


def ledger(radius, use_native):
    derivative = native if use_native else centered
    def smooth(field, factors):
        return filters(field, factors) if use_native else field

    # Start with directly assigned densities and directed fluxes. The triangle
    # solves D_x^2 Q = rho_separated - rho_center, including radius 2.
    center = times(UNIT, 2 * ENERGY)
    ends = {(s * 2 * radius, 0, 0): ENERGY for s in (-1, 1)}
    flux = {(s * (2 * x + 1), 0, 0): s * ENERGY
            for x in range(radius) for s in (-1, 1)}
    triangle = {(2*x, 0, 0): ENERGY * (radius - abs(x))
                for x in range(1-radius, radius)}
    center = smooth(center, (0, 1, 2, 0, 1, 2))   # L0^2
    ends = smooth(ends, (0, 1, 2, 0, 1, 2))
    flux = smooth(flux, (0, 1, 2, 1, 2))         # L0 Lx
    triangle = smooth(triangle, (1, 2, 1, 2))    # Lx^2
    half = Fraction(1, 2)
    change = sub(ends, center)
    assert sum(ends.values()) == sum(center.values()) == 2 * ENERGY
    assert min(ends.values()) > 0 and min(center.values()) > 0

    # A finite scalar dressing carries zero energy dipole. This uncompensated
    # hop has the same nonzero dipole even after native finite averaging.
    single = sub({(2 * radius, 0, 0): ENERGY}, times(UNIT, ENERGY))
    single = smooth(single, (0, 1, 2, 0, 1, 2))
    assert sum(Fraction(p[0], 2) * v for p, v in single.items()) == radius * ENERGY
    assert all(sum(p[i] * v for p, v in change.items()) == 0 for i in range(3))
    # Opposite axial momenta give zero total and angular momentum.
    assert sum(flux.values()) == 0
    assert all(sum(p[i] * v for p, v in flux.items()) == 0 for i in (1, 2))
    # Axial transfer k=(0,0,pi/3) has real cosines on every h/TT site.
    cosines = (1, half, -half, -1, -half, half)
    def axial_component(field):
        assert all(p[2] % 2 == 0 for p in field)
        return sum(v * cosines[(p[2] // 2) % 6] for p, v in field.items())

    for branch in (0, 1):
        for stage in range(len(PERIOD)):
            f, u, prev_u = phase_values(branch, stage)
            h = [times(triangle, sign * f * half) for sign in (1, -1, -1)]
            pxx = times(triangle, u * half)
            stress = times(triangle, u - prev_u)
            assert diagonal_curvature(h, derivative) == times(change, f)
            assert times(derivative(pxx, 0), -2) == times(flux, u)
            assert not add(times(change, u), derivative(times(flux, u), 0))
            assert not add(times(flux, u - prev_u), derivative(stress, 0))
            next_f, _, _ = phase_values(branch, stage + 1)
            prev_f, _, _ = phase_values(branch, stage - 1)
            for i, sign in enumerate((1, -1, -1)):
                next_h = times(triangle, sign * next_f * half)
                kinetic = sub(times(pxx, 2) if i == 0 else {}, pxx)
                assert sub(next_h, h[i]) == kinetic
            # At k parallel to z, H=hxx-hyy is the unnormalized plus mode.
            # Evaluate (delta_t^2 - D_i D_i) H - (tau_xx-tau_yy).
            hplus = sub(h[0], h[1])
            ddh = times(triangle, next_f - 2*f + prev_f)
            laplacian = add(*(derivative(derivative(hplus, i), i) for i in range(3)))
            residual = axial_component(sub(sub(ddh, laplacian), stress))
            predicted = radius**2 * (Fraction(9, 512) if use_native else 2) * f
            assert residual == predicted
    return len(change), len(flux), radius**2 * (Fraction(9, 512) if use_native else 2)


# Exhaustive quantum test for the radius-one block. Only the three diagonal
# metric qudits at its center are shifted. Constraint factors on every other
# qudit commute with the block and cancel from its commutator. Each amplitude
# is a single seventh root of unity; store its exponent exactly.
K = 7


def dressing(branch, stage):
    f, u, _ = phase_values(branch, stage)
    return (f, -f, -f), (u, 0, 0)  # ENERGY/2 = 1


def tick(state):
    branch, stage, coordinates, phase = state
    a, b = dressing(branch, stage)
    target = (stage + 1) % len(PERIOD)
    new_a, new_b = dressing(branch, target)
    common = tuple(x - k for x, k in zip(coordinates, a))
    coords = tuple((x + k) % K for x, k in zip(common, new_a))
    # W_target W_stage^dagger for W = X^a Z^b, with Z acting first.
    phase += sum((t - s) * x for s, t, x in zip(b, new_b, common))
    return branch, target, coords, phase % K


def energy_check(state, position, coefficients):
    branch, stage, coordinates, phase = state
    f, _, _ = phase_values(branch, stage)
    rho_change = {(0, 0, 0): -2 * ENERGY, (2, 0, 0): ENERGY,
                  (-2, 0, 0): ENERGY}.get(position, 0)
    exponent = sum(c * x for c, x in zip(coefficients, coordinates)) - f * rho_change
    return branch, stage, coordinates, (phase + exponent) % K


def momentum_check(state, axis, sign):
    branch, stage, coordinates, phase = state
    _, u, _ = phase_values(branch, stage)
    # At +/- half a site M_i includes +/-2*pi_ii(0). Its exponential
    # translates h_ii(0) by the negative coefficient.
    coords = list(coordinates)
    coords[axis] = (coords[axis] - 2 * sign) % K
    j = sign * ENERGY * u if axis == 0 else 0
    return branch, stage, tuple(coords), (phase - j) % K


def quantum():
    columns = []
    for i in range(3):
        diagonal = [UNIT if j == i else {} for j in range(3)]
        columns.append(diagonal_curvature(diagonal, centered))
    sites = set().union(*columns)
    constraints = [(site, tuple(column.get(site, 0) for column in columns))
                   for site in sorted(sites)]
    count = 0
    for branch, stage, coords in product((0, 1), range(len(PERIOD)),
                                         product(range(K), repeat=3)):
        state = (branch, stage, coords, 0)
        after = tick(state)
        for site, coeff in constraints:
            assert tick(energy_check(state, site, coeff)) == energy_check(after, site, coeff)
        for axis, sign in product(range(3), (-1, 1)):
            assert tick(momentum_check(state, axis, sign)) == momentum_check(after, axis, sign)
        full = state
        for _ in PERIOD:
            full = tick(full)
        assert full == state   # no residual phase from the noncommuting dressings
        count += 1
    assert count == 2 * len(PERIOD) * K**3
    branches = [(b, 0, (0, 0, 0), 0) for b in (0, 1)]
    for _ in range(3):
        branches = [tick(state) for state in branches]
    assert branches[0][2] == (0, 0, 0)
    assert branches[1][2] == (1, K - 1, K - 1)
    return count, len(constraints) + 6




# Unprojected retarded evolution. Symmetric tensors store six independent
# components; contractions below still count both off-diagonal entries.
PAIRS = tuple((i, j) for i in range(3) for j in range(i, 3))


def component(tensor, i, j):
    return tensor[min(i, j), max(i, j)]


def divergence(tensor, derivative):
    return [add(*(derivative(component(tensor, i, j), j) for j in range(3)))
            for i in range(3)]


def spatial_einstein(tensor, derivative):
    trace = add(*(tensor[i, i] for i in range(3)))
    div = divergence(tensor, derivative)
    curvature = sub(add(*(derivative(div[i], i) for i in range(3))),
                    add(*(derivative(derivative(trace, i), i) for i in range(3))))
    force = {}
    for i, j in PAIRS:
        lap = add(*(derivative(derivative(tensor[i, j], k), k) for k in range(3)))
        ddtrace = derivative(derivative(trace, j), i)
        force[i, j] = times(sub(add(derivative(div[j], i), derivative(div[i], j)),
                                add(lap, ddtrace, curvature if i == j else {})),
                            Fraction(1, 2))
    return curvature, force


def tidal_contrast(h, derivative):
    """Twice (R_xzxz - R_yzyz) in the spatial metric on a flat background."""
    def twice_riemann(i):
        shear = times(derivative(derivative(h[i, 2], 2), i), 2)
        return sub(shear, add(derivative(derivative(h[i, i], 2), 2),
                              derivative(derivative(h[2, 2], i), i)))
    return sub(twice_riemann(0), twice_riemann(1))


def evolve(use_native):
    half = Fraction(1, 2)
    speed_sq = Fraction(1, 4)
    # Native verification uses a six-site torus (216 vertices), chosen to
    # include k_z=pi/3. Centered verification uses the infinite sparse lattice.
    def fold(field):
        if not use_native:
            return field
        folded = {}
        for point, value in field.items():
            dest = tuple(x % 12 for x in point)
            folded[dest] = folded.get(dest, 0) + value
        return {p: v for p, v in folded.items() if v}

    def derivative(field, i):
        return fold(native(field, i)) if use_native else centered(field, i)

    def smooth(field, factors):
        return fold(filters(field, factors)) if use_native else field

    triangle = smooth(times(UNIT, ENERGY), (1, 2, 1, 2))
    delta = smooth({(-2, 0, 0): ENERGY, (2, 0, 0): ENERGY,
                    ORIGIN: -2 * ENERGY}, (0, 1, 2, 0, 1, 2))
    flux = smooth({(-1, 0, 0): -ENERGY, (1, 0, 0): ENERGY},
                  (0, 1, 2, 1, 2))
    cosines = (1, half, -half, -1, -half, half)
    def axial_fourier(field, axis):
        assert all(p[axis] % 2 == 0 for p in field)
        # Exact sine divided by sin(pi/3); the histories are reflection-symmetric.
        sines = (0, 1, 1, 0, -1, -1)
        assert sum(v * sines[(p[axis] // 2) % 6] for p, v in field.items()) == 0
        return sum(v * cosines[(p[axis] // 2) % 6] for p, v in field.items())

    def f(n):
        return int(n in (3, 4))   # one pulse, then permanently idle

    h = {ij: {} for ij in PAIRS}
    pi = {ij: {} for ij in PAIRS}
    plus = []
    detector = []
    central = []
    for n in range(10):
        curvature, force = spatial_einstein(h, derivative)
        assert not any(divergence(force, derivative))  # exact spatial Bianchi
        assert curvature == times(delta, f(n))
        expected_j = times(flux, f(n) - f(n-1))
        assert [times(v, -2) for v in divergence(pi, derivative)] == [expected_j, {}, {}]
        central.append(curvature.get(ORIGIN, 0))
        plus.append(axial_fourier(sub(h[0, 0], h[1, 1]), 2))
        # Two transverse polarizations both vanish on the source axis.
        assert axial_fourier(sub(h[1, 1], h[2, 2]), 0) == 0
        # The yz shear is a half-grid in y,z, but integer-valued in x.
        assert axial_fourier(h[1, 2], 0) == 0
        if not use_native:
            detector.append(tidal_contrast(h, derivative).get((0, 0, 6), 0))
        stress = times(triangle, f(n+1) - 2*f(n) + f(n-1))
        if n == 2:
            # At the first launch, doubling just the stress coupling from
            # w=1 to beta=2 produces exactly one extra copy of the flux.
            wrong_pxx = add(pi[0, 0], times(force[0, 0], -speed_sq), stress)
            wrong_pi = {**pi, (0, 0): wrong_pxx}
            assert times(divergence(wrong_pi, derivative)[0], -2) == times(flux, 2)
        for ij in PAIRS:
            pi[ij] = add(pi[ij], times(force[ij], -speed_sq),
                         times(stress, half) if ij == (0, 0) else {})
        trace_pi = add(*(pi[i, i] for i in range(3)))
        for i, j in PAIRS:
            h[i, j] = sub(add(h[i, j], times(pi[i, j], 2)),
                          trace_pi if i == j else {})

    g = Fraction(3, 64) if use_native else Fraction(1, 4)
    B = Fraction(3, 32) if use_native else 2
    invariant = B**2 * g**2 * (4-g) / 2
    for n in range(5, len(plus)-1):
        a, b = plus[n], plus[n+1]
        assert ((b-a)**2 + g*a*b)/2 == invariant
    assert plus[5] == B*(g**2-3*g) and plus[6] == -B*g*(g**2-5*g+5)
    assert all(v == 0 for v in central[5:])
    if use_native:
        assert central[3] == -Fraction(33, 4096)
    else:
        assert central[3] == -4
        assert detector[:5] == [0] * 5
        assert detector[5] == -Fraction(1, 8) and detector[7] == Fraction(21, 64)
    return plus[5:7], invariant, central[3], detector


if __name__ == "__main__":
    for r, use_native in product((1, 2), (False, True)):
        nr, nj, residual = ledger(r, use_native)
        print(f"radius={r}, {'native' if use_native else 'centered'}, "
              f"12 branch/stage pairs verified, {nr} density and {nj} flux entries, "
              f"split-state TT residual {residual}")
    states, stabilizers = quantum()
    print(f"{states} basis states x {stabilizers} stabilizers commute with U; "
          "U^6 = I including phases; neutral-coin branches distinguishable")

    for use_native in (False, True):
        trace, invariant, center, detector = evolve(use_native)
        print(f"retarded {'native torus' if use_native else 'centered open lattice'}: "
              f"H5,H6={[str(x) for x in trace]}, free invariant={invariant}, "
              f"central split curvature={center}")
        if detector:
            print("spatial curvature at z=3 for n=0..9:", [str(x) for x in detector])
photon_wedges.py
"""Read the mixed-input 2D optical-walk chart from Jeong et al., Fig. 6.

Example: python photon_wedges.py --download, or --archive <arXiv source tar>.
This recovers normalized *plotted* measurements. The original photon time
tags, per-site integer counts and their statistical errors are unavailable
in this source. No figure from the article is redistributed by this script.
"""
import argparse
from collections import defaultdict
import hashlib
import io
from math import atan2, hypot, sqrt
from pathlib import Path
import re
import tarfile
from urllib.request import urlopen

SOURCE = "https://arxiv.org/src/1309.6837v1"
FIGURE = "fig5_mixed.eps"
SHA256 = "a21c6290e6f66dadc498e705890497c4e96e8a2163a6186ef0430ef379f7d753"
SIDE_COLORS = {"0 .362646 .277745 0 cmyk", ".582971 .616968 .083497 0 cmyk"}
POINT = re.compile(r"([.\d-]+) ([.\d-]+) (mo|li)")


def components(edges):
    neighbors = defaultdict(set)
    for a, b in edges:
        neighbors[a].add(b)
        neighbors[b].add(a)
    while neighbors:
        todo = [next(iter(neighbors))]
        group = set()
        while todo:
            point = todo.pop()
            if point in neighbors:
                group.add(point)
                todo.extend(neighbors.pop(point))
        yield group


def bars_from_chart(data):
    eps = data.decode("latin1")
    lines = eps[eps.index("%%Page:"):eps.index("%%PageTrailer")].splitlines()
    edges = set()
    for i, line in enumerate(lines):
        if line not in SIDE_COLORS:
            continue
        points = []
        for command in reversed(lines[i-15:i]):
            hit = POINT.fullmatch(command)
            if hit:
                points.append((float(hit[1]), float(hit[2])))
                if hit[3] == "mo":
                    break
        points = list(dict.fromkeys(points))
        assert len(points) == 4
        for a, b in zip(points, points[1:]+points[:1]):
            edges.add(tuple(sorted((a, b))))
    for group in components(edges):
        uprights = [(a, b) for a, b in edges if a in group
                    and abs(b[1]-a[1]) > 5*abs(b[0]-a[0])]
        # In this EPS the graphic's ground plane has the higher y coordinate.
        cols = [(min(g, key=lambda p:p[1]), max(g, key=lambda p:p[1]))
                for g in components(uprights)]
        assert len(cols) == 4
        yield cols


def vanishing_point(lines):
    # Least squares intersection of the unit-normal lines a*x+b*y+c=0.
    aa = ab = bb = ac = bc = 0.0
    for p, q in lines:
        dx, dy = q[0]-p[0], q[1]-p[1]
        a, b = -dy/hypot(dx, dy), dx/hypot(dx, dy)
        c = -a*p[0]-b*p[1]
        aa += a*a
        ab += a*b
        bb += b*b
        ac += a*c
        bc += b*c
    det = aa*bb-ab*ab
    return (ab*bc-bb*ac)/det, (ab*ac-aa*bc)/det


def grid_levels(slopes):
    # Five rows fan out from each horizontal vanishing point. Split the four
    # large inter-row gaps, tolerating the measured cell with zero bar height.
    ranks = sorted(enumerate(slopes), key=lambda row:row[1])
    gaps = [b[1]-a[1] for a, b in zip(ranks, ranks[1:])]
    breaks = set(sorted(range(len(gaps)), key=gaps.__getitem__, reverse=True)[:4])
    labels = [0]*len(slopes)
    level = -4
    for i, (site, _) in enumerate(ranks):
        labels[site] = level
        if i in breaks:
            level += 2
    return labels


def read_panel(bars):
    horizon_edges = [[], []]
    centers = []
    vertical_edges = []
    for cols in bars:
        bases = [b for _, b in cols]
        cx, cy = (sum(p[i] for p in bases)/4 for i in (0, 1))
        centers.append((cx, cy))
        bases.sort(key=lambda p:atan2(p[1]-cy, p[0]-cx))
        for p, q in zip(bases, bases[1:]+bases[:1]):
            family = int((p[0]-q[0])*(p[1]-q[1]) > 0)
            horizon_edges[family].append((p, q))
        vertical_edges.extend((t, b) for t, b in cols if b[1]-t[1] > 5)
    v1, v2 = map(vanishing_point, horizon_edges)
    vz = vanishing_point(vertical_edges)
    # Plane horizon is the line through the two infinite ground directions.
    a, b = v1[1]-v2[1], v2[0]-v1[0]
    c = v1[0]*v2[1]-v1[1]*v2[0]
    axes = [grid_levels([(y-vy)/(x-vx) for x, y in centers]) for vx, vy in (v1, v2)]
    heights = {}
    for x, y, cols in zip(*axes, bars):
        assert (x, y) not in heights
        values = []
        for top, foot in cols:
            # Homogeneous camera depth of the ground, times vertical cross ratio.
            depth = 1/(a*foot[0]+b*foot[1]+c)
            values.append(abs(depth*(top[1]-foot[1])/(vz[1]-top[1])))
        heights[x, y] = values
    return heights


def normalized(heights):
    values = {point:sum(edges)/len(edges) for point, edges in heights.items()}
    norm = sum(values.values())
    return {point:h/norm for point, h in values.items()}


def in_wedges(point):
    x, y = map(abs, point)
    return x+y > 0 and 4*min(x, y) <= max(x, y)


def ideal_four_steps():
    distribution = defaultdict(float)
    for basis in ((1, 0), (0, 1)):
        state = {(0, 0):basis}
        for axis in (0, 1)*4:
            new = defaultdict(lambda:[0, 0])
            for point, (up, down) in state.items():
                for sign in (-1, 1):
                    target = list(point)
                    target[axis] += sign
                    new[tuple(target)][int(sign<0)] += up+sign*down
            state = new
        for point, (up, down) in state.items():
            distribution[point] += (up**2+down**2)/(2*2**8)
    return distribution


def analyze(archive):
    with tarfile.open(fileobj=archive) as source:
        eps = source.extractfile(FIGURE).read()
    assert hashlib.sha256(eps).hexdigest() == SHA256
    panels = [[], []]
    for bar in bars_from_chart(eps):
        region = int(sum(b[0] for _, b in bar)/4 > 195)
        panels[region].append(bar)
    assert [len(p) for p in panels] == [25, 24]
    control, measured = map(read_panel, panels)
    exact = ideal_four_steps()
    digitized, observed = normalized(control), normalized(measured)
    error = max(abs(digitized[p]-v) for p, v in exact.items())
    assert error < 4e-6
    fraction = lambda data: sum(v for p, v in data.items() if in_wedges(p))
    assert fraction(exact) == 19/32
    # Spread obtained by taking the extreme of four reconstructed edges per
    # bar. This probes digitization consistency, not photon sampling error.
    groups = [[edges for p, edges in measured.items() if in_wedges(p) == flag]
              for flag in (True, False)]
    low, high = [(sum(map(min, group)), sum(map(max, group))) for group in groups]
    interval = low[0]/(low[0]+high[1]), low[1]/(low[1]+high[0])
    similarity = sum(sqrt(v*observed.get(p, 0)) for p,v in exact.items())**2
    print(f"maximum single-site error in known theory panel: {error:.8f}")
    print(f"four wedges, exact={fraction(exact):.8f}, theory chart={fraction(digitized):.8f}")
    print(f"four wedges, experiment={fraction(observed):.8f}, edge spread={interval}")
    print(f"origin={observed[0,0]:.8f}, full-distribution similarity={similarity:.8f}")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument("--archive", type=Path)
    source.add_argument("--download", action="store_true")
    args = parser.parse_args()
    if args.archive:
        with args.archive.open("rb") as stream:
            analyze(stream)
    else:
        with urlopen(SOURCE, timeout=60) as response:
            analyze(io.BytesIO(response.read()))


if __name__ == "__main__":
    main()
raw_atom_wedges.py
"""Score four axial wedges in the Young et al. 2D strontium fluorescence shots.

Python standard library. Pass the original tunnel.zip or --download to retrieve
the 392.5 MB Zenodo file in a temporary directory. The angular gate uses
lattice-site coordinates. An unmoved atom contributes to the denominator only.
The interval describes counting noise conditional on two valid detections.
"""
import argparse
import ast
import cmath
from collections import Counter
import hashlib
from math import cos, pi, sin, sqrt
from pathlib import Path
import shutil
import struct
import tempfile
from urllib.request import urlopen
import zipfile

URL = "https://zenodo.org/api/records/6519158/files/tunnel.zip/content"
MD5 = "8fc916b8f123ab74f602c738d06ebf80"
GROUPS = {"5.0 ms": (68, 69, 70, 72), "6.5 ms": (63, 65)}
THRESHOLDS = (4.0, 4.5, 5.0)


def peak_sites(archive, frame, run):
    name = f"tunnel/roisums{frame}_{run}.npy"
    with archive.open(name) as stream:
        assert stream.read(8) == b"\x93NUMPY\x01\x00"
        header_length = int.from_bytes(stream.read(2), "little")
        description = ast.literal_eval(stream.read(header_length).decode("ascii"))
        variations, repeats, regions, sites = description["shape"]
        assert (variations, regions, sites) == (1, 1, 29**2)
        assert description["descr"] == "<f8" and not description["fortran_order"]
        row = struct.Struct(f"<{sites}d")
        for _ in range(repeats):
            values = row.unpack(stream.read(row.size))
            signal = max(values)
            yield divmod(values.index(signal), 29), signal/70
        assert not stream.read(1)


def count_run(archive, run):
    counts = {cut: Counter() for cut in THRESHOLDS}
    for (p0, first), (p1, last) in zip(peak_sites(archive, 0, run),
                                        peak_sites(archive, 1, run)):
        x, y = (abs(a-b) for a, b in zip(p0, p1))
        for cut, count in counts.items():
            count["shots"] += 1
            if first <= cut:
                continue
            count["loaded"] += 1
            if last <= cut:
                continue
            count["retained"] += 1
            count["origin"] += (x == y == 0)
            count["edge"] += (0 in p1 or 28 in p1)
            count["axial"] += (x+y > 0 and 4*min(x, y) <= max(x, y))
    return counts


def wilson(success, total):
    z = 1.959963984540054
    p = success/total
    denominator = 1 + z*z/total
    center = (p + z*z/(2*total))/denominator
    half = z*sqrt((p*(1-p)+z*z/(4*total))/total)/denominator
    return center-half, center+half


def effective(t, settings):
    """Servo-settling fit used in cell 38 of the authors’ QRW_calculations.ipynb."""
    a, tau, t0 = settings
    return sqrt(a + (t/tau-t0)**2) - sqrt(a)
def lattice_probabilities(t, size):
    center = size // 2
    momenta = [pi*p/(size+1) for p in range(1, size+1)]
    coeffs = [2/(size+1)*sin(k*(center+1))*cmath.exp(-2j*t*cos(k))
              for k in momenta]
    return [abs(sum(c*sin(k*(site+1)) for c,k in zip(coeffs, momenta)))**2
            for site in range(size)]
def atomic_model(t, size=29):
    # The two tuples are the fit coefficients printed in notebook cell 39.
    # This comparator omits the independently modeled loss of fringe contrast.
    tx = effective(t, (3.47157536, 0.80615786, 0.72188183))
    ty = effective(t, (2.19631653, 0.95412269, 0.56254985))
    px, py = (lattice_probabilities(q, size) for q in (tx, ty))
    assert abs(sum(px)*sum(py)-1)<1e-12
    center = size // 2
    return sum(a*b for ix, a in enumerate(px) for iy,b in enumerate(py)
               if (ix!=center or iy!=center) and
               4*min(abs(ix-center),abs(iy-center))<=max(abs(ix-center),abs(iy-center)))


def analyze(path):
    digest = hashlib.md5()
    with path.open("rb") as stream:
        for chunk in iter(lambda: stream.read(1024*1024), b""):
            digest.update(chunk)
    assert digest.hexdigest() == MD5, "unexpected Zenodo archive"
    with zipfile.ZipFile(path) as archive:
        for time, runs in GROUPS.items():
            clock_ms = float(time.split()[0])
            print(f"{time}: flat coherent 29-site model per axis, wedge={atomic_model(clock_ms):.6f}")
            totals = {cut: Counter() for cut in THRESHOLDS}
            for run in runs:
                rows = count_run(archive, run)
                for cut in THRESHOLDS:
                    totals[cut].update(rows[cut])
                print(f"  run {run} at 4.5 photons: {dict(rows[4.5])}")
            for cut, count in totals.items():
                a, n = count["axial"], count["retained"]
                lo, hi = wilson(a, n)
                print(f"{time}, cut {cut}: axial {a}/{n}={a/n:.6f}; "
                      f"95% Wilson [{lo:.6f}, {hi:.6f}]; "
                      f"origin={count['origin']}, field edge={count['edge']}")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument("--archive", type=Path)
    source.add_argument("--download", action="store_true")
    args = parser.parse_args()
    if args.archive:
        analyze(args.archive)
    else:
        with tempfile.TemporaryDirectory() as work:
            path = Path(work)/"tunnel.zip"
            with urlopen(URL, timeout=180) as incoming, path.open("wb") as target:
                shutil.copyfileobj(incoming, target)
            analyze(path)


if __name__ == "__main__":
    main()
replay.py
"""Replay the pair-detector study with the pinned Tally runtime and Python."""
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"
WALK_SHA = "6f72200b7e30d71d04149373cae8bd55bc6683c9487c8ae2632ae4acb66d23e5"


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="released 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)
    walk = ROOT / "prior/walk.py"
    if not walk.is_file():
        walk = ROOT.parent / "convex-fronts/walk.py"
    checked(walk, WALK_SHA)
    python = [sys.executable, "-E", "-s", "-B", "-X", "utf8"]
    for script in ("aperture", "counts", "contact", "charge", "synthetic_slice", "gravity"):
        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 / "detectors.tly", work / "detectors.tly")
        result = subprocess.run([*python, str(tally / "tally.py"), "detectors.tly"],
                                cwd=work, stdout=subprocess.PIPE, check=True)
        actual = result.stdout.decode("utf-8").splitlines()
        expected = (ROOT / "detectors.out").read_text(encoding="utf-8").splitlines()
        if actual != expected or sum(row.startswith("✓") for row in actual) != 16:
            raise ValueError("Native transcript differs from the 16 published checks")
    print("All six offline calculations and the complete native Tally transcript passed.")


if __name__ == "__main__":
    main()
synthetic_slice.py
"""Test phase-resolved reconstruction of a three-dimensional one-particle walk.

A full tick has single fine x,y shifts, the paired z shift (one coarse cell),
then single fine y,x shifts. The ideal optical retarder at kappa replaces only
the paired z shift; x and y remain spatial throughout. Python standard library.
"""
from collections import defaultdict
import cmath
from math import pi, sqrt

STAGES = "xyzyx"


def polarized(a, b, axis, sign):
    if axis == "x":
        return (a+sign*b)/2, (b+sign*a)/2
    if axis == "y":
        return (a-1j*sign*b)/2, (b+1j*sign*a)/2
    return (a, 0) if sign == 1 else (0, b)


def evolve(state, ticks, kappa=None):
    """With a real-space z register, kappa=None; with only x,y, supply kappa."""
    for _ in range(ticks):
        for axis in STAGES:
            if axis == "z" and kappa is not None:
                phase = cmath.exp(-1j*kappa)
                state = {r:(phase*a, phase.conjugate()*b) for r,(a,b) in state.items()}
                continue
            following = defaultdict(lambda:[0j, 0j])
            component = "xyz".index(axis)
            for site, (a, b) in state.items():
                for sign in (-1, 1):
                    u, v = polarized(a, b, axis, sign)
                    if u == v == 0:
                        continue
                    target = list(site)
                    target[component] += sign
                    field = following[tuple(target)]
                    field[0] += u
                    field[1] += v
            state = {r:val for r,val in following.items() if any(val)}
    return state


def check(ticks, source, spin, parity_grid):
    direct = {(0,0,z):(weight*spin[0], weight*spin[1]) for z,weight in source}
    direct = evolve(direct, ticks)
    zmin = min(z for z,_ in source) - ticks
    zmax = max(z for z,_ in source) + ticks
    if parity_grid:
        levels = range(zmin, zmax+1, 2)
        phases = [pi*i/len(levels) for i in range(len(levels))]
    else:
        levels = range(zmin, zmax+1)
        phases = [2*pi*i/len(levels) for i in range(len(levels))]
    slices = []
    for kappa in phases:
        initial = sum(weight*cmath.exp(-1j*kappa*z) for z,weight in source)
        slices.append(evolve({(0,0):(initial*spin[0], initial*spin[1])}, ticks, kappa))
    sites = set().union(*(s.keys() for s in slices), (r[:2] for r in direct))
    error = 0.0
    total = 0.0
    for xy in sites:
        fields = [s.get(xy,(0,0)) for s in slices]
        projected = sum(abs(v)**2 for pair in fields for v in pair)/len(phases)
        expected = 0.0
        for z in levels:
            factors = [cmath.exp(1j*kappa*z)/len(phases) for kappa in phases]
            reference = direct.get((*xy,z), (0,0))
            reconstructed = [sum(w*pair[i] for w,pair in zip(factors,fields)) for i in (0,1)]
            error = max(error, *(abs(a-b) for a,b in zip(reference,reconstructed)))
            expected += sum(abs(v)**2 for v in reference)
        assert abs(projected-expected) < 1e-13
        total += expected
    assert abs(total-1) < 1e-13 and error < 1e-13
    return len(phases), error


def main():
    point = [(0,1)]
    balanced = [(-1,1/sqrt(2)),(1,1/sqrt(2))]
    antisymmetric = [(-1,1/sqrt(2)),(1,-1/sqrt(2))]
    for n in (1, 2, 3, 4):
        worst = 0.0
        for spin in ((1,0),(0,1)):
            for source in (point, balanced, antisymmetric):
                for parity_grid in (False, True):
                    count, err = check(n, source, spin, parity_grid)
                    if parity_grid:
                        assert count == n+len(source)
                    worst = max(worst, err)
        print(f"N={n}: point {n+1} and two-site {n+2} parity-resolved settings; "
              f"max amplitude error across all controls {worst:.2e}")

    # An onsite interaction on an eight-site ring couples |0,0> momentum to
    # |1,-1>. Independent one-particle retarder settings preserve each momentum.
    sites = 8
    phase = -1
    matrix_element = sum((phase-1)/sites**2 *
                         cmath.exp(-2j*pi*(1-1)*z/sites) for z in range(sites))
    assert abs(matrix_element + 0.25) < 1e-14
    print("Two-particle contact at phase pi: momentum (0,0) to (1,-1) amplitude = -1/4.")


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

Independent research by Anthony Michael Collado.
One- and two-particle detector study · 1 December 2026

State of the theory → · Study sources (ZIP) ↓