fork(4) download
  1. #include <iostream>
  2. #include <complex>
  3. #include <functional>
  4.  
  5.  
  6. class Kernel {
  7. public:
  8. /*
  9.   Covariance function : return the covariance between two R.V. for the entire kernel's domain definition.
  10.   */
  11. virtual double covarianceFunction(
  12. double X,
  13. double Y
  14. )const = 0 ;
  15. ~Kernel() = default;
  16. };
  17.  
  18.  
  19. template <typename Func>
  20. class FooKernel : public Kernel {
  21. public:
  22.  
  23. FooKernel(Func&& fun) : fun_(std::forward<Func>(fun)) {}
  24. double covarianceFunction(
  25. double X,
  26. double Y
  27. ) const {
  28. return fun_(X, Y);
  29. }
  30. template<class T>
  31. auto operator+(const T b) const {
  32. return make_foo_kernel([b, this](double X, double Y) -> double {
  33. return this->covarianceFunction(X, Y) + b.covarianceFunction(X, Y);
  34. });
  35. }
  36. FooKernel operator=(const FooKernel other) const {
  37. return other;
  38. }
  39. private:
  40. Func fun_;
  41. };
  42.  
  43. template <typename Func>
  44. auto make_foo_kernel(Func&& fun)
  45. {
  46. return FooKernel<Func>(std::forward<Func>(fun));
  47. }
  48.  
  49.  
  50. class GaussianKernel : public Kernel {
  51. public:
  52. GaussianKernel(double sigma, double scale) : m_sigma(sigma), m_scale(scale) {}
  53. GaussianKernel(double sigma) : m_sigma(sigma), m_scale(1) {}
  54. /*
  55.   A well known covariance function that enforces smooth deformations
  56.   Ref : Shape modeling using Gaussian process Morphable Models, Luethi et al.
  57.   */
  58. double covarianceFunction(
  59. double X,
  60. double Y
  61. ) const
  62. {
  63. //use diagonal matrix
  64. double result;
  65. result = m_scale * exp(-std::norm(X - Y) / (m_sigma*m_sigma));
  66. return result;
  67. }
  68. template<class T>
  69. auto operator+(const T b) const {
  70. return make_foo_kernel([b, this](double X, double Y) -> double {
  71. auto debugBval = b.covarianceFunction(X, Y);
  72. auto debugAval = this->covarianceFunction(X, Y);
  73. auto test = debugBval + debugAval;
  74. return test;
  75. });
  76. }
  77. private:
  78. double m_sigma;
  79. double m_scale;
  80. };
  81.  
  82. int main()
  83. {
  84. auto C = GaussianKernel(50,60) + GaussianKernel(100,200);
  85. auto result = C.covarianceFunction(30.0,40.0);
  86.  
  87. return 0;
  88. }
Success #stdin #stdout 0s 4584KB
stdin
Standard input is empty
stdout
Standard output is empty