timbre_score.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. #!/usr/bin/env python3
  2. """timbre_score.py - the TIMBRE SCORE of a single note (round 190ni, the quality gate of LYNX Model).
  3. The waveform score (scripts/fxparity.py score(), untouched) needs a waveform null. A physical model never nulls
  4. against a different recording (phases, the room, the take's noise differ), so the wave score under-rates a good
  5. model: the 190nd prototype's piano scored 4/10 at a 1.0 dB third-octave spectrum difference. This score compares
  6. what a listener hears in ONE note, blind to phase, and is always reported next to the wave score, never instead.
  7. timbre_score.py pair <ref.wav> <cand.wav> [--f0 HZ] [--dur S] [--partials K] [--json OUT]
  8. one note: the measurements, the sub-scores and the timbre score (0-10), plus the wave metrics (JSON)
  9. timbre_score.py selftest
  10. the unit tests (tools/physmod/test_timbre_score.py) on synthetic notes with known answers
  11. Both notes are cut at their onsets (modal_analysis.onset), the candidate then shifted (+-8 ms) to where its 2 ms
  12. envelope best correlates with the reference's (by more than 0.02 over no shift) (two onset detections disagree by a few ms on a soft start), and both
  13. compared over the shorter length (at most --dur, 8 s).
  14. Parts (each 10 at a match, 0 at the distance FULL[part]; the score is 10 minus the weighted quadratic mean of what
  15. the parts miss, as scripts/taillab.py's tail score):
  16. pitch cents error of the reference's main partial (the strongest; with --f0 the strongest near f0)
  17. inharm the partials' frequency pattern: cents error of each partial relative to the main one (weighted)
  18. levels each partial's initial level relative to the main one (dB, weighted)
  19. decay each partial's T60, |log2 ratio| (weighted)
  20. spectime spectral envelope over time: third-octave energy on a log-spaced time grid (0-10-30-60-100-200-400 ms
  21. ... doubling), dB, overall level removed; the cells audible in either note (within 50 dB of the top and
  22. 6 dB above the reference's background in that band: its quietest slice, the room and the take's noise)
  23. attack attack shape: 10-90 % rise time (|log2|), spectral centroid of the first 30 ms (|log2|) and the 1 ms
  24. envelope over the first 150 ms (dB, each normalised to its peak, on a log time grid 0.5-150 ms; band-wise, so
  25. blind to the phases between octaves). The rise ends at the strike's own peak (the first local maximum
  26. of at least half the 150 ms maximum)
  27. level loudness difference of the first 2 s (dB; weight 0.5)
  28. Partial weights are sqrt(energy) (energy = a0^2 * T60) of the reference's K strongest partials (default 16); a
  29. partial the candidate lacks (no peak within 60 cents and 40 dB of it) misses fully in pitch / inharm / levels / decay.
  30. The reference's stiff-string inharmonicity B (f_n = n f0 sqrt(1 + B n^2), least squares) is reported for both notes
  31. when the partials are near-harmonic; it is part of `inharm` through the partial pattern, not a separate part.
  32. """
  33. import json
  34. import os
  35. import sys
  36. import numpy as np
  37. HERE = os.path.dirname(os.path.abspath(__file__))
  38. sys.path.insert(0, HERE)
  39. import modal_analysis as ma # noqa: E402
  40. FULL = {'pitch': 25.0, 'inharm': 30.0, 'levels': 12.0, 'decay': 1.0, 'spectime': 10.0, 'attack': 1.0, 'level': 6.0}
  41. WEIGHT = {'pitch': 1.0, 'inharm': 1.0, 'levels': 1.0, 'decay': 1.0, 'spectime': 1.5, 'attack': 1.0, 'level': 0.5}
  42. ATTACK_FULL = {'rise': 1.5, 'centroid': 1.0, 'curve': 8.0}
  43. MATCH_CENTS = 60.0
  44. MISSING_DB = 24.0 # a candidate partial this far below the reference's (level corrected) counts as missing
  45. MASK_DB = 30.0
  46. FLOOR_DB = 50.0 # reference partials further below the strongest one are not scored
  47. FLOOR_MARGIN = 6.0
  48. def band_floor(grid):
  49. """per band (rows) the background level of a note's band-energy grid: its quietest time slice, as a column"""
  50. return grid.min(axis=1, keepdims=True)
  51. def spectime(gr, gc, lev, rule='190nl'):
  52. """the spectro-temporal part from the two notes' band-energy grids (dB; rows = third-octave bands, columns = time
  53. slices) and the candidate's level offset `lev` (dB): {'miss' 0..1, 'db' mean dB difference or None}.
  54. A cell is part of the note where it stands within 50 dB of the top and FLOOR_MARGIN dB above the reference's
  55. background in that band (its quietest slice: the room, the take's noise) in either note.
  56. Rule '190nl' (round 190nl): (1) the overall offset removed is the median difference over the cells audible in BOTH
  57. notes (190ni took it over every audible cell, so a clean note against a noisy take - every cell the room fills and
  58. the note leaves empty reads 30 dB down - had its real partials pushed up by the room's level); (2) a candidate cell
  59. below the reference's background reads as that background (what the take's room would let one hear of it: a clean
  60. synthesis is not missing the room's rumble). Rule '190ni': the score as round 190ni shipped it (reported beside)."""
  61. top = max(gr.max(), gc.max() - lev)
  62. floor = band_floor(gr)
  63. ra = (gr > top - 50) & (gr > floor + FLOOR_MARGIN)
  64. ca = (gc - lev > top - 50) & (gc - lev > floor + FLOOR_MARGIN)
  65. aud = ra | ca
  66. if not aud.any():
  67. return {'miss': 1.0, 'db': None}
  68. if rule == '190ni':
  69. d = (gc - lev) - gr
  70. d = d - np.median(d[aud])
  71. else:
  72. both = ra & ca
  73. d = np.maximum(gc - lev, floor) - gr
  74. d = d - np.median(d[both] if both.sum() >= 3 else d[aud])
  75. v = float(np.mean(np.minimum(np.abs(d[aud]), 30.0)))
  76. return {'miss': v / FULL['spectime'], 'db': round(v, 2)}
  77. def cents(a, b):
  78. return 1200.0 * np.log2(a / b)
  79. def time_edges(n_seconds):
  80. e = [0.0, 0.01, 0.03, 0.06, 0.1, 0.2, 0.4]
  81. while e[-1] * 2 <= n_seconds + 1e-9:
  82. e.append(e[-1] * 2)
  83. if n_seconds - e[-1] > 0.1:
  84. e.append(n_seconds)
  85. return np.array(e)
  86. def stiff_b(freqs):
  87. """(f0, B) of the stiff-string law fitted to near-harmonic partials, or None"""
  88. fs = np.sort(np.asarray(freqs))
  89. if len(fs) < 4:
  90. return None
  91. f1 = fs[0]
  92. n = np.round(fs / f1)
  93. ok = (n >= 1) & (np.abs(cents(fs, n * f1)) < 80)
  94. if ok.sum() < 4 or len(set(n[ok])) < 4:
  95. return None
  96. A = np.vstack([np.ones(ok.sum()), n[ok] ** 2]).T
  97. sol, *_ = np.linalg.lstsq(A, (fs[ok] / n[ok]) ** 2, rcond=None)
  98. if sol[0] <= 0:
  99. return None
  100. return float(np.sqrt(sol[0])), float(max(sol[1] / sol[0], 0.0))
  101. def envelope_db(x, sr, ms=1.0, span=0.15):
  102. e = ma.band_env(x, sr, ms, span)
  103. return 20.0 * np.log10(e / max(e.max(), 1e-12) + 1e-9)
  104. def envelope_lag(a, b, sr, span=0.08, search=0.008, margin=0.02):
  105. """samples b lags a (b[i + lag] ~ a[i]): the best Pearson correlation of their 2 ms envelopes over the first
  106. `span` s, within +-`search` s (two independent onset detections differ by a few ms on a soft or noisy start). Lag 0
  107. stays unless another lag correlates better by more than `margin` (phase ripple must not move a note)."""
  108. n = int(span * sr)
  109. h = int(search * sr)
  110. ea = ma.smooth_env(np.asarray(a[:n], np.float64), sr, 2.0)
  111. eb = ma.smooth_env(np.concatenate([np.asarray(b[:n + h], np.float64), np.zeros(max(0, n + h - len(b)))]), sr, 2.0)
  112. def corr(L):
  113. seg = eb[max(L, 0):max(L, 0) + n - max(-L, 0)]
  114. ref = ea[max(-L, 0):max(-L, 0) + len(seg)]
  115. if len(seg) < 16 or seg.std() == 0 or ref.std() == 0:
  116. return -1.0
  117. return float(np.corrcoef(ref, seg)[0, 1])
  118. zero = corr(0)
  119. best, lag = zero, 0
  120. for L in range(-h, h + 1):
  121. v = corr(L)
  122. if v > best:
  123. best, lag = v, L
  124. return lag if best - zero > margin else 0
  125. def align(r, c, sr):
  126. """c shifted so its envelope lines up with r's (phase-blind; see envelope_lag)"""
  127. lag = envelope_lag(r, c, sr)
  128. if lag > 0:
  129. return c[lag:]
  130. if lag < 0:
  131. return np.concatenate([np.zeros(-lag), c])
  132. return c
  133. def prepare(x, sr, dur):
  134. on = ma.onset(x, sr)
  135. return x[on:on + int(dur * sr)]
  136. def attack_part(r, c, sr):
  137. """the attack part of two aligned notes: (miss 0..1, measures) - see the module doc"""
  138. rr, rc = ma.rise_time(r, sr), ma.rise_time(c, sr)
  139. a30 = int(0.03 * sr)
  140. cr, cc = ma.centroid(r[:a30], sr), ma.centroid(c[:a30], sr)
  141. er, ec = envelope_db(r, sr), envelope_db(c, sr)
  142. k = min(len(er), len(ec))
  143. # (on a log time grid 0.5 ... 150 ms: the first milliseconds weigh as much as the rest)
  144. grid = np.unique(np.clip((np.geomspace(0.0005, 0.15, 32) * sr).astype(int), 0, k - 1))
  145. er, ec = er[grid], ec[grid]
  146. m = er > -40
  147. curve = float(np.mean(np.minimum(np.abs(er[m] - ec[m]), 30.0))) if m.any() else 30.0
  148. am = {'rise': abs(np.log2(max(rc, 1e-5) / max(rr, 1e-5))) / ATTACK_FULL['rise'],
  149. 'centroid': abs(np.log2(max(cc, 1.0) / max(cr, 1.0))) / ATTACK_FULL['centroid'],
  150. 'curve': curve / ATTACK_FULL['curve']}
  151. return float(np.mean([min(v, 1.0) for v in am.values()])), {
  152. 'rise_ms': [round(rr * 1000, 3), round(rc * 1000, 3)], 'centroid_hz': [round(cr, 1), round(cc, 1)], 'curve_db': round(curve, 2)}
  153. class StrikeLoss:
  154. """the parts of the score a strike's parameters move (round 190nl, tools/physmod/refine.py): the attack and the
  155. spectro-temporal cells of the first `span` s, against one reference note, the reference analysed once.
  156. loss(cand) = (WEIGHT spectime * spectime miss^2 + attack miss^2) / (WEIGHT spectime + 1), the score's own parts;
  157. the candidate's level offset is taken over the first 2 s as the score does (render at least that long)."""
  158. def __init__(self, ref, sr, dur=8.0, span=0.4):
  159. self.sr = sr
  160. self.r = prepare(np.asarray(ref, np.float64), sr, dur)
  161. self.span = span
  162. self.edges = time_edges(len(self.r) / sr)
  163. self.gr = ma.band_energy_grid(self.r, sr, self.edges)
  164. self.cols = int(np.searchsorted(self.edges, span + 1e-9)) - 1
  165. def loss(self, cand, detail=False):
  166. sr = self.sr
  167. c = prepare(np.asarray(cand, np.float64), sr, len(self.r) / sr)
  168. c = align(self.r, c, sr)
  169. n = min(len(self.r), len(c))
  170. r = self.r[:n]
  171. c = c[:n]
  172. m2 = int(min(n, 2 * sr))
  173. lev = 10 * np.log10((np.mean(c[:m2] ** 2) + 1e-30) / (np.mean(r[:m2] ** 2) + 1e-30))
  174. e = self.edges[:self.cols + 1]
  175. gc = ma.band_energy_grid(c, sr, e)
  176. # (the reference's top and background from its whole note, as score_pair sees them)
  177. top = max(self.gr.max(), gc.max() - lev)
  178. floor = band_floor(self.gr)
  179. gr = self.gr[:, :self.cols]
  180. ra = (gr > top - 50) & (gr > floor + FLOOR_MARGIN)
  181. ca = (gc - lev > top - 50) & (gc - lev > floor + FLOOR_MARGIN)
  182. aud, both = ra | ca, ra & ca
  183. if aud.any():
  184. d = np.maximum(gc - lev, floor) - gr
  185. d = d - np.median(d[both] if both.sum() >= 3 else d[aud])
  186. spec = float(np.mean(np.minimum(np.abs(d[aud]), 30.0))) / FULL['spectime']
  187. else:
  188. spec = 1.0
  189. att, info = attack_part(r, c, sr)
  190. w = WEIGHT['spectime']
  191. loss = (w * min(spec, 1.0) ** 2 + att ** 2) / (w + 1.0)
  192. return (loss, {'spec': spec, 'attack': att, **info}) if detail else loss
  193. def score_pair(ref, cand, sr, f0=None, dur=8.0, partials=16, wave=True):
  194. """the timbre score of `cand` against `ref` (mono float arrays at the same rate): a dict (see the module doc)"""
  195. r = prepare(np.asarray(ref, np.float64), sr, dur)
  196. c = prepare(np.asarray(cand, np.float64), sr, dur)
  197. c = align(r, c, sr)
  198. n = min(len(r), len(c))
  199. r, c = r[:n], c[:n]
  200. secs = n / sr
  201. out = {'seconds': round(secs, 3)}
  202. miss = {}
  203. # level
  204. m2 = int(min(n, 2 * sr))
  205. lev = 10 * np.log10((np.mean(c[:m2] ** 2) + 1e-30) / (np.mean(r[:m2] ** 2) + 1e-30))
  206. out['level_db'] = round(float(lev), 2)
  207. miss['level'] = abs(lev) / FULL['level']
  208. # partials
  209. fmin = 0.8 * f0 if f0 else 40.0
  210. rm = ma.analyse_modes(r, sr, fmin=fmin, k=max(partials * 2, 24))
  211. top_a = max([m['a0'] for m in rm] or [0.0])
  212. rm = [m for m in rm if m['a0'] >= top_a * 10 ** (-FLOOR_DB / 20.0)]
  213. # masking: a partial far below a stronger one within about a critical band (+-max(100 Hz, 15 %)) is not heard
  214. rm = [m for m in rm if not any(o['a0'] > m['a0'] * 10 ** (MASK_DB / 20.0) and abs(o['f'] - m['f']) < max(100.0, 0.15 * m['f'])
  215. for o in rm)][:partials]
  216. if not rm:
  217. raise ValueError('no partials found in the reference')
  218. w = np.sqrt(np.array([m['energy'] for m in rm]))
  219. w = w / w.sum()
  220. hop = max(1, int(sr * 0.005))
  221. rows = []
  222. for m in rm:
  223. others = [abs(cents(o['f'], m['f'])) for o in rm if o is not m]
  224. span = min([MATCH_CENTS] + [0.45 * d for d in others])
  225. pk = ma.peak_near(c, sr, m['f'], span, ma.WINDOWS[m['window']])
  226. best = (cents(pk[0], m['f']), pk[0]) if pk is not None else None
  227. row = {'f': round(m['f'], 2), 'ref_t60': round(m['t60'], 3), 'ref_db': round(20 * np.log10(m['a0'] + 1e-12), 2)}
  228. if best is not None:
  229. t, a = ma.track(c, sr, best[1], m['win'], hop)
  230. p = ma.fit_decay(t, a)
  231. if p is not None and 20 * np.log10((p['a0'] + 1e-12) / (m['a0'] + 1e-12)) > -MISSING_DB - abs(lev):
  232. row.update({'cand_f': round(best[1], 2), 'cents': round(best[0], 2), 'cand_t60': round(p['t60'], 3),
  233. 'cand_db': round(20 * np.log10(p['a0'] + 1e-12), 2)})
  234. rows.append(row)
  235. main = 0
  236. if f0:
  237. near = [i for i, m in enumerate(rm[:6]) if abs(cents(m['f'], f0)) < 100 or abs(cents(m['f'], 2 * f0)) < 100]
  238. main = near[0] if near else 0
  239. mr = rows[main]
  240. found = ['cents' in q for q in rows]
  241. out['main_partial_hz'] = mr['f']
  242. out['partials_matched'] = '%d/%d' % (sum(found), len(rows))
  243. miss['pitch'] = abs(mr['cents']) / FULL['pitch'] if found[main] else 1.0
  244. out['pitch_cents'] = mr.get('cents')
  245. inh, lv, dc = [], [], []
  246. for i, q in enumerate(rows):
  247. if not found[i]:
  248. inh.append(1.0); lv.append(1.0); dc.append(1.0)
  249. continue
  250. dc.append(abs(np.log2(q['cand_t60'] / q['ref_t60'])) / FULL['decay'])
  251. if i == main or not found[main]:
  252. inh.append(0.0 if i == main else 1.0)
  253. lv.append(0.0 if i == main else 1.0)
  254. continue
  255. inh.append(abs(q['cents'] - mr['cents']) / FULL['inharm'])
  256. lv.append(abs((q['cand_db'] - mr['cand_db']) - (q['ref_db'] - mr['ref_db'])) / FULL['levels'])
  257. clip = lambda v: np.minimum(np.asarray(v), 1.0)
  258. # (the main partial's own pattern and level terms are 0 by definition: both are relative to it)
  259. wo = w.copy(); wo[main] = 0.0
  260. miss['inharm'] = float((wo * clip(inh)).sum() / max(wo.sum(), 1e-12)) if wo.sum() > 0 else 0.0
  261. miss['levels'] = float((wo * clip(lv)).sum() / max(wo.sum(), 1e-12)) if wo.sum() > 0 else 0.0
  262. miss['decay'] = float((w * clip(dc)).sum())
  263. out['partials'] = rows
  264. ok = [q for q in rows if 'cents' in q]
  265. out['decay_log2_median'] = round(float(np.median([np.log2(q['cand_t60'] / q['ref_t60']) for q in ok])), 3) if ok else None
  266. br = stiff_b([q['f'] for q in rows])
  267. bc = stiff_b([q['cand_f'] for q in ok])
  268. out['inharmonicity_B'] = {'ref': br[1] if br else None, 'cand': bc[1] if bc else None}
  269. # spectral envelope over time
  270. edges = time_edges(secs)
  271. gr, gc = ma.band_energy_grid(r, sr, edges), ma.band_energy_grid(c, sr, edges)
  272. st = spectime(gr, gc, lev)
  273. st_old = spectime(gr, gc, lev, rule='190ni')
  274. miss['spectime'] = st['miss']
  275. if st['db'] is not None:
  276. out['spectime_db'] = st['db']
  277. out['spectime_190ni'] = {'db': st_old['db'], 'miss': round(st_old['miss'], 4)}
  278. # attack
  279. miss['attack'], out['attack'] = attack_part(r, c, sr)
  280. sub = {k2: round(10.0 * (1.0 - min(v, 1.0)), 2) for k2, v in miss.items()}
  281. tw = sum(WEIGHT.values())
  282. agg = np.sqrt(sum(WEIGHT[k2] * min(v, 1.0) ** 2 for k2, v in miss.items()) / tw)
  283. out['subscores'] = sub
  284. out['timbre_score'] = round(float(10.0 * (1.0 - agg)), 2)
  285. # (the same score with round 190ni's spectro-temporal rule, for comparison with its reports)
  286. m_old = dict(miss, spectime=out['spectime_190ni']['miss'])
  287. out['timbre_score_190ni'] = round(float(10.0 * (1.0 - np.sqrt(sum(WEIGHT[k2] * min(v, 1.0) ** 2 for k2, v in m_old.items()) / tw))), 2)
  288. if wave:
  289. out['wave'] = wave_metrics(r, c, sr)
  290. return out
  291. def wave_metrics(r, c, sr):
  292. """LYNX's waveform-side measures (scripts/flref_compare.py, scripts/fxparity.py), read-only, when present"""
  293. scripts = os.path.normpath(os.path.join(HERE, '..', '..', 'scripts'))
  294. try:
  295. sys.path.insert(0, scripts)
  296. import flref_compare as fc
  297. import fxparity
  298. except Exception:
  299. return None
  300. n = min(len(r), len(c))
  301. fa, la = np.stack([r[:n], r[:n]], 1), np.stack([c[:n], c[:n]], 1)
  302. w = {'rms_db': round(fc.db(fc.rms(la)) - fc.db(fc.rms(fa)), 2),
  303. 'esr_db': round(fc.db(fc.rms(la - fa)) - fc.db(fc.rms(fa)), 2),
  304. 'spec_db': round(float(fc.spec_distance(fa, la)), 2)}
  305. w2 = sr // 20
  306. n2 = n // w2
  307. if n2 >= 3:
  308. fw = np.sqrt(np.mean((r[:n2 * w2] ** 2).reshape(n2, -1), 1))
  309. lw = np.sqrt(np.mean((c[:n2 * w2] ** 2).reshape(n2, -1), 1))
  310. aud = fw > fw.max() * 0.01
  311. if aud.sum() >= 3:
  312. w['env_corr'] = round(float(np.corrcoef(20 * np.log10(fw[aud] + 1e-6), 20 * np.log10(lw[aud] + 1e-6))[0, 1]), 3)
  313. try:
  314. w['wave_score'] = fxparity.score(w)
  315. except Exception:
  316. pass
  317. return w
  318. def main():
  319. a = sys.argv[1:]
  320. if not a or a[0] in ('-h', '--help'):
  321. print(__doc__)
  322. return 0
  323. if a[0] == 'selftest':
  324. import unittest
  325. suite = unittest.defaultTestLoader.discover(HERE, pattern='test_timbre_score.py')
  326. return 0 if unittest.TextTestRunner(verbosity=1).run(suite).wasSuccessful() else 1
  327. if a[0] == 'pair':
  328. ref, sr = ma.read_wav(a[1])
  329. cand, sr2 = ma.read_wav(a[2])
  330. if sr2 != sr:
  331. raise SystemExit('sample rates differ: %d vs %d' % (sr, sr2))
  332. opt = lambda k, d: type(d)(a[a.index(k) + 1]) if k in a else d
  333. res = score_pair(ref, cand, sr, f0=opt('--f0', 0.0) or None, dur=opt('--dur', 8.0), partials=opt('--partials', 16))
  334. txt = json.dumps(res, indent=1)
  335. if '--json' in a:
  336. open(a[a.index('--json') + 1], 'w').write(txt)
  337. print(txt)
  338. return 0
  339. print(__doc__)
  340. return 2
  341. if __name__ == '__main__':
  342. sys.exit(main())