use crate::holotensor::dct_2d;
use haagenti_core::Result;
#[derive(Debug, Clone)]
pub struct SpectralAnalyzer {
target_quality: f32,
min_retention: f32,
max_retention: f32,
}
impl Default for SpectralAnalyzer {
fn default() -> Self {
Self {
target_quality: 0.95, min_retention: 0.05, max_retention: 0.90, }
}
}
impl SpectralAnalyzer {
pub fn new(target_quality: f32) -> Self {
Self {
target_quality: target_quality.clamp(0.5, 0.999),
..Default::default()
}
}
pub fn with_min_retention(mut self, min: f32) -> Self {
self.min_retention = min.clamp(0.01, 0.5);
self
}
pub fn with_max_retention(mut self, max: f32) -> Self {
self.max_retention = max.clamp(0.5, 1.0);
self
}
pub fn target_quality(&self) -> f32 {
self.target_quality
}
pub fn min_retention(&self) -> f32 {
self.min_retention
}
pub fn max_retention(&self) -> f32 {
self.max_retention
}
pub fn compute_energy_distribution(
&self,
data: &[f32],
width: usize,
height: usize,
) -> Result<Vec<(usize, f32)>> {
let n = width * height;
if data.len() != n {
return Err(haagenti_core::Error::corrupted("data size mismatch"));
}
let mut dct_coeffs = vec![0.0f32; n];
dct_2d(data, &mut dct_coeffs, width, height);
let mut energy_dist: Vec<(usize, f32)> = dct_coeffs
.iter()
.enumerate()
.map(|(i, &c)| (i, c * c))
.collect();
energy_dist.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
Ok(energy_dist)
}
pub fn compute_cumulative_energy(&self, energy_dist: &[(usize, f32)]) -> Vec<f32> {
if energy_dist.is_empty() {
return vec![];
}
let total_energy: f32 = energy_dist.iter().map(|(_, e)| e).sum();
if total_energy == 0.0 {
return vec![1.0; energy_dist.len()];
}
let mut cumulative = Vec::with_capacity(energy_dist.len());
let mut running_sum = 0.0f32;
for (_, energy) in energy_dist {
running_sum += energy;
cumulative.push(running_sum / total_energy);
}
cumulative
}
pub fn find_knee_point(&self, cumulative_energy: &[f32], threshold: f32) -> usize {
if cumulative_energy.is_empty() {
return 0;
}
for (i, &cum) in cumulative_energy.iter().enumerate() {
if cum >= threshold {
return i + 1; }
}
cumulative_energy.len()
}
pub fn find_knee_by_curvature(&self, cumulative_energy: &[f32]) -> usize {
if cumulative_energy.len() < 3 {
return cumulative_energy.len();
}
let n = cumulative_energy.len();
let mut max_curvature = 0.0f32;
let mut knee_index = 1;
for i in 1..n - 1 {
let _x = i as f32 / n as f32;
let y_prev = cumulative_energy[i - 1];
let y = cumulative_energy[i];
let y_next = cumulative_energy[i + 1];
let d2y = y_next - 2.0 * y + y_prev;
let dy = (y_next - y_prev) / 2.0;
let curvature = d2y.abs() / (1.0 + dy * dy).powf(1.5);
if curvature > max_curvature && d2y < 0.0 {
max_curvature = curvature;
knee_index = i;
}
}
knee_index.max(1)
}
pub fn compute_optimal_retention(
&self,
data: &[f32],
width: usize,
height: usize,
) -> Result<f32> {
let n = width * height;
if n == 0 {
return Ok(self.min_retention);
}
let energy_dist = self.compute_energy_distribution(data, width, height)?;
let cumulative = self.compute_cumulative_energy(&energy_dist);
let knee = self.find_knee_point(&cumulative, self.target_quality);
let retention = knee as f32 / n as f32;
Ok(retention.clamp(self.min_retention, self.max_retention))
}
pub fn analyze(&self, data: &[f32], width: usize, height: usize) -> Result<SpectralStats> {
let n = width * height;
let energy_dist = self.compute_energy_distribution(data, width, height)?;
let cumulative = self.compute_cumulative_energy(&energy_dist);
let total_energy: f32 = energy_dist.iter().map(|(_, e)| e).sum();
let retention_90 = self.find_knee_point(&cumulative, 0.90) as f32 / n as f32;
let retention_95 = self.find_knee_point(&cumulative, 0.95) as f32 / n as f32;
let retention_99 = self.find_knee_point(&cumulative, 0.99) as f32 / n as f32;
let entropy = if total_energy > 0.0 {
let probs: Vec<f32> = energy_dist
.iter()
.map(|(_, e)| e / total_energy)
.filter(|&p| p > 1e-10)
.collect();
-probs.iter().map(|p| p * p.ln()).sum::<f32>() / (n as f32).ln()
} else {
0.0
};
let knee_by_curvature = self.find_knee_by_curvature(&cumulative) as f32 / n as f32;
Ok(SpectralStats {
total_elements: n,
total_energy,
retention_90,
retention_95,
retention_99,
spectral_entropy: entropy,
knee_by_curvature,
optimal_retention: self.compute_optimal_retention(data, width, height)?,
})
}
}
#[derive(Debug, Clone)]
pub struct SpectralStats {
pub total_elements: usize,
pub total_energy: f32,
pub retention_90: f32,
pub retention_95: f32,
pub retention_99: f32,
pub spectral_entropy: f32,
pub knee_by_curvature: f32,
pub optimal_retention: f32,
}
impl SpectralStats {
pub fn compressibility(&self) -> Compressibility {
if self.retention_95 < 0.10 {
Compressibility::High
} else if self.retention_95 < 0.30 {
Compressibility::Medium
} else if self.retention_95 < 0.60 {
Compressibility::Low
} else {
Compressibility::VeryLow
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Compressibility {
High,
Medium,
Low,
VeryLow,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_analyzer_default() {
let analyzer = SpectralAnalyzer::default();
assert!((analyzer.target_quality - 0.95).abs() < 0.01);
}
#[test]
fn test_energy_distribution_uniform() {
let analyzer = SpectralAnalyzer::default();
let data: Vec<f32> = vec![1.0; 64];
let energy = analyzer.compute_energy_distribution(&data, 8, 8).unwrap();
assert!(!energy.is_empty());
}
#[test]
fn test_energy_distribution_sparse() {
let analyzer = SpectralAnalyzer::default();
let mut data = vec![0.0f32; 64];
data[0] = 1.0;
let energy = analyzer.compute_energy_distribution(&data, 8, 8).unwrap();
let cumulative = analyzer.compute_cumulative_energy(&energy);
assert!(cumulative.len() == 64);
}
#[test]
fn test_cumulative_energy_monotonic() {
let analyzer = SpectralAnalyzer::default();
let data: Vec<f32> = (0..64).map(|i| (i as f32 * 0.1).sin()).collect();
let energy = analyzer.compute_energy_distribution(&data, 8, 8).unwrap();
let cumulative = analyzer.compute_cumulative_energy(&energy);
for i in 1..cumulative.len() {
assert!(cumulative[i] >= cumulative[i - 1] - 1e-6);
}
if let Some(&last) = cumulative.last() {
assert!((last - 1.0).abs() < 1e-5);
}
}
#[test]
fn test_knee_point_finds_threshold() {
let analyzer = SpectralAnalyzer::default();
let cumulative = vec![0.5, 0.8, 0.95, 0.99, 1.0];
let knee_90 = analyzer.find_knee_point(&cumulative, 0.90);
let knee_95 = analyzer.find_knee_point(&cumulative, 0.95);
assert_eq!(knee_90, 3); assert_eq!(knee_95, 3); }
#[test]
fn test_optimal_retention_low_rank() {
let analyzer = SpectralAnalyzer::new(0.95);
let u: Vec<f32> = (0..8).map(|i| i as f32).collect();
let v: Vec<f32> = (0..8).map(|i| (i as f32 + 1.0)).collect();
let mut data = vec![0.0f32; 64];
for i in 0..8 {
for j in 0..8 {
data[i * 8 + j] = u[i] * v[j];
}
}
let retention = analyzer.compute_optimal_retention(&data, 8, 8).unwrap();
assert!(
retention < 0.5,
"Low-rank matrix should need low retention, got {}",
retention
);
}
#[test]
fn test_optimal_retention_random() {
let analyzer = SpectralAnalyzer::new(0.95);
let data: Vec<f32> = (0..64)
.map(|i| ((i * 17 + 3) % 100) as f32 / 100.0)
.collect();
let retention = analyzer.compute_optimal_retention(&data, 8, 8).unwrap();
assert!(
retention > 0.1,
"Random data should need higher retention, got {}",
retention
);
}
#[test]
fn test_analyze_returns_stats() {
let analyzer = SpectralAnalyzer::new(0.95);
let data: Vec<f32> = (0..64).map(|i| (i as f32 * 0.1).sin()).collect();
let stats = analyzer.analyze(&data, 8, 8).unwrap();
assert_eq!(stats.total_elements, 64);
assert!(stats.total_energy > 0.0);
assert!(stats.retention_90 <= stats.retention_95);
assert!(stats.retention_95 <= stats.retention_99);
assert!(stats.spectral_entropy >= 0.0 && stats.spectral_entropy <= 1.0);
}
#[test]
fn test_compressibility_classification() {
let stats_high = SpectralStats {
total_elements: 100,
total_energy: 1.0,
retention_90: 0.05,
retention_95: 0.08,
retention_99: 0.15,
spectral_entropy: 0.3,
knee_by_curvature: 0.07,
optimal_retention: 0.08,
};
assert_eq!(stats_high.compressibility(), Compressibility::High);
let stats_low = SpectralStats {
total_elements: 100,
total_energy: 1.0,
retention_90: 0.30,
retention_95: 0.50,
retention_99: 0.80,
spectral_entropy: 0.8,
knee_by_curvature: 0.45,
optimal_retention: 0.50,
};
assert_eq!(stats_low.compressibility(), Compressibility::Low);
}
#[test]
fn test_empty_tensor() {
let analyzer = SpectralAnalyzer::default();
let data: Vec<f32> = vec![];
let result = analyzer.compute_optimal_retention(&data, 0, 0);
assert!(result.is_ok());
}
#[test]
fn test_all_zeros() {
let analyzer = SpectralAnalyzer::default();
let data = vec![0.0f32; 64];
let retention = analyzer.compute_optimal_retention(&data, 8, 8).unwrap();
assert!(
retention <= 0.10,
"All-zero tensor should use minimum retention"
);
}
}