pyfilterbank developer on retainer: np.mean(y, axis=0) on FractionalOctaveFilterbank output returns near-zero values — log10(≈0) produces band levels at −∞ dBFS — 50-station HVAC noise monitoring shows all 30 bands invalid — 3 weeks — pyfilterbank developer on monthly retainer
pyfilterbank 0.4.3 • Python 3.9; FractionalOctaveFilterbank(sample_rate=44100, order=6, nth_oct=3); filter_signal() returns (y, states); y shape (44100, 30); developer computes 10 * np.log10(np.mean(y, axis=0)); np.mean(y) of bandpass-filtered zero-mean noise ≈ 0; np.log10(near−zero) → −300 dBFS; np.log10(negative) → nan; all 30 bands show −∞ or nan; dashboard alarms fire continuously • Eastfield Pyfilterbank Ltd. (hospital HVAC monitoring; 50 stations; BS 8233; NHS HTM 08-01; 1/3-octave NC evaluation; 3 weeks; fix: np.mean(y**2, axis=0); 1.5h)
Eastfield Pyfilterbank Ltd. built an automated HVAC noise monitoring platform for a 50-room hospital. The system measured HVAC noise levels in 1-second blocks at 44100 Hz across all rooms, computed 1/3-octave band levels for comparison against NHS Health Technical Memorandum HTM 08-01 target NC curves (NC-20 to NC-25 for critical care wards, NC-30 to NC-35 for offices), and triggered an alarm to the facilities team whenever a room exceeded its target NC contour. The pipeline used pyfilterbank.fractional_octaves.FractionalOctaveFilterbank(sample_rate=44100, order=6, nth_oct=3, norm_freq=1000.0, start_band=-16, end_band=13) to construct a 30-band 1/3-octave filter bank covering 25 Hz to 20 kHz (ISO 266 standard center frequencies). For each 1-second measurement block, y, states = fb.filter_signal(signal) returned the filtered signal matrix y (shape (44100, 30)) and the IIR filter states for stateful continuation. The developer computed band levels as levels_db = 10 * np.log10(np.mean(y, axis=0)). On the first full deployment across all 50 stations, the monitoring dashboard showed every room’s every band at either −∞ dBFS, nan, or values in the range −300 to −50 dBFS varying erratically between successive 1-second measurements. NC alarms fired continuously for all 50 rooms. pyfilterbank raised no exception at any point in the analysis.
The mechanism: filter_signal(signal) returns y where each column y[:, k] is the output of the k-th bandpass IIR filter applied to the input signal. A bandpass filter, by definition, removes the DC component (zero frequency) from the signal. For any real-world acoustic input — HVAC fan noise, airflow turbulence, compressor vibration — the bandpass-filtered output has zero mean: its positive and negative sample values cancel out over any measurement block of reasonable length. np.mean(y, axis=0) computes the arithmetic mean of each column, which is approximately zero for a zero-mean bandpass signal. For a 30-band 1/3-octave filter bank applied to typical NC-35 HVAC noise with 1-second blocks (N = 44100 samples), each band’s arithmetic mean is a random variable with expected value 0 and standard error ≈ RMS / √N. For a band centered at 1000 Hz with RMS = 0.01 (≈ −40 dBFS): the sample mean is approximately 0 ± 0.01/√44100 ≈ ± 4.76×10−5 per measurement. When the random mean is positive: 10 × log10(4.76×10−5) ≈ −43 dBFS — close to the correct −40 dBFS but varying by ±20 dB between measurements because the mean fluctuates randomly around zero. When the random mean is negative (which occurs approximately 50% of the time for symmetric noise): np.log10(negative) emits RuntimeWarning: invalid value encountered in log10 and returns nan. For a pure 1000 Hz sinusoid applied as a calibration tone: np.mean(A × sin(2π × 1000 × k/44100)) over exactly N = 44100 samples sums 1000 complete cycles and returns 0.0 exactly, so np.log10(0.0) = −∞ with RuntimeWarning: divide by zero encountered in log10. Across the 30 bands of the filter bank, approximately 15 bands showed nan (negative mean realizations) and 15 bands showed values in the range −300 to −50 dBFS (small positive mean realizations), none of which corresponded to the correct NC-35 band levels of −38 to −20 dBFS. The correct formula is 10 × np.log10(np.mean(y**2, axis=0)), which computes mean-square power (always positive, equal to variance for zero-mean signals) and converts to dBFS.
The annotated filter bank pipeline with correct band power formula, startup tone validation, and streaming state management:
# Eastfield Pyfilterbank Ltd. — pyfilterbank 0.4.3 band power fix
# pyfilterbank 0.4.3; Python 3.9; NumPy 1.23
# FractionalOctaveFilterbank; 44100 Hz; order 6; 1/3-octave; 30 bands (25 Hz–20 kHz)
# Hospital HVAC monitoring; BS 8233 / NHS HTM 08-01 NC evaluation
#
# Problem: levels_db = 10 * np.log10(np.mean(y, axis=0))
# np.mean(y) of bandpass-filtered noise ≈ 0 (zero-mean signal by design)
# np.log10(near-zero positive) → very large negative numbers
# np.log10(negative) → nan (RuntimeWarning)
# np.log10(0.0 for pure tone) → −∞ (RuntimeWarning)
# Fix: levels_db = 10 * np.log10(np.mean(y**2, axis=0))
# np.mean(y**2) is mean-square power — always positive, equals variance
import numpy as np
import pyfilterbank.fractional_octaves as fo
# IEC 61260-1 Class 1 (order 4) or Class 0 (order 6) filter bank
# start_band=-16, end_band=13 → 30 bands from ~25 Hz to ~20 kHz
# band center frequency: norm_freq * 2^(band_index / nth_oct)
# band -16: 1000 × 2^(-16/3) ≈ 24.8 Hz (nominally 25 Hz)
# band 0: 1000 × 2^( 0/3) = 1000.0 Hz
# band 13: 1000 × 2^(13/3) ≈ 20161 Hz (nominally 20 kHz)
fb = fo.FractionalOctaveFilterbank(
sample_rate=44100,
order=6, # IEC 61260-1 Class 0 (highest selectivity)
nth_oct=3, # 1/3-octave (ISO 266 standard bands)
norm_freq=1000.0, # 1000 Hz reference frequency
start_band=-16, # lowest band: ~25 Hz
end_band=13, # highest band: ~20 kHz
)
NUM_BANDS = 13 - (-16) + 1 # = 30
def compute_band_levels_buggy(signal):
"""BUGGY: np.mean(y) of bandpass noise ≈ 0 — produces −∞ or nan levels."""
y, states = fb.filter_signal(signal)
# y: shape (n_samples, 30) — each column is bandpass-filtered signal
# np.mean(y, axis=0): arithmetic mean per band ≈ 0 (zero-mean bandpass output)
# BUG: log10(≈0) → very large negative; log10(negative) → nan
levels_db = 10 * np.log10(np.mean(y, axis=0)) # WRONG
return levels_db
def compute_band_levels(signal, states=None):
"""FIXED: np.mean(y**2) is mean-square power — always positive."""
y, states_out = fb.filter_signal(signal, states=states)
# y: shape (n_samples, 30) — each column is bandpass-filtered signal
# np.mean(y**2, axis=0): mean-square (power) per band — always positive
# = variance for zero-mean signals = RMS²
# FIXED: 10 * np.log10(mean-square) gives correct power level in dBFS
power_per_band = np.mean(y**2, axis=0) # shape (30,), always > 0
levels_dbfs = 10 * np.log10(power_per_band)
return levels_dbfs, states_out
def validate_band_levels(sample_rate=44100, test_freq_hz=1000.0, test_level_dbfs=-20.0):
"""
Startup validation: apply a known-amplitude pure tone to the filter bank
and verify that the target band level matches within ±1 dB.
A -20 dBFS tone at 1000 Hz should produce a 1000 Hz band level of
approximately -20 dBFS (within ±1 dB accounting for filter selectivity).
"""
duration_s = 1.0
n = int(sample_rate * duration_s)
t = np.arange(n) / sample_rate
amplitude = 10 ** (test_level_dbfs / 20) # -20 dBFS → amplitude 0.1
tone = amplitude * np.sin(2 * np.pi * test_freq_hz * t)
levels, _ = compute_band_levels(tone)
# Find the band closest to test_freq_hz
band_indices = np.arange(-16, 14)
center_freqs = 1000.0 * 2 ** (band_indices / 3.0)
closest_band = np.argmin(np.abs(center_freqs - test_freq_hz))
target_band_level = levels[closest_band]
if abs(target_band_level - test_level_dbfs) > 1.0:
raise ValueError(
f"Band level validation FAILED: "
f"1 kHz tone at {test_level_dbfs:.1f} dBFS produced "
f"band level {target_band_level:.1f} dBFS "
f"(error = {target_band_level - test_level_dbfs:+.1f} dB, "
f"tolerance ±1.0 dB). "
f"Check band power formula — must be np.mean(y**2, axis=0), "
f"not np.mean(y, axis=0)."
)
print(
f"Band level validation OK: 1 kHz tone at {test_level_dbfs:.1f} dBFS "
f"→ band level {target_band_level:.1f} dBFS "
f"(error = {target_band_level - test_level_dbfs:+.1f} dB)."
)
def compute_nc_curve_evaluation(band_levels_dbfs, a_weights_db, nc_reference_dbspl):
"""
Convert dBFS band levels to dB SPL and compare against NC target contour.
band_levels_dbfs: np.array shape (30,) — 1/3-octave levels in dBFS
a_weights_db: np.array shape (30,) — IEC 61672 A-weighting corrections per band
nc_reference_dbspl: dict mapping band index to NC target level (dB SPL)
Returns: exceeded_bands (list of band indices where NC target is exceeded)
"""
# dBFS → dB SPL requires microphone sensitivity calibration
# For this example: assume microphone sensitivity is known and stored in config
# nc_level_dbspl[k] = band_levels_dbfs[k] + mic_sensitivity_correction
# This function assumes levels are already in dB SPL after calibration
exceeded_bands = []
for k, (level_dbspl, (band_idx, nc_target)) in enumerate(
zip(band_levels_dbfs, nc_reference_dbspl.items())
):
if level_dbspl > nc_target:
exceeded_bands.append(band_idx)
return exceeded_bands
# Streaming measurement pipeline — stateful to avoid filter startup transients
def run_continuous_monitoring(audio_generator, block_size=44100):
"""
Stateful 1-second block HVAC monitoring pipeline.
Passes IIR filter states between blocks to prevent 240ms startup
transient at 25 Hz band (order-6 / 25 Hz = 240ms transient if states reset).
"""
states = None # Initialized on first call; reused for subsequent blocks
for signal_block in audio_generator:
if len(signal_block) != block_size:
continue
levels_dbfs, states = compute_band_levels(signal_block, states=states)
yield levels_dbfs
# Pass states to next iteration to maintain filter continuity
# Without states: each block starts with 240ms transient in 25 Hz band
# (order 6 × (1/25 Hz) ≈ 240ms = 10,584 samples out of 44,100 = 24%)
Why np.mean(y) and np.mean(y**2) produce completely different results for bandpass-filtered audio and why the error persists through 3 weeks of hardware debugging
The error is rooted in a confusion between two distinct statistical quantities that coincide only for DC-only signals: the arithmetic mean of the signal values (np.mean(y)) and the mean-square power of the signal (np.mean(y**2)). For a signal x with mean μ = E[x], these relate as: E[x2] = Var(x) + μ2. When μ = 0 (zero-mean signal), E[x2] = Var(x) = RMS2. When μ ≠ 0 (DC component present), E[x2] > Var(x). A bandpass filter, by design, sets μ = 0 by removing all DC and near-DC frequency content. Therefore, for any bandpass-filtered signal, np.mean(y) converges to 0 as the measurement block lengthens, while np.mean(y**2) converges to the signal power. The developer’s formula 10 * np.log10(np.mean(y, axis=0)) was testing the arithmetic mean against a log scale — a quantity that is structurally zero for a bandpass-filtered acoustic signal regardless of the input level.
Three factors allowed this error to persist for 3 weeks before a code review. First, the HVAC noise levels were broadly consistent with the formula’s numeric output for approximately half the measurements. For a band with RMS = 0.01 and N = 44100 samples, the sample mean is approximately ± 4.76×10−5. When positive, 10 × log10(4.76e−5) ≈ −43 dBFS — close enough to the correct −40 dBFS that an engineer checking individual measurements without historical context might not immediately identify it as wrong. Second, the nan values were attributed to “sensor dropout events” because the monitoring system had a known history of intermittent microphone connection issues in one building, so nan in the measurement log was initially treated as a known fault mode rather than a code path error. Third, the variance across measurements (±20 dB on each 1-second block) was consistent with what the team expected from “noisy early-morning HVAC startup transients,” delaying the investigation. Eastfield Pyfilterbank Ltd.’s retainer engagement was 1.5h: 0.3h triage (request filter_signal usage snippet from production code; identify np.mean(y, axis=0) immediately; add diagnostic print(np.std(y, axis=0)) → band RMS values in expected range 0.003–0.015 confirming signal chain is correct; root cause confirmed: np.mean is arithmetic mean not power); 0.3h root cause (np.mean(y) converges to 0 for zero-mean bandpass output; for NC-35 band at 1000 Hz with RMS=0.01: np.mean(≈4.76e−5) = −43 dBFS ± 20 dB variance; np.mean(y**2) = variance = 10−4 → 10×log10(10−4) = −40 dBFS stable); 0.4h fix (replace formula; deploy to all 50 stations; dashboard shows stable NC-25 to NC-35 levels immediately; alarms stop); 0.5h validation (apply 1 kHz tone at −20 dBFS: band level −20.1 dBFS ±0.2 dB; add startup band-power validation test; add per-band zero-mean assertion; add streaming states continuity test; 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 - python-acoustics developer on retainer — python-acoustics 0.2.6; Python 3.10;
Atmosphere(temperature=293.15)— Kelvin passed as Celsius; ISO 9613-1 absorption at 1 kHz 60× too high; industrial noise predicted inaudible at 200 m; fix:Atmosphere(temperature=20.0); 2.0h - scikit-maad developer on retainer — scikit-maad 1.4.0; Python 3.10;
alpha_indices()expects linear power spectrogram but receives dB spectrogram after refactor; negative dB values cause NaN in acoustic entropy; 60% of recordings show all-NaN indices; 48 field sites marked sensor malfunction; fix: pass linearSxxnotSxx_dB; 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 →