Skip to content
Symbolic & Numerical Algorithms · Computer Algebra

Normal Forms, Term Streams & F_p Reconstruction

Graded operator canonicalization in weyl-canonical, FORM-inspired streaming sort-merge with NVMe spill in weyl-cas, and 63-bit multi-prime CRT & Wang rational reconstruction in weyl-num.

High-order perturbative expansions (such as 14th-order pCUT) simultaneously face two classic computer-algebra bottlenecks: intermediate expression swell (tens or hundreds of millions of terms that overwhelm in-memory hash tables) and coefficient swell (arbitrary-precision rationals growing to thousands of bits before cancellation). Weyl eliminates both bottlenecks through three tightly integrated crates: weyl-canonical, weyl-cas, and weyl-num.

Graded Operator Canonicalization (weyl-canonical) ​

Every operator algebra implements the zero-allocation GradedAlgebra trait (weyl-canonical/src/algebra.rs), reducing products and adjoints directly into canonical monomial byte strings plus an exact phase:

rust
pub trait GradedAlgebra {
    type Word: AsRef<[u8]> + Ord + Hash;
    type Phase: Copy;

    fn grade(w: &Self::Word) -> Grade;
    fn mul(a: &Self::Word, b: &Self::Word, out: &mut WordBuf) -> Self::Phase;
    fn commutes(a: &Self::Word, b: &Self::Word) -> bool;
    fn adjoint(w: &Self::Word, out: &mut WordBuf) -> Self::Phase;
}

Physical operator families map onto GradedAlgebra as follows:

Algebra FamilyCanonical Word EncodingMultiplication & Normal-Form RuleComplexity
Pauli (Spin-1/2)Site-sorted big-endian u32 list (site << 2) | code (X=1, Y=2, Z=3); global phase in Z4\mathbb{Z}_4Linear merge of two sorted lists; 3×33 \times 3 phase table on colliding sites; commutation is parity of differing shared sitesO(∣A∣+∣B∣)O(|A| + |B|)
Majorana FermionsSorted u32 mode-index listLinear merge counting inversions for (−1)inv(-1)^{\mathrm{inv}} and cancelling γi2=1\gamma_i^2 = 1O(∣A∣+∣B∣)O(|A| + |B|)
CAR FermionsNormal-ordered creation-left, annihilation-right listKoszul sign on disjoint supports; recursive {ci,cj†}=δij\{c_i, c_j^\dagger\} = \delta_{ij} contractions on overlapsLocal-support polynomial
CCR BosonsNormal-ordered creation-left, annihilation-right (truncated at nmax⁡n_{\max})Commute on disjoint supports; Wick contractions via [ai,aj†]=δij[a_i, a_j^\dagger] = \delta_{ij} on overlapsLocal-support polynomial
Group Algebra GroupQudit<G>Tensor product of unique single-site basis LhδkL^h \delta_k (h,k∈Gh, k \in G)(Lhδk)(Lh′δk′)=δk,h′k′Lhh′δk′(L^h \delta_k)(L^{h'} \delta_{k'}) = \delta_{k, h'k'} L^{hh'} \delta_{k'} in O(1)O(1) lookup; coefficients in Q(ζn)\mathbb{Q}(\zeta_n)O(∣A∣+∣B∣)O(|A| + |B|)

Byte Order Equals Lexicographic Order

Encoding each Pauli factor as a big-endian u32 (site << 2) | code guarantees that lexicographic order on canonical Pauli words matches raw byte-wise memcmp. Downstream term-stream sorters can therefore radix-sort flat byte buffers directly without deserializing AST nodes.

Worked Example: Linear Pauli Merge and 3×33 \times 3 Phase Table ​

Consider two sparse Pauli words A=X2Z5A = X_2 Z_5 ([0x00000009, 0x00000017]) and B=Y2Z5X9B = Y_2 Z_5 X_9 ([0x0000000A, 0x00000017, 0x00000025]). GradedAlgebra::mul sweeps both sorted slices with two pointers, consulting the 3×33 \times 3 single-site table on colliding sites:

