gam-geometry 0.3.152

Riemannian-manifold geometry (charts, exp/log maps, Fréchet means, curvature estimands) for the gam penalized-likelihood engine
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
//! Independent-oracle conformance for the κ-stereographic family.
//!
//! [`ConstantCurvature`] is deliberately **not** a [`ManifoldSpec`] variant — it
//! carries a continuous parameter rather than a fixed shape — so the shared
//! inventory in [`super::conformance_tests`] does not reach it. It needs its own
//! coverage, and it needs a different *kind* of coverage, because the thing
//! worth checking is not that a formula is self-consistent but that this one
//! chart reproduces three classical geometries it was never told about.
//!
//! The module's whole design claim is that spherical, flat, and hyperbolic
//! space are one analytic object in `u = κt²`, with κ = 0 a removable point
//! rather than a branch. Every test here is an oracle *external* to that claim:
//!
//! | oracle | what it pins |
//! |---|---|
//! | `K ≡ κ` | the curvature the family reports is the curvature it has |
//! | Möbius-translation invariance | the space really is homogeneous |
//! | `d_κ(x,y) = d_{±1}(√|κ|x, √|κ|y)/√|κ|` | the κ-family is one manifold rescaled |
//! | `κ = 0 ⇒ d = 2‖x−y‖` | the flat member is flat (in the `λ₀ = 2` gauge) |
//! | `κ = −1 ⇒ poincare_distance` | agreement with a **separate implementation** |
//! | `J_κ(r) = (sn_κ(r)/r)^{d−1}` | the volume element against its closed form |
//! | metric axioms | symmetry and the triangle inequality |
//! | `‖log_x y‖_{g_x} = d(x,y)` | the logarithm and the distance are the same geometry |
//!
//! The cross-implementation row is the strongest of these: `poincare.rs` reaches
//! hyperbolic distance by a different route, so agreement at `1e-15` is evidence
//! about the mathematics, not about a shared helper.
//!
//! ### The κ-jets are checked against the value path, not against themselves
//!
//! `distance_kappa_jet` and friends return `(f, ∂f/∂κ, ∂²f/∂κ²)` from a
//! `Tower2` program, and those derivatives enter the outer REML optimization as
//! a ψ-coordinate. A wrong `∂²/∂κ²` does not produce a wrong *answer* — it
//! produces a slower or differently-converging search, which is exactly the kind
//! of defect that survives for years. So the jets are differenced against the
//! independently written value methods (`distance`, `log_map`, `exp_map`)
//! evaluated at perturbed κ.
//!
//! Two things had to be right for that to measure anything:
//!
//! * **The test points must not depend on `h`.** The chart for `κ < 0` is a ball
//!   of radius `1/√−κ`, so the obvious "sample inside the chart of `κ − h`"
//!   makes the point cloud blow up as `h → 0`; the h-scan then measures the
//!   sampler instead of the discretization and reads as a catastrophic
//!   derivative error at exactly the κ = 0 point the family exists to handle.
//!   [`chart_point`] uses a fixed radius valid across the whole stencil.
//! * **Each derivative is scaled by its own magnitude.** `∂d/∂κ` grows like
//!   `‖w‖³` and `∂²d/∂κ²` like `‖w‖⁵`, so normalizing them by the *distance*
//!   understates a real error by orders of magnitude.
//!
//! With both fixed, the residual is second-order in `h` (measured: `1.4e-7`,
//! `1.5e-9`, `1.5e-11` at `h = 1e-2, 1e-3, 1e-4` — a clean `h²` ladder until
//! the second difference hits its `ε/h²` roundoff floor). `H = 1e-3` is the
//! bottom of that curve for the second derivative and is what the assertions
//! use.

use ndarray::{Array1, Array2};

use crate::manifold::RiemannianManifold;
use crate::manifolds::constant_curvature::{
    ConstantCurvature, distance_kappa_jet, exp_map_kappa_jet, log_map_kappa_jet,
};
use crate::manifolds::poincare;

