taillab_test.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. #!/usr/bin/env python3
  2. """Unit tests of scripts/taillab.py on synthetic signals with known answers (round 190bp).
  3. python3 scripts/taillab_test.py (or: python3 scripts/taillab.py selftest)
  4. Every test builds its own signal: band-wise exponential noise decays with a known RT60, a capture shorter than
  5. its tail, a two-slope decay, sparse and dense echo patterns, known L/R correlations, a static and a modulated
  6. delay network, a pilot tone through a delay with a known LFO, and render pairs that are the same reverb with a
  7. different phase (must score high on the tail score although the waveform score cannot).
  8. """
  9. import os
  10. import sys
  11. import tempfile
  12. import numpy as np
  13. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
  14. import fxparity # noqa: E402
  15. import taillab as tl # noqa: E402
  16. SR = 48000
  17. FAILS = []
  18. CHECKS = 0
  19. def check(name, cond, info=''):
  20. global CHECKS
  21. CHECKS += 1
  22. if not cond:
  23. FAILS.append(f'{name} {info}')
  24. print('FAIL', name, info)
  25. def near(name, got, want, rel):
  26. check(name, got is not None and abs(got - want) <= rel * abs(want), f'got {got} want {want} +-{rel * 100:.0f} %')
  27. def stim_impulse(seconds=8.0, burst=True, seed=7):
  28. x = np.zeros((int(seconds * SR), 2))
  29. x[int(0.1 * SR)] = 0.5
  30. if burst:
  31. b = np.random.default_rng(seed).standard_normal(int(0.3 * SR)) * 0.25
  32. x[4 * SR:4 * SR + len(b)] = b[:, None]
  33. return x
  34. def noise_ir(rt, seconds=3.5, seed=1, corr=0.0, gain=0.05):
  35. """Stereo noise impulse response whose octave bands decay with rt[k] seconds (RT60); L/R correlation `corr`."""
  36. rng = np.random.default_rng(seed)
  37. n = int(seconds * SR)
  38. t = np.arange(n) / SR
  39. rts = rt if hasattr(rt, '__len__') else [rt] * len(tl.OCT)
  40. com = rng.standard_normal(n)
  41. out = []
  42. for c in (0, 1):
  43. w = np.sqrt(abs(corr)) * com * (1 if corr >= 0 or c == 0 else -1) + np.sqrt(1 - abs(corr)) * rng.standard_normal(n)
  44. b = tl.band_signals(w, SR)
  45. out.append(sum(b[k] * np.exp(-np.log(1000.0) * t / rts[k]) for k in range(len(tl.OCT))))
  46. return np.stack(out, 1) * gain
  47. def render(ir, stim, dry=0.0):
  48. """stim convolved with ir (per channel) plus dry * stim."""
  49. n = len(stim)
  50. nf = 1 << int(np.ceil(np.log2(n + len(ir))))
  51. out = np.stack([np.fft.irfft(np.fft.rfft(stim[:, c], nf) * np.fft.rfft(ir[:, c], nf), nf)[:n] for c in (0, 1)], 1)
  52. return out + dry * stim
  53. def modulated_net(stim, depth, rate=0.7, seed=3, taps=24, fb=0.0):
  54. """A time-variant test effect: `taps` delay taps (20-400 ms, random gains, random pan) whose delays move by
  55. +-`depth` samples at `rate` Hz with random phases. depth 0 = time-invariant."""
  56. rng = np.random.default_rng(seed)
  57. n = len(stim)
  58. t = np.arange(n)
  59. out = np.zeros((n, 2))
  60. m = stim.mean(1)
  61. for _ in range(taps):
  62. d0, g, ph, pan = rng.uniform(0.02, 0.4) * SR, rng.uniform(-1, 1) * 0.3, rng.uniform(0, 2 * np.pi), rng.uniform(0, 1)
  63. pos = t - (d0 + depth * np.sin(2 * np.pi * rate * t / SR + ph))
  64. y = np.interp(pos, t, m, left=0.0, right=0.0)
  65. out[:, 0] += g * pan * y
  66. out[:, 1] += g * (1 - pan) * y
  67. return out
  68. def t_decay_known():
  69. rts = [2.4, 2.0, 1.6, 1.2, 1.0, 0.8, 0.6, 0.4]
  70. s = stim_impulse(burst=False)
  71. st = tl.impulse_stats(render(noise_ir(rts), s), s, SR)
  72. for k, c in enumerate(tl.OCT):
  73. near(f'T20 {c} Hz', st['t20'][k], rts[k], 0.08)
  74. near(f'T30 {c} Hz', st['t30'][k], rts[k], 0.08)
  75. near(f'EDT {c} Hz', st['edt'][k], rts[k], 0.20)
  76. near(f'late RT {c} Hz', st['rt_late'][k], rts[k], 0.15)
  77. check('pre-delay ~0', st['predelay_ms'] < 3.0, str(st['predelay_ms']))
  78. # the same with a dry path and 25 ms of pre-delay
  79. ir = np.concatenate([np.zeros((int(0.025 * SR), 2)), noise_ir(1.0)])
  80. st = tl.impulse_stats(render(ir, s, dry=0.35), s, SR)
  81. near('dry gain', st['dry'][0], 0.35, 0.01)
  82. near('pre-delay 25 ms', st['predelay_ms'], 25.0, 0.12)
  83. near('T30 with dry + pre-delay', st['t30'][4], 1.0, 0.08)
  84. # a plug-in latency of 64 samples: the dry path is found there and time zero moves with it
  85. late = np.concatenate([np.zeros((64, 2)), render(ir, s, dry=0.35)[:-64]])
  86. st = tl.impulse_stats(late, s, SR)
  87. check('latency found', st['latency'] == 64 and abs(st['dry'][0] - 0.35) < 0.004, f"{st['latency']} {st['dry']}")
  88. near('pre-delay unchanged by latency', st['predelay_ms'], 25.0, 0.12)
  89. wetonly = tl.impulse_stats(render(ir, s, dry=0.0), s, SR)
  90. check('no dry path: none reported', wetonly['dry'] == [0.0, 0.0] and wetonly['latency'] == 0, str(wetonly['dry']))
  91. def t_decay_truncated():
  92. """RT 12 s seen through 3.9 s: T30 is out of range, the late-slope RT and EDT must still be right."""
  93. s = stim_impulse(burst=True)
  94. ir = noise_ir(12.0, seconds=7.5)
  95. st = tl.impulse_stats(render(ir, s), s, SR)
  96. check('T30 out of range', st['t30'][4] is None, str(st['t30'][4]))
  97. near('late RT truncated', st['rt_late'][4], 12.0, 0.15)
  98. near('EDT truncated', st['edt'][4], 12.0, 0.25)
  99. def t_two_slopes():
  100. s = stim_impulse(burst=False)
  101. ir = noise_ir(0.3, gain=0.05) + noise_ir(3.0, seed=2, gain=0.05 * 10 ** (-25 / 20.0))
  102. st = tl.impulse_stats(render(ir, s), s, SR)
  103. check('EDT follows the first slope', st['edt'][4] is not None and st['edt'][4] < 0.8, str(st['edt'][4]))
  104. check('T30 sees the second slope', st['t30'][4] is not None and st['t30'][4] > 1.5, str(st['t30'][4]))
  105. one = tl.impulse_stats(render(noise_ir(3.0, seed=2), s), s, SR)
  106. sc = tl.impulse_score(one, st)
  107. check('relief/early punish a missing first slope', sc['parts']['early'] < 8.0 and sc['parts']['relief'] < 9.5, str(sc['parts']))
  108. def t_echo_density():
  109. rng = np.random.default_rng(5)
  110. n = 2 * SR
  111. dense = rng.standard_normal(n)
  112. ned, _ = tl.ned_curve(dense, SR)
  113. near('NED of Gaussian noise', float(ned.mean()), 1.0, 0.06)
  114. sparse = np.zeros(n)
  115. sparse[rng.integers(0, n, 40)] = rng.standard_normal(40) # 20 echoes per second
  116. ned, _ = tl.ned_curve(sparse, SR)
  117. check('NED of sparse echoes', float(ned.mean()) < 0.2, str(float(ned.mean())))
  118. # build-up: echo rate grows with t^2 (as in a room); dense from about 0.25 s on
  119. x = np.zeros(n)
  120. t = np.arange(n) / SR
  121. hit = rng.random(n) < np.minimum(1.0, 60.0 * t * t)
  122. x[hit] = rng.standard_normal(hit.sum())
  123. st = tl.ned_stats(x, SR)
  124. check('NED build-up times ordered', st['t50'] is not None and st['t90'] is not None and 0.01 < st['t50'] < st['t90'] < 0.5, str(st))
  125. fast = np.zeros(n)
  126. hit = rng.random(n) < np.minimum(1.0, 2000.0 * t * t)
  127. fast[hit] = rng.standard_normal(hit.sum())
  128. st2 = tl.ned_stats(fast, SR)
  129. check('faster build-up is seen', st2['t90'] < st['t90'] * 0.5, f"{st2['t90']} vs {st['t90']}")
  130. def t_stereo():
  131. s = stim_impulse(burst=False)
  132. for want in (1.0, 0.5, 0.0, -0.6):
  133. st = tl.impulse_stats(render(noise_ir(1.5, corr=want), s), s, SR)
  134. got = np.mean([v for v in st['corr'][2] if v is not None])
  135. check(f'L/R correlation {want}', abs(got - want) < 0.08, str(got))
  136. wide = tl.impulse_stats(render(noise_ir(1.5, corr=0.0), s), s, SR)
  137. mono = tl.impulse_stats(render(noise_ir(1.5, corr=1.0), s), s, SR)
  138. check('width: mono is narrow', mono['width_db'][2] < -30 and abs(wide['width_db'][2]) < 2.0, f"{mono['width_db'][2]} {wide['width_db'][2]}")
  139. check('stereo part separates them', tl.impulse_score(wide, mono)['parts']['stereo'] < 1.0)
  140. def t_time_variance():
  141. s = stim_impulse(burst=True)
  142. v = []
  143. for depth in (0.0, 2.0, 12.0, 60.0):
  144. st = tl.impulse_stats(modulated_net(s, depth), s, SR)
  145. v.append(np.mean([x for x in st['tvi']['during'] + st['tvi']['after'] if x is not None]))
  146. check('time-invariant network: index ~0', v[0] < 0.01, str(v))
  147. check('index grows with depth', v[0] < v[1] < v[2] <= v[3] + 0.05 and v[3] > 0.6, str(v))
  148. # high bands lose coherence first: at a small excursion 8 kHz is far above 250 Hz
  149. st = tl.impulse_stats(modulated_net(s, 2.0), s, SR)
  150. check('index is larger at high frequency', st['tvi']['during'][7] > st['tvi']['during'][2] + 0.1, str(st['tvi']['during']))
  151. st0 = tl.impulse_stats(render(noise_ir(1.5), s), s, SR)
  152. check('convolution reverb: index ~0', max(x for x in st0['tvi']['during'] + st0['tvi']['after'] if x is not None) < 0.01)
  153. def t_pilot():
  154. n = 10 * SR
  155. t = np.arange(n)
  156. for hz, rate, depth in ((1000.0, 0.8, 20.0), (5000.0, 3.0, 4.0), (1000.0, 6.0, 1.0)):
  157. x = 0.25 * np.sin(2 * np.pi * hz * (t - (500 + depth * np.sin(2 * np.pi * rate * t / SR))) / SR)
  158. st = tl.pilot_stats(np.stack([x, x], 1), SR, hz, 1.0, 9.0)
  159. want = 1200.0 * np.log2(1.0 + 2 * np.pi * rate * depth / SR)
  160. near(f'pilot rate {rate} Hz', st['rate_hz'], rate, 0.03)
  161. near(f'pilot depth {want:.1f} cents', st['depth_cents'], want, 0.05)
  162. x = 0.25 * np.sin(2 * np.pi * 1000.0 * t / SR)
  163. st = tl.pilot_stats(np.stack([x, x], 1), SR, 1000.0, 1.0, 9.0)
  164. check('pilot: steady tone has no modulation', st['depth_cents'] < 0.01 and st['am_db'] < 0.001, str(st))
  165. y = x * (1 + 0.2 * np.sin(2 * np.pi * 2.0 * t / SR))
  166. st = tl.pilot_stats(np.stack([y, y], 1), SR, 1000.0, 1.0, 9.0)
  167. near('pilot: tremolo rate from the level', st['rate_hz'], 2.0, 0.03)
  168. def _prog(seed=11, seconds=6.0):
  169. """Programme-like stimulus: decaying noise hits and tone bursts."""
  170. rng = np.random.default_rng(seed)
  171. n = int(seconds * SR)
  172. x = np.zeros(n)
  173. for k in range(int(seconds * 3)):
  174. i = int(k * SR / 3)
  175. m = min(int(0.15 * SR), n - i)
  176. tt = np.arange(m) / SR
  177. f = (110, 220, 330, 440, 660, 880)[k % 6] * rng.uniform(0.9, 1.1)
  178. tone = sum(np.sin(2 * np.pi * f * h * tt) / h for h in range(1, 12))
  179. x[i:i + m] += (0.3 * rng.standard_normal(m) * np.exp(-tt * 40) + 0.2 * tone * np.exp(-tt * 12))
  180. x[int((seconds - 1.5) * SR):] = 0
  181. return np.stack([x, x], 1)
  182. def t_score_anchors():
  183. """The scale's anchors: the same reverb in another phase >= 9.2, decay + 10 % clearly below that, decay x 2 and
  184. an unrelated space lower still - while the waveform score cannot tell the first from the last."""
  185. rts = [2.0, 1.8, 1.5, 1.3, 1.1, 0.9, 0.7, 0.45]
  186. s = stim_impulse()
  187. prog = _prog()
  188. d = tempfile.mkdtemp(prefix='taillab_')
  189. cases = {'ref': noise_ir(rts, seed=1), 'same': noise_ir(rts, seed=2), 'rt110': noise_ir([r * 1.1 for r in rts], seed=3),
  190. 'rt200': noise_ir([r * 2 for r in rts], seed=4), 'other': noise_ir([0.3] * 8, seed=5, corr=0.9, gain=0.2)}
  191. for name, ir in cases.items():
  192. ir = np.concatenate([np.zeros((48, 2)), ir]) # 1 ms before the first reflection
  193. os.makedirs(f'{d}/{name}', exist_ok=True)
  194. tl.write_wav(f'{d}/{name}/D_impulse.wav', render(ir, s, dry=0.35), SR)
  195. tl.write_wav(f'{d}/{name}/D_music.wav', render(ir, prog, dry=0.35), SR)
  196. os.makedirs(f'{d}/stim', exist_ok=True)
  197. tl.write_wav(f'{d}/stim/impulse.wav', s, SR)
  198. tl.write_wav(f'{d}/stim/music.wav', prog, SR)
  199. res = {k: tl.score_dir(f'{d}/ref', f'{d}/{k}', f'{d}/stim') for k in cases}
  200. t = {k: v['tail'] for k, v in res.items()}
  201. print(' anchors (tail | wave):', ' '.join(f"{k} {v['tail']} | {v['wave']}" for k, v in res.items()))
  202. if os.environ.get('VERBOSE'):
  203. for k, v in res.items():
  204. print(' ', k, {n: (f['score'], f['parts']) for n, f in v['files'].items()})
  205. check('identical files score 10', t['ref'] >= 9.99, str(t))
  206. # noise-built reverbs on a short synthetic programme are the worst case of realisation noise; the real banks'
  207. # repeated recordings of one reference state score 9.7 ... 10 on their programme files (BASELINE-TAIL.md, anchors)
  208. check('same reverb, other phase >= 9.2', t['same'] >= 9.2, str(t))
  209. check('decay +10 % sits below, 8 ... 9.6', 8.0 <= t['rt110'] <= 9.6 and t['rt110'] < t['same'] - 0.2, str(t))
  210. check('decay x 2: 4 ... 6.5', 4.0 <= t['rt200'] <= 6.5, str(t))
  211. check('unrelated space <= 3', t['other'] <= 3.0 and t['other'] < t['rt200'], str(t))
  212. check('wave score cannot rank them', res['same']['wave'] <= 6 and abs(res['same']['wave'] - res['rt110']['wave']) <= 1.0,
  213. f"{res['same']['wave']} {res['rt110']['wave']}")
  214. check('dry gain found on both sides', abs(res['same']['settings']['D']['dry_ref'][0] - 0.35) < 0.01)
  215. # loss table: for the decay x 2 case the decay part must be the largest single loss of the impulse half
  216. imp_loss = {k: v for k, v in res['rt200']['loss'].items() if k.startswith('imp.')}
  217. check('loss table names decay first', next(iter(imp_loss)) in ('imp.decay', 'imp.relief'), str(imp_loss))
  218. near('losses add up to 10 - tail', sum(res['rt200']['loss'].values()), 10.0 - res['rt200']['tail'], 0.02)
  219. # polarity and a 1-sample shift do not matter
  220. a, _ = fxparity.read_wav(f'{d}/ref/D_impulse.wav')
  221. os.makedirs(f'{d}/flip', exist_ok=True)
  222. w = a - 0.35 * s
  223. tl.write_wav(f'{d}/flip/D_impulse.wav', np.concatenate([np.zeros((1, 2)), -w[:-1]]) + 0.35 * s, SR)
  224. r = tl.pair(f'{d}/ref/D_impulse.wav', f'{d}/flip/D_impulse.wav', f'{d}/stim/impulse.wav', g_ref=(0.35, 0.35, 0), g_lynx=(0.35, 0.35, 0))
  225. check('polarity + 1 sample: >= 9.8', r['score'] >= 9.8, str(r['score']) + str(r['parts']))
  226. for name in cases:
  227. for f in os.listdir(f'{d}/{name}'):
  228. os.remove(f'{d}/{name}/{f}')
  229. def t_motion():
  230. """kind mod: an auto-pan / tremolo at another rate must lose the motion part, another LFO phase must not."""
  231. prog = _prog(seconds=8.0)
  232. n = len(prog)
  233. t = np.arange(n) / SR
  234. rng = np.random.default_rng(2)
  235. x = prog + 0.05 * rng.standard_normal((n, 1)) * (t < 6.5)[:, None]
  236. def pan(rate, ph):
  237. p = 0.5 + 0.45 * np.sin(2 * np.pi * rate * t + ph)
  238. return np.stack([x[:, 0] * np.sqrt(1 - p), x[:, 1] * np.sqrt(p)], 1)
  239. A = tl.programme_stats(pan(1.0, 0.0), x, SR, kind='mod')
  240. same = tl.programme_score(A, tl.programme_stats(pan(1.0, 2.0), x, SR, kind='mod'), 'mod')
  241. fast = tl.programme_score(A, tl.programme_stats(pan(4.0, 0.0), x, SR, kind='mod'), 'mod')
  242. still = tl.programme_score(A, tl.programme_stats(x * 0.7, x, SR, kind='mod'), 'mod')
  243. check('motion: other phase, same rate >= 9', same['parts']['motion'] >= 9.0, str(same['parts']))
  244. check('motion: 4x rate is punished', fast['parts']['motion'] <= same['parts']['motion'] - 2.0, str(fast['parts']))
  245. check('motion: no pan at all is punished most', still['parts']['motion'] <= fast['parts']['motion'], str(still['parts']))
  246. def run():
  247. for fn in (t_decay_known, t_decay_truncated, t_two_slopes, t_echo_density, t_stereo, t_time_variance, t_pilot,
  248. t_score_anchors, t_motion):
  249. print(fn.__name__)
  250. fn()
  251. print(f'taillab selftest: {CHECKS} checks, {len(FAILS)} failures')
  252. return 1 if FAILS else 0
  253. if __name__ == '__main__':
  254. sys.exit(run())