ogdoad 1.0.5

Clifford algebras and quadratic forms over exact, finite, local, transfinite, and game-adjacent scalar backends.
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
//! Trace, transfer, and Gold forms from finite field extensions.
//!
//! For a cyclic Galois extension `E/F`, [`trace_twisted_form`] constructs
//! `Q_k(x) = Tr_{E/F}(x σ^k(x))` on the underlying `F`-vector space. In
//! characteristic two the untwisted quadratic map `Tr_{E/F}(x²)` has zero polar
//! form because
//! `Tr((x+y)²) = Tr(x²) + Tr(y²)` and the polar form **vanishes** — it degenerates
//! so nonzero twists supply the relevant polar data:
//!
//! ```text
//! Q_k(x) = Tr_{E/F}( x · σ^k(x) )
//! ```
//!
//! Its polar form is `B(x,y) = Tr(x σ^k(y) + y σ^k(x))`. For
//! `E = F_{2^m}` and `σ` Frobenius, this is the Gold form
//! `Q_a(x) = Tr(x^{1+2^a})`; [`gold_form`] constructs it over supported nim
//! subfields.
//!
//! The same construction over `Surcomplex` (`σ = ` conjugation, `k = 1`) gives the
//! **norm form** `Tr(x·x̄) = 2(a²+b²)` — the binary Pfister/norm form; over `Qq` it
//! gives an unramified local trace form using a Teichmuller-lifted residue basis; and
//! over an odd-characteristic `Fpn` it gives an ordinary diagonalizable trace form.
//!
//! A returned [`Metric`] is limited to [`MAX_BASIS_DIM`] generators.

use crate::clifford::{Metric, MAX_BASIS_DIM};
use crate::forms::ArfInvariants;
use crate::scalar::{
    nim_frobenius_iter, nim_mul, nim_relative_trace, nim_solve_artin_schreier, nim_trace,
    CyclicGaloisExtension, FieldExtension, Fp, Nimber, Scalar,
};
use std::collections::BTreeMap;

/// Assemble the twisted form `Q(x) = trace(x · twist(x))` over a basis: the shared
/// core behind [`trace_twisted_form`] (trait-driven) and [`gold_form`] (nim-native).
/// `twist` is `σ^k` and `trace` is the relative trace `E → F` (= `T`).
fn assemble_twisted_form<E: Scalar, T: Scalar>(
    basis: &[E],
    twist: impl Fn(&E) -> E,
    trace: impl Fn(&E) -> T,
) -> Metric<T> {
    let n = basis.len();
    let tw: Vec<E> = basis.iter().map(&twist).collect();

    // diagonal: q_i = Tr(e_i · σ^k(e_i))
    let q: Vec<T> = basis
        .iter()
        .zip(&tw)
        .map(|(e, te)| trace(&e.mul(te)))
        .collect();

    // polar: b_{ij} = Tr(e_i σ^k(e_j) + e_j σ^k(e_i))  (i < j), sparse
    let mut b = BTreeMap::new();
    for i in 0..n {
        for j in (i + 1)..n {
            let t = trace(&basis[i].mul(&tw[j]).add(&basis[j].mul(&tw[i])));
            if !t.is_zero() {
                b.insert((i, j), t);
            }
        }
    }

    Metric::general(q, b, BTreeMap::new())
}

fn insert_metric_block<S: Scalar>(
    q: &mut [S],
    b: &mut BTreeMap<(usize, usize), S>,
    offset: usize,
    block: Metric<S>,
) {
    let (bq, bb, ba) = block.into_parts();
    debug_assert!(ba.is_empty());
    for (i, qi) in bq.into_iter().enumerate() {
        q[offset + i] = qi;
    }
    for ((i, j), v) in bb {
        b.insert((offset + i, offset + j), v);
    }
}

