ogdoad 1.0.0

Clifford algebras (with nilpotents) over the field-like subclasses of combinatorial games: nimbers, surreals, surcomplex.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
//! The **genus** of an integral lattice: its class up to local equivalence at
//! every place.
//!
//! Two integral lattices are in the same genus iff they are isometric over `ℝ`
//! (same signature) and over `ℤ_p` for every prime `p`. The genus is the natural
//! arithmetic coarsening of the isometry class, and it is exactly the place where
//! the local-global machinery the crate already carries
//! (`local_global/padic.rs`'s square classes, `try_is_square_qp`) acts on a *lattice*
//! rather than a field-level square class.
//!
//! The engine is the **p-adic Jordan decomposition**. Over `ℤ_p` a lattice splits
//! orthogonally into scaled unimodular constituents `⊥_k p^k L_k`; for odd `p`
//! every `L_k` is diagonal, and for `p = 2` the constituents are 1-dimensional
//! (type I) or 2-dimensional even blocks `U = [[0,1],[1,0]]`, `V = [[2,1],[1,2]]`
//! (type II). The Conway–Sloane *p-adic symbol* records, per scale, the dimension,
//! the determinant square class (`sign = ±1`), and at `p = 2` the type and the
//! oddity (trace mod 8 of the type-I part).
//!
//! **Claim level and the p = 2 path.** For odd `p` the symbol is a complete `ℤ_p`
//! invariant and the comparison here is exact. For `p = 2` the symbol carries the
//! Conway–Sloane quintuple data `(scale, dim, det mod 8, type, oddity)` and is
//! canonicalised by the Allcock-corrected fine-symbol calculus: determinant
//! residues are normalised to signs, oddities are fused within type-I
//! compartments, and sign-walking moves signs left along trains, adding `4` to the
//! oddity of any compartment the walk crosses. This is the same canonical
//! reduction exposed by Sage's `canonical_2_adic_reduction`, and replaces the
//! older conservative per-scale sign comparison.
//!
//! References: Conway–Sloane *SPLAG* Ch. 15 §7; Allcock, *On the classification of
//! integral quadratic forms* (the corrected 2-adic sign-walking calculus).

use crate::forms::integral::diagonal::{
    odd_unit_residue, rat_val, rational_congruence_diagonal, rdiv, signature_from_diagonal,
    unit_mod8, DegenerateBehavior,
};
use crate::forms::try_is_square_qp;
use crate::forms::IntegralForm;
use crate::linalg::integer::prime_factors;
use crate::scalar::{Rational, Scalar};
use std::collections::BTreeMap;
use std::fmt;

/// One scale of a p-adic Jordan symbol: the constituent `p^scale · (unimodular of
/// dimension `dim`)`. `sign` is the determinant square class of the unimodular part
/// (`+1` iff a `ℤ_p`-square unit). For `p = 2`, `det_mod8` is the determinant unit
/// of the unimodular part in `{1,3,5,7}` before sign-walking, `type_ii` is true
/// when the constituent is even (a sum of `U`/`V` planes), and `oddity` is the trace
/// mod 8 of the type-I (odd) part. For odd `p`, `det_mod8` is informational only.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ScaleSymbol {
    pub scale: u128,
    pub dim: usize,
    pub sign: i128,
    pub det_mod8: i128,
    pub type_ii: bool,
    pub oddity: i128,
}

/// Render one Conway-Sloane scale constituent as `q^{±n}_t` (type I, `t` = oddity)
/// or `q_{II}^{±n}` (type II), with `base` standing in for `q = p^scale`.
fn render_scale_symbol(base: impl fmt::Display, s: &ScaleSymbol) -> String {
    let sign = if s.sign >= 0 { "+" } else { "-" };
    if s.type_ii {
        format!("{base}_II^{sign}{}", s.dim)
    } else {
        format!("{base}_{}^{sign}{}", s.oddity, s.dim)
    }
}

impl ScaleSymbol {
    /// `display()` alias kept for Python callers.
    pub fn display(&self) -> String {
        self.to_string()
    }
}

impl fmt::Display for ScaleSymbol {
    /// A bare `ScaleSymbol` does not carry the prime it was computed at (that
    /// context lives on [`Genus`]), so the standalone rendering uses the
    /// placeholder base `p`; [`Genus`]'s Display resolves the actual `p^scale`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", render_scale_symbol("p", self))
    }
}

