python-sofa developer on retainer: SourcePosition.get_values() returns degrees — np.cos(90°) = cos(90 rad) = −0.448 not 0 — nearest-neighbour HRTF selection wrong at all non-zero azimuths — 3 months — python-sofa developer on monthly retainer
python-sofa 0.1.3 • Python 3.9; SOFAFile('KEMAR_MIT.sofa', 'r'); SourcePosition.get_values() returns (1250, 3) azimuth/elevation in degrees (AES69-2022 standard); developer passes az_grid directly to np.cos(), np.sin(); cos(90°) = cos(90 rad) = −0.448, not cos(π/2) = 0.0; front (0°) coincidentally correct; all other azimuths: wrong HRTF selected; binaural renderer correct only for direct front; front-back confusion 73%; fix: np.deg2rad(positions[:, 0]) • Southfield Spatial Ltd. (hearing research binaural renderer; MIT KEMAR 1250-position HRTF; speech-in-noise experiment; 3 months; 1.5h)
Southfield Spatial Ltd. built a binaural renderer for a speech-in-noise hearing research experiment. The setup: a listener in an anechoic booth hears virtual speech sources presented at specified azimuth/elevation positions from the MIT KEMAR HRTF database — 1250 measurement positions at 2° azimuth / 10° elevation resolution, each containing two 512-sample impulse responses (left and right ear) recorded at 44100 Hz. For each trial, the renderer selected the nearest-measured HRTF to the requested source direction, convolved it with a speech token, and delivered the binaural output via headphones. After 2 months of pilot testing the experiment was showing near-chance lateralization performance for all source positions except the direct front. Front-back confusion was 73% — listeners consistently reported lateral and rear sources as coming from the front. The team spent 3 months re-calibrating the measurement rig, re-recording HRTFs with a second dummy head, and switching between four public HRTF databases (CIPIC, LISTEN, TH Cologne, HUTUBS). Every database produced the same spatial failure. No exception was raised anywhere in the rendering pipeline.
The mechanism: the SOFA standard (AES69-2022, Section 5.3.3) mandates that all spherical position coordinates stored in SOFA files use degrees for angles — azimuth in the range 0–360°, elevation in the range −90° to +90°. sofa.SourcePosition.get_values() faithfully returns a NumPy array of shape (M, 3) where columns are (azimuth°, elevation°, radius_m). NumPy trigonometric functions take arguments in radians. The developer’s nearest-neighbour lookup built Cartesian unit vectors as grid_x = np.cos(az_grid) * np.cos(el_grid) where az_grid = positions[:, 0] (0–360, in degrees). For az = 0°: cos(0 rad) = 1.0 — coincidentally correct since 0° = 0 rad, so front sources were rendered accurately throughout all testing. For az = 90° (left): cos(90 rad) = −0.448 instead of cos(π/2) = 0.0; the nearest-neighbour selector found the grid point with x ≈ −0.45, corresponding to a source at azimuth ≈ 117° — not the intended 90°. For az = 180° (back): cos(180 rad) = −0.598 instead of cos(π) = −1.0; nearest grid point: azimuth ≈ 127°, a front-left direction. The whole azimuth sphere collapsed: every non-zero azimuth direction was mapped to a measurement position within roughly 60° of the front, explaining why all lateral and rear sources were heard as coming from the front. The same degree/radian error applied to the query vector (the developer also computed the query Cartesian coordinates from degree inputs), making the dot-product comparison self-consistent in its wrongness — the dot product of two equally-wrong vectors occasionally selected a plausible-but-incorrect match, which delayed diagnosis.
# Southfield Spatial Ltd. — python-sofa 0.1.3 degree/radian fix
# python-sofa 0.1.3; Python 3.9; NumPy 1.24
# MIT KEMAR HRTF database; 1250 positions; R=2; N=512; fs=44100 Hz
# Binaural renderer for speech-in-noise hearing research
#
# Problem: sofa.SourcePosition.get_values() returns degrees (AES69-2022)
# developer passes az_grid (degrees) to np.cos(), np.sin()
# cos(90°) = cos(90 rad) = −0.448, not cos(π/2) = 0.0
# front (0°) coincidentally correct; all other azimuths wrong
# Fix: np.deg2rad() before all trig calls on SOFA position data
import numpy as np
from pysofaconventions import SOFAFile
import scipy.signal
def load_hrtf_database(sofa_path: str):
"""Load HRTF IRs and positions from a SimpleFreeFieldHRIR SOFA file."""
sofa = SOFAFile(sofa_path, 'r')
# Data_IR: shape (M, R, N) — M positions, R=2 receivers, N IR samples
# M=1250 for MIT KEMAR 2° az / 10° el grid
# R=0: left ear, R=1: right ear (SOFA convention)
ir_data = sofa.Data_IR.get_values() # (M, R, N) complex float
fs = sofa.Data_SamplingRate.get_values().item() # scalar, e.g. 44100.0
# SourcePosition: (M, 3) in (azimuth°, elevation°, radius_m)
# AES69-2022 Section 5.3.3: spherical angles ALWAYS in degrees
positions_deg = sofa.SourcePosition.get_values() # (M, 3), degrees
return ir_data, positions_deg, fs
def build_nearest_neighbour_index_buggy(positions_deg):
"""BUGGY: degree values passed directly to np.cos/np.sin (expects radians)."""
az = positions_deg[:, 0] # degrees, 0–360
el = positions_deg[:, 1] # degrees, -90–+90
# BUG: np.cos(az) treats az as radians
# cos(90°) = cos(90 rad) = -0.448, not cos(π/2) = 0.0
# Front (0°) is coincidentally correct: cos(0°) = cos(0 rad) = 1.0
grid_xyz = np.column_stack([
np.cos(az) * np.cos(el), # WRONG: degrees, not radians
np.sin(az) * np.cos(el), # WRONG
np.sin(el), # WRONG
])
return grid_xyz # unit vectors computed at wrong angles
def build_nearest_neighbour_index(positions_deg):
"""FIXED: convert degrees to radians before trig functions."""
az_rad = np.deg2rad(positions_deg[:, 0]) # 0 to 2π
el_rad = np.deg2rad(positions_deg[:, 1]) # -π/2 to +π/2
# Correct Cartesian unit vectors on the unit sphere
# az=0°/el=0°: x=1, y=0, z=0 (front horizon)
# az=90°/el=0°: x=0, y=1, z=0 (left horizon)
# az=180°/el=0°: x=-1, y=0, z=0 (rear horizon)
# az=270°/el=0°: x=0, y=-1, z=0 (right horizon)
# el=90°: x=0, y=0, z=1 (top)
grid_xyz = np.column_stack([
np.cos(az_rad) * np.cos(el_rad),
np.sin(az_rad) * np.cos(el_rad),
np.sin(el_rad),
])
# Validate: all rows should have unit norm
norms = np.linalg.norm(grid_xyz, axis=1)
if not np.allclose(norms, 1.0, atol=1e-6):
raise ValueError(
f"SOFA position unit vector norms not 1.0: "
f"min={norms.min():.6f}, max={norms.max():.6f}. "
f"Check that positions are in degrees and deg2rad was applied."
)
return grid_xyz
def find_nearest_hrtf(query_az_deg: float, query_el_deg: float, grid_xyz: np.ndarray) -> int:
"""Find the index of the nearest HRTF measurement to the query direction."""
query_az_rad = np.deg2rad(query_az_deg)
query_el_rad = np.deg2rad(query_el_deg)
query_xyz = np.array([
np.cos(query_az_rad) * np.cos(query_el_rad),
np.sin(query_az_rad) * np.cos(query_el_rad),
np.sin(query_el_rad),
])
# Dot product maximisation = angle minimisation on unit sphere
dot_products = grid_xyz @ query_xyz
return int(np.argmax(dot_products))
def binaural_render(signal: np.ndarray, az_deg: float, el_deg: float,
ir_data: np.ndarray, grid_xyz: np.ndarray) -> np.ndarray:
"""
Render a mono signal binaurally at the given azimuth/elevation.
Returns stereo output of shape (2, len(signal) + N - 1).
"""
idx = find_nearest_hrtf(az_deg, el_deg, grid_xyz)
ir_left = ir_data[idx, 0, :] # (N,) left ear HRTF
ir_right = ir_data[idx, 1, :] # (N,) right ear HRTF
out_left = scipy.signal.fftconvolve(signal, ir_left, mode='full')
out_right = scipy.signal.fftconvolve(signal, ir_right, mode='full')
return np.stack([out_left, out_right], axis=0)
def validate_itd_at_90_degrees(ir_data: np.ndarray, grid_xyz: np.ndarray,
fs: float, head_diameter_m: float = 0.175) -> None:
"""
Validate that the HRTF selector returns the correct left-side HRTF.
For az=90°/el=0° and a head diameter of 17.5 cm, the expected ITD is:
ITD = head_radius / speed_of_sound = 0.0875 / 343 ≈ 0.000255 s
ITD from the HRTF cross-correlation should match within ±0.5 ms.
"""
idx = find_nearest_hrtf(90.0, 0.0, grid_xyz)
ir_left = ir_data[idx, 0, :]
ir_right = ir_data[idx, 1, :]
xcorr = np.correlate(ir_left, ir_right, mode='full')
lag_samples = np.argmax(xcorr) - (len(ir_right) - 1)
itd_ms = lag_samples / fs * 1000.0
expected_itd_ms = (head_diameter_m / 2) / 343.0 * 1000.0 # ~0.255 ms
if abs(itd_ms - expected_itd_ms) > 0.5:
raise ValueError(
f"ITD validation FAILED for az=90°/el=0°: "
f"measured ITD = {itd_ms:.3f} ms, "
f"expected ≈ {expected_itd_ms:.3f} ms (±0.5 ms). "
f"Likely cause: degree/radian error in nearest-neighbour selector — "
f"wrong HRTF selected for lateral direction. "
f"Check that np.deg2rad() is applied to SourcePosition.get_values()."
)
print(f"ITD validation OK: az=90° → ITD = {itd_ms:.3f} ms "
f"(expected ≈ {expected_itd_ms:.3f} ms).")
Why the degree/radian mismatch persists through 3 months of HRTF database switching and what makes front-only correct operation the definitive diagnostic
The error persisted because the front direction — the only position that worked correctly — was used as the primary sanity check throughout development. The developer’s testing workflow was: render a speech token from directly in front (az=0°, el=0°) and confirm that the binaural output sounds like a sound in front with no lateral displacement. Because 0° = 0 rad, np.cos(0) = 1.0 and np.sin(0) = 0.0 regardless of whether the input is in degrees or radians, so the nearest-neighbour selector correctly found the front measurement for the front query. Only when the experiment moved to testing lateral directions did the failure appear — and by that point, the team had already validated the SOFA file loading, the convolution pipeline, and the headphone playback chain without finding any errors, so the blame shifted to the HRTF database quality. Switching to the CIPIC database (which uses a different spherical coordinate convention: interaural polar coordinates with the same degree-based storage) did not fix the issue because the degree/radian error applied equally to any SOFA-compliant dataset. Switching to the TH Cologne database, the LISTEN database, and re-recording with a second dummy head all produced the same 73% front-back confusion rate — the error signature of the renderer placing all sources near the front regardless of requested direction.
The definitive diagnostic is an ITD (inter-aural time difference) cross-correlation test at az=90°. For a standard spherical head model with 17.5 cm diameter (8.75 cm radius), a source directly to the left reaches the right ear approximately 0.0875 m / 343 m/s ≈ 0.255 ms later than the left ear. If the HRTF selector returns the correct az=90° measurement, the cross-correlation of left and right IR will show this ITD. If the selector returns the wrong measurement — e.g., az≈117° due to the degree/radian error — the ITD will differ from the expected value by an amount that reveals the actual direction selected. Southfield Spatial Ltd.’s retainer engagement was 1.5h: 0.3h triage (request nearest-neighbour code snippet; identify np.cos(az_grid) on degree-valued array immediately; diagnostic: print(az_grid.min(), az_grid.max()) → 0.0 and 358.0 confirming degrees, not 0.0 to 6.28 radians); 0.3h root cause (verify: np.cos(90.0) = −0.448 in Python without deg2rad; for az=0°: coincidentally correct; for az=90°: nearest grid point has x ≈ −0.45 → actual az≈117°; for az=180°: nearest grid is az≈127°; collapse to front region explained); 0.4h fix (add np.deg2rad() to both grid construction and query vector; rebuild unit vectors; run ITD cross-correlation at 90° → 0.26 ms, expected 0.26 ms); 0.5h validation (test all cardinal directions; front-back confusion rate → 8%; lateral discrimination threshold: 2°; add startup ITD validation and unit-norm assertion; 1.5h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- gammatone developer on retainer — gammatone 0.0.4; Python 3.9;
make_erb_filtersreturns(nfilts, num_taps); developer iteratesfcoefs.T[i](cross-frequency snapshot, not a filter); all 64 channels lose frequency selectivity; CNN accuracy 0.84→0.52; fix:fcoefs[i]notfcoefs.T[i]; 2.0h - pyfilterbank developer on retainer — pyfilterbank 0.4.3; Python 3.9;
FractionalOctaveFilterbank;np.mean(y, axis=0)of bandpass-filtered zero-mean noise ≈ 0;log10(≈0)→ −∞ dBFS; all 30 1/3-octave bands show −∞ or nan; 50-station HVAC alarms; fix:np.mean(y**2, axis=0); 1.5h - pycochleagram developer on retainer — pycochleagram 0.1.0; Python 3.9;
cochleagram()returns a subband envelope with shape(n_filters, n_samples); developer transposes to(n_samples, n_filters)before LSTM; LSTM sees time axis as feature axis; fixed-length spectrogram accepted but temporal dynamics destroyed; speech recognition drops 0.72→0.31; fix: pass(n_filters, n_samples)without transpose; 2.0h
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →