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
//! The Arf invariant — the complete classifying invariant of a nonsingular
//! quadratic form over F₂ at fixed rank, and the `Z/2` Brauer-Wall/Witt class
//! carried by the associated **graded** characteristic-2 Clifford algebra. It
//! does not by itself classify ungraded Clifford algebras or forms of different
//! ranks.
//!
//! A nim-Clifford metric (q, b) restricted to F₂ entries *is* a quadratic form
//! over F₂ on the generator space: for x ∈ F₂ⁿ,
//!     Q(x) = Σ_i x_i q_i  +  Σ_{i<j} x_i x_j b_{ij}        (x_i² = x_i)
//! with polar form B(e_i,e_j) = b_{ij} (alternating, B(e_i,e_i)=0). We compute
//! a symplectic basis {a_k,b_k} for B (peeling hyperbolic pairs, leaving the
//! radical) and return Arf = Σ_k Q(a_k) Q(b_k) ∈ F₂.
//!
//! `arf_f2` is the F₂ case (u128 bitmask vectors over ≤128 generators).
//! `arf_nimber` handles a form over any nim-subfield F_{2^{2^k}}: symplectic
//! reduction over the field (normalising pairs with `nim_inv`), then the Arf
//! sum is pushed to F₂ by the field trace. `arf_invariant` uses the latter.

use crate::clifford::Metric;
use crate::forms::FiniteChar2Field;
use crate::scalar::{
    nim_add, nim_inv, nim_mul, nim_trace, ordinal_common_finite_subfield_degree, Fpn, Nimber,
    Ordinal, Scalar,
};
use std::collections::BTreeMap;
use std::fmt;

/// The orthogonal type of a symplectic complement: `O+` (split, Arf = 0) or
/// `O-` (non-split, Arf = 1). When [`ArfInvariants::radical_anisotropic`] is
/// true, this complement type is not an isometry invariant of the whole
/// singular form.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OrthogonalType {
    /// Split type (Arf = 0, hyperbolic complement).
    OPlus,
    /// Non-split type (Arf = 1, anisotropic complement).
    OMinus,
}

impl fmt::Display for OrthogonalType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            OrthogonalType::OPlus => f.write_str("O+"),
            OrthogonalType::OMinus => f.write_str("O-"),
        }
    }
}

/// Classification invariants for a characteristic-2 quadratic form over any
/// nim-subfield or supported finite char-2 field.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArfInvariants {
    /// Arf invariant of the nonsingular core (0 or 1).
    pub arf: u128,
    /// Rank of the polar form B = 2 × (number of hyperbolic pairs).
    pub rank: usize,
    /// Dimension of the polar-form radical (where B vanishes).
    pub radical_dim: usize,
    /// Whether Q is nonzero somewhere on the radical (a "defective" direction).
    pub radical_anisotropic: bool,
}

impl ArfInvariants {
    /// Orthogonal type of the chosen symplectic complement: `O+` (split) iff
    /// `arf == 0`. When [`radical_anisotropic`](Self::radical_anisotropic) is
    /// true, this complement type is not an isometry invariant of the whole
    /// singular form.
    pub fn o_type(&self) -> OrthogonalType {
        if self.arf == 0 {
            OrthogonalType::OPlus
        } else {
            OrthogonalType::OMinus
        }
    }

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

impl fmt::Display for ArfInvariants {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "ArfInvariants(arf={}, {}, rank={}, radical_dim={}, radical_anisotropic={})",
            self.arf,
            self.o_type(),
            self.rank,
            self.radical_dim,
            self.radical_anisotropic,
        )
    }
}

/// Bits of `mask` strictly above position `i`.
fn above(i: usize) -> u128 {
    if i >= 127 {
        0
    } else {
        (!0u128) << (i + 1)
    }
}

/// Q(v) for a bitmask vector v.
fn q_of(v: u128, qd: &[bool], bmat: &[u128]) -> bool {
    let mut acc = false;
    let mut vv = v;
    while vv != 0 {
        let i = vv.trailing_zeros() as usize;
        vv &= vv - 1;
        if qd[i] {
            acc ^= true;
        }
        // pairs (i, j), j>i, both in v, with b_{ij}=1
        let inter = bmat[i] & v & above(i);
        if inter.count_ones() & 1 == 1 {
            acc ^= true;
        }
    }
    acc
}

