PolyPurifier.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. // Polyphonic engine - note filter: score each note candidate as a real note or a harmonic "ghost" (an
  2. // overtone of a lower note taken for a note of its own).
  3. //
  4. // Gradient-boosted trees over the features below, trained on mixtures of real instrument
  5. // recordings with known notes (see docs/polyphonic-editing.md): relative energy, how much of the
  6. // candidate's partials it shares with other candidates, whether it moves like an overtone of a
  7. // lower candidate, and so on. All features describe pitched candidates; with neural note evidence
  8. // (Basic Pitch's note posteriors at the candidate's pitch) the "Evidence" model is used, otherwise
  9. // the DSP-only one.
  10. #include "PolyInternal.h"
  11. #include "PolyPurifierModel.h"
  12. #include "PolyGuidedPurifierModel.h"
  13. #include <cassert>
  14. #ifdef POLYPHONIC_DUMP_FEATURES
  15. #include <cstdio>
  16. #endif
  17. namespace polyphonic
  18. {
  19. namespace detail
  20. {
  21. namespace
  22. {
  23. float median(std::vector<float> v)
  24. {
  25. if (v.empty())
  26. return 0.0f;
  27. const size_t n = v.size();
  28. std::nth_element(v.begin(), v.begin() + static_cast<std::ptrdiff_t>(n / 2), v.end());
  29. const float hi = v[n / 2];
  30. if (n % 2)
  31. return hi;
  32. return 0.5f * (hi + *std::max_element(v.begin(), v.begin() + static_cast<std::ptrdiff_t>(n / 2)));
  33. }
  34. double stddev(const std::vector<double>& v)
  35. {
  36. if (v.empty())
  37. return 0.0;
  38. double m = 0.0;
  39. for (double x : v) m += x;
  40. m /= static_cast<double>(v.size());
  41. double s = 0.0;
  42. for (double x : v) s += (x - m) * (x - m);
  43. return std::sqrt(s / static_cast<double>(v.size()));
  44. }
  45. double correlation(const std::vector<double>& a, const std::vector<double>& b)
  46. {
  47. const size_t n = std::min(a.size(), b.size());
  48. if (n < 2)
  49. return 0.0;
  50. double ma = 0.0, mb = 0.0;
  51. for (size_t i = 0; i < n; ++i) { ma += a[i]; mb += b[i]; }
  52. ma /= static_cast<double>(n);
  53. mb /= static_cast<double>(n);
  54. double sab = 0.0, saa = 0.0, sbb = 0.0;
  55. for (size_t i = 0; i < n; ++i)
  56. {
  57. sab += (a[i] - ma) * (b[i] - mb);
  58. saa += (a[i] - ma) * (a[i] - ma);
  59. sbb += (b[i] - mb) * (b[i] - mb);
  60. }
  61. if (saa <= 0.0 || sbb <= 0.0)
  62. return 0.0;
  63. const double r = sab / std::sqrt(saa * sbb);
  64. return (r >= -1.0 && r <= 1.0) ? r : 0.0; // no isfinite(): -ffast-math
  65. }
  66. float predict(const purifier::TreeNode* nodes, const int* starts, int numTrees, float init, float rate,
  67. int numFeatures, const std::vector<float>& x)
  68. {
  69. // the generated model and this file's feature code must agree (retrain after changing features)
  70. assert(static_cast<int>(x.size()) == numFeatures);
  71. if (static_cast<int>(x.size()) != numFeatures)
  72. return 0.5f;
  73. double raw = init;
  74. for (int k = 0; k < numTrees; ++k)
  75. {
  76. int i = starts[k];
  77. while (nodes[i].feature >= 0)
  78. i = (x[static_cast<size_t>(nodes[i].feature)] <= nodes[i].threshold) ? nodes[i].left : nodes[i].right;
  79. raw += static_cast<double>(rate) * nodes[i].value;
  80. }
  81. return static_cast<float>(1.0 / (1.0 + std::exp(-raw)));
  82. }
  83. } // namespace
  84. void scoreCandidates(const Context& ctx, std::vector<Candidate>& cands, const NoteEvidence* evidence,
  85. std::vector<CandidateFeatures>* exportTo)
  86. {
  87. const Params& p = ctx.p;
  88. const auto& pk = ctx.peaks;
  89. const int N = static_cast<int>(cands.size());
  90. if (N == 0)
  91. return;
  92. const float binHz = static_cast<float>(p.sampleRate / p.fftSize);
  93. constexpr int numHarm = 30;
  94. const bool useEvidence = evidence != nullptr && !evidence->empty();
  95. std::vector<float> midi(static_cast<size_t>(N));
  96. for (int i = 0; i < N; ++i)
  97. midi[static_cast<size_t>(i)] = cands[static_cast<size_t>(i)].midi();
  98. // claims table: amplitude at each partial, and per spectral peak its owners (count, highest pitch)
  99. const size_t numPeaks = pk.amp.size();
  100. std::vector<int> ownerCount(numPeaks, 0), lastOwner(numPeaks, -1);
  101. std::vector<float> maxOwnerMidi(numPeaks, -1e9f);
  102. std::vector<std::vector<float>> amps(static_cast<size_t>(N));
  103. std::vector<std::vector<int>> pids(static_cast<size_t>(N));
  104. for (int ni = 0; ni < N; ++ni)
  105. {
  106. const auto& n = cands[static_cast<size_t>(ni)];
  107. auto& am = amps[static_cast<size_t>(ni)];
  108. auto& pi = pids[static_cast<size_t>(ni)];
  109. am.assign(static_cast<size_t>(n.length()) * numHarm, 0.0f);
  110. pi.assign(static_cast<size_t>(n.length()) * numHarm, -1);
  111. for (int i = 0; i < n.length(); ++i)
  112. {
  113. const int t = n.start + i;
  114. if (pk.begin(t) == pk.end(t))
  115. continue;
  116. const float f0 = n.f0[static_cast<size_t>(i)];
  117. for (int h = 1; h <= numHarm; ++h)
  118. {
  119. const float fh = static_cast<float>(f0 * h * std::sqrt(1.0 + n.B * h * h));
  120. if (!(fh < p.sampleRate / 2 - 100))
  121. continue;
  122. const float tol = std::min(std::max(1.2f * binHz, 0.012f * fh), 0.4f * f0);
  123. const int j = pk.nearest(t, fh / binHz);
  124. if (!(std::fabs(pk.fbin[static_cast<size_t>(j)] * binHz - fh) < tol))
  125. continue;
  126. const size_t idx = static_cast<size_t>(i) * numHarm + static_cast<size_t>(h - 1);
  127. am[idx] = pk.amp[static_cast<size_t>(j)];
  128. pi[idx] = j;
  129. if (lastOwner[static_cast<size_t>(j)] != ni)
  130. {
  131. lastOwner[static_cast<size_t>(j)] = ni;
  132. ++ownerCount[static_cast<size_t>(j)];
  133. maxOwnerMidi[static_cast<size_t>(j)] = std::max(maxOwnerMidi[static_cast<size_t>(j)], midi[static_cast<size_t>(ni)]);
  134. }
  135. }
  136. }
  137. }
  138. // relevance of the frame-wise strongest crest, for the relative-strength feature
  139. const auto& r0max = ctx.r0max;
  140. // neural evidence resampled to the analysis frame grid (next evidence frame at or after t)
  141. std::vector<int> evFrame;
  142. if (useEvidence)
  143. {
  144. const int T = ctx.numFrames;
  145. evFrame.resize(static_cast<size_t>(T));
  146. for (int t = 0; t < T; ++t)
  147. {
  148. const float sec = static_cast<float>(t * p.hop / p.sampleRate);
  149. const auto it = std::lower_bound(evidence->frameTimes.begin(), evidence->frameTimes.end(), sec);
  150. evFrame[static_cast<size_t>(t)] = static_cast<int>(std::min<std::ptrdiff_t>(it - evidence->frameTimes.begin(), static_cast<std::ptrdiff_t>(evidence->frameTimes.size()) - 1));
  151. }
  152. }
  153. std::vector<float> x;
  154. for (int ni = 0; ni < N; ++ni)
  155. {
  156. auto& n = cands[static_cast<size_t>(ni)];
  157. const float m = midi[static_cast<size_t>(ni)];
  158. const auto& am = amps[static_cast<size_t>(ni)];
  159. const auto& pi = pids[static_cast<size_t>(ni)];
  160. // ---- relative strength / energy
  161. float ref = 0.0f;
  162. for (int t = n.start; t <= n.end; ++t)
  163. ref = std::max(ref, r0max[static_cast<size_t>(t)]);
  164. const float smax = *std::max_element(n.strength.begin(), n.strength.end());
  165. const double rel = smax / std::max(ref, 1e-12f);
  166. std::vector<int> ov;
  167. double maxEnergy = n.energy;
  168. for (int mi = 0; mi < N; ++mi)
  169. {
  170. const auto& o = cands[static_cast<size_t>(mi)];
  171. if (mi != ni && o.start <= n.end && o.end >= n.start)
  172. {
  173. ov.push_back(mi);
  174. maxEnergy = std::max(maxEnergy, o.energy);
  175. }
  176. }
  177. const double energyRel = n.energy / maxEnergy;
  178. // ---- partial sharing
  179. double tot = 0.0, uniqHi = 0.0, uniqAny = 0.0, f0Share = 0.0;
  180. std::vector<float> f0db;
  181. for (int i = 0; i < n.length(); ++i)
  182. {
  183. float amax = 0.0f;
  184. for (int h = 0; h < numHarm; ++h)
  185. {
  186. const size_t idx = static_cast<size_t>(i) * numHarm + static_cast<size_t>(h);
  187. const double P = static_cast<double>(am[idx]) * am[idx];
  188. amax = std::max(amax, am[idx]);
  189. tot += P;
  190. if (h == 0)
  191. f0Share += P;
  192. const int j = pi[idx];
  193. const bool shHi = j >= 0 && maxOwnerMidi[static_cast<size_t>(j)] > m + 0.5f;
  194. const bool shAny = j >= 0 && ownerCount[static_cast<size_t>(j)] > 1;
  195. if (!shHi) uniqHi += P;
  196. if (!shAny) uniqAny += P;
  197. }
  198. if (amax > 0.0f)
  199. f0db.push_back(20.0f * std::log10(std::max(am[static_cast<size_t>(i) * numHarm], 1e-9f) / amax));
  200. }
  201. tot = std::max(tot, 1e-20);
  202. // ---- overtone relation to a lower candidate: does it move like one of its harmonics?
  203. int bestH = 0, bestDt = 99;
  204. double bestPc = 0.0, bestAc = 0.0;
  205. for (int li = 0; li < N; ++li)
  206. {
  207. if (li == ni || !(midi[static_cast<size_t>(li)] < m - 0.5f))
  208. continue;
  209. const auto& l = cands[static_cast<size_t>(li)];
  210. const int a = std::max(n.start, l.start), b = std::min(n.end, l.end);
  211. if (b - a + 1 < 0.5 * n.length())
  212. continue;
  213. std::vector<float> fu, fl, ratio;
  214. for (int t = a; t <= b; ++t)
  215. {
  216. fu.push_back(n.f0[static_cast<size_t>(t - n.start)]);
  217. fl.push_back(l.f0[static_cast<size_t>(t - l.start)]);
  218. ratio.push_back(fu.back() / fl.back());
  219. }
  220. const int h = static_cast<int>(std::nearbyint(median(ratio)));
  221. if (h < 2 || h > 16)
  222. continue;
  223. const float mfl = median(fl), mfu = median(fu);
  224. const double fh = h * mfl * std::sqrt(1.0 + l.B * h * h);
  225. if (std::fabs(1200.0 * std::log2(mfu / fh)) > 40.0)
  226. continue;
  227. if (!(bestH == 0 || h < bestH))
  228. continue;
  229. std::vector<double> du, dl;
  230. for (size_t q = 0; q < fu.size(); ++q)
  231. {
  232. du.push_back(1200.0 * std::log2(fu[q] / mfu));
  233. dl.push_back(1200.0 * std::log2(fl[q] / mfl));
  234. }
  235. bestPc = (stddev(du) > 3.0 && stddev(dl) > 3.0) ? correlation(du, dl) : 0.0;
  236. bestH = h;
  237. bestDt = std::abs(n.start - l.start);
  238. const auto eu = harmonicEnvelope(ctx, n, 1, a, b);
  239. const auto el = harmonicEnvelope(ctx, l, std::max(1, h + 1), a, b);
  240. std::vector<double> ue(eu.begin(), eu.end()), le(el.begin(), el.end());
  241. bestAc = 0.0;
  242. if (ue.size() > 4 && stddev(ue) > 0.0 && stddev(le) > 0.0 && ue.size() > 5)
  243. {
  244. std::vector<double> dlu, dll;
  245. for (size_t q = 1; q < ue.size(); ++q)
  246. {
  247. dlu.push_back(std::log(ue[q] + 1e-6) - std::log(ue[q - 1] + 1e-6));
  248. dll.push_back(std::log(le[q] + 1e-6) - std::log(le[q - 1] + 1e-6));
  249. }
  250. bestAc = correlation(dlu, dll);
  251. }
  252. }
  253. // ---- sub-harmonic relation: a higher overlapping candidate on this one's h-th partial
  254. int sub = 0;
  255. bool isLowest = true;
  256. for (int mi : ov)
  257. {
  258. const float om = midi[static_cast<size_t>(mi)];
  259. if (!(om > m))
  260. isLowest = false;
  261. if (om <= m + 0.5f)
  262. continue;
  263. const double r = std::pow(2.0, (om - m) / 12.0);
  264. const int h = static_cast<int>(std::nearbyint(r));
  265. if (h >= 2 && h <= 8 && std::fabs(1200.0 * std::log2(r / h)) < 40.0)
  266. sub = sub == 0 ? h : std::min(sub, h);
  267. }
  268. const double dur = n.length() * p.hop / p.sampleRate;
  269. const double f0RelDb = f0db.empty() ? -90.0 : median(f0db);
  270. // feature vector, in the order of PolyPurifierModel.h
  271. x.assign(0, 0.0f);
  272. x.push_back(static_cast<float>(std::log10(std::max(rel, 1e-3))));
  273. x.push_back(static_cast<float>(std::log10(std::max(energyRel, 1e-4))));
  274. x.push_back(static_cast<float>(uniqHi / tot));
  275. x.push_back(static_cast<float>(uniqAny / tot));
  276. x.push_back(static_cast<float>(f0Share / tot));
  277. x.push_back(static_cast<float>(std::max(f0RelDb, -60.0) / 60.0));
  278. x.push_back(static_cast<float>(std::log10(std::max(dur, 0.02))));
  279. x.push_back(static_cast<float>((m - 60.0) / 24.0));
  280. x.push_back(static_cast<float>(std::log2(std::max(n.hits, 1))));
  281. x.push_back(bestH == 2 ? 1.0f : 0.0f);
  282. x.push_back(bestH == 3 ? 1.0f : 0.0f);
  283. x.push_back(bestH >= 4 ? 1.0f : 0.0f);
  284. x.push_back(bestH ? static_cast<float>(std::min(bestDt, 20) / 20.0) : 1.0f);
  285. x.push_back(bestH ? static_cast<float>(bestPc) : 0.0f);
  286. x.push_back(bestH ? static_cast<float>(bestAc) : 0.0f);
  287. x.push_back(sub == 2 ? 1.0f : 0.0f);
  288. x.push_back(sub >= 3 ? 1.0f : 0.0f);
  289. x.push_back(static_cast<float>(std::min(static_cast<int>(ov.size()), 12) / 12.0));
  290. x.push_back(isLowest ? 1.0f : 0.0f);
  291. if (useEvidence)
  292. {
  293. const int k = static_cast<int>(std::nearbyint(m)) - 21;
  294. double bpMean = 0.0, bpMax = 0.0;
  295. if (k >= 0 && k < 88)
  296. {
  297. for (int t = n.start; t <= n.end; ++t)
  298. {
  299. const float v = evidence->note[static_cast<size_t>(evFrame[static_cast<size_t>(t)]) * 88 + static_cast<size_t>(k)];
  300. bpMean += v;
  301. bpMax = std::max(bpMax, static_cast<double>(v));
  302. }
  303. bpMean /= n.length();
  304. }
  305. x.push_back(static_cast<float>(bpMean));
  306. x.push_back(static_cast<float>(bpMax));
  307. if (p.detectionMode == DetectionMode::NeuralGuided)
  308. n.probability = predict(guidedPurifier::kEvidenceNodes, guidedPurifier::kEvidenceTreeStart,
  309. guidedPurifier::kEvidenceNumTrees, guidedPurifier::kEvidenceInit,
  310. guidedPurifier::kEvidenceRate, guidedPurifier::kEvidenceNumFeatures, x);
  311. else
  312. n.probability = predict(purifier::kEvidenceNodes, purifier::kEvidenceTreeStart, purifier::kEvidenceNumTrees,
  313. purifier::kEvidenceInit, purifier::kEvidenceRate, purifier::kEvidenceNumFeatures, x);
  314. }
  315. else
  316. {
  317. n.probability = predict(purifier::kDspNodes, purifier::kDspTreeStart, purifier::kDspNumTrees,
  318. purifier::kDspInit, purifier::kDspRate, purifier::kDspNumFeatures, x);
  319. }
  320. if (exportTo != nullptr)
  321. exportTo->push_back({n.start, n.end, m, n.probability, x});
  322. #ifdef POLYPHONIC_DUMP_FEATURES
  323. std::fprintf(stderr, "feat %d", ni);
  324. for (float v : x)
  325. std::fprintf(stderr, " %.6g", v);
  326. std::fprintf(stderr, " p=%.6g\n", n.probability);
  327. #endif
  328. }
  329. }
  330. } // namespace detail
  331. } // namespace polyphonic