use crate::error::ConsciousnessError;
use crate::simd::build_mi_edges;
use crate::types::TransitionMatrix;
use ruvector_coherence::{CsrMatrixView, SpectralConfig, SpectralTracker};
pub fn spectral_phi_bound(tpm: &TransitionMatrix) -> Result<PhiSpectralBound, ConsciousnessError> {
let n = tpm.n;
if n < 2 {
return Err(crate::error::ValidationError::EmptySystem.into());
}
let (edges, _marginal) = build_mi_edges(tpm.as_slice(), n, 1e-10);
let lap = CsrMatrixView::build_laplacian(n, &edges);
let config = SpectralConfig {
max_iterations: 200,
tolerance: 1e-8,
..SpectralConfig::default()
};
let mut tracker = SpectralTracker::new(config);
let score = tracker.compute(&lap);
Ok(PhiSpectralBound {
fiedler_value: score.fiedler,
spectral_gap: score.spectral_gap,
effective_resistance: score.effective_resistance,
degree_regularity: score.degree_regularity,
coherence_score: score.composite,
phi_lower_bound: score.fiedler.max(0.0),
})
}
#[derive(Debug, Clone)]
pub struct PhiSpectralBound {
pub fiedler_value: f64,
pub spectral_gap: f64,
pub effective_resistance: f64,
pub degree_regularity: f64,
pub coherence_score: f64,
pub phi_lower_bound: f64,
}
pub fn is_highly_integrated(tpm: &TransitionMatrix, threshold: f64) -> Result<bool, ConsciousnessError> {
let bound = spectral_phi_bound(tpm)?;
Ok(bound.spectral_gap > threshold)
}
#[cfg(test)]
mod tests {
use super::*;
fn identity_tpm() -> TransitionMatrix {
TransitionMatrix::identity(4)
}
fn uniform_tpm() -> TransitionMatrix {
TransitionMatrix::new(4, vec![0.25; 16])
}
#[test]
fn spectral_bound_identity() {
let tpm = identity_tpm();
let bound = spectral_phi_bound(&tpm).unwrap();
assert!(bound.fiedler_value >= 0.0);
assert!(bound.coherence_score >= 0.0);
}
#[test]
fn spectral_bound_uniform() {
let tpm = uniform_tpm();
let bound = spectral_phi_bound(&tpm).unwrap();
assert!(bound.fiedler_value < 0.1, "uniform should have low fiedler, got {}", bound.fiedler_value);
}
#[test]
fn integration_check() {
let tpm = identity_tpm();
let result = is_highly_integrated(&tpm, 0.01).unwrap();
assert!(result == true || result == false); }
}