/// Polar form B(u, v) = Σ_{i≠j} u_i v_j b_{ij}.
fn b_of(u: u128, v: u128, bmat: &[u128]) -> bool {
    let mut acc = false;
    let mut uu = u;
    while uu != 0 {
        let i = uu.trailing_zeros() as usize;
        uu &= uu - 1;
        if (bmat[i] & v).count_ones() & 1 == 1 {
            acc ^= true;
        }
    }
    acc
}

/// Arf invariant of an F₂ quadratic form given by diagonal `qd` (the squares)
/// and symmetric adjacency `bmat` (the polar form; `bmat[i]` bit j ⇔ b_{ij}=1).
pub fn arf_f2(n: usize, qd: &[bool], bmat: &[u128]) -> ArfInvariants {
    assert!(
        n <= 128,
        "arf_f2 uses u128 bitmasks, so n must be at most 128"
    );
    assert!(
        qd.len() >= n && bmat.len() >= n,
        "arf_f2 needs qd and bmat entries for every basis vector"
    );
    let mut vectors: Vec<u128> = (0..n).map(|i| 1u128 << i).collect();
    let mut arf = false;
    let mut pairs = 0usize;
    let mut radical: Vec<u128> = Vec::new();

    while let Some(a) = vectors.pop() {
        if let Some(pos) = vectors.iter().position(|&w| b_of(a, w, bmat)) {
            let bb = vectors.swap_remove(pos);
            // make every remaining vector orthogonal to both a and bb
            for w in vectors.iter_mut() {
                let mut nw = *w;
                if b_of(*w, bb, bmat) {
                    nw ^= a;
                }
                if b_of(*w, a, bmat) {
                    nw ^= bb;
                }
                *w = nw;
            }
            if q_of(a, qd, bmat) && q_of(bb, qd, bmat) {
                arf ^= true;
            }
            pairs += 1;
        } else {
            radical.push(a); // orthogonal to everything ⇒ radical
        }
    }

    let radical_anisotropic = radical.iter().any(|&v| q_of(v, qd, bmat));
    ArfInvariants {
        arf: arf as u128,
        rank: 2 * pairs,
        radical_dim: radical.len(),
        radical_anisotropic,
    }
}

// ---------------------------------------------------------------------------
// General nim-field version (any On₂ entries, reduced to F₂ via the trace)
// ---------------------------------------------------------------------------

/// Smallest extension degree m = 2^k over F₂ such that the nim-subfield
/// F_{2^m} (the nimbers below 2^m) contains `max_val`.
pub(crate) fn min_field_degree(max_val: u128) -> u128 {
    let mut m = 1u128; // 2^k, starting k = 0  (F_2)
    loop {
        if m >= 128 {
            return 128;
        }
        if max_val < (1u128 << m) {
            return m;
        }
        m <<= 1;
    }
}

fn vscale(c: u128, v: &[u128]) -> Vec<u128> {
    v.iter().map(|&x| nim_mul(c, x)).collect()
}
fn vadd(u: &[u128], v: &[u128]) -> Vec<u128> {
    u.iter().zip(v).map(|(&a, &b)| nim_add(a, b)).collect()
}

fn vscale_field<F: Scalar>(c: &F, v: &[F]) -> Vec<F> {
    v.iter().map(|x| c.mul(x)).collect()
}

fn vadd_field<F: Scalar>(u: &[F], v: &[F]) -> Vec<F> {
    u.iter().zip(v).map(|(a, b)| a.add(b)).collect()
}

/// Q(v) = Σ_i v_i² q_i + Σ_{i<j} v_i v_j b_{ij}, over the nim-field.
fn qf(v: &[u128], q: &[u128], bmat: &[Vec<u128>]) -> u128 {
    let n = v.len();
    let mut acc = 0u128;
    for i in 0..n {
        acc ^= nim_mul(nim_mul(v[i], v[i]), q[i]);
        for j in (i + 1)..n {
            acc ^= nim_mul(nim_mul(v[i], v[j]), bmat[i][j]);
        }
    }
    acc
}