Left \ RightXX (01)YY (10)ZZ (11)
XX (01)+1⋅I+1 \cdot I+i⋅Z+i \cdot Z−i⋅Y-i \cdot Y
YY (10)−i⋅Z-i \cdot Z+1⋅I+1 \cdot I+i⋅X+i \cdot X
ZZ (11)+i⋅Y+i \cdot Y−i⋅X-i \cdot X+1⋅I+1 \cdot I

As the two-pointer sweep advances, site 2 collides first with X2Y2=+iZ2X_2 Y_2 = +i Z_2, so the merge appends (2 << 2) | 3 to WordBuf and advances the Z4\mathbb{Z}_4 phase by +1+1 (i1i^1). Next, site 5 collides with Z5Z5=+1⋅IZ_5 Z_5 = +1 \cdot I, causing exact cancellation: nothing is emitted to WordBuf and the phase remains unchanged. Site 9 appears only in BB, so X_9 is copied directly into WordBuf. The sweep concludes with AB=+iZ2X9AB = +i Z_2 X_9; because the two words share 1 differing site (site 2), commutes(A, B) == false, and the entire operation completes in O(∣A∣+∣B∣)O(|A| + |B|) time with zero heap allocations.

FORM-Inspired Streaming Term Architecture (weyl-cas) ​

Conventional CAS engines built on global hash tables thrash CPU caches and exhaust RAM once intermediate terms reach 107–10810^7\text{–}10^8. Inspired by FORM, weyl-cas represents streams as flat, 8-byte-aligned records:

rust
/// Fixed 8-byte aligned record header; flat wire layout:
/// [TermHeader (8B)][coeff: [u64; K]][mono: mono_len bytes][pad to 8]
#[repr(C, align(8))]
pub struct TermHeader {
    pub len: u32,       // aligned record size: (8 + 8*K + mono_len + 7) & !7
    pub mono_len: u16,  // parameter monomial prefix + canonical operator bytes
    pub flags: u16,     // bit 0 = FLAG_IMAGINARY separating real & imag parts (i^2 = -1)
}

/// One-word wire coefficient trait: each slot fixes its prime context PrimeId once per stream
pub trait WireCoeff: Field + Send + Sync {
    type Ctx: Copy + Eq + Send + Sync;
    fn ctx(self) -> Self::Ctx;
    fn join_ctx(a: Self::Ctx, b: Self::Ctx) -> Option<Self::Ctx>;
    fn to_word(self) -> u64;
    fn from_word(word: u64, ctx: Self::Ctx) -> Self;
}

In memory, a compact TermRecord carries an 8-byte TermHeader plus lightweight slice/vector metadata (a 24-byte structural footprint for compact records). Inside the flat sort buffer, for K=4K = 4 63-bit primes (32-byte coefficient vector) and a 12-byte monomial, each record occupies 56 contiguous bytes:

text
Offset (bytes):  0..4     4..6       6..8     8..40            40..52          52..56
Field:          [len=56] [mono=12] [flags=0] [coeff: [u64;4]] [mono: 12 bytes] [pad: 4B]

There is zero pointer chasing; perturbative parameter monomials (such as xaκ1bκ2cx^a \kappa_1^b \kappa_2^c) are prepended directly onto mono, so multivariate series combine like terms automatically without polynomial interpolation.

Sort-Merge and External NVMe Spill Pipeline ​

SortingSink normalizes arbitrary incoming term streams in four deterministic stages. Generated terms first append sequentially into a fixed-size buffer (DEFAULT_BUFFER_BYTES = 256 MiB) to maximize write bandwidth. Once the buffer fills, it is sorted in place by key (mono, flags & FLAG_IMAGINARY) using most-significant-digit radix sort (MAX_RADIX_DEPTH = 64, falling back to comparison sort for buckets ≤\le SMALL_BUCKET = 48), followed by a single linear scan that merges adjacent like-term coefficient vectors and drops all-zero terms. Whenever accumulated sorted runs exceed MemBudget, runs spill sequentially to SpillDir on NVMe storage, and SortingSink::finish merges all in-memory and on-disk runs through a kk-way loser tree (FAN_IN = 256), combining like terms across runs on the fly. For buffers containing at least PARALLEL_MIN_TERMS (4096) terms, splitter sampling partitions disjoint monomial ranges across worker threads and concatenates their outputs directly; because byte order is total and Fp\mathbb{F}_p addition is commutative and associative, the resulting output bytes are invariant to buffer size, spill boundaries, and thread count.

