use gam_problem::topology_certificates::{Certificate, Claim, Evidence, Verdict};
use crate::encode::EncodeResult;
use crate::identifiability::ResidualGaugeReport;
use crate::manifold::{
CertificateInputs, CoordinateFidelityCertificate, GlobalOptimalityVerdict,
TopologyPersistenceCertificate,
};
fn put_finite(evidence: &mut Evidence, key: &'static str, value: f64) {
if value.is_finite() {
evidence.insert(key, value.into());
} else {
evidence.insert(key, "n/a".into());
}
}
impl Certificate for EncodeResult {
fn claim(&self) -> Claim {
Claim::new(
"encode-atlas",
"each encoded row carries a per-row Newton–Kantorovich certificate \
(h = β·η·L ≤ ½ at the start point); certified rows converge \
quadratically into the unique root, and uncertified rows are flagged \
for the exact multi-start fallback — never silently encoded wrong",
)
}
fn evidence(&self) -> Evidence {
let mut e = Evidence::new();
let n = self.certified.len();
let certified = n - self.encode_uncertified_count;
e.insert("rows", n.into());
e.insert("certified_rows", certified.into());
e.insert(
"encode_uncertified_count",
self.encode_uncertified_count.into(),
);
let frac = if n > 0 {
certified as f64 / n as f64
} else {
f64::NAN
};
put_finite(&mut e, "certified_fraction", frac);
e
}
fn verdict(&self) -> Verdict {
if self.certified.is_empty() {
Verdict::Unavailable
} else if self.encode_uncertified_count == 0 {
Verdict::Certified
} else {
Verdict::Insufficient
}
}
}
impl Certificate for ResidualGaugeReport {
fn claim(&self) -> Claim {
Claim::new(
"residual-gauge",
"the fit is identified up to a named residual gauge group: every \
generator was curvature-tested in the fit's own metric, the pinning \
span rank is reported, and any surviving (unpinned) freedom is \
enumerated rather than silently absorbed",
)
}
fn evidence(&self) -> Evidence {
let mut e = Evidence::new();
e.insert(
"metric_provenance",
format!("{:?}", self.metric_provenance).into(),
);
e.insert("group_signature", self.group_signature().into());
e.insert("pinning_rank", self.pinning_rank.into());
e.insert("residual_gauge_dim", self.residual_gauge_dim.into());
e.insert(
"diffeomorphism_unpinned",
self.diffeomorphism_unpinned.into(),
);
e.insert("generator_count", self.generators.len().into());
match self.sym_f_trivial_under_output_fisher {
Some(t) => e.insert("sym_f_trivial_under_output_fisher", t.into()),
None => e.insert("sym_f_trivial_under_output_fisher", "n/a".into()),
};
e.insert("summary", self.summary.clone().into());
e
}
fn verdict(&self) -> Verdict {
let pinned = self.residual_gauge_dim == 0
&& !self.diffeomorphism_unpinned
&& self.sym_f_trivial_under_output_fisher != Some(false);
if pinned {
Verdict::Certified
} else {
Verdict::Insufficient
}
}
}
impl Certificate for CertificateInputs {
fn claim(&self) -> Claim {
Claim::new(
"global-optimality",
"the fitted dictionary's basin stationary point is the unique global \
optimum up to the residual gauge group: a conservative sufficient \
condition on mutual coherence, per-atom curvature, activity floors, \
and reconstruction SNR holds with positive margin",
)
}
fn evidence(&self) -> Evidence {
let mut e = Evidence::new();
put_finite(&mut e, "mu_hat", self.mu_hat);
put_finite(&mut e, "mean_activity_floor", self.mean_activity_floor);
put_finite(&mut e, "peak_activity_floor", self.peak_activity_floor);
put_finite(&mut e, "snr_proxy", self.snr_proxy);
put_finite(&mut e, "dispersion", self.dispersion);
put_finite(
&mut e,
"global_optimality_margin",
self.global_optimality.margin(),
);
e.insert(
"global_optimality",
if self.global_optimality.is_certified() {
"certified_global"
} else {
"uncertified"
}
.into(),
);
e.insert("atom_count", self.per_atom_mean_activity.len().into());
e.insert("note", self.note.clone().into());
e
}
fn verdict(&self) -> Verdict {
match self.global_optimality {
GlobalOptimalityVerdict::CertifiedGlobal { .. } => Verdict::Certified,
GlobalOptimalityVerdict::Uncertified { .. } => Verdict::Insufficient,
}
}
}
impl<'a> Certificate for CoordinateFidelityCertificate<'a> {
fn claim(&self) -> Claim {
Claim::new(
"coordinate-fidelity",
"every eligible d=1 SAE chart reports a faithful coordinate reading: \
either the raw chart is already arc-length or the payload supplies \
the pure-read arc-length coordinate; degenerate charts are exposed \
as refusals rather than silently treated as angles",
)
}
fn evidence(&self) -> Evidence {
let mut e = Evidence::new();
let mut eligible = 0_usize;
let mut certified = 0_usize;
let mut degenerate = 0_usize;
let mut max_arclength = f64::NEG_INFINITY;
let mut max_raw_rms = f64::NEG_INFINITY;
let mut max_raw_max = f64::NEG_INFINITY;
let mut max_uniformity = f64::NEG_INFINITY;
let mut min_p = f64::INFINITY;
let mut support_masses = Vec::new();
let mut effective_ns = Vec::new();
let mut support_esses = Vec::new();
let mut worst = "unavailable";
for atom in self.atoms.iter().flatten() {
eligible += 1;
if atom.certified {
certified += 1;
if worst == "unavailable" {
worst = atom.verdict.label();
}
} else {
degenerate += 1;
worst = atom.verdict.label();
}
if atom.arclength_defect.is_finite() {
max_arclength = max_arclength.max(atom.arclength_defect);
}
if atom.raw_arclength_defect_rms.is_finite() {
max_raw_rms = max_raw_rms.max(atom.raw_arclength_defect_rms);
}
if atom.raw_arclength_defect_max.is_finite() {
max_raw_max = max_raw_max.max(atom.raw_arclength_defect_max);
}
if atom.uniformity_statistic.is_finite() {
max_uniformity = max_uniformity.max(atom.uniformity_statistic);
}
if atom.uniformity_p_value.is_finite() {
min_p = min_p.min(atom.uniformity_p_value);
}
support_masses.push(atom.support_mass);
effective_ns.push(atom.effective_n);
support_esses.push(atom.support_ess);
}
e.insert("atom_count", self.atoms.len().into());
e.insert("eligible_d1_atoms", eligible.into());
e.insert("certified_d1_atoms", certified.into());
e.insert("degenerate_d1_atoms", degenerate.into());
e.insert("worst_coordinate_verdict", worst.into());
put_finite(&mut e, "max_arclength_defect", max_arclength);
put_finite(&mut e, "max_raw_arclength_defect_rms", max_raw_rms);
put_finite(&mut e, "max_raw_arclength_defect_max", max_raw_max);
put_finite(&mut e, "max_uniformity_statistic", max_uniformity);
put_finite(&mut e, "min_uniformity_p_value", min_p);
e.insert("support_mass", support_masses.into());
e.insert("effective_n", effective_ns.into());
e.insert("support_ess", support_esses.into());
e
}
fn verdict(&self) -> Verdict {
let mut saw_eligible = false;
for atom in self.atoms.iter().flatten() {
saw_eligible = true;
if !atom.certified {
return Verdict::Insufficient;
}
}
if saw_eligible {
Verdict::Certified
} else {
Verdict::Unavailable
}
}
}
impl<'a> Certificate for TopologyPersistenceCertificate<'a> {
fn claim(&self) -> Claim {
Claim::new(
"topology-persistence",
"each audited SAE atom's assigned-row image has persistent homology \
consistent with the raced topology: measured Betti numbers and loop \
evidence are exposed, and any disagreement is marked contested rather \
than trusted silently",
)
}
fn evidence(&self) -> Evidence {
let mut e = Evidence::new();
let mut audited = 0_usize;
let mut contested = 0_usize;
let mut max_h1 = f64::NEG_INFINITY;
let mut max_h2 = f64::NEG_INFINITY;
let mut betti0 = Vec::new();
let mut betti1 = Vec::new();
let mut betti2 = Vec::new();
let mut expected_betti0 = Vec::new();
let mut expected_betti1 = Vec::new();
let mut expected_betti2 = Vec::new();
let mut support_sizes = Vec::new();
let mut support_masses = Vec::new();
let mut effective_ns = Vec::new();
let mut support_esses = Vec::new();
let mut null_pvalues = Vec::new();
let mut spikein_powers = Vec::new();
for atom in self.atoms.iter().flatten() {
audited += 1;
if atom.contested {
contested += 1;
}
if atom.dominant_h1_persistence.is_finite() {
max_h1 = max_h1.max(atom.dominant_h1_persistence);
}
if atom.dominant_h2_persistence.is_finite() {
max_h2 = max_h2.max(atom.dominant_h2_persistence);
}
betti0.push(atom.measured_betti.b0 as f64);
betti1.push(atom.measured_betti.b1 as f64);
betti2.push(atom.measured_betti.b2.unwrap_or(0) as f64);
expected_betti0.push(atom.expected_betti.b0 as f64);
expected_betti1.push(atom.expected_betti.b1 as f64);
expected_betti2.push(atom.expected_betti.b2.unwrap_or(0) as f64);
support_sizes.push(atom.support_size as f64);
support_masses.push(atom.support_mass);
effective_ns.push(atom.effective_n);
support_esses.push(atom.support_ess);
if let Some(calibration) = &atom.null_calibration {
null_pvalues.push(calibration.null_pvalue);
spikein_powers.push(calibration.spikein_power);
}
}
e.insert("atom_count", self.atoms.len().into());
e.insert("audited_atoms", audited.into());
e.insert("contested_atoms", contested.into());
e.insert("measured_betti0", betti0.into());
e.insert("measured_betti1", betti1.into());
e.insert("measured_betti2", betti2.into());
e.insert("expected_betti0", expected_betti0.into());
e.insert("expected_betti1", expected_betti1.into());
e.insert("expected_betti2", expected_betti2.into());
e.insert("support_size", support_sizes.into());
e.insert("support_mass", support_masses.into());
e.insert("effective_n", effective_ns.into());
e.insert("support_ess", support_esses.into());
e.insert("null_pvalue", null_pvalues.into());
e.insert("spikein_power", spikein_powers.into());
put_finite(&mut e, "max_dominant_h1_persistence", max_h1);
put_finite(&mut e, "max_dominant_h2_persistence", max_h2);
e
}
fn verdict(&self) -> Verdict {
let mut saw_audited = false;
for atom in self.atoms.iter().flatten() {
saw_audited = true;
if atom.contested {
return Verdict::Insufficient;
}
}
if saw_audited {
Verdict::Certified
} else {
Verdict::Unavailable
}
}
}