/// Polar form B(u,v) = Σ_{i<j} (u_i v_j + u_j v_i) b_{ij}, over the nim-field.
fn bf(u: &[u128], v: &[u128], bmat: &[Vec<u128>]) -> u128 {
    let n = u.len();
    let mut acc = 0u128;
    for i in 0..n {
        for j in (i + 1)..n {
            let cross = nim_add(nim_mul(u[i], v[j]), nim_mul(u[j], v[i]));
            acc ^= nim_mul(cross, bmat[i][j]);
        }
    }
    acc
}

/// Q(v) = Σ_i v_i² q_i + Σ_{i<j} v_i v_j b_{ij}, over a finite char-2 field.
fn qf_field<F: Scalar>(v: &[F], q: &[F], bmat: &[Vec<F>]) -> F {
    let n = v.len();
    let mut acc = F::zero();
    for i in 0..n {
        acc = acc.add(&v[i].mul(&v[i]).mul(&q[i]));
        for j in (i + 1)..n {
            acc = acc.add(&v[i].mul(&v[j]).mul(&bmat[i][j]));
        }
    }
    acc
}

/// Polar form B(u,v) = Σ_{i<j} (u_i v_j + u_j v_i) b_{ij}, over a finite
/// char-2 field.
fn bf_field<F: Scalar>(u: &[F], v: &[F], bmat: &[Vec<F>]) -> F {
    let n = u.len();
    let mut acc = F::zero();
    for i in 0..n {
        for j in (i + 1)..n {
            let cross = u[i].mul(&v[j]).add(&u[j].mul(&v[i]));
            acc = acc.add(&cross.mul(&bmat[i][j]));
        }
    }
    acc
}

fn arf_char2_core<F>(
    metric: &Metric<F>,
    trace_to_f2: impl Fn(&F) -> Option<u128>,
) -> Option<ArfInvariants>
where
    F: Scalar,
{
    if !metric.a.is_empty() {
        return None;
    }
    let n = metric.q.len();
    let q = metric.q.clone();
    let mut bmat = vec![vec![F::zero(); n]; n];
    for (&(i, j), v) in &metric.b {
        bmat[i][j] = v.clone();
        bmat[j][i] = v.clone();
    }

    let mut vectors: Vec<Vec<F>> = (0..n)
        .map(|i| {
            let mut e = vec![F::zero(); n];
            e[i] = F::one();
            e
        })
        .collect();

    let mut s = F::zero();
    let mut pairs = 0usize;
    let mut radical_dim = 0usize;
    let mut radical_anisotropic = false;

    while let Some(a) = vectors.pop() {
        if let Some(pos) = vectors
            .iter()
            .position(|w| !bf_field(&a, w, &bmat).is_zero())
        {
            let braw = vectors.swap_remove(pos);
            let c = bf_field(&a, &braw, &bmat);
            let c_inv = c.inv()?;
            let b = vscale_field(&c_inv, &braw); // rescale so B(a,b) = 1
            for w in vectors.iter_mut() {
                let wb = bf_field(w, &b, &bmat);
                let wa = bf_field(w, &a, &bmat);
                let mut nw = w.clone();
                if !wb.is_zero() {
                    nw = vadd_field(&nw, &vscale_field(&wb, &a));
                }
                if !wa.is_zero() {
                    nw = vadd_field(&nw, &vscale_field(&wa, &b));
                }
                *w = nw;
            }
            let qa = qf_field(&a, &q, &bmat);
            let qb = qf_field(&b, &q, &bmat);
            s = s.add(&qa.mul(&qb));
            pairs += 1;
        } else {
            radical_dim += 1;
            if !qf_field(&a, &q, &bmat).is_zero() {
                radical_anisotropic = true;
            }
        }
    }

    let arf = trace_to_f2(&s)?;
    Some(ArfInvariants {
        arf,
        rank: 2 * pairs,
        radical_dim,
        radical_anisotropic,
    })
}

