use crate::compressive::CompressiveSpectralEncoder;
use crate::holotensor::HoloFragment;
use crate::spectral_analysis::SpectralAnalyzer;
use haagenti_core::{Error, Result};
#[derive(Debug, Clone)]
pub struct AdaptiveEncodingMeta {
pub width: usize,
pub height: usize,
pub total_elements: usize,
pub num_fragments: u16,
pub retention_ratio: f32,
pub essential_ratio: f32,
pub retained_coefficients: usize,
pub target_quality: f32,
pub estimated_quality: f32,
}
#[derive(Debug, Clone)]
pub struct AdaptiveSpectralEncoder {
num_fragments: u16,
analyzer: SpectralAnalyzer,
fallback_retention: f32,
}
impl AdaptiveSpectralEncoder {
pub fn new(target_quality: f32, num_fragments: u16) -> Self {
Self {
num_fragments,
analyzer: SpectralAnalyzer::new(target_quality),
fallback_retention: 0.5,
}
}
pub fn with_min_retention(mut self, min: f32) -> Self {
self.analyzer = self.analyzer.with_min_retention(min);
self
}
pub fn with_max_retention(mut self, max: f32) -> Self {
self.analyzer = self.analyzer.with_max_retention(max);
self
}
pub fn with_fallback_retention(mut self, fallback: f32) -> Self {
self.fallback_retention = fallback.clamp(0.1, 0.9);
self
}
pub fn encode_2d(
&self,
data: &[f32],
width: usize,
height: usize,
) -> Result<(AdaptiveEncodingMeta, Vec<HoloFragment>)> {
let n = width * height;
if data.len() != n {
return Err(Error::corrupted("data size mismatch"));
}
let optimal_retention = self
.analyzer
.compute_optimal_retention(data, width, height)
.unwrap_or(self.fallback_retention);
let essential_ratio = if self.num_fragments == 1 { 1.0 } else { 0.2 };
let encoder = CompressiveSpectralEncoder::new(self.num_fragments, optimal_retention)
.with_essential_ratio(essential_ratio);
let fragments = encoder.encode_2d(data, width, height)?;
let retained = ((n as f32 * optimal_retention) as usize).max(1);
let meta = AdaptiveEncodingMeta {
width,
height,
total_elements: n,
num_fragments: self.num_fragments,
retention_ratio: optimal_retention,
essential_ratio,
retained_coefficients: retained,
target_quality: self.analyzer.target_quality(),
estimated_quality: optimal_retention.min(1.0), };
Ok((meta, fragments))
}
pub fn analyze(&self, data: &[f32], width: usize, height: usize) -> Result<f32> {
self.analyzer.compute_optimal_retention(data, width, height)
}
pub fn get_stats(
&self,
data: &[f32],
width: usize,
height: usize,
) -> Result<crate::spectral_analysis::SpectralStats> {
self.analyzer.analyze(data, width, height)
}
}
#[derive(Debug, Clone, Default)]
pub struct AdaptiveSpectralDecoder {
}
impl AdaptiveSpectralDecoder {
pub fn new() -> Self {
Self::default()
}
pub fn decode(
&self,
_meta: &AdaptiveEncodingMeta,
fragments: &[HoloFragment],
) -> Result<Vec<f32>> {
if fragments.is_empty() {
return Err(Error::corrupted("no fragments provided"));
}
let mut decoder = crate::compressive::CompressiveSpectralDecoder::new();
decoder.add_essentials(&fragments[0])?;
for frag in &fragments[1..] {
decoder.add_detail(frag)?;
}
decoder.reconstruct()
}
pub fn decode_progressive(
&self,
meta: &AdaptiveEncodingMeta,
fragments: &[HoloFragment],
num_fragments: usize,
) -> Result<Vec<f32>> {
if fragments.is_empty() || num_fragments == 0 {
return Ok(vec![0.0f32; meta.total_elements]);
}
let use_count = num_fragments.min(fragments.len());
let mut decoder = crate::compressive::CompressiveSpectralDecoder::new();
decoder.add_essentials(&fragments[0])?;
for frag in fragments.iter().take(use_count).skip(1) {
decoder.add_detail(frag)?;
}
decoder.reconstruct()
}
}
#[derive(Debug)]
pub struct AdaptiveBatchEncoder {
encoder: AdaptiveSpectralEncoder,
stats: BatchEncodingStats,
}
#[derive(Debug, Clone, Default)]
pub struct BatchEncodingStats {
pub tensors_processed: usize,
pub avg_retention: f32,
pub min_retention: f32,
pub max_retention: f32,
pub total_input_bytes: usize,
pub total_output_bytes: usize,
pub per_tensor_retention: Vec<f32>,
}
impl AdaptiveBatchEncoder {
pub fn new(target_quality: f32, num_fragments: u16) -> Self {
Self {
encoder: AdaptiveSpectralEncoder::new(target_quality, num_fragments),
stats: BatchEncodingStats {
min_retention: 1.0,
..Default::default()
},
}
}
pub fn encode_tensor(
&mut self,
data: &[f32],
width: usize,
height: usize,
) -> Result<(AdaptiveEncodingMeta, Vec<HoloFragment>)> {
let (meta, fragments) = self.encoder.encode_2d(data, width, height)?;
self.stats.tensors_processed += 1;
self.stats.per_tensor_retention.push(meta.retention_ratio);
self.stats.min_retention = self.stats.min_retention.min(meta.retention_ratio);
self.stats.max_retention = self.stats.max_retention.max(meta.retention_ratio);
let input_bytes = data.len() * 4; let output_bytes = fragments.iter().map(|f| f.data.len()).sum::<usize>();
self.stats.total_input_bytes += input_bytes;
self.stats.total_output_bytes += output_bytes;
let sum: f32 = self.stats.per_tensor_retention.iter().sum();
self.stats.avg_retention = sum / self.stats.tensors_processed as f32;
Ok((meta, fragments))
}
pub fn stats(&self) -> &BatchEncodingStats {
&self.stats
}
pub fn compression_ratio(&self) -> f32 {
if self.stats.total_output_bytes == 0 {
0.0
} else {
self.stats.total_input_bytes as f32 / self.stats.total_output_bytes as f32
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_adaptive_encoder_basic() {
let encoder = AdaptiveSpectralEncoder::new(0.95, 4);
let data: Vec<f32> = (0..64).map(|i| (i as f32 * 0.1).sin()).collect();
let (meta, fragments) = encoder.encode_2d(&data, 8, 8).unwrap();
assert_eq!(meta.width, 8);
assert_eq!(meta.height, 8);
assert_eq!(meta.total_elements, 64);
assert!(!fragments.is_empty());
assert!(meta.retention_ratio > 0.0 && meta.retention_ratio <= 1.0);
}
#[test]
fn test_adaptive_encoder_low_rank() {
let encoder = AdaptiveSpectralEncoder::new(0.95, 4);
let u: Vec<f32> = (0..8).map(|i| i as f32 + 1.0).collect();
let v: Vec<f32> = (0..8).map(|i| (i as f32 + 1.0) * 0.5).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 (meta, _) = encoder.encode_2d(&data, 8, 8).unwrap();
assert!(
meta.retention_ratio < 0.5,
"Low-rank matrix should use low retention: {}",
meta.retention_ratio
);
}
#[test]
fn test_adaptive_decoder_roundtrip() {
let encoder = AdaptiveSpectralEncoder::new(0.95, 4);
let decoder = AdaptiveSpectralDecoder::new();
let data: Vec<f32> = (0..64).map(|i| (i as f32 * 0.1).sin()).collect();
let (meta, fragments) = encoder.encode_2d(&data, 8, 8).unwrap();
let reconstructed = decoder.decode(&meta, &fragments).unwrap();
assert_eq!(reconstructed.len(), data.len());
let mse: f32 = data
.iter()
.zip(reconstructed.iter())
.map(|(a, b)| (a - b).powi(2))
.sum::<f32>()
/ data.len() as f32;
assert!(mse < 1.0, "MSE too high: {}", mse);
}
#[test]
fn test_adaptive_decoder_progressive() {
let encoder = AdaptiveSpectralEncoder::new(0.95, 8);
let decoder = AdaptiveSpectralDecoder::new();
let data: Vec<f32> = (0..256).map(|i| (i as f32 * 0.05).sin()).collect();
let (meta, fragments) = encoder.encode_2d(&data, 16, 16).unwrap();
let partial1 = decoder.decode_progressive(&meta, &fragments, 1).unwrap();
let partial4 = decoder.decode_progressive(&meta, &fragments, 4).unwrap();
let full = decoder.decode_progressive(&meta, &fragments, 8).unwrap();
assert_eq!(partial1.len(), data.len());
assert_eq!(partial4.len(), data.len());
assert_eq!(full.len(), data.len());
}
#[test]
fn test_batch_encoder_stats() {
let mut batch = AdaptiveBatchEncoder::new(0.95, 4);
for i in 0..5 {
let data: Vec<f32> = (0..64).map(|j| ((i * j) as f32 * 0.1).sin()).collect();
batch.encode_tensor(&data, 8, 8).unwrap();
}
let stats = batch.stats();
assert_eq!(stats.tensors_processed, 5);
assert!(stats.avg_retention > 0.0);
assert!(stats.min_retention <= stats.avg_retention);
assert!(stats.max_retention >= stats.avg_retention);
assert!(batch.compression_ratio() > 0.0);
}
#[test]
fn test_retention_varies_by_tensor() {
let encoder = AdaptiveSpectralEncoder::new(0.95, 4);
let u: Vec<f32> = (0..16).map(|i| i as f32).collect();
let v: Vec<f32> = (0..16).map(|i| i as f32 + 1.0).collect();
let mut low_rank = vec![0.0f32; 256];
for i in 0..16 {
for j in 0..16 {
low_rank[i * 16 + j] = u[i] * v[j];
}
}
let high_rank: Vec<f32> = (0..256)
.map(|i| ((i * 17 + 3) % 100) as f32 / 50.0 - 1.0)
.collect();
let ret_low = encoder.analyze(&low_rank, 16, 16).unwrap();
let ret_high = encoder.analyze(&high_rank, 16, 16).unwrap();
assert!(
ret_low < ret_high,
"Low-rank ({}) should need less retention than high-rank ({})",
ret_low,
ret_high
);
}
#[test]
fn test_empty_tensor() {
let encoder = AdaptiveSpectralEncoder::new(0.95, 4);
let data: Vec<f32> = vec![];
let result = encoder.encode_2d(&data, 0, 0);
assert!(result.is_err() || result.is_ok());
}
}