Articulatory tract sources, Story 2008 vowel area functions as data, independent formant estimators

docs/research/articulatory-vocal-tract-sources.md cites what the tract design takes from Story, Pink Trombone, VocalTractLab,
Maeda, Kelly-Lochbaum, nasal coupling and LF, with what could not be retrieved. The CSV is Story 2008 Table I (11 vowels, 44
sections). burg_formants.py (Burg LPC on a WAV) and tube_formants.py (frequency-domain tube chain on an area function) share no
code with the ladder. Unheard.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Aqua 2026-11-08 16:13:29 +00:00
commit 080f236ef2
4 changed files with 245 additions and 0 deletions

View file

@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Independent formant estimator for AquaSynth renders. Shares no code with the C# tests or with the ladder.
Burg linear prediction (not autocorrelation LPC, not the tract's own impulse response): stable on short windows and
unbiased by the window edge. Usage:
burg_formants.py FILE.wav T0 T1 [--order N] [--frame-ms 30] [--json]
Resamples to 10 kHz (FFT-domain), pre-emphasises 0.97, Hamming 30 ms frames hop 10 ms in [T0,T1], Burg order 12 default,
poles with bandwidth < 400 Hz and 150 Hz < f < 4.5 kHz are formants. Prints the per-formant median over frames and the
interquartile spread. It measures; it does not listen.
"""
import sys, json, wave, argparse
import numpy as np
def read_wav(path):
with wave.open(path) as w:
sr, n, ch, sw = w.getframerate(), w.getnframes(), w.getnchannels(), w.getsampwidth()
raw = w.readframes(n)
assert sw == 2, "16-bit PCM only"
x = np.frombuffer(raw, dtype=np.int16).astype(np.float64) / 32768.0
return (x.reshape(-1, ch).mean(axis=1) if ch > 1 else x), sr
def resample(x, sr, target):
if sr == target:
return x
n = int(round(len(x) * target / sr))
X = np.fft.rfft(x)
m = n // 2 + 1
Y = np.zeros(m, dtype=complex)
k = min(m, len(X))
Y[:k] = X[:k]
return np.fft.irfft(Y, n) * (n / len(x))
def burg(x, order):
f = x.copy(); b = x.copy(); a = np.array([1.0])
for _ in range(order):
fp, bp = f[1:], b[:-1]
k = -2.0 * np.dot(fp, bp) / (np.dot(fp, fp) + np.dot(bp, bp) + 1e-30)
a = np.concatenate([a, [0.0]]); a = a + k * a[::-1]
f, b = fp + k * bp, bp + k * fp
return a
def formants(frame, fs, order):
a = burg(frame * np.hamming(len(frame)), order)
r = np.roots(a); r = r[np.imag(r) > 1e-4]
fq = np.angle(r) * fs / (2 * np.pi); bw = -np.log(np.abs(r)) * fs / np.pi
return sorted(float(f) for f, w in zip(fq, bw) if 150 < f < 4500 and w < 400)
def main():
p = argparse.ArgumentParser()
p.add_argument("wav"); p.add_argument("t0", type=float); p.add_argument("t1", type=float)
p.add_argument("--order", type=int, default=12); p.add_argument("--frame-ms", type=float, default=30)
p.add_argument("--json", action="store_true")
a = p.parse_args()
x, sr = read_wav(a.wav)
fs = 10000
y = resample(x, sr, fs)
y = np.append(y[0], y[1:] - 0.97 * y[:-1])
n = int(a.frame_ms * fs / 1000); hop = int(0.010 * fs)
rows = []
for s in range(int(a.t0 * fs), int(a.t1 * fs) - n, hop):
fr = y[s:s + n]
if fr.std() < 1e-6: continue
rows.append(formants(fr, fs, a.order)[:4])
out = {"file": a.wav, "t0": a.t0, "t1": a.t1, "order": a.order, "frames": len(rows)}
for i in range(4):
v = [r[i] for r in rows if len(r) > i]
out[f"F{i+1}"] = None if len(v) < max(3, len(rows) // 2) else {"median": round(float(np.median(v)), 1), "q1": round(float(np.percentile(v, 25)), 1), "q3": round(float(np.percentile(v, 75)), 1), "n": len(v)}
if a.json: print(json.dumps(out))
else:
print(f"{a.wav} [{a.t0},{a.t1}] order {a.order} frames {len(rows)}: " + " ".join(f"F{i+1}={out[f'F{i+1}']['median']} ({out[f'F{i+1}']['q1']}-{out[f'F{i+1}']['q3']})" if out[f"F{i+1}"] else f"F{i+1}=-" for i in range(4)))
if __name__ == "__main__":
main()

View file

@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Frequency-domain formants of a published area function. Independent of the AquaSynth ladder (no time-domain scattering,
no Faust): a chain of lossy uniform tubes (ABCD matrices) between a high-impedance glottis and a piston-in-baffle radiation load.
tube_formants.py CSV [--vowel V] [--length-cm L] [--c 350] [--fmax 5000]
CSV is docs/research/data/story2008-area-functions.csv. --length-cm rescales every vowel to one tract length (the ladder
runs one length for all vowels); default is each vowel's own VTL. Prints F1..F4 as peaks of |U_lips / U_glottis|.
"""
import sys, argparse
import numpy as np
RHO = 1.14e-3 # g/cm^3 as in VocalTractLab's dissertation constants (SI 1.14 kg/m^3)
def load(path):
rows = [l.strip() for l in open(path) if l.strip() and not l.startswith('#')]
head = rows[0].split(',')[1:]
areas = {v: [] for v in head}
extra = {}
for r in rows[1:]:
c = r.split(',')
if c[0].isdigit():
for v, x in zip(head, c[1:]): areas[v].append(float(x))
else:
extra[c[0]] = dict(zip(head, map(float, c[1:])))
return head, {v: np.array(a) for v, a in areas.items()}, extra
def transfer(areas, section_cm, c, freqs, wall=0.0):
"""|U_lip/U_glottis| for tubes of the given areas (cm^2) and one section length (cm). cgs units."""
out = np.zeros(len(freqs))
for n, f in enumerate(freqs):
w = 2 * np.pi * f
# attenuation per cm: viscous/thermal ~ f^0.5 plus wall term, giving F1 bandwidths of order 50-100 Hz
alpha = 4e-5 * np.sqrt(f) + wall + 1.5e-3
k = w / c * (1 - 1j * alpha * c / w) if w > 0 else 0
M = np.eye(2, dtype=complex)
for A in areas: # glottis -> lips; state (P, U)
Z = RHO * c / A
kl = k * section_cm
M = M @ np.array([[np.cos(kl), 1j * Z * np.sin(kl)], [1j * np.sin(kl) / Z, np.cos(kl)]])
A_l = areas[-1]
a = np.sqrt(A_l / np.pi)
ka = w / c * a
# Levine-Schwinger-ish low-ka piston radiation impedance (Flanagan: R||L)
Zr = (RHO * c / A_l) * (ka ** 2 / 2 + 1j * 8 * ka / (3 * np.pi)) if ka < 1.2 else (RHO * c / A_l) * (1 - 0j)
# U_glottis from open-circuit glottis (high Z): P_g free -> use U_g = 1, solve P_l = Zr*U_l; (P,U)_glottis = M (P,U)_lip
# lip: P_l = Zr*U_l. glottis U_g = M[1,0]*P_l + M[1,1]*U_l = U_l*(M10*Zr + M11)
out[n] = 1 / abs(M[1, 0] * Zr + M[1, 1])
return out
def peaks(freqs, mag, n=4):
idx = [i for i in range(1, len(mag) - 1) if mag[i] > mag[i - 1] and mag[i] >= mag[i + 1]]
res = []
for i in idx:
y0, y1, y2 = np.log(mag[i - 1]), np.log(mag[i]), np.log(mag[i + 1])
d = 0.5 * (y0 - y2) / (y0 - 2 * y1 + y2) # parabolic refinement
res.append(freqs[i] + d * (freqs[1] - freqs[0]))
return res[:n]
def main():
p = argparse.ArgumentParser()
p.add_argument('csv'); p.add_argument('--vowel'); p.add_argument('--length-cm', type=float)
p.add_argument('--c', type=float, default=350.0); p.add_argument('--fmax', type=float, default=5000)
a = p.parse_args()
head, areas, extra = load(a.csv)
freqs = np.arange(50, a.fmax, 5.0)
for v in head:
if a.vowel and v != a.vowel: continue
A = areas[v]
L = a.length_cm or extra['vtl_cm'][v]
sec = L * 100 / 100 / len(A) # cm per section
sec = L / len(A)
m = transfer(A, sec, a.c * 100, freqs)
print(f"{v} L={L:.2f}cm " + " ".join(f"F{i+1}={f:.0f}" for i, f in enumerate(peaks(freqs, m))))
if __name__ == '__main__':
main()