/// The Frobenius-twisted trace form `Q_k(x) = Tr_{E/F}(x · σ^k(x))` of a cyclic
/// Galois extension `E/F`, as a [`Metric`] over the base `F` in the distinguished
/// [`basis`](CyclicGaloisExtension::basis) `(e_0,…,e_{d-1})`:
///
/// ```text
/// q_i    = Tr(e_i · σ^k(e_i))
/// b_{ij} = Tr(e_i σ^k(e_j) + e_j σ^k(e_i))      (i < j)
/// ```
///
/// `k = 1` is the standard choice (`σ` itself); larger `k` gives the higher Gold
/// exponents `1 + 2^k`.
///
/// **The transfer reading (`k = 0`).** With `σ^0 = id` the twist vanishes and the
/// form is `Tr_{E/F}(x·y)` — the **Scharlau transfer** `s_*(⟨1⟩)` of the unit form
/// `⟨1⟩ ∈ W(E)` along `s = Tr_{E/F}` (Lam, *Introduction to Quadratic Forms over
/// Fields*, GSM 67, Ch. VII; Scharlau, *Quadratic and Hermitian Forms*, Ch. 2).
/// Equivalently `trace_twisted_form::<E>(0) == transfer_diagonal(&[E::one()])`. The
/// general transfer of a diagonal form is [`transfer_diagonal`].
pub fn trace_twisted_form<E>(k: usize) -> Metric<E::Base>
where
    E: CyclicGaloisExtension,
{
    assemble_twisted_form(&E::basis(), |e| e.sigma_power(k), |z| z.trace())
}

/// The cyclic-algebra trace form `T_A(z) = Trd_A(z²)` for the crossed product
/// algebra `A = (E/F, σ, a) = ⊕ᵢ E·uⁱ`, with `uⁿ = a` and `u·x = σ(x)·u`.
/// The basis is ordered by `u`-line: `(e_0, …, e_{n-1})`,
/// `(e_0u, …, e_{n-1}u)`, …, where `(e_i)` is
/// [`CyclicGaloisExtension::basis`].
///
/// Reduced trace sees only the `u⁰` coefficient, so the form splits into the
/// self-line `E`, the middle self-line `E·u^{n/2}` when `n` is even, and pure
/// polar pairings between `E·uⁱ` and `E·u^{n-i}`:
///
/// ```text
/// T_A(Σ x_i u^i) =
///   Tr(x_0²)
///   + [n even] Tr(a · x_{n/2} σ^{n/2}(x_{n/2}))
///   + Σ_{0<i<n-i} Tr(a · (x_i σ^i(x_{n-i}) + x_{n-i} σ^{n-i}(x_i))).
/// ```
///
/// This is the literal quadratic trace form, not the degree-2 reduced norm. For
/// a quaternion algebra the relation is the Cayley-Hamilton identity
/// `Trd(z²) = Trd(z)² - 2·Nrd(z)`.
pub fn cyclic_algebra_trace_form<E>(a: &E::Base) -> Metric<E::Base>
where
    E: CyclicGaloisExtension,
{
    let basis = E::basis();
    let n = basis.len();
    let dim = n
        .checked_mul(n)
        .expect("cyclic algebra trace-form dimension overflowed");
    assert!(
        dim <= MAX_BASIS_DIM,
        "cyclic_algebra_trace_form has dimension [E:F]^2={dim}, exceeding {MAX_BASIS_DIM}"
    );

    let mut q = vec![E::Base::zero(); dim];
    let mut b = BTreeMap::new();

    let line0 = assemble_twisted_form(&basis, |x| x.clone(), |z| z.trace());
    insert_metric_block(&mut q, &mut b, 0, line0);

    if n % 2 == 0 {
        let mid = n / 2;
        let middle = assemble_twisted_form(&basis, |x| x.sigma_power(mid), |z| a.mul(&z.trace()));
        insert_metric_block(&mut q, &mut b, mid * n, middle);
    }

    for i in 1..n {
        let j = n - i;
        if i >= j {
            continue;
        }
        for r in 0..n {
            for s in 0..n {
                let term = basis[r]
                    .mul(&basis[s].sigma_power(i))
                    .add(&basis[s].mul(&basis[r].sigma_power(j)));
                let value = a.mul(&term.trace());
                if !value.is_zero() {
                    b.insert((i * n + r, j * n + s), value);
                }
            }
        }
    }

    Metric::general(q, b, BTreeMap::new())
}