/// The genus of a nondegenerate integral lattice: signature, determinant, and the
/// p-adic symbol at every prime that can carry a nontrivial local invariant
/// (`p | 2·det`).
#[derive(Clone, Debug)]
pub struct Genus {
    pub dim: usize,
    pub signature: (usize, usize),
    pub det: i128,
    symbols: BTreeMap<u128, Vec<ScaleSymbol>>,
}

// --- exact rational helpers (p-adic valuations, unit residues) ---

fn r_int(n: i128) -> Rational {
    Rational::from_int(n)
}

/// The determinant square class (`±1`) of a rational unit `r` over `ℚ_p` (odd `p`).
fn unit_sign_odd(r: &Rational, p: i128) -> i128 {
    if try_is_square_qp(odd_unit_residue(r, p), p as u128)
        .expect("odd genus prime must be supported")
    {
        1
    } else {
        -1
    }
}

fn sign_from_mod8(u: i128) -> i128 {
    if u == 1 || u == 7 {
        1
    } else {
        -1
    }
}

// --- exact rational matrix utilities ---

type RMat = Vec<Vec<Rational>>;

fn to_rational(gram: &[Vec<i128>]) -> RMat {
    gram.iter()
        .map(|row| row.iter().map(|&x| r_int(x)).collect())
        .collect()
}

// --- the p-adic Jordan decomposition ---

/// A raw Jordan block before per-scale aggregation.
struct RawBlock {
    scale: u128,
    dim: usize,
    sign: i128,
    det_mod8: i128,
    type_ii: bool,
    oddity: i128,
}

/// Minimal p-adic valuation entry `(i, j)` of the symmetric matrix `a` (over the
/// `active` index set). Returns `None` if every active entry is zero.
fn min_val_entry(a: &RMat, active: &[usize], p: i128) -> Option<(usize, usize)> {
    let mut best: Option<(i128, usize, usize)> = None;
    for (ii, &i) in active.iter().enumerate() {
        for &j in &active[ii..] {
            if !a[i][j].is_zero() {
                let v = rat_val(&a[i][j], p);
                if best.is_none_or(|(bv, bi, bj)| v < bv || (v == bv && i == j && bi != bj)) {
                    best = Some((v, i, j));
                }
            }
        }
    }
    best.map(|(_, i, j)| (i, j))
}

/// p-adic Jordan blocks of a nondegenerate symmetric integer Gram matrix. Returns
/// `None` if the form is degenerate at `p` (a radical — should not happen for a
/// nonsingular lattice).
fn jordan_blocks(gram: &[Vec<i128>], p: i128) -> Option<Vec<RawBlock>> {
    let mut a = to_rational(gram);
    let mut active: Vec<usize> = (0..gram.len()).collect();
    let mut blocks = Vec::new();
    let mut guard = 0usize;
    let guard_max = 8 * gram.len() * gram.len() + 16;

    while !active.is_empty() {
        guard += 1;
        if guard > guard_max {
            return None; // defensive: should never trip for a nondegenerate form
        }
        let (i, j) = min_val_entry(&a, &active, p)?;
        let scale = rat_val(&a[i][j], p);

        if i != j && p != 2 {
            // Odd p: rotate e_i ← e_i + e_j so a diagonal entry attains the minimal
            // valuation (2 is a unit, so a[i][i] + 2a[i][j] + a[j][j] has valuation
            // = v(a[i][j])). Then re-loop; the diagonal pivot gets peeled next.
            for &c in &active {
                a[i][c] = a[i][c].add(&a[j][c].clone());
            }
            for &r in &active {
                a[r][i] = a[r][i].add(&a[r][j].clone());
            }
            continue;
        }

        let scale = u128::try_from(scale).ok()?; // negative scale ⇒ not p-integral (bug)
        if i == j {
            // 1-dimensional block ⟨a[i][i]⟩.
            let d = a[i][i].clone();
            let (sign, det_mod8, type_ii, oddity) = if p == 2 {
                let u8v = unit_mod8(&d);
                (sign_from_mod8(u8v), u8v, false, u8v)
            } else {
                (unit_sign_odd(&d, p), 1, false, 0)
            };
            blocks.push(RawBlock {
                scale,
                dim: 1,
                sign,
                det_mod8,
                type_ii,
                oddity,
            });
            // Schur complement removing i.
            let pivot = d;
            let rest: Vec<usize> = active.iter().copied().filter(|&r| r != i).collect();
            for &r in &rest {
                for &s in &rest {
                    let corr = rdiv(&a[r][i].mul(&a[i][s]), &pivot);
                    a[r][s] = a[r][s].sub(&corr);
                }
            }
            active = rest;
        } else {
            // p == 2, 2-dimensional even block on {i, j}.
            let alpha = a[i][i].clone();
            let beta = a[i][j].clone();
            let gamma = a[j][j].clone();
            let det = alpha.mul(&gamma).sub(&beta.mul(&beta));
            let det_mod8 = unit_mod8(&det);
            let sign = sign_from_mod8(det_mod8);
            blocks.push(RawBlock {
                scale,
                dim: 2,
                sign,
                det_mod8,
                type_ii: true,
                oddity: 0,
            });
            // Schur complement removing {i, j} via the 2×2 inverse
            //   B⁻¹ = (1/D)[[γ,−β],[−β,α]].
            let rest: Vec<usize> = active
                .iter()
                .copied()
                .filter(|&r| r != i && r != j)
                .collect();
            for &r in &rest {
                for &s in &rest {
                    // (a[r][i], a[r][j]) · B⁻¹ · (a[i][s], a[j][s])ᵀ
                    let t0 = gamma.mul(&a[i][s]).sub(&beta.mul(&a[j][s]));
                    let t1 = alpha.mul(&a[j][s]).sub(&beta.mul(&a[i][s]));
                    let numer = a[r][i].mul(&t0).add(&a[r][j].mul(&t1));
                    let corr = rdiv(&numer, &det);
                    a[r][s] = a[r][s].sub(&corr);
                }
            }
            active = rest;
        }
    }
    Some(blocks)
}

