swimtracker-app/data_processing/DataAnalysis.js

81 lines
2.8 KiB
JavaScript
Raw Normal View History

import { PeakDetectorSimple } from './PeakDetection';
2020-07-15 15:53:16 +02:00
import { MovingAverage} from './MovingAverage';
import { List } from 'immutable';
export default class DataAnalysis {
constructor() {
this._resetCache(null, 0);
}
analyze(analysisParameters, sessionId, allMeasurements) {
const cacheValid = (
this.sessionId === sessionId &&
this.analyzedUpToIdx <= allMeasurements.size &&
this.analysisParameters === analysisParameters);
let newData = null;
if (cacheValid) {
newData = allMeasurements.slice(this.analyzedUpToIdx);
}
else {
this._resetCache(analysisParameters, sessionId);
newData = allMeasurements;
2020-06-30 18:06:37 +02:00
console.log("cache reset");
}
2020-07-15 15:53:16 +02:00
const newDataArr = newData.toArray();
// active time
const newAverages = this.movingAverage.addVector(newDataArr);
this.activeMeasurements += newAverages.reduce((n, val) => {
return n + (val >= analysisParameters.activeTimeThreshold);
});
// peaks
2020-07-15 15:53:16 +02:00
const newPeaks = this.peakDetectorSimple.addVector(newDataArr);
this.allPeaks = this.allPeaks.concat(List(newPeaks));
// aggregated sum/max
this.aggregatedMomentum = newData.reduce((sum, x) => sum + x, this.aggregatedMomentum);
this.peakMax = newData.reduce((running, x) => Math.max(x, running), this.peakMax);
// windowed
const windowNumDataPoints = analysisParameters.windowSizeInSecs * analysisParameters.numMeasurementsPerSec;
const windowed = allMeasurements.slice(-windowNumDataPoints);
const peakMaxWindow = windowed.reduce((running, x) => Math.max(x, running), 0);
const momentumWindow = windowed.reduce((sum, x) => sum + x, 0);
2020-07-15 15:53:16 +02:00
this.analyzedUpToIdx = allMeasurements.size;
return {
peaks: this.allPeaks,
totalTime: allMeasurements / analysisParameters.numMeasurementsPerSec,
2020-07-15 15:53:16 +02:00
activeTime: this.activeMeasurements / analysisParameters.numMeasurementsPerSec,
2020-06-30 18:06:37 +02:00
totalMomentum: this.aggregatedMomentum,
peakMax: this.peakMax,
momentumWindow: momentumWindow,
peakMaxWindow: peakMaxWindow,
};
}
_resetCache(analysisParameters, sessionId) {
2020-07-15 15:53:16 +02:00
this.movingAverage = analysisParameters ? new MovingAverage(analysisParameters.movingAverageWindowSize) : null;
this.activeMeasurements = 0;
this.peakDetectorSimple = analysisParameters ? new PeakDetectorSimple(analysisParameters.peakDetectorSimpleThreshold) : null;
this.allPeaks = List();
this.aggregatedMomentum = 0;
this.peakMax = 0;
this.sessionId = sessionId;
this.analyzedUpToIdx = 0;
this.analysisParameters = analysisParameters;
}
};