Skip to main content

gam_geometry/
response_geometry.rs

1//! User-selectable response geometries beyond Sphere and Simplex.
2//!
3//! The fit DSL exposes `response_geometry="..."`: one scalar Gaussian GAM is
4//! fitted per tangent coordinate at a fixed base point (the intrinsic Fréchet
5//! mean when none is supplied), and predictions are mapped back to the manifold
6//! by the exponential map. Sphere and Simplex have bespoke batched wrappers in
7//! their own modules; this module supplies the same `(values 2-D, base 1-D) →
8//! tangent 2-D` / `(tangent 2-D, base 1-D) → values 2-D` contract for the
9//! curved matrix manifolds whose per-point math is already wired in
10//! [`crate::geometry`] but which were never reachable as a *fittable* response
11//! geometry: the SPD cone `Sym⁺(n)`, the Grassmannian `Gr(k, n)`, the Stiefel
12//! manifold `St(k, n)`, and the Poincaré ball `B^d_κ`.
13//!
14//! Every primitive here delegates to the canonical landed math
15//! ([`RiemannianManifold::exp_map`]/[`log_map`](RiemannianManifold::log_map) and
16//! the Poincaré [`exp_map`](crate::manifolds::poincare::exp_map)/[`log_map`](crate::manifolds::poincare::log_map));
17//! the only new code is the batched row loop, the base-point dimension wiring,
18//! and a generic Riemannian Karcher (Fréchet) mean shared by all four. There is
19//! no separate per-manifold mean: the SPD safeguarded Karcher iteration is
20//! generalised once, over the metric supplied by
21//! [`RiemannianManifold::metric_tensor`], so adding a curved response geometry
22//! is a single resolver arm.
23
24use ndarray::{Array1, Array2, ArrayView1, ArrayView2};
25
26use crate::manifolds::constant_curvature::ConstantCurvature;
27use crate::manifold::{
28    GEOMETRY_EPS, RiemannianManifold, flatten, from_flat, jacobi_symmetric, spectral_map_symmetric,
29    sym,
30};
31use crate::{
32    GeometryError, GeometryResult, GrassmannManifold, SpdManifold, StiefelManifold,
33};
34
35/// Split a parenthesised `key=value, key=value` parameter list into trimmed,
36/// lower-cased `(key, value)` pairs. An empty list is valid (`spd()`).
37fn parse_kv(inner: &str) -> Result<Vec<(String, String)>, String> {
38    let trimmed = inner.trim();
39    if trimmed.is_empty() {
40        return Ok(Vec::new());
41    }
42    let mut out = Vec::new();
43    for piece in trimmed.split(',') {
44        let piece = piece.trim();
45        if piece.is_empty() {
46            continue;
47        }
48        let (k, v) = piece
49            .split_once('=')
50            .ok_or_else(|| format!("response_geometry parameter {piece:?} must be key=value"))?;
51        out.push((k.trim().to_ascii_lowercase(), v.trim().to_string()));
52    }
53    Ok(out)
54}
55
56/// A fittable curved response geometry. Each variant carries the shape the user
57/// requested; the embedding/ambient flat dimension is fixed by that shape and
58/// is the column count of the `values` matrix the caller supplies.
59#[derive(Debug, Clone, Copy, PartialEq)]
60pub enum ResponseManifold {
61    /// Symmetric positive-definite `n×n` matrices, flattened row-major to `n²`
62    /// ambient coordinates (the layout [`SpdManifold`] uses).
63    Spd { n: usize },
64    /// `k`-dimensional subspaces of `ℝⁿ`, represented by an orthonormal `n×k`
65    /// frame flattened to `n·k` ambient coordinates.
66    Grassmann { k: usize, n: usize },
67    /// Orthonormal `k`-frames in `ℝⁿ`, flattened to `n·k` ambient coordinates.
68    Stiefel { k: usize, n: usize },
69    /// The Poincaré ball of dimension `d` with curvature `κ < 0`.
70    Poincare { dim: usize, curvature: f64 },
71    /// Constant-curvature manifold `M_κ` of dimension `d` with curvature `κ`
72    /// (any finite real value). `κ > 0` → spherical, `κ = 0` → flat (Euclidean
73    /// up to scale), `κ < 0` → hyperbolic (Poincaré ball). Unlike `Poincare`,
74    /// which fixes `κ < 0`, this variant accepts any curvature including zero
75    /// and positive values, and is the target for curvature-as-estimand fits
76    /// where `κ̂` is optimized over all of ℝ (#1104).
77    ConstantCurvature { dim: usize, kappa: f64 },
78}
79
80impl ResponseManifold {
81    /// Resolve a lower-cased geometry label and its shape parameters into a
82    /// response manifold. Shape parameters are passed positionally exactly as
83    /// the FFI marshals them; absent/zero values are rejected here so the error
84    /// surfaces at selection time rather than mid-fit.
85    ///
86    /// - `"spd"` needs `n` (matrix side).
87    /// - `"grassmann"` / `"stiefel"` need `k` and `n` with `1 ≤ k ≤ n`.
88    /// - `"poincare"` needs `dim` and a strictly negative `curvature`.
89    pub fn resolve(
90        kind: &str,
91        n: Option<usize>,
92        k: Option<usize>,
93        dim: Option<usize>,
94        curvature: Option<f64>,
95    ) -> Result<Self, String> {
96        match kind {
97            "spd" => {
98                let n = n.ok_or_else(|| "response_geometry='spd' requires n".to_string())?;
99                if n == 0 {
100                    return Err("response_geometry='spd' requires n >= 1".to_string());
101                }
102                Ok(Self::Spd { n })
103            }
104            "grassmann" => {
105                let k = k.ok_or_else(|| "response_geometry='grassmann' requires k".to_string())?;
106                let n = n.ok_or_else(|| "response_geometry='grassmann' requires n".to_string())?;
107                if k == 0 || n == 0 || k > n {
108                    return Err("response_geometry='grassmann' requires 1 <= k <= n".to_string());
109                }
110                Ok(Self::Grassmann { k, n })
111            }
112            "stiefel" => {
113                let k = k.ok_or_else(|| "response_geometry='stiefel' requires k".to_string())?;
114                let n = n.ok_or_else(|| "response_geometry='stiefel' requires n".to_string())?;
115                if k == 0 || n == 0 || k > n {
116                    return Err("response_geometry='stiefel' requires 1 <= k <= n".to_string());
117                }
118                Ok(Self::Stiefel { k, n })
119            }
120            "poincare" => {
121                let dim =
122                    dim.ok_or_else(|| "response_geometry='poincare' requires dim".to_string())?;
123                if dim == 0 {
124                    return Err("response_geometry='poincare' requires dim >= 1".to_string());
125                }
126                let curvature = curvature
127                    .ok_or_else(|| "response_geometry='poincare' requires curvature".to_string())?;
128                if !(curvature.is_finite() && curvature < 0.0) {
129                    return Err(
130                        "response_geometry='poincare' requires finite curvature < 0".to_string()
131                    );
132                }
133                Ok(Self::Poincare { dim, curvature })
134            }
135            "constant_curvature" => {
136                let dim = dim.ok_or_else(|| {
137                    "response_geometry='constant_curvature' requires dim".to_string()
138                })?;
139                if dim == 0 {
140                    return Err(
141                        "response_geometry='constant_curvature' requires dim >= 1".to_string()
142                    );
143                }
144                // curvature defaults to 0 (flat) when not supplied — the user can
145                // supply any finite value; the κ-estimand outer loop will optimize it.
146                let kappa = curvature.unwrap_or(0.0);
147                if !kappa.is_finite() {
148                    return Err(
149                        "response_geometry='constant_curvature' requires finite curvature"
150                            .to_string(),
151                    );
152                }
153                Ok(Self::ConstantCurvature { dim, kappa })
154            }
155            other => Err(format!(
156                "response_geometry must be one of 'spd', 'grassmann', 'stiefel', 'poincare', \
157                 'constant_curvature', 'spherical', or 'simplex'; got {other:?}"
158            )),
159        }
160    }
161
162    /// Parse a user-facing `response_geometry` label, magic-by-default: the head
163    /// is the geometry name, an optional parenthesised `key=value` list carries
164    /// shape parameters, and anything not given is inferred from the ambient
165    /// column count `cols` of the response matrix.
166    ///
167    /// Recognised forms (case-insensitive, whitespace tolerant):
168    /// - `"spd"` — `n = √cols` (must be a perfect square).
169    /// - `"grassmann(k=2)"` or `"grassmann(k=2,n=5)"` — `n` defaults to
170    ///   `cols / k`; `k` is required (it cannot be inferred from `n·k`).
171    /// - `"stiefel(k=2)"` / `"stiefel(k=2,n=5)"` — same inference as Grassmann.
172    /// - `"poincare"` or `"poincare(curvature=-0.5)"` — `dim = cols`; curvature
173    ///   defaults to `-1.0`.
174    ///
175    /// This is the single mapping from the formula-DSL string to a constructed
176    /// response manifold; the FFI passes the raw label straight through.
177    pub fn parse(label: &str, cols: usize) -> Result<Self, String> {
178        let lowered = label.trim().to_ascii_lowercase();
179        let (head, params) = match lowered.split_once('(') {
180            Some((h, rest)) => {
181                let rest = rest.trim_end();
182                let inner = rest
183                    .strip_suffix(')')
184                    .ok_or_else(|| format!("response_geometry {label:?}: missing closing ')'"))?;
185                (h.trim().to_string(), parse_kv(inner)?)
186            }
187            None => (lowered.clone(), Vec::new()),
188        };
189        let get_usize = |key: &str| -> Result<Option<usize>, String> {
190            for (k, v) in &params {
191                if k == key {
192                    let parsed: usize = v.parse().map_err(|_| {
193                        format!("response_geometry {label:?}: {key} must be a non-negative integer")
194                    })?;
195                    return Ok(Some(parsed));
196                }
197            }
198            Ok(None)
199        };
200        let get_f64 = |key: &str| -> Result<Option<f64>, String> {
201            for (k, v) in &params {
202                if k == key {
203                    let parsed: f64 = v.parse().map_err(|_| {
204                        format!("response_geometry {label:?}: {key} must be a real number")
205                    })?;
206                    return Ok(Some(parsed));
207                }
208            }
209            Ok(None)
210        };
211
212        match head.as_str() {
213            "spd" => {
214                let n = match get_usize("n")? {
215                    Some(n) => n,
216                    None => {
217                        let r = (cols as f64).sqrt().round() as usize;
218                        if r * r != cols {
219                            return Err(format!(
220                                "response_geometry='spd': {cols} response columns is not a perfect \
221                                 square; pass spd(n=...) explicitly"
222                            ));
223                        }
224                        r
225                    }
226                };
227                Self::resolve("spd", Some(n), None, None, None)
228            }
229            "grassmann" | "stiefel" => {
230                let k = get_usize("k")?.ok_or_else(|| {
231                    format!("response_geometry='{head}' requires k, e.g. {head}(k=2)")
232                })?;
233                let n = match get_usize("n")? {
234                    Some(n) => n,
235                    None => {
236                        if k == 0 || cols % k != 0 {
237                            return Err(format!(
238                                "response_geometry='{head}': {cols} response columns is not \
239                                 divisible by k={k}; pass {head}(k=..,n=..) explicitly"
240                            ));
241                        }
242                        cols / k
243                    }
244                };
245                Self::resolve(&head, Some(n), Some(k), None, None)
246            }
247            "poincare" => {
248                let dim = get_usize("dim")?.unwrap_or(cols);
249                let curvature = get_f64("curvature")?.unwrap_or(-1.0);
250                Self::resolve("poincare", None, None, Some(dim), Some(curvature))
251            }
252            "constant_curvature" => {
253                let dim = get_usize("dim")?.unwrap_or(cols);
254                // κ defaults to 0 (flat initial point for the REML optimizer).
255                let kappa = get_f64("kappa")?
256                    .or_else(|| get_f64("curvature").ok().flatten())
257                    .unwrap_or(0.0);
258                Self::resolve("constant_curvature", None, None, Some(dim), Some(kappa))
259            }
260            other => Err(format!(
261                "response_geometry must be one of 'spd', 'grassmann(k=..)', 'stiefel(k=..)', \
262                 'poincare', 'constant_curvature', 'spherical', or 'simplex'; got {other:?}"
263            )),
264        }
265    }
266
267    /// Canonical, fully-specified label echoed back to the caller (mirrors the
268    /// way the sphere/simplex dispatch reports its resolved coordinate label).
269    pub fn canonical_label(&self) -> String {
270        match self {
271            Self::Spd { n } => format!("spd(n={n})"),
272            Self::Grassmann { k, n } => format!("grassmann(k={k},n={n})"),
273            Self::Stiefel { k, n } => format!("stiefel(k={k},n={n})"),
274            Self::Poincare { dim, curvature } => {
275                format!("poincare(dim={dim},curvature={curvature})")
276            }
277            Self::ConstantCurvature { dim, kappa } => {
278                format!("constant_curvature(dim={dim},kappa={kappa})")
279            }
280        }
281    }
282
283    /// Ambient (flattened) coordinate count: the column width of the `values`
284    /// matrix and the `base` vector.
285    pub fn ambient_dim(&self) -> usize {
286        match self {
287            Self::Spd { n } => n * n,
288            Self::Grassmann { k, n } | Self::Stiefel { k, n } => n * k,
289            Self::Poincare { dim, .. } | Self::ConstantCurvature { dim, .. } => *dim,
290        }
291    }
292
293    /// Build the underlying [`RiemannianManifold`] for the matrix geometries.
294    /// `None` for Poincaré, whose primitives are free functions parameterised
295    /// by curvature rather than a trait object.
296    fn riemannian(&self) -> Option<Box<dyn RiemannianManifold>> {
297        match self {
298            Self::Spd { n } => Some(Box::new(SpdManifold::new(*n))),
299            Self::Grassmann { k, n } => GrassmannManifold::new(*k, *n)
300                .ok()
301                .map(|m| Box::new(m) as _),
302            Self::Stiefel { k, n } => StiefelManifold::new(*k, *n).ok().map(|m| Box::new(m) as _),
303            Self::ConstantCurvature { dim, kappa } => {
304                Some(Box::new(ConstantCurvature::new(*dim, *kappa)))
305            }
306            Self::Poincare { .. } => None,
307        }
308    }
309
310    /// Per-point logarithm `log_base(value)` in flat ambient coordinates.
311    fn log_point(
312        &self,
313        base: ArrayView1<'_, f64>,
314        value: ArrayView1<'_, f64>,
315    ) -> GeometryResult<Array1<f64>> {
316        match self {
317            Self::Poincare { curvature, .. } => {
318                crate::manifolds::poincare::log_map(base, value, *curvature)
319            }
320            // ConstantCurvature implements RiemannianManifold::log_map directly.
321            Self::ConstantCurvature { .. }
322            | Self::Spd { .. }
323            | Self::Grassmann { .. }
324            | Self::Stiefel { .. } => self
325                .riemannian()
326                .expect("riemannian response manifold")
327                .log_map(base, value),
328        }
329    }
330
331    /// Per-point exponential `exp_base(tangent)` in flat ambient coordinates.
332    fn exp_point(
333        &self,
334        base: ArrayView1<'_, f64>,
335        tangent: ArrayView1<'_, f64>,
336    ) -> GeometryResult<Array1<f64>> {
337        match self {
338            Self::Poincare { curvature, .. } => {
339                crate::manifolds::poincare::exp_map(base, tangent, *curvature)
340            }
341            Self::ConstantCurvature { .. }
342            | Self::Spd { .. }
343            | Self::Grassmann { .. }
344            | Self::Stiefel { .. } => self
345                .riemannian()
346                .expect("riemannian response manifold")
347                .exp_map(base, tangent),
348        }
349    }
350
351    /// Euclidean / Frobenius distance from an arbitrary ambient row to the
352    /// candidate response geometry, in flat ambient coordinates — the extrinsic
353    /// constraint-violation distance behind [`response_projection_residual`].
354    ///
355    /// Unlike [`log_point`](Self::log_point), which is gatekept to *genuine*
356    /// manifold points on both arguments, this accepts off-manifold `value`. The
357    /// distance is computed in closed form per geometry and is **well-defined for
358    /// every input** — there is no rank-deficiency error path, because the
359    /// distance to a set is defined even where the nearest point is not unique:
360    ///
361    /// * `Gr(k, n)` / `St(k, n)` — distance to the orthonormal-frame set,
362    ///   `√Σ_i (σ_i − 1)²` with `σ_i = √max(λ_i(YᵀY), 0)` the singular values of
363    ///   the `n × k` frame `Y`. Exact for every rank (`σ_i = 0` columns
364    ///   contribute `1` each). Grassmann and Stiefel coincide because this module
365    ///   represents Grassmann points by frames — it is a *representation*
366    ///   distance, not a subspace/principal-angle distance.
367    /// * SPD cone — distance to the *closed* PSD cone,
368    ///   `√(‖skew(A)‖_F² + Σ_{λ_i<0} λ_i²)` with `λ_i` the eigenvalues of the
369    ///   symmetric part `sym(A)`. This is the infimum distance to the open SPD
370    ///   cone; a zero distance means PSD, **not** strictly PD.
371    /// * Poincaré ball — distance to the *manifold* open ball of radius
372    ///   `R = 1/√(−c)`: `max(0, ‖x‖ − R)`. (This uses the true radius `R`, not
373    ///   the slightly smaller numerical safety radius used when projecting points
374    ///   for a fit, so interior points score exactly zero.)
375    /// * `ConstantCurvature` — distance to the chart *domain*: `0` for `κ ≥ 0`
376    ///   (chart is all of `ℝ^d`), else `max(0, ‖x‖ − 1/√(−κ))`. The curvature
377    ///   lives in the metric, not the domain, so this is a domain-admissibility
378    ///   check only and carries little curvature information.
379    fn manifold_residual(&self, value: ArrayView1<'_, f64>) -> GeometryResult<f64> {
380        match self {
381            Self::Poincare { curvature, .. } => ball_domain_residual(value, *curvature),
382            Self::ConstantCurvature { kappa, .. } => {
383                if *kappa >= 0.0 {
384                    Ok(0.0)
385                } else {
386                    ball_domain_residual(value, *kappa)
387                }
388            }
389            Self::Spd { n } => {
390                let mat = from_flat(value, *n, *n)?;
391                let symm = sym(&mat);
392                let psd = spectral_map_symmetric(&symm, |lam| Ok(lam.max(0.0)))?;
393                // Distance to the closed PSD cone, measured against the original
394                // (skew included) input so the skew-symmetric part is counted.
395                Ok(frobenius_distance(value, flatten(&psd).view()))
396            }
397            Self::Grassmann { k, n } | Self::Stiefel { k, n } => {
398                use gam_linalg::faer_ndarray::fast_atb;
399                let frame = from_flat(value, *n, *k)?;
400                let gram = fast_atb(&frame, &frame);
401                let (evals, _) = jacobi_symmetric(&gram)?;
402                let mut sq = 0.0_f64;
403                for &lam in evals.iter() {
404                    let sigma = lam.max(0.0).sqrt();
405                    let d = sigma - 1.0;
406                    sq += d * d;
407                }
408                Ok(sq.sqrt())
409            }
410        }
411    }
412
413    /// Squared metric norm `‖v‖²_base` of a tangent at `base`. Used by the
414    /// Karcher iteration's stationarity test. Poincaré uses the conformal
415    /// factor squared; the matrix manifolds and ConstantCurvature use the trait
416    /// metric tensor.
417    fn sq_metric_norm(
418        &self,
419        base: ArrayView1<'_, f64>,
420        v: ArrayView1<'_, f64>,
421    ) -> GeometryResult<f64> {
422        match self {
423            Self::Poincare { curvature, .. } => {
424                let lam = crate::manifolds::poincare::conformal_factor(base, *curvature)?;
425                Ok(lam * lam * v.iter().map(|x| x * x).sum::<f64>())
426            }
427            Self::ConstantCurvature { .. }
428            | Self::Spd { .. }
429            | Self::Grassmann { .. }
430            | Self::Stiefel { .. } => {
431                let g = self
432                    .riemannian()
433                    .expect("riemannian response manifold")
434                    .metric_tensor(base)?;
435                let gv = g.dot(&v);
436                Ok(v.dot(&gv).max(0.0))
437            }
438        }
439    }
440}
441
442/// Batched response-geometry logarithm: map every manifold-valued response row
443/// to its tangent coordinate at `base`. `values` is `(n_rows, ambient)`, `base`
444/// is `(ambient,)`, and the returned tangent is `(n_rows, ambient)` (the same
445/// flat ambient layout — the tangent of a matrix manifold is itself a flattened
446/// matrix). The scalar Gaussian GAMs the caller fits operate column-wise on
447/// this matrix exactly as they do for the sphere.
448pub fn response_log_map(
449    manifold: ResponseManifold,
450    values: ArrayView2<'_, f64>,
451    base: ArrayView1<'_, f64>,
452) -> Result<Array2<f64>, String> {
453    let ambient = manifold.ambient_dim();
454    let (n_rows, cols) = values.dim();
455    if base.len() != ambient {
456        return Err(format!(
457            "response geometry base point has length {}; expected {ambient}",
458            base.len()
459        ));
460    }
461    if cols != ambient {
462        return Err(format!(
463            "response geometry values have {cols} columns; expected {ambient}"
464        ));
465    }
466    let mut out = Array2::<f64>::zeros((n_rows, ambient));
467    for row in 0..n_rows {
468        let tangent = manifold
469            .log_point(base, values.row(row))
470            .map_err(|e| format!("response geometry log map (row {row}): {e}"))?;
471        out.row_mut(row).assign(&tangent);
472    }
473    Ok(out)
474}
475
476/// Batched response-geometry exponential: map predicted tangent coordinates
477/// back to manifold-valued responses at `base`. Inverse of [`response_log_map`]
478/// with the same shapes.
479pub fn response_exp_map(
480    manifold: ResponseManifold,
481    tangent: ArrayView2<'_, f64>,
482    base: ArrayView1<'_, f64>,
483) -> Result<Array2<f64>, String> {
484    let ambient = manifold.ambient_dim();
485    let (n_rows, cols) = tangent.dim();
486    if base.len() != ambient {
487        return Err(format!(
488            "response geometry base point has length {}; expected {ambient}",
489            base.len()
490        ));
491    }
492    if cols != ambient {
493        return Err(format!(
494            "response geometry tangent has {cols} columns; expected {ambient}"
495        ));
496    }
497    if !tangent.iter().all(|v| v.is_finite()) {
498        return Err("response geometry tangent must contain only finite values".to_string());
499    }
500    let mut out = Array2::<f64>::zeros((n_rows, ambient));
501    for row in 0..n_rows {
502        let value = manifold
503            .exp_point(base, tangent.row(row))
504            .map_err(|e| format!("response geometry exp map (row {row}): {e}"))?;
505        out.row_mut(row).assign(&value);
506    }
507    Ok(out)
508}
509
510/// Numerically-stable Euclidean norm `‖v‖₂`, scaled by the largest-magnitude
511/// entry so the squared sum cannot overflow for large but finite inputs.
512fn scaled_l2_norm(v: ArrayView1<'_, f64>) -> f64 {
513    let mut scale = 0.0_f64;
514    for &x in v.iter() {
515        let a = x.abs();
516        if a > scale {
517            scale = a;
518        }
519    }
520    if scale == 0.0 {
521        return 0.0;
522    }
523    let mut ssq = 0.0_f64;
524    for &x in v.iter() {
525        let t = x / scale;
526        ssq += t * t;
527    }
528    scale * ssq.sqrt()
529}
530
531/// Numerically-stable Frobenius distance `‖a − b‖₂` over equal-length flat
532/// vectors, scaled by the largest entrywise difference to avoid overflow.
533fn frobenius_distance(a: ArrayView1<'_, f64>, b: ArrayView1<'_, f64>) -> f64 {
534    let mut scale = 0.0_f64;
535    for (x, y) in a.iter().zip(b.iter()) {
536        let d = (x - y).abs();
537        if d > scale {
538            scale = d;
539        }
540    }
541    if scale == 0.0 {
542        return 0.0;
543    }
544    let mut ssq = 0.0_f64;
545    for (x, y) in a.iter().zip(b.iter()) {
546        let t = (x - y) / scale;
547        ssq += t * t;
548    }
549    scale * ssq.sqrt()
550}
551
552/// Distance from `value` to the open ball of radius `R = 1/√(−c)` (`c < 0`):
553/// `max(0, ‖value‖ − R)`, the true Euclidean infimum distance to the ball.
554/// Errors if the curvature is not a finite negative number.
555fn ball_domain_residual(value: ArrayView1<'_, f64>, curvature: f64) -> GeometryResult<f64> {
556    if !curvature.is_finite() || curvature >= 0.0 {
557        return Err(GeometryError::InvalidPoint(
558            "ball distance requires a finite negative curvature",
559        ));
560    }
561    let radius = (-curvature).sqrt().recip();
562    Ok((scaled_l2_norm(value) - radius).max(0.0))
563}
564
565/// Per-row extrinsic distance from ambient observations to a *candidate*
566/// response geometry — a coordinate-dependent constraint / closure-distance
567/// diagnostic.
568///
569/// What this is (and is not)
570/// -------------------------
571/// This is a cheap, pre-fit **constraint-violation** measure: given a candidate
572/// response geometry, how far does each raw row sit from that geometry's
573/// extrinsic representation (the unit-norm frame, the PSD cone, the Poincaré
574/// ball)? It is **not** the post-fit on/off-manifold membership signal (which
575/// comes from a fitted geometric smooth's residual and posterior predictive
576/// density), and it is **not** a universal cross-geometry model-selection score:
577/// it measures extrinsic constraint violation *in a chosen coordinate chart*,
578/// not intrinsic topology or curvature. Different candidate geometries have
579/// different chart codimensions (a full-dimensional Poincaré/`κ ≥ 0` chart can
580/// score zero trivially), so residuals are not directly comparable across
581/// candidates without a noise model and per-candidate calibration. Use it as a
582/// fast per-candidate gate, with candidate-specific thresholds.
583///
584/// What it computes
585/// ----------------
586/// For each ambient row `x`, [`manifold_residual`](Self::manifold_residual)
587/// returns the closed-form distance to the candidate geometry (well-defined for
588/// every input and every rank — see that method for the per-geometry formulas),
589/// and this returns:
590///
591/// * `residual[i]` — the absolute distance-to-geometry (zero for genuinely
592///   admissible rows; for the matrix manifolds, exact to machine precision).
593/// * `relative[i] = residual[i] / (‖x‖ + eps)` — the distance normalised by the
594///   row's ambient magnitude. **Note:** this is dimensionless but *not*
595///   scale-invariant for the fixed-radius geometries (Stiefel/Grassmann/ball)
596///   and is *not* bounded by `1` (it diverges as `‖x‖ → 0`); it is scale-free
597///   only for the homogeneous SPD cone. Treat it as `input_norm_relative`, not
598///   an off-manifold fraction.
599///
600/// Unlike [`response_log_map`], **no base point is needed**. `values` is
601/// `(n_rows, ambient)`; both returned arrays are `(n_rows,)`. Every fittable
602/// response geometry — including `ConstantCurvature` — has a closed-form
603/// distance, so no variant errors on a valid, finite input.
604pub fn response_projection_residual(
605    manifold: ResponseManifold,
606    values: ArrayView2<'_, f64>,
607) -> Result<(Array1<f64>, Array1<f64>), String> {
608    let ambient = manifold.ambient_dim();
609    let (n_rows, cols) = values.dim();
610    if cols != ambient {
611        return Err(format!(
612            "response geometry values have {cols} columns; expected {ambient}"
613        ));
614    }
615    if !values.iter().all(|v| v.is_finite()) {
616        return Err("response geometry values must contain only finite values".to_string());
617    }
618
619    let mut residual = Array1::<f64>::zeros(n_rows);
620    let mut relative = Array1::<f64>::zeros(n_rows);
621    for row in 0..n_rows {
622        let value = values.row(row);
623        let dist = manifold
624            .manifold_residual(value)
625            .map_err(|e| format!("response geometry residual (row {row}): {e}"))?;
626        let rel = dist / (scaled_l2_norm(value) + GEOMETRY_EPS);
627        if !dist.is_finite() || !rel.is_finite() {
628            return Err(format!(
629                "response geometry residual (row {row}) is non-finite"
630            ));
631        }
632        residual[row] = dist;
633        relative[row] = rel;
634    }
635    Ok((residual, relative))
636}
637
638/// String-driven response-geometry log map: parse the user `label` (with shape
639/// inference from the response column count), pick the base point (intrinsic
640/// Fréchet mean when `base` is `None`), map every row to its tangent, and report
641/// the canonical resolved label. This is the curved-manifold analogue of the
642/// sphere/simplex dispatch and the single entry the FFI calls for these
643/// geometries.
644pub fn dispatch_log_map(
645    values: ArrayView2<'_, f64>,
646    label: &str,
647    base: Option<ArrayView1<'_, f64>>,
648) -> Result<(Array2<f64>, Array1<f64>, String), String> {
649    let manifold = ResponseManifold::parse(label, values.ncols())?;
650    let base_point = match base {
651        Some(b) => b.to_owned(),
652        None => response_frechet_mean(manifold, values, None, 1.0e-12, 256)?,
653    };
654    let tangent = response_log_map(manifold, values, base_point.view())?;
655    Ok((tangent, base_point, manifold.canonical_label()))
656}
657
658/// String-driven response-geometry exponential map: inverse of
659/// [`dispatch_log_map`] given an explicit base point.
660pub fn dispatch_exp_map(
661    tangent: ArrayView2<'_, f64>,
662    label: &str,
663    base: ArrayView1<'_, f64>,
664) -> Result<Array2<f64>, String> {
665    let manifold = ResponseManifold::parse(label, tangent.ncols())?;
666    response_exp_map(manifold, tangent, base)
667}
668
669/// Intrinsic (Karcher) Fréchet mean of manifold-valued responses, the default
670/// base point when the user supplies none. `values` is `(n_rows, ambient)`.
671///
672/// This is the SPD safeguarded Karcher iteration generalised over an arbitrary
673/// [`ResponseManifold`]: a Riemannian gradient-descent on the weighted
674/// dispersion `V(P) = Σ_i w_i ‖log_P(X_i)‖²_P` with the descent direction
675/// `ξ = Σ_i w_i log_P(X_i)` (`= −½ grad V`), a unit Karcher step `exp_P(t·ξ)`
676/// with Armijo backtracking plus a round-off cushion, a best-iterate stall
677/// guard, and the metric-norm stationarity test `‖ξ‖_P ≤ tol`. The SPD-specific
678/// version in [`crate::manifolds::spd::spd_frechet_mean`] remains for the affine
679/// inverse it caches per step; this generic form pays a metric-tensor solve but
680/// covers all four geometries uniformly.
681pub fn response_frechet_mean(
682    manifold: ResponseManifold,
683    values: ArrayView2<'_, f64>,
684    weights: Option<ArrayView1<'_, f64>>,
685    tol: f64,
686    max_iter: usize,
687) -> Result<Array1<f64>, String> {
688    let ambient = manifold.ambient_dim();
689    let (m, cols) = values.dim();
690    if m == 0 || cols != ambient {
691        return Err(format!(
692            "response geometry Fréchet mean: values must be M×{ambient} with M >= 1"
693        ));
694    }
695    if !(tol.is_finite() && tol > 0.0) {
696        return Err("response geometry Fréchet mean tolerance must be finite and positive".into());
697    }
698    let w = crate::normalize_weights(m, weights)
699        .map_err(|_| "response geometry Fréchet mean: invalid weights".to_string())?;
700    let samples: Vec<Array1<f64>> = (0..m).map(|i| values.row(i).to_owned()).collect();
701
702    let dispersion = |p: ArrayView1<'_, f64>| -> Result<f64, String> {
703        let mut acc = 0.0_f64;
704        for (i, x) in samples.iter().enumerate() {
705            let lg = manifold
706                .log_point(p, x.view())
707                .map_err(|e| format!("response geometry Fréchet mean log map: {e}"))?;
708            let sq = manifold
709                .sq_metric_norm(p, lg.view())
710                .map_err(|e| format!("response geometry Fréchet mean metric: {e}"))?;
711            acc += w[i] * sq;
712        }
713        Ok(acc)
714    };
715
716    // Seed the Karcher iteration at a sample whose tangent star is fully
717    // defined, then take one Riemannian averaging step for an interior start.
718    //
719    // A fixed seed at `samples[0]` is fragile: if any *other* sample lies at
720    // that seed's cut locus the seeding log is undefined and the whole mean
721    // aborts, even though the Fréchet mean itself is well defined. On
722    // `Gr(1,n) = ℝP^{n-1}` two orthogonal lines (principal angle π/2) are
723    // exactly such a cut-locus pair, so a design whose first response happens
724    // to be orthogonal to another could never be averaged. Instead, try each
725    // sample as the seed and keep the first whose log-tangents to *every*
726    // sample land: the safeguarded descent below converges to the same mean
727    // from any admissible seed, so this only changes which interior point the
728    // iteration starts from — and the very first sample is chosen whenever it
729    // is admissible (so SPD/Stiefel/Poincaré data with no cut-locus pair seed
730    // exactly as before). A design where every sample sits at another's cut
731    // locus has a genuinely ambiguous mean and is reported as such.
732    let mut seeded: Option<Array1<f64>> = None;
733    let mut last_seed_err = String::new();
734    for seed in &samples {
735        let base = match manifold.exp_point(seed.view(), Array1::<f64>::zeros(ambient).view()) {
736            Ok(base) => base,
737            Err(e) => {
738                last_seed_err = e.to_string();
739                continue;
740            }
741        };
742        let mut xi = Array1::<f64>::zeros(ambient);
743        let mut admissible = true;
744        for (i, x) in samples.iter().enumerate() {
745            match manifold.log_point(base.view(), x.view()) {
746                Ok(lg) => xi.scaled_add(w[i], &lg),
747                Err(e) => {
748                    last_seed_err = e.to_string();
749                    admissible = false;
750                    break;
751                }
752            }
753        }
754        if !admissible {
755            continue;
756        }
757        match manifold.exp_point(base.view(), xi.view()) {
758            Ok(stepped) => {
759                seeded = Some(stepped);
760                break;
761            }
762            Err(e) => {
763                last_seed_err = e.to_string();
764            }
765        }
766    }
767    let mut p = seeded.ok_or_else(|| {
768        format!(
769            "response geometry Fréchet mean init: no admissible seed among samples \
770             (every sample lies at another's cut locus; last error: {last_seed_err})"
771        )
772    })?;
773
774    let mut f_cur = dispersion(p.view())?;
775    let mut best_p = p.clone();
776    let mut best_grad = f64::INFINITY;
777    const STALL_REL: f64 = 5.0e-3;
778    const STALL_PATIENCE: usize = 10;
779    let mut stall = 0_usize;
780    const ARMIJO_C1: f64 = 1.0e-4;
781    const MAX_BACKTRACK_HALVINGS: usize = 60;
782    const ARMIJO_ROUNDOFF_EPS_MULTIPLE: f64 = 8.0;
783
784    for _ in 0..max_iter {
785        let mut xi = Array1::<f64>::zeros(ambient);
786        for (i, x) in samples.iter().enumerate() {
787            let lg = manifold
788                .log_point(p.view(), x.view())
789                .map_err(|e| format!("response geometry Fréchet mean log map: {e}"))?;
790            xi.scaled_add(w[i], &lg);
791        }
792        let grad_norm = manifold
793            .sq_metric_norm(p.view(), xi.view())
794            .map_err(|e| format!("response geometry Fréchet mean metric: {e}"))?
795            .sqrt();
796        if grad_norm <= tol {
797            return Ok(p);
798        }
799
800        let improved = grad_norm < best_grad * (1.0 - STALL_REL);
801        if grad_norm < best_grad {
802            best_grad = grad_norm;
803            best_p.assign(&p);
804        }
805        if improved {
806            stall = 0;
807        } else {
808            stall += 1;
809            if stall >= STALL_PATIENCE {
810                return Ok(best_p);
811            }
812        }
813
814        let pred = grad_norm * grad_norm;
815        let f_tol = ARMIJO_ROUNDOFF_EPS_MULTIPLE * f64::EPSILON * (1.0 + f_cur.abs());
816        let mut t = 1.0_f64;
817        let mut accepted = false;
818        for _ in 0..MAX_BACKTRACK_HALVINGS {
819            let step = &xi * t;
820            let cand = match manifold.exp_point(p.view(), step.view()) {
821                Ok(c) => c,
822                Err(_) => {
823                    // The step left the manifold's domain (e.g. a Poincaré
824                    // overshoot past the ball boundary); shrink and retry.
825                    t *= 0.5;
826                    continue;
827                }
828            };
829            let f_cand = match dispersion(cand.view()) {
830                Ok(f) => f,
831                Err(_) => {
832                    t *= 0.5;
833                    continue;
834                }
835            };
836            if f_cand <= f_cur - 2.0 * ARMIJO_C1 * t * pred + f_tol {
837                p = cand;
838                f_cur = f_cand;
839                accepted = true;
840                break;
841            }
842            t *= 0.5;
843        }
844        if !accepted {
845            return Ok(best_p);
846        }
847    }
848    Err("response geometry Fréchet mean did not reach stationarity within max_iter".into())
849}
850
851// ── Curvature as an estimand on the response geometry (#944 stage 4 / #1104) ──
852//
853// `response_geometry="constant_curvature(dim=d)"` does NOT take a fixed κ from
854// the user: κ is ESTIMATED from the manifold-valued responses. At each κ the
855// family `ConstantCurvature{dim, κ}` is laid down and κ is scored by the HONEST
856// change-of-variables likelihood of the observed chart coordinates `yᵢ` w.r.t.
857// ambient Lebesgue measure `dy` — the density that is automatically normalised on
858// the SAME measure in which the data are observed, regardless of how the manifold
859// is parameterised. This is the crux of the #1104 fix.
860//
861// ## Why dispersion alone (and the self-normalising wrapped Gaussian) is degenerate
862//
863// The generative model is the wrapped normal `yᵢ = exp_μ(vᵢ)`, `vᵢ` isotropic at
864// geodesic scale σ. Its density w.r.t. the Riemannian volume `dvol_κ` is
865// `N(sᵢ;0,σ²)/Jᵧ_κ(sᵢ)` with `sᵢ = d_κ(μ,yᵢ)` the geodesic radius and
866// `J_κ(s) = (sn_κ(s)/s)^{d−1}` the exp-map volume Jacobian
867// (`ConstantCurvature::jacobian_radial`). The naive criterion
868// `½nd·ln(Σsᵢ²/nd)` (dispersion only), and even the full `dvol_κ`-density NLL
869// `Σ[sᵢ²/2σ² + (d/2)ln2πσ² + ln J_κ(sᵢ)]`, are SCALE-DEGENERATE: rescaling the
870// manifold radius `R = 1/√|κ|` rescales every `sᵢ` and every volume element, and
871// the σ-profile absorbs the change with no κ information left. That is exactly
872// why a `dvol_κ`-normalised (self-normalising) wrapped Gaussian rails, and why an
873// intrinsic-volume partition function double-counts: the density is already
874// normalised on `dvol_κ`, so re-integrating its volume adds nothing identifying.
875//
876// ## The restoring force is the ambient (chart) volume element at the DATA points
877//
878// Curvature is identified only when the abstract manifold is tied to the CONCRETE
879// observed chart coordinates `yᵢ`. The data are observed as points of `ℝ^d` under
880// Lebesgue `dy`, so the likelihood must be the density w.r.t. `dy`, obtained from
881// the `dvol_κ`-density by the chart volume factor `dvol_κ/dy = λ_{yᵢ}^d`,
882// `λ_y = 2/(1+κ‖y‖²)`:
883//
884// ```text
885//   −ℓ(κ,μ,σ²) = Σᵢ[ sᵢ²/(2σ²) + (d/2)ln(2πσ²) + ln J_κ(sᵢ) − d·ln λ_{yᵢ} ].
886// ```
887//
888// The new term `−d·Σ ln λ_{yᵢ} = d·Σ ln((1+κ‖yᵢ‖²)/2)` is evaluated at every DATA
889// point (not at the mean), so `‖yᵢ‖² > 0` even for mean-centred clouds and it
890// supplies a genuine κ-restoring force: it grows like `+d·κ·Σ‖yᵢ‖²` for small κ
891// and `→ +∞` as κ→+∞ (each `−ln λ_{yᵢ}→+∞`), exactly opposing the dispersion /
892// `ln J_κ` terms which fall as the sphere shrinks. The minimum is therefore
893// INTERIOR at the data-generating curvature. None of `ln J_κ` or `λ` depend on σ,
894// so σ profiles in closed form `σ̂² = D/(nd)`, `D = Σ sᵢ²`.
895//
896// ## Reparameterisation invariance / unit-covariance of κ̂
897//
898// κ carries units of `1/length²`. Under a global rescaling `yᵢ ↦ α·yᵢ` the chart
899// of `M_κ` at scale `α` equals the chart of `M_{κ/α²}` at scale 1 (because
900// `λ` and every geodesic primitive depend on `y` only through `κ‖y‖²`). The whole
901// criterion `V(κ, αy)` therefore equals `V(α²κ, y)`, so its minimiser transforms
902// as `κ̂(αy) = κ̂(y)/α²` — the CORRECT covariance of a curvature with units
903// `1/length²`. The base point μ is held at the κ-independent flat centroid (NOT
904// re-solved per κ): re-solving the Fréchet mean per κ is precisely what
905// re-entangles κ with the chart scale and biases the estimate, so it is removed.
906//
907// `V_p` is a negative log-evidence (lower is better) so κ̂ = argmin V_p; it is the
908// full NLL summed over all `n·d` scalar observations, so `2[V_p(0) − V_p(κ̂)]` is
909// the Wilks LR statistic with a calibrated χ²₁ flatness reference — exactly the
910// contract `profile_ci_walk` / `flatness_lr_test` in `curvature_estimand.rs`
911// consume, with no new outer machinery.
912
913/// Outcome of fitting curvature as an estimand on a constant-curvature response
914/// geometry: the optimised κ̂, its tangent base point, the profile-likelihood CI,
915/// and the interior-point flatness (Wilks) test of κ = 0.
916#[derive(Clone, Debug)]
917pub struct ResponseCurvatureFit {
918    /// The dimension `d` of the constant-curvature response manifold.
919    pub dim: usize,
920    /// The REML/evidence-optimal curvature κ̂ (argmin of the profiled criterion).
921    ///
922    /// **Units `1/length²`** — κ̂ is therefore *scale-dependent*: rescaling the
923    /// cloud `y ↦ α·y` rescales `κ̂ ↦ κ̂/α²`. For a scale-free statement of how
924    /// curved the cloud is, read [`kappa_r2`](Self::kappa_r2) instead. When the
925    /// cloud is curved BEYOND what its spread can resolve (it fills a large
926    /// fraction of the sphere `S^d(1/√κ̂)`), the optimiser rails to the
927    /// chart-resolution cap and [`railed_at_resolution_limit`](Self::railed_at_resolution_limit)
928    /// is `true`: κ̂ is then a *lower bound on |κ|*, not a point estimate.
929    pub kappa_hat: f64,
930    /// The DIMENSIONLESS geometric invariant the cloud actually determines:
931    /// `κ̂ · r²` with `r` = [`characteristic_radius`](Self::characteristic_radius).
932    /// This is scale-FREE (`κ̂·r²` is invariant under `y ↦ α·y`, since `κ̂ ↦ κ̂/α²`
933    /// and `r ↦ α·r`) — the honest answer to "how curved is this cloud relative
934    /// to its own spread". `|κ̂·r²| ≪ 1` ⇒ nearly flat at this scale; `κ̂·r² ↗ (π/2)²`
935    /// ⇒ the cloud fills the sphere and curvature is at the chart-resolution limit.
936    pub kappa_r2: f64,
937    /// Characteristic geodesic radius `r` of the cloud at κ = 0 (the doubled-gauge
938    /// chart distance `r = 2·max_i‖y_i − μ‖`): the length scale against which κ̂ is
939    /// dimensionless. Reported so the caller can convert between scale-dependent κ̂
940    /// and the scale-free `κ̂·r²` without re-deriving the chart gauge.
941    pub characteristic_radius: f64,
942    /// The intrinsic Fréchet-mean base point at κ̂ (the tangent expansion point
943    /// the scalar GAMs are fitted around).
944    pub base: Array1<f64>,
945    /// Profiled criterion value `V_p(κ̂)` (concentrated negative log-evidence).
946    pub v_p_hat: f64,
947    /// `true` when the κ̂ search converged ONTO the chart-resolution cap rather
948    /// than an interior optimum: the data want curvature at or beyond the
949    /// conjugate radius of their geodesic spread (the cloud fills the sphere).
950    /// In that case κ̂ / the CI upper end are NOT a resolved point estimate but a
951    /// HONEST "curvature exceeds chart-resolvable range at this scale" flag — the
952    /// caller must report it as such and never as a silent `κ̂ = ci_hi`. The
953    /// hyperbolic side cannot rail this way (κ < 0 has no conjugate radius), so a
954    /// rail here always means strongly spherical relative to the spread.
955    pub railed_at_resolution_limit: bool,
956    /// `true` only when the SIGN of κ̂ is statistically resolved — i.e. the
957    /// profile-likelihood CI excludes 0 (`profile_ci.verdict ≠ Flat`).
958    ///
959    /// ## Why a point estimate alone is not enough (the #944/#1059 flat-floor)
960    ///
961    /// Curvature is resolvable only through the dimensionless product `κ·r²`
962    /// (see [`kappa_r2`](Self::kappa_r2)); the per-point Fisher information for κ
963    /// scales like `σ⁴`. When the cloud is nearly flat at its own scale
964    /// (`|κ·r²| ≪ 1`), the profiled criterion is so shallow that its single-cloud
965    /// argmin κ̂ can land on the WRONG SIDE OF ZERO purely by Monte-Carlo
966    /// fluctuation — empirically a coin-flip below `|κ·r²| ≈ 0.03`, reliable above
967    /// `≈ 0.09` (the #944 power curve). The estimand itself is UNBIASED (the
968    /// criterion averaged over clouds minimises exactly at κ⋆), so this is a
969    /// resolution limit, not a bias.
970    ///
971    /// The CI, in contrast, is honest in this regime: at an under-resolved
972    /// operating point it reports `Flat` (straddles 0) rather than a confident
973    /// wrong sign — it essentially never claims the wrong-signed geometry. So the
974    /// SIGN-bearing summary the caller may quote is the CI verdict, not the bare
975    /// κ̂. This flag exposes that contract on the point-estimate surface: when it
976    /// is `false`, κ̂'s sign is noise — the caller must report "curvature not
977    /// resolved at this scale (|κ·r²| too small)" and quote the CI / `kappa_r2`,
978    /// never a sign-confident κ̂. It is the flat-floor twin of
979    /// [`railed_at_resolution_limit`](Self::railed_at_resolution_limit) (the
980    /// spherical-cap rail); together they bracket the two ends of the resolvable
981    /// `κ·r²` band where κ̂ is a genuine interior point estimate.
982    pub sign_resolved: bool,
983    /// Profile-likelihood CI for κ and the geometry verdict from its sign.
984    pub profile_ci: crate::curvature_estimand::KappaProfileCi,
985    /// Interior-point χ²₁ likelihood-ratio test of flatness (κ = 0).
986    pub flatness: crate::curvature_estimand::FlatnessTest,
987}
988
989/// Chart-validity bounds on κ for a constant-curvature response geometry built
990/// from the supplied responses, plus the characteristic geodesic radius
991/// `ρ_max = 2·max_i‖y_i − μ‖` against which κ is made dimensionless.
992///
993/// Returns `(kappa_min, kappa_max, rho_max)`.
994///
995/// * **Lower (hyperbolic) bound.** The κ-stereographic chart requires
996///   `1 + κ‖x‖² > 0` at every point measured from the chart origin, i.e.
997///   `κ > −1/R²` with `R² = max_i ‖y_i‖²`. With a safety margin: `−0.999/R²`.
998/// * **Upper (spherical) bound.** Unlike the hyperbolic side this is NOT
999///   unbounded: on a sphere of curvature κ the geodesic radius cannot exceed the
1000///   conjugate radius `π/√κ`, beyond which the exp-map volume Jacobian
1001///   `J_κ = (sn_κ/·)^{d−1}` changes sign (clamped to 0 here) and `ln J_κ` would
1002///   collapse `V_p` toward `−∞`, railing the optimiser onto a spurious shell.
1003///   The κ = 0 geodesic radius of the farthest point from the centroid is
1004///   `ρ_max = 2·max_i‖y_i − μ‖` (doubled-gauge chart). We cap κ so that radius
1005///   stays strictly inside the first conjugate shell with a 10% margin:
1006///   `√κ·ρ_max ≤ 0.9π ⇒ κ_max = (0.9π / ρ_max)²`. This keeps every geodesic
1007///   radius before the antipodal singularity along the whole search/CI walk.
1008///
1009/// `κ_max` is the chart-RESOLUTION limit of the cloud: at it the geodesic spread
1010/// fills `(0.9π)² ≈ (π/2·1.8)²` of the conjugate shell, i.e. the cloud nearly
1011/// fills the sphere `S^d(1/√κ_max)`. The DIMENSIONLESS product `κ_max·ρ_max²
1012/// = (0.9π)²` is fixed and data-scale-free — it is the natural "the cloud is
1013/// maximally curved relative to its spread" sentinel the rail check compares κ̂ to.
1014fn response_kappa_bounds(values: ArrayView2<'_, f64>) -> (f64, f64, f64) {
1015    let (n_rows, dim) = values.dim();
1016    // ‖y_i‖² from the chart origin (governs the λ / hyperbolic-chart constraint).
1017    let mut r2_max = 0.0_f64;
1018    for row in values.outer_iter() {
1019        let r2 = row.dot(&row);
1020        if r2 > r2_max {
1021            r2_max = r2;
1022        }
1023    }
1024    // ‖y_i − μ‖² from the centroid (governs the spherical conjugate-radius cap).
1025    let mut centroid = Array1::<f64>::zeros(dim.max(1));
1026    if n_rows > 0 && dim > 0 {
1027        for row in values.outer_iter() {
1028            centroid += &row;
1029        }
1030        centroid.mapv_inplace(|v| v / n_rows as f64);
1031    }
1032    let mut s2_max = 0.0_f64;
1033    if dim > 0 {
1034        for row in values.outer_iter() {
1035            let diff = &row - &centroid;
1036            let r2 = diff.dot(&diff);
1037            if r2 > s2_max {
1038                s2_max = r2;
1039            }
1040        }
1041    }
1042    if r2_max <= 0.0 && s2_max <= 0.0 {
1043        // Degenerate (all points at the origin): κ is unidentified; use a wide
1044        // symmetric default so the optimiser/CI report a flat, unbounded result.
1045        return (-1.0e6, 1.0e6, 0.0);
1046    }
1047    // Keep a safety margin off the singular hyperbolic boundary.
1048    let kappa_min = if r2_max > 0.0 {
1049        -0.999 / r2_max
1050    } else {
1051        -1.0e6
1052    };
1053    // Conjugate-radius cap: ρ_max = 2·max‖y_i − μ‖ is the κ=0 geodesic radius.
1054    let rho_max = 2.0 * s2_max.sqrt();
1055    let kappa_max = if s2_max > 0.0 {
1056        let edge = 0.9 * std::f64::consts::PI / rho_max;
1057        edge * edge
1058    } else {
1059        1.0e6
1060    };
1061    (kappa_min, kappa_max, rho_max)
1062}
1063
1064/// Profiled curvature criterion `V_p(κ)` for the constant-curvature response
1065/// geometry: the σ-profiled HONEST change-of-variables negative log-likelihood of
1066/// the observed chart coordinates `y_i` at curvature `κ`, expressed w.r.t. ambient
1067/// Lebesgue measure `dy`. Lower is better (κ̂ = argmin). Returns `(V_p, base)`;
1068/// the base point is the κ-INDEPENDENT flat centroid (the tangent expansion point
1069/// that the scalar GAMs are fitted around), held fixed across κ so the estimate is
1070/// not re-entangled with the chart scale.
1071///
1072/// The model is the wrapped normal `y_i = exp_{μ,κ}(v_i)` with isotropic geodesic
1073/// scale σ; `s_i = d_κ(μ, y_i)` is the geodesic radius and `J_κ(s)` the exp-map
1074/// volume Jacobian. The density on the Riemannian volume `dvol_κ` is
1075/// `N(s_i;0,σ²)/J_κ(s_i)`; converting to ambient `dy` multiplies by the chart
1076/// volume factor `λ_{y_i}^d`, `λ_y = 2/(1+κ‖y‖²)`. The negative log-likelihood is
1077///
1078/// ```text
1079///   −ℓ(κ,σ²) = Σ_i[ s_i²/(2σ²) + (d/2)ln(2πσ²) + ln J_κ(s_i) − d·ln λ_{y_i} ].
1080/// ```
1081///
1082/// `ln J_κ` and `λ` do not depend on σ, so σ profiles in closed form
1083/// `σ̂² = D/(nd)`, `D = Σ s_i²`. The `−d·Σ ln λ_{y_i}` term — evaluated at the DATA
1084/// points, not the mean — is the κ-restoring force that breaks the scale
1085/// degeneracy of the dispersion / `dvol_κ`-density alone (see the module notes).
1086/// Additive constants independent of κ are kept implicit; they cancel in every
1087/// LR / profile-drop the CI machinery forms. μ is the closed-form flat centroid,
1088/// so the criterion is a pure function of κ with no inner tolerance/iteration
1089/// budget (the outer κ̂ search owns those).
1090pub fn response_curvature_criterion(
1091    values: ArrayView2<'_, f64>,
1092    dim: usize,
1093    kappa: f64,
1094) -> Result<(f64, Array1<f64>), String> {
1095    if !kappa.is_finite() {
1096        return Err("response curvature criterion: kappa must be finite".into());
1097    }
1098    let (n_rows, cols) = values.dim();
1099    if n_rows == 0 || cols != dim || dim == 0 {
1100        return Err(format!(
1101            "response curvature criterion: values must be N×{dim} with N >= 1"
1102        ));
1103    }
1104    // κ-independent base point: the flat (ambient) centroid. Holding μ fixed across
1105    // κ is the de-entangling move — re-solving the Fréchet mean per κ couples the
1106    // base to the chart scale and biases κ̂ (#1104 root cause).
1107    let mut base = Array1::<f64>::zeros(dim);
1108    for row in values.outer_iter() {
1109        base += &row;
1110    }
1111    base.mapv_inplace(|v| v / n_rows as f64);
1112
1113    let chart = ConstantCurvature::new(dim, kappa);
1114    // Reject κ at/over the chart boundary (1 + κ‖x‖² ≤ 0) at the centroid or any
1115    // data point: the geodesic primitives are undefined there. The bracket in
1116    // `response_kappa_bounds` keeps the optimiser strictly inside, but a CI/LR
1117    // probe can still land on the edge, so guard rather than panic.
1118    chart
1119        .conformal_factor(base.view())
1120        .map_err(|e| format!("response curvature criterion: base off chart: {e}"))?;
1121
1122    let d = dim as f64;
1123    let mut dispersion = 0.0_f64; // D = Σ s_i²
1124    let mut ln_jac = 0.0_f64; // Σ ln J_κ(s_i)
1125    let mut ln_lambda = 0.0_f64; // Σ ln λ_{y_i}
1126    for row in values.outer_iter() {
1127        // Geodesic radius s_i = d_κ(μ, y_i); also validates y_i is in-chart.
1128        let s = chart
1129            .distance(base.view(), row)
1130            .map_err(|e| format!("response curvature criterion distance: {e}"))?;
1131        dispersion += s * s;
1132        // ln J_κ(s_i): exp-map volume Jacobian (≥ 0); floor before the log so the
1133        // conjugate-shell clamp (J → 0 on the κ>0 antipodal shell) is a large
1134        // finite penalty rather than −∞.
1135        ln_jac += chart.jacobian_radial(s).max(1.0e-300).ln();
1136        // ln λ_{y_i} = ln(2) − ln(1 + κ‖y_i‖²); `conformal_factor` validates chart.
1137        let lam = chart
1138            .conformal_factor(row)
1139            .map_err(|e| format!("response curvature criterion conformal factor: {e}"))?;
1140        ln_lambda += lam.ln();
1141    }
1142    let nobs = (n_rows * dim) as f64;
1143    // Floor the dispersion so a (near-)perfect flat fit does not blow ln up; the
1144    // floor is far below any genuine residual scale and cancels in profile drops.
1145    let disp = dispersion.max(1.0e-300 * nobs.max(1.0));
1146
1147    // σ profiles in closed form: σ̂² = D/(nd). Substituting and dropping the
1148    // κ-independent constant (nd/2)(1 + ln 2π):
1149    //   V_p(κ) = (nd/2)·ln(D/(nd)) + Σ ln J_κ(s_i) − d·Σ ln λ_{y_i}.
1150    let v_p = 0.5 * nobs * (disp / nobs).ln() + ln_jac - d * ln_lambda;
1151    Ok((v_p, base))
1152}
1153
1154/// Fit curvature as an estimand on a constant-curvature response geometry.
1155///
1156/// κ̂ is the minimiser of the profiled criterion [`response_curvature_criterion`]
1157/// (the σ-profiled honest change-of-variables negative log-evidence of the wrapped
1158/// normal w.r.t. ambient measure), found by a golden-section search inside the
1159/// chart-validity bracket. The base point μ is the κ-independent flat centroid, so
1160/// every `V_p` evaluation scores the SAME geometry without re-entangling κ with the
1161/// chart scale (the #1104 fix). The exact outer
1162/// curvature `V_p''(κ̂)` is taken by a central second difference of the same
1163/// criterion and handed to [`profile_ci_walk`](crate::profile_ci_walk)
1164/// to size the initial Wald step; the CI itself is the exact χ²₁ profile crossing.
1165/// Flatness is the interior-point χ²₁ LR test
1166/// [`flatness_lr_test`](crate::flatness_lr_test). κ = 0 is an interior
1167/// point of the analytic `S^d ← ℝ^d → H^d` family, so no boundary correction is
1168/// applied. Returns the κ̂, its tangent base point, the profile CI, and the Wilks
1169/// flatness test for the fit summary.
1170///
1171/// ## Scale-awareness and honest railing (#1104)
1172///
1173/// κ has units `1/length²`, so a cloud of characteristic geodesic radius `r`
1174/// resolves only the DIMENSIONLESS product `κ·r²` (every chart primitive depends
1175/// on `y` through `κ‖y‖²`, hence `V(κ, αy) = V(α²κ, y)` and `κ̂ ↦ κ̂/α²` under
1176/// `y ↦ αy`). The fit therefore also returns:
1177/// * `kappa_r2 = κ̂·r²` — the scale-FREE invariant the cloud actually determines
1178///   (how curved relative to its own spread), and `characteristic_radius = r`;
1179/// * `railed_at_resolution_limit` — `true` when the data want curvature at or
1180///   beyond the conjugate radius of their spread (the cloud fills the sphere),
1181///   so the search converges onto the spherical cap. There κ̂ is a LOWER BOUND on
1182///   `|κ|`, not a resolved point estimate, and the caller must report "curvature
1183///   exceeds chart-resolvable range at this scale" rather than silently quoting
1184///   `κ̂ = ci_hi`. This is the #1104 fix: a tightly-concentrated near-spherical
1185///   cloud (e.g. unit-normalised OLMo activations) no longer SILENTLY rails to a
1186///   huge scale-dependent `ci_hi` while claiming a point estimate + CI.
1187pub fn fit_response_curvature(
1188    values: ArrayView2<'_, f64>,
1189    dim: usize,
1190    level: f64,
1191    tol: f64,
1192    max_iter: usize,
1193) -> Result<ResponseCurvatureFit, String> {
1194    if dim == 0 {
1195        return Err("constant-curvature response geometry requires dim >= 1".into());
1196    }
1197    let (n_rows, cols) = values.dim();
1198    if n_rows == 0 || cols != dim {
1199        return Err(format!(
1200            "constant-curvature response geometry: values must be N×{dim} with N >= 1"
1201        ));
1202    }
1203    if !(level > 0.0 && level < 1.0) {
1204        return Err("response curvature CI level must lie in (0, 1)".into());
1205    }
1206    let (kappa_min, kappa_max, rho_max) = response_kappa_bounds(values);
1207
1208    // `V_p` as a closure over the criterion; threaded through both the κ̂ search
1209    // and the CI walk. Every evaluation uses the same κ-independent flat-centroid
1210    // base, so the criterion is a clean 1-D function of κ.
1211    let mut v_p = |kappa: f64| -> Result<f64, String> {
1212        response_curvature_criterion(values, dim, kappa).map(|(v, _)| v)
1213    };
1214
1215    // ── κ̂: golden-section minimisation inside the chart bracket. ────────────
1216    // The dispersion criterion is smooth and unimodal in practice; golden
1217    // section is derivative-free and respects the bracket bounds exactly.
1218    const GOLDEN_INV: f64 = 0.618_033_988_749_894_8; // 1/φ
1219    let mut a = kappa_min;
1220    let mut b = kappa_max;
1221    let mut c = b - GOLDEN_INV * (b - a);
1222    let mut d_pt = a + GOLDEN_INV * (b - a);
1223    let mut fc = v_p(c)?;
1224    let mut fd = v_p(d_pt)?;
1225    let ktol = (tol * (kappa_max - kappa_min)).max(tol).max(1.0e-12);
1226    for _ in 0..max_iter {
1227        if (b - a).abs() <= ktol {
1228            break;
1229        }
1230        if fc < fd {
1231            b = d_pt;
1232            d_pt = c;
1233            fd = fc;
1234            c = b - GOLDEN_INV * (b - a);
1235            fc = v_p(c)?;
1236        } else {
1237            a = c;
1238            c = d_pt;
1239            fc = fd;
1240            d_pt = a + GOLDEN_INV * (b - a);
1241            fd = v_p(d_pt)?;
1242        }
1243    }
1244    let kappa_hat = 0.5 * (a + b);
1245    let (v_p_hat, base) = response_curvature_criterion(values, dim, kappa_hat)?;
1246
1247    // ── Honest chart-resolution-rail detection. ─────────────────────────────
1248    // The spherical cap κ_max is the curvature at which the cloud's geodesic
1249    // spread ρ_max fills `(0.9π)²` of the conjugate shell — i.e. the cloud nearly
1250    // fills the sphere S^d(1/√κ_max). When the criterion's optimum sits AT that
1251    // cap (the data want κ ≥ κ_max, but the chart cannot resolve a sphere smaller
1252    // than the cloud), the search converges onto the upper bracket and κ̂ ≈ κ_max
1253    // is NOT a resolved point estimate — it is a lower bound on |κ|. We flag this
1254    // so the caller reports "curvature exceeds chart-resolvable range at this
1255    // scale" instead of silently quoting κ̂ / ci_hi as if interior. The detection
1256    // is scale-free: it triggers when κ̂ lands within the final golden-section
1257    // resolution of κ_max (the dimensionless product κ̂·ρ_max² ↗ (0.9π)²), never
1258    // by an absolute κ threshold. The hyperbolic side has no conjugate radius, so
1259    // only the spherical (upper) cap can rail this way.
1260    let span = kappa_max - kappa_min;
1261    let rail_margin = (0.02 * span).max(ktol);
1262    let railed_at_resolution_limit = kappa_hat >= kappa_max - rail_margin;
1263
1264    // Dimensionless scale-free invariant κ̂·r²: the geometric content the cloud
1265    // actually determines (invariant under y ↦ αy). r = ρ_max is the κ=0 doubled-
1266    // gauge characteristic radius; for a degenerate (point) cloud r = 0 and the
1267    // product is 0 (κ unidentified). This is what the caller should report as the
1268    // honest "how curved relative to its spread" number alongside the dimensional κ̂.
1269    let kappa_r2 = kappa_hat * rho_max * rho_max;
1270
1271    // Exact outer curvature V_p''(κ̂) by a central second difference, on a step
1272    // scaled to the bracket; only used to size the Wald bracket of the CI walk.
1273    let h = (1.0e-3 * (kappa_max - kappa_min)).max(1.0e-6);
1274    let v_pp = if (kappa_hat - h) > kappa_min && (kappa_hat + h) < kappa_max {
1275        let vp = v_p(kappa_hat + h)?;
1276        let vm = v_p(kappa_hat - h)?;
1277        (vp - 2.0 * v_p_hat + vm) / (h * h)
1278    } else {
1279        // Near a bound: leave it to the walk's default step.
1280        f64::NAN
1281    };
1282
1283    let profile_ci = crate::curvature_estimand::profile_ci_walk(
1284        &mut v_p, kappa_hat, v_pp, kappa_min, kappa_max, level, ktol,
1285    )?;
1286    let flatness = crate::curvature_estimand::flatness_lr_test(&mut v_p, kappa_hat)?;
1287
1288    // The sign of κ̂ is statistically resolved iff the profile CI excludes 0 — the
1289    // CI is the honest sign-bearing summary (it reports Flat under-resolution rather
1290    // than a confident wrong sign), so we mirror its verdict onto the point-estimate
1291    // surface. Below the resolvable `κ·r²` floor (`|κ·r²| ≪ 1`) the bare κ̂ argmin can
1292    // flip sign on Monte-Carlo noise, so `false` here means "do not quote κ̂'s sign".
1293    let sign_resolved = !matches!(
1294        profile_ci.verdict,
1295        crate::curvature_estimand::CurvatureVerdict::Flat
1296    );
1297
1298    Ok(ResponseCurvatureFit {
1299        dim,
1300        kappa_hat,
1301        kappa_r2,
1302        characteristic_radius: rho_max,
1303        railed_at_resolution_limit,
1304        sign_resolved,
1305        base,
1306        v_p_hat,
1307        profile_ci,
1308        flatness,
1309    })
1310}
1311
1312#[cfg(test)]
1313mod tests {
1314    use super::*;
1315    use ndarray::{Array2, array};
1316
1317    fn round_trip(manifold: ResponseManifold, values: Array2<f64>) {
1318        let base =
1319            response_frechet_mean(manifold, values.view(), None, 1e-12, 500).expect("frechet mean");
1320        let tangent = response_log_map(manifold, values.view(), base.view()).expect("log map");
1321        let back = response_exp_map(manifold, tangent.view(), base.view()).expect("exp map");
1322        for row in 0..values.nrows() {
1323            for col in 0..values.ncols() {
1324                assert!(
1325                    (back[[row, col]] - values[[row, col]]).abs() < 1e-6,
1326                    "{manifold:?} exp∘log mismatch at ({row},{col}): {} vs {}",
1327                    back[[row, col]],
1328                    values[[row, col]]
1329                );
1330            }
1331        }
1332    }
1333
1334    #[test]
1335    fn spd_round_trip_and_mean() {
1336        // Three 2×2 SPD matrices, row-major flat.
1337        let values = array![
1338            [2.0, 0.0, 0.0, 1.0],
1339            [1.0, 0.3, 0.3, 2.0],
1340            [3.0, -0.5, -0.5, 1.5],
1341        ];
1342        round_trip(ResponseManifold::Spd { n: 2 }, values);
1343    }
1344
1345    #[test]
1346    fn grassmann_round_trip_and_mean() {
1347        // Gr(1, 3): unit columns (lines through the origin), n·k = 3 flat.
1348        let values = array![[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.6, 0.8, 0.0],];
1349        round_trip(ResponseManifold::Grassmann { k: 1, n: 3 }, values);
1350    }
1351
1352    #[test]
1353    fn stiefel_round_trip_and_mean() {
1354        // St(1, 3): unit 1-frames in ℝ³ (== sphere S²).
1355        let values = array![[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.6, 0.8],];
1356        round_trip(ResponseManifold::Stiefel { k: 1, n: 3 }, values);
1357    }
1358
1359    #[test]
1360    fn poincare_round_trip_and_mean() {
1361        let values = array![[0.1, 0.2], [-0.3, 0.1], [0.2, -0.25],];
1362        round_trip(
1363            ResponseManifold::Poincare {
1364                dim: 2,
1365                curvature: -1.0,
1366            },
1367            values,
1368        );
1369    }
1370
1371    #[test]
1372    fn resolver_rejects_bad_shapes() {
1373        assert!(ResponseManifold::resolve("grassmann", Some(2), Some(3), None, None).is_err());
1374        assert!(ResponseManifold::resolve("spd", None, None, None, None).is_err());
1375        assert!(ResponseManifold::resolve("poincare", None, None, Some(2), Some(1.0)).is_err());
1376        assert!(ResponseManifold::resolve("nonsense", None, None, None, None).is_err());
1377        assert_eq!(
1378            ResponseManifold::resolve("spd", Some(3), None, None, None).unwrap(),
1379            ResponseManifold::Spd { n: 3 }
1380        );
1381    }
1382
1383    #[test]
1384    fn parse_infers_shapes_from_columns() {
1385        // SPD: n from the perfect-square column count.
1386        assert_eq!(
1387            ResponseManifold::parse("spd", 9).unwrap(),
1388            ResponseManifold::Spd { n: 3 }
1389        );
1390        assert!(ResponseManifold::parse("spd", 8).is_err());
1391        // Grassmann/Stiefel: n inferred as cols / k.
1392        assert_eq!(
1393            ResponseManifold::parse("grassmann(k=2)", 10).unwrap(),
1394            ResponseManifold::Grassmann { k: 2, n: 5 }
1395        );
1396        assert_eq!(
1397            ResponseManifold::parse("Stiefel( k = 2 , n = 4 )", 8).unwrap(),
1398            ResponseManifold::Stiefel { k: 2, n: 4 }
1399        );
1400        assert!(ResponseManifold::parse("grassmann", 10).is_err());
1401        assert!(ResponseManifold::parse("grassmann(k=3)", 10).is_err());
1402        // Poincaré: dim = cols, default curvature -1.
1403        assert_eq!(
1404            ResponseManifold::parse("poincare", 3).unwrap(),
1405            ResponseManifold::Poincare {
1406                dim: 3,
1407                curvature: -1.0
1408            }
1409        );
1410        assert_eq!(
1411            ResponseManifold::parse("poincare(curvature=-0.5)", 3).unwrap(),
1412            ResponseManifold::Poincare {
1413                dim: 3,
1414                curvature: -0.5
1415            }
1416        );
1417        assert!(ResponseManifold::parse("hyperbolic", 3).is_err());
1418    }
1419
1420    #[test]
1421    fn dispatch_round_trips_through_user_label() {
1422        // Drive the full string-selected user path for each geometry: parse the
1423        // label, build the intrinsic base, log to the tangent, exp back.
1424        let cases: Vec<(&str, Array2<f64>)> = vec![
1425            (
1426                "spd",
1427                array![
1428                    [2.0, 0.0, 0.0, 1.0],
1429                    [1.0, 0.3, 0.3, 2.0],
1430                    [3.0, -0.5, -0.5, 1.5],
1431                ],
1432            ),
1433            (
1434                "grassmann(k=1)",
1435                array![[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.6, 0.8, 0.0]],
1436            ),
1437            (
1438                "stiefel(k=1)",
1439                array![[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.6, 0.8]],
1440            ),
1441            ("poincare", array![[0.1, 0.2], [-0.3, 0.1], [0.2, -0.25]]),
1442        ];
1443        for (label, values) in cases {
1444            let (tangent, base, canonical) =
1445                dispatch_log_map(values.view(), label, None).expect("dispatch log");
1446            assert!(canonical.starts_with(label.split('(').next().unwrap()));
1447            let back = dispatch_exp_map(tangent.view(), label, base.view()).expect("dispatch exp");
1448            for row in 0..values.nrows() {
1449                for col in 0..values.ncols() {
1450                    assert!(
1451                        (back[[row, col]] - values[[row, col]]).abs() < 1e-6,
1452                        "{label} exp∘log mismatch at ({row},{col}): {} vs {}",
1453                        back[[row, col]],
1454                        values[[row, col]]
1455                    );
1456                }
1457            }
1458        }
1459    }
1460
1461    #[test]
1462    fn ambient_dim_matches_layout() {
1463        assert_eq!(ResponseManifold::Spd { n: 3 }.ambient_dim(), 9);
1464        assert_eq!(ResponseManifold::Grassmann { k: 2, n: 5 }.ambient_dim(), 10);
1465        assert_eq!(ResponseManifold::Stiefel { k: 2, n: 4 }.ambient_dim(), 8);
1466        assert_eq!(
1467            ResponseManifold::Poincare {
1468                dim: 4,
1469                curvature: -1.0
1470            }
1471            .ambient_dim(),
1472            4
1473        );
1474    }
1475
1476    /// Deterministic xorshift64* + Box–Muller standard normals — a dependency-free
1477    /// reproducible source for the synthetic known-κ clouds. Seeded per call so
1478    /// the test is bit-stable across runs and platforms.
1479    struct DetNormal {
1480        state: u64,
1481        spare: Option<f64>,
1482    }
1483    impl DetNormal {
1484        fn new(seed: u64) -> Self {
1485            Self {
1486                state: seed | 1,
1487                spare: None,
1488            }
1489        }
1490        fn u01(&mut self) -> f64 {
1491            // xorshift64*; take the top 53 bits as a (0,1) double.
1492            let mut x = self.state;
1493            x ^= x >> 12;
1494            x ^= x << 25;
1495            x ^= x >> 27;
1496            self.state = x;
1497            let v = x.wrapping_mul(0x2545_F491_4F6C_DD1D);
1498            ((v >> 11) as f64 + 0.5) / (1u64 << 53) as f64
1499        }
1500        fn normal(&mut self) -> f64 {
1501            if let Some(z) = self.spare.take() {
1502                return z;
1503            }
1504            // Box–Muller; clamp u1 away from 0 so ln is finite.
1505            let u1 = self.u01().max(1e-12);
1506            let u2 = self.u01();
1507            let r = (-2.0 * u1.ln()).sqrt();
1508            let theta = 2.0 * std::f64::consts::PI * u2;
1509            self.spare = Some(r * theta.sin());
1510            r * theta.cos()
1511        }
1512    }
1513
1514    /// Build a synthetic cloud at known curvature `k_star`: `n` points whose
1515    /// geodesic normal coordinates about `center` are i.i.d. isotropic Gaussian
1516    /// of scale `sigma`, exp-mapped onto `M_{k_star}`, then mean-centred in the
1517    /// ambient chart to mimic the real (mean-subtracted) response clouds.
1518    fn synth_cloud(dim: usize, k_star: f64, n: usize, sigma: f64, seed: u64) -> Array2<f64> {
1519        let manifold = ResponseManifold::ConstantCurvature { dim, kappa: k_star };
1520        let center = Array1::<f64>::zeros(dim);
1521        let mut rng = DetNormal::new(seed);
1522        let mut values = Array2::<f64>::zeros((n, dim));
1523        for i in 0..n {
1524            let t: Array1<f64> = (0..dim).map(|_| sigma * rng.normal()).collect();
1525            let y = manifold
1526                .exp_point(center.view(), t.view())
1527                .expect("exp tangent to response");
1528            values.row_mut(i).assign(&y);
1529        }
1530        // Mean-centre in the ambient chart (the real-data preprocessing).
1531        let mut mean = Array1::<f64>::zeros(dim);
1532        for row in values.outer_iter() {
1533            mean += &row;
1534        }
1535        mean.mapv_inplace(|v| v / n as f64);
1536        for mut row in values.outer_iter_mut() {
1537            row -= &mean;
1538        }
1539        values
1540    }
1541
1542    /// The #1104 reparameterisation-invariant curvature estimator: on synthetic
1543    /// clouds generated at known κ⋆ the fitted κ̂ must be (a) INTERIOR to the
1544    /// chart bracket (never railed), (b) close to κ⋆ and MONOTONE in κ⋆, (c)
1545    /// produce a smooth (non-degenerate) χ²₁ flatness p-value that does not reject
1546    /// the flat truth, and (d) be correctly COVARIANT under a global rescaling of
1547    /// the cloud (κ has units 1/length², so `y ↦ α y ⇒ κ̂ ↦ κ̂/α²`).
1548    #[test]
1549    fn fit_response_curvature_is_reparameterization_invariant() {
1550        let dim = 3usize;
1551        // Unit-ish scale: σ=0.15 keeps every geodesic radius (≈ a few·σ) well
1552        // inside the κ-stereographic chart for the most hyperbolic κ⋆ = −1.5
1553        // (chart needs ‖y‖² < 1/1.5 ≈ 0.667).
1554        let sigma = 0.15;
1555        let n = 300usize;
1556        let k_stars = [-1.5_f64, -0.5, 0.0, 0.6, 1.2];
1557        let mut k_hats = Vec::new();
1558        for (idx, &k_star) in k_stars.iter().enumerate() {
1559            let values = synth_cloud(dim, k_star, n, sigma, 0xC0FFEE ^ (idx as u64 + 1));
1560            let (kmin, kmax, _rho) = response_kappa_bounds(values.view());
1561            let fit = fit_response_curvature(values.view(), dim, 0.95, 1e-12, 256)
1562                .expect("response curvature fit");
1563            k_hats.push(fit.kappa_hat);
1564
1565            // (a) INTERIOR: κ̂ strictly inside the bracket, not railed to either end.
1566            let span = kmax - kmin;
1567            assert!(
1568                fit.kappa_hat > kmin + 0.02 * span && fit.kappa_hat < kmax - 0.02 * span,
1569                "κ⋆={k_star}: κ̂={} railed to bracket [{kmin}, {kmax}]",
1570                fit.kappa_hat
1571            );
1572
1573            // (b-direct) recovery within a sane tolerance (finite-sample bias is
1574            // O(1/n); the estimator only needs the right region and sign).
1575            assert!(
1576                (fit.kappa_hat - k_star).abs() <= 0.6 + 0.3 * k_star.abs(),
1577                "κ⋆={k_star}: κ̂={} too far",
1578                fit.kappa_hat
1579            );
1580
1581            // (c) the profile CI is a valid interval bracketing κ̂.
1582            assert!(
1583                fit.profile_ci.ci_lo <= fit.kappa_hat && fit.kappa_hat <= fit.profile_ci.ci_hi,
1584                "κ⋆={k_star}: CI [{}, {}] excludes κ̂={}",
1585                fit.profile_ci.ci_lo,
1586                fit.profile_ci.ci_hi,
1587                fit.kappa_hat
1588            );
1589            // The flatness LR statistic and p-value are valid; the p-value is a
1590            // genuine probability strictly between 0 and 1 (smooth, not 0/1).
1591            assert!(fit.flatness.lr_stat >= 0.0);
1592            assert!(
1593                fit.flatness.p_value > 0.0 && fit.flatness.p_value < 1.0,
1594                "κ⋆={k_star}: degenerate flatness p={}",
1595                fit.flatness.p_value
1596            );
1597            // The flat truth κ⋆ = 0 must NOT be rejected at 5% (lr < χ²_{1,.95}).
1598            if k_star == 0.0 {
1599                assert!(
1600                    fit.flatness.lr_stat < 3.84,
1601                    "flat truth wrongly rejected: lr={}",
1602                    fit.flatness.lr_stat
1603                );
1604            }
1605
1606            // (d) RESCALING COVARIANCE: scale the SAME cloud by α and refit; κ̂
1607            // must transform as κ̂/α² (curvature has units 1/length²). We reuse the
1608            // identical points so the only change is the global scale.
1609            let alpha = 1.5_f64;
1610            let scaled = values.mapv(|v| alpha * v);
1611            let fit_scaled = fit_response_curvature(scaled.view(), dim, 0.95, 1e-12, 256)
1612                .expect("scaled response curvature fit");
1613            let expected = fit.kappa_hat / (alpha * alpha);
1614            // Tolerance scales with magnitude; the transform is exact in the
1615            // criterion (V(κ, αy) = V(α²κ, y)) up to the finite golden-section /
1616            // bracket discretisation.
1617            assert!(
1618                (fit_scaled.kappa_hat - expected).abs() <= 0.05 + 0.05 * expected.abs(),
1619                "κ⋆={k_star}: rescale covariance broken: κ̂(αy)={} vs κ̂(y)/α²={}",
1620                fit_scaled.kappa_hat,
1621                expected
1622            );
1623        }
1624
1625        // (b-monotone) κ̂ is monotone increasing in κ⋆ across the whole sweep.
1626        for w in k_hats.windows(2) {
1627            assert!(w[1] > w[0] - 0.05, "κ̂ not monotone in κ⋆: {:?}", k_hats);
1628        }
1629    }
1630
1631    /// d = 1 carries REDUCED curvature information: the transverse volume
1632    /// Jacobian is identically 1 (radial isometry), so κ is identified by the
1633    /// conformal-factor restoring force `−d·Σ ln λ_{y_i}` alone (#944 power
1634    /// analysis). The estimator must still run end-to-end, return an INTERIOR
1635    /// κ̂, and produce a valid CI — never divide/exponentiate the absent
1636    /// transverse direction.
1637    #[test]
1638    fn fit_response_curvature_d1_uses_conformal_term_only() {
1639        let sigma = 0.12;
1640        let n = 400usize;
1641        for &k_star in &[-1.0_f64, 0.0, 0.8] {
1642            let values = synth_cloud(1, k_star, n, sigma, 0xD1 ^ (k_star.to_bits()));
1643            let (kmin, kmax, _rho) = response_kappa_bounds(values.view());
1644            let fit = fit_response_curvature(values.view(), 1, 0.95, 1e-12, 256)
1645                .expect("d=1 curvature fit");
1646            let span = kmax - kmin;
1647            assert!(
1648                fit.kappa_hat > kmin + 0.01 * span && fit.kappa_hat < kmax - 0.01 * span,
1649                "d=1 κ⋆={k_star}: κ̂={} railed to [{kmin},{kmax}]",
1650                fit.kappa_hat
1651            );
1652            assert!(
1653                fit.profile_ci.ci_lo <= fit.kappa_hat && fit.kappa_hat <= fit.profile_ci.ci_hi,
1654                "d=1 κ⋆={k_star}: CI excludes κ̂"
1655            );
1656            assert!(fit.kappa_hat.is_finite() && fit.v_p_hat.is_finite());
1657        }
1658    }
1659
1660    /// The criterion guard must reject κ probes AT or PAST the chart boundary
1661    /// gracefully (an `Err`, never a panic / NaN): on the hyperbolic edge
1662    /// `1 + κ‖y‖² ≤ 0` and on the spherical antipode. The `response_kappa_bounds`
1663    /// bracket stays strictly interior, but a stray CI/LR probe can land on the
1664    /// edge, so the criterion itself must be defensive.
1665    #[test]
1666    fn response_curvature_criterion_rejects_boundary_probes() {
1667        // A cloud with a known max radius R²; the hyperbolic edge is κ = −1/R².
1668        let values = array![[0.5_f64, 0.0], [-0.4, 0.3], [0.1, -0.5]];
1669        let r2_max = values
1670            .outer_iter()
1671            .map(|r| r.dot(&r))
1672            .fold(0.0_f64, f64::max);
1673        // Exactly on / past the hyperbolic edge: 1 + κ‖y‖² = 0 (or < 0).
1674        let kappa_edge = -1.0 / r2_max;
1675        assert!(
1676            response_curvature_criterion(values.view(), 2, kappa_edge).is_err(),
1677            "criterion must reject the hyperbolic chart edge κ=−1/R²"
1678        );
1679        assert!(
1680            response_curvature_criterion(values.view(), 2, 1.5 * kappa_edge).is_err(),
1681            "criterion must reject past the hyperbolic chart edge"
1682        );
1683        // Interior κ just inside the edge succeeds and is finite.
1684        let (v, _) = response_curvature_criterion(values.view(), 2, 0.9 * kappa_edge)
1685            .expect("interior κ valid");
1686        assert!(v.is_finite());
1687        // Non-finite κ is rejected up front.
1688        assert!(response_curvature_criterion(values.view(), 2, f64::NAN).is_err());
1689        assert!(response_curvature_criterion(values.view(), 2, f64::INFINITY).is_err());
1690    }
1691
1692    // ── Projection residual (distance to candidate manifold) ───────────────
1693
1694    #[test]
1695    fn projection_residual_is_zero_for_on_manifold_points() {
1696        // On-manifold rows are their own nearest point, so the residual is ~0
1697        // row-wise. No base point / Fréchet mean is involved — projection is
1698        // base-independent — so this no longer depends on the inputs forming an
1699        // admissible Karcher seed.
1700        let cases: Vec<(ResponseManifold, Array2<f64>)> = vec![
1701            (
1702                ResponseManifold::Spd { n: 2 }, // PD: eigenvalues {2,1} and {2,1}
1703                array![[2.0, 0.0, 0.0, 1.0], [1.5, 0.5, 0.5, 1.5]],
1704            ),
1705            (
1706                ResponseManifold::Grassmann { k: 1, n: 3 }, // unit columns
1707                array![[1.0, 0.0, 0.0], [0.6, 0.8, 0.0]],
1708            ),
1709            (
1710                ResponseManifold::Poincare {
1711                    dim: 2,
1712                    curvature: -1.0,
1713                }, // strictly inside the ball
1714                array![[0.1, 0.2], [-0.3, 0.1]],
1715            ),
1716        ];
1717        for (manifold, values) in cases {
1718            let (resid, rel) =
1719                response_projection_residual(manifold, values.view()).expect("projection residual");
1720            for row in 0..values.nrows() {
1721                assert!(
1722                    resid[row] < 1e-9,
1723                    "{manifold:?} on-manifold row {row} should have ~0 residual, got {}",
1724                    resid[row]
1725                );
1726                assert!(rel[row] < 1e-9 && rel[row] >= 0.0);
1727            }
1728        }
1729    }
1730
1731    #[test]
1732    fn projection_residual_recovers_known_off_manifold_displacement() {
1733        // Closed-form checks against the exact nearest-point distance.
1734
1735        // Gr(1,3) / sphere: nearest unit vector to x is x/‖x‖, so the distance
1736        // is |‖x‖ − 1|. [2,0,0] ⇒ 1; [0,3,0] ⇒ 2. Relative = dist/‖x‖.
1737        let g = ResponseManifold::Grassmann { k: 1, n: 3 };
1738        let gv = array![[2.0, 0.0, 0.0], [0.0, 3.0, 0.0]];
1739        let (gres, grel) = response_projection_residual(g, gv.view()).expect("grassmann");
1740        assert!((gres[0] - 1.0).abs() < 1e-12, "got {}", gres[0]);
1741        assert!((gres[1] - 2.0).abs() < 1e-12, "got {}", gres[1]);
1742        assert!((grel[0] - 0.5).abs() < 1e-12);
1743        assert!((grel[1] - 2.0 / 3.0).abs() < 1e-12);
1744
1745        // SPD(2): nearest PSD matrix clamps negative eigenvalues to 0, so the
1746        // distance is the norm of the discarded negative part. [[1,0],[0,-1]]
1747        // has eigenvalue −1 discarded ⇒ distance 1; ‖x‖_F = √2.
1748        let s = ResponseManifold::Spd { n: 2 };
1749        let sv = array![[1.0, 0.0, 0.0, -1.0]];
1750        let (sres, srel) = response_projection_residual(s, sv.view()).expect("spd");
1751        assert!((sres[0] - 1.0).abs() < 1e-9, "got {}", sres[0]);
1752        assert!((srel[0] - 1.0 / 2.0_f64.sqrt()).abs() < 1e-9);
1753
1754        // Poincaré ball (c = −1, true radius R = 1): the distance to the open
1755        // ball is max(0, ‖x‖ − R). [3,0] ⇒ exactly 2 (not 3 − (1 − BOUNDARY_EPS)
1756        // — the diagnostic uses the manifold radius, not the safety radius).
1757        let p = ResponseManifold::Poincare {
1758            dim: 2,
1759            curvature: -1.0,
1760        };
1761        let pv = array![[3.0, 0.0]];
1762        let (pres, _prel) = response_projection_residual(p, pv.view()).expect("poincare");
1763        assert!((pres[0] - 2.0).abs() < 1e-12, "got {}", pres[0]);
1764
1765        // A different curvature (c = −4, R = 1/2): [2,0] ⇒ 2 − 0.5 = 1.5.
1766        let p4 = ResponseManifold::Poincare {
1767            dim: 2,
1768            curvature: -4.0,
1769        };
1770        let (p4res, _) =
1771            response_projection_residual(p4, array![[2.0, 0.0]].view()).expect("poincare c=-4");
1772        assert!((p4res[0] - 1.5).abs() < 1e-12, "got {}", p4res[0]);
1773    }
1774
1775    #[test]
1776    fn projection_residual_validates_shapes_and_finiteness() {
1777        let manifold = ResponseManifold::Spd { n: 2 }; // ambient = 4
1778        // Wrong column count.
1779        let bad_cols = array![[1.0, 2.0, 3.0]];
1780        assert!(response_projection_residual(manifold, bad_cols.view()).is_err());
1781        // Non-finite value.
1782        let nan_vals = array![[f64::NAN, 0.0, 0.0, 1.0]];
1783        assert!(response_projection_residual(manifold, nan_vals.view()).is_err());
1784        let inf_vals = array![[f64::INFINITY, 0.0, 0.0, 1.0]];
1785        assert!(response_projection_residual(manifold, inf_vals.view()).is_err());
1786    }
1787
1788    #[test]
1789    fn projection_residual_separates_on_and_off_manifold() {
1790        // The motivating case, now honestly answered: an on-manifold row sits
1791        // at zero distance from the candidate shape; a row pushed off it has a
1792        // clearly positive distance. This is the shape-plausibility signal that
1793        // gates which topology is worth fitting — not the post-fit membership
1794        // decision, which comes from the fitted surface's residual instead.
1795        let manifold = ResponseManifold::Grassmann { k: 1, n: 3 };
1796        let on = array![[0.6, 0.8, 0.0]]; // a genuine unit direction
1797        let off = array![[0.6, 0.8, 1.4]]; // same direction, pushed off-sphere
1798
1799        let (resid_on, _) = response_projection_residual(manifold, on.view()).expect("on");
1800        let (resid_off, _) = response_projection_residual(manifold, off.view()).expect("off");
1801
1802        assert!(
1803            resid_on[0] < 1e-9,
1804            "on-manifold should be ~0, got {}",
1805            resid_on[0]
1806        );
1807        assert!(
1808            resid_off[0] > 1e-2 && resid_off[0] > resid_on[0],
1809            "off-manifold distance ({}) must clearly exceed on-manifold ({})",
1810            resid_off[0],
1811            resid_on[0]
1812        );
1813    }
1814
1815    #[test]
1816    fn projection_residual_supports_k_greater_than_one_frames() {
1817        // k > 1 frames use the closed form √Σ(σ_i − 1)². St(2,3), ambient = 6,
1818        // row-major n×k.
1819        let manifold = ResponseManifold::Stiefel { k: 2, n: 3 };
1820
1821        // An orthonormal frame [e1 | e2] is its own nearest point ⇒ residual 0.
1822        let on = array![[1.0, 0.0, 0.0, 1.0, 0.0, 0.0]];
1823        let (resid_on, _) = response_projection_residual(manifold, on.view()).expect("on");
1824        assert!(
1825            resid_on[0] < 1e-9,
1826            "orthonormal frame should be ~0, got {}",
1827            resid_on[0]
1828        );
1829
1830        // Scale the first column by 2: Y = [2·e1 | e2]. YᵀY = diag(4,1) ⇒
1831        // σ = (2,1), distance √((2−1)²+(1−1)²) = 1, relative = 1/‖Y‖_F = 1/√5.
1832        let off = array![[2.0, 0.0, 0.0, 1.0, 0.0, 0.0]];
1833        let (resid_off, rel_off) = response_projection_residual(manifold, off.view()).expect("off");
1834        assert!((resid_off[0] - 1.0).abs() < 1e-9, "got {}", resid_off[0]);
1835        assert!(
1836            (rel_off[0] - 1.0 / 5.0_f64.sqrt()).abs() < 1e-9,
1837            "got {}",
1838            rel_off[0]
1839        );
1840
1841        // Grassmann(2,4) gives the identical score for the same frame data.
1842        let g = ResponseManifold::Grassmann { k: 2, n: 4 };
1843        let g_on = array![[1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]];
1844        let (g_resid, _) = response_projection_residual(g, g_on.view()).expect("grassmann");
1845        assert!(g_resid[0] < 1e-9, "got {}", g_resid[0]);
1846    }
1847
1848    #[test]
1849    fn projection_residual_handles_nontrivial_eigenvectors() {
1850        // A frame whose Gram is NOT diagonal, so the singular values come from a
1851        // genuine eigendecomposition. Y = [[1,1],[0,1],[0,0]] (St(2,3)):
1852        // YᵀY = [[1,1],[1,2]], eigenvalues (3±√5)/2, σ = ((1+√5)/2, (√5−1)/2).
1853        // distance² = (σ₁−1)² + (σ₂−1)².
1854        let manifold = ResponseManifold::Stiefel { k: 2, n: 3 };
1855        let y = array![[1.0, 1.0, 0.0, 1.0, 0.0, 0.0]]; // row-major rows [1,1],[0,1],[0,0]
1856        let (resid, _) = response_projection_residual(manifold, y.view()).expect("frame");
1857        let s5 = 5.0_f64.sqrt();
1858        let sig1 = (1.0 + s5) / 2.0;
1859        let sig2 = (s5 - 1.0) / 2.0;
1860        let expect = ((sig1 - 1.0).powi(2) + (sig2 - 1.0).powi(2)).sqrt();
1861        assert!(
1862            (resid[0] - expect).abs() < 1e-9,
1863            "got {} want {}",
1864            resid[0],
1865            expect
1866        );
1867    }
1868
1869    #[test]
1870    fn projection_residual_is_defined_for_rank_deficient_frames() {
1871        // A rank-deficient frame has a well-defined distance even though the
1872        // nearest orthonormal frame is not unique — distance to a compact set is
1873        // always defined, so this must NOT error. Two identical columns e1 give
1874        // YᵀY = [[1,1],[1,1]], σ = (√2, 0), distance √((√2−1)²+(0−1)²) = √(4−2√2).
1875        let manifold = ResponseManifold::Stiefel { k: 2, n: 3 };
1876        let degenerate = array![[1.0, 1.0, 0.0, 0.0, 0.0, 0.0]]; // both columns = e1
1877        let (resid, _) =
1878            response_projection_residual(manifold, degenerate.view()).expect("rank-deficient ok");
1879        let expect = (4.0 - 2.0 * 2.0_f64.sqrt()).sqrt(); // ≈ 1.0823922
1880        assert!(
1881            (resid[0] - expect).abs() < 1e-9,
1882            "got {} want {}",
1883            resid[0],
1884            expect
1885        );
1886
1887        // Minimal case: zero vector on the sphere (Gr(1,3)). Every unit vector is
1888        // a nearest point and the distance is exactly 1 — also must not error.
1889        let sphere = ResponseManifold::Grassmann { k: 1, n: 3 };
1890        let (zres, _) =
1891            response_projection_residual(sphere, array![[0.0, 0.0, 0.0]].view()).expect("zero");
1892        assert!((zres[0] - 1.0).abs() < 1e-12, "got {}", zres[0]);
1893    }
1894
1895    #[test]
1896    fn projection_residual_handles_tiny_full_rank_frame() {
1897        // A tiny but full-rank frame must NOT be rejected as rank-deficient: the
1898        // distance is scale-correct. Y = 1e-7·[e1 | e2] (St(2,3)) ⇒ σ = (1e-7,
1899        // 1e-7), distance √2·(1 − 1e-7) ≈ 1.41421342.
1900        let manifold = ResponseManifold::Stiefel { k: 2, n: 3 };
1901        let tiny = array![[1e-7, 0.0, 0.0, 1e-7, 0.0, 0.0]];
1902        let (resid, _) = response_projection_residual(manifold, tiny.view()).expect("tiny ok");
1903        let expect = 2.0_f64.sqrt() * (1.0 - 1e-7);
1904        assert!(
1905            (resid[0] - expect).abs() < 1e-9,
1906            "got {} want {}",
1907            resid[0],
1908            expect
1909        );
1910    }
1911
1912    #[test]
1913    fn projection_residual_spd_nonsymmetric_and_singular() {
1914        // Non-symmetric input: A = [[1,1],[-1,1]] has sym(A) = I (no negative
1915        // part), but the distance to the PSD cone still counts the skew part:
1916        // ‖A − I‖_F = √2.
1917        let spd = ResponseManifold::Spd { n: 2 };
1918        let asym = array![[1.0, 1.0, -1.0, 1.0]]; // row-major [[1,1],[-1,1]]
1919        let (ares, _) = response_projection_residual(spd, asym.view()).expect("nonsym");
1920        assert!((ares[0] - 2.0_f64.sqrt()).abs() < 1e-9, "got {}", ares[0]);
1921
1922        // A singular PSD matrix diag(1,0) is in the closed cone ⇒ distance 0
1923        // (even though it is not strictly positive definite).
1924        let singular = array![[1.0, 0.0, 0.0, 0.0]];
1925        let (sres, _) = response_projection_residual(spd, singular.view()).expect("singular psd");
1926        assert!(
1927            sres[0] < 1e-12,
1928            "singular PSD should be ~0, got {}",
1929            sres[0]
1930        );
1931    }
1932
1933    #[test]
1934    fn projection_residual_poincare_interior_shell_is_zero() {
1935        // A point in the numerical safety shell R_safe < ‖x‖ < R is a genuine
1936        // interior point of the manifold ball, so it must score exactly 0 — the
1937        // diagnostic uses the true radius, not the projection safety radius.
1938        let p = ResponseManifold::Poincare {
1939            dim: 2,
1940            curvature: -1.0,
1941        };
1942        let shell = array![[0.999999, 0.0]]; // inside R = 1, outside R_safe ≈ 0.99999
1943        let (resid, _) = response_projection_residual(p, shell.view()).expect("shell");
1944        assert!(
1945            resid[0] < 1e-12,
1946            "interior point must be 0, got {}",
1947            resid[0]
1948        );
1949    }
1950
1951    #[test]
1952    fn projection_residual_handles_constant_curvature_domain() {
1953        // ConstantCurvature is a fittable response geometry produced by the
1954        // resolver/parser, so it must return a closed-form distance, not error.
1955        // κ ≥ 0: chart is all of ℝ^d ⇒ every finite row scores 0.
1956        let pos = ResponseManifold::parse("constant_curvature(dim=3,kappa=1.0)", 3)
1957            .expect("parse constant_curvature");
1958        assert!(matches!(pos, ResponseManifold::ConstantCurvature { .. }));
1959        let (pres, _) =
1960            response_projection_residual(pos, array![[0.1, 9.0, -100.0]].view()).expect("kappa>=0");
1961        assert!(pres[0] < 1e-12, "κ≥0 finite row must be 0, got {}", pres[0]);
1962
1963        // κ < 0: chart is the ball of radius 1/√(−κ). For κ = −1, R = 1, so a
1964        // point of norm 3 is at distance 2; an interior point is at 0.
1965        let neg = ResponseManifold::ConstantCurvature {
1966            dim: 2,
1967            kappa: -1.0,
1968        };
1969        let (nres, _) = response_projection_residual(neg, array![[3.0, 0.0], [0.2, 0.1]].view())
1970            .expect("kappa<0");
1971        assert!((nres[0] - 2.0).abs() < 1e-12, "got {}", nres[0]);
1972        assert!(nres[1] < 1e-12, "interior row must be 0, got {}", nres[1]);
1973    }
1974
1975    #[test]
1976    fn projection_residual_accepts_empty_batch() {
1977        // A zero-row batch is valid and returns empty arrays for every geometry.
1978        let manifold = ResponseManifold::Spd { n: 2 }; // ambient = 4
1979        let empty = Array2::<f64>::zeros((0, 4));
1980        let (resid, rel) = response_projection_residual(manifold, empty.view()).expect("empty");
1981        assert_eq!(resid.len(), 0);
1982        assert_eq!(rel.len(), 0);
1983    }
1984}