fn mul_mod8_unit(a: i128, b: i128) -> i128 {
    (a * b).rem_euclid(8)
}

/// Aggregate raw blocks at prime `p` into the per-scale Conway–Sloane symbol
/// (sorted by scale).
fn aggregate(blocks: &[RawBlock], p: i128) -> Vec<ScaleSymbol> {
    let mut by_scale: BTreeMap<u128, (usize, i128, i128, bool, i128)> = BTreeMap::new();
    for b in blocks {
        let e = by_scale.entry(b.scale).or_insert((0, 1, 1, p == 2, 0));
        e.0 += b.dim;
        e.1 *= b.sign;
        if p == 2 {
            e.2 = mul_mod8_unit(e.2, b.det_mod8);
        }
        if p == 2 && !b.type_ii {
            e.3 = false; // any type-I constituent makes the scale type I
        }
        if !b.type_ii {
            e.4 = (e.4 + b.oddity).rem_euclid(8);
        }
    }
    by_scale
        .into_iter()
        .map(
            |(scale, (dim, sign, det_mod8, type_ii, oddity))| ScaleSymbol {
                scale,
                dim,
                sign,
                det_mod8,
                type_ii,
                oddity: if type_ii { 0 } else { oddity },
            },
        )
        .collect()
}

/// The signature `(p₊, p₋)` of a nondegenerate symmetric integer matrix, by exact
/// rational congruence diagonalization (Jacobi/Sylvester): the sign of each pivot.
fn signature(gram: &[Vec<i128>]) -> (usize, usize) {
    let diag = rational_congruence_diagonal(gram, DegenerateBehavior::RequireNonsingular);
    signature_from_diagonal(&diag)
}

/// The primes that can carry a nontrivial local invariant: `2` and every odd prime
/// dividing the determinant. `2` is always included, even for odd determinant,
/// since it always carries a local invariant at the genus level.
fn relevant_primes(det: i128) -> Vec<u128> {
    let mut ps = prime_factors(det.unsigned_abs());
    if !ps.contains(&2) {
        ps.push(2);
        ps.sort_unstable();
    }
    ps
}

impl Genus {
    /// The genus of a nondegenerate integral lattice, or `None` if `det = 0`.
    pub fn from_lattice(lattice: &IntegralForm) -> Option<Genus> {
        let det = lattice.determinant();
        if det == 0 {
            return None;
        }
        let gram = lattice.gram();
        let mut symbols = BTreeMap::new();
        for p in relevant_primes(det) {
            let blocks = jordan_blocks(gram, p as i128)?;
            symbols.insert(p, aggregate(&blocks, p as i128));
        }
        Some(Genus {
            dim: lattice.dim(),
            signature: signature(gram),
            det,
            symbols,
        })
    }

    /// The Conway–Sloane symbol at prime `p` (per-scale), or an empty slice if `p`
    /// carries no constituent.
    pub fn symbol_at(&self, p: u128) -> &[ScaleSymbol] {
        self.symbols.get(&p).map_or(&[], |v| v)
    }

