Skip to main content

Spectrogram

Struct Spectrogram 

Source
pub struct Spectrogram<T: Float> {
    pub data: Vec<Vec<Complex<T>>>,
    pub num_frames: usize,
    pub num_freqs: usize,
    pub sample_rate: T,
    pub config: OverlapConfig,
}
Expand description

Espectrograma - matriz tempo-frequência

Fields§

§data: Vec<Vec<Complex<T>>>

Dados [freq][time]

§num_frames: usize

Número de frames temporais

§num_freqs: usize

Número de bins de frequência

§sample_rate: T

Taxa de amostragem

§config: OverlapConfig

Configuração de overlap

Implementations§

Source§

impl<T: Float> Spectrogram<T>

Source

pub fn new( num_frames: usize, num_freqs: usize, sample_rate: T, config: OverlapConfig, ) -> Self

Cria espectrograma vazio

Source

pub fn get(&self, freq_idx: usize, time_idx: usize) -> Complex<T>

Acessa valor em (freq, time)

Source

pub fn set(&mut self, freq_idx: usize, time_idx: usize, value: Complex<T>)

Define valor em (freq, time)

Source

pub fn magnitude(&self) -> Vec<Vec<T>>

Calcula magnitude do espectrograma

Examples found in repository?
examples/audio_analysis.rs (line 334)
333fn track_multiple_peaks(spec: &Spectrogram<f64>, num_peaks: usize, num_points: usize) {
334    let mag = spec.magnitude();
335    let freqs = spec.frequencies();
336    let times = spec.times();
337
338    let step = spec.num_frames / num_points.min(spec.num_frames);
339
340    println!("   Time (s) │ Peak 1 (Hz) │ Peak 2 (Hz) │ Peak 3 (Hz)");
341    println!("   ─────────┼─────────────┼─────────────┼────────────");
342
343    for frame in (0..spec.num_frames).step_by(step.max(1)) {
344        // Find top N peaks
345        let mut peak_indices: Vec<(usize, f64)> = mag.iter()
346            .enumerate()
347            .map(|(idx, row)| (idx, row[frame]))
348            .collect();
349
350        peak_indices.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
351
352        print!("   {:8.2} │", times[frame]);
353        for i in 0..num_peaks {
354            if i < peak_indices.len() {
355                print!(" {:9.1}  │", freqs[peak_indices[i].0]);
356            } else {
357                print!("     -     │");
358            }
359        }
360        println!();
361    }
362}
363
364/// Test perfect reconstruction with ISTFT
365fn test_reconstruction(
366    processor: &StftProcessor<f64>,
367    spec: &Spectrogram<f64>,
368    original: &[f64],
369    n_samples: usize,
370    margin: usize,
371) {
372    let start = std::time::Instant::now();
373    let reconstructed = processor.inverse(spec).unwrap();
374    let elapsed = start.elapsed();
375
376    let mut error_sum = 0.0;
377    let mut max_error: f64 = 0.0;
378    let mut count = 0;
379
380    for i in margin..(n_samples - margin).min(reconstructed.len()) {
381        let error = (original[i] - reconstructed[i]).abs();
382        error_sum += error * error;
383        max_error = max_error.max(error);
384        count += 1;
385    }
386
387    let rms_error = (error_sum / count as f64).sqrt();
388    let original_rms = (original.iter().map(|&s| s * s).sum::<f64>() / n_samples as f64).sqrt();
389    let snr_db = 20.0 * (original_rms / rms_error).log10();
390
391    println!("   ├─ Reconstruction time: {:.2} ms", elapsed.as_secs_f64() * 1000.0);
392    println!("   ├─ RMS error: {:.3e}", rms_error);
393    println!("   ├─ Max error: {:.3e}", max_error);
394    println!("   ├─ SNR: {:.1} dB", snr_db);
395    println!("   └─ Quality: {}",
396             if snr_db > 100.0 { "⭐ Excellent (>100 dB)" }
397             else if snr_db > 60.0 { "✓ Very Good (>60 dB)" }
398             else if snr_db > 40.0 { "✓ Good (>40 dB)" }
399             else { "⚠ Acceptable" });
400}
401
402/// Detect harmonics in the signal
403fn detect_harmonics(signal: &[f64], sample_rate: f64) {
404    println!("🎼 Harmonic Analysis");
405
406    let config = OverlapConfig::overlap_75(2048); // Larger window for better frequency resolution
407    let processor = StftProcessor::new(config, WindowType::BlackmanHarris).unwrap();
408    let spec = processor.process(signal, sample_rate).unwrap();
409
410    let mag = spec.magnitude();
411    let freqs = spec.frequencies();
412
413    // Average magnitude across all frames
414    let mut avg_mag: Vec<f64> = vec![0.0; spec.num_freqs];
415    for freq_idx in 0..spec.num_freqs {
416        let sum: f64 = mag[freq_idx].iter().sum();
417        avg_mag[freq_idx] = sum / spec.num_frames as f64;
418    }
419
420    // Find peaks in the spectrum
421    let mut peaks = Vec::new();
422    for i in 2..avg_mag.len() - 2 {
423        if avg_mag[i] > avg_mag[i-1] && avg_mag[i] > avg_mag[i+1] &&
424           avg_mag[i] > avg_mag[i-2] && avg_mag[i] > avg_mag[i+2] {
425            let threshold = avg_mag.iter().cloned().fold(0.0, f64::max) * 0.05;
426            if avg_mag[i] > threshold {
427                peaks.push((freqs[i], avg_mag[i]));
428            }
429        }
430    }
431
432    peaks.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
433
434    println!("   Detected {} significant frequency peaks:", peaks.len().min(10));
435
436    if peaks.is_empty() {
437        println!("   └─ No significant peaks detected");
438        return;
439    }
440
441    // Display top 10 peaks
442    for (idx, (freq, mag)) in peaks.iter().take(10).enumerate() {
443        let note = frequency_to_note(*freq);
444        println!("   {}─ {:.1} Hz ({}) │ magnitude: {:.4}",
445                 if idx == peaks.len().min(10) - 1 { "└" } else { "├" },
446                 freq, note, mag);
447    }
448
449    // Detect harmonic relationships
450    if peaks.len() >= 2 {
451        println!("\n   Harmonic Relationships:");
452        let fundamental = peaks[0].0;
453        let mut found_harmonics = false;
454
455        for (idx, (freq, _)) in peaks.iter().skip(1).take(5).enumerate() {
456            let ratio = freq / fundamental;
457            if (ratio - ratio.round()).abs() < 0.05 {
458                println!("   {}─ {:.1} Hz ≈ {}x fundamental ({:.2}x)",
459                         if idx == 4 { "└" } else { "├" },
460                         freq, ratio.round() as i32, ratio);
461                found_harmonics = true;
462            }
463        }
464
465        if !found_harmonics {
466            println!("   └─ No clear harmonic relationships detected");
467        }
468    }
469}
Source

pub fn power(&self) -> Vec<Vec<T>>

Calcula potência (magnitude²)

