SPB Git

Repository Public License

SpectrumTests.swift 14.2 KB 268 lines swift

1//2//  ORIX Audio3//  File: Core/Tests/ORIXAudioCoreTests/SpectrumTests.swift4//  Description: Reference-signal validation of the FFT, window scaling, spectrum analyzer and spectrogram.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//9import Foundation10import Testing11@testable import ORIXAudioCore1213let fs = 48_000.01415@Suite struct WindowTests {16    @Test(arguments: WindowFunction.allCases) func gainsMatchCoefficients(_ w: WindowFunction) {17        let c = w.coefficients(count: 4096).map(Double.init)18        let mean = c.reduce(0, +) / 4096, meanSq = c.reduce(0) { $0 + $1 * $1 } / 409619        #expect(abs(mean - w.coherentGain) < 1e-6)20        #expect(abs(meanSq - w.noisePowerGain) < 1e-6)21    }2223    @Test func equivalentNoiseBandwidths() {24        #expect(abs(WindowFunction.rectangular.equivalentNoiseBandwidthBins - 1.0) < 1e-9)25        #expect(abs(WindowFunction.hann.equivalentNoiseBandwidthBins - 1.5) < 1e-9)26        #expect(abs(WindowFunction.hamming.equivalentNoiseBandwidthBins - 1.3628) < 1e-3)27        #expect(abs(WindowFunction.blackmanHarris.equivalentNoiseBandwidthBins - 2.0044) < 1e-3)28        #expect(abs(WindowFunction.flatTop.equivalentNoiseBandwidthBins - 3.7702) < 1e-2)29    }30}3132@Suite struct FFTTests {33    @Test(arguments: [256, 1024, 4096, 16384]) func binCentredSineReadsItsAmplitude(_ n: Int) {34        let bin = n / 8 + 335        let f = Double(bin) * fs / Double(n)36        for window in WindowFunction.allCases {37            let fft = RealFFT(size: n, window: window)38            let s = fft.spectrum(of: SignalGenerator.sine(frequency: f, amplitude: 0.5, sampleRate: fs, count: n), scaling: .amplitude, sampleRate: fs)39            let peak = s.indices.max { s[$0] < s[$1] }!40            #expect(peak == bin)41            #expect(abs(s[bin] - 0.5) < 0.001, "\(window) amplitude \(s[bin])")42        }43    }4445    @Test func powerScalingIsMeanSquare() {46        let n = 4096, bin = 20047        let fft = RealFFT(size: n, window: .hann)48        let s = fft.spectrum(of: SignalGenerator.sine(frequency: Double(bin) * fs / Double(n), amplitude: 0.8, sampleRate: fs, count: n), scaling: .power, sampleRate: fs)49        #expect(abs(s[bin] - 0.32) < 0.001)       // A²/250    }5152    @Test func dcAndNyquistAreNotDoubled() {53        let n = 102454        let fft = RealFFT(size: n, window: .rectangular)55        let dc = fft.spectrum(of: [Float](repeating: 0.25, count: n), scaling: .amplitude, sampleRate: fs)56        #expect(abs(dc[0] - 0.25) < 1e-4)57        let nyq = fft.spectrum(of: (0..<n).map { $0 % 2 == 0 ? Float(0.3) : Float(-0.3) }, scaling: .amplitude, sampleRate: fs)58        #expect(abs(nyq[n / 2] - 0.3) < 1e-4)59    }6061    @Test func flatTopReadsOffBinAmplitudeWithin002dB() {62        let n = 409663        let fft = RealFFT(size: n, window: .flatTop)64        for offset in [0.0, 0.25, 0.5] {65            let f = (300 + offset) * fs / Double(n)66            let s = fft.spectrum(of: SignalGenerator.sine(frequency: f, amplitude: 1, sampleRate: fs, count: n), scaling: .amplitude, sampleRate: fs)67            #expect(abs(Decibels.fromAmplitude(s.max()!)) < 0.02)68        }69    }7071    @Test func hannScallopingLossIsAtMost142dB() {72        let n = 409673        let fft = RealFFT(size: n, window: .hann)74        let s = fft.spectrum(of: SignalGenerator.sine(frequency: 300.5 * fs / Double(n), sampleRate: fs, count: n), scaling: .amplitude, sampleRate: fs)75        let loss = -Decibels.fromAmplitude(s.max()!)76        #expect(loss > 1.3 && loss < 1.5)         // theoretical worst case 1.42 dB77    }7879    @Test func hannSuppressesLeakageComparedToRectangular() {80        let n = 409681        let x = SignalGenerator.sine(frequency: 300.5 * fs / Double(n), sampleRate: fs, count: n)82        let rect = RealFFT(size: n, window: .rectangular).spectrum(of: x, scaling: .amplitude, sampleRate: fs)83        let hann = RealFFT(size: n, window: .hann).spectrum(of: x, scaling: .amplitude, sampleRate: fs)84        // 40 bins away from the tone85        #expect(Decibels.fromAmplitude(rect[340]) > -45)86        #expect(Decibels.fromAmplitude(hann[340]) < -95)87    }8889    @Test func twoTonesFourBinsApartAreResolved() {90        let n = 409691        let res = fs / Double(n)92        let x = SignalGenerator.multitone([(400 * res, 0.4), (404 * res, 0.4)], sampleRate: fs, count: n)93        let s = RealFFT(size: n, window: .hann).spectrum(of: x, scaling: .amplitude, sampleRate: fs)94        #expect(s[400] > 0.39 && s[404] > 0.39 && s[402] < 0.01)95    }9697    @Test func psdIntegratesToVarianceOfWhiteNoise() {98        let n = 2048, frames = 20099        let noise = SignalGenerator.whiteNoise(rms: 0.1, count: n * frames, seed: 7)100        let fft = RealFFT(size: n, window: .hann)101        var mean = [Double](repeating: 0, count: n / 2 + 1)102        for f in 0..<frames {103            let s = fft.spectrum(of: Array(noise[(f * n)..<((f + 1) * n)]), scaling: .powerSpectralDensity, sampleRate: fs)104            for k in s.indices { mean[k] += Double(s[k]) / Double(frames) }105        }106        let integral = mean.reduce(0, +) * fs / Double(n)107        #expect(abs(integral - 0.01) / 0.01 < 0.03)108        // and it is flat: the PSD level is σ² / (fs/2)109        let expected = 0.01 / (fs / 2)110        let mid = mean[100..<900].reduce(0, +) / 800111        #expect(abs(mid - expected) / expected < 0.05)112    }113114    @Test func silenceAndFullScaleProduceFiniteValues() {115        let fft = RealFFT(size: 1024, window: .hann)116        var a = fft.spectrum(of: SignalGenerator.silence(count: 1024), scaling: .amplitude, sampleRate: fs)117        Decibels.convert(&a, isPower: false)118        #expect(a.allSatisfy { $0.isFinite && $0 <= -150 })119        let b = fft.spectrum(of: [Float](repeating: 1, count: 1024), scaling: .powerSpectralDensity, sampleRate: fs)120        #expect(b.allSatisfy { $0.isFinite })121    }122}123124@Suite struct SpectrumAnalyzerTests {125    @Test(arguments: [61.7, 440.0, 1234.5, 9876.5]) func dominantFrequencyWithinHalfHertzAt8192(_ f: Double) {126        var cfg = SpectrumConfiguration(); cfg.fftSize = 8192; cfg.smoothing = 0127        let an = SpectrumAnalyzer(sampleRate: fs, configuration: cfg)128        let frame = SignalGenerator.sine(frequency: f, amplitude: 0.3, sampleRate: fs, count: 8192).withUnsafeBufferPointer { an.process($0.baseAddress!, elapsed: 0.1) }129        #expect(abs(frame.dominantFrequency! - f) < 0.5)130        #expect(abs(frame.dominantLevel - Decibels.fromAmplitude(0.3)) < 0.3)131    }132133    @Test func silenceHasNoDominantFrequency() {134        let an = SpectrumAnalyzer(sampleRate: fs)135        let frame = SignalGenerator.silence(count: 4096).withUnsafeBufferPointer { an.process($0.baseAddress!, elapsed: 0.1) }136        #expect(frame.dominantFrequency == nil)137    }138139    @Test func bandPowerEqualsSinePower() {140        var cfg = SpectrumConfiguration(); cfg.smoothing = 0141        let an = SpectrumAnalyzer(sampleRate: fs, configuration: cfg)142        let cases: [(Double, Int)] = [(40, 0), (120, 1), (350, 2), (1000, 3), (3000, 4), (5000, 5), (10000, 6)]143        for (f, band) in cases {144            let frame = SignalGenerator.sine(frequency: f, amplitude: 0.5, sampleRate: fs, count: 4096).withUnsafeBufferPointer { an.process($0.baseAddress!, elapsed: 0.1) }145            #expect(abs(frame.bandPower[band] - 0.125) / 0.125 < 0.03, "band \(band) power \(frame.bandPower[band])")146            #expect(frame.bandPower.enumerated().filter { $0.offset != band }.allSatisfy { $0.element < 0.002 })147        }148    }149150    @Test func peakHoldDecaysAtConfiguredRate() {151        var cfg = SpectrumConfiguration(); cfg.smoothing = 0; cfg.peakDecayDBPerSecond = 10152        let an = SpectrumAnalyzer(sampleRate: fs, configuration: cfg)153        let bin = 85154        let loud = SignalGenerator.sine(frequency: Double(bin) * fs / 4096, amplitude: 1, sampleRate: fs, count: 4096)155        let a = loud.withUnsafeBufferPointer { an.process($0.baseAddress!, elapsed: 0.1) }156        let b = SignalGenerator.silence(count: 4096).withUnsafeBufferPointer { an.process($0.baseAddress!, elapsed: 0.5) }157        #expect(abs(a.peakHold[bin]) < 0.05)158        #expect(abs(b.peakHold[bin] - (-5)) < 0.05)159        #expect(b.decibels[bin] < -100)160    }161162    @Test func smoothingAveragesPower() {163        var cfg = SpectrumConfiguration(); cfg.smoothing = 0.5164        let an = SpectrumAnalyzer(sampleRate: fs, configuration: cfg)165        let bin = 85166        let loud = SignalGenerator.sine(frequency: Double(bin) * fs / 4096, amplitude: 1, sampleRate: fs, count: 4096)167        _ = loud.withUnsafeBufferPointer { an.process($0.baseAddress!, elapsed: 0.1) }168        let b = SignalGenerator.silence(count: 4096).withUnsafeBufferPointer { an.process($0.baseAddress!, elapsed: 0.1) }169        #expect(abs(b.decibels[bin] - (-3.01)) < 0.05)       // half the power170    }171172    @Test func spectralPeaksFindTheTones() {173        let x = SignalGenerator.multitone([(500, 0.5), (2000, 0.25), (7000, 0.1)], sampleRate: fs, count: 8192)174        var s = RealFFT(size: 8192, window: .blackmanHarris).spectrum(of: x, scaling: .amplitude, sampleRate: fs)175        Decibels.convert(&s, isPower: false)176        let peaks = SpectrumAnalyzer.peaks(in: s, fftSize: 8192, sampleRate: fs, count: 3, thresholdDB: -40, minimumSeparationBins: 8)177        #expect(peaks.count == 3)178        for (p, expected) in zip(peaks, [500.0, 2000, 7000]) { #expect(abs(p.frequency - expected) < 2) }179        #expect(abs(peaks[0].decibels - (-6.02)) < 0.3 && abs(peaks[2].decibels - (-20)) < 0.3)180    }181182    @Test func logAxisRoundTripsAndKeepsNarrowPeaks() {183        let axis = FrequencyAxis.logarithmic184        for f in [20.0, 100, 1000, 15000] { #expect(abs(axis.frequency(at: axis.position(of: f, min: 20, max: 20000), min: 20, max: 20000) - f) < 1e-6) }185        var dB = [Float](repeating: -120, count: 2049)186        dB[1500] = -3187        let cols = axis.resample(dB, fftSize: 4096, sampleRate: fs, columns: 200, min: 20, max: 20000)188        #expect(cols.max()! == -3)189    }190}191192@Suite struct SpectrogramTests {193    @Test func columnTimingMatchesToneBurst() {194        var x = SignalGenerator.silence(count: Int(fs * 2))195        let burst = SignalGenerator.sine(frequency: 1875, amplitude: 0.5, sampleRate: fs, count: Int(fs * 0.5))   // bin 40 exactly196        x.replaceSubrange(Int(fs)..<Int(fs * 1.5), with: burst)197        let cfg = SpectrogramConfiguration(fftSize: 1024, hopSize: 256)198        let tile = SpectrogramProcessor.compute(x, sampleRate: fs, configuration: cfg)199        #expect(tile.columnCount == SpectrogramProcessor.columnCount(sampleCount: x.count, configuration: cfg))200        let bin = 40201        let on = (0..<tile.columnCount).filter { tile.value(column: $0, bin: bin) > -12 }202        let start = tile.time(ofColumn: on.first!), end = tile.time(ofColumn: on.last!)203        #expect(abs(start - 1.0) < 2 * cfg.timeResolution(sampleRate: fs))204        #expect(abs(end - 1.5) < 2 * cfg.timeResolution(sampleRate: fs))205        // fully inside the burst the level is the tone's amplitude206        let mid = on[on.count / 2]207        #expect(abs(tile.value(column: mid, bin: bin) - Decibels.fromAmplitude(0.5)) < 0.3)208    }209210    @Test func chirpRidgeFollowsInstantaneousFrequency() {211        let n = Int(fs * 2)212        let x = SignalGenerator.chirp(from: 500, to: 8000, amplitude: 0.5, sampleRate: fs, count: n)213        let cfg = SpectrogramConfiguration(fftSize: 2048, hopSize: 512)214        let tile = SpectrogramProcessor.compute(x, sampleRate: fs, configuration: cfg)215        var worst = 0.0216        for c in stride(from: 4, to: tile.columnCount - 4, by: 7) {217            let ridge = (0..<tile.binCount).max { tile.value(column: c, bin: $0) < tile.value(column: c, bin: $1) }!218            let expected = 500 + (8000 - 500) * tile.time(ofColumn: c) / 2219            worst = max(worst, abs(tile.frequency(ofBin: ridge) - expected))220        }221        #expect(worst <= 2 * cfg.frequencyResolution(sampleRate: fs))222    }223224    @Test func impulseAppearsOnlyInColumnsThatContainIt() {225        let x = SignalGenerator.impulse(at: 10_000, count: 20_000)226        let cfg = SpectrogramConfiguration(fftSize: 1024, hopSize: 512)227        let tile = SpectrogramProcessor.compute(x, sampleRate: fs, configuration: cfg)228        for c in 0..<tile.columnCount {229            let range = SpectrogramProcessor.sampleRange(forColumns: c..<(c + 1), configuration: cfg)230            let energetic = tile.value(column: c, bin: 100) > -150231            #expect(energetic == range.contains(10_000) || !energetic)232            if !range.contains(10_000) { #expect(!energetic) }233        }234    }235236    @Test func streamingEqualsOneShot() {237        let x = SignalGenerator.pinkNoise(rms: 0.1, count: 30_000, seed: 3)238        let cfg = SpectrogramConfiguration(fftSize: 512, hopSize: 128)239        let whole = SpectrogramProcessor.compute(x, sampleRate: fs, configuration: cfg)240        let p = SpectrogramProcessor(sampleRate: fs, configuration: cfg)241        var values: [Float] = []242        var i = 0243        for chunk in [1, 777, 4096, 13, 9000, 20_000] { let end = min(x.count, i + chunk); p.push(Array(x[i..<end]), into: &values); i = end }244        p.push(Array(x[i...]), into: &values)245        #expect(values == whole.values)246    }247248    @Test func rasterMapsRangeOntoPalette() {249        let x = SignalGenerator.sine(frequency: 6000, amplitude: 1, sampleRate: fs, count: 8192)250        let tile = SpectrogramProcessor.compute(x, sampleRate: fs, configuration: .init(fftSize: 1024, hopSize: 512))251        let rows = 64252        let px = SpectrogramRasterizer.rgba(tile: tile, rows: rows, axis: .linear, minFrequency: 0, maxFrequency: 24000, floorDB: -100, ceilingDB: 0, palette: .monochrome)253        #expect(px.count == tile.columnCount * rows * 4)254        // 6 kHz of 24 kHz → a quarter of the way up → row 48 from the top255        let col = tile.columnCount / 2256        let brightest = (0..<rows).max { px[($0 * tile.columnCount + col) * 4] < px[($1 * tile.columnCount + col) * 4] }!257        #expect(abs(brightest - 47) <= 1)258        #expect(px[(brightest * tile.columnCount + col) * 4] > 245)259        #expect(px[(2 * tile.columnCount + col) * 4] < 40)260    }261262    @Test(arguments: [Colormap.scientific, .thermal, .monochrome, .colorblind, .orixSpectrum]) func palettesIncreaseInLuminance(_ map: Colormap) {263        var previous = -1.0264        for i in stride(from: 0, to: 256, by: 8) { let l = map.luminance(at: i); #expect(l >= previous - 0.5, "\(map) at \(i)"); previous = l }265        #expect(map.luminance(at: 255) - map.luminance(at: 0) > 150)266    }267}268
Files main
Menu

Theme