    /// The symbol at `p` in the canonical form used for genus comparison.
    ///
    /// For odd `p` the raw Jordan symbol is already canonical. At `p = 2`, this
    /// applies the Conway–Sloane/Allcock fine-symbol reduction: determinant
    /// residues become signs, type-I compartment oddities are fused, and signs
    /// are walked left along trains.
    pub fn canonical_symbol_at(&self, p: u128) -> Vec<ScaleSymbol> {
        let symbol = self.symbol_at(p);
        if p == 2 {
            canonical_2adic_symbol(symbol)
        } else {
            symbol.to_vec()
        }
    }

    /// The primes carrying a recorded local symbol.
    pub fn primes(&self) -> Vec<u128> {
        self.symbols.keys().copied().collect()
    }

    /// `display()` alias kept for Python callers.
    pub fn display(&self) -> String {
        self.to_string()
    }
}

impl fmt::Display for Genus {
    /// One line: dimension, signature, determinant, and the canonical
    /// Conway-Sloane symbol at every prime carrying a local invariant.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Genus(dim={}, signature=({}, {}), det={}",
            self.dim, self.signature.0, self.signature.1, self.det
        )?;
        for p in self.primes() {
            let rendered = self
                .canonical_symbol_at(p)
                .iter()
                .map(|s| {
                    let q = u32::try_from(s.scale)
                        .ok()
                        .and_then(|e| p.checked_pow(e))
                        .unwrap_or(p);
                    render_scale_symbol(q, s)
                })
                .collect::<Vec<_>>()
                .join(" ");
            write!(f, ", {p}: [{rendered}]")?;
        }
        write!(f, ")")
    }
}

/// Fuse oddities within compartments (maximal runs of consecutive type-I scales):
/// the per-compartment oddity sum mod 8 is the invariant. Returns a canonicalised
/// copy with each compartment's total oddity on its lowest scale and `0` elsewhere.
fn fuse_oddities(syms: &[ScaleSymbol]) -> Vec<ScaleSymbol> {
    let mut out = syms.to_vec();
    let mut i = 0;
    while i < out.len() {
        if out[i].type_ii {
            i += 1;
            continue;
        }
        // start of a compartment: extend over consecutive (scale+1) type-I scales
        let mut j = i;
        let mut total = 0i128;
        loop {
            total += out[j].oddity;
            let extends =
                j + 1 < out.len() && !out[j + 1].type_ii && out[j + 1].scale == out[j].scale + 1;
            if !extends {
                break;
            }
            j += 1;
        }
        let total = total.rem_euclid(8);
        out[i].oddity = total;
        for k in (i + 1)..=j {
            out[k].oddity = 0;
        }
        i = j + 1;
    }
    out
}

/// Maximal type-I compartments: consecutive scales with type-I constituents.
fn two_adic_compartments(syms: &[ScaleSymbol]) -> Vec<Vec<usize>> {
    let mut out = Vec::new();
    let mut i = 0usize;
    while i < syms.len() {
        if syms[i].type_ii {
            i += 1;
            continue;
        }
        let mut comp = vec![i];
        let mut j = i;
        while j + 1 < syms.len() && !syms[j + 1].type_ii && syms[j + 1].scale == syms[j].scale + 1 {
            j += 1;
            comp.push(j);
        }
        out.push(comp);
        i = j + 1;
    }
    out
}

/// Maximal trains: consecutive scales such that each adjacent pair has at least
/// one type-I term. This is the Allcock/Sage-corrected train relation, including
/// type-II terms that are connected to a neighboring type-I scale.
fn two_adic_trains(syms: &[ScaleSymbol]) -> Vec<Vec<usize>> {
    if syms.is_empty() {
        return Vec::new();
    }
    let mut out = Vec::new();
    let mut cur = vec![0usize];
    for i in 1..syms.len() {
        let scale_gap = syms[i].scale - syms[i - 1].scale;
        let connected_by_type_i = !syms[i].type_ii || !syms[i - 1].type_ii;
        let connected_across_empty_type_ii =
            scale_gap == 2 && !syms[i].type_ii && !syms[i - 1].type_ii;
        if (scale_gap == 1 && connected_by_type_i) || connected_across_empty_type_ii {
            cur.push(i);
        } else {
            out.push(cur);
            cur = vec![i];
        }
    }
    out.push(cur);
    out
}