Examples found in repository?
examples/audio_analysis.rs (line 290)
289fn detect_transients_enhanced(spec: &Spectrogram<f64>) {
290    let power = spec.power();
291    let times = spec.times();
292
293    let mut frame_energy: Vec<f64> = Vec::new();
294    for frame in 0..spec.num_frames {
295        let energy: f64 = power.iter()
296            .map(|row| row[frame])
297            .sum();
298        frame_energy.push(energy);
299    }
300
301    // Calculate onset strength (energy difference)
302    let mut onset_strength: Vec<f64> = vec![0.0];
303    for i in 1..frame_energy.len() {
304        let diff = (frame_energy[i] - frame_energy[i - 1]).max(0.0);
305        onset_strength.push(diff);
306    }
307
308    let avg_onset: f64 = onset_strength.iter().sum::<f64>() / onset_strength.len() as f64;
309    let threshold = avg_onset * 3.0;
310
311    let mut transients = Vec::new();
312    for i in 1..onset_strength.len() - 1 {
313        if onset_strength[i] > threshold &&
314           onset_strength[i] > onset_strength[i - 1] &&
315           onset_strength[i] > onset_strength[i + 1] {
316            transients.push((times[i], onset_strength[i], frame_energy[i]));
317        }
318    }
319
320    println!("   Detected {} transient(s):", transients.len());
321    if transients.is_empty() {
322        println!("   └─ No significant transients found");
323    } else {
324        for (idx, (time, strength, energy)) in transients.iter().enumerate().take(5) {
325            println!("   {}─ t={:.3}s │ strength={:.2} │ energy={:.1}",
326                     if idx == transients.len() - 1 { "└" } else { "├" },
327                     time, strength, energy);
328        }
329    }
330}
331
332/// Track multiple frequency peaks simultaneously
333fn track_multiple_peaks(spec: &Spectrogram<f64>, num_peaks: usize, num_points: usize) {
334    let mag = spec.magnitude();
335    let freqs = spec.frequencies();
336    let times = spec.times();
337
338    let step = spec.num_frames / num_points.min(spec.num_frames);
339
340    println!("   Time (s) │ Peak 1 (Hz) │ Peak 2 (Hz) │ Peak 3 (Hz)");
341    println!("   ─────────┼─────────────┼─────────────┼────────────");
342
343    for frame in (0..spec.num_frames).step_by(step.max(1)) {
344        // Find top N peaks
345        let mut peak_indices: Vec<(usize, f64)> = mag.iter()
346            .enumerate()
347            .map(|(idx, row)| (idx, row[frame]))
348            .collect();
349
350        peak_indices.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
351
352        print!("   {:8.2} │", times[frame]);
353        for i in 0..num_peaks {
354            if i < peak_indices.len() {
355                print!(" {:9.1}  │", freqs[peak_indices[i].0]);
356            } else {
357                print!("     -     │");
358            }
359        }
360        println!();
361    }
362}
363
364/// Test perfect reconstruction with ISTFT
365fn test_reconstruction(
366    processor: &StftProcessor<f64>,
367    spec: &Spectrogram<f64>,
368    original: &[f64],
369    n_samples: usize,
370    margin: usize,
371) {
372    let start = std::time::Instant::now();
373    let reconstructed = processor.inverse(spec).unwrap();
374    let elapsed = start.elapsed();
375
376    let mut error_sum = 0.0;
377    let mut max_error: f64 = 0.0;
378    let mut count = 0;
379
380    for i in margin..(n_samples - margin).min(reconstructed.len()) {
381        let error = (original[i] - reconstructed[i]).abs();
382        error_sum += error * error;
383        max_error = max_error.max(error);
384        count += 1;
385    }
386
387    let rms_error = (error_sum / count as f64).sqrt();
388    let original_rms = (original.iter().map(|&s| s * s).sum::<f64>() / n_samples as f64).sqrt();
389    let snr_db = 20.0 * (original_rms / rms_error).log10();
390
391    println!("   ├─ Reconstruction time: {:.2} ms", elapsed.as_secs_f64() * 1000.0);
392    println!("   ├─ RMS error: {:.3e}", rms_error);
393    println!("   ├─ Max error: {:.3e}", max_error);
394    println!("   ├─ SNR: {:.1} dB", snr_db);
395    println!("   └─ Quality: {}",
396             if snr_db > 100.0 { "⭐ Excellent (>100 dB)" }
397             else if snr_db > 60.0 { "✓ Very Good (>60 dB)" }
398             else if snr_db > 40.0 { "✓ Good (>40 dB)" }
399             else { "⚠ Acceptable" });
400}
401
402/// Detect harmonics in the signal
403fn detect_harmonics(signal: &[f64], sample_rate: f64) {
404    println!("🎼 Harmonic Analysis");
405
406    let config = OverlapConfig::overlap_75(2048); // Larger window for better frequency resolution
407    let processor = StftProcessor::new(config, WindowType::BlackmanHarris).unwrap();
408    let spec = processor.process(signal, sample_rate).unwrap();
409
410    let mag = spec.magnitude();
411    let freqs = spec.frequencies();
412
413    // Average magnitude across all frames
414    let mut avg_mag: Vec<f64> = vec![0.0; spec.num_freqs];
415    for freq_idx in 0..spec.num_freqs {
416        let sum: f64 = mag[freq_idx].iter().sum();
417        avg_mag[freq_idx] = sum / spec.num_frames as f64;
418    }
419
420    // Find peaks in the spectrum
421    let mut peaks = Vec::new();
422    for i in 2..avg_mag.len() - 2 {
423        if avg_mag[i] > avg_mag[i-1] && avg_mag[i] > avg_mag[i+1] &&
424           avg_mag[i] > avg_mag[i-2] && avg_mag[i] > avg_mag[i+2] {
425            let threshold = avg_mag.iter().cloned().fold(0.0, f64::max) * 0.05;
426            if avg_mag[i] > threshold {
427                peaks.push((freqs[i], avg_mag[i]));
428            }
429        }
430    }
431
432    peaks.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
433
434    println!("   Detected {} significant frequency peaks:", peaks.len().min(10));
435
436    if peaks.is_empty() {
437        println!("   └─ No significant peaks detected");
438        return;
439    }
440
441    // Display top 10 peaks
442    for (idx, (freq, mag)) in peaks.iter().take(10).enumerate() {
443        let note = frequency_to_note(*freq);
444        println!("   {}─ {:.1} Hz ({}) │ magnitude: {:.4}",
445                 if idx == peaks.len().min(10) - 1 { "└" } else { "├" },
446                 freq, note, mag);
447    }
448
449    // Detect harmonic relationships
450    if peaks.len() >= 2 {
451        println!("\n   Harmonic Relationships:");
452        let fundamental = peaks[0].0;
453        let mut found_harmonics = false;
454
455        for (idx, (freq, _)) in peaks.iter().skip(1).take(5).enumerate() {
456            let ratio = freq / fundamental;
457            if (ratio - ratio.round()).abs() < 0.05 {
458                println!("   {}─ {:.1} Hz ≈ {}x fundamental ({:.2}x)",
459                         if idx == 4 { "└" } else { "├" },
460                         freq, ratio.round() as i32, ratio);
461                found_harmonics = true;
462            }
463        }
464
465        if !found_harmonics {
466            println!("   └─ No clear harmonic relationships detected");
467        }
468    }
469}
470
471/// Convert frequency to musical note
472fn frequency_to_note(freq: f64) -> String {
473    let a4 = 440.0;
474    let notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
475
476    let half_steps = 12.0 * (freq / a4).log2();
477    let note_index = ((half_steps.round() as i32 + 9) % 12 + 12) % 12;
478    let octave = 4 + ((half_steps.round() as i32 + 9) / 12);
479    let cents = ((half_steps - half_steps.round()) * 100.0) as i32;
480
481    if cents.abs() > 10 {
482        format!("{}{} {:+}¢", notes[note_index as usize], octave, cents)
483    } else {
484        format!("{}{}", notes[note_index as usize], octave)
485    }
486}
487
488/// Analyze phase coherence across frequency bands
489fn analyze_phase_coherence(signal: &[f64], sample_rate: f64) {
490    println!("🌀 Phase Coherence Analysis");
491
492    let config = OverlapConfig::overlap_75(1024);
493    let processor = StftProcessor::new(config, WindowType::Hann).unwrap();
494    let spec = processor.process(signal, sample_rate).unwrap();
495
496    let phase = spec.phase();
497    let freqs = spec.frequencies();
498
499    // Analyze phase stability over time
500    let mut phase_variance: Vec<f64> = Vec::new();
501
502    for freq_idx in 0..spec.num_freqs.min(100) { // Limit to lower frequencies
503        if spec.num_frames < 2 {
504            continue;
505        }
506
507        // Calculate phase differences between consecutive frames
508        let mut diffs = Vec::new();
509        for frame in 1..spec.num_frames {
510            let mut diff = phase[freq_idx][frame] - phase[freq_idx][frame - 1];
511
512            // Unwrap phase (handle 2π discontinuities)
513            while diff > PI { diff -= 2.0 * PI; }
514            while diff < -PI { diff += 2.0 * PI; }
515
516            diffs.push(diff);
517        }
518
519        if diffs.is_empty() {
520            continue;
521        }
522
523        // Calculate variance
524        let mean: f64 = diffs.iter().sum::<f64>() / diffs.len() as f64;
525        let variance: f64 = diffs.iter()
526            .map(|&d| (d - mean).powi(2))
527            .sum::<f64>() / diffs.len() as f64;
528
529        phase_variance.push(variance);
530    }
531
532    if phase_variance.is_empty() {
533        println!("   └─ Insufficient data for phase analysis");
534        return;
535    }
536
537    let avg_variance = phase_variance.iter().sum::<f64>() / phase_variance.len() as f64;
538    let coherence_score = (-avg_variance).exp();
539
540    println!("   Phase Statistics:");
541    println!("   ├─ Average phase variance: {:.4} rad²", avg_variance);
542    println!("   ├─ Phase coherence score: {:.4} (0-1)", coherence_score);
543    println!("   └─ Interpretation: {} phase stability",
544             if coherence_score > 0.9 { "Excellent" }
545             else if coherence_score > 0.7 { "Good" }
546             else if coherence_score > 0.5 { "Moderate" }
547             else { "Low" });
548
549    // Find frequency bands with highest phase stability
550    let mut indexed_variance: Vec<(usize, f64)> = phase_variance.iter()
551        .enumerate()
552        .map(|(i, &v)| (i, v))
553        .collect();
554    indexed_variance.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
555
556    println!("\n   Most Stable Frequency Bands:");
557    for (idx, (freq_idx, variance)) in indexed_variance.iter().take(5).enumerate() {
558        let stability = (-variance).exp();
559        println!("   {}─ {:.1} Hz │ stability: {:.4}",
560                 if idx == 4 { "└" } else { "├" },
561                 freqs[*freq_idx], stability);
562    }
563}
564
565/// Estimate temporal SNR (Signal-to-Noise Ratio) over time
566fn estimate_temporal_snr(signal: &[f64], sample_rate: f64) {
567    println!("📡 Temporal SNR Estimation");
568
569    let config = OverlapConfig::overlap_75(1024);
570    let processor = StftProcessor::new(config, WindowType::Hann).unwrap();
571    let spec = processor.process(signal, sample_rate).unwrap();
572
573    let power = spec.power();
574    let times = spec.times();
575
576    // Calculate energy per frame
577    let mut frame_energy: Vec<f64> = Vec::new();
578    for frame in 0..spec.num_frames {
579        let energy: f64 = power.iter().map(|row| row[frame]).sum();
580        frame_energy.push(energy);
581    }
582
583    if frame_energy.is_empty() {
584        println!("   └─ No data available");
585        return;
586    }
587
588    // Estimate noise floor (minimum energy in quiet regions)
589    let mut sorted_energy = frame_energy.clone();
590    sorted_energy.sort_by(|a, b| a.partial_cmp(b).unwrap());
591    let noise_floor = sorted_energy[sorted_energy.len() / 10]; // 10th percentile
592
593    // Calculate SNR for each frame
594    let snr_db: Vec<f64> = frame_energy.iter()
595        .map(|&e| {
596            let signal_power = (e - noise_floor).max(noise_floor * 0.01);
597            10.0 * (signal_power / noise_floor).log10()
598        })
599        .collect();
600
601    let avg_snr = snr_db.iter().sum::<f64>() / snr_db.len() as f64;
602    let max_snr = snr_db.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
603    let min_snr = snr_db.iter().cloned().fold(f64::INFINITY, f64::min);
604
605    println!("   SNR Statistics:");
606    println!("   ├─ Average SNR: {:.1} dB", avg_snr);
607    println!("   ├─ Peak SNR: {:.1} dB", max_snr);
608    println!("   ├─ Minimum SNR: {:.1} dB", min_snr);
609    println!("   ├─ Dynamic range: {:.1} dB", max_snr - min_snr);
610    println!("   └─ Noise floor: {:.2e} (power units)", noise_floor);
611
612    // Show SNR evolution over time
613    println!("\n   SNR Evolution (10 snapshots):");
614    println!("   Time (s) │ SNR (dB) │ Signal Quality");
615    println!("   ─────────┼──────────┼────────────────");
616
617    let step = spec.num_frames / 10.min(spec.num_frames);
618    for frame in (0..spec.num_frames).step_by(step.max(1)) {
619        let quality = if snr_db[frame] > 40.0 { "⭐ Excellent" }
620                     else if snr_db[frame] > 30.0 { "✓ Very Good" }
621                     else if snr_db[frame] > 20.0 { "✓ Good" }
622                     else if snr_db[frame] > 10.0 { "○ Fair" }
623                     else { "⚠ Poor" };
624
625        println!("   {:8.2} │ {:8.1} │ {}", times[frame], snr_db[frame], quality);
626    }
627
628    // Identify high-quality segments
629    let high_quality_threshold = 30.0;
630    let high_quality_frames: Vec<usize> = snr_db.iter()
631        .enumerate()
632        .filter(|(_, &snr)| snr > high_quality_threshold)
633        .map(|(i, _)| i)
634        .collect();
635
636    let coverage = (high_quality_frames.len() as f64 / spec.num_frames as f64) * 100.0;
637    println!("\n   High-Quality Coverage:");
638    println!("   ├─ Frames above {} dB: {}/{}", high_quality_threshold,
639             high_quality_frames.len(), spec.num_frames);
640    println!("   └─ Coverage: {:.1}%", coverage);
641}
Source

pub fn phase(&self) -> Vec<Vec<T>>

Calcula fase

