#![cfg(test)]
use super::*;
use crate::manifold::tests_gauge_frame_roundtrip_2720::planted_circle_cloud;
#[derive(Debug, Clone, Copy)]
struct CellMeasurement {
max_ratio: f64,
directions: usize,
tolerance: f64,
null_share_worst_dir: f64,
null_share_worst_dir_deep: f64,
max_null_over_tol: f64,
}
#[derive(Debug, Clone)]
enum CellOutcome {
Measured(CellMeasurement),
Refused { budget: usize, note: String },
}
fn seeded_term_of_kind(
kind: &str,
target: ArrayView2<'_, f64>,
) -> (SaeManifoldTerm, SaeManifoldRho) {
let minimal = build_sae_minimal_seed(SaeMinimalSeedRequest {
target,
atom_basis: vec![kind.to_string()],
atom_dim: vec![1],
assignment_kind: SaeFitAssignmentKind::Softmax,
alpha: 1.0,
tau: 1.0,
threshold: 0.0,
top_k: None,
random_state: 45,
initial_logits: None,
initial_coords: None,
})
.unwrap_or_else(|e| panic!("[2720-geom] minimal seed failed for {kind}: {e}"));
let registry = AnalyticPenaltyRegistry::new();
let seed = build_sae_fit_seed(SaeFitSeedRequest {
target,
geometry_plans: &minimal.geometry_plans,
basis_values: minimal.basis_values.view(),
basis_jacobian: minimal.basis_jacobian.view(),
decoder_coefficients: minimal.decoder_coefficients.view(),
smooth_penalties: minimal.smooth_penalties.view(),
initial_logits: minimal.initial_logits.view(),
initial_coords: minimal.initial_coords.view(),
alpha: 1.0,
tau: 1.0,
learnable_alpha: false,
assignment_kind: SaeFitAssignmentKind::Softmax,
sparsity_strength: 1.0,
smoothness: 1.0,
max_iter: 40,
learning_rate: 0.05,
ridge_ext_coord: 1.0e-6,
ridge_beta: 1.0e-6,
top_k: None,
threshold: 0.0,
native_ard_enabled: true,
seed_refine_routing: minimal.refine_routing,
seed_refine_random_state: 45,
data_row_reseed: false,
fit_config: SaeFitConfig::default(),
temperature_schedule: None,
fisher_metric: None,
row_loss_weights: None,
registry: ®istry,
})
.unwrap_or_else(|e| panic!("[2720-geom] fit seed failed for {kind}: {e}"));
(seed.base_term, seed.initial_rho)
}
fn ard_saddle_rho(mut rho: SaeManifoldRho) -> SaeManifoldRho {
rho.log_lambda_sparse = -0.5;
for value in rho.log_lambda_smooth.iter_mut() {
*value = -1.0;
}
for axis in rho.log_ard.iter_mut() {
for value in axis.iter_mut() {
*value = -0.5;
}
}
rho
}
fn near_null_penalty_rho(rho: &SaeManifoldRho, log_floor: f64) -> SaeManifoldRho {
let mut null = rho.clone();
null.log_lambda_sparse = log_floor;
for value in null.log_lambda_smooth.iter_mut() {
*value = log_floor;
}
for axis in null.log_ard.iter_mut() {
for value in axis.iter_mut() {
*value = log_floor;
}
}
for value in null.log_lambda_block.iter_mut() {
*value = log_floor;
}
null
}
fn joint_gradient(
term: &mut SaeManifoldTerm,
target: ArrayView2<'_, f64>,
rho: &SaeManifoldRho,
label: &str,
) -> (Array1<f64>, usize, usize, Vec<usize>) {
let sys = term
.assemble_arrow_schur(target, rho, None)
.unwrap_or_else(|e| panic!("[2720-geom] {label}: assemble_arrow_schur failed: {e}"));
let n_rows = sys.rows.len();
let border_dim = sys.gb.len();
let full_len: usize = sys.rows.iter().map(|r| r.gt.len()).sum::<usize>() + border_dim;
let mut grad = Array1::<f64>::zeros(full_len);
let mut row_offsets = Vec::with_capacity(n_rows + 1);
row_offsets.push(0usize);
let mut offset = 0usize;
for row in &sys.rows {
for (i, &v) in row.gt.iter().enumerate() {
grad[offset + i] = v;
}
offset += row.gt.len();
row_offsets.push(offset);
}
for (i, &v) in sys.gb.iter().enumerate() {
grad[offset + i] = v;
}
assert!(
grad.iter().all(|v| v.is_finite()),
"[2720-geom] {label}: KKT gradient contains non-finite entries"
);
(grad, n_rows, border_dim, row_offsets)
}
fn measure_orbit_projection_2720(
term: &mut SaeManifoldTerm,
target: ArrayView2<'_, f64>,
rho: &SaeManifoldRho,
budget: usize,
label: &str,
) -> CellOutcome {
let result = term.penalized_quasi_laplace_criterion_with_cache(
target, rho, None, budget, 0.4, 1.0e-6, 1.0e-6,
);
let (criterion_value, loss, _cache) = match result {
Ok(ok) => ok,
Err(e) => {
let note = e.to_string();
assert!(
note.contains("inner solve did not converge"),
"[2720-geom] {label}: inner solve failed for an unrecognized reason \
(not the known convergence refusal): {note}"
);
let share_token = ["null_share=", "gauge_share="].iter().find_map(|key| {
note.find(key).map(|idx| {
note[idx + key.len()..]
.chars()
.take_while(|c| c.is_ascii_digit() || *c == '.' || *c == '-' || *c == 'e')
.collect::<String>()
})
});
if let Some(token) = share_token {
if let Ok(share) = token.parse::<f64>() {
assert!(
share.is_finite() && (0.0..=1.0).contains(&share),
"[2720-geom] {label}: refusal telemetry corrupt — \
gauge_share={share} outside [0,1]"
);
eprintln!(
"[2720-geom] {label}: refusal telemetry: {note} \
(from a NONSTATIONARY iterate; not an orbit measurement)"
);
}
}
return CellOutcome::Refused { budget, note };
}
};
eprintln!(
"[2720-geom] {label}: criterion={criterion_value:.6e} \
(data_fit={:.3e}, sparsity={:.3e}, smoothness={:.3e}, ard={:.3e})",
loss.data_fit, loss.assignment_sparsity, loss.smoothness, loss.ard
);
let (grad, n_rows, border_dim, row_offsets) = joint_gradient(term, target, rho, label);
let grad_norm = grad.dot(&grad).sqrt();
eprintln!("[2720-geom] {label}: n_rows={n_rows} border_dim={border_dim} ‖g‖={grad_norm:.6e}");
let gauge_basis = term
.joint_chart_gauge_basis_for_arrow_layout(
&row_offsets,
border_dim,
&format!("2720-geom {label}"),
)
.unwrap_or_else(|e| panic!("[2720-geom] {label}: joint_chart_gauge_basis failed: {e}"));
if gauge_basis.is_empty() {
panic!(
"[2720-geom] {label}: NO gauge directions at this state — the measurement \
instrument is inapplicable here, which for these fixtures is a harness bug \
(the baseline measured ≥1 direction on the same fixture family)"
);
}
for (i, v) in gauge_basis.iter().enumerate() {
let norm = v.dot(v).sqrt();
assert!(
(norm - 1.0).abs() < 1.0e-12,
"[2720-geom] {label}: gauge vector v_{i} has norm {norm:.6e}, expected 1"
);
}
let iterate_scale = term.inner_iterate_scale();
let tolerance = SAE_MANIFOLD_INNER_GRAD_REL_TOL * iterate_scale;
assert!(
tolerance.is_finite() && tolerance > 0.0,
"[2720-geom] {label}: tolerance is non-finite or non-positive"
);
let null_grad = {
let null_rho = near_null_penalty_rho(rho, -20.0);
let (g, _, _, _) = joint_gradient(term, target, &null_rho, label);
g
};
let deep_grad = {
let deep_rho = near_null_penalty_rho(rho, -26.0);
let (g, _, _, _) = joint_gradient(term, target, &deep_rho, label);
g
};
let mut max_ratio = 0.0f64;
let mut worst_abs = 0.0f64;
let mut worst_dir = 0usize;
let mut max_null_over_tol = 0.0f64;
for (i, v) in gauge_basis.iter().enumerate() {
let proj = grad.dot(v);
assert!(
proj.is_finite(),
"[2720-geom] {label}: v_{i} projection is non-finite"
);
let ratio = proj.abs() / tolerance;
let null_proj = null_grad.dot(v).abs();
let null_over_tol = null_proj / tolerance;
max_null_over_tol = max_null_over_tol.max(null_over_tol);
if proj.abs() > worst_abs {
worst_abs = proj.abs();
worst_dir = i;
}
max_ratio = max_ratio.max(ratio);
eprintln!(
"[2720-geom] {label}: v_{i}: |gᵀv| = {:.6e} ({:.2}× tolerance) \
near-null e⁻²⁰: {:.3e} ({:.2e}× tol)",
proj.abs(),
ratio,
null_proj,
null_over_tol
);
}
assert!(
max_null_over_tol < 1.0e-3,
"[2720-geom] {label}: near-null projection hit {:.3e}× tol on some direction — \
the data term carries gauge content, so the violation is NOT purely prior-side",
max_null_over_tol
);
let null_share_worst_dir = null_grad.dot(&gauge_basis[worst_dir]).abs() / worst_abs;
let null_share_worst_dir_deep = deep_grad.dot(&gauge_basis[worst_dir]).abs() / worst_abs;
eprintln!(
"[2720-geom] {label}: max |gᵀv|/tol = {max_ratio:.2}× over {} directions \
(tol={tolerance:.3e}; worst-dir near-null share: {:.2e} at e⁻²⁰, {:.2e} at e⁻²⁶)",
gauge_basis.len(),
null_share_worst_dir,
null_share_worst_dir_deep
);
CellOutcome::Measured(CellMeasurement {
max_ratio,
directions: gauge_basis.len(),
tolerance,
null_share_worst_dir,
null_share_worst_dir_deep,
max_null_over_tol,
})
}
fn run_cell_2720(kind: &str, framed: bool) -> CellOutcome {
let label = format!("{kind}/{}", if framed { "framed" } else { "unframed" });
let z = planted_circle_cloud();
let (mut term, rho) = seeded_term_of_kind(kind, z.view());
let rho = ard_saddle_rho(rho);
if framed {
let output_dim = term.output_dim();
let mut activated = Vec::new();
for (atom_idx, atom) in term.atoms.iter_mut().enumerate() {
match atom.maybe_activate_decoder_frame() {
Ok(Some(rank)) => activated.push((atom_idx, rank)),
Ok(None) => {}
Err(e) => panic!("[2720-geom] {label}: frame activation errored: {e}"),
}
}
eprintln!("[2720-geom] {label}: activated_frames={activated:?} output_dim={output_dim}");
assert!(
!activated.is_empty(),
"[2720-geom] {label}: no decoder frame activated, so the framed cell would \
silently duplicate the unframed cell"
);
for (_atom_idx, rank) in activated {
assert!(
rank < term.output_dim(),
"[2720-geom] {label}: rank-{rank} frame at output_dim {} is full rank; \
the round trip is trivially exact and measures nothing",
term.output_dim()
);
}
} else {
for atom in term.atoms.iter_mut() {
atom.deactivate_decoder_frame();
}
}
measure_orbit_projection_2720(&mut term, z.view(), &rho, 40, &label)
}
#[test]
fn chart_gauge_orbit_violation_across_geometries_2720() {
let kinds = ["periodic", "duchon", "poincare", "linear"];
eprintln!("[2720-geom] ════════ geometry × frame sweep ════════");
let mut summary: Vec<(String, CellOutcome)> = Vec::new();
for kind in kinds {
for framed in [false, true] {
let label = format!("{kind}/{}", if framed { "framed" } else { "unframed" });
let cell = run_cell_2720(kind, framed);
summary.push((label, cell));
}
}
eprintln!("[2720-geom] ════════ summary ════════");
eprintln!("[2720-geom] (tol gate = SAE_MANIFOLD_INNER_GRAD_REL_TOL · iterate_scale)");
for (label, cell) in &summary {
match cell {
CellOutcome::Measured(m) => {
let verdict = if m.max_ratio <= 1.0 {
"AT/BELOW tol"
} else {
"ABOVE tol"
};
eprintln!(
"[2720-geom] {label:<20} max|gᵀv|/tol = {:6.2}× ({} dirs, tol={:.3e}, \
near-null: {:.1e}/e⁻²⁰ {:.1e}/e⁻²⁶ worst-dir, {:.1e}× tol max) {verdict}",
m.max_ratio,
m.directions,
m.tolerance,
m.null_share_worst_dir,
m.null_share_worst_dir_deep,
m.max_null_over_tol
);
}
CellOutcome::Refused { budget, note } => eprintln!(
"[2720-geom] {label:<20} REFUSED under budget={budget}: {}",
note.chars().take(160).collect::<String>()
),
}
}
assert_eq!(
summary.len(),
8,
"the sweep must attempt all 8 cells (4 kinds × 2 frame states)"
);
for (label, cell) in &summary {
if !label.starts_with("poincare") {
assert!(
matches!(cell, CellOutcome::Measured(_)),
"[2720-geom] {label}: expected a measurement — a refusal outside poincare \
is an instrument failure, not a geometry result"
);
}
}
let control = &summary[0];
assert!(
matches!(control.1, CellOutcome::Measured(_)),
"[2720-geom] the periodic/unframed control produced no measurement; every \
other cell is uninterpretable until the instrument control works"
);
let poincare_refused = summary
.iter()
.filter(|(l, c)| l.starts_with("poincare") && matches!(c, CellOutcome::Refused { .. }))
.count();
if poincare_refused > 0 {
eprintln!("[2720-geom] ════════ poincare escalated-budget retry (400) ════════");
let z = planted_circle_cloud();
let (mut term, rho) = seeded_term_of_kind("poincare", z.view());
let rho = ard_saddle_rho(rho);
for atom in term.atoms.iter_mut() {
atom.deactivate_decoder_frame();
}
match measure_orbit_projection_2720(&mut term, z.view(), &rho, 400, "poincare/retry400") {
CellOutcome::Measured(m) => eprintln!(
"[2720-geom] poincare/retry400 max|gᵀv|/tol = {:6.2}× over {} dirs — \
the 40-budget refusal was budget-conditioned, measurement obtained",
m.max_ratio, m.directions
),
CellOutcome::Refused { budget, note } => eprintln!(
"[2720-geom] poincare/retry400 STILL REFUSED under budget={budget}: {}",
note.chars().take(160).collect::<String>()
),
}
}
let measured = |label: &str| {
summary
.iter()
.find(|(l, _)| l == label)
.unwrap_or_else(|| panic!("[2720-geom] cell {label} missing from summary"))
};
for kind in ["periodic", "duchon", "poincare"] {
for frame in ["unframed", "framed"] {
let (label, cell) = measured(&format!("{kind}/{frame}"));
let m = match cell {
CellOutcome::Measured(m) => *m,
CellOutcome::Refused { .. } => panic!(
"[2720-geom] {label} refused — the three curved kinds measured at both \
frames post-fix (the pre-fix poincare refusal was killed by #2762's \
descend_gauge_orbit); a refusal now is an instrument or solver change"
),
};
assert!(
m.max_ratio < 1.0,
"[2720-geom] {label}: max|gᵀv|/tol = {:.2}× is above tolerance — the \
post-fix finding is that the landed #2720/#2762 resolution meets the \
issue's acceptance criterion on every curved kind (measured 0.19× / \
0.01× / 0.00×); if this rose, the orbit mover lost the curved kinds",
m.max_ratio
);
}
}
for frame in ["unframed", "framed"] {
let (label, cell) = measured(&format!("linear/{frame}"));
let m = match cell {
CellOutcome::Measured(m) => *m,
CellOutcome::Refused { .. } => panic!(
"[2720-geom] {label} refused — linear measured at both frames when this \
pin was re-taken; a refusal now is an instrument or solver change"
),
};
assert!(
m.max_ratio > 1.0 && m.max_ratio < 20.0,
"[2720-geom] {label}: max|gᵀv|/tol = {:.2}× left the post-fix band (1, 20) \
— the linear exemption INVERTED in the post-fix world (pre-fix 0.13× below, \
post-fix 4.21× above); if this band fails the linear exit story changed; \
re-measure before updating",
m.max_ratio
);
}
}