fn set_canonical_det_from_sign(sym: &mut ScaleSymbol) {
    sym.det_mod8 = if sym.sign > 0 { 1 } else { 3 };
}

/// Canonicalise the carried 2-adic Conway–Sloane symbol: normalize determinant
/// residues, fuse oddities within compartments, then sign-walk left along trains.
/// Crossing a type-I compartment changes its fused oddity by `4`; this is the
/// giver/receiver bookkeeping in the fine-symbol calculus.
fn canonical_2adic_symbol(syms: &[ScaleSymbol]) -> Vec<ScaleSymbol> {
    let mut out = syms.to_vec();
    for sym in &mut out {
        sym.sign = sign_from_mod8(sym.det_mod8);
        set_canonical_det_from_sign(sym);
        if sym.type_ii {
            sym.oddity = 0;
        } else {
            sym.oddity = sym.oddity.rem_euclid(8);
        }
    }
    out = fuse_oddities(&out);
    let compartments = two_adic_compartments(&out);
    for train in two_adic_trains(&out) {
        for &i in train.iter().rev().take(train.len().saturating_sub(1)) {
            if out[i].sign < 0 {
                out[i].sign = 1;
                set_canonical_det_from_sign(&mut out[i]);
                let prev = i - 1;
                out[prev].sign *= -1;
                set_canonical_det_from_sign(&mut out[prev]);
                for compartment in &compartments {
                    if compartment.contains(&prev) || compartment.contains(&i) {
                        let head = compartment[0];
                        out[head].oddity = (out[head].oddity + 4).rem_euclid(8);
                    }
                }
            }
        }
    }
    out
}