Examples found in repository?
examples/audio_analysis.rs (line 496)
489fn analyze_phase_coherence(signal: &[f64], sample_rate: f64) {
490    println!("🌀 Phase Coherence Analysis");
491
492    let config = OverlapConfig::overlap_75(1024);
493    let processor = StftProcessor::new(config, WindowType::Hann).unwrap();
494    let spec = processor.process(signal, sample_rate).unwrap();
495
496    let phase = spec.phase();
497    let freqs = spec.frequencies();
498
499    // Analyze phase stability over time
500    let mut phase_variance: Vec<f64> = Vec::new();
501
502    for freq_idx in 0..spec.num_freqs.min(100) { // Limit to lower frequencies
503        if spec.num_frames < 2 {
504            continue;
505        }
506
507        // Calculate phase differences between consecutive frames
508        let mut diffs = Vec::new();
509        for frame in 1..spec.num_frames {
510            let mut diff = phase[freq_idx][frame] - phase[freq_idx][frame - 1];
511
512            // Unwrap phase (handle 2π discontinuities)
513            while diff > PI { diff -= 2.0 * PI; }
514            while diff < -PI { diff += 2.0 * PI; }
515
516            diffs.push(diff);
517        }
518
519        if diffs.is_empty() {
520            continue;
521        }
522
523        // Calculate variance
524        let mean: f64 = diffs.iter().sum::<f64>() / diffs.len() as f64;
525        let variance: f64 = diffs.iter()
526            .map(|&d| (d - mean).powi(2))
527            .sum::<f64>() / diffs.len() as f64;
528
529        phase_variance.push(variance);
530    }
531
532    if phase_variance.is_empty() {
533        println!("   └─ Insufficient data for phase analysis");
534        return;
535    }
536
537    let avg_variance = phase_variance.iter().sum::<f64>() / phase_variance.len() as f64;
538    let coherence_score = (-avg_variance).exp();
539
540    println!("   Phase Statistics:");
541    println!("   ├─ Average phase variance: {:.4} rad²", avg_variance);
542    println!("   ├─ Phase coherence score: {:.4} (0-1)", coherence_score);
543    println!("   └─ Interpretation: {} phase stability",
544             if coherence_score > 0.9 { "Excellent" }
545             else if coherence_score > 0.7 { "Good" }
546             else if coherence_score > 0.5 { "Moderate" }
547             else { "Low" });
548
549    // Find frequency bands with highest phase stability
550    let mut indexed_variance: Vec<(usize, f64)> = phase_variance.iter()
551        .enumerate()
552        .map(|(i, &v)| (i, v))
553        .collect();
554    indexed_variance.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
555
556    println!("\n   Most Stable Frequency Bands:");
557    for (idx, (freq_idx, variance)) in indexed_variance.iter().take(5).enumerate() {
558        let stability = (-variance).exp();
559        println!("   {}─ {:.1} Hz │ stability: {:.4}",
560                 if idx == 4 { "└" } else { "├" },
561                 freqs[*freq_idx], stability);
562    }
563}
Source

pub fn magnitude_db(&self) -> Vec<Vec<T>>

Converte magnitude para dB

Examples found in repository?
examples/audio_analysis.rs (line 234)
233fn visualize_spectrogram_enhanced(spec: &Spectrogram<f64>, max_frames: usize) {
234    let mag_db = spec.magnitude_db();
235    let freqs = spec.frequencies();
236
237    let max_freq_idx = freqs.iter()
238        .position(|&f| f > 3000.0)
239        .unwrap_or(spec.num_freqs)
240        .min(30);
241
242    let num_frames = spec.num_frames.min(max_frames);
243
244    println!("   Frequency │ Time → (dB scale: █ > -10, ▓ > -20, ▒ > -30, ░ > -40)");
245    println!("   ──────────┼{}", "─".repeat(num_frames));
246
247    for freq_idx in (0..max_freq_idx).rev().step_by(1) {
248        print!("   {:6.0} Hz │ ", freqs[freq_idx]);
249
250        for frame in 0..num_frames {
251            let db = mag_db[freq_idx][frame];
252            let symbol = match db {
253                db if db > -10.0 => '█',
254                db if db > -20.0 => '▓',
255                db if db > -30.0 => '▒',
256                db if db > -40.0 => '░',
257                db if db > -50.0 => '·',
258                _ => ' ',
259            };
260            print!("{}", symbol);
261        }
262        println!();
263    }
264    println!("   ──────────┴{}", "─".repeat(num_frames));
265}
Source

pub fn frequencies(&self) -> Vec<T>

Retorna vetor de frequências (Hz)

Examples found in repository?
examples/audio_analysis.rs (line 235)
233fn visualize_spectrogram_enhanced(spec: &Spectrogram<f64>, max_frames: usize) {
234    let mag_db = spec.magnitude_db();
235    let freqs = spec.frequencies();
236
237    let max_freq_idx = freqs.iter()
238        .position(|&f| f > 3000.0)
239        .unwrap_or(spec.num_freqs)
240        .min(30);
241
242    let num_frames = spec.num_frames.min(max_frames);
243
244    println!("   Frequency │ Time → (dB scale: █ > -10, ▓ > -20, ▒ > -30, ░ > -40)");
245    println!("   ──────────┼{}", "─".repeat(num_frames));
246
247    for freq_idx in (0..max_freq_idx).rev().step_by(1) {
248        print!("   {:6.0} Hz │ ", freqs[freq_idx]);
249
250        for frame in 0..num_frames {
251            let db = mag_db[freq_idx][frame];
252            let symbol = match db {
253                db if db > -10.0 => '█',
254                db if db > -20.0 => '▓',
255                db if db > -30.0 => '▒',
256                db if db > -40.0 => '░',
257                db if db > -50.0 => '·',
258                _ => ' ',
259            };
260            print!("{}", symbol);
261        }
262        println!();
263    }
264    println!("   ──────────┴{}", "─".repeat(num_frames));
265}
266
267/// Analyze spectral evolution over time
268fn analyze_time_evolution(spec: &Spectrogram<f64>, num_snapshots: usize) {
269    let centroids = spec.spectral_centroid();
270    let bandwidths = spec.spectral_bandwidth();
271    let times = spec.times();
272
273    let step = spec.num_frames / num_snapshots.min(spec.num_frames);
274
275    println!("   Time (s) │ Centroid (Hz) │ Bandwidth (Hz) │ Dynamics");
276    println!("   ─────────┼───────────────┼────────────────┼──────────");
277
278    for frame in (0..spec.num_frames).step_by(step.max(1)) {
279        let dynamics = if centroids[frame] > 800.0 { "High" }
280                      else if centroids[frame] > 500.0 { "Mid" }
281                      else { "Low" };
282
283        println!("   {:8.2} │  {:10.1}  │   {:10.1}   │ {}",
284                 times[frame], centroids[frame], bandwidths[frame], dynamics);
285    }
286}
287
288/// Enhanced transient detection with onset strength
289fn detect_transients_enhanced(spec: &Spectrogram<f64>) {
290    let power = spec.power();
291    let times = spec.times();
292
293    let mut frame_energy: Vec<f64> = Vec::new();
294    for frame in 0..spec.num_frames {
295        let energy: f64 = power.iter()
296            .map(|row| row[frame])
297            .sum();
298        frame_energy.push(energy);
299    }
300
301    // Calculate onset strength (energy difference)
302    let mut onset_strength: Vec<f64> = vec![0.0];
303    for i in 1..frame_energy.len() {
304        let diff = (frame_energy[i] - frame_energy[i - 1]).max(0.0);
305        onset_strength.push(diff);
306    }
307
308    let avg_onset: f64 = onset_strength.iter().sum::<f64>() / onset_strength.len() as f64;
309    let threshold = avg_onset * 3.0;
310
311    let mut transients = Vec::new();
312    for i in 1..onset_strength.len() - 1 {
313        if onset_strength[i] > threshold &&
314           onset_strength[i] > onset_strength[i - 1] &&
315           onset_strength[i] > onset_strength[i + 1] {
316            transients.push((times[i], onset_strength[i], frame_energy[i]));
317        }
318    }
319
320    println!("   Detected {} transient(s):", transients.len());
321    if transients.is_empty() {
322        println!("   └─ No significant transients found");
323    } else {
324        for (idx, (time, strength, energy)) in transients.iter().enumerate().take(5) {
325            println!("   {}─ t={:.3}s │ strength={:.2} │ energy={:.1}",
326                     if idx == transients.len() - 1 { "└" } else { "├" },
327                     time, strength, energy);
328        }
329    }
330}
331
332/// Track multiple frequency peaks simultaneously
333fn track_multiple_peaks(spec: &Spectrogram<f64>, num_peaks: usize, num_points: usize) {
334    let mag = spec.magnitude();
335    let freqs = spec.frequencies();
336    let times = spec.times();
337
338    let step = spec.num_frames / num_points.min(spec.num_frames);
339
340    println!("   Time (s) │ Peak 1 (Hz) │ Peak 2 (Hz) │ Peak 3 (Hz)");
341    println!("   ─────────┼─────────────┼─────────────┼────────────");
342
343    for frame in (0..spec.num_frames).step_by(step.max(1)) {
344        // Find top N peaks
345        let mut peak_indices: Vec<(usize, f64)> = mag.iter()
346            .enumerate()
347            .map(|(idx, row)| (idx, row[frame]))
348            .collect();
349
350        peak_indices.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
351
352        print!("   {:8.2} │", times[frame]);
353        for i in 0..num_peaks {
354            if i < peak_indices.len() {
355                print!(" {:9.1}  │", freqs[peak_indices[i].0]);
356            } else {
357                print!("     -     │");
358            }
359        }
360        println!();
361    }
362}
363
364/// Test perfect reconstruction with ISTFT
365fn test_reconstruction(
366    processor: &StftProcessor<f64>,
367    spec: &Spectrogram<f64>,
368    original: &[f64],
369    n_samples: usize,
370    margin: usize,
371) {
372    let start = std::time::Instant::now();
373    let reconstructed = processor.inverse(spec).unwrap();
374    let elapsed = start.elapsed();
375
376    let mut error_sum = 0.0;
377    let mut max_error: f64 = 0.0;
378    let mut count = 0;
379
380    for i in margin..(n_samples - margin).min(reconstructed.len()) {
381        let error = (original[i] - reconstructed[i]).abs();
382        error_sum += error * error;
383        max_error = max_error.max(error);
384        count += 1;
385    }
386
387    let rms_error = (error_sum / count as f64).sqrt();
388    let original_rms = (original.iter().map(|&s| s * s).sum::<f64>() / n_samples as f64).sqrt();
389    let snr_db = 20.0 * (original_rms / rms_error).log10();
390
391    println!("   ├─ Reconstruction time: {:.2} ms", elapsed.as_secs_f64() * 1000.0);
392    println!("   ├─ RMS error: {:.3e}", rms_error);
393    println!("   ├─ Max error: {:.3e}", max_error);
394    println!("   ├─ SNR: {:.1} dB", snr_db);
395    println!("   └─ Quality: {}",
396             if snr_db > 100.0 { "⭐ Excellent (>100 dB)" }
397             else if snr_db > 60.0 { "✓ Very Good (>60 dB)" }
398             else if snr_db > 40.0 { "✓ Good (>40 dB)" }
399             else { "⚠ Acceptable" });
400}
401
402/// Detect harmonics in the signal
403fn detect_harmonics(signal: &[f64], sample_rate: f64) {
404    println!("🎼 Harmonic Analysis");
405
406    let config = OverlapConfig::overlap_75(2048); // Larger window for better frequency resolution
407    let processor = StftProcessor::new(config, WindowType::BlackmanHarris).unwrap();
408    let spec = processor.process(signal, sample_rate).unwrap();
409
410    let mag = spec.magnitude();
411    let freqs = spec.frequencies();
412
413    // Average magnitude across all frames
414    let mut avg_mag: Vec<f64> = vec![0.0; spec.num_freqs];
415    for freq_idx in 0..spec.num_freqs {
416        let sum: f64 = mag[freq_idx].iter().sum();
417        avg_mag[freq_idx] = sum / spec.num_frames as f64;
418    }
419
420    // Find peaks in the spectrum
421    let mut peaks = Vec::new();
422    for i in 2..avg_mag.len() - 2 {
423        if avg_mag[i] > avg_mag[i-1] && avg_mag[i] > avg_mag[i+1] &&
424           avg_mag[i] > avg_mag[i-2] && avg_mag[i] > avg_mag[i+2] {
425            let threshold = avg_mag.iter().cloned().fold(0.0, f64::max) * 0.05;
426            if avg_mag[i] > threshold {
427                peaks.push((freqs[i], avg_mag[i]));
428            }
429        }
430    }
431
432    peaks.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
433
434    println!("   Detected {} significant frequency peaks:", peaks.len().min(10));
435
436    if peaks.is_empty() {
437        println!("   └─ No significant peaks detected");
438        return;
439    }
440
441    // Display top 10 peaks
442    for (idx, (freq, mag)) in peaks.iter().take(10).enumerate() {
443        let note = frequency_to_note(*freq);
444        println!("   {}─ {:.1} Hz ({}) │ magnitude: {:.4}",
445                 if idx == peaks.len().min(10) - 1 { "└" } else { "├" },
446                 freq, note, mag);
447    }
448
449    // Detect harmonic relationships
450    if peaks.len() >= 2 {
451        println!("\n   Harmonic Relationships:");
452        let fundamental = peaks[0].0;
453        let mut found_harmonics = false;
454
455        for (idx, (freq, _)) in peaks.iter().skip(1).take(5).enumerate() {
456            let ratio = freq / fundamental;
457            if (ratio - ratio.round()).abs() < 0.05 {
458                println!("   {}─ {:.1} Hz ≈ {}x fundamental ({:.2}x)",
459                         if idx == 4 { "└" } else { "├" },
460                         freq, ratio.round() as i32, ratio);
461                found_harmonics = true;
462            }
463        }
464
465        if !found_harmonics {
466            println!("   └─ No clear harmonic relationships detected");
467        }
468    }
469}
470
471/// Convert frequency to musical note
472fn frequency_to_note(freq: f64) -> String {
473    let a4 = 440.0;
474    let notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
475
476    let half_steps = 12.0 * (freq / a4).log2();
477    let note_index = ((half_steps.round() as i32 + 9) % 12 + 12) % 12;
478    let octave = 4 + ((half_steps.round() as i32 + 9) / 12);
479    let cents = ((half_steps - half_steps.round()) * 100.0) as i32;
480
481    if cents.abs() > 10 {
482        format!("{}{} {:+}¢", notes[note_index as usize], octave, cents)
483    } else {
484        format!("{}{}", notes[note_index as usize], octave)
485    }
486}
487
488/// Analyze phase coherence across frequency bands
489fn analyze_phase_coherence(signal: &[f64], sample_rate: f64) {
490    println!("🌀 Phase Coherence Analysis");
491
492    let config = OverlapConfig::overlap_75(1024);
493    let processor = StftProcessor::new(config, WindowType::Hann).unwrap();
494    let spec = processor.process(signal, sample_rate).unwrap();
495
496    let phase = spec.phase();
497    let freqs = spec.frequencies();
498
499    // Analyze phase stability over time
500    let mut phase_variance: Vec<f64> = Vec::new();
501
502    for freq_idx in 0..spec.num_freqs.min(100) { // Limit to lower frequencies
503        if spec.num_frames < 2 {
504            continue;
505        }
506
507        // Calculate phase differences between consecutive frames
508        let mut diffs = Vec::new();
509        for frame in 1..spec.num_frames {
510            let mut diff = phase[freq_idx][frame] - phase[freq_idx][frame - 1];
511
512            // Unwrap phase (handle 2π discontinuities)
513            while diff > PI { diff -= 2.0 * PI; }
514            while diff < -PI { diff += 2.0 * PI; }
515
516            diffs.push(diff);
517        }
518
519        if diffs.is_empty() {
520            continue;
521        }
522
523        // Calculate variance
524        let mean: f64 = diffs.iter().sum::<f64>() / diffs.len() as f64;
525        let variance: f64 = diffs.iter()
526            .map(|&d| (d - mean).powi(2))
527            .sum::<f64>() / diffs.len() as f64;
528
529        phase_variance.push(variance);
530    }
531
532    if phase_variance.is_empty() {
533        println!("   └─ Insufficient data for phase analysis");
534        return;
535    }
536
537    let avg_variance = phase_variance.iter().sum::<f64>() / phase_variance.len() as f64;
538    let coherence_score = (-avg_variance).exp();
539
540    println!("   Phase Statistics:");
541    println!("   ├─ Average phase variance: {:.4} rad²", avg_variance);
542    println!("   ├─ Phase coherence score: {:.4} (0-1)", coherence_score);
543    println!("   └─ Interpretation: {} phase stability",
544             if coherence_score > 0.9 { "Excellent" }
545             else if coherence_score > 0.7 { "Good" }
546             else if coherence_score > 0.5 { "Moderate" }
547             else { "Low" });
548
549    // Find frequency bands with highest phase stability
550    let mut indexed_variance: Vec<(usize, f64)> = phase_variance.iter()
551        .enumerate()
552        .map(|(i, &v)| (i, v))
553        .collect();
554    indexed_variance.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
555
556    println!("\n   Most Stable Frequency Bands:");
557    for (idx, (freq_idx, variance)) in indexed_variance.iter().take(5).enumerate() {
558        let stability = (-variance).exp();
559        println!("   {}─ {:.1} Hz │ stability: {:.4}",
560                 if idx == 4 { "└" } else { "├" },
561                 freqs[*freq_idx], stability);
562    }
563}
Source