/// Maximum nim-field entry value across all `q` and `b` scalars of `metric`.
/// Used by `isometric_nimber` to find a common field degree for two metrics.
pub(crate) fn nimber_metric_max_val(metric: &Metric<Nimber>) -> u128 {
    let mut maxv = metric.q.iter().map(|x| x.0).max().unwrap_or(0);
    for v in metric.b.values() {
        maxv = maxv.max(v.0);
    }
    maxv
}

/// Arf invariant of a nimber Clifford metric over its field of definition (the
/// smallest nim-subfield containing all entries), reduced to F₂ via the trace.
/// Works for any nimber metric — F₂ is the special case where the trace is the
/// identity. Symplectic reduction normalises each pair with `nim_inv`.
pub fn arf_nimber(metric: &Metric<Nimber>) -> Option<ArfInvariants> {
    let maxv = nimber_metric_max_val(metric);
    arf_nimber_at_degree(metric, min_field_degree(maxv))
}

/// Arf invariant of a nimber metric using an explicit field degree `m` (a power
/// of 2 up to 128) for the F_{2^m} → F₂ trace.  Callers that need to compare
/// two forms isometrically must pass the same `m` to both — typically
/// `min_field_degree(max(maxv1, maxv2))`.  General-bilinear metrics return `None`.
pub(crate) fn arf_nimber_at_degree(metric: &Metric<Nimber>, m: u128) -> Option<ArfInvariants> {
    if !metric.a.is_empty() {
        return None;
    }
    let n = metric.q.len();
    let q: Vec<u128> = metric.q.iter().map(|x| x.0).collect();
    let mut bmat = vec![vec![0u128; n]; n];
    for (&(i, j), v) in &metric.b {
        bmat[i][j] = v.0;
        bmat[j][i] = v.0;
    }

    // (m is already determined by the caller)

    let mut vectors: Vec<Vec<u128>> = (0..n)
        .map(|i| {
            let mut e = vec![0u128; n];
            e[i] = 1;
            e
        })
        .collect();

    let mut s = 0u128; // Σ Q(a_k) Q(b_k), a field element
    let mut pairs = 0usize;
    let mut radical_dim = 0usize;
    let mut radical_anisotropic = false;

    while let Some(a) = vectors.pop() {
        if let Some(pos) = vectors.iter().position(|w| bf(&a, w, &bmat) != 0) {
            let braw = vectors.swap_remove(pos);
            let c = bf(&a, &braw, &bmat);
            let b = vscale(nim_inv(c)?, &braw); // rescale so B(a,b) = 1
            for w in vectors.iter_mut() {
                let wb = bf(w, &b, &bmat);
                let wa = bf(w, &a, &bmat);
                let mut nw = w.clone();
                if wb != 0 {
                    nw = vadd(&nw, &vscale(wb, &a));
                }
                if wa != 0 {
                    nw = vadd(&nw, &vscale(wa, &b));
                }
                *w = nw;
            }
            s ^= nim_mul(qf(&a, &q, &bmat), qf(&b, &q, &bmat));
            pairs += 1;
        } else {
            radical_dim += 1;
            if qf(&a, &q, &bmat) != 0 {
                radical_anisotropic = true;
            }
        }
    }

    let arf = nim_trace(s, m);
    Some(ArfInvariants {
        arf,
        rank: 2 * pairs,
        radical_dim,
        radical_anisotropic,
    })
}

/// Arf invariant of a quadratic Clifford metric over a supported finite field of
/// characteristic 2 (`F₂` or `F_{2^N}`), reduced through the absolute trace
/// `Tr_{F/F₂}`. This is the `Fpn<2,N>` mirror of [`arf_nimber`].
pub fn arf_char2<F: FiniteChar2Field>(metric: &Metric<F>) -> Option<ArfInvariants> {
    F::ensure_supported()?;
    arf_char2_core(metric, |x| Some(F::artin_schreier_class(*x)))
}

