Page MenuHomePhorge

StateHandler.cpp
No OneTemporary

Size
20 KB
Referenced Files
None
Subscribers
None

StateHandler.cpp

#include "StateHandler.h"
#include <algorithm>
#include "printError.h"
#include "rlutil.h"
//TODO: also change also hardcoded value in "SlaveAgentHandlerOfAgent.cpp"
#define SLIDINGWINDOWSIZE 3 //3 //10
#define STABLENUMBER 2 //2 //8
#define STABLETHRESHOLD (float)0.04 //0.4 //0.03
#define RELATEDTHRESHOLD (float)0.08 //0.08
#define INJECTIONPARTITIONING 5
#define CMPDISTANCE 3
#define THDRIFT (float)0.08 //0.8
#define MINNUMTOBEVALIDSTATE 11 //11 //8 //10
using namespace rlutil;
void StateHandler::initStateHandler() {
flagVariablesWereStable = false;
slidingWindowBufferSize = SLIDINGWINDOWSIZE;
minNumOfRelatedValuesToBeStable = STABLENUMBER;
thresholdToBeStable = STABLETHRESHOLD;
thresholdToBeRelated = RELATEDTHRESHOLD;
discreteAveragePartitionSize = INJECTIONPARTITIONING;
compareDistanceDiscreteAveragePartition = CMPDISTANCE;
thresholdNotDrift = THDRIFT;
minNumToBeValidState = MINNUMTOBEVALIDSTATE;
activeState = NULL;
//XXX - only for now:
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\Bearing-DefectWithoutLoad.csv");
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\Bearing-DefectWithLoad.csv");
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\ChangeSpeed.csv");
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut.csv");
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\NormalOperationChangingLoad.csv");
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\NormalOperation.csv");
csv_writer = new CSV_Writer("C:\\csv-data\\NormalOperation.csv");
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut4pc.csv");
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut5pc.csv");
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut6pc.csv");
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut7pc.csv");
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut8pc.csv");
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut9pc.csv");
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut10pc.csv");
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\WearOut20pc.csv");
//csv_writer = new CSV_Writer("CSV Writer", "C:\\csv-data\\Wearing-out-HedyehNew.csv");
//printf("jetzt");
//getchar();
}
StateHandler::StateHandler() {
setName(NO_NAME);
initStateHandler();
}
StateHandler::StateHandler(char* name) {
setName(name);
initStateHandler();
}
bool StateHandler::setDiscreteAveragePartitionSize(unsigned int discreteAveragePartitionSize) {
if (discreteAveragePartitionSize > 0) {
this->discreteAveragePartitionSize = discreteAveragePartitionSize;
return true;
}
return false;
}
unsigned int StateHandler::getDiscreteAveragePartitionSize() {
return discreteAveragePartitionSize;
}
bool StateHandler::addVariable(vector<SlaveAgentSlotOfAgent*>* vVariables, SlaveAgentSlotOfAgent* slot) {
if (vVariables != NULL && slot != NULL) {
if (find((*vVariables).begin(), (*vVariables).end(), slot) == (*vVariables).end()) {
try {
(*vVariables).push_back(slot);
return true;
}
catch (bad_alloc& error) {
printError("bad_alloc caught: ", error.what());
}
}
}
return false;
}
bool StateHandler::addInputVariable(SlaveAgentSlotOfAgent* slot) {
return addVariable(&vInputVariables, slot);
}
bool StateHandler::addOutputVariable(SlaveAgentSlotOfAgent* slot) {
return addVariable(&vOutputVariables, slot);
}
bool StateHandler::setSlidingWindowBufferSize(unsigned int slidingWindowBufferSize) {
if (slidingWindowBufferSize >= minNumOfRelatedValuesToBeStable) {
this->slidingWindowBufferSize = slidingWindowBufferSize;
return true;
}
return false;
}
bool StateHandler::setMinNumOfRelatedValuesToBeStable(unsigned int minNumOfRelatedValuesToBeStable) {
if (minNumOfRelatedValuesToBeStable <= slidingWindowBufferSize) {
this->minNumOfRelatedValuesToBeStable = minNumOfRelatedValuesToBeStable;
return true;
}
return false;
}
bool StateHandler::setThresholdToBeStable(float thresholdToBeStable) {
if (thresholdToBeStable >= 0 && thresholdToBeStable <= 1) {
this->thresholdToBeStable = thresholdToBeStable;
return true;
}
return false;
}
bool StateHandler::setThresholdToBeRelated(float thresholdToBeRelated) {
if (thresholdToBeRelated >= 0 && thresholdToBeRelated <= 1) {
this->thresholdToBeRelated = thresholdToBeRelated;
return true;
}
return false;
}
bool StateHandler::variableIsStable(SlaveAgentSlotOfAgent* variable) {
if ((variable->getHistoryLength() >= slidingWindowBufferSize - 1) && (variable->getNumberOfRelativesToActualValue(thresholdToBeStable) >= minNumOfRelatedValuesToBeStable)) //-1 because actual value is not in the history
return true;
return false;
}
bool StateHandler::variablesAreStable(vector<SlaveAgentSlotOfAgent*>* vVariables) {
bool flagAllVariablesAreStable = true;
for (auto &slot : *vVariables) {
if (slot->getHistoryLength() >= slidingWindowBufferSize - 1) { //-1 because actual value is not in the history
if (slot->getNumberOfRelativesToActualValue(thresholdToBeStable) < minNumOfRelatedValuesToBeStable) { //-1 because actual value is also on of minNumOfRelatedValuesToBeStable
flagAllVariablesAreStable = false;
}
}
else {
return false;
}
}
return flagAllVariablesAreStable;
}
State* StateHandler::makeNewState() {
printf(" >> New State\n");
State* state = new (nothrow) State();
if (state != NULL) {
bool flagLoadVariablesWorked = true;
for (auto &slot : vInputVariables) {
if (!state->addInputSubState(slot))
flagLoadVariablesWorked = false;
}
for (auto &slot : vOutputVariables) {
if (!state->addOutputSubState(slot))
flagLoadVariablesWorked = false;
}
if (!flagLoadVariablesWorked) {
delete state;
return NULL;
}
}
else {
return NULL;
}
return state;
}
bool StateHandler::addActiveStateToStateVector() {
printf(" >> Save Active State\n");
if (activeState != NULL) {
for (auto &state : vStates) {
if (state == activeState)
return true;
}
try {
vStates.push_back(activeState);
return true;
}
catch (bad_alloc& error) {
printError("bad_alloc caught: ", error.what());
delete activeState;
}
}
return false;
}
/*
bool StateHandler::addStateAndMakeItActive() {
State* state = addState();
if (state != NULL) {
activeState = state;
return true;
}
return false;
}
*/
bool StateHandler::makeNewActiveState() {
State* state = makeNewState();
if (state != NULL) {
activeState = state;
return true;
}
return false;
}
State* StateHandler::findRelatedState() {
for (auto &state : vStates) {
if (state->inputVariablesAreRelated(thresholdToBeRelated) && state->outputVariablesAreRelated(thresholdToBeRelated)) {
return state;
}
}
return NULL;
}
bool StateHandler::findRelatedStateAndMakeItActive() {
State* state = findRelatedState();
if (state != NULL) {
activeState = state;
return true;
}
return false;
}
void StateHandler::eraseStatesWithLessInjections() {
if (activeState != NULL) {
if (activeState->getNumOfInjections() < minNumToBeValidState) {
activeState = NULL;
}
}
for (vector<State*>::iterator state = vStates.begin(); state < vStates.end(); state++) {
if ((*state)->getNumOfInjections() < minNumToBeValidState) {
//TODO: also delete all subStates (etc.) of the State? Because: Memory Leakage.
vStates.erase(state);
state--;
}
}
/*
for (auto &state : vStates) {
//TODO: also delete all subStates (etc.) of the State? Because: Memory Leakage.
if (state->getNumOfInjections() < minNumToBeValidState) {
vStates.erase(state);
}
}
*/
}
//XXX - only for now
bool test = true;
unsigned int brokenCounter = 0, driftCounter = 0;
void printDrift() {
driftCounter++;
setColor(YELLOW);
printf(" >> DRIFT\n");
setColor(GREY);
test = true;
}
void printBroken() {
brokenCounter++;
setColor(LIGHTRED);
printf(" >> BROKEN\n");
setColor(GREY);
test = true;
}
//XXX - only for now
unsigned int old_cycle = 1;
void StateHandler::trigger(unsigned int cycle) {
printf("cycle: %u\n", cycle);
//XXX - only for now
for (unsigned int i = 1; i < (cycle - old_cycle); i++) {
csv_writer->make_new_field();
csv_writer->make_new_field();
csv_writer->make_new_field();
csv_writer->make_new_line();
//printf("%u\n", i);
}
old_cycle = cycle;
//getchar();
if (variablesAreStable(&vInputVariables) && variablesAreStable(&vOutputVariables)) {
printf(" > stable\n");
//XXX - only for now
csv_writer->write_field(2); //stable
csv_writer->make_new_field();
//getchar();
if (activeState == NULL && vStates.empty()) {
makeNewActiveState();
activeState->injectValues(discreteAveragePartitionSize);
//XXX - only for now
csv_writer->write_field(1); //new active state
csv_writer->make_new_field();
csv_writer->make_new_field();
}
else {
if (activeState != NULL) {
printf("\nbeginning here:\n");
bool flagInputUnchanged = activeState->inputVariablesAreRelated(thresholdToBeRelated);
bool flagOutputUnchanged = activeState->outputVariablesAreRelated(thresholdToBeRelated);
//input and/or output unchanged?
if (flagInputUnchanged && flagOutputUnchanged) {
activeState->injectValues(discreteAveragePartitionSize);
if (!activeState->checkAllVariablesForNotDrifting(discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition, thresholdNotDrift)) {
printDrift();
//XXX - only for now
csv_writer->make_new_field();
csv_writer->write_field(1); //drift
csv_writer->make_new_field();
}
//XXX - only for now
else {
csv_writer->make_new_field();
csv_writer->make_new_field();
}
}
else {
if (activeState->getNumOfInjections() >= minNumToBeValidState) {
if ((!flagInputUnchanged && flagOutputUnchanged) || (flagInputUnchanged && !flagOutputUnchanged)) {
printBroken();
getchar();
//XXX - only for now
csv_writer->make_new_field();
csv_writer->write_field(2); //broken
csv_writer->make_new_field();
}
else {
addActiveStateToStateVector();
if (!findRelatedStateAndMakeItActive()) {
makeNewActiveState();
activeState->injectValues(discreteAveragePartitionSize);
//XXX - only for now
csv_writer->write_field(1); //new active state
csv_writer->make_new_field();
csv_writer->make_new_field();
}
else {
//next line is new
activeState->resetDiscreteAveragePartitionCounter();
//XXX - only for now
csv_writer->write_field(2); //change to existing state
csv_writer->make_new_field();
activeState->injectValues(discreteAveragePartitionSize);
if (!activeState->checkAllVariablesForNotDrifting(discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition, thresholdNotDrift)) {
printDrift();
//XXX - only for now
csv_writer->write_field(1); //drift
csv_writer->make_new_field();
}
//XXX - only for now
else {
csv_writer->make_new_field();
}
}
}
}
else {
delete activeState;
if (!findRelatedStateAndMakeItActive()) {
makeNewActiveState();
activeState->injectValues(discreteAveragePartitionSize);
//XXX - only for now
csv_writer->write_field(1); //new active state
csv_writer->make_new_field();
csv_writer->make_new_field();
}
else {
//next line is new
activeState->resetDiscreteAveragePartitionCounter();
//XXX - only for now
csv_writer->write_field(2); //change to existing state
csv_writer->make_new_field();
activeState->injectValues(discreteAveragePartitionSize);
if (!activeState->checkAllVariablesForNotDrifting(discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition, thresholdNotDrift)) {
printDrift();
//XXX - only for now
csv_writer->write_field(1); //drift
csv_writer->make_new_field();
}
//XXX - only for now
else {
csv_writer->make_new_field();
}
}
}
}
}
else {
if (!findRelatedStateAndMakeItActive()) {
makeNewActiveState();
activeState->injectValues(discreteAveragePartitionSize);
//XXX - only for now
csv_writer->write_field(1); //new active state
csv_writer->make_new_field();
csv_writer->make_new_field();
}
else {
//next line is new
activeState->resetDiscreteAveragePartitionCounter();
//XXX - only for now
csv_writer->write_field(2); //change to existing state
csv_writer->make_new_field();
activeState->injectValues(discreteAveragePartitionSize);
if (!activeState->checkAllVariablesForNotDrifting(discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition, thresholdNotDrift)) {
printDrift();
//XXX - only for now
csv_writer->write_field(1); //drift
csv_writer->make_new_field();
}
//XXX - only for now
else {
csv_writer->make_new_field();
}
}
}
}
if (activeState != NULL) {
printf(" -- an activeState exist: \n");
printf(" --- injections: %u\n", activeState->getNumOfInjections());
//XXX - only for now
csv_writer->write_field((int)activeState->getNumOfInjections()); //number of injections
csv_writer->make_new_line();
}
//XXX - only for now
else {
csv_writer->make_new_field();
}
printf(" -- Number of States (excl. activeState): %u\n", vStates.size());
for (auto &s : vStates) {
printf(" --- injections: %u\n", s->getNumOfInjections());
}
printf(" ... BrokenCounter: %u\n", brokenCounter);
printf(" ... driftCounter: %u\n", driftCounter);
printf("cycle: %u\n", cycle);
if (test) {
test = false;
//getchar();
}
/*
if (vStates.empty()) {
//XXX - What to do if addStateAndMakeItActive returns a false?
addStateAndMakeItActive();
//XXX - What to do if injectValues returns a false?
activeState->injectValues(discreteAveragePartitionSize);
}
else {
bool flagInputUnchanged = false;
bool flagOutputUnchanged = false;
if (activeState != NULL) {
activeState->inputVariablesAreRelated(thresholdToBeRelated);
activeState->outputVariablesAreRelated(thresholdToBeRelated);
}
if (flagInputUnchanged && flagOutputUnchanged) {
printf(" >> unchanged\n");
//XXX - What to do if injectValues returns a false?
activeState->injectValues(discreteAveragePartitionSize);
//Check for drift
if (!activeState->checkAllVariablesForNotDrifting(discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition, thresholdNotDrift)) {
driftCounter++;
setColor(TXTCOLOR_YELLOW);
printf(" >> DRIFT\n");
setColor(GREY);
test = true;
}
}
else if ((!flagInputUnchanged && !flagOutputUnchanged)) {
printf(" >> changed\n");
eraseStatesWithLessInjections();
if (!findRelatedStateAndMakeItActive()) {
//XXX - What to do if addStateAndMakeItActive returns a false?
addStateAndMakeItActive();
}
//XXX - What to do if injectValues returns a false?
activeState->injectValues(discreteAveragePartitionSize);
//Check for drift NEUUUU!
if (!activeState->checkAllVariablesForNotDrifting(discreteAveragePartitionSize, compareDistanceDiscreteAveragePartition, thresholdNotDrift)) {
driftCounter++;
setColor(TXTCOLOR_YELLOW);
printf(" >> DRIFT\n");
setColor(GREY);
test = true;
}
}
else {
brokenCounter++;
setColor(LIGHTRED);
printf(" >> BROKEN\n");
setColor(GREY);
test = true;
}
}
printf(" -- Number of States: %u\n", vStates.size());
for (auto &s : vStates) {
printf(" --- injections: %u\n", s->getNumOfInjections());
}
printf(" ... BrokenCounter: %u\n", brokenCounter);
printf(" ... driftCounter: %u\n", driftCounter);
printf("cycle: %u\n", cycle);
if (test) {
test = false;
getchar();
}*/
flagVariablesWereStable = true;
}
else {
printf(" > unstable\n");
//XXX - only for now
csv_writer->write_field(1); //unstable
csv_writer->make_new_field();
csv_writer->make_new_field();
csv_writer->make_new_field();
csv_writer->make_new_line();
if (flagVariablesWereStable)
test = true;
//search for states with less injections in all states
if (flagVariablesWereStable) {
if (activeState != NULL) {
if (activeState->getNumOfInjections() >= minNumToBeValidState) {
addActiveStateToStateVector();
}
else {
delete activeState;
}
activeState = NULL;
//getchar();
}
}
flagVariablesWereStable = false;
}
//xxx - only for now
//csv_writer->make_new_line();
}
void StateHandler::closeCsvFile() {
if(csv_writer != NULL)
csv_writer->close_file();
}
/*
void StateHandler :: initStateHandler() {
//activeState = NULL;
thresholdToAverage = THRESHOLDTOAVG;
minNumOfChangedForValidStateChange = MINNUMCHANGEDFORVALIDSTATECHANGE;
minimumInjectionsForBeingState = MININJFORBEINGSTATE;
}
StateHandler :: StateHandler() {
setName(NO_NAME);
initStateHandler();
}
StateHandler :: StateHandler(char* name) {
setName(name);
initStateHandler();
}
bool StateHandler :: setMinimumInjectionsForBeingState(unsigned int minimumInjectionsForBeingState) {
if (minimumInjectionsForBeingState > 0) {
this->minimumInjectionsForBeingState = minimumInjectionsForBeingState;
return true;
}
return false;
}
unsigned int StateHandler :: getMinimumInjectionsForBeingState() {
return minimumInjectionsForBeingState;
}
bool StateHandler :: add_slot(SlaveAgentSlotOfAgent* slot) {
if(slot != NULL) {
try {
vSlots.push_back(slot);
return true;
}
catch(bad_alloc& error) {
printError("bad_alloc caught: ", error.what());
delete slot;
}
}
return false;
}
void StateHandler :: setThresholdToAverage(float thresholdToAverage) {
this->thresholdToAverage = thresholdToAverage;
}
float StateHandler :: getThresholdToAverage() {
return thresholdToAverage;
}
void StateHandler::set_minNumOfChangedForValidStateChange(unsigned int minNumOfChangedForValidStateChange) {
this->minNumOfChangedForValidStateChange = minNumOfChangedForValidStateChange;
}
unsigned int StateHandler::get_minNumOfChangedForValidStateChange() {
return minNumOfChangedForValidStateChange;
}
bool StateHandler :: trigger() {
bool flagWorked = true;
printf("NumOfStates: ");
for (auto &slot : vSlots) {
printf("%u, ", slot->getNumberOfStates());
}
printf("\n");
//Check all input values if they have changed more than threshold ...and count how many changed
unsigned int numberOfChanges = 0;
for (auto &slot : vSlots) {
float value;
if (slot->get_slaveAgentValue(&value)) {
State* activeState = slot->getActiveState();
if (activeState != NULL) {
printf("act - ");
if (activeState->isNew()) {
printf("new - ");
//numberOfChanges++;
}
else if (activeState->valueIsRelated(value, thresholdToAverage)) {
printf("rel - ");
}
else {
printf("nrel - ");
numberOfChanges++;
}
}
else {
printf("nact - ");
}
}
}
printf("\n");
printf(" >> Number of Changes: %u\n", numberOfChanges);
//nothing has changes more than threshold
if (numberOfChanges == 0) {
printf("\n\n >>> inject in active state\n");
for (auto &slot : vSlots) {
slot->injectValueInActiveState();
}
}
else if(numberOfChanges >= minNumOfChangedForValidStateChange) {
printf("\n\n >>> new (or another) state\n");
for (auto &slot : vSlots) {
State* activeState = slot->getActiveState();
if (activeState != NULL) {
if (activeState->getNumberOfInjections() < minimumInjectionsForBeingState) {
slot->deleteActiveState();
printf(" >> delete State\n");
}
}
}
//search for existing state
bool flagRelated = false;
if (vSlots.empty() == false) {
int ix = vSlots.front()->getIndexOfRelatedState(0, thresholdToAverage);
while (ix > -2) {
if (ix >= 0) {
//TODO: maybe another state fits a bit better.. approach -> euklidean distance?
flagRelated = true;
for (vector<SlaveAgentSlotOfAgent*>::iterator slot = vSlots.begin() + 1; slot < vSlots.end(); slot++) {
if ((*slot)->valueIsRelated(ix, thresholdToAverage) == false) {
flagRelated = false;
}
}
if (flagRelated == true) {
for (auto &slot : vSlots) {
slot->setActiveState(ix);
}
break;
}
ix = vSlots.front()->getIndexOfRelatedState(ix+1, thresholdToAverage);
}
}
}
if (flagRelated == false) {
printf(" >> No related state found\n");
printf("\n\n >>> inject in active state\n");
for (auto &slot : vSlots) {
slot->injectValueInActiveState();
}
}
}
printf("ende\n");
return false;
}
*/

File Metadata

Mime Type
text/x-c
Expires
Sun, Mar 1, 9:23 PM (8 h, 12 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
287736
Default Alt Text
StateHandler.cpp (20 KB)

Event Timeline