/// Whether two integral lattices lie in the same genus.
///
/// Exact for the signature, determinant, and every odd-prime symbol. At `p = 2`
/// the comparison uses oddity fusion plus train sign-walking before matching the
/// carried Conway–Sloane symbols.
pub fn are_in_same_genus(a: &IntegralForm, b: &IntegralForm) -> bool {
    let (Some(ga), Some(gb)) = (Genus::from_lattice(a), Genus::from_lattice(b)) else {
        return false;
    };
    if ga.dim != gb.dim || ga.signature != gb.signature || ga.det != gb.det {
        return false;
    }
    if ga.symbols.keys().ne(gb.symbols.keys()) {
        return false;
    }
    for (&p, sa) in &ga.symbols {
        let sb = &gb.symbols[&p];
        if p == 2 {
            if canonical_2adic_symbol(sa) != canonical_2adic_symbol(sb) {
                return false;
            }
        } else if sa != sb {
            return false;
        }
    }
    true
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::forms::{d16_plus, is_root_lattice};
    use crate::forms::{e_6, e_7, e_8};

    // `root_lattices::a_n`/`d_n` are `Option`-checked on out-of-domain rank; every
    // call site below passes an in-domain rank, so these thin local wrappers keep
    // the test bodies unchanged.
    fn a_n(n: usize) -> IntegralForm {
        crate::forms::a_n(n).unwrap()
    }
    fn d_n(n: usize) -> IntegralForm {
        crate::forms::d_n(n).unwrap()
    }

    fn zn(n: usize) -> IntegralForm {
        IntegralForm::diagonal(&vec![1i128; n])
    }

    fn s2(scale: u128, dim: usize, det_mod8: i128, type_ii: bool, oddity: i128) -> ScaleSymbol {
        ScaleSymbol {
            scale,
            dim,
            sign: sign_from_mod8(det_mod8.rem_euclid(8)),
            det_mod8: det_mod8.rem_euclid(8),
            type_ii,
            oddity,
        }
    }

    /// Apply a unimodular change of basis Uᵀ G U (U upper-unitriangular with the
    /// given off-diagonal entries) — an isometry, so the genus is unchanged.
    fn congruent(g: &IntegralForm, shears: &[(usize, usize, i128)]) -> IntegralForm {
        let n = g.dim();
        let mut u = vec![vec![0i128; n]; n];
        for (i, row) in u.iter_mut().enumerate() {
            row[i] = 1;
        }
        for &(i, j, c) in shears {
            u[i][j] += c; // add c·(col i) to col j
        }
        // G' = Uᵀ G U
        let gram = g.gram();
        let mut gu = vec![vec![0i128; n]; n];
        for i in 0..n {
            for j in 0..n {
                let mut s = 0i128;
                for k in 0..n {
                    s += gram[i][k] * u[k][j];
                }
                gu[i][j] = s;
            }
        }
        let mut out = vec![vec![0i128; n]; n];
        for i in 0..n {
            for j in 0..n {
                let mut s = 0i128;
                for k in 0..n {
                    s += u[k][i] * gu[k][j];
                }
                out[i][j] = s;
            }
        }
        IntegralForm::new(out).unwrap()
    }

    #[test]
    fn z8_and_e8_differ_only_at_two() {
        let z8 = Genus::from_lattice(&zn(8)).unwrap();
        let e8 = Genus::from_lattice(&e_8()).unwrap();
        // Same rank, signature, determinant.
        assert_eq!(z8.dim, e8.dim);
        assert_eq!(z8.signature, e8.signature);
        assert_eq!(z8.det, e8.det);
        // Z^8: a single type-I scale-0 constituent, oddity 8 ≡ 0 mod 8.
        let s2_z = z8.symbol_at(2);
        assert_eq!(s2_z.len(), 1);
        assert_eq!((s2_z[0].scale, s2_z[0].dim, s2_z[0].type_ii), (0, 8, false));
        // E_8: a single type-II scale-0 constituent.
        let s2_e = e8.symbol_at(2);
        assert_eq!(s2_e.len(), 1);
        assert_eq!((s2_e[0].scale, s2_e[0].dim, s2_e[0].type_ii), (0, 8, true));
        // Distinguished only at p = 2 (type I vs II) — different genus.
        assert!(!are_in_same_genus(&zn(8), &e_8()));
    }

    #[test]
    fn jordan_symbols_match_known_oracles() {
        // A_2: det 3. p=2 single type-II dim-2; p=3 has a scale-1 constituent.
        let a2 = Genus::from_lattice(&a_n(2)).unwrap();
        let s2 = a2.symbol_at(2);
        assert_eq!(s2.len(), 1);
        assert!(s2[0].type_ii && s2[0].dim == 2 && s2[0].scale == 0);
        // det = product over scales of p^(scale·dim) at each p must recover |det|.
        assert_eq!(a2.det, 3);

        // D_4: p=2 symbol is two type-II scales (0 and 1), each dim 2.
        let d4 = Genus::from_lattice(&d_n(4)).unwrap();
        let s2 = d4.symbol_at(2);
        assert_eq!(s2.len(), 2);
        assert_eq!((s2[0].scale, s2[0].dim, s2[0].type_ii), (0, 2, true));
        assert_eq!((s2[1].scale, s2[1].dim, s2[1].type_ii), (1, 2, true));

        // A_1 = ⟨2⟩: p=2 single type-I scale-1 dim-1, oddity 1.
        let a1 = Genus::from_lattice(&IntegralForm::diagonal(&[2])).unwrap();
        let s2 = a1.symbol_at(2);
        assert_eq!(s2.len(), 1);
        assert_eq!(
            (s2[0].scale, s2[0].dim, s2[0].type_ii, s2[0].oddity),
            (1, 1, false, 1)
        );
    }

    #[test]
    fn two_adic_jordan_prefers_odd_block_on_valuation_tie() {
        let g = IntegralForm::new(vec![vec![2, 1], vec![1, 1]]).unwrap();
        assert!(are_in_same_genus(&zn(2), &g));

        let s2_g = Genus::from_lattice(&g).unwrap().symbol_at(2).to_vec();
        assert_eq!(s2_g.len(), 1);
        assert_eq!((s2_g[0].scale, s2_g[0].dim, s2_g[0].type_ii), (0, 2, false));
    }

    #[test]
    fn two_adic_compartments_and_trains_follow_the_corrected_rules() {
        let syms = vec![
            s2(0, 1, 1, false, 1),
            s2(1, 2, 3, true, 0),
            s2(2, 1, 1, false, 1),
            s2(4, 1, 1, false, 1),
        ];
        assert_eq!(
            two_adic_compartments(&syms),
            vec![vec![0], vec![2], vec![3]]
        );
        assert_eq!(two_adic_trains(&syms), vec![vec![0, 1, 2, 3]]);

        let gap_bridge = vec![s2(0, 1, 1, false, 1), s2(2, 1, 1, false, 1)];
        assert_eq!(two_adic_trains(&gap_bridge), vec![vec![0, 1]]);
    }

    #[test]
    fn two_adic_trains_continue_across_one_empty_scale() {
        let a = IntegralForm::diagonal(&[1, 20]);
        let b = IntegralForm::diagonal(&[5, 4]);
        assert!(are_in_same_genus(&a, &b));
    }

    #[test]
    fn two_adic_sign_walking_canonicalizes_train_signs() {
        let a = vec![s2(0, 1, 3, false, 3), s2(1, 1, 3, false, 3)];
        let b = vec![s2(0, 1, 1, false, 1), s2(1, 1, 1, false, 1)];
        assert_ne!(fuse_oddities(&a), fuse_oddities(&b));
        assert_eq!(canonical_2adic_symbol(&a), canonical_2adic_symbol(&b));

        let c = vec![s2(0, 3, 3, false, 1), s2(1, 1, 1, true, 0)];
        let canon = canonical_2adic_symbol(&c);
        assert_eq!(canon[0].sign, -1); // Sage/CS canonical walking moves signs left
        assert_eq!(canon[1].sign, 1);
    }

    #[test]
    fn canonical_symbol_at_exposes_the_compared_two_adic_symbol() {
        let g = Genus::from_lattice(&IntegralForm::diagonal(&[1, 6])).unwrap();
        let raw = g.symbol_at(2);
        let canonical = g.canonical_symbol_at(2);
        assert_ne!(raw, canonical.as_slice());
        assert_eq!(
            canonical
                .iter()
                .map(|s| (s.scale, s.dim, s.sign, s.type_ii, s.oddity))
                .collect::<Vec<_>>(),
            vec![(0, 1, -1, false, 0), (1, 1, 1, false, 0)]
        );
        assert_eq!(g.canonical_symbol_at(3), g.symbol_at(3).to_vec());
    }

    #[test]
    fn two_adic_reduction_matches_sage_quintuple_examples() {
        // Sage canonical_2_adic_reduction:
        // [[0,1,1,1,1], [1,1,1,1,1]] -> [[0,1,1,1,2], [1,1,1,1,0]]
        let fused = canonical_2adic_symbol(&[s2(0, 1, 1, false, 1), s2(1, 1, 1, false, 1)]);
        assert_eq!(
            fused
                .iter()
                .map(|s| (s.scale, s.dim, s.sign, s.type_ii, s.oddity))
                .collect::<Vec<_>>(),
            vec![(0, 1, 1, false, 2), (1, 1, 1, false, 0)]
        );

        // [[1,2,3,1,4], [2,1,1,1,1], [3,1,1,1,1]]
        // -> [[1,2,-1,1,6], [2,1,1,1,0], [3,1,1,1,0]]
        let sage = canonical_2adic_symbol(&[
            s2(1, 2, 3, false, 4),
            s2(2, 1, 1, false, 1),
            s2(3, 1, 1, false, 1),
        ]);
        assert_eq!(
            sage.iter()
                .map(|s| (s.scale, s.dim, s.sign, s.type_ii, s.oddity))
                .collect::<Vec<_>>(),
            vec![
                (1, 2, -1, false, 6),
                (2, 1, 1, false, 0),
                (3, 1, 1, false, 0)
            ]
        );

        // Walking a minus across a type-I compartment adds 4 to the fused oddity.
        let crossed = canonical_2adic_symbol(&[s2(0, 1, 1, false, 1), s2(1, 1, 3, false, 3)]);
        assert_eq!(
            crossed
                .iter()
                .map(|s| (s.scale, s.dim, s.sign, s.type_ii, s.oddity))
                .collect::<Vec<_>>(),
            vec![(0, 1, -1, false, 0), (1, 1, 1, false, 0)]
        );
    }

    #[test]
    fn two_adic_sign_walking_across_type_ii_bridge_is_pinned() {
        // A type-II constituent bridges two separate type-I compartments into one
        // train. Walking a sign from the right compartment to the left crosses
        // both incident type-I compartments, adding 4 to each fused oddity.
        let crossed = canonical_2adic_symbol(&[
            s2(0, 1, 1, false, 1),
            s2(1, 2, 1, true, 0),
            s2(2, 1, 3, false, 1),
        ]);
        assert_eq!(
            crossed
                .iter()
                .map(|s| (s.scale, s.dim, s.sign, s.type_ii, s.oddity))
                .collect::<Vec<_>>(),
            vec![
                (0, 1, -1, false, 5),
                (1, 2, 1, true, 0),
                (2, 1, 1, false, 5)
            ]
        );
    }

    #[test]
    fn reflexive_and_isometry_invariant() {
        // A lattice is in its own genus.
        for g in [a_n(2), a_n(4), d_n(4), d_n(5), e_6(), e_7(), e_8(), zn(5)] {
            assert!(are_in_same_genus(&g, &g), "reflexive");
        }
        // Isometric copies (unimodular congruence) share the genus — the strong
        // randomised oracle for the Jordan splitting + canonicalisation.
        let cases = [a_n(3), d_n(4), e_6(), e_8(), zn(6)];
        // Strictly upper-triangular shears ⇒ U is unit-upper-triangular ⇒ det U = 1
        // ⇒ Uᵀ G U is a genuine isometry (preserves det and genus).
        let shear_sets: &[&[(usize, usize, i128)]] = &[
            &[(0, 1, 1)],
            &[(0, 1, 2), (1, 2, -1)],
            &[(0, 2, 1), (0, 1, -3), (1, 2, 1)],
        ];
        for g in &cases {
            for shears in shear_sets {
                let valid: Vec<_> = shears
                    .iter()
                    .copied()
                    .filter(|&(i, j, _)| i < g.dim() && j < g.dim() && i < j)
                    .collect();
                let h = congruent(g, &valid);
                assert_eq!(h.determinant(), g.determinant(), "congruence keeps det");
                assert!(
                    are_in_same_genus(g, &h),
                    "isometric copy must share the genus (dim {})",
                    g.dim()
                );
            }
        }
    }

    #[test]
    fn determinant_and_signature_distinguish_genera() {
        // Different determinant ⇒ different genus.
        assert!(!are_in_same_genus(&a_n(2), &a_n(3))); // det 3 vs 4
        assert!(!are_in_same_genus(
            &IntegralForm::diagonal(&[1]),
            &IntegralForm::diagonal(&[3])
        ));
        // Same det and rank, different signature ⇒ different genus.
        let pos = IntegralForm::diagonal(&[1, 1]);
        let indef = IntegralForm::diagonal(&[1, -1]);
        assert_eq!(pos.determinant().abs(), indef.determinant().abs());
        assert!(!are_in_same_genus(&pos, &indef));
    }

    #[test]
    fn even_unimodular_rank16_share_a_genus() {
        // E_8 ⊕ E_8 and D16+ are the two rank-16 even unimodular lattices:
        // same genus, not isometric. We witness non-isometry by the roots:
        // E_8 ⊕ E_8 is generated by its roots, while D16+ contains D16 roots
        // generating an index-2 sublattice.
        let e8e8 = e_8().direct_sum(&e_8());
        let d16 = d16_plus();
        assert_eq!(e8e8.determinant(), 1);
        assert_eq!(d16.determinant(), 1);
        assert!(e8e8.is_even());
        assert!(d16.is_even());
        assert!(are_in_same_genus(&e8e8, &d16));
        assert!(is_root_lattice(&e8e8));
        assert!(!is_root_lattice(&d16));
        let g = Genus::from_lattice(&e8e8).unwrap();
        assert_eq!(g.signature, (16, 0));
        // single type-II scale-0 constituent of dim 16
        let s2 = g.symbol_at(2);
        assert_eq!(s2.len(), 1);
        assert_eq!((s2[0].dim, s2[0].type_ii), (16, true));
    }

    #[test]
    fn scale_symbol_display_renders_the_conway_sloane_notation() {
        let e8 = Genus::from_lattice(&e_8()).unwrap();
        let s2 = &e8.canonical_symbol_at(2)[0];
        assert_eq!(s2.to_string(), "p_II^+8");
        assert_eq!(s2.display(), s2.to_string());

        let a2 = Genus::from_lattice(&a_n(2)).unwrap();
        let s3 = &a2.canonical_symbol_at(3)[0];
        assert_eq!(s3.to_string(), "p_0^-1");
    }

    #[test]
    fn genus_display_renders_signature_det_and_canonical_symbols() {
        let z1 = Genus::from_lattice(&IntegralForm::diagonal(&[1])).unwrap();
        assert_eq!(
            z1.to_string(),
            "Genus(dim=1, signature=(1, 0), det=1, 2: [1_1^+1])"
        );
        assert_eq!(z1.display(), z1.to_string());

        let e8 = Genus::from_lattice(&e_8()).unwrap();
        assert_eq!(
            e8.to_string(),
            "Genus(dim=8, signature=(8, 0), det=1, 2: [1_II^+8])"
        );

        let a2 = Genus::from_lattice(&a_n(2)).unwrap();
        assert_eq!(
            a2.to_string(),
            "Genus(dim=2, signature=(2, 0), det=3, 2: [1_II^-2], 3: [1_0^-1 3_0^-1])"
        );
    }
}