/// Arf invariant for a const-generic `Fpn<P,N>` metric, returning `None` unless
/// `P = 2`. This exists so the finite-field façade can dispatch inside the single
/// `Fpn<P,N>` monomorphisation without pretending odd fields are char-2 fields.
pub fn arf_fpn_char2<const P: u128, const N: usize>(
    metric: &Metric<Fpn<P, N>>,
) -> Option<ArfInvariants> {
    if P != 2 || !Fpn::<P, N>::is_supported_field() {
        return None;
    }
    use crate::scalar::FieldExtension;
    arf_char2_core(metric, |x| Some(x.trace().value()))
}

/// Arf invariant of a nimber Clifford metric (the char-2 Clifford classifier).
pub fn arf_invariant(metric: &Metric<Nimber>) -> Option<ArfInvariants> {
    arf_nimber(metric)
}

fn ordinal_trace_to_f2_at_degree(x: &Ordinal, degree: u128) -> Option<u128> {
    let mut acc = Ordinal::zero();
    let mut y = x.clone();
    for i in 0..degree {
        acc = acc.add(&y);
        if i + 1 != degree {
            y = y.nim_mul(&y)?;
        }
    }
    match acc.as_finite()? {
        0 => Some(0),
        1 => Some(1),
        _ => None,
    }
}

/// Try to convert a pure-finite ordinal metric to a `Metric<Nimber>`.
/// Returns `None` if any entry is not a finite ordinal.
pub(crate) fn ordinal_to_nimber_metric(metric: &Metric<Ordinal>) -> Option<Metric<Nimber>> {
    if !metric.a.is_empty() {
        return None;
    }
    let q = metric
        .q
        .iter()
        .map(|x| x.as_finite().map(Nimber))
        .collect::<Option<Vec<_>>>()?;
    let b = metric
        .b
        .iter()
        .map(|(&(i, j), x)| x.as_finite().map(|v| ((i, j), Nimber(v))))
        .collect::<Option<BTreeMap<_, _>>>()?;
    Some(Metric::new(q, b))
}

/// Minimal finite subfield degree containing every scalar in an ordinal metric.
/// Returns `None` for general-bilinear metrics or entries outside the staged
/// finite-subfield detector.
pub fn ordinal_metric_finite_subfield_degree(metric: &Metric<Ordinal>) -> Option<u128> {
    if !metric.a.is_empty() {
        return None;
    }
    ordinal_common_finite_subfield_degree(metric.q.iter().chain(metric.b.values()))
}

/// Arf invariant for a finite ordinal-nimber metric using an explicit containing
/// field degree for the absolute trace. The caller is responsible for choosing a
/// common degree when comparing multiple forms.
pub(crate) fn arf_ordinal_at_degree(
    metric: &Metric<Ordinal>,
    degree: u128,
) -> Option<ArfInvariants> {
    if !metric.a.is_empty() {
        return None;
    }
    let metric_degree = ordinal_metric_finite_subfield_degree(metric)?;
    if !degree.is_multiple_of(metric_degree) {
        return None;
    }
    arf_char2_core(metric, |x| ordinal_trace_to_f2_at_degree(x, degree))
}

