keyfit.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. #!/usr/bin/env python3
  2. """keyfit.py - LYNX Model's mode tables across keys (round 190nl): mode families and smooth fits against key.
  3. A table holds one anchor per recorded key and velocity layer (calibrate.py). Between anchors the engine blends the two
  4. neighbours (src/core/physmod/LynxModel.cpp blend()); before round 190nl it paired modes by frequency ratio within 4 %,
  5. so a mode whose ratio drifts across a 5-12 semitone gap (a glockenspiel's second mode moves 3.04 -> 2.88 over an
  6. octave) fell apart into two half-level modes at the wrong frequencies. This module:
  7. families(anchors) tags each mode of each layer with a family id (u8, 1-254; 0 = none; 255 = a line at
  8. its own pitch, left alone): the same physical mode in neighbouring anchors, matched by
  9. log ratio within a tolerance that grows with the key gap plus their level difference,
  10. lowest cost first, one to one. The engine pairs modes by family when both carry one
  11. (the 4 % rule stays for untagged modes and tables).
  12. densify(anchors, ...) adds synthetic anchors inside gaps wider than `max_gap` semitones: each family's log
  13. ratio, level and log T60 (and each anchor scalar: level, contact, noise, build-up) at the
  14. new key from a smooth fit against key (Gaussian-weighted local linear regression over the
  15. family's anchors, width `sigma` semitones) plus the two neighbours' residuals, linearly
  16. blended and shrunk towards the fit in the middle of the gap by `shrink` (1 - shrink * 4 t (1 - t)).
  17. At a recorded key nothing changes; the recorded anchors stay exactly as fitted.
  18. choose(anchors, ...) sigma and shrink per quantity by leave-one-out over the table's own anchors (each inner
  19. anchor predicted from the others), so no held-out note is involved in the choice.
  20. densify and choose are lab tools: round 190nl tried synthetic anchors (every semitone, linear and LOO-chosen fits) on the
  21. three held-out folds and found no gain over the engine's family-aware blend of the recorded anchors, so the shipped
  22. tables hold recorded anchors only (calibrate.py uses families()).
  23. Only parameters: a synthetic anchor is a prediction from fitted parameters, never audio.
  24. """
  25. import numpy as np
  26. ABSOLUTE = 255 # (lpm.ABSOLUTE: a line at its own pitch, never part of a family)
  27. SCALARS = [('gainDb', 'lin'), ('contact', 'log'), ('riseMs', 'lin'), ('noiseDb', 'lin'), ('noiseHz', 'log'), ('noiseQ', 'log'),
  28. ('noiseMs', 'log')]
  29. QUANT = ('ratio', 'ampDb', 't60')
  30. def _layers(anchors):
  31. out = {}
  32. for a in anchors:
  33. out.setdefault(round(a['velocity'], 4), []).append(a)
  34. for v in out:
  35. out[v].sort(key=lambda a: a['key'])
  36. return out
  37. def families(anchors, tol=0.03, per_semitone=0.003, tol_cap=0.08, level_db=24.0):
  38. """sets m['fam'] (1-255) on every mode; modes of one layer's neighbouring anchors that are the same mode share it.
  39. A pair's cost is its log-ratio distance re the tolerance plus its level difference re `level_db` (a strong mode
  40. continues as a strong mode, not as a weak line that happens to sit closer), lowest cost first, one to one.
  41. (round 190nm: the main modes - ratio 1, the key's tuned mode - always pair with each other; and the working ids
  42. start at 1000, so a family can no longer take the id 255 of the absolute lines before the final ids are given: with
  43. more than 254 families a table had regular modes marked absolute)"""
  44. absolute = {id(m) for a in anchors for m in a['modes'] if m.get('fam') == ABSOLUTE}
  45. is_main = lambda m: abs(np.log(m['ratio'])) < 1e-3
  46. next_id = 1000
  47. for layer in _layers(anchors).values():
  48. prev = None
  49. for a in layer:
  50. for m in a['modes']:
  51. m['fam'] = 0
  52. if prev is not None:
  53. lim = min(tol + per_semitone * abs(a['key'] - prev['key']), tol_cap)
  54. pairs = []
  55. for i, p in enumerate(prev['modes']):
  56. if id(p) in absolute:
  57. continue
  58. for j, q in enumerate(a['modes']):
  59. if id(q) in absolute:
  60. continue
  61. if is_main(p) and is_main(q):
  62. pairs.append((-1.0, i, j))
  63. continue
  64. d = abs(np.log(q['ratio'] / p['ratio']))
  65. if d < lim:
  66. cost = d / lim + abs(q['ampDb'] - p['ampDb']) / level_db
  67. if p.get('part') or q.get('part'):
  68. # (round 190nm: the parts of a split mode - a two-stage decay, a beating pair - continue
  69. # as the same part: like decay, like role)
  70. cost += abs(np.log2(q['t60'] / p['t60'])) / 3.0 + (0.5 if p.get('part', 0) != q.get('part', 0) else 0.0)
  71. pairs.append((cost, i, j))
  72. pairs.sort()
  73. ui, uj = set(), set()
  74. for d, i, j in pairs:
  75. if i in ui or j in uj:
  76. continue
  77. ui.add(i)
  78. uj.add(j)
  79. a['modes'][j]['fam'] = prev['modes'][i]['fam']
  80. for m in a['modes']:
  81. if m['fam'] == 0 and id(m) not in absolute:
  82. m['fam'] = next_id
  83. next_id += 1
  84. prev = a
  85. # ids are u8: families seen in a single anchor only need none (the engine then uses the 4 % rule); the others get
  86. # ids 1..254, each the smallest id no other family uses at its keys or the neighbouring recorded keys, in ANY layer
  87. # (the engine compares neighbouring keys, and a note between two layers carries modes of both: two families that can
  88. # meet never share an id; further away an id may repeat); absolute lines get 255
  89. count = {}
  90. for a in anchors:
  91. for m in a['modes']:
  92. if id(m) not in absolute:
  93. count[m['fam']] = count.get(m['fam'], 0) + 1
  94. keys = sorted(set(a['key'] for a in anchors))
  95. kidx = {k: i for i, k in enumerate(keys)}
  96. where = {}
  97. for a in anchors:
  98. for m in a['modes']:
  99. if id(m) not in absolute and count[m['fam']] >= 2:
  100. where.setdefault(m['fam'], set()).add(kidx[a['key']])
  101. taken = [dict() for _ in keys] # per recorded key: id -> family
  102. remap = {}
  103. for f in sorted(where, key=lambda f: (min(where[f]), f)):
  104. near = set()
  105. for j in where[f]:
  106. for k in (j - 1, j, j + 1):
  107. if 0 <= k < len(keys):
  108. near |= set(taken[k])
  109. new_id = next((i for i in range(1, 255) if i not in near), None)
  110. if new_id is None:
  111. continue # (no id left: the family stays untagged)
  112. remap[f] = new_id
  113. for j in where[f]:
  114. taken[j][new_id] = f
  115. for a in anchors:
  116. for m in a['modes']:
  117. m['fam'] = ABSOLUTE if id(m) in absolute else remap.get(m['fam'], 0)
  118. return anchors
  119. def _val(m, q):
  120. return np.log(m[q]) if q in ('ratio', 't60') else m[q]
  121. def _scal(a, name, kind):
  122. v = a.get(name, 0.0)
  123. return np.log(max(v, 1e-9)) if kind == 'log' else v
  124. def _trend(keys, vals, k, sigma):
  125. """Gaussian-weighted local linear regression of vals against keys, evaluated at k"""
  126. keys, vals = np.asarray(keys, float), np.asarray(vals, float)
  127. if len(keys) == 1:
  128. return float(vals[0])
  129. w = np.ones(len(keys)) if sigma is None else np.exp(-0.5 * ((keys - k) / sigma) ** 2) + 1e-9
  130. A = np.vstack([np.ones(len(keys)), keys - k]).T * np.sqrt(w)[:, None]
  131. sol, *_ = np.linalg.lstsq(A, vals * np.sqrt(w), rcond=None)
  132. return float(sol[0])
  133. def _predict(points, k, k0, v0, k1, v1, sigma, shrink):
  134. """value at k (k0 < k < k1) from the fit over `points` (key, value) plus the neighbours' residuals"""
  135. keys = [p[0] for p in points]
  136. vals = [p[1] for p in points]
  137. t = (k - k0) / (k1 - k0)
  138. f = _trend(keys, vals, k, sigma)
  139. r0 = v0 - _trend(keys, vals, k0, sigma)
  140. r1 = v1 - _trend(keys, vals, k1, sigma)
  141. return f + ((1 - t) * r0 + t * r1) * (1.0 - shrink * 4.0 * t * (1.0 - t))
  142. def _family_points(layer, fam, q):
  143. pts = []
  144. for a in layer:
  145. for m in a['modes']:
  146. if m.get('fam') == fam:
  147. pts.append((a['key'], _val(m, q)))
  148. break
  149. return pts
  150. def synth_anchor(layer, j, k, params, max_modes, absolute=False):
  151. """an anchor at key k between layer[j] and layer[j + 1]. absolute: a mode only one side has keeps its frequency
  152. in Hz rather than its ratio to the key (lines of the instrument's other bars or tines ringing along sit at their own
  153. pitch whatever key is struck)"""
  154. a, b = layer[j], layer[j + 1]
  155. t = (k - a['key']) / (b['key'] - a['key'])
  156. move = lambda r, k0: r * 2 ** ((k0 - k) / 12.0) if absolute else r
  157. new = {'key': float(k), 'velocity': a['velocity'], 'synthetic': True}
  158. for name, kind in SCALARS:
  159. pts = [(x['key'], _scal(x, name, kind)) for x in layer]
  160. sg, sh = params.get(name, (None, 0.0))
  161. v = _predict(pts, k, a['key'], _scal(a, name, kind), b['key'], _scal(b, name, kind), sg, sh)
  162. new[name] = float(np.exp(v)) if kind == 'log' else float(v)
  163. new['riseMs'] = max(new['riseMs'], 0.0)
  164. modes = []
  165. bf = {m['fam']: m for m in b['modes'] if m.get('fam')}
  166. used = set()
  167. for m in a['modes']:
  168. f = m.get('fam')
  169. if f and f in bf:
  170. used.add(f)
  171. q = {'shape': m['shape'] or bf[f]['shape'], 'fam': f}
  172. for name in QUANT:
  173. sg, sh = params.get(name, (None, 0.0))
  174. v = _predict(_family_points(layer, f, name), k, a['key'], _val(m, name), b['key'], _val(bf[f], name), sg, sh)
  175. q[name] = float(np.exp(v)) if name in ('ratio', 't60') else float(v)
  176. modes.append(q)
  177. else: # (only on this side: it fades out across the gap, as the engine's blend does)
  178. modes.append({'ratio': move(m['ratio'], a['key']), 'ampDb': m['ampDb'] + 20 * np.log10(max(1 - t, 1e-3)), 't60': m['t60'],
  179. 'shape': 0 if absolute else m['shape'], 'fam': f or 0})
  180. for m in b['modes']:
  181. f = m.get('fam')
  182. if not (f and f in used):
  183. modes.append({'ratio': move(m['ratio'], b['key']), 'ampDb': m['ampDb'] + 20 * np.log10(max(t, 1e-3)), 't60': m['t60'],
  184. 'shape': 0 if absolute else m['shape'], 'fam': f or 0})
  185. modes.sort(key=lambda m: -(10 ** (m['ampDb'] / 10)) * min(m['t60'], 3.0))
  186. new['modes'] = sorted(modes[:max_modes], key=lambda m: m['ratio'])
  187. # (the main mode keeps ratio 1 exactly: the note's pitch)
  188. main = min(new['modes'], key=lambda m: abs(np.log(m['ratio'])))
  189. if abs(np.log(main['ratio'])) < 0.01:
  190. main['ratio'] = 1.0
  191. main['ampDb'] = 0.0
  192. return new
  193. def densify(anchors, max_gap=2.0, step=None, params=None, max_modes=28, absolute=False):
  194. """the anchors plus synthetic ones inside each layer's gaps wider than max_gap semitones (at every `step` semitones,
  195. default: as evenly as possible with spacing <= max_gap)"""
  196. params = params or {}
  197. out = list(anchors)
  198. for layer in _layers(anchors).values():
  199. for j in range(len(layer) - 1):
  200. k0, k1 = layer[j]['key'], layer[j + 1]['key']
  201. gap = k1 - k0
  202. if gap <= max_gap:
  203. continue
  204. n = int(np.ceil(gap / (step or max_gap))) - 1
  205. for i in range(1, n + 1):
  206. k = k0 + gap * i / (n + 1)
  207. k = round(k * 2) / 2.0 # (half semitones: a held-out key lands on an anchor or between two)
  208. if k <= k0 or k >= k1:
  209. continue
  210. out.append(synth_anchor(layer, j, k, params, max_modes, absolute))
  211. # (duplicates from rounding: keep the first)
  212. seen, res = set(), []
  213. for a in sorted(out, key=lambda a: (a['key'], a['velocity'])):
  214. if (a['key'], a['velocity']) in seen:
  215. continue
  216. seen.add((a['key'], a['velocity']))
  217. res.append(a)
  218. return res
  219. def choose(anchors, sigmas=(3.0, 6.0, 12.0, None), shrinks=(0.0, 0.5, 1.0)):
  220. """sigma and shrink per quantity by leave-one-out over the anchors (inner anchors of each layer, predicted from the
  221. anchors left after removing them); errors: levels in dB, ratios in cents, T60s and log scalars in log2, weighted by
  222. each mode's energy. Returns ({quantity: (sigma, shrink)}, {quantity: best error})"""
  223. layers = list(_layers(anchors).values())
  224. best, errs = {}, {}
  225. for name in list(QUANT) + [s[0] for s in SCALARS]:
  226. scores = {}
  227. for sg in sigmas:
  228. for sh in shrinks:
  229. e, wsum = 0.0, 0.0
  230. for layer in layers:
  231. for j in range(1, len(layer) - 1):
  232. rest = layer[:j] + layer[j + 1:]
  233. a, b, x = layer[j - 1], layer[j + 1], layer[j]
  234. if name in QUANT:
  235. bf = {m['fam']: m for m in b['modes'] if m.get('fam')}
  236. for m in a['modes']:
  237. f = m.get('fam')
  238. mx = next((y for y in x['modes'] if f and y.get('fam') == f), None)
  239. if not f or f not in bf or mx is None:
  240. continue
  241. pts = [(r['key'], _val(y, name)) for r in rest for y in r['modes'] if y.get('fam') == f]
  242. v = _predict(pts, x['key'], a['key'], _val(m, name), b['key'], _val(bf[f], name), sg, sh)
  243. w = np.sqrt(10 ** (mx['ampDb'] / 10) * min(mx['t60'], 3.0))
  244. d = abs(v - _val(mx, name))
  245. d = d * 1200 / np.log(2) if name == 'ratio' else d / np.log(2) if name == 't60' else d
  246. e += w * min(d, 30.0)
  247. wsum += w
  248. else:
  249. kind = dict(SCALARS)[name]
  250. pts = [(r['key'], _scal(r, name, kind)) for r in rest]
  251. v = _predict(pts, x['key'], a['key'], _scal(a, name, kind), b['key'], _scal(b, name, kind), sg, sh)
  252. d = abs(v - _scal(x, name, kind))
  253. e += d / np.log(2) if kind == 'log' else d
  254. wsum += 1.0
  255. scores[(sg, sh)] = e / max(wsum, 1e-12)
  256. k = min(scores, key=lambda q: (round(scores[q], 6), q[1], -(q[0] or 1e9)))
  257. best[name] = k
  258. errs[name] = {'best': round(scores[k], 4), 'linear': round(scores.get((None, 0.0), np.nan), 4)}
  259. return best, errs