use serde::{Deserialize, Serialize};
use crate::layer2::sheaf_cohomology::{
build_coboundary_0_matrix, compute_coboundary_1, compute_sheaf_cohomology_dims,
CellularSheafCover, SheafCoboundaryError,
};
pub use crate::layer2::sheaf_cohomology::{
compute_coboundary_0, compute_sheaf_cohomology_dims as compute_dims,
compute_sheaf_laplacian_energy as compute_integer_laplacian_energy,
CellularSheafCover as SheafCover, SheafEdgeRestriction, SheafTriangleRestriction, SheafVertexStalk,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SheafHolonomyRegime {
TrivialCohomologyConsensus,
LatentObstructionConsensus,
CyclicMonodromy,
NonCocycle2Simplex,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CocycleHolonomyReport {
pub residual_norm: f64,
pub residual_vector: Vec<f64>,
pub coboundary1_norm: f64,
pub is_cocycle: bool,
pub numeric_rank_delta0: usize,
pub exact_rank_delta0: usize,
pub dim_h0: usize,
pub dim_h1: usize,
pub singular_values: Vec<f64>,
pub laplacian_spectrum: Vec<f64>,
pub cutoff_tau: f64,
pub near_threshold_conditioning: bool,
pub witness_potential: Vec<f64>,
pub regime: SheafHolonomyRegime,
}
struct SvdTriplet {
sigma: f64,
u: Vec<f64>,
v: Vec<f64>,
}
fn clean_zero(val: f64) -> f64 {
if val.abs() == 0.0 || val.abs() < 1e-18 {
0.0
} else {
val
}
}
fn l2_norm(vec: &[f64]) -> f64 {
vec.iter().map(|&v| v * v).sum::<f64>().sqrt()
}
fn compute_one_sided_jacobi_svd(matrix: &[Vec<f64>], rows: usize, cols: usize) -> Vec<SvdTriplet> {
if rows == 0 || cols == 0 {
return Vec::new();
}
let tall = rows >= cols;
let p = if tall { rows } else { cols };
let q = if tall { cols } else { rows };
let mut work: Vec<Vec<f64>> = (0..p)
.map(|r| (0..q).map(|c| if tall { matrix[r][c] } else { matrix[c][r] }).collect())
.collect();
let mut rot: Vec<Vec<f64>> = (0..q)
.map(|r| (0..q).map(|c| if r == c { 1.0 } else { 0.0 }).collect())
.collect();
for _sweep in 0..80 {
let mut max_rel_coupling = 0.0f64;
for i in 0..(q - 1) {
for j in (i + 1)..q {
let mut alpha = 0.0f64;
let mut beta = 0.0f64;
let mut gamma = 0.0f64;
for r in 0..p {
let wi = work[r][i];
let wj = work[r][j];
alpha += wi * wi;
beta += wj * wj;
gamma += wi * wj;
}
let scale = (alpha * beta).sqrt();
if scale > 0.0 && gamma.abs() > 1e-15 * scale {
let coupling = gamma.abs() / scale;
if coupling > max_rel_coupling {
max_rel_coupling = coupling;
}
let zeta = (beta - alpha) / (2.0 * gamma);
let sign_zeta = if zeta >= 0.0 { 1.0 } else { -1.0 };
let t = sign_zeta / (zeta.abs() + (1.0 + zeta * zeta).sqrt());
let c = 1.0 / (1.0 + t * t).sqrt();
let s = c * t;
for r in 0..p {
let wi = work[r][i];
let wj = work[r][j];
work[r][i] = c * wi - s * wj;
work[r][j] = s * wi + c * wj;
}
for r in 0..q {
let ri = rot[r][i];
let rj = rot[r][j];
rot[r][i] = c * ri - s * rj;
rot[r][j] = s * ri + c * rj;
}
}
}
}
if max_rel_coupling == 0.0 {
break;
}
}
let mut triplets: Vec<SvdTriplet> = Vec::new();
for k in 0..q {
let mut norm_sq = 0.0f64;
for r in 0..p {
let val = work[r][k];
norm_sq += val * val;
}
let sigma = norm_sq.sqrt();
let ortho_col: Vec<f64> = (0..p)
.map(|r| if sigma > 0.0 { work[r][k] / sigma } else { 0.0 })
.collect();
let rot_col: Vec<f64> = (0..q).map(|r| rot[r][k]).collect();
triplets.push(SvdTriplet {
sigma,
u: if tall { ortho_col.clone() } else { rot_col.clone() },
v: if tall { rot_col } else { ortho_col },
});
}
triplets.sort_by(|a, b| b.sigma.partial_cmp(&a.sigma).unwrap_or(std::cmp::Ordering::Equal));
triplets
}
pub fn compute_sheaf_laplacian_matrix(cover: &CellularSheafCover) -> Result<Vec<Vec<f64>>, SheafCoboundaryError> {
let d0_int = build_coboundary_0_matrix(cover)?;
let dim_c0: usize = cover.vertices.iter().map(|v| v.dimension).sum();
let dim_c1 = d0_int.len();
let mut lap: Vec<Vec<f64>> = vec![vec![0.0; dim_c0]; dim_c0];
for i in 0..dim_c0 {
for j in i..dim_c0 {
let mut sum = 0.0f64;
for e in 0..dim_c1 {
sum += (d0_int[e][i] as f64) * (d0_int[e][j] as f64);
}
let cleaned = clean_zero(sum);
lap[i][j] = cleaned;
lap[j][i] = cleaned;
}
}
Ok(lap)
}
pub fn compute_sheaf_laplacian_energy(cover: &CellularSheafCover, cochain0: &[f64]) -> Result<f64, SheafCoboundaryError> {
let dim_c0: usize = cover.vertices.iter().map(|v| v.dimension).sum();
if cochain0.len() != dim_c0 {
return Err(SheafCoboundaryError::CochainLengthMismatch {
expected: dim_c0,
actual: cochain0.len(),
});
}
let d0_int = build_coboundary_0_matrix(cover)?;
let mut energy = 0.0f64;
for row in &d0_int {
let mut diff_e = 0.0f64;
for (j, &coeff) in row.iter().enumerate() {
diff_e += (coeff as f64) * cochain0[j];
}
energy += diff_e * diff_e;
}
Ok(clean_zero(energy))
}
pub fn compute_cocycle_holonomy_residual(
cover: &CellularSheafCover,
cochain1: &[f64],
) -> Result<CocycleHolonomyReport, SheafCoboundaryError> {
let dims = compute_sheaf_cohomology_dims(cover)?;
let d0_int = build_coboundary_0_matrix(cover)?;
let m = dims.dim_c1;
let n = dims.dim_c0;
if cochain1.len() != m {
return Err(SheafCoboundaryError::CochainLengthMismatch {
expected: m,
actual: cochain1.len(),
});
}
let d0_float: Vec<Vec<f64>> = d0_int
.into_iter()
.map(|row| row.into_iter().map(|c| c as f64).collect())
.collect();
let triplets = compute_one_sided_jacobi_svd(&d0_float, m, n);
let singular_values: Vec<f64> = triplets.iter().map(|t| clean_zero(t.sigma)).collect();
let sigma_max = singular_values.first().copied().unwrap_or(0.0);
let cutoff_tau = if m == 0 || n == 0 {
0.0
} else {
1e-9 * (std::cmp::max(m, n) as f64) * sigma_max
};
let mut numeric_rank_delta0 = 0usize;
let mut near_threshold_conditioning = false;
let mut projected = vec![0.0f64; m];
let mut witness_potential = vec![0.0f64; n];
for trip in &triplets {
if cutoff_tau > 0.0 && trip.sigma >= 0.1 * cutoff_tau && trip.sigma <= 10.0 * cutoff_tau {
near_threshold_conditioning = true;
}
if trip.sigma > cutoff_tau {
numeric_rank_delta0 += 1;
let mut uz = 0.0f64;
for (idx, &ui) in trip.u.iter().enumerate() {
uz += ui * cochain1[idx];
}
for i in 0..m {
projected[i] += uz * trip.u[i];
}
let scale = uz / trip.sigma;
for j in 0..n {
witness_potential[j] += scale * trip.v[j];
}
}
}
let residual_vector: Vec<f64> = cochain1
.iter()
.enumerate()
.map(|(idx, &zi)| clean_zero(zi - projected[idx]))
.collect();
let residual_norm = clean_zero(l2_norm(&residual_vector));
let cochain1_int: Vec<i64> = cochain1.iter().map(|&v| v.round() as i64).collect();
let d1z = compute_coboundary_1(cover, &cochain1_int)?;
let d1z_float: Vec<f64> = d1z.iter().map(|&v| v as f64).collect();
let coboundary1_norm = clean_zero(l2_norm(&d1z_float));
let scale_norm = 1.0f64.max(l2_norm(cochain1));
let tol = 1e-9f64.max(cutoff_tau * scale_norm);
let is_cocycle = coboundary1_norm <= tol;
let has_holonomy = residual_norm > tol;
let spectrum_pad = if n > triplets.len() { n - triplets.len() } else { 0 };
let mut laplacian_spectrum = vec![0.0f64; spectrum_pad];
let mut non_zero_spec: Vec<f64> = triplets.iter().map(|t| clean_zero(t.sigma * t.sigma)).collect();
non_zero_spec.reverse();
laplacian_spectrum.extend(non_zero_spec);
let regime = if !is_cocycle {
SheafHolonomyRegime::NonCocycle2Simplex
} else if has_holonomy {
SheafHolonomyRegime::CyclicMonodromy
} else if dims.dim_h1 > 0 {
SheafHolonomyRegime::LatentObstructionConsensus
} else {
SheafHolonomyRegime::TrivialCohomologyConsensus
};
Ok(CocycleHolonomyReport {
residual_norm,
residual_vector,
coboundary1_norm,
is_cocycle,
numeric_rank_delta0,
exact_rank_delta0: dims.rank_delta0,
dim_h0: dims.dim_h0,
dim_h1: dims.dim_h1,
singular_values,
laplacian_spectrum,
cutoff_tau,
near_threshold_conditioning,
witness_potential: witness_potential.into_iter().map(clean_zero).collect(),
regime,
})
}