# Copyright (C) 2026 Yusuke Oda # SPDX-License-Identifier: AGPL-3.0-only """Plot the fixed EQ's phase and verify against its actual Rust impulse output.""" from pathlib import Path import hashlib import json import subprocess import tempfile import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt ROOT = Path(__file__).resolve().parent FS = 48000.0 NFFT = 131072 COMMIT = '5c754c2cc5f7cd92f368cb7aa4f2e5b14032e60d' def band_response(freq, band, center, gain, q=1.0): a = 10.0 ** (gain / 40.0) g = np.tan(np.pi * min(center, FS * 0.49) / FS) if band == 0: g /= np.sqrt(a) k, m0, m1, m2 = np.sqrt(2.0), 1.0, np.sqrt(2.0) * (a - 1.0), a*a - 1.0 elif band == 1: k = 1.0 / (q * a) m0, m1, m2 = 1.0, k * (a*a - 1.0), 0.0 else: g *= np.sqrt(a) k, m0, m1, m2 = np.sqrt(2.0), a*a, np.sqrt(2.0) * (1.0-a) * a, 1.0-a*a s = 1j * np.tan(np.pi * np.asarray(freq) / FS) / g return (m0*s*s + (m0*k+m1)*s + (m0+m2)) / (s*s+k*s+1.0) def tone_response(freq): return np.prod([band_response(freq, b, f, gain, 1.2) for b, (f, gain) in enumerate(zip([120., 1200., 7000.], [6., -8., 4.]))], axis=0) def phase(h): return np.rad2deg(np.unwrap(np.angle(h))) with tempfile.TemporaryDirectory() as temporary: binary = Path(temporary) / 'probe' subprocess.run(['rustc', '--edition=2024', '-O', str(ROOT/'probe.rs'), '-o', str(binary)], check=True) impulses = np.frombuffer(subprocess.check_output([str(binary)]), dtype='= 20.0) & (fft_freq <= 20000.0) fcheck = fft_freq[mask] verification = [] names = ['low_boost', 'low_cut', 'peak_boost', 'peak_cut', 'high_boost', 'high_cut', 'tone', 'flat', 'off'] for case, name in enumerate(names): measured = np.fft.rfft(impulses[case])[mask] if case < 6: expected = band_response(fcheck, case//2, 1000.0, 12.0 if case%2==0 else -12.0) elif case == 6: expected = tone_response(fcheck) else: expected = np.ones_like(measured) assert np.array_equal(impulses[case], np.r_[1.0, np.zeros(NFFT-1)]) row = {'case': name, 'complex_max_absolute_error': float(np.max(np.abs(measured-expected))), 'phase_max_absolute_error_degrees': float(np.max(np.abs(np.rad2deg(np.angle(measured/expected)))))} assert row['complex_max_absolute_error'] < 1e-10, row verification.append(row) np.savez_compressed(ROOT/'impulses.npz', sample_rate=FS, names=names, impulses=impulses) freq = np.unique(np.r_[np.geomspace(20., 20000., 6001), 120., 1000., 1200., 7000.]) curves = {} plt.rcParams.update({'font.size': 12, 'axes.titlesize': 14, 'axes.labelsize': 12, 'legend.fontsize': 10}) fig, axes = plt.subplots(2, 2, figsize=(13, 8), layout='constrained') for band, label in enumerate(['Low shelf', 'Peak', 'High shelf']): ax = axes.flat[band] for gain, color in [(12., '#155f93'), (-12., '#c9572b')]: y = phase(band_response(freq, band, 1000., gain)) curves[f'{label.replace(" ", "_").lower()}_{gain:+.0f}dB_degrees'] = y ax.semilogx(freq, y, color=color, lw=2.1, label=f'{gain:+.0f} dB') ax.set_title(label + ' | 1 kHz' + (' | Q = 1' if band == 1 else ' | fixed slope')) ax.axvline(1000., color='#888888', lw=.8, ls=':') ax.set_ylim(-60., 60.) ax.legend(loc='upper right') ax = axes[1, 1] for band, (center, gain, color) in enumerate(zip([120., 1200., 7000.], [6., -8., 4.], ['#257b4b', '#8b54a2', '#c18b20'])): y = phase(band_response(freq, band, center, gain, 1.2)) curves[f'tone_band_{band}_degrees'] = y ax.semilogx(freq, y, color=color, lw=1.2, ls='--', label=f'{["Low", "Mid", "High"][band]}: {center:g} Hz / {gain:+g} dB') combined = phase(tone_response(freq)) curves['tone_combined_degrees'] = combined ax.semilogx(freq, combined, color='#171717', lw=2.4, label='Combined (Mid Q = 1.2)') ax.set_title('Three-band example | phase contributions add') ax.set_ylim(-60., 60.) ax.legend(loc='lower right') for ax in axes.flat: ax.axhline(0, color='#606060', lw=.7) ax.set_xlim(20., 20000.) ax.set_xticks([20, 100, 1000, 10000, 20000], ['20', '100', '1k', '10k', '20k']) ax.set_xlabel('Frequency (Hz)') ax.set_ylabel('Phase (degrees)') ax.grid(True, which='both', alpha=.19) fig.suptitle('Current TPT SVF EQ: phase relative to EQ input | 48 kHz\nPositive = phase lead; negative = phase lag | fixed settings', fontsize=15) fig.savefig(ROOT/'eq-phase.png', dpi=160) fig.savefig(ROOT/'eq-phase.svg') plt.close(fig) np.savetxt(ROOT/'phase.csv', np.column_stack([freq, *curves.values()]), delimiter=',', header=','.join(['frequency_hz', *curves]), comments='', fmt='%.12g') report = {'source_commit': COMMIT, 'source_sha256': hashlib.sha256((ROOT/'eq.rs').read_bytes()).hexdigest(), 'sample_rate': FS, 'fft_samples': NFFT, 'fft_window': 'rectangular, no normalization', 'scope': 'EQ output relative to EQ input; fixed parameters', 'validation': verification, 'numpy': np.__version__, 'matplotlib': matplotlib.__version__, 'rustc': subprocess.check_output(['rustc', '--version'], text=True).strip(), 'single_band_1000_hz_phase_degrees': {name: float(phase(band_response(np.array([1000.]), b, 1000., 12.))[0]) for b, name in enumerate(['low', 'peak', 'high'])}, 'tone_phase_degrees': {str(f): float(phase(tone_response(np.array([f])))[0]) for f in [20., 120., 1000., 1200., 2000., 7000., 20000.]}} (ROOT/'validation.json').write_text(json.dumps(report, indent=2)+'\n') print(json.dumps(report, indent=2))