/// Scalar extension (Witt restriction)
/// `r*: W(F) -> W(E)` of a diagonal form along a cyclic Galois extension
/// `E/F`: `⟨a_1,...,a_r⟩` becomes `⟨i(a_1),...,i(a_r)⟩` via the canonical
/// [`embed`](FieldExtension::embed) map.
///
/// This is additive on orthogonal sums and multiplicative for tensor products.
/// Together with [`transfer_diagonal`] it satisfies Frobenius reciprocity
/// `s_*(r*(x) y) = x s_*(y)`.  Odd-degree injectivity is Springer's theorem;
/// even-degree restriction can kill a nonzero Witt class.
pub fn restrict_diagonal<E>(entries: &[E::Base]) -> Metric<E>
where
    E: CyclicGaloisExtension,
{
    Metric::diagonal(entries.iter().map(E::embed).collect())
}

/// The **Scharlau transfer** `s_*(⟨λ_1,…,λ_r⟩)` of a diagonal form over `E`, pushed
/// to `W(F)` along the field trace `s = Tr_{E/F}` (Lam, GSM 67, Ch. VII; Scharlau,
/// *Quadratic and Hermitian Forms*, Ch. 2). Each diagonal entry `λ ∈ E` contributes
/// the `[E:F]`-dimensional block `(x, y) ↦ Tr_{E/F}(λ·x·y)` over the distinguished
/// [`basis`](CyclicGaloisExtension::basis) `(e_0,…,e_{d-1})`:
///
/// ```text
/// q_a      = Tr(λ · e_a · e_a)
/// b_{ab}   = Tr(λ · (e_a e_b + e_b e_a))            (a < b)
/// ```
///
/// and the blocks are orthogonally summed — `s_*` is additive on `⟂`. The unit case
/// `transfer_diagonal(&[E::one()])` is `Tr(x·y)`, i.e. `s_*(⟨1⟩)`, the `k = 0` member
/// of [`trace_twisted_form`].
///
/// `s_*` is a group homomorphism `W(E) → W(F)` (the transfer of a hyperbolic form is
/// hyperbolic), and satisfies **Frobenius reciprocity** `s_*(r*(x)·y) = x·s_*(y)`,
/// where `r* : W(F) → W(E)` is restriction. Restriction itself is **injective** for
/// odd `[E:F]` (Springer's odd-degree theorem) — the companion to the Springer
/// *residue* theorem that drives the local layer.
///
/// **Boundary:** char `≠ 2`. In characteristic 2 the trace form `Tr(x·σ^k(x))`
/// degenerates (the `Tr(x²)` trap this module documents); the char-2 transfer story
/// is the Artin–Schreier route in `function_field_char2.rs`. The total dimension is
/// `r·[E:F]`, so as a [`Metric`] it is capped at `MAX_BASIS_DIM = 128`.
pub fn transfer_diagonal<E>(entries: &[E]) -> Metric<E::Base>
where
    E: CyclicGaloisExtension,
{
    let basis = E::basis();
    let mut result = Metric::diagonal(Vec::new());
    for lambda in entries {
        let block = assemble_twisted_form(&basis, |x| lambda.mul(x), |z| z.trace());
        result = result.direct_sum(&block);
    }
    result
}