struct Rng(u64);

impl Rng {
    fn new(seed: u64) -> Self {
        Self(seed)
    }
    fn next_u64(&mut self) -> u64 {
        let mut x = self.0;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.0 = x;
        x
    }
    fn uniform(&mut self) -> f64 {
        (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
    }
    fn normal(&mut self) -> f64 {
        let u1 = self.uniform().max(1.0e-300);
        let u2 = self.uniform();
        (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos()
    }
    fn gaussian_vec(&mut self, n: usize) -> Array1<f64> {
        Array1::from_shape_fn(n, |_| self.normal())
    }
}

/// A chart point of radius `< 0.45`.
///
/// Fixed, and in particular independent of κ and of any finite-difference step:
/// the κ < 0 chart is the ball of radius `1/√−κ`, so a radius chosen from the
/// current κ would make each stencil arm see a different point cloud. 0.45 is
/// interior for every κ ≥ −1.1, which covers every curvature used below plus
/// the widest stencil arm.
fn chart_point(rng: &mut Rng, dim: usize) -> Array1<f64> {
    let mut v = rng.gaussian_vec(dim);
    let magnitude = v.dot(&v).sqrt().max(1.0e-30);
    v *= 0.45 * rng.uniform() / magnitude;
    v
}

/// Curvatures spanning both signs, both series/closed-form regimes of the
/// `C`/`S`/`T` primitives, and the removable point itself.
const CURVATURES: [f64; 11] = [
    2.0, 1.0, 0.35, 0.01, 1.0e-6, 0.0, -1.0e-6, -0.01, -0.35, -1.0, -2.0,
];
const DIMS: [usize; 4] = [1, 2, 3, 5];
const TRIALS: usize = 200;
const SEED: u64 = 0x9E37_79B9_7F4A_7C15;

fn seed_for(dim: usize, kappa: f64) -> u64 {
    SEED ^ ((dim as u64) << 32) ^ kappa.to_bits()
}

fn sup_diff(a: &Array1<f64>, b: &Array1<f64>) -> f64 {
    a.iter()
        .zip(b.iter())
        .map(|(x, y)| (x - y).abs())
        .fold(0.0, f64::max)
}

/// Largest magnitude across two vectors, floored at 1 — the scale a residual
/// between them is relative to.
fn joint_scale(a: &Array1<f64>, b: &Array1<f64>) -> f64 {
    a.iter()
        .chain(b.iter())
        .fold(1.0_f64, |acc, v| acc.max(v.abs()))
}

#[test]
fn sectional_curvature_is_kappa_everywhere() {
    let mut verified = 0usize;
    for dim in DIMS {
        if dim < 2 {
            continue;
        }
        for kappa in CURVATURES {
            let manifold = ConstantCurvature::new(dim, kappa);
            let mut rng = Rng::new(seed_for(dim, kappa));
            for _ in 0..TRIALS {
                let x = chart_point(&mut rng, dim);
                let u = manifold
                    .project_tangent(x.view(), rng.gaussian_vec(dim).view())
                    .expect("tangent u");
                let v = manifold
                    .project_tangent(x.view(), rng.gaussian_vec(dim).view())
                    .expect("tangent v");
                let Ok(k) = manifold.sectional_curvature(x.view(), (u.view(), v.view())) else {
                    continue;
                };
                assert!(
                    (k - kappa).abs() <= 1.0e-9 * kappa.abs().max(1.0),
                    "dim {dim} kappa {kappa}: sectional curvature is {k}, not kappa"
                );
                verified += 1;
            }
        }
    }
    assert!(verified > 0, "no sectional curvature was evaluated");
}

#[test]
fn distance_is_invariant_under_mobius_translation() {
    // M_κ is homogeneous: Möbius addition by a fixed g is an isometry. This is
    // the property whose failure was #2351 — a κ̂ verdict that moved when the
    // data was translated.
    let mut verified = 0usize;
    for dim in DIMS {
        for kappa in CURVATURES {
            let manifold = ConstantCurvature::new(dim, kappa);
            let mut rng = Rng::new(seed_for(dim, kappa));
            for _ in 0..TRIALS {
                let x = chart_point(&mut rng, dim);
                let y = chart_point(&mut rng, dim);
                let g = chart_point(&mut rng, dim);
                let base = manifold.distance(x.view(), y.view()).expect("d(x,y)");
                let (Ok(gx), Ok(gy)) = (
                    manifold.mobius_add(g.view(), x.view()),
                    manifold.mobius_add(g.view(), y.view()),
                ) else {
                    continue;
                };
                let Ok(moved) = manifold.distance(gx.view(), gy.view()) else {
                    continue;
                };
                assert!(
                    (moved - base).abs() <= 1.0e-9 * base.max(1.0),
                    "dim {dim} kappa {kappa}: translation changed the distance \
                     ({base} -> {moved})"
                );
                verified += 1;
            }
        }
    }
    assert!(verified > 0, "no translated distance was evaluated");
}

#[test]
fn the_kappa_family_is_one_manifold_rescaled() {
    // A space form of curvature κ is the unit-curvature form of the same sign
    // scaled by 1/√|κ|, so d_κ(x, y) = d_{sign κ}(√|κ|·x, √|κ|·y) / √|κ|. This
    // ties every κ to the two reference geometries with no free parameter.
    let mut verified = 0usize;
    for dim in DIMS {
        for kappa in CURVATURES {
            if kappa.abs() <= 1.0e-9 {
                continue;
            }
            let manifold = ConstantCurvature::new(dim, kappa);
            let unit = ConstantCurvature::new(dim, kappa.signum());
            let scale = kappa.abs().sqrt();
            let mut rng = Rng::new(seed_for(dim, kappa));
            for _ in 0..TRIALS {
                let x = chart_point(&mut rng, dim);
                let y = chart_point(&mut rng, dim);
                let here = manifold.distance(x.view(), y.view()).expect("d_kappa");
                let Ok(there) = unit.distance((&x * scale).view(), (&y * scale).view()) else {
                    continue;
                };
                assert!(
                    (here - there / scale).abs() <= 1.0e-9 * here.max(1.0),
                    "dim {dim} kappa {kappa}: d_kappa = {here} but the rescaled unit \
                     form gives {}",
                    there / scale
                );
                verified += 1;
            }
        }
    }
    assert!(verified > 0, "no rescaling was evaluated");
}

#[test]
fn the_flat_and_hyperbolic_members_match_their_classical_forms() {
    // Two external anchors:
    //   κ = 0  — the conformal gauge is λ₀ = 2, so the flat metric is 4δ and
    //            the distance is 2‖x − y‖ (Euclidean up to the isometry x ↦ 2x,
    //            exactly as the module documents).
    //   κ = −1 — must agree with `poincare.rs`, which computes hyperbolic
    //            distance by an independent route. This is the only assertion
    //            in the file that compares two implementations rather than an
    //            implementation to a formula, and so is the strongest.
    let mut flat_checked = 0usize;
    let mut hyperbolic_checked = 0usize;
    for dim in DIMS {
        let flat = ConstantCurvature::new(dim, 0.0);
        let hyperbolic = ConstantCurvature::new(dim, -1.0);
        let mut rng = Rng::new(seed_for(dim, 0.0));
        for _ in 0..TRIALS {
            let x = chart_point(&mut rng, dim);
            let y = chart_point(&mut rng, dim);

            let got = flat.distance(x.view(), y.view()).expect("flat distance");
            let want = 2.0 * (&x - &y).dot(&(&x - &y)).sqrt();
            assert!(
                (got - want).abs() <= 1.0e-12 * want.max(1.0),
                "dim {dim}: flat distance {got} != 2||x-y|| = {want}"
            );
            flat_checked += 1;

            let got = hyperbolic
                .distance(x.view(), y.view())
                .expect("hyperbolic distance");
            let want =
                poincare::poincare_distance(x.view(), y.view(), -1.0).expect("poincare distance");
            assert!(
                (got - want).abs() <= 1.0e-12 * want.max(1.0),
                "dim {dim}: kappa=-1 distance {got} disagrees with poincare.rs {want}"
            );
            hyperbolic_checked += 1;
        }
    }
    assert!(flat_checked > 0 && hyperbolic_checked > 0);
}

#[test]
fn distance_is_a_metric_and_agrees_with_the_logarithm() {
    let mut verified = 0usize;
    for dim in DIMS {
        for kappa in CURVATURES {
            let manifold = ConstantCurvature::new(dim, kappa);
            let mut rng = Rng::new(seed_for(dim, kappa));
            for _ in 0..TRIALS {
                let x = chart_point(&mut rng, dim);
                let y = chart_point(&mut rng, dim);
                let z = chart_point(&mut rng, dim);
                let dxy = manifold.distance(x.view(), y.view()).expect("d(x,y)");
                let dyx = manifold.distance(y.view(), x.view()).expect("d(y,x)");
                let dyz = manifold.distance(y.view(), z.view()).expect("d(y,z)");
                let dxz = manifold.distance(x.view(), z.view()).expect("d(x,z)");

                assert!(
                    (dxy - dyx).abs() <= 1.0e-12 * dxy.max(1.0),
                    "dim {dim} kappa {kappa}: distance is not symmetric ({dxy} vs {dyx})"
                );
                assert!(
                    dxz <= dxy + dyz + 1.0e-12 * dxz.max(1.0),
                    "dim {dim} kappa {kappa}: triangle inequality violated \
                     ({dxz} > {dxy} + {dyz})"
                );

                // ‖log_x y‖ in the metric at x is the geodesic distance. The
                // metric is conformal, so the norm is λ_x·‖·‖.
                let logarithm = manifold.log_map(x.view(), y.view()).expect("log");
                let lambda = manifold
                    .conformal_factor(x.view())
                    .expect("conformal factor");
                let metric_norm = lambda * logarithm.dot(&logarithm).sqrt();
                assert!(
                    (metric_norm - dxy).abs() <= 1.0e-9 * dxy.max(1.0),
                    "dim {dim} kappa {kappa}: ||log|| = {metric_norm} != d = {dxy}"
                );
                verified += 1;
            }
        }
    }
    assert!(verified > 0, "no metric axiom was evaluated");
}

#[test]
fn radial_volume_jacobian_matches_its_closed_form() {
    // J_κ(r) = (sn_κ(r)/r)^{d−1}, with sn_κ the curvature-normalized sine. This
    // is the volume term in the change-of-variables criterion, so an error here
    // biases the curvature estimate itself rather than merely slowing it.
    let mut verified = 0usize;
    for dim in DIMS {
        for kappa in CURVATURES {
            let manifold = ConstantCurvature::new(dim, kappa);
            let mut rng = Rng::new(seed_for(dim, kappa));
            for _ in 0..TRIALS {
                let r = 2.0 * rng.uniform();
                let got = manifold.jacobian_radial(r);
                let want = if dim <= 1 {
                    1.0
                } else {
                    let sn_over_r = if kappa.abs() <= 1.0e-12 || r == 0.0 {
                        1.0
                    } else if kappa > 0.0 {
                        let arc = kappa.sqrt() * r;
                        (arc.sin() / arc).max(0.0)
                    } else {
                        let arc = (-kappa).sqrt() * r;
                        arc.sinh() / arc
                    };
                    sn_over_r.powi((dim - 1) as i32)
                };
                assert!(
                    (got - want).abs() <= 1.0e-9 * want.abs().max(1.0e-12),
                    "dim {dim} kappa {kappa} r {r}: J = {got}, closed form {want}"
                );
                verified += 1;
            }
        }
    }
    assert!(verified > 0, "no volume Jacobian was evaluated");
}

#[test]
fn batched_distance_is_bit_identical_to_the_scalar_path() {
    // `distance_batch` documents bit-for-bit agreement with `distance`, which is
    // a stronger claim than "close": the SIMD `T`-series must reproduce the
    // scalar value per lane exactly, and the tail and closed-form lanes must
    // fall back rather than approximate. Asserting equality (not a tolerance) is
    // the only way to test the claim that is actually made.
    let mut verified = 0usize;
    for dim in DIMS {
        for kappa in CURVATURES {
            let manifold = ConstantCurvature::new(dim, kappa);
            let mut rng = Rng::new(seed_for(dim, kappa));
            // Row counts either side of the f64x4 lane width, so the vectorised
            // body and the scalar tail are both exercised.
            for rows in [1usize, 3, 4, 5, 8, 11] {
                let base = chart_point(&mut rng, dim);
                let mut targets = Array2::<f64>::zeros((rows, dim));
                for r in 0..rows {
                    targets.row_mut(r).assign(&chart_point(&mut rng, dim));
                }
                let mut batched = vec![0.0_f64; rows];
                manifold
                    .distance_batch(base.view(), targets.view(), &mut batched)
                    .expect("distance_batch");
                for r in 0..rows {
                    let scalar = manifold
                        .distance(base.view(), targets.row(r))
                        .expect("scalar distance");
                    assert_eq!(
                        batched[r].to_bits(),
                        scalar.to_bits(),
                        "dim {dim} kappa {kappa} rows {rows} row {r}: \
                         batched {} != scalar {scalar}",
                        batched[r]
                    );
                    verified += 1;
                }
            }
        }
    }
    assert!(verified > 0, "no batched distance was evaluated");
}

/// Relative tolerance for a jet component, plus an absolute floor set by what
/// the finite-difference instrument can actually resolve.
///
/// The absolute term is the point of this function. These derivatives are
/// *small*: `∂d/∂κ` spans `1e-7 … 0.17` over the fixtures below and `∂²d/∂κ²`
/// reaches down to `6e-12` for near-coincident points, while the FD residual
/// against a correct analytic derivative sits at `1e-9 … 2e-8` regardless.
/// Below that floor the difference quotient carries no information, so no
/// tolerance can be honest about the small cases — but the floor must be set
/// from the *measured* noise and not, as this test first did, from a `max(…,
/// 1.0)` guard. That guard made the bound `1e-6` absolute everywhere, which is
/// fifty times looser than the instrument: a mutation perturbing `∂²d/∂κ²` by
/// `1e-5` relative passed it. With the floor at the measured noise (5–10× over
/// the worst residual observed across all 15 dim × κ fixtures) the same
/// mutation fails, which is the property that makes this test worth running.
fn jet_tolerance(analytic: f64, difference: f64, floor: f64) -> f64 {
    1.0e-6 * analytic.abs().max(difference.abs()) + floor
}

/// Noise floor of the central first difference: worst residual measured 4.4e-9.
const FIRST_FLOOR: f64 = 5.0e-8;
/// Noise floor of the central second difference, which amplifies roundoff by
/// `1/H²`: worst residual measured 1.9e-8.
const SECOND_FLOOR: f64 = 1.0e-7;

/// Largest componentwise gap between two vectors, against the same bound.
fn assert_vector_close(
    analytic: &Array1<f64>,
    difference: &Array1<f64>,
    floor: f64,
    context: &str,
) {
    for (i, (a, d)) in analytic.iter().zip(difference.iter()).enumerate() {
        assert!(
            (a - d).abs() <= jet_tolerance(*a, *d, floor),
            "{context}: component {i} analytic {a} vs finite difference {d}"
        );
    }
}

#[test]
fn kappa_jets_match_central_differences_of_the_value_path() {
    // See the module docs for why H is 1e-3 and why the sample radius must not
    // depend on it. The jets are compared against `distance` / `log_map` /
    // `exp_map` — separately written value code — at κ ± H, so agreement is
    // evidence about the Tower2 program rather than about itself.
    const H: f64 = 1.0e-3;
    let mut verified = 0usize;
    for dim in [1usize, 2, 3] {
        for kappa in [1.0_f64, 0.3, 0.0, -0.3, -1.0] {
            let manifold = ConstantCurvature::new(dim, kappa);
            let up = ConstantCurvature::new(dim, kappa + H);
            let down = ConstantCurvature::new(dim, kappa - H);
            let mut rng = Rng::new(seed_for(dim, kappa));
            for _ in 0..TRIALS {
                let x = chart_point(&mut rng, dim);
                let y = chart_point(&mut rng, dim);

                // ---- distance ----
                let (value, first, second) =
                    distance_kappa_jet(&manifold, x.view(), y.view()).expect("distance jet");
                let here = manifold.distance(x.view(), y.view()).expect("d");
                let above = up.distance(x.view(), y.view()).expect("d+");
                let below = down.distance(x.view(), y.view()).expect("d-");
                assert!(
                    (value - here).abs() <= 1.0e-12 * here.max(1.0),
                    "dim {dim} kappa {kappa}: jet value {value} != distance {here}"
                );
                let fd_first = (above - below) / (2.0 * H);
                let fd_second = (above - 2.0 * here + below) / (H * H);
                assert!(
                    (first - fd_first).abs() <= jet_tolerance(first, fd_first, FIRST_FLOOR),
                    "dim {dim} kappa {kappa}: d/dkappa distance {first} vs FD {fd_first}"
                );
                assert!(
                    (second - fd_second).abs() <= jet_tolerance(second, fd_second, SECOND_FLOOR),
                    "dim {dim} kappa {kappa}: d2/dkappa2 distance {second} vs FD {fd_second}"
                );

                // ---- logarithm ----
                let (value, first, second) =
                    log_map_kappa_jet(&manifold, x.view(), y.view()).expect("log jet");
                let here = manifold.log_map(x.view(), y.view()).expect("log");
                let above = up.log_map(x.view(), y.view()).expect("log+");
                let below = down.log_map(x.view(), y.view()).expect("log-");
                assert!(
                    sup_diff(&value, &here) <= 1.0e-12 * joint_scale(&value, &here),
                    "dim {dim} kappa {kappa}: log jet value disagrees with log_map"
                );
                let fd_first = (&above - &below) / (2.0 * H);
                let fd_second = (&above - &(&here * 2.0) + &below) / (H * H);
                assert_vector_close(
                    &first,
                    &fd_first,
                    FIRST_FLOOR,
                    &format!("dim {dim} kappa {kappa}: d/dkappa log"),
                );
                assert_vector_close(
                    &second,
                    &fd_second,
                    SECOND_FLOOR,
                    &format!("dim {dim} kappa {kappa}: d2/dkappa2 log"),
                );

                // ---- exponential ----
                let tangent = manifold
                    .project_tangent(x.view(), (rng.gaussian_vec(dim) * 0.2).view())
                    .expect("tangent");
                let (value, first, second) =
                    exp_map_kappa_jet(&manifold, x.view(), tangent.view()).expect("exp jet");
                let here = manifold.exp_map(x.view(), tangent.view()).expect("exp");
                let above = up.exp_map(x.view(), tangent.view()).expect("exp+");
                let below = down.exp_map(x.view(), tangent.view()).expect("exp-");
                assert!(
                    sup_diff(&value, &here) <= 1.0e-12 * joint_scale(&value, &here),
                    "dim {dim} kappa {kappa}: exp jet value disagrees with exp_map"
                );
                let fd_first = (&above - &below) / (2.0 * H);
                let fd_second = (&above - &(&here * 2.0) + &below) / (H * H);
                assert_vector_close(
                    &first,
                    &fd_first,
                    FIRST_FLOOR,
                    &format!("dim {dim} kappa {kappa}: d/dkappa exp"),
                );
                assert_vector_close(
                    &second,
                    &fd_second,
                    SECOND_FLOOR,
                    &format!("dim {dim} kappa {kappa}: d2/dkappa2 exp"),
                );

                verified += 1;
            }
        }
    }
    assert!(verified > 0, "no kappa jet was differenced");
}

/// #2687: the κ > 0 branch is **not** unconstrained, and its singular locus sits
/// at the same `|κ| = 1/R²` as the hyperbolic one.
///
/// The per-point chart gauge `1 + κ‖x‖²` really is vacuous for `κ ≥ 0` — but it
/// is not the condition the kernel evaluates. Every distance goes through
/// `w = (−x) ⊕_κ y`, whose Möbius denominator is
///
/// ```text
///   D(κ) = 1 + 2κ⟨x,y⟩ + κ²‖x‖²‖y‖²
/// ```
///
/// For an anti-aligned pair (`⟨x,y⟩ = −‖x‖‖y‖`) that is `(1 − κ‖x‖‖y‖)²`, which
/// vanishes at `κ = +1/(‖x‖‖y‖)`. There the two points are exactly ANTIPODAL on
/// the sphere of radius `1/√κ` and the chart coordinate `w` passes through
/// infinity — the exact spherical mirror of `1 + κ‖x‖² = 0` on the hyperbolic
/// side. Worst case over a cloud of maximum chart radius `R` is `κ = +1/R²`, so
/// a κ window symmetric about zero at a fraction of `1/R²` is a genuine margin
/// on BOTH sides rather than one branch's constraint mirrored onto the other.
///
/// Past the fold the chart is not merely inaccurate, it is **folded**: the
/// normalized separation `d_κ(x,y)·√κ/π` (the pair's fraction of the antipodal
/// maximum, the only scale-free thing κ can be read off) is exactly invariant
/// under the involution `κ ↦ 1/(κ‖x‖²‖y‖²)`, so every κ past the fold is an
/// exact reflection of one before it.
///
/// Every number below was pinned from `d = (2/√κ)·arctan(√κ‖w‖)`,
/// `‖w‖ = 2R/(1 − κR²)` BEFORE this test was first run.
#[test]
fn spherical_branch_folds_at_kappa_r2_one_so_the_kappa_window_is_symmetric_2687() {
    const R: f64 = 0.6;
    let r2 = R * R;
    let x = ndarray::array![R, 0.0];
    let y = ndarray::array![-R, 0.0];

    // (a) The shipped window's cap, κ = CONSTANT_CURVATURE_KAPPA_CHART_FRACTION/R²
    // with the fraction 0.5. Interior, and 78.4% of the way to the antipode.
    let cap = 0.5 / r2;
    let manifold = ConstantCurvature::new(2, cap);
    let d_cap = manifold
        .distance(x.view(), y.view())
        .expect("the shipped κ cap must be strictly inside the chart");
    assert!(
        (d_cap - 2.089_007_403_281_048).abs() <= 1.0e-12,
        "κ = 0.5/R²: d = {d_cap}, predicted 2.089007403281048"
    );
    let frac_cap = d_cap * cap.sqrt() / std::f64::consts::PI;
    assert!(
        (frac_cap - 0.783_653_104_061_214_8).abs() <= 1.0e-12,
        "κ = 0.5/R²: antipodal fraction = {frac_cap}, predicted 0.7836531040612148"
    );

    // (b) κ = 1/R² is the fold itself: D = (1 − κR²)² collapses and the shipped
    // guard refuses. This is the number the ±0.5 fraction is half of.
    let fold = 1.0 / r2;
    let refused = ConstantCurvature::new(2, fold).distance(x.view(), y.view());
    assert!(
        refused.is_err(),
        "κ = 1/R² = {fold} is the κ>0 antipodal fold and must be refused; got {refused:?}"
    );

    // (c) The same fold with an exactly representable denominator, so the
    // refusal cannot be an artifact of a near-miss: κ‖x‖‖y‖ = 4·0.25 = 1 in f64.
    let exact = ConstantCurvature::new(2, 4.0);
    let exact_refused = exact.distance(
        ndarray::array![0.5, 0.0].view(),
        ndarray::array![-0.5, 0.0].view(),
    );
    assert!(
        exact_refused.is_err(),
        "κ‖x‖‖y‖ = 1 exactly must be refused; got {exact_refused:?}"
    );

    // (d) The involution. `κ_wide = 9.5/R²` is the widening proposed on #2687;
    // it is the EXACT reflection of `κ_twin = (1/9.5)/R²`, which is interior to
    // the shipped window. Widening the box to 9.5/R² would therefore admit an
    // exact duplicate of a κ the box already contains.
    let kappa_wide = 9.5 / r2;
    let kappa_twin = (1.0 / 9.5) / r2;
    let d_wide = ConstantCurvature::new(2, kappa_wide)
        .distance(x.view(), y.view())
        .expect("past the fold the chart still evaluates — that is the problem");
    let d_twin = ConstantCurvature::new(2, kappa_twin)
        .distance(x.view(), y.view())
        .expect("the twin is interior");
    let frac_wide = d_wide * kappa_wide.sqrt() / std::f64::consts::PI;
    let frac_twin = d_twin * kappa_twin.sqrt() / std::f64::consts::PI;
    assert!(
        (frac_wide - 0.399_450_751_329_086_6).abs() <= 1.0e-12,
        "κ = 9.5/R²: antipodal fraction = {frac_wide}, predicted 0.3994507513290866"
    );
    assert!(
        (frac_wide - frac_twin).abs() <= 1.0e-14,
        "κ = 9.5/R² and κ = (1/9.5)/R² must be indistinguishable in the pair's \
         scale-free geometry: {frac_wide} vs {frac_twin}"
    );
    assert!(
        kappa_twin < cap && cap < fold && fold < kappa_wide,
        "the ordering this test is about: twin {kappa_twin} < cap {cap} < fold \
         {fold} < proposed {kappa_wide}"
    );

    // (e) The involution is not special to the anti-aligned pair — it is a
    // property of the chart. Over general pairs the reflected κ reproduces the
    // scale-free separation to machine precision.
    let mut rng = Rng::new(0x2687);
    let mut verified = 0usize;
    for _ in 0..64 {
        let p = chart_point(&mut rng, 2);
        let q = chart_point(&mut rng, 2);
        let ab2 = p.dot(&p) * q.dot(&q);
        for s in [0.25_f64, 0.75, 3.0] {
            let k_lo = s / ab2.sqrt();
            let k_hi = 1.0 / (k_lo * ab2);
            let (Ok(d_lo), Ok(d_hi)) = (
                ConstantCurvature::new(2, k_lo).distance(p.view(), q.view()),
                ConstantCurvature::new(2, k_hi).distance(p.view(), q.view()),
            ) else {
                continue;
            };
            let f_lo = d_lo * k_lo.sqrt() / std::f64::consts::PI;
            let f_hi = d_hi * k_hi.sqrt() / std::f64::consts::PI;
            assert!(
                (f_lo - f_hi).abs() <= 1.0e-12,
                "κ ↦ 1/(κ‖x‖²‖y‖²) must fix the scale-free separation: \
                 κ={k_lo} gives {f_lo}, κ={k_hi} gives {f_hi}"
            );
            verified += 1;
        }
    }
    assert!(verified > 0, "no reflected pair was evaluated");
}