Added other tests

Added tests for:
-Average (all cases)
-STD (all cases)
-Anomaly detection (on a uniform distribution)
This commit is contained in:
2024-11-21 16:35:08 +01:00
parent 4a97a81d7a
commit d31bedd63e
3 changed files with 155 additions and 11 deletions

View File

@@ -3,6 +3,8 @@
#include <stdbool.h>
#include <math.h>
int outlierCount;
// Variable definition
static float **readings;
static int sensorsNumber;
@@ -35,11 +37,19 @@ void initializeReadings(int numSensors, int windowSize) {
setSlidingWindowSize(windowSize);
}
void freeReadings() {
bool freeReadings() {
for (int i = 0; i < sensorsNumber; i++) {
free(readings[i]);
}
free(readings);
if(readings != NULL){
free(readings);
return true;
}
else{
return false;
}
}
// Functions
@@ -64,6 +74,14 @@ bool isFull(int sensorIndex) {
return true;
}
float getLastReading(int sensorIndex) {
if (isFull(sensorIndex)) {
return readings[sensorIndex][slidingWindowSize - 1];
} else {
return readings[sensorIndex][0];
}
}
// Add a reading to the readings array
void addReading(float value, int sensorIndex) {
if (isFull(sensorIndex)) {
@@ -75,6 +93,8 @@ void addReading(float value, int sensorIndex) {
for (int i = 0; i < slidingWindowSize; i++) {
if (readings[sensorIndex][i] == 0) {
readings[sensorIndex][i] = value;
// Update the position index
break;
}
@@ -99,7 +119,7 @@ float getAverageOnSensor(int sensorIndex) {
float getAverageOnAllSensors() {
float sum = 0;
for (int i = 0; i < sensorsNumber; i++) {
sum += getAverageOnSensor(i);
sum += getLastReading(i);
}
return sum / sensorsNumber;
}
@@ -137,15 +157,33 @@ float getStandardDeviationOnSensor(int sensorIndex) {
float getStandardDeviationOnAllSensors() {
float sum = 0;
float average = getAverageOnAllSensors();
for (int i = 0; i < sensorsNumber; i++) {
sum += getStandardDeviationOnSensor(i);
float lastReading = getLastReading(i);
sum += pow(lastReading - average, 2);
}
return sum / sensorsNumber;
return sqrt(sum / sensorsNumber);
}
void anomalyDetect(float average, float standardDeviation) {
float upperThreshold = average + 2.17 * standardDeviation; // 97% confidence interval
float lowerThreshold = average - 2.17 * standardDeviation; // Lower bound for anomaly detection
outlierCount = 0;
for (int i = 0; i < sensorsNumber; i++) {
for (int j = 0; j < slidingWindowSize; j++) {
if (readings[i][j] > upperThreshold || readings[i][j] < lowerThreshold) {
outlierCount++;
}
}
}
}
float getOverallStandardDeviation() {
float sum = 0;
int totalReadings = 0;
float totalAverage = getOverallAverage();
for (int i = 0; i < sensorsNumber; i++) {
if (!isFull(i)) {
printf("The sliding window for sensor %d is not full\n", i);
@@ -156,5 +194,14 @@ float getOverallStandardDeviation() {
totalReadings++;
}
}
return sqrt(sum / totalReadings);
float totalStandardDeviation = sqrt(sum / totalReadings);
anomalyDetect(totalAverage, totalStandardDeviation);
return totalStandardDeviation;
}
int getOutlierCount() {
return outlierCount;
}