/// The Arf invariant of the characteristic-two twisted trace form of `E/F_2`.
/// Builds `Q_k` over `F_2`, lifts the
/// coefficients `F_2 ↪ Nimber` (so the char-2 [`ArfInvariants`] classifier can read the
/// form), and returns its Arf data. For `E = Fpn<2,m>` with `k = a` this is the Gold
/// form `Tr(x^{1+2^a})`; see [`gold_form`] for the nim-native construction that
/// reaches the larger power-of-two fields.
pub fn trace_form_arf<E>(k: usize) -> Option<ArfInvariants>
where
    E: CyclicGaloisExtension + FieldExtension<Base = Fp<2>>,
{
    trace_twisted_form::<E>(k)
        .map(|x| Nimber(x.value()))
        .classify()
        .ok()
}

fn assert_nim_subfield_degree(m: usize) {
    assert!(
        m.is_power_of_two() && m <= 128,
        "the nimbers < 2^m form a subfield only for m a power of two <= 128"
    );
}

fn assert_in_nim_subfield(x: u128, m: usize) {
    assert!(
        m == 128 || x < (1u128 << m),
        "the scale must lie in the selected nim subfield"
    );
}

/// The trace-dual of the canonical-basis diagonal of the scaled Gold component
///
/// ```text
/// Q_{a,c}(x) = Tr(c * x^(1 + 2^a)).
/// ```
///
/// More precisely, if `e_i = 2^i` is the canonical bit basis of
/// `F_{2^m} ⊂ Nimber`, the returned `lambda` is the unique element satisfying
///
/// ```text
/// Tr(lambda * e_i) = Tr(c * e_i * e_i^(2^a))     for every i < m.
/// ```
///
/// The construction is tower-recursive and does not evaluate the right-hand
/// side one coordinate at a time.  Write `F_{2^(2M)} = F_{2^M}(u)` in the
/// canonical nim tower, with top-half basis `u*e_j`.  If `c = c0 + u*c1`, the
/// relative traces of `c` and `c*u^(1+2^a)` are the two smaller scaled
/// components.  The trace-pairing block identities
///
/// ```text
/// Tr_rel((A + u*B) * e)     = B*e,
/// Tr_rel((A + u*B) * u*e)   = (A+B)*e
/// ```
///
/// then reconstruct the dual as `(lambda0+lambda1) + u*lambda0`.
///
/// `m` must be a power of two at most 128 and `c` must lie in that subfield.
pub fn gold_component_diagonal_dual(m: usize, a: usize, c: u128) -> u128 {
    assert_nim_subfield_degree(m);
    assert_in_nim_subfield(c, m);

    fn recurse(m: usize, a: usize, c: u128) -> u128 {
        if m == 1 {
            return c & 1;
        }

        let half = m / 2;
        let u = 1u128 << half;
        let low_scale = nim_relative_trace(c, m as u128, half as u128);
        let u_twisted = nim_frobenius_iter(u, a % m);
        let top_scale =
            nim_relative_trace(nim_mul(c, nim_mul(u, u_twisted)), m as u128, half as u128);
        let low_dual = recurse(half, a, low_scale);
        let top_dual = recurse(half, a, top_scale);

        (low_dual ^ top_dual) ^ (low_dual << half)
    }

    recurse(m, a, c)
}

/// The trace-dual `lambda_a^(m)` of the unscaled Gold diagonal
/// `Q_a(e_i) = Tr(e_i^(1+2^a))` in the canonical nim basis.
///
/// This is [`gold_component_diagonal_dual`] with scale `c = 1`.
pub fn gold_diagonal_dual(m: usize, a: usize) -> u128 {
    gold_component_diagonal_dual(m, a, 1)
}

