Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
214702cffThis file is pinned to the selected release. Download the original to open it in your design tool.
"""
envelope_wash.py - the envelope instrument: look for the rotor where the rotor
actually is.
Why this exists
---------------
The first real propeller recording put +0.2 dB into the 200-800 Hz band the
detector searches and +12.6 dB into 3.2-7.8 kHz. Every comb tier hunts a
harmonic comb of the blade-pass fundamental, in a band where that recording
had essentially nothing.
But the high-band energy is not featureless hiss. Broadband rotor noise - tip
vortices, blade-wake interaction, trailing-edge turbulence - is generated by a
blade, once per blade per revolution. So the received high-band envelope should
be amplitude-modulated at the blade-pass rate. The periodicity this whole
project keys on is still there; it has just moved from the spectrum of the
signal to the spectrum of its envelope.
That is the entire idea. Demodulate the high band, take the spectrum of the
envelope, and look for a comb at 40-650 Hz.
What separates what
-------------------
rotor wash envelope periodic at blade-pass (and often shaft) rate
speech high-band sibilance, but envelope periodicity is syllabic,
2-8 Hz - two orders of magnitude below the search grid
steady hiss HVAC, distant traffic: flat envelope spectrum, no peak
rain high-band crackle, but the droplet process is Poisson, so
the envelope spectrum is flat too
a box fan is a rotor. Blade-pass ~30-90 Hz. This is the real
near-enemy, and it is why the grid starts at 40 Hz and why
this module reports where the peak is rather than
thresholding blindly.
The alias residual, measured
----------------------------
Decimating the envelope by 8 puts the envelope Nyquist at 1000 Hz. The two
cascaded 800 Hz one-poles give -8.1 dB there, which is real attenuation but
not a brick wall. Consequence, measured rather than assumed: an amplitude
modulation at ~2.1 kHz folds to ~100 Hz - inside the search grid - and arrives
with a wash score of W = 4.8 to 6.7 depending on the noise realisation, i.e.
hovering around the nominal detection threshold of 6.
That is a genuine false-positive route. What could produce a 2.1 kHz amplitude
modulation of the 3-8 kHz band? Not a rotor (that would be 126,000 rpm) - but
two high-band tones separated by ~2.1 kHz beat at exactly that rate.
It does not threaten the rotor result. That capture scores W = 31.8 with a
coherent four-harmonic series at 82/164/246/328 Hz, agreed independently by all
four microphones. An alias folds one line, not a harmonic series.
A third cascaded pole costs nothing and halves the leak. Measured: the 2.1 kHz
fold drops from W = 4.8 to W = 2.5, while the real rotor capture stays at
W = 31.84 - identical to four significant figures, because the extra pole is a
flat gain across the whole envelope band and this instrument's statistic is
blind to flat gain by construction. The default here stays at 2 poles because
the published numbers from this instrument are computed with it; `n_poles=3`
is one keyword away, and Tier 3 (detector_t3.py) uses three.
Measurement only. Nothing in this file gates, vetoes or fires anything. It
produces numbers and figures; the version of this statistic that raises alerts
is Tier 3.
"""
import numpy as np
FS = 16000
HP_FC = 3000.0 # high-pass corner
ENV_LP_FC = 800.0 # envelope smoother corner
ENV_LP_POLES = 2 # cascaded one-poles. See "The alias residual" above.
DECIM = 8
FS_ENV = FS // DECIM # 2000 Hz
ENV_NFFT = 1024 # 0.512 s
ENV_HOP = 256
WELCH_N = 4 # windows averaged -> ~1.3 s effective, causal trailing
RATE_LO, RATE_HI = 40.0, 650.0
N_HARM = 4
HARM_CAP_DB = 12.0 # one line cannot fake a comb
LOCAL_HALF = 8 # +-8 envelope bins for the local median
LOCAL_SKIP = 1 # excluding +-1
HB_LO, HB_HI = 3200.0, 7800.0
HB_TAU_S = 30.0 # the same slow constant Tier-2's floor uses
# ---------------------------------------------------------------------------
# 4th-order Butterworth high-pass, fc = 3000 Hz at fs = 16000, as second-order
# sections. Frozen as literals, computed once in float64 by
# scipy.signal.butter(4, 3000.0, 'high', fs=16000, output='sos')
# so that a firmware port copies numbers rather than reimplementing a filter
# designer - the same discipline that freezes the floor's smoothing
# coefficients into the generated header.
#
# Measured response: -84.3 dB at 300 Hz, -50.0 dB at 800 Hz, -27.4 dB at
# 1500 Hz, -3.0 dB at 3000 Hz, -0.0 dB at 5000 Hz.
# ---------------------------------------------------------------------------
HP_SOS = np.array([
(0.19050441083226208, -0.38100882166452416, 0.19050441083226208,
1.0, -0.4129187044810216, 0.07900857355927177),
(1.0, -2.0, 1.0,
1.0, -0.565450073893807, 0.47759225007251704),
], dtype=np.float64)
def _sosfilt(sos, x):
"""Causal SOS filtering, direct form II transposed. Written out rather
than calling scipy so the arithmetic a firmware port must reproduce is
visible here, in the order it happens."""
y = np.asarray(x, np.float64).copy()
for b0, b1, b2, a0, a1, a2 in sos:
z1 = z2 = 0.0
out = np.empty_like(y)
for n in range(len(y)):
xn = y[n]
yn = b0 * xn + z1
z1 = b1 * xn - a1 * yn + z2
z2 = b2 * xn - a2 * yn
out[n] = yn
y = out
return y
def _sosfilt_fast(sos, x):
"""scipy's sosfilt - identical maths, vectorised. Used everywhere; the
slow reference above exists so a port has something to diff against, and
a test asserts they agree."""
from scipy.signal import sosfilt
return sosfilt(sos, np.asarray(x, np.float64))
# ---------------------------------------------------------------------------
# stage 1-3: high-band envelope
# ---------------------------------------------------------------------------
def envelope(x, fs=FS, decim=DECIM, n_poles=ENV_LP_POLES):
"""One channel -> its decimated high-band amplitude envelope at FS_ENV.
e = x_hp^2, smoothed by TWO cascaded one-pole low-passes at 800 Hz, then
decimated by 8, then square-rooted. Squaring first and rooting last is what
makes this an amplitude envelope rather than a rectified average, and the
two-pole smoother is what stops the 3-8 kHz carrier itself aliasing into
the 0-1000 Hz envelope band after decimation.
"""
xh = _sosfilt_fast(HP_SOS, np.asarray(x, np.float64))
e = xh * xh
a = float(np.exp(-2.0 * np.pi * ENV_LP_FC / fs))
from scipy.signal import lfilter
for _ in range(n_poles): # cascaded, as specified
e = lfilter([1.0 - a], [1.0, -a], e)
e = e[::decim]
return np.sqrt(np.maximum(e, 0.0))
def channel_mean_envelope(X, fs=FS, decim=DECIM, n_poles=ENV_LP_POLES):
"""Envelopes of every channel, averaged.
The average is of envelopes, never of the high-band time samples. Above
~2.8 kHz the array's 61 mm baseline is more than half a wavelength, so
summing the raw high-band waveforms partially cancels - it is a spatial
low-pass, and it would attenuate exactly the band this instrument exists to
look at. Envelopes are non-negative and add incoherently, so averaging them
is a clean sqrt(N) noise reduction with no directional dependence at all.
"""
X = np.atleast_2d(np.asarray(X))
return np.mean([envelope(ch, fs, decim, n_poles) for ch in X], axis=0)
# ---------------------------------------------------------------------------
# stage 4-5: the envelope spectrum, whitened without a floor
# ---------------------------------------------------------------------------
def _running_median(v, half=32):
"""Median over a sliding window across frequency. This is the whitening,
and it is deliberately floor-free: it has no memory, no time constant and
no state, so nothing it reports can be an artifact of a smoother's history.
An instrument that inherits the detector's adaptive floor reports the
floor, not the signal, which is the reason."""
n = len(v)
out = np.empty(n)
pad = np.pad(v, half, mode="edge")
for i in range(n):
out[i] = np.median(pad[i:i + 2 * half + 1])
return out
def envelope_spectrum(a, n_fft=ENV_NFFT, hop=ENV_HOP, welch=WELCH_N,
fs_env=FS_ENV):
"""Welch-averaged envelope PSD series.
Returns (freqs, psd_frames, times) where psd_frames[i] is the average of
`welch` consecutive periodograms ending at times[i] - causal and trailing,
so a future streaming implementation is the same computation.
"""
a = np.asarray(a, np.float64)
win = np.hanning(n_fft)
freqs = np.fft.rfftfreq(n_fft, 1.0 / fs_env)
per, tt = [], []
for i in range(0, len(a) - n_fft + 1, hop):
seg = a[i:i + n_fft]
seg = seg - seg.mean() # DC out: it is not a rate
P = np.abs(np.fft.rfft(seg * win)) ** 2
per.append(P)
tt.append((i + n_fft) / fs_env)
if not per:
return freqs, np.zeros((0, len(freqs))), np.zeros(0)
per = np.array(per)
out, ot = [], []
for i in range(welch - 1, len(per)):
out.append(per[i - welch + 1:i + 1].mean(axis=0))
ot.append(tt[i])
return freqs, np.array(out), np.array(ot)
def prominence_db(psd, half=LOCAL_HALF, skip=LOCAL_SKIP):
"""dB of every bin over its own local median, excluding the bin's
immediate neighbours. Floor-free and blind to any flat gain, which is what
lets a 4 m capture and a 10 m capture be compared at all."""
n = len(psd)
out = np.empty(n)
for i in range(n):
lo, hi = max(0, i - half), min(n, i + half + 1)
idx = np.arange(lo, hi)
idx = idx[np.abs(idx - i) > skip]
ref = np.median(psd[idx]) if len(idx) else psd[i]
out[i] = 10.0 * np.log10((psd[i] + 1e-30) / (ref + 1e-30))
return out
# ---------------------------------------------------------------------------
# stage 6: the wash comb score
# ---------------------------------------------------------------------------
def wash_score(freqs, psd, rate_lo=RATE_LO, rate_hi=RATE_HI, step=1.0,
n_harm=N_HARM, cap_db=HARM_CAP_DB):
"""W(r) over the rate grid, and the winner.
W(r) = sum_k (1/sqrt(k)) * min(prom(k*r), cap), for k*r <= 950 Hz.
The cap is the important part: without it a single strong envelope line -
a mains hum beating, a fan tone - scores as high as a genuine four-harmonic
comb. With it, a comb has to actually BE a comb.
"""
prom = prominence_db(psd)
df = freqs[1] - freqs[0]
rates = np.arange(rate_lo, rate_hi + 1e-9, step)
W = np.zeros(len(rates))
for j, r in enumerate(rates):
s = 0.0
for k in range(1, n_harm + 1):
f = k * r
if f > 950.0 or f > freqs[-1]:
break
i = int(round(f / df))
if i >= len(prom):
break
s += (1.0 / np.sqrt(k)) * min(prom[i], cap_db)
W[j] = s
b = int(np.argmax(W))
per_harm = []
for k in range(1, n_harm + 1):
f = k * rates[b]
if f > 950.0 or f > freqs[-1]:
per_harm.append(float("nan"))
continue
per_harm.append(float(prom[int(round(f / df))]))
return {"rates": rates, "W": W, "r_best": float(rates[b]),
"W_best": float(W[b]), "per_harmonic_db": per_harm,
"prom": prom}
# ---------------------------------------------------------------------------
# stage 7: the companion level statistic
# ---------------------------------------------------------------------------
def high_band_level_db(X, fs=FS, lo=HB_LO, hi=HB_HI, tau_s=HB_TAU_S,
n_fft=2048, hop=512):
"""L_hb: 3.2-7.8 kHz band power in dB over its OWN slow floor.
The floor is the asymmetric smoother Tier-2 uses - slow up, fast down -
reduced to one scalar per frame instead of one per bin. So this answers
"is the high band louder than it has recently been", which is the question,
rather than "is it loud", which depends on the room.
"""
X = np.atleast_2d(np.asarray(X, np.float64))
w = np.hanning(n_fft)
f = np.arange(n_fft // 2 + 1) * (fs / n_fft)
band = (f >= lo) & (f <= hi)
dt = hop / fs
a_up = float(np.exp(-dt / tau_s))
a_dn = float(np.exp(-dt / 0.8))
floor = None
out, tt = [], []
for i in range(0, X.shape[1] - n_fft + 1, hop):
P = (np.abs(np.fft.rfft(X[:, i:i + n_fft] * w, axis=1)) ** 2
).mean(axis=0)
p = float(P[band].sum())
if floor is None:
floor = p
a = a_up if p > floor else a_dn
floor = a * floor + (1.0 - a) * p
out.append(10.0 * np.log10((p + 1e-30) / (floor + 1e-30)))
tt.append((i + n_fft) / fs)
return np.array(out), np.array(tt)
def high_band_power_db(X, fs=FS, bands=((100, 200), (200, 400), (400, 800),
(800, 1600), (1600, 3200),
(3200, 7800)),
skip_s=2.0, n_fft=2048, hop=512, stride=4):
"""Median-over-time band levels in dB. The same instrument that produced
the original band table, kept here so the 10 m capture can be reported on
exactly the same basis as the 4 m one."""
X = np.atleast_2d(np.asarray(X, np.float64))
w = np.hanning(n_fft)
f = np.arange(n_fft // 2 + 1) * (fs / n_fft)
rows = []
for i in range(int(skip_s * fs), X.shape[1] - n_fft, hop * stride):
rows.append(np.abs(np.fft.rfft(X[:, i:i + n_fft] * w, axis=1)
).mean(axis=0))
if not rows:
return {}
M = np.median(np.array(rows), axis=0)
return {f"{lo}-{hi}": 20.0 * np.log10(
np.sqrt((M[(f >= lo) & (f < hi)] ** 2).mean()) + 1e-12)
for lo, hi in bands}
# ---------------------------------------------------------------------------
# stage 8: stability, the Tier-2 discipline applied to the rate
# ---------------------------------------------------------------------------
def longest_stable_run(r_series, W_series, w_min, frac=0.03, fs_frames=None):
"""Longest run of consecutive envelope-spectrum updates whose winning rate
stays within +-frac of the run's own first value AND whose W clears w_min.
Same argument as Tier-2's M-of-N: a real rotor holds ONE rate for as long
as it turns, and a spurious envelope peak does not. Reported in seconds.
"""
best = cur = 0
anchor = None
runs = []
for r, W in zip(r_series, W_series):
ok = W >= w_min and np.isfinite(r)
if ok and anchor is not None and abs(r - anchor) <= frac * anchor:
cur += 1
elif ok:
anchor, cur = r, 1
else:
anchor, cur = None, 0
if cur > best:
best = cur
runs.append(cur)
dt = 1.0 / fs_frames if fs_frames else (ENV_HOP / FS_ENV)
return best * dt, np.array(runs)
# ---------------------------------------------------------------------------
# the whole instrument
# ---------------------------------------------------------------------------
def analyse(X, fs=FS, skip_s=2.0, w_min=6.0, rate_lo=RATE_LO,
rate_hi=RATE_HI, n_poles=ENV_LP_POLES):
"""Run the full instrument on (n_ch, n_samples) audio.
skip_s drops the INMP441 start-up transient, which is ~25 dB above the room
for the first two seconds of every capture and would otherwise dominate
both the envelope and the level statistic.
"""
X = np.atleast_2d(np.asarray(X))
if X.dtype != np.float32 and X.dtype != np.float64:
X = np.stack([np.asarray(c, np.int16).astype(np.float64) / 32767.0
for c in X])
X = X[:, int(skip_s * fs):]
a = channel_mean_envelope(X, fs, n_poles=n_poles)
freqs, psd_frames, times = envelope_spectrum(a)
# the whole-capture answer: average every Welch frame, then score once
if len(psd_frames):
mean_psd = psd_frames.mean(axis=0)
agg = wash_score(freqs, mean_psd, rate_lo, rate_hi)
else:
mean_psd = np.zeros(len(freqs))
agg = {"r_best": float("nan"), "W_best": float("nan"),
"per_harmonic_db": [], "rates": np.zeros(0),
"W": np.zeros(0), "prom": np.zeros(len(freqs))}
# and the per-update series, for the stability layer
r_series, w_series = [], []
for P in psd_frames:
s = wash_score(freqs, P, rate_lo, rate_hi)
r_series.append(s["r_best"])
w_series.append(s["W_best"])
r_series = np.array(r_series)
w_series = np.array(w_series)
stable_s, _ = longest_stable_run(r_series, w_series, w_min,
fs_frames=FS_ENV / ENV_HOP)
lhb, lhb_t = high_band_level_db(X, fs)
return {
"freqs": freqs, "mean_psd": mean_psd, "times": times,
"r_best": agg["r_best"], "W_best": agg["W_best"],
"per_harmonic_db": agg["per_harmonic_db"],
"rates": agg["rates"], "W_curve": agg["W"], "prom": agg["prom"],
"r_series": r_series, "W_series": w_series,
"W_p90": float(np.percentile(w_series, 90)) if len(w_series) else float("nan"),
"r_median": float(np.median(r_series)) if len(r_series) else float("nan"),
"stable_run_s": float(stable_s),
"L_hb_max": float(np.max(lhb)) if len(lhb) else float("nan"),
"L_hb_p90": float(np.percentile(lhb, 90)) if len(lhb) else float("nan"),
"bands_db": high_band_power_db(X, fs, skip_s=0.0),
"seconds": X.shape[1] / fs,
}