Reduction StrategyPeak Memory BehaviorCache LocalityMeasured Single-Core Throughput
Naive hash table (normalize_naive)Linear in distinct terms; high-load thrashingRandom pointer chasingL3 differential reference only
In-RAM MSD radix sort-merge (weyl-cas)Hard-capped by MemBudgetSequential writes + contiguous buckets1.21 × 10⁷ terms/s (1M terms in 82.89 ms)
External kk-way loser-tree spillBounded working set (10810^8 terms ≤64 GB\le 64\text{ GB})Large sequential NVMe I/OBounded by NVMe sequential bandwidth

Tuning Constants and Streaming Execution Model ​

weyl-cas/src/sort.rs centralizes the external-memory tuning constants to align with CPU cache lines and NVMe transfer blocks:

rust
pub const DEFAULT_BUFFER_BYTES: usize = 256 << 20; // 256 MiB per-chunk sort buffer
const FAN_IN: usize                   = 256;       // max ways merged per loser-tree pass
const SMALL_BUCKET: usize             = 48;        // MSD radix fallback to comparison sort
const MAX_RADIX_DEPTH: usize          = 64;        // max radix depth guarding long prefixes
const PARALLEL_MIN_TERMS: usize       = 1 << 12;   // keep < 4096 terms single-threaded

As KirOp::Apply streams perturbative operators T(m)T(m) onto state vectors, outputs flow directly into SortingSink. Whenever spilled runs exceed FAN_IN = 256, multi-pass merging keeps open file descriptors and merge buffers strictly within MemBudget. The KIR execution engine composes five pure streaming operators into a single pipeline: KirOp::Load(SourceRef) seeds initial vacuum or single-quasiparticle state streams from SIR templates; KirOp::Apply acts with local operators on syndrome bitstrings while filtering allowed TnT_n components dynamically via ΔQ=Q(s′,ℓ′)−Q(s,ℓ)\Delta Q = Q(s', \ell') - Q(s, \ell) without materializing 2r2^r projectors; KirOp::Project(Sector) filters streams by conserved charges and quasiparticle sector; KirOp::Normalize drives the chunked MSD radix sort, NVMe spill, and kk-way loser-tree merge; and KirOp::Reconstruct invokes multi-prime CRT or Wang rational reconstruction on the final reduced stream to emit exact rational series tables.

63-Bit Modular Arithmetic, CRT, and Wang Reconstruction (weyl-num) ​

To avoid big-integer GCD overhead during intermediate accumulation, rational coefficients are accumulated simultaneously across KK coprime 63-bit prime fields Fpi\mathbb{F}_{p_i} (pi<263p_i < 2^{63}, curated in weyl-num/src/fp.rs as PRIMES_63: 263−25,263−165,…2^{63}-25, 2^{63}-165, \dots):

rust
// weyl-num/src/fp.rs: curated 63-bit primes (< 2^63, leaving headroom for u128 reduction)
pub const PRIMES_63: &[u64] = &[
    9_223_372_036_854_775_783, // 2^63 - 25
    9_223_372_036_854_775_643, // 2^63 - 165
    9_223_372_036_854_775_549, // 2^63 - 259
    9_223_372_036_854_775_507, // 2^63 - 301
    // ... 16 verified 63-bit primes (> 1000 bits of combined CRT capacity)
];

// Pick the first k 63-bit primes coprime to the per-order common denominator D_k
let primes: Vec<PrimeId> = PrimeTable::select_coprime(k, common_denom_d_k);