/// A tower-uniform Artin--Schreier source for every Gold diagonal.
///
/// Returns `w in F_{2^m}` such that, with `lambda = w^2 + w`,
///
/// ```text
/// Tr(lambda * e_i) = Tr(e_i^(1+2^a))     for every canonical basis coin e_i.
/// ```
///
/// For every even power-of-two degree `m`, the first step of the dual recursion
/// has zero low block, so [`gold_diagonal_dual`] lies in the half-field
/// `F_{2^(m/2)}`.  Its absolute trace from the quadratic extension is therefore
/// zero, which is exactly the Artin--Schreier solvability criterion.  The returned
/// root is selected by the exact nim-field solver; its companion is `w ^ 1`.
///
/// This supplies the diagonal source for every Gold exponent, including even
/// `a`; it does not construct or analyze a game rule.
pub fn gold_diagonal_artin_schreier_source(m: usize, a: usize) -> u128 {
    assert!(
        m >= 2,
        "the Artin--Schreier source needs an even extension degree"
    );
    let lambda = gold_diagonal_dual(m, a);
    debug_assert!(lambda < (1u128 << (m / 2)));
    nim_solve_artin_schreier(lambda, m as u128)
        .expect("the Gold diagonal dual lies in the Artin--Schreier image")
}

/// The **Gold form** `Q_a(x) = Tr_{F_{2^m}/F_2}(x^{1+2^a})` over the nim subfield
/// `F_{2^m} ⊂ Nimber`, as an `F_2`-valued [`Metric`]`<Nimber>`. The bit basis
/// `{1, 2, …, 2^{m-1}}` is an `F_2`-basis of `F_{2^m}`, the twist `σ^a` is the
/// `a`-fold nim-Frobenius `x ↦ x^{2^a}`, and the trace is `nim_trace(·, m)`.
///
/// `m` must be a **power of two** `≤ 128`: only then do the nimbers `< 2^m` form a
/// subfield (`F_{2^{2^k}}`) closed under nim-multiplication. The Gold-rank theorem
/// gives `rank = m − gcd(2a, m)`.
pub fn gold_form(m: usize, a: usize) -> Metric<Nimber> {
    assert_nim_subfield_degree(m);
    let basis: Vec<Nimber> = (0..m).map(|i| Nimber(1u128 << i)).collect();
    assemble_twisted_form(
        &basis,
        |x| {
            // σ^a = the a-fold nim-Frobenius x ↦ x^{2^a}
            Nimber(nim_frobenius_iter(x.0, a % m))
        },
        |x| Nimber(nim_trace(x.0, m as u128)),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scalar::{Fp, Fpn, Qq, Rational, Surcomplex};

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

    fn gcd(a: usize, b: usize) -> usize {
        if b == 0 {
            a
        } else {
            gcd(b, a % b)
        }
    }

    fn eval_rational_metric(m: &Metric<Rational>, coords: &[i128]) -> Rational {
        assert_eq!(m.dim(), coords.len());
        let mut total = Rational::zero();
        for (i, &ci) in coords.iter().enumerate() {
            let x = r(ci);
            total = total.add(&m.q[i].mul(&x).mul(&x));
        }
        for (&(i, j), bij) in &m.b {
            total = total.add(&bij.mul(&r(coords[i])).mul(&r(coords[j])));
        }
        total
    }

    #[test]
    fn surcomplex_twist_is_the_norm_form() {
        // E = ℚ(i)/ℚ, σ = conjugation, k = 1: Q(x) = Tr(x·x̄) = 2(a²+b²), the binary
        // norm form ⟨2, 2⟩ (diagonal, no polar term).
        let m = trace_twisted_form::<Surcomplex<Rational>>(1);
        assert_eq!(m.q, vec![Rational::from_int(2), Rational::from_int(2)]);
        assert!(m.b.is_empty());
    }

    #[test]
    fn cyclic_trace_form_degree_two_is_literal_trd_square() {
        // For A = (Q(i)/Q, conjugation, a), ordered as (1, i, u, iu),
        // Trd(z^2) is <2, -2, 2a, 2a>. This is adjacent to, but not equal to,
        // the reduced norm <1, 1, -a, -a>.
        for a in [-3i128, -1, 2, 5] {
            let m = cyclic_algebra_trace_form::<Surcomplex<Rational>>(&r(a));
            assert_eq!(m.q, vec![r(2), r(-2), r(2 * a), r(2 * a)]);
            assert!(m.b.is_empty());
        }
    }

    #[test]
    fn cyclic_trace_form_degree_two_satisfies_cayley_hamilton_relation() {
        // The degree-2 relation to the reduced norm is
        // Trd(z^2) = Trd(z)^2 - 2*Nrd(z), not equality with Nrd.
        for a in [-3i128, 2, 5] {
            let m = cyclic_algebra_trace_form::<Surcomplex<Rational>>(&r(a));
            for p in -1..=1 {
                for q in -1..=1 {
                    for u in -1..=1 {
                        for v in -1..=1 {
                            let lhs = eval_rational_metric(&m, &[p, q, u, v]);
                            let trd = 2 * p;
                            let nrd = p * p + q * q - a * u * u - a * v * v;
                            let rhs = r(trd * trd - 2 * nrd);
                            assert_eq!(lhs, rhs, "a={a}, coords={:?}", [p, q, u, v]);
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn qq_twist_uses_the_unramified_galois_basis() {
        // E = Q_9/Q_3 uses the unramified local
        // leg via the Teichmüller-lifted residue basis and the Witt-Frobenius.
        type Q9 = Qq<3, 3, 2>;
        let m = trace_twisted_form::<Q9>(1);
        assert_eq!(m.q.len(), 2);
        assert!(m.q.iter().all(|x| !x.is_zero()));
        assert!(m.q.iter().all(|x| x.valuation().is_some()));
    }

    #[test]
    fn cyclic_trace_form_degree_three_has_hyperbolic_cross_pair() {
        // For n = 3 there is one self-line (u^0) and one pure polar pair
        // (u^1, u^2). The pair is hyperbolic, so the Witt anisotropic kernel
        // matches the u^0 trace-square block.
        let t = cyclic_algebra_trace_form::<Fpn<3, 3>>(&Fp::<3>::one());
        let line0 = trace_twisted_form::<Fpn<3, 3>>(0);
        assert_eq!(t.dim(), 9);
        assert_eq!(&t.q[..3], line0.q());
        assert!(t.q[3..].iter().all(|x| x.is_zero()));
        for (&(i, j), v) in line0.b() {
            assert_eq!(t.b.get(&(i, j)), Some(v));
        }

        let t_dec = t.witt_decompose().expect("F_3 trace form decomposition");
        let line_dec = line0
            .witt_decompose()
            .expect("F_3 line trace form decomposition");
        assert_eq!(t_dec.anisotropic_dim, line_dec.anisotropic_dim);
    }

    #[test]
    fn gold_form_over_small_fpn_matches_rank_formula() {
        // The typed finite-field path: Gold Q_a over Fpn<2,m>, m = 2, 3.
        // F_4 (m=2), a=1: gcd(2,2)=2 ⇒ Q ≡ 0, all radical.
        let f4 = trace_form_arf::<Fpn<2, 2>>(1).unwrap();
        assert_eq!((f4.rank, f4.radical_dim), (0, 2));
        // F_8 (m=3), a=1: gcd(2,3)=1 ⇒ rank 2, radical 1.
        let f8 = trace_form_arf::<Fpn<2, 3>>(1).unwrap();
        assert_eq!((f8.rank, f8.radical_dim), (2, 1));
    }

    #[test]
    fn gold_form_over_nim_subfields_matches_rank_formula() {
        // The nim-native path reaches the power-of-two nim subfields
        // (F_16, F_256). arf_nimber computes rank by independent symplectic reduction
        // of the polar form — agreement with m − gcd(2a, m) is a real cross-check.
        for m in [2usize, 4, 8] {
            let a = 1usize;
            let arf = gold_form(m, a).classify().unwrap();
            let g = gcd(2 * a, m);
            assert_eq!(
                (arf.rank, arf.radical_dim),
                (m - g, g),
                "Gold form over F_2^{m} (a={a})"
            );
        }
        // a higher Gold exponent: m=8, a=3 ⇒ gcd(6,8)=2 ⇒ rank 6.
        let arf = gold_form(8, 3).classify().unwrap();
        assert_eq!((arf.rank, arf.radical_dim), (6, 2));

        // Frobenius has period m; huge public exponents must not trigger a
        // literal a-step loop.
        assert_eq!(gold_form(8, usize::MAX), gold_form(8, usize::MAX % 8));
    }

    #[test]
    fn scaled_gold_diagonal_dual_matches_the_trace_pairing() {
        // Exhaust every scale in the small canonical nim towers.  This is an
        // independent direct-coordinate oracle for the tower recursion: the
        // implementation never assembles these m diagonal equations.
        for m in [1usize, 2, 4, 8] {
            let scales = if m == 1 { 2 } else { 1u128 << m };
            for a in 0..m {
                for c in 0..scales {
                    let lambda = gold_component_diagonal_dual(m, a, c);
                    for i in 0..m {
                        let e = 1u128 << i;
                        let twisted = nim_frobenius_iter(e, a);
                        let direct = nim_trace(nim_mul(c, nim_mul(e, twisted)), m as u128);
                        let paired = nim_trace(nim_mul(lambda, e), m as u128);
                        assert_eq!(paired, direct, "m={m}, a={a}, c={c}, i={i}");
                    }
                }
            }
        }
    }

    #[test]
    fn unscaled_gold_dual_descends_and_has_artin_schreier_source() {
        for m in [2usize, 4, 8, 16, 32, 64, 128] {
            for a in [0usize, 1, 2, 3, 4, 7, m - 1, m] {
                let lambda = gold_diagonal_dual(m, a);
                assert!(
                    lambda < (1u128 << (m / 2)),
                    "unscaled dual did not descend: m={m}, a={a}, lambda={lambda}"
                );
                let w = gold_diagonal_artin_schreier_source(m, a);
                assert_eq!(nim_mul(w, w) ^ w, lambda, "m={m}, a={a}");

                for i in 0..m {
                    let e = 1u128 << i;
                    let sourced = nim_trace(nim_mul(nim_mul(w, w) ^ w, e), m as u128);
                    let gold = nim_trace(nim_mul(e, nim_frobenius_iter(e, a % m)), m as u128);
                    assert_eq!(sourced, gold, "m={m}, a={a}, i={i}");
                }
            }
        }

        // Even exponents depend on the tower level; the recursive source computes
        // the corresponding value at each level.
        assert_eq!(gold_diagonal_dual(4, 2), 0);
        assert_eq!(gold_diagonal_dual(8, 2), 6);
        assert_eq!(gold_diagonal_dual(16, 2), 102);
        assert_eq!(gold_diagonal_dual(32, 2), 24_582);
        assert_eq!(gold_diagonal_dual(16, 4), 31);
        assert_eq!(gold_diagonal_dual(32, 4), 8_030);
    }

    #[test]
    fn transfer_of_unit_form_is_the_k0_twisted_form() {
        // s_*(⟨1⟩) = Tr(x·y) is the k = 0 member of the twisted-form family.
        let s = transfer_diagonal::<Fpn<3, 2>>(&[Fpn::<3, 2>::one()]);
        let t0 = trace_twisted_form::<Fpn<3, 2>>(0);
        assert_eq!(s.q, t0.q);
        assert_eq!(s.b, t0.b);
    }

    #[test]
    fn transfer_of_a_hyperbolic_form_is_split() {
        // s_* : W(E) → W(F) is a group homomorphism, so the transfer of the
        // hyperbolic form ⟨1, −1⟩ over E is Witt-trivial over F.
        let one = Fpn::<3, 2>::one();
        let hyp = transfer_diagonal::<Fpn<3, 2>>(&[one, one.neg()]);
        let dec = hyp.witt_decompose().expect("Fp<3> Witt decomposition");
        assert_eq!(
            dec.anisotropic_dim, 0,
            "transfer of a hyperbolic form splits"
        );
    }

    #[test]
    fn restriction_preserves_orthogonal_sums_and_exposes_even_degree_kernel() {
        let left = [Fp::<3>::one(), Fp::<3>::from_int(2)];
        let right = [Fp::<3>::one()];
        let together = restrict_diagonal::<Fpn<3, 2>>(&[left[0], left[1], right[0]]);
        let separately = restrict_diagonal::<Fpn<3, 2>>(&left)
            .direct_sum(&restrict_diagonal::<Fpn<3, 2>>(&right));
        assert_eq!(
            together, separately,
            "restriction is additive on orthogonal sums"
        );

        // The anisotropic <1,1>/F_3 becomes hyperbolic over F_9: restriction is
        // not generally injective in even degree.
        let killed = restrict_diagonal::<Fpn<3, 2>>(&[Fp::<3>::one(), Fp::<3>::one()]);
        match killed.witt_decompose().expect("F_9 Witt decomposition") {
            crate::forms::FiniteFieldWittDecomp::Odd(d) => assert_eq!(d.anisotropic_dim, 0),
            other => panic!("expected odd-characteristic decomposition, got {other:?}"),
        }
    }

    #[test]
    fn frobenius_reciprocity_projection_formula() {
        // Representative-level, multi-rank form of
        // s_*(r*(x)·y) = x·s_*(y).
        let x = [Fp::<3>::one(), Fp::<3>::from_int(2)];
        let y = [
            Fpn::<3, 2>::from_coeffs(&[1, 1]),
            Fpn::<3, 2>::from_coeffs(&[2, 1]),
        ];
        let restricted = restrict_diagonal::<Fpn<3, 2>>(&x);
        let product = crate::forms::tensor_form(&restricted, &Metric::diagonal(y.to_vec()))
            .expect("both representatives are diagonal");
        let lhs = transfer_diagonal::<Fpn<3, 2>>(product.q());

        let transferred = transfer_diagonal::<Fpn<3, 2>>(&y);
        let scale = |c: Fp<3>| {
            Metric::general(
                transferred.q.iter().map(|v| c.mul(v)).collect(),
                transferred.b.iter().map(|(k, v)| (*k, c.mul(v))),
                Vec::new(),
            )
        };
        let rhs = scale(x[0]).direct_sum(&scale(x[1]));
        assert_eq!(lhs, rhs);
    }

    #[test]
    fn springer_odd_degree_restriction_is_injective() {
        // r* : W(K) → W(E) is injective for odd [E:K] (Springer's odd-degree
        // theorem). Witness: the anisotropic binary form ⟨1,1⟩/F_3 stays anisotropic
        // over F_27 (degree 3, odd) — its nonzero Witt class does not die.
        let aniso = Metric::<Fp<3>>::diagonal(vec![Fp::<3>::one(), Fp::<3>::one()]);
        let base_dec = aniso.witt_decompose().expect("Fp<3> Witt decomposition");
        assert_eq!(base_dec.anisotropic_dim, 2, "⟨1,1⟩ anisotropic over F_3");

        let restricted = restrict_diagonal::<Fpn<3, 3>>(&[Fp::<3>::one(), Fp::<3>::one()]);
        match restricted
            .witt_decompose()
            .expect("F_27 Witt decomposition")
        {
            crate::forms::FiniteFieldWittDecomp::Odd(d) => {
                assert_eq!(
                    d.anisotropic_dim, 2,
                    "still anisotropic over F_27 ⇒ injective"
                );
            }
            other => panic!("expected odd-characteristic decomposition, got {other:?}"),
        }
    }

    #[test]
    fn metric_map_lifts_fp2_to_nimber() {
        // base-change F_2 ↪ Nimber preserves the form's structure.
        let over_f2 = trace_twisted_form::<Fpn<2, 3>>(1);
        let lifted = over_f2.map(|x| Nimber(x.value()));
        assert_eq!(lifted.q.len(), over_f2.q.len());
        for (i, qi) in over_f2.q.iter().enumerate() {
            assert_eq!(lifted.q[i].0, qi.value());
        }
        assert_eq!(lifted.b.len(), over_f2.b.len());
    }
}