evaluate.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. #!/usr/bin/env python3
  2. """evaluate.py - LYNX Model's quality report (round 190ni): every recorded note against the engine's render of it.
  3. evaluate.py <physmodrender> <notes-root> <fit-dir> <out-dir> [--instruments a,b] [--sets held_out,extra,in_sample]
  4. [--tables DIR] [--keep-wavs]
  5. <fit-dir> holds calibrate.py's output: <instrument>.lpm / .fit.json (the shipped tables, fitted on every note) and
  6. <instrument>-holdout3.lpm / .fit.json (fitted without the held-out keys; with -holdout3f1 / -f2, every fold present,
  7. --folds N: the first N); --tables: where the shipped .lpm files are
  8. when the reports were written elsewhere (calibrate.py --report-dir). The model's sets per instrument:
  9. held_out the held-out keys' takes, rendered from the holdout table (keys it never saw: the interpolation)
  10. extra other takes of a key the table has (a second tine, a second hit; same key, a different take)
  11. in_sample every fitted take, rendered from the shipped table (the fit itself)
  12. and the references for the held-out notes (round 190nl; no render of the model's own sound is involved except ctl_key):
  13. sampler the bar to beat: the nearest key of the holdout table's recordings at the same layer, transposed by
  14. resampling to the held-out key and retuned to the take's own tuning as the model's render is (a tuned
  15. multisample playing between its samples)
  16. ctl_key control, must score low: the model at a shuffled key (another held-out note's key, else 5 semitones up)
  17. ctl_inst control, must score low: another instrument's recording at the nearest key, transposed to the held-out key
  18. (a sampler of the wrong instrument)
  19. Each render is the take's sounding key at its layer's velocity and the take's own tuning (cents of its main mode; the
  20. model itself plays in tune), the model's preset values otherwise; the recording is
  21. raised by the table's level offset so both sit at the same level. Scored with timbre_score.score_pair (and its wave
  22. metrics, side by side). Writes <out-dir>/evaluation.json and evaluation.md. Renders are deleted unless --keep-wavs.
  23. """
  24. import json
  25. import os
  26. import subprocess
  27. import sys
  28. import numpy as np
  29. HERE = os.path.dirname(os.path.abspath(__file__))
  30. sys.path.insert(0, HERE)
  31. import calibrate # noqa: E402
  32. import lpm # noqa: E402
  33. import modal_analysis as ma # noqa: E402
  34. import timbre_score as ts # noqa: E402
  35. CAP = {'tubularbells': 10.0, 'vibraphone': 8.0}
  36. def tuning_of(x, sr, key):
  37. """cents of the take's main mode (the strongest spectral peak within 70 cents of the key, first second) re equal
  38. temperament, 0 if none. (Round 190nl: by the peak's magnitude, not a fitted decay: a vibraphone's fundamental rings
  39. for ~20 s, its decay cannot be fitted on a short segment, and the old rule then took a -50 dB leakage line 50 cents
  40. off as the main mode, so every vibraphone render was detuned by up to 53 cents.)"""
  41. f = calibrate.hz(key)
  42. near = [p for p in ma.pick_peaks(x[:int(1.5 * sr)], sr, 0.85 * f, None, 24, 12.0) if abs(calibrate.cents(p[0], f)) < 70]
  43. return float(calibrate.cents(max(near, key=lambda p: p[1])[0], f)) if near else 0.0
  44. def render_all(exe, jobs, out_dir, rate):
  45. lst = os.path.join(out_dir, 'notes-%d.txt' % rate)
  46. with open(lst, 'w') as f:
  47. for j in jobs:
  48. f.write('%s %s %d %.4f %.3f cents=%.2f\n' % (j['wav'], j['table'], j['key'], j['velocity'], j['seconds'], j['cents']))
  49. r = subprocess.run([exe, 'notes', lst, '--rate', str(rate)], capture_output=True, text=True)
  50. if r.returncode != 0:
  51. raise SystemExit('physmodrender failed: %s %s' % (r.stdout, r.stderr))
  52. os.remove(lst)
  53. def score_job(j, ref_root, keep):
  54. x, sr = ma.read_wav(os.path.join(ref_root, j['set'], j['file']))
  55. on = ma.onset(x, sr)
  56. x = x[max(0, on - int(0.001 * sr)):][:int(j['seconds'] * sr)] * 10 ** (j['offset_db'] / 20.0)
  57. y, sr2 = ma.read_wav(j['wav'])
  58. if not keep:
  59. os.remove(j['wav'])
  60. res = ts.score_pair(x, y, sr, f0=calibrate.hz(j['ref_key']) if j['instrument'] != 'tubularbells' else None, dur=j['seconds'])
  61. return {'file': j['file'], 'key': j['ref_key'], 'rendered_key': j['key'], 'velocity': j['velocity'], 'timbre_score': res['timbre_score'], 'timbre_score_190ni': res['timbre_score_190ni'],
  62. 'subscores': {k: float(v) for k, v in res['subscores'].items()}, 'partials_matched': res['partials_matched'],
  63. 'pitch_cents': res['pitch_cents'], 'level_db': res['level_db'], 'spectime_db': res.get('spectime_db'),
  64. 'attack': res['attack'], 'decay_log2_median': res['decay_log2_median'],
  65. 'wave': {k: (float(v) if v is not None else None) for k, v in (res['wave'] or {}).items()}}
  66. def resample(y, semitones):
  67. """y played faster by 2^(semitones / 12) (linear interpolation): a sampler's transposition"""
  68. ratio = 2 ** (semitones / 12.0)
  69. idx = np.arange(0, len(y) - 1, ratio)
  70. i = idx.astype(int)
  71. fr = idx - i
  72. return y[i] * (1 - fr) + y[i + 1] * fr
  73. def score_arrays(inst, name, file, key, velocity, x, y, sr, seconds):
  74. res = ts.score_pair(x[:int(seconds * sr)], y[:int(seconds * sr)], sr, f0=calibrate.hz(key) if inst != 'tubularbells' else None,
  75. dur=seconds)
  76. return {'file': file, 'key': key, 'velocity': velocity, 'from': name, 'timbre_score': res['timbre_score'], 'timbre_score_190ni': res['timbre_score_190ni'],
  77. 'subscores': {k: float(v) for k, v in res['subscores'].items()}, 'partials_matched': res['partials_matched'],
  78. 'pitch_cents': res['pitch_cents'], 'level_db': res['level_db'], 'spectime_db': res.get('spectime_db'),
  79. 'attack': res['attack'], 'decay_log2_median': res['decay_log2_median'],
  80. 'wave': {k: (float(v) if v is not None else None) for k, v in (res['wave'] or {}).items()}}
  81. def load_note(root, set_name, file):
  82. x, sr = ma.read_wav(os.path.join(root, set_name, file))
  83. return x[ma.onset(x, sr):], sr
  84. def reference_sets(inst, root, hold, want):
  85. """the sampler baseline and the wrong-instrument control for the held-out takes (recordings only)"""
  86. cfg = calibrate.INSTRUMENTS[inst]
  87. used = [(n['key'], n['layer'], n['file']) for n in hold['notes']]
  88. out = {'sampler': [], 'ctl_inst': []}
  89. for t in hold['held_out_takes']:
  90. x, sr = load_note(root, cfg['set'], t['file'])
  91. secs = min(len(x) / sr - 0.05, CAP.get(inst, 6.0))
  92. vel = t['layer'] # (the layer's name: no velocity is rendered here)
  93. if 'sampler' in want:
  94. k, _, f = min([u for u in used if u[1] == t['layer']], key=lambda u: (abs(u[0] - t['key']), u[0]))
  95. y, _ = load_note(root, cfg['set'], f)
  96. # (a tuned multisample: the neighbour retuned to the take's own tuning, as the model's render is)
  97. tune = (tuning_of(x, sr, t['key']) - tuning_of(y, sr, k)) / 100.0
  98. out['sampler'].append(score_arrays(inst, f, t['file'], t['key'], vel, x, resample(y, t['key'] - k + tune), sr, secs))
  99. if 'ctl_inst' in want:
  100. # the other instruments' recordings (their fitted takes), the nearest key; ties: the instrument order
  101. best = None
  102. for other, ocfg in calibrate.INSTRUMENTS.items():
  103. if other == inst:
  104. continue
  105. for n in json.load(open(os.path.join(os.path.dirname(hold['_path']), other + '.fit.json')))['notes']:
  106. d = abs(n['key'] - t['key'])
  107. if best is None or d < best[0]:
  108. best = (d, ocfg['set'], n['file'], n['key'])
  109. _, oset, f, k = best
  110. y, sr2 = load_note(root, oset, f)
  111. # (transposed to the key and brought to the reference's rate in one resampling)
  112. y = resample(y, t['key'] - k + 12.0 * np.log2(sr2 / float(sr)))
  113. out['ctl_inst'].append(score_arrays(inst, oset + '/' + f, t['file'], t['key'], vel, x, y, sr, secs))
  114. return out
  115. def summary(rows):
  116. if not rows:
  117. return None
  118. s = np.array([r['timbre_score'] for r in rows])
  119. w = [r['wave'].get('wave_score') for r in rows if r['wave'].get('wave_score') is not None]
  120. subs = {k: round(float(np.median([r['subscores'][k] for r in rows])), 2) for k in rows[0]['subscores']}
  121. s0 = np.array([r.get('timbre_score_190ni', np.nan) for r in rows])
  122. return {'notes': len(rows), 'timbre_median': round(float(np.median(s)), 2), 'timbre_190ni_median': round(float(np.median(s0)), 2),
  123. 'timbre_190ni_mean': round(float(np.mean(s0)), 2), 'timbre_mean': round(float(s.mean()), 2),
  124. 'timbre_min': round(float(s.min()), 2), 'wave_median': float(np.median(w)) if w else None, 'subscores_median': subs,
  125. 'spec_db_median': round(float(np.median([r['wave']['spec_db'] for r in rows if r['wave'].get('spec_db') is not None] or [np.nan])), 2)}
  126. def main():
  127. a = sys.argv[1:]
  128. if len(a) < 4:
  129. print(__doc__)
  130. return 2
  131. exe, root, fit, out = a[:4]
  132. tables = a[a.index('--tables') + 1] if '--tables' in a else fit # (the shipped .lpm files: resources/physmod)
  133. keep = '--keep-wavs' in a
  134. insts = a[a.index('--instruments') + 1].split(',') if '--instruments' in a else list(calibrate.INSTRUMENTS)
  135. os.makedirs(out, exist_ok=True)
  136. report = {}
  137. for inst in insts:
  138. cfg = calibrate.INSTRUMENTS[inst]
  139. full = json.load(open(os.path.join(fit, inst + '.fit.json')))
  140. offset = lpm.read(open(os.path.join(tables, inst + '.lpm'), 'rb').read())['gainOffsetDb']
  141. # the holdout tables: <inst>-holdout3 and, when fitted, its other folds <inst>-holdout3f1, -f2 (round 190nl:
  142. # together they hold every inner recorded key out once)
  143. nl = len(cfg['layers'])
  144. vel = lambda layer: 0.8 if nl == 1 else (cfg['layers'].index(layer) + 1) / nl
  145. sets = {
  146. 'held_out': [],
  147. 'extra': [(t['file'], t['key'], vel(t['layer']), os.path.join(tables, inst + '.lpm'), offset) for t in full['extra_takes']],
  148. 'in_sample': [(n['file'], n['key'], n['velocity'], os.path.join(tables, inst + '.lpm'), offset) for n in full['notes']],
  149. 'ctl_key': [],
  150. }
  151. report[inst] = {}
  152. want = a[a.index('--sets') + 1].split(',') if '--sets' in a else list(sets) + ['sampler', 'ctl_inst']
  153. refrows = {}
  154. folds = [t for t in ('holdout3', 'holdout3f1', 'holdout3f2') if os.path.exists(os.path.join(fit, '%s-%s.fit.json' % (inst, t)))]
  155. if '--folds' in a:
  156. folds = folds[:int(a[a.index('--folds') + 1])]
  157. for tag in folds:
  158. hp = os.path.join(fit, '%s-%s.fit.json' % (inst, tag))
  159. tp = os.path.join(fit, '%s-%s.lpm' % (inst, tag))
  160. hold = json.load(open(hp))
  161. hold['_path'] = hp
  162. offset_h = lpm.read(open(tp, 'rb').read())['gainOffsetDb']
  163. sets['held_out'] += [(t['file'], t['key'], vel(t['layer']), tp, offset_h) for t in hold['held_out_takes']]
  164. hk = [t['key'] for t in hold['held_out_takes']]
  165. shuffled = [next((k for k in hk[i + 1:] + hk[:i] if k != hk[i]), hk[i] + 5) for i in range(len(hk))]
  166. sets['ctl_key'] += [(t['file'], k, vel(t['layer']), tp, offset_h, t['key']) for t, k in zip(hold['held_out_takes'], shuffled)]
  167. for name, rows in reference_sets(inst, root, hold, want).items():
  168. refrows.setdefault(name, []).extend(rows)
  169. for name, rows in refrows.items():
  170. if name in want:
  171. for r in rows:
  172. print(' %-13s %-9s %-46s timbre %5.2f' % (inst, name, r['file'][:46], r['timbre_score']), flush=True)
  173. report[inst][name] = {'summary': summary(rows), 'notes': rows}
  174. for name, takes in sets.items():
  175. if name not in want:
  176. report[inst][name] = {'summary': None, 'notes': []}
  177. continue
  178. by_rate = {}
  179. for i, (f, key, v, table, off, *rk) in enumerate(takes):
  180. x, sr = ma.read_wav(os.path.join(root, cfg['set'], f))
  181. secs = min(len(x) / sr - 0.05, CAP.get(inst, 6.0))
  182. # the take's own tuning (the model plays in tune; the score compares timbre, not the take's tuning)
  183. # (round 190nl: the bells too - their strike tone, the strongest peak near the key, as calibrate.py takes it;
  184. # 190ni rendered them in tune against takes 4-14 cents sharp, while the sampler kept the takes' tuning)
  185. cents = tuning_of(x[ma.onset(x, sr):], sr, key) if name != 'ctl_key' else 0.0
  186. by_rate.setdefault(sr, []).append({'instrument': inst, 'set': cfg['set'], 'file': f, 'key': key, 'velocity': v,
  187. 'table': table, 'offset_db': off, 'seconds': secs, 'cents': cents, 'ref_key': rk[0] if rk else key,
  188. 'wav': os.path.join(out, '%s-%s-%03d.wav' % (inst, name, i))})
  189. rows = []
  190. for sr, jobs in by_rate.items():
  191. render_all(exe, jobs, out, sr)
  192. for j in jobs:
  193. rows.append(score_job(j, root, keep))
  194. print(' %-13s %-9s %-46s timbre %5.2f wave %s' % (inst, name, j['file'][:46], rows[-1]['timbre_score'],
  195. rows[-1]['wave'].get('wave_score')), flush=True)
  196. report[inst][name] = {'summary': summary(rows), 'notes': rows}
  197. s = report[inst]
  198. med = lambda name: s.get(name, {}).get('summary') and s[name]['summary']['timbre_median']
  199. print('%s: held-out %s | sampler %s | extra %s | in-sample %s | ctl_key %s | ctl_inst %s' % (
  200. inst, med('held_out'), med('sampler'), med('extra'), med('in_sample'), med('ctl_key'), med('ctl_inst')), flush=True)
  201. json.dump(report, open(os.path.join(out, 'evaluation.json'), 'w'), indent=1)
  202. lines = ['# LYNX Model: timbre scores against the CC0 recordings', '',
  203. 'Timbre score 0-10 (tools/physmod/timbre_score.py; phase-blind, per note), median (mean) per set; the wave score '
  204. '(scripts/fxparity.py, waveform null) beside it. held-out = keys the table never saw (holdout table); sampler = '
  205. 'the nearest recorded key transposed (the bar to beat); ctl_key / ctl_inst = controls (wrong key / wrong '
  206. 'instrument), must be low. Score rule 190nl (spectro-temporal part against the take\'s background); the 190ni '
  207. 'rule beside it.', '',
  208. '| Instrument | held-out (n) | held-out min | sampler | extra takes (n) | in-sample (n) | ctl_key | ctl_inst | held-out, 190ni rule | sampler, 190ni rule | wave score, held-out | spec_db held-out |',
  209. '|---|---|---|---|---|---|---|---|---|---|---|---|']
  210. for inst, s in report.items():
  211. z = lambda name: s.get(name, {}).get('summary')
  212. f = lambda q: ('%.2f (%.2f, %d)' % (q['timbre_median'], q['timbre_mean'], q['notes'])) if q else '-'
  213. h = z('held_out')
  214. g = lambda q: ('%.2f (%.2f)' % (q['timbre_190ni_median'], q['timbre_190ni_mean'])) if q else '-'
  215. lines.append('| %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s | %s |' % (
  216. inst, f(h), h['timbre_min'] if h else '-', f(z('sampler')), f(z('extra')), f(z('in_sample')), f(z('ctl_key')), f(z('ctl_inst')),
  217. g(h), g(z('sampler')), h['wave_median'] if h else '-', h['spec_db_median'] if h else '-'))
  218. for name in ('held_out', 'sampler', 'in_sample'):
  219. lines += ['', 'Sub-scores (median, %s):' % name, '']
  220. for inst, s in report.items():
  221. if s.get(name, {}).get('summary'):
  222. lines.append('- %s: %s' % (inst, ', '.join('%s %.1f' % kv for kv in s[name]['summary']['subscores_median'].items())))
  223. open(os.path.join(out, 'evaluation.md'), 'w').write('\n'.join(lines) + '\n')
  224. print('\n'.join(lines))
  225. return 0
  226. if __name__ == '__main__':
  227. sys.exit(main())