pub fn times(&self) -> Vec<T>

Retorna vetor de tempos (segundos)

Examples found in repository?
examples/audio_analysis.rs (line 168)
142fn perform_detailed_analysis(signal: &[f64], sample_rate: f64, _duration: f64) {
143    let n_samples = signal.len();
144
145    // STFT configuration
146    let window_size = 1024; // Larger window for better frequency resolution
147    let config = OverlapConfig::overlap_75(window_size);
148
149    println!("⚙️  STFT Configuration");
150    println!("   ├─ Window: Hann (optimal for general use)");
151    println!("   ├─ Window size: {} samples", config.window_size);
152    println!("   ├─ Hop size: {} samples", config.hop_size);
153    println!("   ├─ Overlap: {:.1}%", config.overlap_percent());
154    println!("   ├─ Time resolution: {:.2} ms", (config.hop_size as f64 / sample_rate) * 1000.0);
155    println!("   └─ Frequency resolution: {:.2} Hz\n", sample_rate / (config.window_size as f64));
156
157    // Process STFT
158    println!("🔄 Processing STFT...");
159    let start = std::time::Instant::now();
160    let processor = StftProcessor::new(config, WindowType::Hann).unwrap();
161    let spec = processor.process(signal, sample_rate).unwrap();
162    let elapsed = start.elapsed();
163
164    println!("   ✓ Spectrogram computed in {:.2} ms", elapsed.as_secs_f64() * 1000.0);
165    println!("   ├─ Time frames: {}", spec.num_frames);
166    println!("   ├─ Frequency bins: {}", spec.num_freqs);
167    println!("   ├─ Data points: {}", spec.num_frames * spec.num_freqs);
168    println!("   └─ Coverage: {:.2} s\n", spec.times().last().unwrap());
169
170    // Advanced spectral analysis
171    println!("📈 Advanced Spectral Features");
172
173    let centroids = spec.spectral_centroid();
174    let bandwidths = spec.spectral_bandwidth();
175    let flatness = spec.spectral_flatness();
176    let rolloff_85 = spec.spectral_rolloff(85.0);
177    let rolloff_95 = spec.spectral_rolloff(95.0);
178
179    let avg_centroid = centroids.iter().sum::<f64>() / centroids.len() as f64;
180    let avg_bandwidth = bandwidths.iter().sum::<f64>() / bandwidths.len() as f64;
181    let avg_flatness = flatness.iter().sum::<f64>() / flatness.len() as f64;
182    let avg_rolloff_85 = rolloff_85.iter().sum::<f64>() / rolloff_85.len() as f64;
183    let avg_rolloff_95 = rolloff_95.iter().sum::<f64>() / rolloff_95.len() as f64;
184
185    println!("   Spectral Centroid (brightness indicator):");
186    println!("   ├─ Average: {:.1} Hz", avg_centroid);
187    println!("   ├─ Min: {:.1} Hz", centroids.iter().cloned().fold(f64::INFINITY, f64::min));
188    println!("   ├─ Max: {:.1} Hz", centroids.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
189    println!("   └─ Std dev: {:.1} Hz\n",
190             ((centroids.iter().map(|&c| (c - avg_centroid).powi(2)).sum::<f64>()
191               / centroids.len() as f64).sqrt()));
192
193    println!("   Spectral Bandwidth (spread around centroid):");
194    println!("   ├─ Average: {:.1} Hz", avg_bandwidth);
195    println!("   └─ Range: {:.1} - {:.1} Hz\n",
196             bandwidths.iter().cloned().fold(f64::INFINITY, f64::min),
197             bandwidths.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
198
199    println!("   Spectral Flatness (tonality measure):");
200    println!("   ├─ Average: {:.5} (0=pure tone, 1=white noise)", avg_flatness);
201    println!("   └─ Interpretation: {} signal\n",
202             if avg_flatness < 0.1 { "Highly tonal" }
203             else if avg_flatness < 0.3 { "Tonal" }
204             else if avg_flatness < 0.7 { "Mixed" }
205             else { "Noisy" });
206
207    println!("   Spectral Rolloff:");
208    println!("   ├─ 85% energy below: {:.1} Hz", avg_rolloff_85);
209    println!("   └─ 95% energy below: {:.1} Hz\n", avg_rolloff_95);
210
211    // Enhanced spectrogram visualization
212    println!("🎨 Enhanced Spectrogram (first 60 frames)");
213    visualize_spectrogram_enhanced(&spec, 60);
214
215    // Time-varying analysis
216    println!("\n📊 Time-Varying Analysis (10 snapshots)");
217    analyze_time_evolution(&spec, 10);
218
219    // Transient detection
220    println!("\n⚡ Transient Detection");
221    detect_transients_enhanced(&spec);
222
223    // Frequency tracking
224    println!("\n🎵 Multi-Peak Frequency Tracking");
225    track_multiple_peaks(&spec, 3, 15);
226
227    // ISTFT validation
228    println!("\n✅ Perfect Reconstruction Test (ISTFT)");
229    test_reconstruction(&processor, &spec, signal, n_samples, window_size);
230}
231
232/// Enhanced spectrogram visualization with color mapping
233fn visualize_spectrogram_enhanced(spec: &Spectrogram<f64>, max_frames: usize) {
234    let mag_db = spec.magnitude_db();
235    let freqs = spec.frequencies();
236
237    let max_freq_idx = freqs.iter()
238        .position(|&f| f > 3000.0)
239        .unwrap_or(spec.num_freqs)
240        .min(30);
241
242    let num_frames = spec.num_frames.min(max_frames);
243
244    println!("   Frequency │ Time → (dB scale: █ > -10, ▓ > -20, ▒ > -30, ░ > -40)");
245    println!("   ──────────┼{}", "─".repeat(num_frames));
246
247    for freq_idx in (0..max_freq_idx).rev().step_by(1) {
248        print!("   {:6.0} Hz │ ", freqs[freq_idx]);
249
250        for frame in 0..num_frames {
251            let db = mag_db[freq_idx][frame];
252            let symbol = match db {
253                db if db > -10.0 => '█',
254                db if db > -20.0 => '▓',
255                db if db > -30.0 => '▒',
256                db if db > -40.0 => '░',
257                db if db > -50.0 => '·',
258                _ => ' ',
259            };
260            print!("{}", symbol);
261        }
262        println!();
263    }
264    println!("   ──────────┴{}", "─".repeat(num_frames));
265}
266
267/// Analyze spectral evolution over time
268fn analyze_time_evolution(spec: &Spectrogram<f64>, num_snapshots: usize) {
269    let centroids = spec.spectral_centroid();
270    let bandwidths = spec.spectral_bandwidth();
271    let times = spec.times();
272
273    let step = spec.num_frames / num_snapshots.min(spec.num_frames);
274
275    println!("   Time (s) │ Centroid (Hz) │ Bandwidth (Hz) │ Dynamics");
276    println!("   ─────────┼───────────────┼────────────────┼──────────");
277
278    for frame in (0..spec.num_frames).step_by(step.max(1)) {
279        let dynamics = if centroids[frame] > 800.0 { "High" }
280                      else if centroids[frame] > 500.0 { "Mid" }
281                      else { "Low" };
282
283        println!("   {:8.2} │  {:10.1}  │   {:10.1}   │ {}",
284                 times[frame], centroids[frame], bandwidths[frame], dynamics);
285    }
286}
287
288/// Enhanced transient detection with onset strength
289fn detect_transients_enhanced(spec: &Spectrogram<f64>) {
290    let power = spec.power();
291    let times = spec.times();
292
293    let mut frame_energy: Vec<f64> = Vec::new();
294    for frame in 0..spec.num_frames {
295        let energy: f64 = power.iter()
296            .map(|row| row[frame])
297            .sum();
298        frame_energy.push(energy);
299    }
300
301    // Calculate onset strength (energy difference)
302    let mut onset_strength: Vec<f64> = vec![0.0];
303    for i in 1..frame_energy.len() {
304        let diff = (frame_energy[i] - frame_energy[i - 1]).max(0.0);
305        onset_strength.push(diff);
306    }
307
308    let avg_onset: f64 = onset_strength.iter().sum::<f64>() / onset_strength.len() as f64;
309    let threshold = avg_onset * 3.0;
310
311    let mut transients = Vec::new();
312    for i in 1..onset_strength.len() - 1 {
313        if onset_strength[i] > threshold &&
314           onset_strength[i] > onset_strength[i - 1] &&
315           onset_strength[i] > onset_strength[i + 1] {
316            transients.push((times[i], onset_strength[i], frame_energy[i]));
317        }
318    }
319
320    println!("   Detected {} transient(s):", transients.len());
321    if transients.is_empty() {
322        println!("   └─ No significant transients found");
323    } else {
324        for (idx, (time, strength, energy)) in transients.iter().enumerate().take(5) {
325            println!("   {}─ t={:.3}s │ strength={:.2} │ energy={:.1}",
326                     if idx == transients.len() - 1 { "└" } else { "├" },
327                     time, strength, energy);
328        }
329    }
330}
331
332/// Track multiple frequency peaks simultaneously
333fn track_multiple_peaks(spec: &Spectrogram<f64>, num_peaks: usize, num_points: usize) {
334    let mag = spec.magnitude();
335    let freqs = spec.frequencies();
336    let times = spec.times();
337
338    let step = spec.num_frames / num_points.min(spec.num_frames);
339
340    println!("   Time (s) │ Peak 1 (Hz) │ Peak 2 (Hz) │ Peak 3 (Hz)");
341    println!("   ─────────┼─────────────┼─────────────┼────────────");
342
343    for frame in (0..spec.num_frames).step_by(step.max(1)) {
344        // Find top N peaks
345        let mut peak_indices: Vec<(usize, f64)> = mag.iter()
346            .enumerate()
347            .map(|(idx, row)| (idx, row[frame]))
348            .collect();
349
350        peak_indices.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
351
352        print!("   {:8.2} │", times[frame]);
353        for i in 0..num_peaks {
354            if i < peak_indices.len() {
355                print!(" {:9.1}  │", freqs[peak_indices[i].0]);
356            } else {
357                print!("     -     │");
358            }
359        }
360        println!();
361    }
362}
363
364/// Test perfect reconstruction with ISTFT
365fn test_reconstruction(
366    processor: &StftProcessor<f64>,
367    spec: &Spectrogram<f64>,
368    original: &[f64],
369    n_samples: usize,
370    margin: usize,
371) {
372    let start = std::time::Instant::now();
373    let reconstructed = processor.inverse(spec).unwrap();
374    let elapsed = start.elapsed();
375
376    let mut error_sum = 0.0;
377    let mut max_error: f64 = 0.0;
378    let mut count = 0;
379
380    for i in margin..(n_samples - margin).min(reconstructed.len()) {
381        let error = (original[i] - reconstructed[i]).abs();
382        error_sum += error * error;
383        max_error = max_error.max(error);
384        count += 1;
385    }
386
387    let rms_error = (error_sum / count as f64).sqrt();
388    let original_rms = (original.iter().map(|&s| s * s).sum::<f64>() / n_samples as f64).sqrt();
389    let snr_db = 20.0 * (original_rms / rms_error).log10();
390
391    println!("   ├─ Reconstruction time: {:.2} ms", elapsed.as_secs_f64() * 1000.0);
392    println!("   ├─ RMS error: {:.3e}", rms_error);
393    println!("   ├─ Max error: {:.3e}", max_error);
394    println!("   ├─ SNR: {:.1} dB", snr_db);
395    println!("   └─ Quality: {}",
396             if snr_db > 100.0 { "⭐ Excellent (>100 dB)" }
397             else if snr_db > 60.0 { "✓ Very Good (>60 dB)" }
398             else if snr_db > 40.0 { "✓ Good (>40 dB)" }
399             else { "⚠ Acceptable" });
400}
401
402/// Detect harmonics in the signal
403fn detect_harmonics(signal: &[f64], sample_rate: f64) {
404    println!("🎼 Harmonic Analysis");
405
406    let config = OverlapConfig::overlap_75(2048); // Larger window for better frequency resolution
407    let processor = StftProcessor::new(config, WindowType::BlackmanHarris).unwrap();
408    let spec = processor.process(signal, sample_rate).unwrap();
409
410    let mag = spec.magnitude();
411    let freqs = spec.frequencies();
412
413    // Average magnitude across all frames
414    let mut avg_mag: Vec<f64> = vec![0.0; spec.num_freqs];
415    for freq_idx in 0..spec.num_freqs {
416        let sum: f64 = mag[freq_idx].iter().sum();
417        avg_mag[freq_idx] = sum / spec.num_frames as f64;
418    }
419
420    // Find peaks in the spectrum
421    let mut peaks = Vec::new();
422    for i in 2..avg_mag.len() - 2 {
423        if avg_mag[i] > avg_mag[i-1] && avg_mag[i] > avg_mag[i+1] &&
424           avg_mag[i] > avg_mag[i-2] && avg_mag[i] > avg_mag[i+2] {
425            let threshold = avg_mag.iter().cloned().fold(0.0, f64::max) * 0.05;
426            if avg_mag[i] > threshold {
427                peaks.push((freqs[i], avg_mag[i]));
428            }
429        }
430    }
431
432    peaks.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());
433
434    println!("   Detected {} significant frequency peaks:", peaks.len().min(10));
435
436    if peaks.is_empty() {
437        println!("   └─ No significant peaks detected");
438        return;
439    }
440
441    // Display top 10 peaks
442    for (idx, (freq, mag)) in peaks.iter().take(10).enumerate() {
443        let note = frequency_to_note(*freq);
444        println!("   {}─ {:.1} Hz ({}) │ magnitude: {:.4}",
445                 if idx == peaks.len().min(10) - 1 { "└" } else { "├" },
446                 freq, note, mag);
447    }
448
449    // Detect harmonic relationships
450    if peaks.len() >= 2 {
451        println!("\n   Harmonic Relationships:");
452        let fundamental = peaks[0].0;
453        let mut found_harmonics = false;
454
455        for (idx, (freq, _)) in peaks.iter().skip(1).take(5).enumerate() {
456            let ratio = freq / fundamental;
457            if (ratio - ratio.round()).abs() < 0.05 {
458                println!("   {}─ {:.1} Hz ≈ {}x fundamental ({:.2}x)",
459                         if idx == 4 { "└" } else { "├" },
460                         freq, ratio.round() as i32, ratio);
461                found_harmonics = true;
462            }
463        }
464
465        if !found_harmonics {
466            println!("   └─ No clear harmonic relationships detected");
467        }
468    }
469}
470
471/// Convert frequency to musical note
472fn frequency_to_note(freq: f64) -> String {
473    let a4 = 440.0;
474    let notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
475
476    let half_steps = 12.0 * (freq / a4).log2();
477    let note_index = ((half_steps.round() as i32 + 9) % 12 + 12) % 12;
478    let octave = 4 + ((half_steps.round() as i32 + 9) / 12);
479    let cents = ((half_steps - half_steps.round()) * 100.0) as i32;
480
481    if cents.abs() > 10 {
482        format!("{}{} {:+}¢", notes[note_index as usize], octave, cents)
483    } else {
484        format!("{}{}", notes[note_index as usize], octave)
485    }
486}
487
488/// Analyze phase coherence across frequency bands
489fn analyze_phase_coherence(signal: &[f64], sample_rate: f64) {
490    println!("🌀 Phase Coherence Analysis");
491
492    let config = OverlapConfig::overlap_75(1024);
493    let processor = StftProcessor::new(config, WindowType::Hann).unwrap();
494    let spec = processor.process(signal, sample_rate).unwrap();
495
496    let phase = spec.phase();
497    let freqs = spec.frequencies();
498
499    // Analyze phase stability over time
500    let mut phase_variance: Vec<f64> = Vec::new();
501
502    for freq_idx in 0..spec.num_freqs.min(100) { // Limit to lower frequencies
503        if spec.num_frames < 2 {
504            continue;
505        }
506
507        // Calculate phase differences between consecutive frames
508        let mut diffs = Vec::new();
509        for frame in 1..spec.num_frames {
510            let mut diff = phase[freq_idx][frame] - phase[freq_idx][frame - 1];
511
512            // Unwrap phase (handle 2π discontinuities)
513            while diff > PI { diff -= 2.0 * PI; }
514            while diff < -PI { diff += 2.0 * PI; }
515
516            diffs.push(diff);
517        }
518
519        if diffs.is_empty() {
520            continue;
521        }
522
523        // Calculate variance
524        let mean: f64 = diffs.iter().sum::<f64>() / diffs.len() as f64;
525        let variance: f64 = diffs.iter()
526            .map(|&d| (d - mean).powi(2))
527            .sum::<f64>() / diffs.len() as f64;
528
529        phase_variance.push(variance);
530    }
531
532    if phase_variance.is_empty() {
533        println!("   └─ Insufficient data for phase analysis");
534        return;
535    }
536
537    let avg_variance = phase_variance.iter().sum::<f64>() / phase_variance.len() as f64;
538    let coherence_score = (-avg_variance).exp();
539
540    println!("   Phase Statistics:");
541    println!("   ├─ Average phase variance: {:.4} rad²", avg_variance);
542    println!("   ├─ Phase coherence score: {:.4} (0-1)", coherence_score);
543    println!("   └─ Interpretation: {} phase stability",
544             if coherence_score > 0.9 { "Excellent" }
545             else if coherence_score > 0.7 { "Good" }
546             else if coherence_score > 0.5 { "Moderate" }
547             else { "Low" });
548
549    // Find frequency bands with highest phase stability
550    let mut indexed_variance: Vec<(usize, f64)> = phase_variance.iter()
551        .enumerate()
552        .map(|(i, &v)| (i, v))
553        .collect();
554    indexed_variance.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
555
556    println!("\n   Most Stable Frequency Bands:");
557    for (idx, (freq_idx, variance)) in indexed_variance.iter().take(5).enumerate() {
558        let stability = (-variance).exp();
559        println!("   {}─ {:.1} Hz │ stability: {:.4}",
560                 if idx == 4 { "└" } else { "├" },
561                 freqs[*freq_idx], stability);
562    }
563}
564
565/// Estimate temporal SNR (Signal-to-Noise Ratio) over time
566fn estimate_temporal_snr(signal: &[f64], sample_rate: f64) {
567    println!("📡 Temporal SNR Estimation");
568
569    let config = OverlapConfig::overlap_75(1024);
570    let processor = StftProcessor::new(config, WindowType::Hann).unwrap();
571    let spec = processor.process(signal, sample_rate).unwrap();
572
573    let power = spec.power();
574    let times = spec.times();
575
576    // Calculate energy per frame
577    let mut frame_energy: Vec<f64> = Vec::new();
578    for frame in 0..spec.num_frames {
579        let energy: f64 = power.iter().map(|row| row[frame]).sum();
580        frame_energy.push(energy);
581    }
582
583    if frame_energy.is_empty() {
584        println!("   └─ No data available");
585        return;
586    }
587
588    // Estimate noise floor (minimum energy in quiet regions)
589    let mut sorted_energy = frame_energy.clone();
590    sorted_energy.sort_by(|a, b| a.partial_cmp(b).unwrap());
591    let noise_floor = sorted_energy[sorted_energy.len() / 10]; // 10th percentile
592
593    // Calculate SNR for each frame
594    let snr_db: Vec<f64> = frame_energy.iter()
595        .map(|&e| {
596            let signal_power = (e - noise_floor).max(noise_floor * 0.01);
597            10.0 * (signal_power / noise_floor).log10()
598        })
599        .collect();
600
601    let avg_snr = snr_db.iter().sum::<f64>() / snr_db.len() as f64;
602    let max_snr = snr_db.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
603    let min_snr = snr_db.iter().cloned().fold(f64::INFINITY, f64::min);
604
605    println!("   SNR Statistics:");
606    println!("   ├─ Average SNR: {:.1} dB", avg_snr);
607    println!("   ├─ Peak SNR: {:.1} dB", max_snr);
608    println!("   ├─ Minimum SNR: {:.1} dB", min_snr);
609    println!("   ├─ Dynamic range: {:.1} dB", max_snr - min_snr);
610    println!("   └─ Noise floor: {:.2e} (power units)", noise_floor);
611
612    // Show SNR evolution over time
613    println!("\n   SNR Evolution (10 snapshots):");
614    println!("   Time (s) │ SNR (dB) │ Signal Quality");
615    println!("   ─────────┼──────────┼────────────────");
616
617    let step = spec.num_frames / 10.min(spec.num_frames);
618    for frame in (0..spec.num_frames).step_by(step.max(1)) {
619        let quality = if snr_db[frame] > 40.0 { "⭐ Excellent" }
620                     else if snr_db[frame] > 30.0 { "✓ Very Good" }
621                     else if snr_db[frame] > 20.0 { "✓ Good" }
622                     else if snr_db[frame] > 10.0 { "○ Fair" }
623                     else { "⚠ Poor" };
624
625        println!("   {:8.2} │ {:8.1} │ {}", times[frame], snr_db[frame], quality);
626    }
627
628    // Identify high-quality segments
629    let high_quality_threshold = 30.0;
630    let high_quality_frames: Vec<usize> = snr_db.iter()
631        .enumerate()
632        .filter(|(_, &snr)| snr > high_quality_threshold)
633        .map(|(i, _)| i)
634        .collect();
635
636    let coverage = (high_quality_frames.len() as f64 / spec.num_frames as f64) * 100.0;
637    println!("\n   High-Quality Coverage:");
638    println!("   ├─ Frames above {} dB: {}/{}", high_quality_threshold,
639             high_quality_frames.len(), spec.num_frames);
640    println!("   └─ Coverage: {:.1}%", coverage);
641}
Source

pub fn spectral_centroid(&self) -> Vec<T>

Centróide espectral por frame (centro de massa do espectro)

Examples found in repository?
examples/audio_analysis.rs (line 129)
111fn compare_window_types(signal: &[f64], sample_rate: f64) {
112    println!("🔬 Window Function Comparison");
113
114    let config = OverlapConfig::overlap_75(512);
115    let windows = [
116        (WindowType::Hann, "Hann"),
117        (WindowType::Hamming, "Hamming"),
118        (WindowType::Blackman, "Blackman"),
119        (WindowType::BlackmanHarris, "Blackman-Harris"),
120    ];
121
122    println!("   Window Type      │ Avg Centroid │ Avg Flatness │ Frames");
123    println!("   ─────────────────┼──────────────┼──────────────┼────────");
124
125    for (window_type, name) in windows.iter() {
126        let processor = StftProcessor::new(config, *window_type).unwrap();
127        let spec = processor.process(signal, sample_rate).unwrap();
128
129        let centroids = spec.spectral_centroid();
130        let flatness = spec.spectral_flatness();
131
132        let avg_centroid = centroids.iter().sum::<f64>() / centroids.len() as f64;
133        let avg_flatness = flatness.iter().sum::<f64>() / flatness.len() as f64;
134
135        println!("   {:16} │ {:8.1} Hz │   {:8.5}   │  {}",
136                 name, avg_centroid, avg_flatness, spec.num_frames);
137    }
138    println!();
139}
140
141/// Perform detailed STFT analysis
142fn perform_detailed_analysis(signal: &[f64], sample_rate: f64, _duration: f64) {
143    let n_samples = signal.len();
144
145    // STFT configuration
146    let window_size = 1024; // Larger window for better frequency resolution
147    let config = OverlapConfig::overlap_75(window_size);
148
149    println!("⚙️  STFT Configuration");
150    println!("   ├─ Window: Hann (optimal for general use)");
151    println!("   ├─ Window size: {} samples", config.window_size);
152    println!("   ├─ Hop size: {} samples", config.hop_size);
153    println!("   ├─ Overlap: {:.1}%", config.overlap_percent());
154    println!("   ├─ Time resolution: {:.2} ms", (config.hop_size as f64 / sample_rate) * 1000.0);
155    println!("   └─ Frequency resolution: {:.2} Hz\n", sample_rate / (config.window_size as f64));
156
157    // Process STFT
158    println!("🔄 Processing STFT...");
159    let start = std::time::Instant::now();
160    let processor = StftProcessor::new(config, WindowType::Hann).unwrap();
161    let spec = processor.process(signal, sample_rate).unwrap();
162    let elapsed = start.elapsed();
163
164    println!("   ✓ Spectrogram computed in {:.2} ms", elapsed.as_secs_f64() * 1000.0);
165    println!("   ├─ Time frames: {}", spec.num_frames);
166    println!("   ├─ Frequency bins: {}", spec.num_freqs);
167    println!("   ├─ Data points: {}", spec.num_frames * spec.num_freqs);
168    println!("   └─ Coverage: {:.2} s\n", spec.times().last().unwrap());
169
170    // Advanced spectral analysis
171    println!("📈 Advanced Spectral Features");
172
173    let centroids = spec.spectral_centroid();
174    let bandwidths = spec.spectral_bandwidth();
175    let flatness = spec.spectral_flatness();
176    let rolloff_85 = spec.spectral_rolloff(85.0);
177    let rolloff_95 = spec.spectral_rolloff(95.0);
178
179    let avg_centroid = centroids.iter().sum::<f64>() / centroids.len() as f64;
180    let avg_bandwidth = bandwidths.iter().sum::<f64>() / bandwidths.len() as f64;
181    let avg_flatness = flatness.iter().sum::<f64>() / flatness.len() as f64;
182    let avg_rolloff_85 = rolloff_85.iter().sum::<f64>() / rolloff_85.len() as f64;
183    let avg_rolloff_95 = rolloff_95.iter().sum::<f64>() / rolloff_95.len() as f64;
184
185    println!("   Spectral Centroid (brightness indicator):");
186    println!("   ├─ Average: {:.1} Hz", avg_centroid);
187    println!("   ├─ Min: {:.1} Hz", centroids.iter().cloned().fold(f64::INFINITY, f64::min));
188    println!("   ├─ Max: {:.1} Hz", centroids.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
189    println!("   └─ Std dev: {:.1} Hz\n",
190             ((centroids.iter().map(|&c| (c - avg_centroid).powi(2)).sum::<f64>()
191               / centroids.len() as f64).sqrt()));
192
193    println!("   Spectral Bandwidth (spread around centroid):");
194    println!("   ├─ Average: {:.1} Hz", avg_bandwidth);
195    println!("   └─ Range: {:.1} - {:.1} Hz\n",
196             bandwidths.iter().cloned().fold(f64::INFINITY, f64::min),
197             bandwidths.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
198
199    println!("   Spectral Flatness (tonality measure):");
200    println!("   ├─ Average: {:.5} (0=pure tone, 1=white noise)", avg_flatness);
201    println!("   └─ Interpretation: {} signal\n",
202             if avg_flatness < 0.1 { "Highly tonal" }
203             else if avg_flatness < 0.3 { "Tonal" }
204             else if avg_flatness < 0.7 { "Mixed" }
205             else { "Noisy" });
206
207    println!("   Spectral Rolloff:");
208    println!("   ├─ 85% energy below: {:.1} Hz", avg_rolloff_85);
209    println!("   └─ 95% energy below: {:.1} Hz\n", avg_rolloff_95);
210
211    // Enhanced spectrogram visualization
212    println!("🎨 Enhanced Spectrogram (first 60 frames)");
213    visualize_spectrogram_enhanced(&spec, 60);
214
215    // Time-varying analysis
216    println!("\n📊 Time-Varying Analysis (10 snapshots)");
217    analyze_time_evolution(&spec, 10);
218
219    // Transient detection
220    println!("\n⚡ Transient Detection");
221    detect_transients_enhanced(&spec);
222
223    // Frequency tracking
224    println!("\n🎵 Multi-Peak Frequency Tracking");
225    track_multiple_peaks(&spec, 3, 15);
226
227    // ISTFT validation
228    println!("\n✅ Perfect Reconstruction Test (ISTFT)");
229    test_reconstruction(&processor, &spec, signal, n_samples, window_size);
230}
231
232/// Enhanced spectrogram visualization with color mapping
233fn visualize_spectrogram_enhanced(spec: &Spectrogram<f64>, max_frames: usize) {
234    let mag_db = spec.magnitude_db();
235    let freqs = spec.frequencies();
236
237    let max_freq_idx = freqs.iter()
238        .position(|&f| f > 3000.0)
239        .unwrap_or(spec.num_freqs)
240        .min(30);
241
242    let num_frames = spec.num_frames.min(max_frames);
243
244    println!("   Frequency │ Time → (dB scale: █ > -10, ▓ > -20, ▒ > -30, ░ > -40)");
245    println!("   ──────────┼{}", "─".repeat(num_frames));
246
247    for freq_idx in (0..max_freq_idx).rev().step_by(1) {
248        print!("   {:6.0} Hz │ ", freqs[freq_idx]);
249
250        for frame in 0..num_frames {
251            let db = mag_db[freq_idx][frame];
252            let symbol = match db {
253                db if db > -10.0 => '█',
254                db if db > -20.0 => '▓',
255                db if db > -30.0 => '▒',
256                db if db > -40.0 => '░',
257                db if db > -50.0 => '·',
258                _ => ' ',
259            };
260            print!("{}", symbol);
261        }
262        println!();
263    }
264    println!("   ──────────┴{}", "─".repeat(num_frames));
265}
266
267/// Analyze spectral evolution over time
268fn analyze_time_evolution(spec: &Spectrogram<f64>, num_snapshots: usize) {
269    let centroids = spec.spectral_centroid();
270    let bandwidths = spec.spectral_bandwidth();
271    let times = spec.times();
272
273    let step = spec.num_frames / num_snapshots.min(spec.num_frames);
274
275    println!("   Time (s) │ Centroid (Hz) │ Bandwidth (Hz) │ Dynamics");
276    println!("   ─────────┼───────────────┼────────────────┼──────────");
277
278    for frame in (0..spec.num_frames).step_by(step.max(1)) {
279        let dynamics = if centroids[frame] > 800.0 { "High" }
280                      else if centroids[frame] > 500.0 { "Mid" }
281                      else { "Low" };
282
283        println!("   {:8.2} │  {:10.1}  │   {:10.1}   │ {}",
284                 times[frame], centroids[frame], bandwidths[frame], dynamics);
285    }
286}
Source

pub fn spectral_bandwidth(&self) -> Vec<T>

Largura de banda espectral por frame

Examples found in repository?
examples/audio_analysis.rs (line 174)
142fn perform_detailed_analysis(signal: &[f64], sample_rate: f64, _duration: f64) {
143    let n_samples = signal.len();
144
145    // STFT configuration
146    let window_size = 1024; // Larger window for better frequency resolution
147    let config = OverlapConfig::overlap_75(window_size);
148
149    println!("⚙️  STFT Configuration");
150    println!("   ├─ Window: Hann (optimal for general use)");
151    println!("   ├─ Window size: {} samples", config.window_size);
152    println!("   ├─ Hop size: {} samples", config.hop_size);
153    println!("   ├─ Overlap: {:.1}%", config.overlap_percent());
154    println!("   ├─ Time resolution: {:.2} ms", (config.hop_size as f64 / sample_rate) * 1000.0);
155    println!("   └─ Frequency resolution: {:.2} Hz\n", sample_rate / (config.window_size as f64));
156
157    // Process STFT
158    println!("🔄 Processing STFT...");
159    let start = std::time::Instant::now();
160    let processor = StftProcessor::new(config, WindowType::Hann).unwrap();
161    let spec = processor.process(signal, sample_rate).unwrap();
162    let elapsed = start.elapsed();
163
164    println!("   ✓ Spectrogram computed in {:.2} ms", elapsed.as_secs_f64() * 1000.0);
165    println!("   ├─ Time frames: {}", spec.num_frames);
166    println!("   ├─ Frequency bins: {}", spec.num_freqs);
167    println!("   ├─ Data points: {}", spec.num_frames * spec.num_freqs);
168    println!("   └─ Coverage: {:.2} s\n", spec.times().last().unwrap());
169
170    // Advanced spectral analysis
171    println!("📈 Advanced Spectral Features");
172
173    let centroids = spec.spectral_centroid();
174    let bandwidths = spec.spectral_bandwidth();
175    let flatness = spec.spectral_flatness();
176    let rolloff_85 = spec.spectral_rolloff(85.0);
177    let rolloff_95 = spec.spectral_rolloff(95.0);
178
179    let avg_centroid = centroids.iter().sum::<f64>() / centroids.len() as f64;
180    let avg_bandwidth = bandwidths.iter().sum::<f64>() / bandwidths.len() as f64;
181    let avg_flatness = flatness.iter().sum::<f64>() / flatness.len() as f64;
182    let avg_rolloff_85 = rolloff_85.iter().sum::<f64>() / rolloff_85.len() as f64;
183    let avg_rolloff_95 = rolloff_95.iter().sum::<f64>() / rolloff_95.len() as f64;
184
185    println!("   Spectral Centroid (brightness indicator):");
186    println!("   ├─ Average: {:.1} Hz", avg_centroid);
187    println!("   ├─ Min: {:.1} Hz", centroids.iter().cloned().fold(f64::INFINITY, f64::min));
188    println!("   ├─ Max: {:.1} Hz", centroids.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
189    println!("   └─ Std dev: {:.1} Hz\n",
190             ((centroids.iter().map(|&c| (c - avg_centroid).powi(2)).sum::<f64>()
191               / centroids.len() as f64).sqrt()));
192
193    println!("   Spectral Bandwidth (spread around centroid):");
194    println!("   ├─ Average: {:.1} Hz", avg_bandwidth);
195    println!("   └─ Range: {:.1} - {:.1} Hz\n",
196             bandwidths.iter().cloned().fold(f64::INFINITY, f64::min),
197             bandwidths.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
198
199    println!("   Spectral Flatness (tonality measure):");
200    println!("   ├─ Average: {:.5} (0=pure tone, 1=white noise)", avg_flatness);
201    println!("   └─ Interpretation: {} signal\n",
202             if avg_flatness < 0.1 { "Highly tonal" }
203             else if avg_flatness < 0.3 { "Tonal" }
204             else if avg_flatness < 0.7 { "Mixed" }
205             else { "Noisy" });
206
207    println!("   Spectral Rolloff:");
208    println!("   ├─ 85% energy below: {:.1} Hz", avg_rolloff_85);
209    println!("   └─ 95% energy below: {:.1} Hz\n", avg_rolloff_95);
210
211    // Enhanced spectrogram visualization
212    println!("🎨 Enhanced Spectrogram (first 60 frames)");
213    visualize_spectrogram_enhanced(&spec, 60);
214
215    // Time-varying analysis
216    println!("\n📊 Time-Varying Analysis (10 snapshots)");
217    analyze_time_evolution(&spec, 10);
218
219    // Transient detection
220    println!("\n⚡ Transient Detection");
221    detect_transients_enhanced(&spec);
222
223    // Frequency tracking
224    println!("\n🎵 Multi-Peak Frequency Tracking");
225    track_multiple_peaks(&spec, 3, 15);
226
227    // ISTFT validation
228    println!("\n✅ Perfect Reconstruction Test (ISTFT)");
229    test_reconstruction(&processor, &spec, signal, n_samples, window_size);
230}
231
232/// Enhanced spectrogram visualization with color mapping
233fn visualize_spectrogram_enhanced(spec: &Spectrogram<f64>, max_frames: usize) {
234    let mag_db = spec.magnitude_db();
235    let freqs = spec.frequencies();
236
237    let max_freq_idx = freqs.iter()
238        .position(|&f| f > 3000.0)
239        .unwrap_or(spec.num_freqs)
240        .min(30);
241
242    let num_frames = spec.num_frames.min(max_frames);
243
244    println!("   Frequency │ Time → (dB scale: █ > -10, ▓ > -20, ▒ > -30, ░ > -40)");
245    println!("   ──────────┼{}", "─".repeat(num_frames));
246
247    for freq_idx in (0..max_freq_idx).rev().step_by(1) {
248        print!("   {:6.0} Hz │ ", freqs[freq_idx]);
249
250        for frame in 0..num_frames {
251            let db = mag_db[freq_idx][frame];
252            let symbol = match db {
253                db if db > -10.0 => '█',
254                db if db > -20.0 => '▓',
255                db if db > -30.0 => '▒',
256                db if db > -40.0 => '░',
257                db if db > -50.0 => '·',
258                _ => ' ',
259            };
260            print!("{}", symbol);
261        }
262        println!();
263    }
264    println!("   ──────────┴{}", "─".repeat(num_frames));
265}
266
267/// Analyze spectral evolution over time
268fn analyze_time_evolution(spec: &Spectrogram<f64>, num_snapshots: usize) {
269    let centroids = spec.spectral_centroid();
270    let bandwidths = spec.spectral_bandwidth();
271    let times = spec.times();
272
273    let step = spec.num_frames / num_snapshots.min(spec.num_frames);
274
275    println!("   Time (s) │ Centroid (Hz) │ Bandwidth (Hz) │ Dynamics");
276    println!("   ─────────┼───────────────┼────────────────┼──────────");
277
278    for frame in (0..spec.num_frames).step_by(step.max(1)) {
279        let dynamics = if centroids[frame] > 800.0 { "High" }
280                      else if centroids[frame] > 500.0 { "Mid" }
281                      else { "Low" };
282
283        println!("   {:8.2} │  {:10.1}  │   {:10.1}   │ {}",
284                 times[frame], centroids[frame], bandwidths[frame], dynamics);
285    }
286}
Source

pub fn spectral_flatness(&self) -> Vec<T>

Flatness espectral (razão entre média geométrica e aritmética) Valores próximos de 1 = ruído branco, próximos de 0 = tons puros

Examples found in repository?
examples/audio_analysis.rs (line 130)
111fn compare_window_types(signal: &[f64], sample_rate: f64) {
112    println!("🔬 Window Function Comparison");
113
114    let config = OverlapConfig::overlap_75(512);
115    let windows = [
116        (WindowType::Hann, "Hann"),
117        (WindowType::Hamming, "Hamming"),
118        (WindowType::Blackman, "Blackman"),
119        (WindowType::BlackmanHarris, "Blackman-Harris"),
120    ];
121
122    println!("   Window Type      │ Avg Centroid │ Avg Flatness │ Frames");
123    println!("   ─────────────────┼──────────────┼──────────────┼────────");
124
125    for (window_type, name) in windows.iter() {
126        let processor = StftProcessor::new(config, *window_type).unwrap();
127        let spec = processor.process(signal, sample_rate).unwrap();
128
129        let centroids = spec.spectral_centroid();
130        let flatness = spec.spectral_flatness();
131
132        let avg_centroid = centroids.iter().sum::<f64>() / centroids.len() as f64;
133        let avg_flatness = flatness.iter().sum::<f64>() / flatness.len() as f64;
134
135        println!("   {:16} │ {:8.1} Hz │   {:8.5}   │  {}",
136                 name, avg_centroid, avg_flatness, spec.num_frames);
137    }
138    println!();
139}
140
141/// Perform detailed STFT analysis
142fn perform_detailed_analysis(signal: &[f64], sample_rate: f64, _duration: f64) {
143    let n_samples = signal.len();
144
145    // STFT configuration
146    let window_size = 1024; // Larger window for better frequency resolution
147    let config = OverlapConfig::overlap_75(window_size);
148
149    println!("⚙️  STFT Configuration");
150    println!("   ├─ Window: Hann (optimal for general use)");
151    println!("   ├─ Window size: {} samples", config.window_size);
152    println!("   ├─ Hop size: {} samples", config.hop_size);
153    println!("   ├─ Overlap: {:.1}%", config.overlap_percent());
154    println!("   ├─ Time resolution: {:.2} ms", (config.hop_size as f64 / sample_rate) * 1000.0);
155    println!("   └─ Frequency resolution: {:.2} Hz\n", sample_rate / (config.window_size as f64));
156
157    // Process STFT
158    println!("🔄 Processing STFT...");
159    let start = std::time::Instant::now();
160    let processor = StftProcessor::new(config, WindowType::Hann).unwrap();
161    let spec = processor.process(signal, sample_rate).unwrap();
162    let elapsed = start.elapsed();
163
164    println!("   ✓ Spectrogram computed in {:.2} ms", elapsed.as_secs_f64() * 1000.0);
165    println!("   ├─ Time frames: {}", spec.num_frames);
166    println!("   ├─ Frequency bins: {}", spec.num_freqs);
167    println!("   ├─ Data points: {}", spec.num_frames * spec.num_freqs);
168    println!("   └─ Coverage: {:.2} s\n", spec.times().last().unwrap());
169
170    // Advanced spectral analysis
171    println!("📈 Advanced Spectral Features");
172
173    let centroids = spec.spectral_centroid();
174    let bandwidths = spec.spectral_bandwidth();
175    let flatness = spec.spectral_flatness();
176    let rolloff_85 = spec.spectral_rolloff(85.0);
177    let rolloff_95 = spec.spectral_rolloff(95.0);
178
179    let avg_centroid = centroids.iter().sum::<f64>() / centroids.len() as f64;
180    let avg_bandwidth = bandwidths.iter().sum::<f64>() / bandwidths.len() as f64;
181    let avg_flatness = flatness.iter().sum::<f64>() / flatness.len() as f64;
182    let avg_rolloff_85 = rolloff_85.iter().sum::<f64>() / rolloff_85.len() as f64;
183    let avg_rolloff_95 = rolloff_95.iter().sum::<f64>() / rolloff_95.len() as f64;
184
185    println!("   Spectral Centroid (brightness indicator):");
186    println!("   ├─ Average: {:.1} Hz", avg_centroid);
187    println!("   ├─ Min: {:.1} Hz", centroids.iter().cloned().fold(f64::INFINITY, f64::min));
188    println!("   ├─ Max: {:.1} Hz", centroids.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
189    println!("   └─ Std dev: {:.1} Hz\n",
190             ((centroids.iter().map(|&c| (c - avg_centroid).powi(2)).sum::<f64>()
191               / centroids.len() as f64).sqrt()));
192
193    println!("   Spectral Bandwidth (spread around centroid):");
194    println!("   ├─ Average: {:.1} Hz", avg_bandwidth);
195    println!("   └─ Range: {:.1} - {:.1} Hz\n",
196             bandwidths.iter().cloned().fold(f64::INFINITY, f64::min),
197             bandwidths.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
198
199    println!("   Spectral Flatness (tonality measure):");
200    println!("   ├─ Average: {:.5} (0=pure tone, 1=white noise)", avg_flatness);
201    println!("   └─ Interpretation: {} signal\n",
202             if avg_flatness < 0.1 { "Highly tonal" }
203             else if avg_flatness < 0.3 { "Tonal" }
204             else if avg_flatness < 0.7 { "Mixed" }
205             else { "Noisy" });
206
207    println!("   Spectral Rolloff:");
208    println!("   ├─ 85% energy below: {:.1} Hz", avg_rolloff_85);
209    println!("   └─ 95% energy below: {:.1} Hz\n", avg_rolloff_95);
210
211    // Enhanced spectrogram visualization
212    println!("🎨 Enhanced Spectrogram (first 60 frames)");
213    visualize_spectrogram_enhanced(&spec, 60);
214
215    // Time-varying analysis
216    println!("\n📊 Time-Varying Analysis (10 snapshots)");
217    analyze_time_evolution(&spec, 10);
218
219    // Transient detection
220    println!("\n⚡ Transient Detection");
221    detect_transients_enhanced(&spec);
222
223    // Frequency tracking
224    println!("\n🎵 Multi-Peak Frequency Tracking");
225    track_multiple_peaks(&spec, 3, 15);
226
227    // ISTFT validation
228    println!("\n✅ Perfect Reconstruction Test (ISTFT)");
229    test_reconstruction(&processor, &spec, signal, n_samples, window_size);
230}
Source

pub fn spectral_rolloff(&self, threshold_percent: T) -> Vec<T>

Rolloff espectral (frequência abaixo da qual está X% da energia)

Examples found in repository?
examples/audio_analysis.rs (line 176)
142fn perform_detailed_analysis(signal: &[f64], sample_rate: f64, _duration: f64) {
143    let n_samples = signal.len();
144
145    // STFT configuration
146    let window_size = 1024; // Larger window for better frequency resolution
147    let config = OverlapConfig::overlap_75(window_size);
148
149    println!("⚙️  STFT Configuration");
150    println!("   ├─ Window: Hann (optimal for general use)");
151    println!("   ├─ Window size: {} samples", config.window_size);
152    println!("   ├─ Hop size: {} samples", config.hop_size);
153    println!("   ├─ Overlap: {:.1}%", config.overlap_percent());
154    println!("   ├─ Time resolution: {:.2} ms", (config.hop_size as f64 / sample_rate) * 1000.0);
155    println!("   └─ Frequency resolution: {:.2} Hz\n", sample_rate / (config.window_size as f64));
156
157    // Process STFT
158    println!("🔄 Processing STFT...");
159    let start = std::time::Instant::now();
160    let processor = StftProcessor::new(config, WindowType::Hann).unwrap();
161    let spec = processor.process(signal, sample_rate).unwrap();
162    let elapsed = start.elapsed();
163
164    println!("   ✓ Spectrogram computed in {:.2} ms", elapsed.as_secs_f64() * 1000.0);
165    println!("   ├─ Time frames: {}", spec.num_frames);
166    println!("   ├─ Frequency bins: {}", spec.num_freqs);
167    println!("   ├─ Data points: {}", spec.num_frames * spec.num_freqs);
168    println!("   └─ Coverage: {:.2} s\n", spec.times().last().unwrap());
169
170    // Advanced spectral analysis
171    println!("📈 Advanced Spectral Features");
172
173    let centroids = spec.spectral_centroid();
174    let bandwidths = spec.spectral_bandwidth();
175    let flatness = spec.spectral_flatness();
176    let rolloff_85 = spec.spectral_rolloff(85.0);
177    let rolloff_95 = spec.spectral_rolloff(95.0);
178
179    let avg_centroid = centroids.iter().sum::<f64>() / centroids.len() as f64;
180    let avg_bandwidth = bandwidths.iter().sum::<f64>() / bandwidths.len() as f64;
181    let avg_flatness = flatness.iter().sum::<f64>() / flatness.len() as f64;
182    let avg_rolloff_85 = rolloff_85.iter().sum::<f64>() / rolloff_85.len() as f64;
183    let avg_rolloff_95 = rolloff_95.iter().sum::<f64>() / rolloff_95.len() as f64;
184
185    println!("   Spectral Centroid (brightness indicator):");
186    println!("   ├─ Average: {:.1} Hz", avg_centroid);
187    println!("   ├─ Min: {:.1} Hz", centroids.iter().cloned().fold(f64::INFINITY, f64::min));
188    println!("   ├─ Max: {:.1} Hz", centroids.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
189    println!("   └─ Std dev: {:.1} Hz\n",
190             ((centroids.iter().map(|&c| (c - avg_centroid).powi(2)).sum::<f64>()
191               / centroids.len() as f64).sqrt()));
192
193    println!("   Spectral Bandwidth (spread around centroid):");
194    println!("   ├─ Average: {:.1} Hz", avg_bandwidth);
195    println!("   └─ Range: {:.1} - {:.1} Hz\n",
196             bandwidths.iter().cloned().fold(f64::INFINITY, f64::min),
197             bandwidths.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
198
199    println!("   Spectral Flatness (tonality measure):");
200    println!("   ├─ Average: {:.5} (0=pure tone, 1=white noise)", avg_flatness);
201    println!("   └─ Interpretation: {} signal\n",
202             if avg_flatness < 0.1 { "Highly tonal" }
203             else if avg_flatness < 0.3 { "Tonal" }
204             else if avg_flatness < 0.7 { "Mixed" }
205             else { "Noisy" });
206
207    println!("   Spectral Rolloff:");
208    println!("   ├─ 85% energy below: {:.1} Hz", avg_rolloff_85);
209    println!("   └─ 95% energy below: {:.1} Hz\n", avg_rolloff_95);
210
211    // Enhanced spectrogram visualization
212    println!("🎨 Enhanced Spectrogram (first 60 frames)");
213    visualize_spectrogram_enhanced(&spec, 60);
214
215    // Time-varying analysis
216    println!("\n📊 Time-Varying Analysis (10 snapshots)");
217    analyze_time_evolution(&spec, 10);
218
219    // Transient detection
220    println!("\n⚡ Transient Detection");
221    detect_transients_enhanced(&spec);
222
223    // Frequency tracking
224    println!("\n🎵 Multi-Peak Frequency Tracking");
225    track_multiple_peaks(&spec, 3, 15);
226
227    // ISTFT validation
228    println!("\n✅ Perfect Reconstruction Test (ISTFT)");
229    test_reconstruction(&processor, &spec, signal, n_samples, window_size);
230}

Trait Implementations§

Source§

impl<T: Clone + Float> Clone for Spectrogram<T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug + Float> Debug for Spectrogram<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Spectrogram<T>
where Vec<Vec<Complex<T>>>: Freeze, T: Freeze,

§

impl<T> RefUnwindSafe for Spectrogram<T>

§

impl<T> Send for Spectrogram<T>
where Vec<Vec<Complex<T>>>: Send, T: Send,

§

impl<T> Sync for Spectrogram<T>
where Vec<Vec<Complex<T>>>: Sync, T: Sync,

§

impl<T> Unpin for Spectrogram<T>
where Vec<Vec<Complex<T>>>: Unpin, T: Unpin,

§

impl<T> UnsafeUnpin for Spectrogram<T>

§

impl<T> UnwindSafe for Spectrogram<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.