modal_analysis.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. #!/usr/bin/env python3
  2. """modal_analysis.py - shared signal analysis for LYNX Model (round 190ni): the timbre score (timbre_score.py) and the
  3. auto-calibration (calibrate.py) both read notes through these functions. numpy only, so it runs wherever the other
  4. LYNX scoring scripts run (scripts/taillab.py, scripts/fxparity.py).
  5. read_wav / write_wav PCM 16 / 24 / 32-bit float WAV, mixed to mono (float64)
  6. onset the first sample of the note (1 ms envelope rises above a fraction of its peak)
  7. pick_peaks the prominent spectral peaks of a note (early and main windows, parabolic interpolation)
  8. track one partial's amplitude over time (heterodyne: Hann-windowed DFT at its frequency)
  9. fit_decay exponential decay of a partial's track: level at the onset, T60, fit error
  10. analyse_modes peaks -> tracked, fitted modes (frequency, initial amplitude, T60), strongest first
  11. rise_time / centroid attack measures (10-90 % rise of the 0.5 ms envelope, at least 0.5 ms; spectral centroid)
  12. """
  13. import struct
  14. import numpy as np
  15. # --- files ----------------------------------------------------------------------------------------------------------
  16. def read_wav(path, mono=True):
  17. """(samples float64, sample rate). PCM 16 / 24 / 32 bit and IEEE float 32; WAVE_FORMAT_EXTENSIBLE is accepted."""
  18. d = open(path, 'rb').read()
  19. if d[:4] != b'RIFF' or d[8:12] != b'WAVE':
  20. raise ValueError('not a WAV file: %s' % path)
  21. i, fmt = 12, None
  22. while i + 8 <= len(d):
  23. cid, size = d[i:i + 4], struct.unpack('<I', d[i + 4:i + 8])[0]
  24. if cid == b'fmt ':
  25. fmt = struct.unpack('<HHIIHH', d[i + 8:i + 24])
  26. elif cid == b'data' and fmt:
  27. tag, ch, rate, _, _, bits = fmt
  28. raw = d[i + 8:i + 8 + size]
  29. if bits == 24:
  30. a = np.frombuffer(raw[:len(raw) // 3 * 3], np.uint8).reshape(-1, 3).astype(np.int32)
  31. x = ((a[:, 0] | (a[:, 1] << 8) | (a[:, 2] << 16)) << 8 >> 8) / 8388608.0
  32. elif bits == 16:
  33. x = np.frombuffer(raw[:len(raw) // 2 * 2], '<i2') / 32768.0
  34. elif bits == 32 and tag in (3, 0xFFFE):
  35. x = np.frombuffer(raw[:len(raw) // 4 * 4], '<f4').astype(np.float64)
  36. elif bits == 32:
  37. x = np.frombuffer(raw[:len(raw) // 4 * 4], '<i4') / 2147483648.0
  38. else:
  39. raise ValueError('unsupported WAV: %d bits' % bits)
  40. x = x[:len(x) // ch * ch].reshape(-1, ch)
  41. return (x.mean(axis=1) if mono else x), rate
  42. i += 8 + size + (size & 1)
  43. raise ValueError('no data chunk: %s' % path)
  44. def write_wav(path, x, sr, bits=16):
  45. """mono or (n, 2) float array in -1..1 -> PCM WAV (16 or 24 bit)"""
  46. y = np.asarray(x, dtype=np.float64)
  47. ch = 1 if y.ndim == 1 else y.shape[1]
  48. y = np.clip(y.reshape(-1), -1.0, 1.0)
  49. if bits == 24:
  50. v = np.round(y * 8388607.0).astype(np.int32)
  51. pcm = np.stack([v & 255, (v >> 8) & 255, (v >> 16) & 255], 1).astype(np.uint8).tobytes()
  52. else:
  53. bits = 16
  54. pcm = np.round(y * 32767.0).astype('<i2').tobytes()
  55. ba = ch * bits // 8
  56. with open(path, 'wb') as f:
  57. f.write(b'RIFF' + struct.pack('<I', 36 + len(pcm)) + b'WAVEfmt ' + struct.pack('<IHHIIHH', 16, 1, ch, sr, sr * ba, ba, bits))
  58. f.write(b'data' + struct.pack('<I', len(pcm)) + pcm)
  59. # --- time -----------------------------------------------------------------------------------------------------------
  60. def smooth_env(x, sr, ms):
  61. """|x| smoothed by a moving RMS of `ms` milliseconds (same length as x)"""
  62. n = max(1, int(sr * ms / 1000.0))
  63. c = np.cumsum(np.concatenate([[0.0], x * x]))
  64. e = np.sqrt(np.maximum((c[n:] - c[:-n]) / n, 0.0))
  65. return np.concatenate([e, np.full(n - 1, e[-1] if len(e) else 0.0)])
  66. def onset(x, sr, fraction=0.05):
  67. """first sample where the 1 ms envelope reaches `fraction` of its peak, moved back to where it left the floor"""
  68. e = smooth_env(x, sr, 1.0)
  69. if e.max() <= 0:
  70. return 0
  71. k = int(np.nonzero(e >= fraction * e.max())[0][0])
  72. floor = max(np.median(e[:max(k, 1)]) * 2.0, e.max() * 1e-3)
  73. j = k
  74. while j > 0 and e[j - 1] > floor and k - j < int(0.02 * sr):
  75. j -= 1
  76. return max(0, j - int(0.0005 * sr))
  77. def band_env(x, sr, ms=0.5, span=0.15):
  78. """amplitude envelope of the first `span` s, phase-blind between bands: the root of the summed energies of the
  79. analytic signals of octave bands (31 Hz ... Nyquist), each smoothed over `ms`. A lone partial gives its exact
  80. amplitude; partials in different octaves add their energies whatever their phases."""
  81. n = int(span * sr)
  82. seg = np.asarray(x[:n], np.float64)
  83. if len(seg) < 64:
  84. return np.zeros(len(seg))
  85. N = 1 << int(np.ceil(np.log2(len(seg) * 2)))
  86. X = np.fft.fft(seg, N)
  87. fr = np.abs(np.fft.fftfreq(N, 1.0 / sr))
  88. pos = np.fft.fftfreq(N) > 0
  89. e2 = np.zeros(len(seg))
  90. lo = 0.0
  91. edges = [44.2 * 2 ** k for k in range(12)] + [sr]
  92. for hi in edges:
  93. m = pos & (fr >= lo) & (fr < hi)
  94. lo = hi
  95. if not m.any():
  96. continue
  97. z = np.fft.ifft(np.where(m, 2.0 * X, 0.0))[:len(seg)]
  98. e2 += smooth_env(np.abs(z), sr, ms) ** 2
  99. return np.sqrt(e2)
  100. def rise_time(x, sr, lo=0.1, hi=0.9, ms=0.5, floor_s=0.0005):
  101. """seconds from `lo` to `hi` of the envelope's first maximum (the attack), broadband envelope smoothed over `ms`
  102. (band_env would smear a 1 ms onset to ~3 ms: an octave band at 500 Hz cannot resolve it)"""
  103. return rise_of_env(smooth_env(np.asarray(x[:int(0.15 * sr)], np.float64), sr, ms), sr, lo, hi, floor_s)
  104. def rise_of_env(seg, sr, lo=0.1, hi=0.9, floor_s=0.0005):
  105. """rise_time on an envelope already computed (the calibration combines envelopes of emulated parts)"""
  106. if len(seg) == 0 or seg.max() <= 0:
  107. return 0.0
  108. # the strike's own peak: the first local maximum reaching half of the 150 ms maximum (a marimba's resonator, a
  109. # bell's build-up can peak later; that is not the attack)
  110. # (a maximum over +-2 ms: the beats between partials ripple the envelope faster than that)
  111. big = seg.max()
  112. h = max(1, int(0.002 * sr))
  113. pad = np.concatenate([np.full(h, -1.0), seg, np.full(h, -1.0)])
  114. wmax = np.lib.stride_tricks.sliding_window_view(pad, 2 * h + 1).max(axis=1)
  115. loc = np.nonzero((seg >= wmax) & (seg >= 0.5 * big))[0]
  116. pk = int(loc[0]) if len(loc) else int(np.argmax(seg))
  117. top = seg[pk]
  118. a = np.nonzero(seg[:pk + 1] >= lo * top)[0]
  119. b = np.nonzero(seg[:pk + 1] >= hi * top)[0]
  120. if len(a) == 0 or len(b) == 0:
  121. return 0.0
  122. return max(float(b[0] - a[0]) / sr, floor_s)
  123. def centroid(seg, sr, fmin=40.0):
  124. """spectral centroid (Hz) of a segment, Hann window, above fmin"""
  125. if len(seg) < 16:
  126. return 0.0
  127. S = np.abs(np.fft.rfft(seg * np.hanning(len(seg)))) ** 2
  128. fr = np.fft.rfftfreq(len(seg), 1.0 / sr)
  129. m = fr >= fmin
  130. return float((S[m] * fr[m]).sum() / max(S[m].sum(), 1e-30))
  131. # --- frequency ------------------------------------------------------------------------------------------------------
  132. def _spectrum(seg, sr, nfft):
  133. w = np.hanning(len(seg))
  134. S = np.abs(np.fft.rfft(seg * w, nfft)) * (2.0 / w.sum())
  135. return S, np.fft.rfftfreq(nfft, 1.0 / sr)
  136. def _interp(S, fr, k):
  137. if 0 < k < len(S) - 1:
  138. a, b, c = np.log(S[k - 1] + 1e-30), np.log(S[k] + 1e-30), np.log(S[k + 1] + 1e-30)
  139. den = a - 2 * b + c
  140. p = 0.5 * (a - c) / den if den != 0 else 0.0
  141. p = float(np.clip(p, -0.5, 0.5))
  142. return float(fr[k] + p * (fr[1] - fr[0])), float(np.exp(b - 0.25 * (a - c) * p))
  143. return float(fr[k]), float(S[k])
  144. def pick_peaks(x, sr, fmin=40.0, fmax=None, k=40, prom_db=12.0, floor_db=-75.0, windows=((0.004, 0.08), (0.03, 1.0))):
  145. """prominent spectral peaks of a note that starts at sample 0: (frequency Hz, peak magnitude) strongest first.
  146. Two windows (early: the fast high modes; main: resolution for the low ones); a peak must stand `prom_db` over the
  147. median of its +-1/3 octave and lie within `-floor_db` of the window's maximum; picks closer than 1.5 % merge."""
  148. fmax = fmax or 0.45 * sr
  149. out = []
  150. for wi, (t0, t1) in enumerate(windows):
  151. a, b = int(t0 * sr), min(len(x), int(t1 * sr))
  152. if b - a < 256:
  153. continue
  154. seg = x[a:b]
  155. nfft = 1 << int(np.ceil(np.log2(max(len(seg) * 4, 1 << 15))))
  156. S, fr = _spectrum(seg, sr, nfft)
  157. band = (fr >= fmin) & (fr <= fmax)
  158. if not band.any():
  159. continue
  160. top = S[band].max()
  161. # local maxima
  162. loc = np.nonzero((S[1:-1] > S[:-2]) & (S[1:-1] >= S[2:]))[0] + 1
  163. loc = loc[band[loc] & (S[loc] > top * 10 ** (floor_db / 20.0))]
  164. loc = loc[np.argsort(S[loc])[::-1]][:400]
  165. lS = np.log(S + 1e-30)
  166. res = sr / float(len(seg)) # (the window's resolution: Hann main lobe +-2 res)
  167. kept = []
  168. for j in loc:
  169. # a Hann sidelobe of a stronger peak nearby (first sidelobe -31 dB, falling 18 dB / octave): not a partial
  170. if any(abs(fr[j] - fr[q]) < 12 * res and S[j] < S[q] * 10 ** (-(25.0 + 18.0 * np.log2(max(abs(fr[j] - fr[q]) / (2.5 * res), 1.0))) / 20.0)
  171. for q in kept):
  172. continue
  173. kept.append(j)
  174. lo = np.searchsorted(fr, fr[j] * 2 ** (-1 / 3)); hi = np.searchsorted(fr, fr[j] * 2 ** (1 / 3))
  175. med = np.median(lS[lo:hi]) if hi > lo else lS[j]
  176. if 20.0 / np.log(10) * (lS[j] - med) < prom_db:
  177. continue
  178. f, m = _interp(S, fr, j)
  179. out.append((f, m, wi))
  180. out.sort(key=lambda p: -p[1])
  181. merged = []
  182. for f, m, wi in out:
  183. if all(abs(f - g) > 0.015 * g for g, _, _ in merged):
  184. merged.append((f, m, wi))
  185. if len(merged) >= k:
  186. break
  187. return merged
  188. def peak_near(x, sr, f, cents=60.0, window=(0.03, 1.0)):
  189. """(frequency, magnitude) of the largest spectral peak within +-cents of f in the given window (as pick_peaks
  190. computes it), or None"""
  191. a, b = int(window[0] * sr), min(len(x), int(window[1] * sr))
  192. if b - a < 256:
  193. return None
  194. seg = x[a:b]
  195. nfft = 1 << int(np.ceil(np.log2(max(len(seg) * 4, 1 << 15))))
  196. S, fr = _spectrum(seg, sr, nfft)
  197. lo, hi = np.searchsorted(fr, f * 2 ** (-cents / 1200.0)), np.searchsorted(fr, f * 2 ** (cents / 1200.0))
  198. if hi <= lo + 1:
  199. return None
  200. lo, hi = max(lo, 1), min(hi, len(S) - 1)
  201. seg = S[lo:hi]
  202. loc = np.nonzero((seg > S[lo - 1:hi - 1]) & (seg >= S[lo + 1:hi + 1]))[0]
  203. if len(loc) == 0:
  204. return None # (no local maximum inside: only a neighbour's skirt)
  205. j = lo + int(loc[np.argmax(seg[loc])])
  206. return _interp(S, fr, j)
  207. def track(x, sr, f, win, hop):
  208. """(times, amplitudes): the partial at f Hz, Hann-windowed DFT per frame (amplitude of a unit sine = 1)"""
  209. win = int(min(win, len(x)))
  210. if win < 16:
  211. return np.zeros(0), np.zeros(0)
  212. w = np.hanning(win)
  213. g = 2.0 / w.sum()
  214. c = np.exp(-2j * np.pi * f * np.arange(win) / sr) * w * g
  215. starts = np.arange(0, len(x) - win + 1, hop)
  216. fr = np.lib.stride_tricks.sliding_window_view(x, win)[starts]
  217. z = fr @ c
  218. return (starts + win / 2.0) / sr, np.abs(z)
  219. def track_window(f, neighbours, sr):
  220. """window length for tracking f: resolves its nearest neighbour (3 main-lobe widths) and holds >= 6 periods"""
  221. sp = min([abs(f - g) for g in neighbours if abs(f - g) > 1e-6] or [f])
  222. return int(np.clip(max(3.0 * 2.0 * sr / max(sp, 1.0), 6.0 * sr / f), 256, 16384))
  223. def window_gain(t60, win, sr):
  224. """what a Hann window of `win` samples reads of a decaying partial re its value at the window's centre (> 1: the
  225. window's earlier half weighs the louder past); 1 for a slow decay"""
  226. w = np.hanning(int(win))
  227. n = (np.arange(len(w)) - (len(w) - 1) / 2.0) / sr
  228. return float((w * np.exp(-6.9078 / max(t60, 1e-3) * n)).sum() / w.sum())
  229. def fit_decay(t, a, range_db=45.0, floor_margin_db=8.0, min_points=5, win=None, sr=None):
  230. """exponential decay fitted in dB from the track's peak: {'a0' level at t=0, 't60' s, 'rms_db', 't_peak'} or None.
  231. Uses the points between the peak and the first fall to (noise floor + margin) or (peak - range_db).
  232. (round 190nm) With the track's window `win` (samples) and rate `sr`: a0 is corrected for what the window reads of a
  233. fast decay (window_gain; a 0.15 s partial tracked with a 0.27 s window read 37 dB too loud). The timbre score
  234. calls it without, as before."""
  235. if len(a) < min_points:
  236. return None
  237. adb = 20.0 * np.log10(a + 1e-12)
  238. floor = np.percentile(adb[-max(5, len(adb) // 8):], 50)
  239. pk = int(np.argmax(adb))
  240. stop = max(floor + floor_margin_db, adb[pk] - range_db)
  241. below = np.nonzero(adb[pk:] < stop)[0]
  242. end = pk + (int(below[0]) if len(below) else len(adb) - pk)
  243. idx = np.arange(pk, end)
  244. if len(idx) < min_points:
  245. # a fast mode: fit what there is down to 3 points
  246. idx = np.arange(pk, min(len(adb), pk + min_points))
  247. if adb[pk] - floor < 10:
  248. return None
  249. tt, yy = t[idx], adb[idx]
  250. A = np.vstack([np.ones(len(tt)), tt]).T
  251. sol, *_ = np.linalg.lstsq(A, yy, rcond=None)
  252. b0, slope = float(sol[0]), float(sol[1])
  253. if slope >= -1e-3: # not decaying within the take: a very long T60
  254. slope = -60.0 / 120.0
  255. t60 = -60.0 / slope
  256. rms_db = float(np.sqrt(np.mean((A @ sol - yy) ** 2)))
  257. # the level at t = 0: the fit at the peak, carried back over the first frame's offset only (a track that peaks
  258. # late - noise, a neighbour's leakage - must not be extrapolated over its whole rise)
  259. a0db = b0 + slope * t[pk] - slope * t[0]
  260. if win is not None and sr:
  261. a0db -= 20.0 * np.log10(window_gain(t60, win, sr))
  262. return {'a0': float(10 ** (min(a0db, b0) / 20.0)), 't60': float(t60), 'rms_db': rms_db, 't_peak': float(t[pk]),
  263. 'peak_db': float(adb[pk]), 'floor_db': float(floor), 'points': int(len(idx))}
  264. WINDOWS = ((0.004, 0.08), (0.03, 1.0))
  265. def analyse_modes(x, sr, fmin=40.0, fmax=None, k=40, prom_db=12.0, hop_ms=5.0, peaks=None, window_exact=False):
  266. """the note's modes, strongest (energy a0^2 * t60) first: [{'f', 'a0', 't60', 'rms_db', 'energy', 'mag'}]
  267. (window_exact, round 190nm: a0 corrected for the tracking window, fit_decay)"""
  268. peaks = peaks if peaks is not None else pick_peaks(x, sr, fmin, fmax, k, prom_db)
  269. freqs = [p[0] for p in peaks]
  270. hop = max(1, int(sr * hop_ms / 1000.0))
  271. modes = []
  272. for f, mag, wi in peaks:
  273. win = track_window(f, freqs, sr)
  274. t, a = track(x, sr, f, win, hop)
  275. p = fit_decay(t, a, win=win if window_exact else None, sr=sr)
  276. if p is None:
  277. continue
  278. if window_exact and p['t60'] < 2.0 * win / sr:
  279. # (round 190nm: a partial that dies within its tracking window - a long window chosen to resolve a weak
  280. # neighbour - is tracked again with a window of half its T60: a plucked tine's fast fundamental read
  281. # through a 0.3 s window lost its first 20 dB and seemed to die four times too fast)
  282. win2 = int(np.clip(0.5 * p['t60'] * sr, 256, win))
  283. if win2 < win:
  284. t2, a2 = track(x, sr, f, win2, hop)
  285. p2 = fit_decay(t2, a2, win=win2, sr=sr)
  286. if p2 is not None:
  287. p, win = p2, win2
  288. p['f'] = float(f)
  289. p['mag'] = float(mag)
  290. p['win'] = win
  291. p['window'] = wi
  292. p['energy'] = p['a0'] ** 2 * p['t60']
  293. modes.append(p)
  294. modes.sort(key=lambda m: -m['energy'])
  295. return modes
  296. def third_octave_centres(lo=31.25, hi=16000.0):
  297. c = 1000.0 * 2.0 ** (np.arange(-15, 13) / 3.0)
  298. return c[(c >= lo * 0.99) & (c <= hi * 1.01)]
  299. def band_energy_grid(x, sr, edges_s, centres=None):
  300. """energy (dB) per third-octave band (rows) per time slice [edges_s[i], edges_s[i+1]) (columns)"""
  301. centres = third_octave_centres() if centres is None else centres
  302. out = np.full((len(centres), len(edges_s) - 1), -200.0)
  303. for j in range(len(edges_s) - 1):
  304. a, b = int(edges_s[j] * sr), int(edges_s[j + 1] * sr)
  305. seg = x[a:min(b, len(x))]
  306. if len(seg) < 32:
  307. continue
  308. nfft = 1 << int(np.ceil(np.log2(max(len(seg), 4096))))
  309. S = np.abs(np.fft.rfft(seg * np.hanning(len(seg)), nfft)) ** 2
  310. fr = np.fft.rfftfreq(nfft, 1.0 / sr)
  311. for i, c in enumerate(centres):
  312. m = (fr >= c * 2 ** (-1 / 6)) & (fr < c * 2 ** (1 / 6))
  313. out[i, j] = 10.0 * np.log10(S[m].sum() / len(seg) + 1e-30) if m.any() else -200.0
  314. return out
  315. # --- round 190nm: two components per partial (a two-stage decay, a beating pair) ---------------------------------------
  316. def track_complex(x, sr, f, win, hop):
  317. """(times, complex baseband track): the partial at f Hz as track() measures it, heterodyned to 0 Hz (a component
  318. at f + d Hz turns at d Hz; the amplitude of a unit sine = 1)"""
  319. win = int(min(win, len(x)))
  320. if win < 16:
  321. return np.zeros(0), np.zeros(0, complex)
  322. w = np.hanning(win)
  323. g = 2.0 / w.sum()
  324. c = np.exp(-2j * np.pi * f * np.arange(win) / sr) * w * g
  325. starts = np.arange(0, len(x) - win + 1, hop)
  326. fr = np.lib.stride_tricks.sliding_window_view(x, win)[starts]
  327. z = (fr @ c) * np.exp(-2j * np.pi * f * starts / sr)
  328. return (starts + win / 2.0) / sr, z
  329. def _pencil(z, order):
  330. """the poles of `order` damped complex exponentials in z (matrix pencil, pencil parameter len / 3)"""
  331. n = len(z)
  332. L = max(order, n // 3)
  333. Y = np.lib.stride_tricks.sliding_window_view(z, L + 1)
  334. U, s, Vh = np.linalg.svd(Y, full_matrices=False)
  335. V = Vh[:order].T # (the row space of Y: spanned by [1, p, p^2, ...] per pole)
  336. V1, V2 = V[:-1], V[1:]
  337. return np.linalg.eigvals(np.linalg.pinv(V1) @ V2)
  338. def fit_two(t, z, single, max_split_hz=3.0, min_gain_db=0.6, min_level_db=-30.0):
  339. """a partial's track as TWO components (round 190nm): c (e^(l1 t) + rho e^(l2 t)), rho real (the strike drives both
  340. components of a doublet - a near-degenerate pair of a tube or a tine - from rest, so they start in phase or in
  341. antiphase); l = -alpha + i 2 pi d. Same d: a two-stage decay (a fast and a slow part); different d: a beating pair.
  342. Fitted on the same span as fit_decay's single exponential (`single`, its result), by the matrix pencil on the complex
  343. track, then rho by a search; kept only when the track's dB error falls by `min_gain_db` and both components matter.
  344. Returns None or {'parts': [{'df' Hz re the tracked frequency, 'a0', 't60'}, ...], 'rms_db', 'rms_db_single'}"""
  345. if single is None or len(t) < 12:
  346. return None
  347. adb = 20 * np.log10(np.abs(z) + 1e-12)
  348. pk = int(np.argmax(adb))
  349. stop = max(single['floor_db'] + 8.0, adb[pk] - 45.0)
  350. below = np.nonzero(adb[pk:] < stop)[0]
  351. end = pk + (int(below[0]) if len(below) else len(adb) - pk)
  352. if end - pk < 12:
  353. return None
  354. tt, zz = t[pk:end], z[pk:end]
  355. dt = tt[1] - tt[0]
  356. # the single exponential's error on this span (a straight line in dB)
  357. A1 = np.vstack([np.ones(len(tt)), tt]).T
  358. sol, *_ = np.linalg.lstsq(A1, adb[pk:end], rcond=None)
  359. rms1 = float(np.sqrt(np.mean((A1 @ sol - adb[pk:end]) ** 2)))
  360. try:
  361. poles = _pencil(zz, 2)
  362. except np.linalg.LinAlgError:
  363. return None
  364. lam = np.log(poles.astype(complex) + 1e-30) / dt
  365. alpha = -lam.real
  366. df = lam.imag / (2 * np.pi)
  367. if np.any(alpha <= 0.0) or np.any(np.abs(df) > max_split_hz) or not np.all(np.isfinite(lam)):
  368. return None
  369. E = np.exp(np.outer(tt - tt[0], lam))
  370. def trial(rho):
  371. b = E[:, 0] + rho * E[:, 1]
  372. c = (b.conj() @ zz) / max((b.conj() @ b).real, 1e-30)
  373. m = 20 * np.log10(np.abs(c * b) + 1e-12)
  374. return float(np.sqrt(np.mean(np.minimum(np.abs(m - adb[pk:end]), 30.0) ** 2))), rho, c
  375. # (rho: the free complex amplitudes' ratio projected onto the real axis, and a search over signed ratios)
  376. cc, *_ = np.linalg.lstsq(E, zz, rcond=None)
  377. q = cc[1] / cc[0] if abs(cc[0]) > 0 else 1.0
  378. proj = abs(q) * (1.0 if q.real >= 0 else -1.0)
  379. grid = np.concatenate([-np.geomspace(30.0, 0.03, 40), np.geomspace(0.03, 30.0, 40), [proj] if np.isfinite(proj) and proj != 0 else []])
  380. best = min((trial(r) for r in grid), key=lambda q: q[0])
  381. best = min([best] + [trial(best[1] * k) for k in np.geomspace(0.84, 1.19, 15)], key=lambda q: q[0])
  382. err, rho, c = best
  383. if err > rms1 - min_gain_db:
  384. return None
  385. # the components' levels at the span's start, carried back over the first frame's offset only (as fit_decay does)
  386. a = np.abs(c) * np.array([1.0, abs(rho)]) * np.exp(alpha * t[0])
  387. lv = 20 * np.log10(a / a.max())
  388. if lv.min() < min_level_db:
  389. return None
  390. sign = [1.0, 1.0 if rho > 0 else -1.0]
  391. parts = [{'df': float(df[k]), 'a0': float(a[k]), 't60': float(min(6.9078 / alpha[k], 120.0)), 'sign': sign[k]} for k in range(2)]
  392. return {'parts': parts, 'rms_db': round(err, 3), 'rms_db_single': round(rms1, 3)}