refine.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. #!/usr/bin/env python3
  2. """refine.py - LYNX Model's strike refinement through the real engine (round 190nl).
  3. calibrate.py fits the strike (the contact time constant, the resonator build-up, the strike noise's level, centre, Q
  4. and decay) through a closed-form emulation of the engine's first 150 ms. That emulation leaves the contact at the
  5. ends of its range for many notes (0.03 or 2 ms in neighbouring keys), so a key between two recorded ones interpolated a
  6. strike neither had: the held-out notes' attacks rose 4x too fast. This tool refines those parameters by rendering
  7. candidates with the engine itself (tools/physmodrender, one single-anchor table per candidate) and scoring them with
  8. the timbre score's own attack and spectro-temporal parts (timbre_score.StrikeLoss), coordinate by coordinate over
  9. absolute grids, with a smoothness term that pulls each anchor towards its layer's neighbours (so the parameters stay
  10. interpolable between recorded keys).
  11. refine.py <physmodrender> <notes-root> <fit.json> <table.lpm> <out.lpm> [--noise-order 1|2] [--sweeps N]
  12. [--smooth L] [--report OUT.json] [--work DIR] [--inc-dir DIR] [--level]
  13. --level (round 190nm): then each anchor's level matched through the engine (its first 2 s against its recording,
  14. as the timbre score's level part measures them)
  15. --inc-dir: also write <instrument>.inc there (src/core/physmod/tables/, the table LYNX compiles in)
  16. Only parameters change; modes stay as fitted. The output table keeps the input's header (position mapping, level
  17. offset, provenance hash), with the noise order set.
  18. """
  19. import json
  20. import os
  21. import shutil
  22. import subprocess
  23. import sys
  24. import numpy as np
  25. HERE = os.path.dirname(os.path.abspath(__file__))
  26. sys.path.insert(0, HERE)
  27. import calibrate # noqa: E402
  28. import lpm # noqa: E402
  29. import modal_analysis as ma # noqa: E402
  30. import timbre_score as ts # noqa: E402
  31. # parameter: (grid, kind, unit of the smoothness term)
  32. GRIDS = {
  33. 'contact': (list(np.geomspace(0.00003, 0.004, 10)), 'log', 1.0),
  34. 'riseMs': ([0.0, 2.0, 4.0, 8.0, 16.0, 32.0], 'lin', 8.0),
  35. 'noiseDb': ([-60.0] + list(np.arange(-40.0, 21.0, 5.0)), 'lin', 6.0),
  36. 'noiseHz': (None, 'log', 1.0), # (per sample rate: 150 Hz ... 0.4 fs)
  37. 'noiseQ': ([0.5, 0.7, 1.0, 1.4, 2.0, 3.0, 4.5], 'log', 1.0),
  38. 'noiseMs': ([1.5, 3.0, 6.0, 12.0, 25.0, 50.0, 100.0], 'log', 1.0),
  39. }
  40. ORDER = ['contact', 'noiseDb', 'noiseHz', 'noiseMs', 'noiseQ', 'riseMs']
  41. SECONDS = 1.0
  42. def pval(name, v):
  43. kind, unit = GRIDS[name][1], GRIDS[name][2]
  44. return (np.log2(max(v, 1e-9)) if kind == 'log' else v) / unit
  45. def render(exe, work, jobs, sr):
  46. """jobs: (anchor, header, tuning cents) -> list of float arrays"""
  47. lst = os.path.join(work, 'list.txt')
  48. lines = []
  49. for i, (a, head, cents) in enumerate(jobs):
  50. tp = os.path.join(work, 'c%05d.lpm' % i)
  51. lpm.write(tp, head['model'], head['beam'], head['posRef'], head['posU0'], head['posU1'], head['gainOffsetDb'], [a], b'',
  52. head['noiseOrder'], head.get('onset', 0), head.get('fade', 0))
  53. lines.append('%s %s %d %.4f %.3f cents=%.2f' % (os.path.join(work, 'c%05d.wav' % i), tp, int(round(a['key'])), a['velocity'],
  54. SECONDS, cents))
  55. open(lst, 'w').write('\n'.join(lines) + '\n')
  56. r = subprocess.run([exe, 'notes', lst, '--rate', str(sr)], capture_output=True, text=True)
  57. if r.returncode != 0:
  58. raise SystemExit('physmodrender failed: %s %s' % (r.stdout[-400:], r.stderr[-400:]))
  59. out = []
  60. for i in range(len(jobs)):
  61. y, _ = ma.read_wav(os.path.join(work, 'c%05d.wav' % i))
  62. out.append(y)
  63. os.remove(os.path.join(work, 'c%05d.wav' % i))
  64. os.remove(os.path.join(work, 'c%05d.lpm' % i))
  65. os.remove(lst)
  66. return out
  67. def neighbours(anchors, i):
  68. """the same layer's nearest anchors below and above"""
  69. a = anchors[i]
  70. same = [j for j, b in enumerate(anchors) if j != i and abs(b['velocity'] - a['velocity']) < 1e-4]
  71. lo = [j for j in same if anchors[j]['key'] < a['key']]
  72. hi = [j for j in same if anchors[j]['key'] > a['key']]
  73. return ([max(lo, key=lambda j: anchors[j]['key'])] if lo else []) + ([min(hi, key=lambda j: anchors[j]['key'])] if hi else [])
  74. def main():
  75. a = sys.argv[1:]
  76. if len(a) < 5:
  77. print(__doc__)
  78. return 2
  79. exe, root, fitp, tin, tout = a[:5]
  80. opt = lambda k, d: type(d)(a[a.index(k) + 1]) if k in a else d
  81. order = opt('--noise-order', 2)
  82. sweeps = opt('--sweeps', 2)
  83. smooth = opt('--smooth', 0.01)
  84. work = opt('--work', os.path.join(os.path.dirname(os.path.abspath(tout)), 'refine-work-%d' % os.getpid()))
  85. os.makedirs(work, exist_ok=True)
  86. fit = json.load(open(fitp))
  87. head = lpm.read(open(tin, 'rb').read())
  88. head['noiseOrder'] = order
  89. inst = fit['instrument']
  90. cfg = calibrate.INSTRUMENTS[inst]
  91. anchors = [dict(x) for x in head['anchors']]
  92. for x in anchors:
  93. x['modes'] = [dict(m) for m in x['modes']]
  94. notes = {(float(n['key']), round(float(n['velocity']), 4)): n for n in fit['notes']}
  95. refs, sr = [], None
  96. for x in anchors:
  97. n = notes[(x['key'], round(x['velocity'], 4))]
  98. y, rate = ma.read_wav(os.path.join(root, cfg['set'], n['file']))
  99. sr = sr or rate
  100. y = y[ma.onset(y, rate):][:int(min(cfg['seconds'], 8.0) * rate)]
  101. refs.append((ts.StrikeLoss(y, rate), n.get('tuning_offset_cents', 0.0)))
  102. GRIDS['noiseHz'] = (list(np.geomspace(150.0, 0.4 * sr, 11)), 'log', 1.0)
  103. if head.get('onset', 0) in (1, 2):
  104. # (round 190nm: riseMs is the whole note's onset there - a 10-90 % rise of about 2.2 x rise (2.6 x for the
  105. # S-shaped onset 2, round 190nn) - finer steps)
  106. GRIDS['riseMs'] = ([0.0, 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0], 'lin', 1.0)
  107. def losses(cands):
  108. """cands: list of (anchor index, anchor dict) -> losses"""
  109. ys = render(exe, work, [(c, head, refs[i][1]) for i, c in cands], sr)
  110. return [refs[i][0].loss(y) for (i, _), y in zip(cands, ys)]
  111. start = losses(list(enumerate(anchors)))
  112. hist = []
  113. for sweep in range(sweeps):
  114. for name in ORDER:
  115. grid = GRIDS[name][0]
  116. prev = [x[name] for x in anchors]
  117. cands = []
  118. for i, x in enumerate(anchors):
  119. for v in grid:
  120. c = dict(x)
  121. c[name] = float(v)
  122. cands.append((i, c))
  123. ls = losses(cands)
  124. k = 0
  125. for i, x in enumerate(anchors):
  126. nb = [prev[j] for j in neighbours(anchors, i)]
  127. best = None
  128. for v in grid:
  129. pen = smooth * np.mean([(pval(name, v) - pval(name, w)) ** 2 for w in nb]) if nb else 0.0
  130. tot = ls[k] + pen
  131. if best is None or tot < best[0]:
  132. best = (tot, v, ls[k])
  133. k += 1
  134. x[name] = float(best[1])
  135. hist.append({'sweep': sweep, 'param': name})
  136. print(' %s sweep %d done' % (inst, sweep + 1), flush=True)
  137. if '--level' in a:
  138. # (round 190nm) each anchor's level matched through the engine: the first 2 s of its render against its recording
  139. # raised by the table's level offset, as the timbre score's level part measures them (a fitted main mode's
  140. # level misses a two-stage decay's loud start, or a fast mode's)
  141. global SECONDS
  142. keep, SECONDS = SECONDS, 2.5
  143. ys = render(exe, work, [(x, head, refs[i][1]) for i, x in enumerate(anchors)], sr)
  144. SECONDS = keep
  145. g = 10 ** (head['gainOffsetDb'] / 20.0)
  146. for i, (x, y) in enumerate(zip(anchors, ys)):
  147. r = refs[i][0].r * g
  148. c = ts.align(r, ts.prepare(np.asarray(y, np.float64), sr, len(r) / sr), sr)
  149. n = min(len(r), len(c), int(2 * sr))
  150. lev = 10 * np.log10((np.mean(c[:n] ** 2) + 1e-30) / (np.mean(r[:n] ** 2) + 1e-30))
  151. x['gainDb'] = float(x['gainDb'] - np.clip(lev, -24.0, 24.0))
  152. end = losses(list(enumerate(anchors)))
  153. lpm.write(tout, head['model'], head['beam'], head['posRef'], head['posU0'], head['posU1'], head['gainOffsetDb'], anchors,
  154. b'', order, head.get('onset', 0), head.get('fade', 0))
  155. # (the provenance hash: lpm.write hashed b''; keep the input's)
  156. data = bytearray(open(tout, 'rb').read())
  157. data[32:40] = bytes.fromhex(head['provenance_sha256_8'])
  158. open(tout, 'wb').write(bytes(data))
  159. rep = {'instrument': inst, 'table_in': tin, 'table_out': tout, 'noise_order': order, 'sweeps': sweeps, 'smooth': smooth,
  160. 'loss_start_mean': round(float(np.mean(start)), 4), 'loss_end_mean': round(float(np.mean(end)), 4),
  161. 'anchors': [{'key': x['key'], 'velocity': x['velocity'], 'loss_start': round(s0, 4), 'loss_end': round(s1, 4),
  162. **{k: x[k] for k in ORDER}} for x, s0, s1 in zip(anchors, start, end)]}
  163. if '--inc-dir' in a:
  164. calibrate.write_inc(inst, bytes(data), opt('--inc-dir', ''))
  165. if '--report' in a:
  166. json.dump(rep, open(opt('--report', ''), 'w'), indent=1)
  167. print('%s: strike loss %.4f -> %.4f (%d anchors)' % (inst, rep['loss_start_mean'], rep['loss_end_mean'], len(anchors)), flush=True)
  168. shutil.rmtree(work, ignore_errors=True)
  169. return 0
  170. if __name__ == '__main__':
  171. sys.exit(main())