test_timbre_score.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. #!/usr/bin/env python3
  2. """Unit tests of tools/physmod/timbre_score.py on synthetic notes with known answers (round 190ni).
  3. python3 -m unittest discover -s tools/physmod -p 'test_*.py' (or: python3 tools/physmod/timbre_score.py selftest)
  4. Each test builds its notes from decaying partials (frequency, level, T60, phase, attack time) so the expected
  5. change of each sub-score is known: phase changes must not matter, a detune moves only `pitch`, one moved partial
  6. moves `inharm`, scaled decays move `decay`, a slower attack moves `attack`, a level change moves `level`.
  7. """
  8. import os
  9. import sys
  10. import unittest
  11. import numpy as np
  12. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
  13. import modal_analysis as ma # noqa: E402
  14. import timbre_score as ts # noqa: E402
  15. SR = 48000
  16. # a marimba-like bar: 1 : 3.93 : 9.2 : 16.3, plus a weak resonator line
  17. BAR = [(523.25, 0.0, 2.0), (523.25 * 3.93, -9.0, 0.45), (523.25 * 9.2, -16.0, 0.18), (523.25 * 16.3, -24.0, 0.09),
  18. (523.25 * 2.0, -30.0, 1.2)]
  19. def note(partials=BAR, seconds=2.5, rise=0.001, gain_db=-6.0, cents=0.0, decay=1.0, phases=None, sr=SR, noise_db=-90.0,
  20. seed=1):
  21. t = np.arange(int(seconds * sr)) / sr
  22. rng = np.random.default_rng(seed)
  23. y = np.zeros(len(t))
  24. for i, (f, db, t60) in enumerate(partials):
  25. ph = phases[i] if phases is not None else 0.0
  26. y += 10 ** (db / 20) * np.exp(-6.9078 * t / (t60 * decay)) * np.sin(2 * np.pi * f * 2 ** (cents / 1200) * t + ph)
  27. a = np.clip(t / rise, 0, 1)
  28. y *= 0.5 - 0.5 * np.cos(np.pi * a)
  29. y = np.concatenate([np.zeros(int(0.01 * sr)), y])
  30. y *= 10 ** (gain_db / 20) # (a fixed gain: a peak normalisation would change the level with the phases)
  31. y += 10 ** (noise_db / 20) * rng.standard_normal(len(y))
  32. return y
  33. def score(a, b, **kw):
  34. return ts.score_pair(a, b, SR, **kw)
  35. class TimbreScoreTests(unittest.TestCase):
  36. @classmethod
  37. def setUpClass(cls):
  38. cls.ref = note()
  39. def test_identical_is_ten(self):
  40. r = score(self.ref, self.ref)
  41. self.assertEqual(r['timbre_score'], 10.0)
  42. self.assertTrue(all(v == 10.0 for v in r['subscores'].values()), r['subscores'])
  43. def test_phase_blind(self):
  44. rng = np.random.default_rng(7)
  45. other = note(phases=rng.uniform(0, 2 * np.pi, len(BAR)))
  46. r = score(self.ref, other)
  47. # (random phases change the attack's crest and the first 10 ms slices, whose short windows see the abrupt 1 ms
  48. # onset's splatter differently: physically real, but small; the partial parts must not move)
  49. self.assertGreaterEqual(r['timbre_score'], 9.3, r['subscores'])
  50. for k in ('pitch', 'inharm', 'levels', 'decay', 'level'):
  51. self.assertGreaterEqual(r['subscores'][k], 9.8, k)
  52. inv = score(self.ref, -self.ref)
  53. self.assertEqual(inv['timbre_score'], 10.0)
  54. if inv['wave'] is not None: # the wave score cannot see this: the error is twice the signal
  55. self.assertGreater(inv['wave']['esr_db'], 5.0)
  56. def test_detune_moves_pitch_only(self):
  57. r = score(self.ref, note(cents=15.0))
  58. self.assertAlmostEqual(r['pitch_cents'], 15.0, delta=1.0)
  59. self.assertAlmostEqual(r['subscores']['pitch'], 10 * (1 - 15 / ts.FULL['pitch']), delta=0.5)
  60. self.assertGreaterEqual(r['subscores']['inharm'], 9.5)
  61. self.assertGreaterEqual(r['subscores']['decay'], 9.5)
  62. def test_moved_partial_moves_inharm(self):
  63. moved = list(BAR)
  64. f, db, t60 = moved[1]
  65. moved[1] = (f * 2 ** (20 / 1200), db, t60)
  66. r = score(self.ref, note(partials=moved))
  67. self.assertGreaterEqual(r['subscores']['pitch'], 9.8)
  68. self.assertLess(r['subscores']['inharm'], 9.0)
  69. row = [q for q in r['partials'] if abs(q['f'] - f) < 5][0]
  70. self.assertAlmostEqual(row['cents'], 20.0, delta=1.5)
  71. def test_decay_scale(self):
  72. r2 = score(self.ref, note(decay=2.0))
  73. r14 = score(self.ref, note(decay=2 ** 0.5))
  74. self.assertLess(r2['subscores']['decay'], 1.0)
  75. self.assertAlmostEqual(r14['subscores']['decay'], 5.0, delta=1.0)
  76. self.assertAlmostEqual(r14['decay_log2_median'], 0.5, delta=0.08)
  77. self.assertGreater(r14['timbre_score'], r2['timbre_score'])
  78. def test_slow_attack(self):
  79. r = score(self.ref, note(rise=0.012))
  80. self.assertLess(r['subscores']['attack'], 7.0)
  81. self.assertGreater(r['attack']['rise_ms'][1], 3 * r['attack']['rise_ms'][0])
  82. def test_level_only(self):
  83. r = score(self.ref, note(gain_db=-9.0))
  84. self.assertAlmostEqual(r['level_db'], -3.0, delta=0.2)
  85. self.assertAlmostEqual(r['subscores']['level'], 5.0, delta=0.4)
  86. for k in ('pitch', 'inharm', 'levels', 'decay', 'spectime', 'attack'):
  87. self.assertGreaterEqual(r['subscores'][k], 9.5, k)
  88. def test_missing_partials_cost(self):
  89. r = score(self.ref, note(partials=BAR[:1]))
  90. full = score(self.ref, note(cents=2.0))
  91. self.assertLess(r['timbre_score'], full['timbre_score'] - 2.0)
  92. self.assertEqual(r['partials_matched'].split('/')[0], '1')
  93. def test_monotonic_in_detune(self):
  94. s = [score(self.ref, note(cents=c))['timbre_score'] for c in (0.0, 5.0, 12.0, 25.0, 45.0)]
  95. self.assertEqual(s, sorted(s, reverse=True), s)
  96. def test_noise_is_not_a_note(self):
  97. rng = np.random.default_rng(3)
  98. t = np.arange(len(self.ref)) / SR
  99. nz = rng.standard_normal(len(self.ref)) * np.exp(-3 * t) * 0.1
  100. r = score(self.ref, nz)
  101. self.assertLess(r['timbre_score'], 4.0, r['subscores'])
  102. def test_other_rate(self):
  103. a = note(sr=44100)
  104. b = note(sr=44100, cents=10.0)
  105. r = ts.score_pair(a, b, 44100)
  106. self.assertAlmostEqual(r['pitch_cents'], 10.0, delta=1.0)
  107. def test_stiff_string_b(self):
  108. f0, B = 110.0, 4e-4
  109. fs = [n * f0 * np.sqrt(1 + B * n * n) for n in range(1, 13)]
  110. got = ts.stiff_b(fs)
  111. self.assertIsNotNone(got)
  112. self.assertAlmostEqual(got[0], f0, delta=0.05)
  113. self.assertAlmostEqual(got[1] / B, 1.0, delta=0.02)
  114. def test_wav_round_trip(self):
  115. import tempfile
  116. with tempfile.TemporaryDirectory() as d:
  117. p = os.path.join(d, 'n.wav')
  118. ma.write_wav(p, self.ref, SR, bits=24)
  119. x, sr = ma.read_wav(p)
  120. self.assertEqual(sr, SR)
  121. self.assertLess(np.abs(x - self.ref).max(), 2e-7)
  122. self.assertEqual(score(self.ref, x)['timbre_score'], 10.0)
  123. def test_clean_note_against_a_noisy_take(self):
  124. # (round 190nl) a take with a fluctuating room rumble: the clean note itself must score about as well as a
  125. # copy of the take with the same note, and better than a clean note one semitone off
  126. rng = np.random.default_rng(11)
  127. n = len(self.ref)
  128. t = np.arange(n) / SR
  129. rumble = np.convolve(rng.standard_normal(n), np.ones(400) / 400, 'same') * (1 + 0.8 * np.sin(2 * np.pi * 0.7 * t)) * 0.02
  130. take = self.ref + rumble
  131. clean = score(take, self.ref)
  132. self.assertGreaterEqual(clean['subscores']['spectime'], 5.0, clean.get('spectime_db'))
  133. self.assertLess(clean['spectime_db'], clean['spectime_190ni']['db'] - 1.0) # (the 190ni rule counted the room as missing)
  134. self.assertGreater(clean['timbre_score'], score(take, note(cents=100.0))['timbre_score'] + 2.0)
  135. # (the 190ni rule is reported beside, never above the new one for a clean note)
  136. self.assertLessEqual(clean['timbre_score_190ni'], clean['timbre_score'] + 1e-9)
  137. def test_strike_loss_matches_the_score_parts(self):
  138. # (round 190nl) refine.py's loss: zero for the note itself, larger for a slower attack and for a darker strike
  139. sl = ts.StrikeLoss(self.ref, SR)
  140. self.assertLess(sl.loss(self.ref), 1e-6)
  141. slow = sl.loss(note(rise=0.012))
  142. dark = sl.loss(note(partials=BAR[:2]))
  143. self.assertGreater(slow, 0.01)
  144. self.assertGreater(dark, 0.01)
  145. class TuningTests(unittest.TestCase):
  146. def test_long_ringing_fundamental(self):
  147. # (round 190nl) evaluate.tuning_of on a vibraphone-like note: a 20 s fundamental 12 cents flat with a -50 dB
  148. # line 50 cents below it; the tuning is the fundamental's, not the line's
  149. import evaluate
  150. f = 440.0 * 2 ** (-12 / 1200.0)
  151. x = note(partials=[(f, 0.0, 20.0), (440.0 * 2 ** (-50 / 1200.0), -50.0, 20.0), (4 * f, -12.0, 3.0)], seconds=2.0)
  152. x = x[int(0.01 * SR):]
  153. self.assertAlmostEqual(evaluate.tuning_of(x, SR, 69), -12.0, delta=1.0)
  154. if __name__ == '__main__':
  155. unittest.main()