data analysis scripts
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.2 KiB

  1. #pragma once
  2. #include <cmath>
  3. #include <vector>
  4. #include <assert.h>
  5. inline double gauss(double sigma, double x) {
  6. double expVal = -1 * (pow(x, 2) / pow(2 * sigma, 2));
  7. double divider = sqrt(2 * M_PI * pow(sigma, 2));
  8. return (1 / divider) * exp(expVal);
  9. }
  10. inline std::vector<double> gaussKernel(int samples, double sigma) {
  11. std::vector<double> v;
  12. bool doubleCenter = false;
  13. if (samples % 2 == 0) {
  14. doubleCenter = true;
  15. samples--;
  16. }
  17. int steps = (samples - 1) / 2;
  18. double stepSize = (3 * sigma) / steps;
  19. for (int i = steps; i >= 1; i--) {
  20. v.push_back(gauss(sigma, i * stepSize * -1));
  21. }
  22. std::cout << std::endl;
  23. v.push_back(gauss(sigma, 0));
  24. if (doubleCenter) {
  25. v.push_back(gauss(sigma, 0));
  26. }
  27. for (int i = 1; i <= steps; i++) {
  28. v.push_back(gauss(sigma, i * stepSize));
  29. }
  30. std::cout << "The kernel contains " << v.size() << " entries:";
  31. for (auto it = v.begin(); it != v.end(); ++it) {
  32. std::cout << ' ' << *it;
  33. }
  34. std::cout << std::endl;
  35. assert(v.size() == samples);
  36. return v;
  37. }
  38. inline std::vector<double> gaussSmoothen(std::vector<double> values, double sigma, int samples) {
  39. std::vector<double> out;
  40. auto kernel = gaussKernel(samples, sigma);
  41. int sampleSide = samples / 2;
  42. int valueIdx = samples / 2 + 1;
  43. unsigned long ubound = values.size();
  44. for (unsigned long i = 0; i < ubound; i++) {
  45. double sample = 0;
  46. int sampleCtr = 0;
  47. std::cout << "Now at value" << i << ": ";
  48. for (long j = i - sampleSide; j <= i + sampleSide; j++) {
  49. std::cout << j << " ";
  50. if (j > 0 && j < ubound) {
  51. int sampleWeightIndex = sampleSide + (j - i);
  52. std::cout << "(" << sampleWeightIndex << " [" << kernel[sampleWeightIndex] << "]) ";
  53. sample += kernel[sampleWeightIndex] * values[j];
  54. sampleCtr++;
  55. }
  56. }
  57. double smoothed = sample / (double)sampleCtr;
  58. std::cout << " S: " << sample << " C: " << sampleCtr << " V: " << values[i] << " SM: " << smoothed << std::endl;
  59. out.push_back(smoothed);
  60. }
  61. return out;
  62. }