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.

ThresholdCalculator.java 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package com.feemers.android.fftdrawer.SignalProcessing;
  2. class ThresholdCalculator {
  3. private double[] m_buffer;
  4. private int m_windowSize;
  5. private int m_bufferCounter;
  6. private int m_bufferInitCounter;
  7. private double m_constantThresholdPart;
  8. private double m_adaptiveThresholdPart;
  9. public ThresholdCalculator(int windowSize) {
  10. if (windowSize <= 0) {
  11. throw new AssertionError("windowSize should be postive");
  12. }
  13. m_windowSize = windowSize;
  14. reset();
  15. }
  16. public double getThreshold() {
  17. // This method is meant for the use inside of a detector implementation
  18. // Should be called every time a new sensor value is available
  19. // Returns the sum of the constant part of the threshold (determined by the user) and the
  20. // adaptive part of the threshold (determined by the noise level of the signal)
  21. return m_constantThresholdPart + m_adaptiveThresholdPart;
  22. }
  23. public void setConstantThresholdPart(double constantThresholdPart) {
  24. // This method should be called when the User changes the constant part of the threshold with the GUI
  25. this.m_constantThresholdPart = constantThresholdPart;
  26. }
  27. public void onNewSample(double sample) {
  28. // store sample
  29. m_buffer[m_bufferCounter] = sample;
  30. // increase counter
  31. m_bufferCounter++;
  32. // check if we are on the end of Array -> go to start
  33. if (m_bufferCounter >= m_windowSize) {
  34. m_bufferCounter = 0;
  35. }
  36. // when we start the application we will have an arry with emty values
  37. // hence we define how many values are already new
  38. // after N_sample == windowSize this will have no further effect
  39. if (m_bufferInitCounter < m_windowSize) {
  40. m_bufferInitCounter++;
  41. }
  42. // now calculate Mean
  43. double absMean = 0;
  44. for (int i = 0; i < m_bufferInitCounter; i++) {
  45. double sampleVal = m_buffer[i];
  46. absMean += Math.sqrt(sampleVal * sampleVal);
  47. }
  48. m_adaptiveThresholdPart = absMean / m_bufferInitCounter;
  49. }
  50. // for reset this class reset
  51. public void reset() {
  52. m_bufferCounter = 0;
  53. m_bufferInitCounter = 0;
  54. m_buffer = new double[m_windowSize];
  55. for (int i = 0; i < m_windowSize; i++) {
  56. m_buffer[i] = 0;
  57. }
  58. }
  59. }