calibrate.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. #!/usr/bin/env python3
  2. """calibrate.py - LYNX Model's auto-calibration (round 190ni): fits each mallet instrument's mode tables per key and
  3. velocity layer from CC0 recordings and writes the parameter table (.lpm, tools/physmod/lpm.py), its provenance record
  4. and the C++ include LYNX compiles in. Only fitted parameters ship (a few KB per instrument), never audio, and the
  5. attack is synthesised by the engine (a Gaussian contact pulse + band-pass noise), never a recorded transient.
  6. calibrate.py fit <instrument|all> <notes-root> <manifest.json> <out-dir> [--holdout N] [--inc-dir DIR]
  7. <notes-root>/<set>/*.wav as fetched with the manifest (path, git blob SHA-1, SHA-256, commit, licence per file).
  8. --holdout N: leave out every N-th note (by key, starting with the 2nd) and list them in the report: the held-out
  9. notes test the key interpolation; the shipped tables are fitted on every note (no --holdout).
  10. --fold F (round 190nl): start with the (2 + F)-th key instead, F < N; the table is <instrument>-holdoutNfF
  11. (fold 0 keeps the name <instrument>-holdoutN). N folds together hold every inner key out once.
  12. --inc-dir: also write <instrument>.inc there (tools/make_model_inc.py's format) for src/core/physmod/tables/.
  13. --set name=value[,...] (round 190nm): override an instrument's settings (INSTRUMENTS) for a variant
  14. --report-dir: the fit reports (<instrument>.fit.json, per note: modes, tuning, contact, noise, fit losses) go
  15. there instead of <out-dir> (the shipped run: tables and provenance in resources/physmod/, reports elsewhere).
  16. Per recorded note (one velocity layer):
  17. 1. onset, mono, the sounding key = the file's note label + 12 (VCSL labels sit one octave below the sounding pitch;
  18. checked against the strongest mode for every file, see the report's `label_octave_check`)
  19. 2. modes: prominent peaks (modal_analysis.pick_peaks), each tracked and fitted with an exponential decay (a0, T60);
  20. modes below the instrument's lowest useful frequency (room rumble), 60 dB under the strongest, and (kalimba) the
  21. other tines' sympathetic lines (the same absolute frequency in >= 3 other notes, off the note's own series) dropped;
  22. the strongest M by energy kept, then (round 190nl) up to `long` more by audible duration, at most 44 per anchor
  23. 3. tuning: the main mode (the strongest within 70 cents of the label) defines the note's tuning offset, removed so
  24. the instrument plays in tune; mode ratios refer to the key's equal-tempered frequency
  25. 4. strike position law: each mode's bending-mode number (shape) from the instrument's mode series
  26. 5. strike: the noise's band guessed from the first 100 ms with every mode notched out; then the contact time
  27. constant tau (the engine's force t e^(-t / tau)) and the noise's level, centre and decay fitted through the
  28. engine's own first 150 ms, emulated in closed form (fit_attack_noise): the timbre score's spectro-temporal grid and
  29. attack measures are the loss (automated refinement against the recording)
  30. 6. (round 190nl) mode families across each layer's keys (keyfit.families, the LPM mode's family byte); the strike is
  31. then refined through the engine itself by tools/physmod/refine.py, which writes the shipped tables and includes
  32. (round 190nm: refine.py --level then matches each anchor's level through the engine)
  33. Round 190nm settings (per instrument in INSTRUMENTS, or --set for a variant):
  34. window_exact a mode's level corrected for its tracking window (a fast partial read through a long window - chosen to
  35. resolve a weak neighbour - read up to 37 dB too loud), and a partial dying within its window tracked
  36. again with a window of half its T60 (modal_analysis.analyse_modes)
  37. split the SPLIT_TOP strongest modes each fitted as two components where two follow the track clearly better
  38. (modal_analysis.fit_two): a two-stage decay (a tine's fast start and slow tail through its coupling to
  39. the body) or a beating pair (a tube's near-degenerate doublet); the second component may start in
  40. antiphase (LPM shape byte bit 7)
  41. cover, peaks the `long` extra modes chosen by what they add to their third-octave band (select_modes); peaks: how
  42. many spectral peaks are analysed (56)
  43. onset the strike's slow start as the whole note's onset 1 - e^(-t / rise) (LPM header byte 14) instead of the
  44. resonated modes' build-up twins; onset_law=2 (round 190nn): the table asks for the S-shaped onset
  45. (1 - e^(-t / rise))^2 (the fit's first guess still emulates the exponential one; refine.py retunes the
  46. rise through the engine)
  47. fade='power' between two recorded keys a mode only one of them has fades by its power (LPM header byte 15)
  48. fmin_hz (round 190nn) the analysis floor in Hz where fmin x the key lies above it (the lines under a high key)
  49. sympathetic 'flag': lines found in 3+ other takes are kept absolute (in Hz, LPM family 255), and with fmin_hz so is
  50. every line below fmin x the key; 'below' (round 190nn): only the lines below fmin x the key (the body,
  51. the frame, the other tubes ringing along) are absolute
  52. """
  53. import datetime
  54. import hashlib
  55. import json
  56. import os
  57. import re
  58. import sys
  59. import numpy as np
  60. HERE = os.path.dirname(os.path.abspath(__file__))
  61. sys.path.insert(0, HERE)
  62. import keyfit # noqa: E402
  63. import lpm # noqa: E402
  64. import modal_analysis as ma # noqa: E402
  65. TOOL_VERSION = '190nn-1'
  66. NOTE = {'C': 0, 'D': 2, 'E': 4, 'F': 5, 'G': 7, 'A': 9, 'B': 11}
  67. # the instruments: VCSL folder (as fetch_vcsl.py names it), velocity layers in order, modes kept, mode series (ratios to
  68. # the main mode; None = the uniform free-free law (2k+1)^2), beam (0 free-free, 1 clamped-free), position mapping
  69. # (round 190nl) long=N: after the `modes` strongest by energy, up to N more by audible duration (the quiet partials that
  70. # ring longest: the score's spectro-temporal part sees every slice they are heard in); fmin re the key's frequency
  71. INSTRUMENTS = {
  72. 'marimba': dict(set='marimba', layers=['soft', 'med', 'loud'], modes=24, series=[1.0, 3.95, 9.5, 16.5, 25.0], beam=0,
  73. pos=(0.25, 0.5, 0.95), fmin=0.85, seconds=8.0),
  74. 'vibraphone': dict(set='vibraphone', layers=['v1', 'v2'], modes=24, series=[1.0, 3.98, 9.8, 17.0], beam=0,
  75. pos=(0.25, 0.5, 0.95), fmin=0.85, seconds=12.0),
  76. 'xylophone': dict(set='xylophone', layers=['pp', 'ff'], modes=24, series=[1.0, 3.0, 6.0, 9.9, 14.5], beam=0,
  77. pos=(0.25, 0.5, 0.95), fmin=0.85, seconds=4.0),
  78. 'glockenspiel': dict(set='glockenspiel', layers=['soft', 'medium', 'loud'], modes=20, series=None, beam=0,
  79. pos=(0.25, 0.5, 0.95), fmin=0.85, seconds=8.0),
  80. # (round 190nm: fmin 0.28 - the tubes' hum near 0.31 x the strike note rings 3-8 s and was cut at 0.4 -, two-component
  81. # modes - the doublets of a tube - and the whole note's onset: a bell's strike rises in about 1.8 ms)
  82. 'tubularbells': dict(set='tubularbells', layers=['v2', 'v4'], modes=32, series=None, beam=0, pos=(0.0, 0.02, 0.35),
  83. fmin=0.28, seconds=14.0, split=True, onset=True),
  84. # (the kalimba's other tines ring along in every take: sympathetic='flag' (round 190nl) keeps their lines and marks
  85. # them absolute - LPM family 255, played at their own pitch whatever key is struck, so a key between two recorded
  86. # ones hears the same tines ring; sympathetic=True would drop them)
  87. # (fmin 0.3: the lower tines ring along too, below the plucked one; round 190nl)
  88. # (round 190nm: the window-exact levels, two-component modes, band-covering long modes from 80 peaks, the whole
  89. # note's onset - a pluck starts in 2-10 ms - and the equal-power fade of the lines only one neighbour has)
  90. # (round 190nn: fmin_hz 60 - under a high tine the analysis reaches the lower tines and the body ringing along, kept
  91. # in Hz -, and the S-shaped onset (LPM onset 2): a pluck's quiet first moment, then the rise)
  92. 'kalimba': dict(set='kalimba', layers=[None], modes=28, series=[1.0, 6.27, 17.55, 34.39], beam=1,
  93. pos=(0.2, 0.95, 0.55), fmin=0.3, seconds=6.0, sympathetic='flag', window_exact=True, split=True,
  94. cover=True, long=16, peaks=80, onset=True, fade='power', fmin_hz=60.0, onset_law=2),
  95. }
  96. PIPELINE = ('calibrate.py fit (modes, tuning, strike first guess), then refine.py (the strike refined through the engine '
  97. 'against the timbre score\'s attack and spectro-temporal parts; round 190nm: then each anchor\'s level matched '
  98. 'through the engine, --level); rounds 190nl, 190nm, 190nn')
  99. LONG_MODES = 12 # (the default `long`)
  100. NOISE_ORDER = 2 # the engine's strike noise: two band-pass sections (LPM header byte 13)
  101. MAX_LANES = 44 # modes per anchor at most: the engine's 48 lanes less the build-up twins
  102. def audible_seconds(m, top_a0):
  103. """how long a mode stays within 50 dB of the note's strongest one: its T60 x (its level + 50 dB) / 60 dB"""
  104. lvl = 20 * np.log10(max(m['a0'], 1e-12) / max(top_a0, 1e-12))
  105. return max(lvl + 50.0, 0.0) / 60.0 * min(m['t60'], 60.0)
  106. def select_modes(modes, main, n_energy, n_long, cover=False):
  107. """the `n_energy` strongest modes by energy (a0^2 min(T60, 3 s)), then up to `n_long` more by audible duration
  108. (round 190nl), the main mode always. cover (round 190nm): the `n_long` by what they add to their third-octave band -
  109. their audible duration beyond the longest kept mode's in that band (the timbre score's spectro-temporal cells are
  110. third-octave bands: a quiet high partial alone in its band is heard there for its whole duration, a quiet partial
  111. next to a louder, longer one adds nothing)"""
  112. top = max(m['a0'] for m in modes)
  113. by_e = sorted(modes, key=lambda m: -m['a0'] ** 2 * min(m['t60'], 3.0))
  114. kept = by_e[:n_energy]
  115. if cover:
  116. band = lambda m: int(np.floor(3.0 * np.log2(m['f'] / 1000.0) + 0.5))
  117. have = {}
  118. for m in kept:
  119. have[band(m)] = max(have.get(band(m), 0.0), audible_seconds(m, top))
  120. rest = list(by_e[n_energy:])
  121. for _ in range(n_long):
  122. gains = [(audible_seconds(m, top) - have.get(band(m), 0.0), i) for i, m in enumerate(rest)]
  123. if not gains:
  124. break
  125. g, i = max(gains)
  126. if g <= 0.05:
  127. break
  128. m = rest.pop(i)
  129. kept.append(m)
  130. have[band(m)] = max(have.get(band(m), 0.0), audible_seconds(m, top))
  131. else:
  132. rest = sorted(by_e[n_energy:], key=lambda m: -audible_seconds(m, top))
  133. kept += [m for m in rest[:n_long] if audible_seconds(m, top) > 0.05]
  134. kept = kept[:MAX_LANES]
  135. if main not in kept:
  136. kept = [main] + kept[:-1]
  137. return kept
  138. def write_inc(instrument, data, inc_dir):
  139. """src/core/physmod/tables/<instrument>.inc: the table's bytes as a C array"""
  140. os.makedirs(inc_dir, exist_ok=True)
  141. name = 'lpm_' + instrument
  142. lines = [', '.join(str(b) for b in data[i:i + 40]) + ',' for i in range(0, len(data), 40)]
  143. with open(os.path.join(inc_dir, instrument + '.inc'), 'w', newline='\n') as f:
  144. f.write('// Generated by tools/physmod/calibrate.py from resources/physmod/%s.lpm (%d bytes, SHA-256 %s). Do not edit.\n'
  145. % (instrument, len(data), hashlib.sha256(data).hexdigest()))
  146. f.write('alignas (16) static const unsigned char %s[%d] = {\n' % (name, len(data)))
  147. f.write('\n'.join(lines))
  148. f.write('\n};\n')
  149. FREE_BETA = [4.730040745, 7.853204624, 10.99560784, 14.13716549, 17.27875966, 20.42035225, 23.56194490, 26.70353756]
  150. CLAMPED_BETA = [1.875104069, 4.694091133, 7.854757438, 10.99554073, 14.13716839, 17.27875953, 20.42035225, 23.56194490]
  151. def mode_shape(beam, shape, u):
  152. """the engine's modeShape (LynxModel.cpp): bending mode `shape` of a free-free (0) or clamped-free (1) beam at u"""
  153. if shape <= 0:
  154. return 1.0
  155. k = shape - 1
  156. if k < 8:
  157. b = (CLAMPED_BETA if beam == 1 else FREE_BETA)[k]
  158. bx = b * u
  159. if beam == 1:
  160. s = (np.cosh(b) + np.cos(b)) / (np.sinh(b) + np.sin(b))
  161. return float(np.cosh(bx) - np.cos(bx) - s * (np.sinh(bx) - np.sin(bx)))
  162. s = (np.cosh(b) - np.cos(b)) / (np.sinh(b) - np.sin(b))
  163. return float(np.cosh(bx) + np.cos(bx) - s * (np.sinh(bx) + np.sin(bx)))
  164. b = (2 * shape - 1) * np.pi / 2 if beam == 1 else (2 * shape + 1) * np.pi / 2
  165. return float(np.sqrt(2) * (np.sin(b * u - np.pi / 4) if beam == 1 else np.cos(b * u + np.pi / 4)))
  166. def label_key(name):
  167. m = re.search(r'_([A-G])(#?)(\d)_', name)
  168. return 12 * (int(m.group(3)) + 1) + NOTE[m.group(1)] + (1 if m.group(2) else 0) + 12
  169. def layer_of(name, layers):
  170. if layers == [None]:
  171. return 0
  172. for i, l in enumerate(layers):
  173. if '_%s_' % l in name:
  174. return i
  175. return None
  176. def hz(key):
  177. return 440.0 * 2 ** ((key - 69) / 12.0)
  178. def cents(a, b):
  179. return 1200.0 * np.log2(a / b)
  180. def shape_of(ratio, series, beam):
  181. """the bending-mode number of a mode at `ratio` (to the main mode), 0 when it fits no mode of the series"""
  182. if series is None: # uniform free-free beam: f_k ~ (2k+1)^2 with the main mode as k = kmain
  183. return None
  184. best, bd = 0, 1e9
  185. for k, s in enumerate(series):
  186. d = abs(cents(ratio, s))
  187. if d < bd:
  188. best, bd = k + 1, d
  189. return best if bd < 200 else 0
  190. def uniform_shapes(modes, main_f):
  191. """free-free bars and tubes without a tuned series: the main mode's order from the strong modes' frequency pattern
  192. ((2k+1)^2 law), then each mode's order; 0 where a mode sits between orders"""
  193. strong = sorted([m['f'] for m in modes[:6]])
  194. best = None
  195. for kmain in range(1, 9):
  196. c = main_f / (2 * kmain + 1) ** 2
  197. err = 0.0
  198. for f in strong:
  199. k = (np.sqrt(f / c) - 1) / 2
  200. err += min(abs(k - np.round(k)), 0.5)
  201. if best is None or err < best[0] - 1e-9:
  202. best = (err, kmain, c)
  203. _, kmain, c = best
  204. out = []
  205. for m in modes:
  206. k = (np.sqrt(m['f'] / c) - 1) / 2
  207. out.append(int(np.round(k)) if abs(k - np.round(k)) < 0.2 and np.round(k) >= 1 else 0)
  208. return out, kmain
  209. def noise_fit(x, sr, modes_all, main_a0):
  210. """strike noise: the first 100 ms with every detected mode notched out (+-max(1.5 %, 4 bins))"""
  211. n = int(0.1 * sr)
  212. seg = x[:n].copy()
  213. N = 1 << int(np.ceil(np.log2(n * 2)))
  214. X = np.fft.rfft(seg, N)
  215. fr = np.fft.rfftfreq(N, 1.0 / sr)
  216. for m in modes_all:
  217. X[np.abs(fr - m['f']) < max(0.015 * m['f'], 4 * sr / N)] = 0
  218. X[fr < 60] = 0
  219. r = np.fft.irfft(X, N)[:n]
  220. hop = int(0.002 * sr)
  221. k = len(r) // hop
  222. e = np.sqrt(np.mean(r[:k * hop].reshape(k, -1) ** 2, 1)) + 1e-12
  223. edb = 20 * np.log10(e)
  224. pk = int(np.argmax(edb[:10]))
  225. t = (np.arange(k) + 0.5) * hop / sr
  226. floor = np.percentile(edb, 20)
  227. use = np.arange(k) >= pk
  228. use &= edb > max(floor + 3, edb[pk] - 40)
  229. if use.sum() >= 3:
  230. sl = np.polyfit(t[use], edb[use], 1)[0]
  231. tau_ms = float(np.clip(8.686 / max(-sl, 1e-3) * 1000.0, 2.0, 120.0))
  232. else:
  233. tau_ms = 10.0
  234. a20 = int(0.02 * sr)
  235. S = np.abs(np.fft.rfft(r[:a20] * np.hanning(a20))) ** 2
  236. f2 = np.fft.rfftfreq(a20, 1.0 / sr)
  237. S[f2 < 60] = 0
  238. tot = S.sum() + 1e-30
  239. fc = float((S * f2).sum() / tot)
  240. spread = float(np.sqrt((S * (f2 - fc) ** 2).sum() / tot))
  241. q = float(np.clip(fc / max(2 * spread, 1.0), 0.5, 4.0))
  242. fc = float(np.clip(fc, 150.0, 0.4 * sr))
  243. # level: the residual's peak 2 ms RMS re the main mode's amplitude, as the engine's normalised band-pass noise:
  244. # white uniform noise (RMS 1/sqrt(3)) through a unity-peak band-pass passes ENBW = (pi/2) fc / Q of fs / 2
  245. chain = (1 / np.sqrt(3)) * np.sqrt(np.pi * fc / (q * sr))
  246. level = float(np.clip(20 * np.log10(e[pk] / (main_a0 * chain + 1e-12)), -60.0, 20.0))
  247. return {'noiseDb': level, 'noiseHz': fc, 'noiseQ': q, 'noiseMs': tau_ms}
  248. # --- the engine's first 150 ms, emulated (src/core/physmod/LynxModel.cpp at its default knobs) ------------------------
  249. EMU_SECONDS = 0.15
  250. EMU_EDGES = np.array([0.0, 0.003, 0.006, 0.012, 0.025, 0.05, 0.1, 0.15])
  251. TAUS = np.geomspace(0.00003, 0.002, 11)
  252. RISES = np.array([0.0, 0.002, 0.004, 0.008, 0.016])
  253. H_DRIVE = 0.1 # LynxModel.cpp hDrive
  254. NOISE_T = np.array([0.0015, 0.003, 0.006, 0.012, 0.025, 0.05])
  255. NOISE_DB = np.arange(-50.0, 21.0, 3.0)
  256. def with_build_up(modes, main_f, rise):
  257. """the resonated modes (within 6 % of the main mode) with their build-up: a twin of opposite sign decaying with the
  258. time constant `rise` (the engine's twin lanes), so the pair grows as e^(-t/T) - e^(-t/rise)"""
  259. if rise <= 0:
  260. return modes
  261. out = list(modes)
  262. for f, a0, t60, sign in modes:
  263. if abs(f / main_f - 1) < 0.06:
  264. out.append((f, a0, 6.9078 * rise, -sign))
  265. return out
  266. def emulate_modes(modes, sr, n, tau):
  267. """the modal part: each mode (f, a0, t60, sign) driven by the contact pulse t e^(-t/tau) as the engine does it
  268. (two one-pole low-passes on an impulse, the mode's drive a0 / |H(w)| so its amplitude after the strike is a0; a
  269. mode the pulse reaches less than H_DRIVE gets a0 as a kick at the force's peak):
  270. closed form y[n] = Im(d (1-c)^2 g[n]), g = 1 / ((1 - p z^-1)(1 - c z^-1)^2) by partial fractions"""
  271. c = np.exp(-1.0 / max(tau * sr, 0.05))
  272. t = np.arange(n)
  273. y = np.zeros(n)
  274. for f, a0, t60, sign in modes:
  275. w = 2 * np.pi * f / sr
  276. if w >= 2 * np.pi * 0.45:
  277. continue
  278. r = 10 ** (-3.0 / (t60 * sr))
  279. p = r * np.exp(1j * w)
  280. h = (1 - c) ** 2 / (1 - 2 * c * np.cos(w) + c * c)
  281. if h < H_DRIVE: # (the engine kicks it at the force's peak)
  282. k = int(np.argmax((1 - c) ** 2 * (t + 1) * c ** t))
  283. y[k:] += np.imag(sign * a0 * p ** (t[: n - k] + 1))
  284. continue
  285. d = sign * a0 / h
  286. al = p * p / (p - c) ** 2
  287. ga = c / (c - p)
  288. be = 1 - al - ga
  289. g = al * p ** t + (be + ga * (t + 1)) * c ** t
  290. y += np.imag(d * (1 - c) ** 2 * g)
  291. return y
  292. def noise_env(sr, n, tau, T):
  293. """the strike noise's envelope: the contact force normalised to its peak while it rises, then e^(-t / T)"""
  294. c = np.exp(-1.0 / max(tau * sr, 0.05))
  295. t = np.arange(n)
  296. force = (1 - c) ** 2 * (t + 1) * c ** t
  297. pk = int(np.argmax(force))
  298. env = force / force[pk]
  299. env[pk:] = np.exp(-(t[pk:] - pk) / (T * sr))
  300. return env
  301. def noise_carrier(sr, n, fc, q, seed=7, order=None):
  302. """white noise of RMS 1/sqrt(3) (the engine's uniform noise) through a unity-peak band-pass at fc, Q (the TPT
  303. state-variable filter's analog prototype, pre-warped), `order` sections (NOISE_ORDER)"""
  304. rng = np.random.default_rng(seed)
  305. N = 1 << int(np.ceil(np.log2(n * 2)))
  306. X = np.fft.rfft(rng.standard_normal(N) / np.sqrt(3.0))
  307. f = np.fft.rfftfreq(N, 1.0 / sr)
  308. W = np.tan(np.pi * np.minimum(f, 0.499 * sr) / sr) / np.tan(np.pi * fc / sr)
  309. H = (W / q) / np.sqrt((1 - W * W) ** 2 + (W / q) ** 2 + 1e-30)
  310. return np.fft.irfft(X * H ** (order or NOISE_ORDER), N)[:n]
  311. ONSETS = np.array([0.0, 0.00025, 0.0005, 0.001, 0.002, 0.004])
  312. def onset_env(sr, n, rise):
  313. """the engine's whole-note onset (LPM onset tables, round 190nm): 1 - e^(-t / rise)"""
  314. if rise <= 0:
  315. return np.ones(n)
  316. return 1.0 - np.exp(-np.arange(n) / (rise * sr))
  317. def fit_attack_noise(x, sr, modes, main_a0, fc0, q0, floor=None, main_f=None, onset=False):
  318. """contact time constant and strike noise (level re the main mode, centre, Q, decay) that make the emulated first
  319. 150 ms closest to the recording: the timbre score's spectro-temporal grid (third-octaves x 0-3-6-12-25-50-100-150 ms,
  320. absolute levels) and its attack (10-90 % rise, the 1 ms envelope on a log time grid), grid search"""
  321. n = int(EMU_SECONDS * sr)
  322. ref = x[:n]
  323. gr = ma.band_energy_grid(ref, sr, EMU_EDGES)
  324. top = gr.max()
  325. fl = (floor if floor is not None else np.full((gr.shape[0], 1), -300.0)) + 6.0 # (the timbre score's background rule)
  326. e_ref = ma.smooth_env(ref, sr, 0.5)
  327. rise_ref = ma.rise_of_env(e_ref[::4], sr / 4.0)
  328. grid_t = np.unique(np.clip((np.geomspace(0.0005, EMU_SECONDS, 32) * sr).astype(int), 0, n - 1))
  329. curve_ref = 20 * np.log10(ma.smooth_env(ref, sr, 1.0)[grid_t] / max(ma.smooth_env(ref, sr, 1.0).max(), 1e-12) + 1e-9)
  330. fcs = [float(np.clip(fc0 * k, 150.0, 0.4 * sr)) for k in (0.5, 1.0, 2.0)]
  331. carriers = {fc: noise_carrier(sr, n, fc, q0) for fc in fcs}
  332. chain = main_a0
  333. best = None
  334. import timbre_score as ts
  335. def shifted(y, lag):
  336. y = y[lag:] if lag > 0 else np.concatenate([np.zeros(-lag), y]) if lag < 0 else y
  337. return np.concatenate([y, np.zeros(max(0, n - len(y)))])[:n]
  338. m = curve_ref > -40
  339. noise_cache = {}
  340. for tau, rise in [(t, r) for t in TAUS for r in (ONSETS if onset else RISES if main_f else [0.0])]:
  341. env = onset_env(sr, n, rise) if onset else None
  342. ym = emulate_modes(modes if onset else with_build_up(modes, main_f, rise), sr, n, tau)
  343. if onset:
  344. ym = ym * env
  345. lag = ts.envelope_lag(ref, ym, sr) # (the timbre score lines the notes up so; the noise moves with the modes)
  346. ym = shifted(ym, lag)
  347. Em = 10 ** (ma.band_energy_grid(ym, sr, EMU_EDGES) / 10)
  348. em2 = ma.smooth_env(ym, sr, 0.5) ** 2
  349. em2c = ma.smooth_env(ym, sr, 1.0) ** 2
  350. for fc in fcs:
  351. for T in NOISE_T:
  352. key = (tau, fc, T, lag, rise if onset else 0.0)
  353. if key not in noise_cache:
  354. yn = shifted(carriers[fc] * noise_env(sr, n, tau, T) * chain * (env if onset else 1.0), lag)
  355. noise_cache[key] = (10 ** (ma.band_energy_grid(yn, sr, EMU_EDGES) / 10), ma.smooth_env(yn, sr, 0.5) ** 2,
  356. ma.smooth_env(yn, sr, 1.0) ** 2)
  357. En, en2, en2c = noise_cache[key]
  358. for ndb in list(NOISE_DB) + [None]:
  359. L2 = 0.0 if ndb is None else 10 ** (ndb / 10)
  360. ge = 10 * np.log10(Em + L2 * En + 1e-30)
  361. aud = ((gr > top - 50) & (gr > fl)) | ((ge > top - 50) & (ge > fl))
  362. spec = float(np.mean(np.minimum(np.abs(ge[aud] - gr[aud]), 30.0))) / 10.0
  363. env = np.sqrt(em2 + L2 * en2)
  364. # (the rise on the envelope decimated by 4: 0.09 ms steps, well under the score's 0.5 ms floor)
  365. rise_m = abs(np.log2(max(ma.rise_of_env(env[::4], sr / 4.0), 1e-5) / max(rise_ref, 1e-5))) / 1.5
  366. ec = np.sqrt(em2c + L2 * en2c)
  367. curve_e = 20 * np.log10(ec[grid_t] / max(ec.max(), 1e-12) + 1e-9)
  368. curve = float(np.mean(np.minimum(np.abs(curve_e[m] - curve_ref[m]), 30.0))) / 8.0 if m.any() else 1.0
  369. att = (min(rise_m, 1.0) + min(curve, 1.0)) / 2.0
  370. loss = 1.5 * min(spec, 1.0) ** 2 + att ** 2
  371. if best is None or loss < best[0]:
  372. best = (loss, tau, fc, T, ndb, spec, att, rise)
  373. loss, tau, fc, T, ndb, spec, att, rise = best
  374. return {'contact': float(tau), 'riseMs': float(rise * 1000.0), 'noiseDb': float(ndb) if ndb is not None else -60.0, 'noiseHz': fc, 'noiseQ': float(q0),
  375. 'noiseMs': float(T * 1000.0), 'fit_loss': round(float(loss), 4), 'fit_spec_miss': round(spec, 3), 'fit_attack_miss': round(att, 3),
  376. 'rise_ref_ms': round(rise_ref * 1000.0, 3)}
  377. SPLIT_TOP = 16 # (round 190nm) the strongest modes by energy tried as two components
  378. def split_modes(x, sr, kept, main, cfg):
  379. """round 190nm: the strongest SPLIT_TOP kept modes, each fitted as two components on its complex track
  380. (modal_analysis.fit_two: a two-stage decay or a beating pair); a mode whose track two components follow clearly
  381. better becomes two modes (part 1 the stronger at the strike, part 2 the other, its sign as fitted). The lanes stay
  382. within MAX_LANES: each split takes the place of the weakest unsplit mode (never the main mode)."""
  383. hop = max(1, int(sr * 0.005))
  384. order = sorted(kept, key=lambda m: -m['a0'] ** 2 * min(m['t60'], 3.0))
  385. out = list(kept)
  386. tried = 0
  387. for m in order:
  388. if tried >= cfg.get('split_top', SPLIT_TOP):
  389. break
  390. if m.get('absolute') or not any(q is m for q in out):
  391. continue # (an absolute line, or a weak mode an earlier split took the place of)
  392. tried += 1
  393. t, z = ma.track_complex(x, sr, m['f'], m['win'], hop)
  394. single = ma.fit_decay(t, np.abs(z))
  395. two = ma.fit_two(t, z, single, max_split_hz=cfg.get('split_hz', 3.0), min_gain_db=cfg.get('split_gain_db', 0.6))
  396. if two is None:
  397. continue
  398. if len(out) + 1 > MAX_LANES:
  399. spare = [q for q in sorted(out, key=lambda q: q['a0'] ** 2 * min(q['t60'], 3.0)) if q is not main and not q.get('part')
  400. and q is not m]
  401. if not spare:
  402. break
  403. out.remove(spare[0])
  404. if cfg.get('window_exact'):
  405. for p in two['parts']:
  406. p['a0'] /= ma.window_gain(p['t60'], m['win'], sr)
  407. p1, p2 = sorted(two['parts'], key=lambda p: -p['a0'])
  408. # (the main mode's stronger part stays at the main mode's frequency: the note's tuning and the key's ratio 1)
  409. shift = p1['df'] if m is main else 0.0
  410. a = dict(m, f=m['f'] + p1['df'] - shift, a0=p1['a0'], t60=p1['t60'], part=1, split=two)
  411. b = dict(m, f=m['f'] + p2['df'] - shift, a0=p2['a0'], t60=p2['t60'], part=2, invert=p2['sign'] * p1['sign'] < 0, sibling=a)
  412. for q in (a, b):
  413. q['energy'] = q['a0'] ** 2 * q['t60']
  414. i = next(j for j, q in enumerate(out) if q is m)
  415. out[i:i + 1] = [a, b]
  416. return out
  417. def fit_note(path, cfg, sympathetic_lines=None):
  418. x, sr = ma.read_wav(path)
  419. on = ma.onset(x, sr)
  420. x = x[on:][:int(cfg['seconds'] * sr)]
  421. name = os.path.basename(path)
  422. key = label_key(name)
  423. f_nom = hz(key)
  424. # (round 190nn: fmin_hz - the analysis reaches down to this many Hz where fmin x the key lies above it; with
  425. # sympathetic='flag' a line found there - below fmin x the key, another tine or the body - is kept in Hz, absolute)
  426. floor_hz = min(cfg['fmin'] * f_nom, cfg.get('fmin_hz', 1e9))
  427. modes = ma.analyse_modes(x, sr, fmin=floor_hz, k=cfg.get('peaks', 56), prom_db=10.0, window_exact=cfg.get('window_exact', False))
  428. if not modes:
  429. raise ValueError('no modes: %s' % name)
  430. top = max(m['a0'] for m in modes)
  431. modes = [m for m in modes if m['a0'] >= top * 1e-3 and m['t60'] > 0.01]
  432. near = [m for m in modes if abs(cents(m['f'], f_nom)) < 70]
  433. main = max(near, key=lambda m: m['energy']) if near else max(modes, key=lambda m: m['energy'])
  434. offset = cents(main['f'], f_nom) if near else 0.0
  435. strongest = max(modes, key=lambda m: m['energy'])
  436. octave_check = round(float(np.log2(strongest['f'] / f_nom)), 2)
  437. f_tuned = f_nom * 2 ** (offset / 1200)
  438. dropped = []
  439. if cfg.get('sympathetic') == 'below':
  440. # (round 190nn: only the lines below fmin x the key - the body, the frame, the other tubes - kept in Hz)
  441. for m in modes:
  442. if m['f'] < cfg['fmin'] * f_nom and m is not main:
  443. m['absolute'] = True
  444. elif sympathetic_lines is not None:
  445. keep = []
  446. for m in modes:
  447. r = m['f'] / main['f']
  448. own = any(abs(cents(r, s)) < 60 for s in cfg['series']) or m is main
  449. hits = sum(1 for other in sympathetic_lines if any(abs(cents(m['f'], g)) < 8 for g in other))
  450. if m['f'] < cfg['fmin'] * f_nom and m is not main and cfg.get('sympathetic') == 'flag':
  451. m['absolute'] = True
  452. keep.append(m)
  453. elif hits >= 3 and not own:
  454. if cfg.get('sympathetic') == 'flag':
  455. m['absolute'] = True
  456. keep.append(m)
  457. else:
  458. dropped.append(round(m['f'], 1))
  459. else:
  460. keep.append(m)
  461. modes = keep
  462. kept = select_modes(modes, main, cfg['modes'], cfg.get('long', LONG_MODES), cfg.get('cover', False))
  463. if cfg.get('split'):
  464. kept = split_modes(x, sr, kept, main, cfg)
  465. # (round 190nm: the two parts of a split mode share their mode's shape - one physical mode)
  466. whole = [m for m in kept if m.get('part', 0) != 2]
  467. if cfg['series'] is None:
  468. shapes, kmain = uniform_shapes(sorted(whole, key=lambda m: -m['energy']), main['f'])
  469. order = sorted(whole, key=lambda m: -m['energy'])
  470. shape = {id(m): s for m, s in zip(order, shapes)}
  471. else:
  472. shape = {id(m): shape_of(m['f'] / main['f'], cfg['series'], cfg['beam']) for m in whole}
  473. kmain = 1
  474. # one mode per bending order (the strongest); the rest keep no position law
  475. seen = {}
  476. for m in sorted(whole, key=lambda m: -m['energy']):
  477. s = shape[id(m)]
  478. if s and s in seen:
  479. shape[id(m)] = 0
  480. elif s:
  481. seen[s] = m
  482. for m in kept:
  483. if m.get('part', 0) == 2:
  484. shape[id(m)] = shape[id(m['sibling'])]
  485. # strike: a first guess of the noise's band from the notched residual, then the contact and the noise fitted through
  486. # the engine's emulated first 150 ms (the modes kept, with their strike-point signs at the default position)
  487. guess = noise_fit(x, sr, modes, main['a0'])
  488. u_ref = cfg['pos'][1] + (cfg['pos'][2] - cfg['pos'][1]) * cfg['pos'][0]
  489. emu = [(m['f'], m['a0'], min(m['t60'], 60.0), (-1.0 if m.get('invert') else 1.0) *
  490. (-1.0 if shape[id(m)] and mode_shape(cfg['beam'], shape[id(m)], u_ref) < 0 else 1.0)) for m in kept]
  491. import timbre_score as ts
  492. floor = ts.band_floor(ma.band_energy_grid(x, sr, ts.time_edges(len(x) / sr)))
  493. nz = fit_attack_noise(x, sr, emu, main['a0'], guess['noiseHz'], guess['noiseQ'], floor, main['f'], cfg.get('onset', False))
  494. contact = nz.pop('contact')
  495. rise = nz['rise_ref_ms'] / 1000.0
  496. # (ratio = f / (the key's equal-tempered frequency x the tuning offset): the main mode lands on ratio 1, in tune)
  497. # (an absolute line - another tine - refers to the key's equal-tempered frequency, not the take's tuning: played at
  498. # the take's tuning it must land on its own frequency, the engine keeps it in Hz)
  499. out_modes = [{'ratio': float(m['f'] / (f_nom if m.get('absolute') else f_tuned)),
  500. 'ampDb': float(20 * np.log10(m['a0'] / main['a0'])), 't60': float(min(m['t60'], 60.0)),
  501. 'shape': 0 if m.get('absolute') else int(shape[id(m)]), 'absolute': bool(m.get('absolute')),
  502. 'f_hz': m['f'], 'fit_rms_db': m['rms_db'], **({'part': m['part'], 'invert': bool(m.get('invert'))} if m.get('part') else {})}
  503. for m in sorted(kept, key=lambda m: m['f'])]
  504. return {'file': name, 'key': key, 'tuning_offset_cents': round(float(offset), 2), 'label_octave_check': octave_check,
  505. 'main_hz': main['f'], 'gainDb': float(20 * np.log10(main['a0'])), 'contact': contact, 'rise_ms': rise * 1000.0,
  506. 'kmain': kmain, 'modes': out_modes, 'dropped_sympathetic_hz': dropped, 'sr': sr, **nz}
  507. def notes_of(root, cfg, manifest):
  508. files = [f for f in manifest['files'] if f['set'] == cfg['set']]
  509. out = []
  510. for f in files:
  511. name = f['path'].split('/')[-1]
  512. layer = layer_of(name, cfg['layers'])
  513. if layer is None:
  514. continue
  515. out.append((label_key(name), layer, name, f))
  516. out.sort(key=lambda t: (t[0], t[1], t[2]))
  517. # one take per (key, layer): the first by name; the others are kept aside as extra checks (another tine, a 2nd take)
  518. first, extra = [], []
  519. seen = set()
  520. for t in out:
  521. (extra if (t[0], t[1]) in seen else first).append(t)
  522. seen.add((t[0], t[1]))
  523. return first, extra
  524. def calibrate(instrument, root, manifest, outdir, holdout=0, inc_dir=None, report_dir=None, fold=0):
  525. cfg = INSTRUMENTS[instrument]
  526. takes, extra = notes_of(root, cfg, manifest)
  527. keys = sorted(set(t[0] for t in takes))
  528. held = set(keys[1 + fold::holdout]) if holdout else set()
  529. held.discard(keys[0]); held.discard(keys[-1]) # (the range's ends stay: held-out notes test interpolation only)
  530. use = [t for t in takes if t[0] not in held]
  531. sym = None
  532. if cfg.get('sympathetic') and cfg.get('sympathetic') != 'below':
  533. sym = []
  534. for t in takes:
  535. x, sr = ma.read_wav(os.path.join(root, cfg['set'], t[2]))
  536. x = x[ma.onset(x, sr):][:int(cfg['seconds'] * sr)]
  537. sym.append([m['f'] for m in ma.analyse_modes(x, sr, fmin=60.0, k=40, prom_db=10.0)])
  538. fits = []
  539. for key, layer, name, f in use:
  540. path = os.path.join(root, cfg['set'], name)
  541. others = None
  542. if sym is not None:
  543. idx = [i for i, t in enumerate(takes) if t[2] == name][0]
  544. others = [s for i, s in enumerate(sym) if i != idx and takes[i][0] != key]
  545. r = fit_note(path, cfg, others)
  546. nl = len(cfg['layers'])
  547. r['velocity'] = 0.8 if nl == 1 else (layer + 1) / nl
  548. r['layer'] = cfg['layers'][layer]
  549. r['source'] = f
  550. fits.append(r)
  551. print(' %-14s %-46s key %3d off %+6.1f c modes %2d contact %.3f ms noise %5.1f dB %6.0f Hz' % (
  552. instrument, name[:46], key, r['tuning_offset_cents'], len(r['modes']), r['contact'] * 1000, r['noiseDb'], r['noiseHz']), flush=True)
  553. # the instrument's level: the loudest layer's notes peak around -8 dBFS (the sum of their mode amplitudes)
  554. top = max(f['velocity'] for f in fits)
  555. peaks = [f['gainDb'] + 20 * np.log10(sum(10 ** (m['ampDb'] / 20) for m in f['modes'])) for f in fits if f['velocity'] == top]
  556. gain_offset = float(-8.0 - np.median(peaks))
  557. pos_ref, u0, u1 = cfg['pos']
  558. anchors = [{'key': float(f['key']), 'velocity': float(f['velocity']), 'gainDb': float(f['gainDb']), 'contact': f['contact'], 'riseMs': f['riseMs'],
  559. 'noiseDb': f['noiseDb'], 'noiseHz': f['noiseHz'], 'noiseQ': f['noiseQ'], 'noiseMs': f['noiseMs'],
  560. 'modes': [dict({k: m[k] for k in ('ratio', 'ampDb', 't60', 'shape')}, **({'fam': lpm.ABSOLUTE} if m.get('absolute') else {}),
  561. **({'part': m['part'], 'invert': m['invert']} if m.get('part') else {}))
  562. for m in f['modes']]} for f in fits]
  563. keyfit.families(anchors) # (round 190nl: the engine pairs the same mode across keys by its family)
  564. tag = instrument + ('-holdout%d' % holdout if holdout else '') + ('f%d' % fold if holdout and fold else '')
  565. provenance = {
  566. 'instrument': instrument, 'table': tag + '.lpm', 'tool': 'tools/physmod/calibrate.py ' + TOOL_VERSION,
  567. 'date': datetime.date.today().isoformat(),
  568. 'pipeline': PIPELINE,
  569. 'data_policy': 'CC0 only; fitted parameters ship, no audio; synthesised attack (no recorded transient)',
  570. 'source': {'library': 'Versilian Community Sample Library (VCSL)', 'url': manifest['source'], 'commit': manifest['commit'],
  571. 'licence': manifest['licence'], 'licence_sha256': manifest.get('licence_sha256'),
  572. 'licence_check': manifest.get('licence_check')},
  573. 'files': [{'path': f['source']['path'], 'git_blob_sha1': f['source']['git_blob_sha1'], 'sha256': f['source']['sha256'],
  574. 'bytes': f['source']['bytes'], 'licence': 'CC0-1.0', 'layer': f['layer'], 'velocity': f['velocity'],
  575. 'sounding_key': f['key']} for f in fits],
  576. 'held_out_keys': sorted(held), 'not_used_extra_takes': [t[2] for t in extra],
  577. }
  578. pbytes = json.dumps(provenance, indent=1, sort_keys=True).encode()
  579. os.makedirs(outdir, exist_ok=True)
  580. data = lpm.write(os.path.join(outdir, tag + '.lpm'), instrument, cfg['beam'], pos_ref, u0, u1, gain_offset, anchors, pbytes,
  581. NOISE_ORDER, cfg.get('onset_law', 1) if cfg.get('onset') else 0, 1 if cfg.get('fade') == 'power' else 0)
  582. open(os.path.join(outdir, tag + '.provenance.json'), 'wb').write(pbytes)
  583. report = {'instrument': instrument, 'bytes': len(data), 'anchors': len(anchors), 'modes': sum(len(a['modes']) for a in anchors),
  584. 'gain_offset_db': gain_offset, 'held_out_keys': sorted(held),
  585. 'held_out_takes': [{'file': t[2], 'key': t[0], 'layer': cfg['layers'][t[1]]} for t in takes if t[0] in held],
  586. 'extra_takes': [{'file': t[2], 'key': t[0], 'layer': cfg['layers'][t[1]]} for t in extra],
  587. 'notes': fits}
  588. os.makedirs(report_dir or outdir, exist_ok=True)
  589. json.dump(report, open(os.path.join(report_dir or outdir, tag + '.fit.json'), 'w'), indent=1)
  590. if inc_dir and not holdout:
  591. write_inc(instrument, data, inc_dir)
  592. print('%s: %d anchors, %d modes, %d bytes, gain offset %.1f dB, held out %s' % (
  593. tag, len(anchors), report['modes'], len(data), gain_offset, sorted(held)), flush=True)
  594. return report
  595. def main():
  596. a = sys.argv[1:]
  597. if len(a) < 5 or a[0] != 'fit':
  598. print(__doc__)
  599. return 2
  600. inst, root, man, out = a[1], a[2], json.load(open(a[3])), a[4]
  601. holdout = int(a[a.index('--holdout') + 1]) if '--holdout' in a else 0
  602. fold = int(a[a.index('--fold') + 1]) if '--fold' in a else 0
  603. inc = a[a.index('--inc-dir') + 1] if '--inc-dir' in a else None
  604. rep = a[a.index('--report-dir') + 1] if '--report-dir' in a else None
  605. # (round 190nm) --set name=value[,name=value]: override the instruments' settings (variants; numbers parse as such)
  606. if '--set' in a:
  607. for kv in a[a.index('--set') + 1].split(','):
  608. k, v = kv.split('=')
  609. for i in (INSTRUMENTS if inst == 'all' else inst.split(',')):
  610. INSTRUMENTS[i][k] = json.loads(v)
  611. for i in (INSTRUMENTS if inst == 'all' else inst.split(',')):
  612. calibrate(i, root, man, out, holdout, inc, rep, fold)
  613. return 0
  614. if __name__ == '__main__':
  615. sys.exit(main())