lanczos_smoothing.hpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. // (C) Copyright Nick Thompson 2019.
  2. // Use, modification and distribution are subject to the
  3. // Boost Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef BOOST_MATH_DIFFERENTIATION_LANCZOS_SMOOTHING_HPP
  6. #define BOOST_MATH_DIFFERENTIATION_LANCZOS_SMOOTHING_HPP
  7. #include <cmath> // for std::abs
  8. #include <limits> // to nan initialize
  9. #include <vector>
  10. #include <string>
  11. #include <stdexcept>
  12. #include <boost/assert.hpp>
  13. namespace boost::math::differentiation {
  14. namespace detail {
  15. template <typename Real>
  16. class discrete_legendre {
  17. public:
  18. explicit discrete_legendre(std::size_t n, Real x) : m_n{n}, m_r{2}, m_x{x},
  19. m_qrm2{1}, m_qrm1{x},
  20. m_qrm2p{0}, m_qrm1p{1},
  21. m_qrm2pp{0}, m_qrm1pp{0}
  22. {
  23. using std::abs;
  24. BOOST_ASSERT_MSG(abs(m_x) <= 1, "Three term recurrence is stable only for |x| <=1.");
  25. // The integer n indexes a family of discrete Legendre polynomials indexed by k <= 2*n
  26. }
  27. Real norm_sq(int r) const
  28. {
  29. Real prod = Real(2) / Real(2 * r + 1);
  30. for (int k = -r; k <= r; ++k) {
  31. prod *= Real(2 * m_n + 1 + k) / Real(2 * m_n);
  32. }
  33. return prod;
  34. }
  35. Real next()
  36. {
  37. Real N = 2 * m_n + 1;
  38. Real num = (m_r - 1) * (N * N - (m_r - 1) * (m_r - 1)) * m_qrm2;
  39. Real tmp = (2 * m_r - 1) * m_x * m_qrm1 - num / Real(4 * m_n * m_n);
  40. m_qrm2 = m_qrm1;
  41. m_qrm1 = tmp / m_r;
  42. ++m_r;
  43. return m_qrm1;
  44. }
  45. Real next_prime()
  46. {
  47. Real N = 2 * m_n + 1;
  48. Real s = (m_r - 1) * (N * N - (m_r - 1) * (m_r - 1)) / Real(4 * m_n * m_n);
  49. Real tmp1 = ((2 * m_r - 1) * m_x * m_qrm1 - s * m_qrm2) / m_r;
  50. Real tmp2 = ((2 * m_r - 1) * (m_qrm1 + m_x * m_qrm1p) - s * m_qrm2p) / m_r;
  51. m_qrm2 = m_qrm1;
  52. m_qrm1 = tmp1;
  53. m_qrm2p = m_qrm1p;
  54. m_qrm1p = tmp2;
  55. ++m_r;
  56. return m_qrm1p;
  57. }
  58. Real next_dbl_prime()
  59. {
  60. Real N = 2*m_n + 1;
  61. Real trm1 = 2*m_r - 1;
  62. Real s = (m_r - 1) * (N * N - (m_r - 1) * (m_r - 1)) / Real(4 * m_n * m_n);
  63. Real rqrpp = 2*trm1*m_qrm1p + trm1*m_x*m_qrm1pp - s*m_qrm2pp;
  64. Real tmp1 = ((2 * m_r - 1) * m_x * m_qrm1 - s * m_qrm2) / m_r;
  65. Real tmp2 = ((2 * m_r - 1) * (m_qrm1 + m_x * m_qrm1p) - s * m_qrm2p) / m_r;
  66. m_qrm2 = m_qrm1;
  67. m_qrm1 = tmp1;
  68. m_qrm2p = m_qrm1p;
  69. m_qrm1p = tmp2;
  70. m_qrm2pp = m_qrm1pp;
  71. m_qrm1pp = rqrpp/m_r;
  72. ++m_r;
  73. return m_qrm1pp;
  74. }
  75. Real operator()(Real x, std::size_t k)
  76. {
  77. BOOST_ASSERT_MSG(k <= 2 * m_n, "r <= 2n is required.");
  78. if (k == 0)
  79. {
  80. return 1;
  81. }
  82. if (k == 1)
  83. {
  84. return x;
  85. }
  86. Real qrm2 = 1;
  87. Real qrm1 = x;
  88. Real N = 2 * m_n + 1;
  89. for (std::size_t r = 2; r <= k; ++r) {
  90. Real num = (r - 1) * (N * N - (r - 1) * (r - 1)) * qrm2;
  91. Real tmp = (2 * r - 1) * x * qrm1 - num / Real(4 * m_n * m_n);
  92. qrm2 = qrm1;
  93. qrm1 = tmp / r;
  94. }
  95. return qrm1;
  96. }
  97. Real prime(Real x, std::size_t k) {
  98. BOOST_ASSERT_MSG(k <= 2 * m_n, "r <= 2n is required.");
  99. if (k == 0) {
  100. return 0;
  101. }
  102. if (k == 1) {
  103. return 1;
  104. }
  105. Real qrm2 = 1;
  106. Real qrm1 = x;
  107. Real qrm2p = 0;
  108. Real qrm1p = 1;
  109. Real N = 2 * m_n + 1;
  110. for (std::size_t r = 2; r <= k; ++r) {
  111. Real s =
  112. (r - 1) * (N * N - (r - 1) * (r - 1)) / Real(4 * m_n * m_n);
  113. Real tmp1 = ((2 * r - 1) * x * qrm1 - s * qrm2) / r;
  114. Real tmp2 = ((2 * r - 1) * (qrm1 + x * qrm1p) - s * qrm2p) / r;
  115. qrm2 = qrm1;
  116. qrm1 = tmp1;
  117. qrm2p = qrm1p;
  118. qrm1p = tmp2;
  119. }
  120. return qrm1p;
  121. }
  122. private:
  123. std::size_t m_n;
  124. std::size_t m_r;
  125. Real m_x;
  126. Real m_qrm2;
  127. Real m_qrm1;
  128. Real m_qrm2p;
  129. Real m_qrm1p;
  130. Real m_qrm2pp;
  131. Real m_qrm1pp;
  132. };
  133. template <class Real>
  134. std::vector<Real> interior_velocity_filter(std::size_t n, std::size_t p) {
  135. auto dlp = discrete_legendre<Real>(n, 0);
  136. std::vector<Real> coeffs(p+1);
  137. coeffs[1] = 1/dlp.norm_sq(1);
  138. for (std::size_t l = 3; l < p + 1; l += 2)
  139. {
  140. dlp.next_prime();
  141. coeffs[l] = dlp.next_prime()/ dlp.norm_sq(l);
  142. }
  143. // We could make the filter length n, as f[0] = 0,
  144. // but that'd make the indexing awkward when applying the filter.
  145. std::vector<Real> f(n + 1);
  146. // This value should never be read, but this is the correct value *if it is read*.
  147. // Hmm, should it be a nan then? I'm not gonna agonize.
  148. f[0] = 0;
  149. for (std::size_t j = 1; j < f.size(); ++j)
  150. {
  151. Real arg = Real(j) / Real(n);
  152. dlp = discrete_legendre<Real>(n, arg);
  153. f[j] = coeffs[1]*arg;
  154. for (std::size_t l = 3; l <= p; l += 2)
  155. {
  156. dlp.next();
  157. f[j] += coeffs[l]*dlp.next();
  158. }
  159. f[j] /= (n * n);
  160. }
  161. return f;
  162. }
  163. template <class Real>
  164. std::vector<Real> boundary_velocity_filter(std::size_t n, std::size_t p, int64_t s)
  165. {
  166. std::vector<Real> coeffs(p+1, std::numeric_limits<Real>::quiet_NaN());
  167. Real sn = Real(s) / Real(n);
  168. auto dlp = discrete_legendre<Real>(n, sn);
  169. coeffs[0] = 0;
  170. coeffs[1] = 1/dlp.norm_sq(1);
  171. for (std::size_t l = 2; l < p + 1; ++l)
  172. {
  173. // Calculation of the norms is common to all filters,
  174. // so it seems like an obvious optimization target.
  175. // I tried this: The spent in computing the norms time is not negligible,
  176. // but still a small fraction of the total compute time.
  177. // Hence I'm not refactoring out these norm calculations.
  178. coeffs[l] = dlp.next_prime()/ dlp.norm_sq(l);
  179. }
  180. std::vector<Real> f(2*n + 1);
  181. for (std::size_t k = 0; k < f.size(); ++k)
  182. {
  183. Real j = Real(k) - Real(n);
  184. Real arg = j/Real(n);
  185. dlp = discrete_legendre<Real>(n, arg);
  186. f[k] = coeffs[1]*arg;
  187. for (std::size_t l = 2; l <= p; ++l)
  188. {
  189. f[k] += coeffs[l]*dlp.next();
  190. }
  191. f[k] /= (n * n);
  192. }
  193. return f;
  194. }
  195. template <class Real>
  196. std::vector<Real> acceleration_filter(std::size_t n, std::size_t p, int64_t s)
  197. {
  198. BOOST_ASSERT_MSG(p <= 2*n, "Approximation order must be <= 2*n");
  199. BOOST_ASSERT_MSG(p > 2, "Approximation order must be > 2");
  200. std::vector<Real> coeffs(p+1, std::numeric_limits<Real>::quiet_NaN());
  201. Real sn = Real(s) / Real(n);
  202. auto dlp = discrete_legendre<Real>(n, sn);
  203. coeffs[0] = 0;
  204. coeffs[1] = 0;
  205. for (std::size_t l = 2; l < p + 1; ++l)
  206. {
  207. coeffs[l] = dlp.next_dbl_prime()/ dlp.norm_sq(l);
  208. }
  209. std::vector<Real> f(2*n + 1, 0);
  210. for (std::size_t k = 0; k < f.size(); ++k)
  211. {
  212. Real j = Real(k) - Real(n);
  213. Real arg = j/Real(n);
  214. dlp = discrete_legendre<Real>(n, arg);
  215. for (std::size_t l = 2; l <= p; ++l)
  216. {
  217. f[k] += coeffs[l]*dlp.next();
  218. }
  219. f[k] /= (n * n * n);
  220. }
  221. return f;
  222. }
  223. } // namespace detail
  224. template <typename Real, std::size_t order = 1>
  225. class discrete_lanczos_derivative {
  226. public:
  227. discrete_lanczos_derivative(Real const & spacing,
  228. std::size_t n = 18,
  229. std::size_t approximation_order = 3)
  230. : m_dt{spacing}
  231. {
  232. static_assert(!std::is_integral_v<Real>,
  233. "Spacing must be a floating point type.");
  234. BOOST_ASSERT_MSG(spacing > 0,
  235. "Spacing between samples must be > 0.");
  236. if constexpr (order == 1)
  237. {
  238. BOOST_ASSERT_MSG(approximation_order <= 2 * n,
  239. "The approximation order must be <= 2n");
  240. BOOST_ASSERT_MSG(approximation_order >= 2,
  241. "The approximation order must be >= 2");
  242. if constexpr (std::is_same_v<Real, float> || std::is_same_v<Real, double>)
  243. {
  244. auto interior = detail::interior_velocity_filter<long double>(n, approximation_order);
  245. m_f.resize(interior.size());
  246. for (std::size_t j = 0; j < interior.size(); ++j)
  247. {
  248. m_f[j] = static_cast<Real>(interior[j])/m_dt;
  249. }
  250. }
  251. else
  252. {
  253. m_f = detail::interior_velocity_filter<Real>(n, approximation_order);
  254. for (auto & x : m_f)
  255. {
  256. x /= m_dt;
  257. }
  258. }
  259. m_boundary_filters.resize(n);
  260. // This for loop is a natural candidate for parallelization.
  261. // But does it matter? Probably not.
  262. for (std::size_t i = 0; i < n; ++i)
  263. {
  264. if constexpr (std::is_same_v<Real, float> || std::is_same_v<Real, double>)
  265. {
  266. int64_t s = static_cast<int64_t>(i) - static_cast<int64_t>(n);
  267. auto bf = detail::boundary_velocity_filter<long double>(n, approximation_order, s);
  268. m_boundary_filters[i].resize(bf.size());
  269. for (std::size_t j = 0; j < bf.size(); ++j)
  270. {
  271. m_boundary_filters[i][j] = static_cast<Real>(bf[j])/m_dt;
  272. }
  273. }
  274. else
  275. {
  276. int64_t s = static_cast<int64_t>(i) - static_cast<int64_t>(n);
  277. m_boundary_filters[i] = detail::boundary_velocity_filter<Real>(n, approximation_order, s);
  278. for (auto & bf : m_boundary_filters[i])
  279. {
  280. bf /= m_dt;
  281. }
  282. }
  283. }
  284. }
  285. else if constexpr (order == 2)
  286. {
  287. // High precision isn't warranted for small p; only for large p.
  288. // (The computation appears stable for large n.)
  289. // But given that the filters are reusable for many vectors,
  290. // it's better to do a high precision computation and then cast back,
  291. // since the resulting cost is a factor of 2, and the cost of the filters not working is hours of debugging.
  292. if constexpr (std::is_same_v<Real, double> || std::is_same_v<Real, float>)
  293. {
  294. auto f = detail::acceleration_filter<long double>(n, approximation_order, 0);
  295. m_f.resize(n+1);
  296. for (std::size_t i = 0; i < m_f.size(); ++i)
  297. {
  298. m_f[i] = static_cast<Real>(f[i+n])/(m_dt*m_dt);
  299. }
  300. m_boundary_filters.resize(n);
  301. for (std::size_t i = 0; i < n; ++i)
  302. {
  303. int64_t s = static_cast<int64_t>(i) - static_cast<int64_t>(n);
  304. auto bf = detail::acceleration_filter<long double>(n, approximation_order, s);
  305. m_boundary_filters[i].resize(bf.size());
  306. for (std::size_t j = 0; j < bf.size(); ++j)
  307. {
  308. m_boundary_filters[i][j] = static_cast<Real>(bf[j])/(m_dt*m_dt);
  309. }
  310. }
  311. }
  312. else
  313. {
  314. // Given that the purpose is denoising, for higher precision calculations,
  315. // the default precision should be fine.
  316. auto f = detail::acceleration_filter<Real>(n, approximation_order, 0);
  317. m_f.resize(n+1);
  318. for (std::size_t i = 0; i < m_f.size(); ++i)
  319. {
  320. m_f[i] = f[i+n]/(m_dt*m_dt);
  321. }
  322. m_boundary_filters.resize(n);
  323. for (std::size_t i = 0; i < n; ++i)
  324. {
  325. int64_t s = static_cast<int64_t>(i) - static_cast<int64_t>(n);
  326. m_boundary_filters[i] = detail::acceleration_filter<Real>(n, approximation_order, s);
  327. for (auto & bf : m_boundary_filters[i])
  328. {
  329. bf /= (m_dt*m_dt);
  330. }
  331. }
  332. }
  333. }
  334. else
  335. {
  336. BOOST_ASSERT_MSG(false, "Derivatives of order 3 and higher are not implemented.");
  337. }
  338. }
  339. Real get_spacing() const
  340. {
  341. return m_dt;
  342. }
  343. template<class RandomAccessContainer>
  344. Real operator()(RandomAccessContainer const & v, std::size_t i) const
  345. {
  346. static_assert(std::is_same_v<typename RandomAccessContainer::value_type, Real>,
  347. "The type of the values in the vector provided does not match the type in the filters.");
  348. BOOST_ASSERT_MSG(std::size(v) >= m_boundary_filters[0].size(),
  349. "Vector must be at least as long as the filter length");
  350. if constexpr (order==1)
  351. {
  352. if (i >= m_f.size() - 1 && i <= std::size(v) - m_f.size())
  353. {
  354. // The filter has length >= 1:
  355. Real dvdt = m_f[1] * (v[i + 1] - v[i - 1]);
  356. for (std::size_t j = 2; j < m_f.size(); ++j)
  357. {
  358. dvdt += m_f[j] * (v[i + j] - v[i - j]);
  359. }
  360. return dvdt;
  361. }
  362. // m_f.size() = N+1
  363. if (i < m_f.size() - 1)
  364. {
  365. auto &bf = m_boundary_filters[i];
  366. Real dvdt = bf[0]*v[0];
  367. for (std::size_t j = 1; j < bf.size(); ++j)
  368. {
  369. dvdt += bf[j] * v[j];
  370. }
  371. return dvdt;
  372. }
  373. if (i > std::size(v) - m_f.size() && i < std::size(v))
  374. {
  375. int k = std::size(v) - 1 - i;
  376. auto &bf = m_boundary_filters[k];
  377. Real dvdt = bf[0]*v[std::size(v)-1];
  378. for (std::size_t j = 1; j < bf.size(); ++j)
  379. {
  380. dvdt += bf[j] * v[std::size(v) - 1 - j];
  381. }
  382. return -dvdt;
  383. }
  384. }
  385. else if constexpr (order==2)
  386. {
  387. if (i >= m_f.size() - 1 && i <= std::size(v) - m_f.size())
  388. {
  389. Real d2vdt2 = m_f[0]*v[i];
  390. for (std::size_t j = 1; j < m_f.size(); ++j)
  391. {
  392. d2vdt2 += m_f[j] * (v[i + j] + v[i - j]);
  393. }
  394. return d2vdt2;
  395. }
  396. // m_f.size() = N+1
  397. if (i < m_f.size() - 1)
  398. {
  399. auto &bf = m_boundary_filters[i];
  400. Real d2vdt2 = bf[0]*v[0];
  401. for (std::size_t j = 1; j < bf.size(); ++j)
  402. {
  403. d2vdt2 += bf[j] * v[j];
  404. }
  405. return d2vdt2;
  406. }
  407. if (i > std::size(v) - m_f.size() && i < std::size(v))
  408. {
  409. int k = std::size(v) - 1 - i;
  410. auto &bf = m_boundary_filters[k];
  411. Real d2vdt2 = bf[0] * v[std::size(v) - 1];
  412. for (std::size_t j = 1; j < bf.size(); ++j)
  413. {
  414. d2vdt2 += bf[j] * v[std::size(v) - 1 - j];
  415. }
  416. return d2vdt2;
  417. }
  418. }
  419. // OOB access:
  420. std::string msg = "Out of bounds access in Lanczos derivative.";
  421. msg += "Input vector has length " + std::to_string(std::size(v)) + ", but user requested access at index " + std::to_string(i) + ".";
  422. throw std::out_of_range(msg);
  423. return std::numeric_limits<Real>::quiet_NaN();
  424. }
  425. template<class RandomAccessContainer>
  426. void operator()(RandomAccessContainer const & v, RandomAccessContainer & w) const
  427. {
  428. static_assert(std::is_same_v<typename RandomAccessContainer::value_type, Real>,
  429. "The type of the values in the vector provided does not match the type in the filters.");
  430. if (&w[0] == &v[0])
  431. {
  432. throw std::logic_error("This transform cannot be performed in-place.");
  433. }
  434. if (std::size(v) < m_boundary_filters[0].size())
  435. {
  436. std::string msg = "The input vector must be at least as long as the filter length. ";
  437. msg += "The input vector has length = " + std::to_string(std::size(v)) + ", the filter has length " + std::to_string(m_boundary_filters[0].size());
  438. throw std::length_error(msg);
  439. }
  440. if (std::size(w) < std::size(v))
  441. {
  442. std::string msg = "The output vector (containing the derivative) must be at least as long as the input vector.";
  443. msg += "The output vector has length = " + std::to_string(std::size(w)) + ", the input vector has length " + std::to_string(std::size(v));
  444. throw std::length_error(msg);
  445. }
  446. if constexpr (order==1)
  447. {
  448. for (std::size_t i = 0; i < m_f.size() - 1; ++i)
  449. {
  450. auto &bf = m_boundary_filters[i];
  451. Real dvdt = bf[0] * v[0];
  452. for (std::size_t j = 1; j < bf.size(); ++j)
  453. {
  454. dvdt += bf[j] * v[j];
  455. }
  456. w[i] = dvdt;
  457. }
  458. for(std::size_t i = m_f.size() - 1; i <= std::size(v) - m_f.size(); ++i)
  459. {
  460. Real dvdt = m_f[1] * (v[i + 1] - v[i - 1]);
  461. for (std::size_t j = 2; j < m_f.size(); ++j)
  462. {
  463. dvdt += m_f[j] *(v[i + j] - v[i - j]);
  464. }
  465. w[i] = dvdt;
  466. }
  467. for(std::size_t i = std::size(v) - m_f.size() + 1; i < std::size(v); ++i)
  468. {
  469. int k = std::size(v) - 1 - i;
  470. auto &f = m_boundary_filters[k];
  471. Real dvdt = f[0] * v[std::size(v) - 1];;
  472. for (std::size_t j = 1; j < f.size(); ++j)
  473. {
  474. dvdt += f[j] * v[std::size(v) - 1 - j];
  475. }
  476. w[i] = -dvdt;
  477. }
  478. }
  479. else if constexpr (order==2)
  480. {
  481. // m_f.size() = N+1
  482. for (std::size_t i = 0; i < m_f.size() - 1; ++i)
  483. {
  484. auto &bf = m_boundary_filters[i];
  485. Real d2vdt2 = 0;
  486. for (std::size_t j = 0; j < bf.size(); ++j)
  487. {
  488. d2vdt2 += bf[j] * v[j];
  489. }
  490. w[i] = d2vdt2;
  491. }
  492. for (std::size_t i = m_f.size() - 1; i <= std::size(v) - m_f.size(); ++i)
  493. {
  494. Real d2vdt2 = m_f[0]*v[i];
  495. for (std::size_t j = 1; j < m_f.size(); ++j)
  496. {
  497. d2vdt2 += m_f[j] * (v[i + j] + v[i - j]);
  498. }
  499. w[i] = d2vdt2;
  500. }
  501. for (std::size_t i = std::size(v) - m_f.size() + 1; i < std::size(v); ++i)
  502. {
  503. int k = std::size(v) - 1 - i;
  504. auto &bf = m_boundary_filters[k];
  505. Real d2vdt2 = bf[0] * v[std::size(v) - 1];
  506. for (std::size_t j = 1; j < bf.size(); ++j)
  507. {
  508. d2vdt2 += bf[j] * v[std::size(v) - 1 - j];
  509. }
  510. w[i] = d2vdt2;
  511. }
  512. }
  513. }
  514. template<class RandomAccessContainer>
  515. RandomAccessContainer operator()(RandomAccessContainer const & v) const
  516. {
  517. RandomAccessContainer w(std::size(v));
  518. this->operator()(v, w);
  519. return w;
  520. }
  521. // Don't copy; too big.
  522. discrete_lanczos_derivative( const discrete_lanczos_derivative & ) = delete;
  523. discrete_lanczos_derivative& operator=(const discrete_lanczos_derivative&) = delete;
  524. // Allow moves:
  525. discrete_lanczos_derivative(discrete_lanczos_derivative&&) = default;
  526. discrete_lanczos_derivative& operator=(discrete_lanczos_derivative&&) = default;
  527. private:
  528. std::vector<Real> m_f;
  529. std::vector<std::vector<Real>> m_boundary_filters;
  530. Real m_dt;
  531. };
  532. } // namespaces
  533. #endif