Intermediate ±i\pm i Pauli phases are tracked via FLAG_IMAGINARY, keeping real and imaginary residues separate in Fpi\mathbb{F}_{p_i} with multiplication obeying i2=−1i^2 = -1. Real physical observables verify that all imaginary residues vanish identically across all KK primes.

A Priori Bounds and Guaranteed Uniqueness ​

Weyl never stops heuristically when an extra prime happens to agree; instead, prime counts are fixed statically before expansion using a priori bounds. When a common denominator DkD_k is known in advance—as in pCUT, where exact rational tables C(m)∈QC(m) \in \mathbb{Q}, energy scaling ε01−k\varepsilon_0^{1-k}, cluster embedding counts, and inclusion-exclusion weights determine both DkD_k and a strict integer numerator bound NkN_k on DkD_k-scaled outputs—centered CRT lifting applies directly. Choosing K≥4K \ge 4 primes such that

M=∏i=1Kpi>2NkM = \prod_{i=1}^{K} p_i > 2 N_k

guarantees that combining residues (r1,…,rK)(r_1, \dots, r_K) via the Chinese Remainder Theorem into R∈[0,M)R \in [0, M) and taking the centered representative

n={R,R≤M/2R−M,R>M/2n = \begin{cases} R, & R \le M/2 \\ R - M, & R > M/2 \end{cases}

recovers the exact rational n/Dk∈Qn / D_k \in \mathbb{Q} with mathematical certainty.

When no common denominator is known in advance and only a numerator bound NN and denominator bound DD are available, Wang’s rational reconstruction selects primes with M>2NDM > 2ND and runs the extended Euclidean recurrence on (M,R)(M, R),

(r0,t0)=(M,0),(r1,t1)=(R,1),(ri+1,ti+1)=(ri−1−qiri, ti−1−qiti),(r_0, t_0) = (M, 0), \qquad (r_1, t_1) = (R, 1), \qquad (r_{i+1}, t_{i+1}) = (r_{i-1} - q_i r_i,\ t_{i-1} - q_i t_i),

terminating at the first step satisfying ∣ri∣≤N|r_i| \le N and ∣ti∣≤D|t_i| \le D. Provided gcd⁡(ri,ti)=1\gcd(r_i, t_i) = 1, this uniquely recovers ri/tir_i / t_i (normalized with ti>0t_i > 0); if the modulus product is insufficient, the reconstructor fails explicitly with NumError::InsufficientPrimes rather than guessing.

rust
pub enum NumError {
    DivisionByZero,
    NonCoprimeModuli,
    EmptyResidues,
    InsufficientPrimes,    // prime product cannot exceed the a priori bound
    DenominatorMismatch,   // recovered denominator does not divide declared D_k
}

Worked Example: Recovering an Order-10 pCUT Coefficient ​

Suppose an order-1010 linked-cluster expansion has a priori common denominator D10=218⋅34⋅52D_{10} = 2^{18} \cdot 3^4 \cdot 5^2 and integer numerator bound N10≈1068N_{10} \approx 10^{68}. Since each 63-bit prime supplies ≈18.96\approx 18.96 decimal digits of dynamic range, K=⌈log⁡263(2N10)⌉=4K = \lceil \log_{2^{63}}(2 N_{10}) \rceil = 4 coprime primes yield M≈7.2×1075>2N10M \approx 7.2 \times 10^{75} > 2 N_{10}. During execution, weyl-cas accumulates all four prime lanes in parallel and reduces the target monomial’s residue vector to (r1,r2,r3,r4)(r_1, r_2, r_3, r_4). Finally, weyl-num::crt_centered combines those residues into the unique centered integer n∈(−M/2,M/2]n \in (-M/2, M/2] and constructs the reduced Rational::new(n, D_10). Because M>2N10M > 2N_{10} was proven before expansion, modular wraparound is mathematically impossible.

Certification Gate for Symbolic Interpolation

Any rational-function interpolation over symbolic parameters requires independent degree bounds and exact algebraic identity verification; unverified interpolants are never tagged Exact.

Weyl v0.1 · MIT License