/// Arf invariant for finite ordinal-nimber windows represented by the `Ordinal`
/// backend. Purely finite entries delegate to [`arf_nimber`]. All other detected
/// finite subfields use the same generic symplectic reduction plus the absolute
/// trace from their minimal common `F_{2^m}`. Genuinely transfinite coefficients
/// return `None`; choosing a classifier there remains open.
pub fn arf_ordinal_finite(metric: &Metric<Ordinal>) -> Option<ArfInvariants> {
    if !metric.a.is_empty() {
        return None;
    }

    if let Some(nim) = ordinal_to_nimber_metric(metric) {
        return arf_nimber(&nim);
    }

    let degree = ordinal_metric_finite_subfield_degree(metric)?;
    arf_ordinal_at_degree(metric, degree)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scalar::{Fp, Fpn, Ordinal};
    use std::collections::BTreeMap;

    fn metric(qs: &[u128], bs: &[((usize, usize), u128)]) -> Metric<Nimber> {
        let q = qs.iter().map(|&x| Nimber(x)).collect();
        let mut b = BTreeMap::new();
        for &((i, j), v) in bs {
            b.insert((i, j), Nimber(v));
        }
        Metric::new(q, b)
    }
    fn b1(pairs: &[(usize, usize)]) -> Vec<((usize, usize), u128)> {
        pairs.iter().map(|&p| (p, 1)).collect()
    }
    fn metric_field<F: Scalar>(qs: &[F], bs: &[((usize, usize), F)]) -> Metric<F> {
        let mut b = BTreeMap::new();
        for ((i, j), v) in bs {
            b.insert((*i, *j), v.clone());
        }
        Metric::new(qs.to_vec(), b)
    }

    #[test]
    fn hyperbolic_plane_is_o_plus() {
        // Q = x0 x1: a single hyperbolic pair, Arf 0.
        let r = arf_invariant(&metric(&[0, 0], &b1(&[(0, 1)]))).unwrap();
        assert_eq!(
            (r.arf, r.rank, r.radical_dim, r.o_type()),
            (0, 2, 0, OrthogonalType::OPlus)
        );
    }

    #[test]
    fn anisotropic_plane_is_o_minus() {
        // Q = x0² + x0 x1 + x1²: Arf 1.
        let r = arf_invariant(&metric(&[1, 1], &b1(&[(0, 1)]))).unwrap();
        assert_eq!((r.arf, r.rank, r.o_type()), (1, 2, OrthogonalType::OMinus));
    }

    #[test]
    fn the_two_planes_are_distinguished() {
        let h = arf_invariant(&metric(&[0, 0], &b1(&[(0, 1)]))).unwrap();
        let a = arf_invariant(&metric(&[1, 1], &b1(&[(0, 1)]))).unwrap();
        assert_ne!(h.arf, a.arf); // exactly what classifies them
    }

    #[test]
    fn arf_is_additive_over_orthogonal_sum() {
        // H⊕H = O+,  H⊕A = O-,  A⊕A = O+  (two anisotropic planes ≅ two hyperbolic)
        let hh = arf_invariant(&metric(&[0, 0, 0, 0], &b1(&[(0, 1), (2, 3)]))).unwrap();
        let ha = arf_invariant(&metric(&[0, 0, 1, 1], &b1(&[(0, 1), (2, 3)]))).unwrap();
        let aa = arf_invariant(&metric(&[1, 1, 1, 1], &b1(&[(0, 1), (2, 3)]))).unwrap();
        assert_eq!((hh.arf, hh.rank), (0, 4));
        assert_eq!((ha.arf, ha.rank), (1, 4));
        assert_eq!((aa.arf, aa.rank), (0, 4)); // A⊕A ≅ H⊕H
    }

    #[test]
    fn arf_additive_over_graded_tensor() {
        // The same A⊕A ≅ H⊕H fact, but built with the `direct_sum` *operation*
        // rather than a hand-written 4-generator metric: arf is additive over ⟂.
        let a = metric(&[1, 1], &b1(&[(0, 1)])); // anisotropic plane, Arf 1
        let h = metric(&[0, 0], &b1(&[(0, 1)])); // hyperbolic plane,  Arf 0
        let aa = arf_invariant(&a.direct_sum(&a)).unwrap();
        let hh = arf_invariant(&h.direct_sum(&h)).unwrap();
        let ah = arf_invariant(&a.direct_sum(&h)).unwrap();
        assert_eq!(aa.arf, 0); // 1 + 1 = 0
        assert_eq!(hh.arf, 0); // 0 + 0 = 0  ⇒  A⊕A ≅ H⊕H
        assert_eq!(ah.arf, 1); // 1 + 0 = 1
        assert_eq!((aa.rank, hh.rank, ah.rank), (4, 4, 4));
    }

    #[test]
    fn radical_is_detected() {
        // Q = x0 x1 + x2²: rank-2 core ⊕ a defective radical direction.
        let r = arf_invariant(&metric(&[0, 0, 1], &b1(&[(0, 1)]))).unwrap();
        assert_eq!(
            (r.rank, r.radical_dim, r.radical_anisotropic, r.arf),
            (2, 1, true, 0)
        );
    }

    #[test]
    fn f4_forms_via_trace() {
        // Genuine F₄ forms (entries up to *3), hand-computed via the trace:
        //   q=[*2,*3], b01=*1:  S = *2⊗*3 = *1,  Tr_{F₄/F₂}(*1) = *1+*1 = 0  ⇒ O+
        let r1 = arf_invariant(&metric(&[2, 3], &b1(&[(0, 1)]))).unwrap();
        assert_eq!(
            (r1.arf, r1.o_type(), r1.rank),
            (0, OrthogonalType::OPlus, 2)
        );
        //   q=[*2,*2], b01=*1:  S = *2⊗*2 = *3,  Tr(*3) = *3+*2 = *1       ⇒ O-
        let r2 = arf_invariant(&metric(&[2, 2], &b1(&[(0, 1)]))).unwrap();
        assert_eq!(
            (r2.arf, r2.o_type(), r2.rank),
            (1, OrthogonalType::OMinus, 2)
        );
    }

    #[test]
    #[allow(clippy::type_complexity)] // compact table of F2 diagonals and polar pairs
    fn generic_char2_agrees_with_f2_bitmask() {
        let cases: &[(&[u128], &[(usize, usize)])] = &[
            (&[0, 0], &[(0, 1)]),
            (&[1, 1], &[(0, 1)]),
            (&[0, 0, 1], &[(0, 1)]),
            (&[1, 0, 1, 1], &[(0, 1), (2, 3)]),
        ];
        for (qs, ps) in cases {
            let qf: Vec<Fp<2>> = qs.iter().map(|&x| Fp::<2>::from_u128(x)).collect();
            let bf: Vec<((usize, usize), Fp<2>)> =
                ps.iter().map(|&p| (p, Fp::<2>::one())).collect();
            let general = arf_char2(&metric_field(&qf, &bf)).unwrap();
            let n = qs.len();
            let qd: Vec<bool> = qs.iter().map(|&x| x == 1).collect();
            let mut bmat = vec![0u128; n];
            for &(i, j) in *ps {
                bmat[i] |= 1 << j;
                bmat[j] |= 1 << i;
            }
            assert_eq!(general, arf_f2(n, &qd, &bmat), "mismatch on q={qs:?}");
        }
    }

    #[test]
    fn f8_forms_use_the_absolute_trace() {
        type F8 = Fpn<2, 3>;
        let a = F8::generator();
        let one = F8::one();

        // A normalized plane has Arf Tr(q0*q1). This uses the genuine F_8
        // coefficient a rather than an F_2-valued diagonal.
        let m = metric_field(&[a, a], &[((0, 1), one)]);
        let r = arf_char2(&m).unwrap();
        assert_eq!(r.rank, 2);
        assert_eq!(r.radical_dim, 0);
        assert_eq!(r.arf, F8::artin_schreier_class(a.mul(&a)));

        // Additivity over orthogonal sums is XOR of the trace-reduced plane bits.
        let doubled = m.direct_sum(&m);
        assert_eq!(arf_char2(&doubled).unwrap().arf, 0);
    }

    #[test]
    fn f8_zero_count_matches_arf_for_planes() {
        type F8 = Fpn<2, 3>;
        let elems: Vec<F8> = (0..F8::field_order()).map(F8::from_index).collect();
        let planes = [
            metric_field(&[F8::zero(), F8::zero()], &[((0, 1), F8::one())]),
            metric_field(&[F8::generator(), F8::generator()], &[((0, 1), F8::one())]),
        ];
        for m in planes {
            let r = arf_char2(&m).unwrap();
            let q0 = m.q[0];
            let q1 = m.q[1];
            let b01 = m.b[&(0, 1)];
            let zeros = elems
                .iter()
                .flat_map(|&x| elems.iter().map(move |&y| (x, y)))
                .filter(|&(x, y)| {
                    x.mul(&x)
                        .mul(&q0)
                        .add(&y.mul(&y).mul(&q1))
                        .add(&x.mul(&y).mul(&b01))
                        .is_zero()
                })
                .count() as i128;
            let q = F8::field_order() as i128;
            let expected = if r.arf == 0 { q + (q - 1) } else { q - (q - 1) };
            assert_eq!(zeros, expected, "wrong zero count for {r:?}");
        }
    }

    #[test]
    fn ordinal_f64_forms_use_the_absolute_trace() {
        let w = Ordinal::omega();
        let one = Ordinal::one();
        let m = metric_field(&[w.clone(), w.clone()], &[((0, 1), one)]);
        let r = arf_ordinal_finite(&m).unwrap();
        assert_eq!(r.rank, 2);
        assert_eq!(r.radical_dim, 0);
        assert_eq!(ordinal_metric_finite_subfield_degree(&m), Some(6));
        assert_eq!(r.arf, ordinal_trace_to_f2_at_degree(&w.mul(&w), 6).unwrap());

        let higher = Metric::diagonal(vec![Ordinal::omega_pow(Ordinal::omega())]);
        assert_eq!(ordinal_metric_finite_subfield_degree(&higher), Some(20));
        assert!(arf_ordinal_finite(&higher).is_some());
    }

    #[test]
    fn ordinal_detector_extends_past_f64_window() {
        let chi5 = Ordinal::omega_pow(Ordinal::omega());
        let mut b = BTreeMap::new();
        b.insert((0usize, 1usize), chi5.clone());
        let m = Metric::new(vec![Ordinal::zero(), Ordinal::zero()], b);
        let r = arf_ordinal_finite(&m).unwrap();
        assert_eq!(ordinal_metric_finite_subfield_degree(&m), Some(20));
        assert_eq!((r.arf, r.rank, r.radical_dim), (0, 2, 0));
    }

    #[test]
    fn ordinal_detector_rejects_past_the_staged_segment() {
        let outside = Metric::diagonal(vec![Ordinal::omega_pow(Ordinal::omega_pow(
            Ordinal::omega(),
        ))]);
        assert_eq!(ordinal_metric_finite_subfield_degree(&outside), None);
        assert_eq!(arf_ordinal_finite(&outside), None);
    }

    #[test]
    fn arf_rejects_general_bilinear_metrics() {
        let mut a = BTreeMap::new();
        a.insert((0, 1), Nimber(1));
        let m = Metric::general(vec![Nimber(1), Nimber(1)], BTreeMap::new(), a);
        assert_eq!(arf_invariant(&m), None);
    }

    #[test]
    #[allow(clippy::type_complexity)] // test fixture: list of (q-diagonal, polar-pairs)
    fn general_agrees_with_f2_bitmask() {
        // The general nim-field path must match the F₂ bitmask version on every
        // F₂ form (arf, rank, radical_dim, anisotropy, type all invariant).
        let cases: &[(&[u128], &[(usize, usize)])] = &[
            (&[0, 0], &[(0, 1)]),
            (&[1, 1], &[(0, 1)]),
            (&[0, 0, 1], &[(0, 1)]),
            (&[1, 0, 1, 1], &[(0, 1), (2, 3)]),
            (&[1, 1, 1, 1, 0], &[(0, 1), (2, 3)]),
        ];
        for (qs, ps) in cases {
            let general = arf_nimber(&metric(qs, &b1(ps))).unwrap();
            let n = qs.len();
            let qd: Vec<bool> = qs.iter().map(|&x| x == 1).collect();
            let mut bmat = vec![0u128; n];
            for &(i, j) in *ps {
                bmat[i] |= 1 << j;
                bmat[j] |= 1 << i;
            }
            assert_eq!(general, arf_f2(n, &qd, &bmat), "mismatch on q={:?}", qs);
        }
    }

    // `arf_f2` and `brown_f2` are declared to mirror each other field-for-field
    // (CONSISTENCY.md `micro-naming-2`); `brown_f2` already asserts these input
    // shapes (`forms/char2/brown.rs`), so `arf_f2` must too.
    #[test]
    #[should_panic(expected = "at most 128")]
    fn arf_f2_rejects_dimension_past_u128_bitmask() {
        arf_f2(129, &[false; 129], &[0u128; 129]);
    }

    #[test]
    #[should_panic(expected = "entries for every basis vector")]
    fn arf_f2_rejects_mismatched_lengths() {
        arf_f2(3, &[false, false], &[0u128, 0u128, 0u128]);
    }
}