Page MenuHomePhorge

No OneTemporary

Size
452 KB
Referenced Files
None
Subscribers
None
This file is larger than 256 KB, so syntax highlighting was skipped.
This document is not UTF8. It was detected as ISO-8859-1 (Latin 1) and converted to UTF8 for display.
diff --git a/Version_Max_07_05_2018_CMake/src/Agent.cpp b/Version_Max_07_05_2018_CMake/src/Agent.cpp
index fa63204..ec72717 100755
--- a/Version_Max_07_05_2018_CMake/src/Agent.cpp
+++ b/Version_Max_07_05_2018_CMake/src/Agent.cpp
@@ -1,1086 +1,262 @@
#include "Agent.h"
#include "printError.h"
#include <stdio.h>
//TODO: Move this include to ControlModule
#include "instruction_set_architecture.h"
/*
#include "Evaluation.h"
#include "instruction_set_architecture.h"
*/
#define PRINT_READING
void Agent :: init_agent() {
sensorHandlerOfAgent = NULL;
slaveAgentHandlerOfAgent = NULL;
masterAgentHandlerOfAgent = NULL;
stateHandler = NULL;
workingCycleCounter = 0;
}
Agent :: Agent() {
set_name(NO_NAME);
init_agent();
}
-Agent :: Agent(char* name) {
+Agent :: Agent(string name) {
set_name(name);
init_agent();
}
bool Agent :: set_sensorHandlerOfAgent() {
sensorHandlerOfAgent = new SensorHandlerOfAgent();
if(sensorHandlerOfAgent == NULL) {
printError("Couldn't create Sensor Handler!");
return false;
}
return true;
}
bool Agent :: del_sensorHandlerOfAgent() {
if(sensorHandlerOfAgent != NULL) {
//TODO: Unmount/delete all sensorSlots with everything inside (history module, confidence module, ...)
delete sensorHandlerOfAgent;
return true;
}
return false;
}
SensorHandlerOfAgent* Agent :: get_sensorHandlerOfAgent() {
if(sensorHandlerOfAgent == NULL) {
set_sensorHandlerOfAgent();
}
return sensorHandlerOfAgent;
}
bool Agent :: set_slaveAgentHandlerOfAgent() {
slaveAgentHandlerOfAgent = new SlaveAgentHandlerOfAgent();
if(slaveAgentHandlerOfAgent == NULL) {
printError("Couldn't create Slave Agent Handler!");
return false;
}
return true;
}
bool Agent :: del_slaveAgentHandlerOfAgent() {
if(slaveAgentHandlerOfAgent != NULL) {
//TODO: Unmount/delete all SlaveAgentSlots with everything inside (history module, confidence module, ...)
delete slaveAgentHandlerOfAgent;
return true;
}
return false;
}
SlaveAgentHandlerOfAgent* Agent :: get_slaveAgentHandlerOfAgent() {
if(slaveAgentHandlerOfAgent == NULL) {
set_slaveAgentHandlerOfAgent();
}
return slaveAgentHandlerOfAgent;
}
bool Agent :: set_masterAgentHandlerOfAgent() {
masterAgentHandlerOfAgent = new MasterAgentHandlerOfAgent();
if(masterAgentHandlerOfAgent == NULL) {
printError("Couldn't create Master Agent Handler!");
return false;
}
return true;
}
bool Agent :: del_masterAgentHandlerOfAgent() {
if(masterAgentHandlerOfAgent != NULL) {
//TODO: Unmount/delete (all) MasterAgentSlot(s) with everything inside
delete masterAgentHandlerOfAgent;
return true;
}
return false;
}
MasterAgentHandlerOfAgent* Agent :: get_masterAgentHandlerOfAgent() {
if(masterAgentHandlerOfAgent == NULL) {
set_masterAgentHandlerOfAgent();
}
return masterAgentHandlerOfAgent;
}
bool Agent :: set_stateHandler() {
stateHandler = new StateHandler();
if(stateHandler == NULL) {
printError("Couldn't create Master Agent Handler!");
return false;
}
return true;
}
+bool Agent ::set_stateHandler(std::string csvWriterPath) {
+ stateHandler = new StateHandler(NO_NAME, csvWriterPath);
+
+ if (stateHandler == NULL) {
+ printError("Couldn't create Master Agent Handler!");
+ return false;
+ }
+ return true;
+}
+
+bool Agent ::set_stateHandler(
+ std::string name, std::string csvWriterPath) {
+ stateHandler = new StateHandler(name, csvWriterPath);
+
+ if (stateHandler == NULL) {
+ printError("Couldn't create Master Agent Handler!");
+ return false;
+ }
+ return true;
+}
+
+
bool Agent :: set_stateHandler(StateHandler* stateHandler) {
if(stateHandler == NULL) {
this->stateHandler = stateHandler;
return true;
}
return false;
}
bool Agent :: del_stateHandler() {
if(stateHandler != NULL) {
//TODO: Unmount/delete (all) MasterAgentSlot(s) with everything inside
delete stateHandler;
return true;
}
return false;
}
StateHandler* Agent :: get_stateHandler() {
if(stateHandler == NULL) {
set_stateHandler();
}
return stateHandler;
}
StateHandler* Agent::get_stateHandler2() {
return stateHandler;
}
Agent::~Agent()
{
del_masterAgentHandlerOfAgent();
del_slaveAgentHandlerOfAgent();
del_sensorHandlerOfAgent();
del_stateHandler();
}
void Agent :: trigger(unsigned int cycle) {
if (workingCycleCounter < get_workingCycle())
workingCycleCounter++;
else
workingCycleCounter = 1;
if (workingCycleCounter == 1) {
//TODO: make control_module to set the method of operating for each agent individual
//Job: Read all sensory data
if(sensorHandlerOfAgent != NULL) {
//printf("%s->sensorHandler: ", name);
sensorHandlerOfAgent->read_allSensorValues();
}
//Job: Read all slave agent data
if(slaveAgentHandlerOfAgent != NULL) {
//TODO: do this in HistoryModule //TODO: this for all slots (not only for slaveagents)
slaveAgentHandlerOfAgent->saveAllValuesInHistory();
//getchar();
slaveAgentHandlerOfAgent->read_allSlaveAgentValues();
}
//Job: Just pass the Sensory Data (without abstraction) to master
if(masterAgentHandlerOfAgent != NULL) {
if(sensorHandlerOfAgent != NULL) {
vector<SensorSlotOfAgent*>* vSensoryData = sensorHandlerOfAgent->get_vMountedSensors();
for(auto &sensorSlot : *vSensoryData) {
//TODO: also for int
float sensorValue;
if(sensorSlot->get_sensorValue(&sensorValue)) {
masterAgentHandlerOfAgent->pass_msgToSendBuffer(ISA_SensoryData);
masterAgentHandlerOfAgent->pass_msgToSendBuffer(sensorValue);
}
}
}
masterAgentHandlerOfAgent->send_msgs();
}
if (stateHandler != NULL) {
stateHandler->trigger(cycle);
}
}
- /*
- read_all_mountedSensors();
-
- validate_confidence_of_all_mountedSensors();
-
- //TODO: save only when confident or save everytime? ...maybe safe confidence as meta data.
- save_all_mountedSensor_histories();
-
- read_all_slaveAgents();
- */
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- /* OLD
- //has to be done in an extra loop because every slave agent values are needed
- for(unsigned int sa_ix = 0; sa_ix<num_of_mounted_slaveagents; sa_ix++) {
-
- if(flag_ccv_module_exist[sa_ix]) {
- //flag_slaveagent_value_confident[sa_ix] = list_of_ccv_modules[sa_ix]->cross_validate(num_of_mounted_slaveagents, slaveagent_value, &flag_slaveagent_value_confident[0]);
- }
- }
-
-
- //bunch //TODO: auch f�r integer (slaveagents)
- if(flag_bunch_module_exist) {
- bunch_score_confidency = bunch_module->bunch(num_of_mounted_slaveagents, &slaveagent_value[0], &flag_slaveagent_value_confident[0], &bunched_score);
- //printf("flag_bunched_score_exist setzten - ");
- if(bunch_score_confidency > 0) {
- flag_bunched_score_exist = true;
- //printf("true\n");
- }
- else {
- flag_bunched_score_exist = false;
- //printf("false\n");
- }
- }
-
-
-
-
-
-
- //abstract data //TODO: auch f�r integer (slaveagents)
- for(unsigned int s_ix = 0; s_ix<num_of_mounted_sensors; s_ix++) {
- if(flag_sensor_value_set[s_ix]) {
- if(flag_abstraction_exist[s_ix]) {
- if(list_of_abstractions[s_ix]->abstract(sensor_value[s_ix], &abstracted_sensor_score[s_ix])) {
- flag_abstracted_sensor_score_exist[s_ix] = true;
- }
- else {
- flag_abstracted_sensor_score_exist[s_ix] = false;
- }
- }
- }
- }
-
- //sending data / do specific task
- if(flag_masteragent_outputport_is_active) {
- for(unsigned int s_ix = 0; s_ix<num_of_mounted_sensors; s_ix++) {
-
- if(flag_abstracted_sensor_score_exist[s_ix]) {
-
-
- if(flag_confidence_validator_exist[s_ix]) {
- if(flag_sensor_value_confident[s_ix]) {
- mounted_masteragent_outputport->set_msg((int)ISA_SCORE_VALID);
- }
- else {
- mounted_masteragent_outputport->set_msg((int)ISA_SCORE_INVALID);
- }
- }
- else {
- mounted_masteragent_outputport->set_msg((int)ISA_SCORE_VALID);
- }
-
-
-
- //if(flag_sensor_value_confident || flag_confidence_validator_exist == false) {
- // mounted_masteragent_outputport->set_msg((int)IS_SCORE_VALID);
- //}
- //else {
- // mounted_masteragent_outputport->set_msg((int)IS_SCORE_INVALID);
- //}
-
- mounted_masteragent_outputport->set_msg(abstracted_sensor_score[s_ix]);
- }
- }
- }
- */
-}
-
-
-
-/*
-void Agent :: initialize_master_slot() {
- //TODO: also mast_is_active needed?
- flag_masteragent_is_mounted = UNMOUNTED;
- flag_masteragent_inputport_is_active = INACTIVE;
- flag_masteragent_outputport_is_active = INACTIVE;
-}
-
-void Agent :: initialize_slaveagent_slots() {
- num_of_mounted_slaveagents = 0;
- //number_of_active_mounted_subagents = 0; //TODO: do i need it??
- for(unsigned int sa_ix=0; sa_ix<MAX_NUM_OF_MOUNTED_SLAVEAGENTS; sa_ix++) {
- flag_slaveagent_is_mounted[sa_ix] = UNMOUNTED;
- flag_slaveagent_has_dedicated_position[sa_ix] = NO;
- flag_slaveagent_inputport_is_active[sa_ix] = INACTIVE;
- flag_slaveagent_outputport_is_active[sa_ix] = INACTIVE;
-
- //Slaveagent value
- flag_slaveagent_value_set[sa_ix] = false;
- flag_slaveagent_value_changed[sa_ix] = false;
-
- flag_slaveagent_value_confident[sa_ix] = false;
-
- flag_ccv_module_exist[sa_ix] = false;
- }
-}
-
-void Agent :: initialize_sensor_slots() {
- num_of_mounted_sensors = 0;
- //number_of_active_mounted_sensors = 0;
- for(unsigned int s_ix=0; s_ix<MAX_NUM_OF_MOUNTED_SENSORS; s_ix++) {
- //sensors
- flag_sensor_is_mounted[s_ix] = UNMOUNTED;
- flag_sensor_has_dedicated_position[s_ix] = NO;
- mounted_sensor_inputport[s_ix] = INACTIVE;
- flag_sensor_inputport_is_active[s_ix] = INACTIVE;
-
- //Sensor value
- flag_sensor_value_set[s_ix] = false;
- flag_sensor_value_changed[s_ix] = false;
-
- //Sensor History
- flag_sensor_history_exist[s_ix] = false;
-
- //confedence
- flag_confidence_validator_exist[s_ix] = false;
- flag_sensor_value_confident[s_ix] = false;
-
- //abstraction
- flag_abstraction_exist[s_ix] = false;
- flag_abstracted_sensor_score_exist[s_ix] = false;
- }
-}
-
-void Agent :: initialize_bunch_module() {
- flag_bunch_module_exist = false;
- flag_bunched_score_exist = false;
- bunch_score_confidency = 0;
-}
-
-void Agent :: initialize_working_frequency(int* success_indicator) {
- if(set_working_frequency(working_frequency)) {
- *success_indicator = 0;
- }
- else {
- *success_indicator = 1;
- }
-}
-
-// ----- Standard Attributes -----
-Agent :: Agent() {
- set_name(NO_NAME);
- initialize_master_slot();
- initialize_slaveagent_slots();
- initialize_sensor_slots();
- initialize_bunch_module();
-}
-
-Agent :: Agent(char* name) {
- set_name(name);
- initialize_master_slot();
- initialize_slaveagent_slots();
- initialize_sensor_slots();
- initialize_bunch_module();
-}
-
-Agent :: Agent(unsigned int working_frequency, int* success_indicator) {
- set_name(NO_NAME);
- initialize_master_slot();
- initialize_slaveagent_slots();
- initialize_sensor_slots();
- initialize_bunch_module();
- initialize_working_frequency(success_indicator);
-}
-
-Agent :: Agent(char* name, unsigned int working_frequency, int* success_indicator) {
- set_name(name);
- initialize_master_slot();
- initialize_slaveagent_slots();
- initialize_sensor_slots();
- initialize_bunch_module();
- initialize_working_frequency(success_indicator);
-}
-
-bool Agent :: set_working_frequency(unsigned int working_frequency) {
- if(working_frequency <= MAX_WORK_FREQU) {
- this->working_frequency = working_frequency;
- return true;
- }
- this->working_frequency = 0;
- return false;
-}
-
-
-bool Agent :: read_mountedSensor(unsigned int s_ix) {
-
- bool flag_got_new_sensor_value;
- float temp_sensor_value;
-
- flag_got_new_sensor_value = mounted_sensor_inputport[s_ix]->get_msg_float(&temp_sensor_value);
-
- if(flag_got_new_sensor_value) {
-
- if(!flag_sensor_value_set[s_ix]) {
- flag_sensor_value_set[s_ix] = true;
- flag_sensor_value_changed[s_ix] = true;
- sensor_value[s_ix] = temp_sensor_value;
- }
- else {
- if(sensor_value[s_ix] == temp_sensor_value) {
- flag_sensor_value_changed[s_ix] = false;
- }
- else {
- flag_sensor_value_changed[s_ix] = true;
- sensor_value[s_ix] = temp_sensor_value;
- }
- }
- }
- else {
- flag_sensor_value_changed[s_ix] = false;
- }
-
- return flag_got_new_sensor_value;
-}
-
-
-void Agent :: read_all_mountedSensors() {
-
- for(unsigned int s_ix = 0; s_ix<num_of_mounted_sensors; s_ix++) {
- read_mountedSensor(s_ix);
- printf("Agent %s got value: %f\n", name, sensor_value[s_ix]);
- }
-}
-
-bool Agent :: save_mountedSensor_history(unsigned int s_ix) {
-
- bool flag_data_saved = false;
-
- if(flag_sensor_value_set[s_ix] && flag_sensor_history_exist[s_ix]) {
- flag_data_saved = sensor_history[s_ix]->drop_data(sensor_value[s_ix]);
- }
-
- return flag_data_saved;
}
-void Agent :: save_all_mountedSensor_histories() {
- for(unsigned int s_ix = 0; s_ix<num_of_mounted_sensors; s_ix++) {
- save_mountedSensor_history(s_ix);
- //Next lines are only for print
- float temp_value;
- if(flag_sensor_history_exist[s_ix]) {
- if(sensor_history[s_ix]->get_latest_value(&temp_value))
- printf("History %s got value: %f\n", name, temp_value);
- else
- printf("History %s got no value.\n", name);
- }
- else {
- printf("History doesn't exist.\n");
- }
- }
-}
-//TODO: this function is untested - test it!
-bool Agent :: validate_confidence_of_mountedSensor(unsigned int s_ix) {
-
- if(flag_sensor_value_set[s_ix]) {
-
- if(flag_confidence_validator_exist[s_ix]) {
- //TODO: modify validate_confidence function in a way that there is parameter that says if actual sensor_value[s_ix] is already in history or not!
- flag_sensor_value_confident[s_ix] = list_of_confidence_validators[s_ix]->validate_confidence(sensor_value[s_ix], sensor_history[s_ix]);
- }
- else {
- //I have to believe it if I don't know
- flag_sensor_value_confident[s_ix] = true;
- }
- }
-
- return flag_sensor_value_confident[s_ix];
-}
-
-void Agent :: validate_confidence_of_all_mountedSensors() {
- for(unsigned int s_ix = 0; s_ix<num_of_mounted_sensors; s_ix++) {
- validate_confidence_of_mountedSensor(s_ix);
- }
-}
-
-//TODO: test / modify!
-bool Agent :: read_slaveAgent(unsigned int sa_ix) {
- //TODO: instructions in own line (unsigned int) ?!
- //TODO: Class/Object Control Unit (with included instruction set)
- int instruction = ISA_NO_INSTRUCTION;
- int data = 0; //TODO: better value
-
- while(mounted_slaveagent_inputport[sa_ix]->is_there_a_msg_for_me_int()) {
-
- instruction = mounted_slaveagent_inputport[sa_ix]->get_msg_int(); //TODO: hier (vllt) auch die m�glichkeit float (score) einzulesen!!
-
- if(instruction == ISA_SCORE_VALID || instruction == ISA_SCORE_INVALID) {
-
- bool got_msg = mounted_slaveagent_inputport[sa_ix]->is_there_a_msg_for_me_int();
-
- if(got_msg) {
- data = mounted_slaveagent_inputport[sa_ix]->get_msg_int();
-
- if(slaveagent_value[sa_ix] != data) {
- flag_slaveagent_value_changed[sa_ix] = true;
- }
- slaveagent_value[sa_ix] = data;
- flag_slaveagent_value_set[sa_ix] = true;
-
- if(instruction == ISA_SCORE_VALID) {
- //if(id == 0)
- // printf("setze valid\n");
- flag_slaveagent_value_confident[sa_ix] = true;
- }
- else {
- //if(id == 0)
- // printf("setze invalid\n");
- flag_slaveagent_value_confident[sa_ix] = false;
- }
- }
- else {
- flag_slaveagent_value_set[sa_ix] = false;
- }
- } else {
- flag_slaveagent_value_set[sa_ix] = false;
- }
- }
- //TODO: do i need a return value?
- return false;
-}
-
-void Agent :: read_all_slaveAgents() {
- for(unsigned int sa_ix = 0; sa_ix<num_of_mounted_slaveagents; sa_ix++) {
- read_slaveAgent(sa_ix);
- }
-}
-
-
-
-// ----- Runtime Functions -----
-void Agent :: trigger() {
-
- //NOTE: I made readig, confidence, etc. in own loops/functions... because it may happen that confidence range changes and the sensor value is still the same but then valid or not
-
- read_all_mountedSensors();
-
- validate_confidence_of_all_mountedSensors();
- //TODO: save only when confident or save everytime? ...maybe safe confidence as meta data.
- save_all_mountedSensor_histories();
- read_all_slaveAgents();
-
-
-
-
-
-
- /* OLD
- //has to be done in an extra loop because every slave agent values are needed
- for(unsigned int sa_ix = 0; sa_ix<num_of_mounted_slaveagents; sa_ix++) {
-
- if(flag_ccv_module_exist[sa_ix]) {
- //flag_slaveagent_value_confident[sa_ix] = list_of_ccv_modules[sa_ix]->cross_validate(num_of_mounted_slaveagents, slaveagent_value, &flag_slaveagent_value_confident[0]);
- }
- }
-
-
- //bunch //TODO: auch f�r integer (slaveagents)
- if(flag_bunch_module_exist) {
- bunch_score_confidency = bunch_module->bunch(num_of_mounted_slaveagents, &slaveagent_value[0], &flag_slaveagent_value_confident[0], &bunched_score);
- //printf("flag_bunched_score_exist setzten - ");
- if(bunch_score_confidency > 0) {
- flag_bunched_score_exist = true;
- //printf("true\n");
- }
- else {
- flag_bunched_score_exist = false;
- //printf("false\n");
- }
- }
-
-
-
-
-
-
- //abstract data //TODO: auch f�r integer (slaveagents)
- for(unsigned int s_ix = 0; s_ix<num_of_mounted_sensors; s_ix++) {
- if(flag_sensor_value_set[s_ix]) {
- if(flag_abstraction_exist[s_ix]) {
- if(list_of_abstractions[s_ix]->abstract(sensor_value[s_ix], &abstracted_sensor_score[s_ix])) {
- flag_abstracted_sensor_score_exist[s_ix] = true;
- }
- else {
- flag_abstracted_sensor_score_exist[s_ix] = false;
- }
- }
- }
- }
-
- //sending data / do specific task
- if(flag_masteragent_outputport_is_active) {
- for(unsigned int s_ix = 0; s_ix<num_of_mounted_sensors; s_ix++) {
-
- if(flag_abstracted_sensor_score_exist[s_ix]) {
-
-
- if(flag_confidence_validator_exist[s_ix]) {
- if(flag_sensor_value_confident[s_ix]) {
- mounted_masteragent_outputport->set_msg((int)ISA_SCORE_VALID);
- }
- else {
- mounted_masteragent_outputport->set_msg((int)ISA_SCORE_INVALID);
- }
- }
- else {
- mounted_masteragent_outputport->set_msg((int)ISA_SCORE_VALID);
- }
-
-
-
- //if(flag_sensor_value_confident || flag_confidence_validator_exist == false) {
- // mounted_masteragent_outputport->set_msg((int)IS_SCORE_VALID);
- //}
- //else {
- // mounted_masteragent_outputport->set_msg((int)IS_SCORE_INVALID);
- //}
-
- mounted_masteragent_outputport->set_msg(abstracted_sensor_score[s_ix]);
- }
- }
- }
- */
-/*}
-
-
-//TODO: prevent possibility to mount yourself as subagent!
-//TODO: prevent possibility to mount sensor as subagent!
-bool Agent :: mount_slaveagent(Channel* inputport, Channel* outputport) {
- if(num_of_mounted_slaveagents < MAX_NUM_OF_MOUNTED_SLAVEAGENTS && (inputport != NULL || outputport != NULL)) {
- for(unsigned int sa_ix=0; sa_ix<MAX_NUM_OF_MOUNTED_SLAVEAGENTS; sa_ix++) {
- if(flag_slaveagent_is_mounted[sa_ix] == UNMOUNTED) {
- flag_slaveagent_is_mounted[sa_ix] = MOUNTED;
- flag_slaveagent_has_dedicated_position[sa_ix] = NO;
- if(inputport != NULL) {
- mounted_slaveagent_inputport[sa_ix] = inputport;
- flag_slaveagent_inputport_is_active[sa_ix] = ACTIVE;
- }
- else {
- flag_slaveagent_inputport_is_active[sa_ix] = INACTIVE;
- }
- if(outputport != NULL) {
- mounted_slaveagent_outputport[sa_ix] = outputport;
- flag_slaveagent_outputport_is_active[sa_ix] = ACTIVE;
- }
- else {
- flag_slaveagent_outputport_is_active[sa_ix] = INACTIVE;
- }
- num_of_mounted_slaveagents++;
- //abstraction.set_num_of_slaveagents(num_of_mounted_slaveagents);
- return true;
- }
- }
- }
- return false;
-}
-
-
-//TODO: prevent possibility to mount yourself as subagent!
-//TODO: prevent possibility to mount sensor as subagent!
-bool Agent :: mount_slaveagent(Channel* inputport, Channel* outputport, unsigned int position) {
- if(position < MAX_NUM_OF_MOUNTED_SLAVEAGENTS) {
- if(flag_slaveagent_has_dedicated_position[position] == NO && (inputport != NULL || outputport != NULL)) {
- if(flag_slaveagent_is_mounted[position] == MOUNTED) {
- if(num_of_mounted_slaveagents < MAX_NUM_OF_MOUNTED_SLAVEAGENTS) {
- for(unsigned int sa_ix=0; sa_ix<MAX_NUM_OF_MOUNTED_SLAVEAGENTS; sa_ix++) {
- if(flag_slaveagent_is_mounted[sa_ix] == UNMOUNTED) {
- flag_slaveagent_is_mounted[sa_ix] = flag_slaveagent_is_mounted[position];
- flag_slaveagent_has_dedicated_position[sa_ix] = flag_slaveagent_has_dedicated_position[position];
- flag_slaveagent_inputport_is_active[sa_ix] = flag_slaveagent_inputport_is_active[position];
- if(flag_slaveagent_inputport_is_active[position])
- mounted_slaveagent_inputport[sa_ix] = mounted_slaveagent_inputport[position];
- flag_slaveagent_outputport_is_active[sa_ix] = flag_slaveagent_outputport_is_active[position];
- if(flag_slaveagent_outputport_is_active[position])
- mounted_slaveagent_outputport[sa_ix] = mounted_slaveagent_outputport[position];
- break;
- }
- }
- }
- else {
- return false;
- }
- }
-
- flag_slaveagent_is_mounted[position] = MOUNTED;
- flag_slaveagent_has_dedicated_position[position] = YES;
-
- if(inputport != NULL) {
- mounted_slaveagent_inputport[position] = inputport;
- flag_slaveagent_inputport_is_active[position] = ACTIVE;
- }
- else {
- flag_slaveagent_inputport_is_active[position] = INACTIVE;
- }
- if(outputport != NULL) {
- mounted_slaveagent_outputport[position] = outputport;
- flag_slaveagent_outputport_is_active[position] = ACTIVE;
- }
- else {
- flag_slaveagent_outputport_is_active[position] = INACTIVE;
- }
- num_of_mounted_slaveagents++;
- //abstraction.set_num_of_slaveagents(num_of_mounted_slaveagents);
- return true;
- }
- }
- return false;
-}
-
-//TODO: soetwas wie ccv != NULL auch bei anderen mounting sachen amchen.. mit Confidence, Abstraction usw
-bool Agent :: mount_slaveagent(Channel* inputport, Channel* outputport, Cross_Confidence_Validator* ccv) {
- if(num_of_mounted_slaveagents < MAX_NUM_OF_MOUNTED_SLAVEAGENTS && (inputport != NULL || outputport != NULL) && ccv != NULL) {
- for(unsigned int sa_ix=0; sa_ix<MAX_NUM_OF_MOUNTED_SLAVEAGENTS; sa_ix++) {
- if(flag_slaveagent_is_mounted[sa_ix] == UNMOUNTED) {
- flag_slaveagent_is_mounted[sa_ix] = MOUNTED;
- flag_slaveagent_has_dedicated_position[sa_ix] = NO;
- if(inputport != NULL) {
- mounted_slaveagent_inputport[sa_ix] = inputport;
- flag_slaveagent_inputport_is_active[sa_ix] = ACTIVE;
- }
- else {
- flag_slaveagent_inputport_is_active[sa_ix] = INACTIVE;
- }
- if(outputport != NULL) {
- mounted_slaveagent_outputport[sa_ix] = outputport;
- flag_slaveagent_outputport_is_active[sa_ix] = ACTIVE;
- }
- else {
- flag_slaveagent_outputport_is_active[sa_ix] = INACTIVE;
- }
-
- list_of_ccv_modules[sa_ix] = ccv;
- flag_ccv_module_exist[sa_ix] = true;
- //TODO: Fehlerbehandlung
- list_of_ccv_modules[sa_ix]->set_proband(sa_ix);
-
- num_of_mounted_slaveagents++;
- return true;
- }
- }
- }
- return false;
-}
-
-
-
-//TODO: prevent possibility to mount yourself as subagent!
-//TODO: prevent possibility to mount subagent as sensor!
-bool Agent :: mount_masteragent(Channel* inputport, Channel* outputport) {
- if(inputport != NULL || outputport != NULL) {
-
- if(inputport != NULL) {
- mounted_masteragent_inputport = inputport;
- flag_masteragent_inputport_is_active = ACTIVE;
- }
- else {
- flag_masteragent_inputport_is_active = INACTIVE;
- }
-
- if(outputport != NULL) {
- mounted_masteragent_outputport = outputport;
- flag_masteragent_outputport_is_active = ACTIVE;
- }
- else {
- flag_masteragent_outputport_is_active = INACTIVE;
- }
-
- return true;
- }
- return false;
-}
-
-
-bool Agent :: mount_sensor(Channel* inputport, unsigned int position) {
- if(position < MAX_NUM_OF_MOUNTED_SENSORS) {
- if(flag_sensor_has_dedicated_position[position] == NO && inputport != NULL) {
- if(flag_sensor_is_mounted[position] == MOUNTED) {
- if(num_of_mounted_sensors < MAX_NUM_OF_MOUNTED_SENSORS) {
- for(unsigned int s_ix=0; s_ix<MAX_NUM_OF_MOUNTED_SENSORS; s_ix++) {
- if(flag_sensor_is_mounted[s_ix] == UNMOUNTED) {
- flag_sensor_is_mounted[s_ix] = flag_sensor_is_mounted[position];
- flag_sensor_has_dedicated_position[s_ix] = flag_sensor_has_dedicated_position[position];
- mounted_sensor_inputport[s_ix] = mounted_sensor_inputport[position];
- flag_sensor_inputport_is_active[s_ix] = flag_sensor_inputport_is_active[position];
- }
- }
- }
- else {
- return false;
- }
- }
- flag_sensor_is_mounted[position] = MOUNTED;
- flag_sensor_has_dedicated_position[position] = YES;
- mounted_sensor_inputport[position] = inputport;
- flag_sensor_inputport_is_active[position] = ACTIVE;
- num_of_mounted_sensors++;
- //abstraction.set_num_of_sensors(num_of_mounted_sensors);
- return true;
- }
- }
- return false;
-}
-
-
-//TODO: prevent possibility to mount yourself as subagent!
-//TODO: prevent possibility to mount subagent as sensor!
-bool Agent :: mount_sensor(Channel* inputport) {
- if(num_of_mounted_sensors < MAX_NUM_OF_MOUNTED_SENSORS && inputport != NULL) {
- for(unsigned int s_ix=0; s_ix<MAX_NUM_OF_MOUNTED_SENSORS; s_ix++) {
- if(flag_sensor_is_mounted[s_ix] == UNMOUNTED) {
- flag_sensor_is_mounted[s_ix] = MOUNTED;
- flag_sensor_has_dedicated_position[s_ix] = NO;
- mounted_sensor_inputport[s_ix] = inputport;
- flag_sensor_inputport_is_active[s_ix] = ACTIVE;
- num_of_mounted_sensors++;
- //abstraction.set_num_of_sensors(num_of_mounted_sensors);
- return true;
- }
- }
- }
- return false;
-}
-
-bool Agent :: mount_sensor(Channel* inputport, Abstraction* abstraction) {
- if(num_of_mounted_sensors < MAX_NUM_OF_MOUNTED_SENSORS && inputport != NULL) {
- for(unsigned int s_ix=0; s_ix<MAX_NUM_OF_MOUNTED_SENSORS; s_ix++) {
- if(flag_sensor_is_mounted[s_ix] == UNMOUNTED) {
- flag_sensor_is_mounted[s_ix] = MOUNTED;
- flag_sensor_has_dedicated_position[s_ix] = NO;
- mounted_sensor_inputport[s_ix] = inputport;
- flag_sensor_inputport_is_active[s_ix] = ACTIVE;
-
- if(abstraction != NULL) {
- flag_abstraction_exist[s_ix] = true;
- list_of_abstractions[s_ix] = abstraction;
- }
-
- num_of_mounted_sensors++;
-
- return true;
- }
- }
- }
- return false;
-}
-
-bool Agent :: mount_sensor(Channel* inputport, Confidence_Validator* confidence_validator) {
- if(num_of_mounted_sensors < MAX_NUM_OF_MOUNTED_SENSORS && inputport != NULL) {
- for(unsigned int s_ix=0; s_ix<MAX_NUM_OF_MOUNTED_SENSORS; s_ix++) {
- if(flag_sensor_is_mounted[s_ix] == UNMOUNTED) {
- flag_sensor_is_mounted[s_ix] = MOUNTED;
- flag_sensor_has_dedicated_position[s_ix] = NO;
- mounted_sensor_inputport[s_ix] = inputport;
- flag_sensor_inputport_is_active[s_ix] = ACTIVE;
-
- if(confidence_validator != NULL) {
- flag_confidence_validator_exist[s_ix] = true;
- list_of_confidence_validators[s_ix] = confidence_validator;
- }
-
- num_of_mounted_sensors++;
-
- return true;
- }
- }
- }
- return false;
-}
-
-
-bool Agent :: mount_sensor(Channel* inputport, HistoryModule* historyModule) {
-
- /*
- sensor_history[MAX_NUM_OF_MOUNTED_SENSORS];
- flag_sensor_history_exist[MAX_NUM_OF_MOUNTED_SENSORS];
- */
-
-/* if(num_of_mounted_sensors < MAX_NUM_OF_MOUNTED_SENSORS && inputport != NULL && historyModule != NULL) {
-
- for(unsigned int s_ix=0; s_ix<MAX_NUM_OF_MOUNTED_SENSORS; s_ix++) {
-
- if(flag_sensor_is_mounted[s_ix] == UNMOUNTED) {
-
- flag_sensor_is_mounted[s_ix] = MOUNTED;
- flag_sensor_has_dedicated_position[s_ix] = NO;
- mounted_sensor_inputport[s_ix] = inputport;
- flag_sensor_inputport_is_active[s_ix] = ACTIVE;
-
- flag_sensor_history_exist[s_ix] = true;
- sensor_history[s_ix] = historyModule;
-
- num_of_mounted_sensors++;
-
- return true;
- }
- }
- }
-
- return false;
-}
-
-
-bool Agent :: mount_sensor(Channel* inputport, Confidence_Validator* confidence_validator, Abstraction* abstraction) {
- if(num_of_mounted_sensors < MAX_NUM_OF_MOUNTED_SENSORS && inputport != NULL) {
- for(unsigned int s_ix=0; s_ix<MAX_NUM_OF_MOUNTED_SENSORS; s_ix++) {
- if(flag_sensor_is_mounted[s_ix] == UNMOUNTED) {
- flag_sensor_is_mounted[s_ix] = MOUNTED;
- flag_sensor_has_dedicated_position[s_ix] = NO;
- mounted_sensor_inputport[s_ix] = inputport;
- flag_sensor_inputport_is_active[s_ix] = ACTIVE;
-
- if(confidence_validator != NULL) {
- flag_confidence_validator_exist[s_ix] = true;
- list_of_confidence_validators[s_ix] = confidence_validator;
- }
-
- if(abstraction != NULL) {
- flag_abstraction_exist[s_ix] = true;
- list_of_abstractions[s_ix] = abstraction;
- }
-
- num_of_mounted_sensors++;
-
- return true;
- }
- }
- }
- return false;
-}
-
-// ----- Bunch Module -----
-bool Agent :: mount_bunch_module(Bunch_Module* bunch_module){
- if(bunch_module != NULL) {
- this->bunch_module = bunch_module;
- this->flag_bunch_module_exist = true;
- return true;
- }
- return false;
-}
-
-
-bool Agent :: get_flag_abstracted_sensor_score_exist(unsigned int position) {
- return flag_abstracted_sensor_score_exist[position];
-}
-
-//TODO: r�ckgabewert, wenn kein vern�nftiger wert
-int Agent :: get_abstracted_sensor_score(unsigned int position) {
- if(position < num_of_mounted_sensors && flag_abstracted_sensor_score_exist[position]) {
- return abstracted_sensor_score[position];
- }
- return -1;
-}
-
-bool Agent :: get_flag_bunched_score_exist() {
- return flag_bunched_score_exist;
-}
-
-int Agent :: get_bunched_score() {
- if(flag_bunched_score_exist) {
- return bunched_score;
- }
- return -1;
-}
-
-unsigned int Agent :: get_bunch_score_confidency() {
- return bunch_score_confidency;
-}
-
-
-
-
-
-
-void Agent :: test_print_all_slaveagents() {
-
- for(int i=0; i<MAX_NUM_OF_MOUNTED_SLAVEAGENTS; i++) {
- if(flag_slaveagent_is_mounted[i]) {
- if(flag_slaveagent_inputport_is_active[i]) {
- printf("%s has mounted %s on position %i\n", this->name, mounted_slaveagent_inputport[i]->get_name(), i);
- }
- if(flag_slaveagent_outputport_is_active[i]) {
- printf("%s has mounted %s on position %i\n", this->name, mounted_slaveagent_outputport[i]->get_name(), i);
- }
- }
- else {
- printf("%s has nothing mounted on position %i\n", this->name, i);
- }
- }
- getchar();
-}
-
-void Agent :: test_print_all_sensors() {
-
- for(int i=0; i<MAX_NUM_OF_MOUNTED_SENSORS; i++) {
- if(flag_sensor_is_mounted[i]) {
- if(flag_sensor_inputport_is_active[i]) {
- printf("%s has mounted %s on position %i\n", this->name, mounted_sensor_inputport[i]->get_name(), i);
- }
- }
- else {
- printf("%s has nothing mounted on position %i\n", this->name, i);
- }
- }
- getchar();
-}
-*/
diff --git a/Version_Max_07_05_2018_CMake/src/Agent.h b/Version_Max_07_05_2018_CMake/src/Agent.h
index dd0b42d..d498da3 100755
--- a/Version_Max_07_05_2018_CMake/src/Agent.h
+++ b/Version_Max_07_05_2018_CMake/src/Agent.h
@@ -1,208 +1,211 @@
#ifndef AGENT_HEADERFILE
#define AGENT_HEADERFILE
#include "MasterAgentHandlerOfAgent.h"
#include "Node.h"
#include "SensorHandlerOfAgent.h"
#include "SlaveAgentHandlerOfAgent.h"
#include "StateHandler.h"
#include <string.h>
class Agent : public Node {
private :
SensorHandlerOfAgent* sensorHandlerOfAgent;
SlaveAgentHandlerOfAgent* slaveAgentHandlerOfAgent;
MasterAgentHandlerOfAgent* masterAgentHandlerOfAgent;
/// Pointer to the stateHandler
StateHandler* stateHandler;
unsigned int workingCycleCounter;
void init_agent();
public:
Agent();
- Agent(char* name);
+ Agent(string name);
bool set_sensorHandlerOfAgent();
bool del_sensorHandlerOfAgent();
SensorHandlerOfAgent* get_sensorHandlerOfAgent();
bool set_slaveAgentHandlerOfAgent();
bool del_slaveAgentHandlerOfAgent();
SlaveAgentHandlerOfAgent* get_slaveAgentHandlerOfAgent();
bool set_masterAgentHandlerOfAgent();
bool del_masterAgentHandlerOfAgent();
MasterAgentHandlerOfAgent* get_masterAgentHandlerOfAgent();
bool set_stateHandler();
+ bool set_stateHandler(std::string csvWriterPath);
+ bool set_stateHandler(std::string name,
+ std::string csvWriterPath);
bool set_stateHandler(StateHandler* stateHandler);
bool del_stateHandler();
StateHandler* get_stateHandler();
StateHandler* get_stateHandler2();
void trigger(unsigned int cycle);
bool operator !=(const Agent& a) {
- return strcmp(this->name, a.name);
+ return strcmp(this->name.c_str(), a.name.c_str());
}
~Agent();
/*
private:
unsigned int working_frequency;
//master agent
bool flag_masteragent_is_mounted;
Channel* mounted_masteragent_inputport;
Channel* mounted_masteragent_outputport;
bool flag_masteragent_inputport_is_active;
bool flag_masteragent_outputport_is_active;
//slave agents
unsigned int num_of_mounted_slaveagents;
bool flag_slaveagent_is_mounted[MAX_NUM_OF_MOUNTED_SLAVEAGENTS];
bool flag_slaveagent_has_dedicated_position[MAX_NUM_OF_MOUNTED_SLAVEAGENTS];
Channel* mounted_slaveagent_inputport[MAX_NUM_OF_MOUNTED_SLAVEAGENTS];
Channel* mounted_slaveagent_outputport[MAX_NUM_OF_MOUNTED_SLAVEAGENTS];
bool flag_slaveagent_inputport_is_active[MAX_NUM_OF_MOUNTED_SLAVEAGENTS];
bool flag_slaveagent_outputport_is_active[MAX_NUM_OF_MOUNTED_SLAVEAGENTS];
//slaveagent values
int slaveagent_value[MAX_NUM_OF_MOUNTED_SENSORS];
bool flag_slaveagent_value_set[MAX_NUM_OF_MOUNTED_SENSORS];
bool flag_slaveagent_value_changed[MAX_NUM_OF_MOUNTED_SENSORS];
//sensors
unsigned int num_of_mounted_sensors;
bool flag_sensor_is_mounted[MAX_NUM_OF_MOUNTED_SENSORS];
bool flag_sensor_has_dedicated_position[MAX_NUM_OF_MOUNTED_SENSORS];
Channel* mounted_sensor_inputport[MAX_NUM_OF_MOUNTED_SENSORS];
bool flag_sensor_inputport_is_active[MAX_NUM_OF_MOUNTED_SENSORS];
//sensor values
float sensor_value[MAX_NUM_OF_MOUNTED_SENSORS];
bool flag_sensor_value_set[MAX_NUM_OF_MOUNTED_SENSORS];
bool flag_sensor_value_changed[MAX_NUM_OF_MOUNTED_SENSORS];
//sensor history
HistoryModule* sensor_history[MAX_NUM_OF_MOUNTED_SENSORS];
bool flag_sensor_history_exist[MAX_NUM_OF_MOUNTED_SENSORS];
//confidence
bool flag_confidence_validator_exist[MAX_NUM_OF_MOUNTED_SENSORS];
ConfidenceModule* list_of_confidence_validators[MAX_NUM_OF_MOUNTED_SENSORS];
bool flag_sensor_value_confident[MAX_NUM_OF_MOUNTED_SENSORS];
bool flag_slaveagent_value_confident[MAX_NUM_OF_MOUNTED_SLAVEAGENTS];
//abstraction modules
bool flag_abstraction_exist[MAX_NUM_OF_MOUNTED_SENSORS];
AbstractionModule* list_of_abstractions[MAX_NUM_OF_MOUNTED_SENSORS];
int abstracted_sensor_score[MAX_NUM_OF_MOUNTED_SENSORS];
bool flag_abstracted_sensor_score_exist[MAX_NUM_OF_MOUNTED_SENSORS];
//bunch module
bool flag_bunch_module_exist;
Bunch_Module* bunch_module;
int bunched_score;
bool flag_bunched_score_exist;
unsigned int bunch_score_confidency;
//private functions
void initialize_master_slot();
void initialize_slaveagent_slots();
void initialize_sensor_slots();
void initialize_bunch_module();
void initialize_working_frequency(int* success_indicator);
//cross confidence
Cross_Confidence_Validator* list_of_ccv_modules[MAX_NUM_OF_MOUNTED_SLAVEAGENTS];
bool flag_ccv_module_exist[MAX_NUM_OF_MOUNTED_SLAVEAGENTS];
bool read_mountedSensor(unsigned int s_ix);
void read_all_mountedSensors();
bool save_mountedSensor_history(unsigned int s_ix);
void save_all_mountedSensor_histories();
bool validate_confidence_of_mountedSensor(unsigned int s_ix);
void validate_confidence_of_all_mountedSensors();
bool read_slaveAgent(unsigned int sa_ix);
void read_all_slaveAgents();
public:
// ----- Standard Attributes -----
Agent();
Agent(char* name);
Agent(unsigned int working_frequency, int* success_indicator);
Agent(char* name, unsigned int working_frequency, int* success_indicator);
bool set_working_frequency(unsigned int working_frequency);
// ----- Runtime Functions -----
void trigger();
// ----- Setup Subagents -----
bool mount_slaveagent(Channel* inputport, Channel* outputport);
bool mount_slaveagent(Channel* inputport, Channel* outputport, unsigned int position);
bool mount_slaveagent(Channel* inputport, Channel* outputport, Cross_Confidence_Validator* ccv);
bool mount_masteragent(Channel* inputport, Channel* outputport);
// ----- Setup Mounted Sensors -----
bool mount_sensor(Channel* inputport);
bool mount_sensor(Channel* inputport, unsigned int position);
bool mount_sensor(Channel* inputport, Abstraction* abstraction);
bool mount_sensor(Channel* inputport, Confidence_Validator* confidence_validator);
bool mount_sensor(Channel* inputport, HistoryModule* historyModule);
bool mount_sensor(Channel* inputport, Confidence_Validator* confidence_validator, Abstraction* abstraction);
// ----- Bunch Module -----
bool mount_bunch_module(Bunch_Module* bunch_module);
// ----- Setup Abstraction Method -----
//bool set_abstraction_method(unsigned int abstraction_method);
//unsigned int get_abstraction_method();
//void set_agent_id(unsigned int id);
//unsigned int get_agent_id();
// ----- Setup Agent -----
//TODO: DEACTIVATE, ACTIVATE (muss auch in miunt funktion an den Subagent weitergegeben werden)
void set_active_state_flag(bool flag);
bool get_active_state_flag();
void set_master_agent(Agent* agent);
void Agent :: register_as_master_agent(Agent* agent);
void Agent :: deregister_as_master_agent();
Agent* get_master_agent();
bool get_flag_abstracted_sensor_score_exist(unsigned int position);
int get_abstracted_sensor_score(unsigned int position);
bool get_flag_bunched_score_exist();
int get_bunched_score();
unsigned int get_bunch_score_confidency();
//test functions
void test_print_all_slaveagents();
void test_print_all_sensors();
*/
};
#endif
diff --git a/Version_Max_07_05_2018_CMake/src/CSV_Writer.cpp b/Version_Max_07_05_2018_CMake/src/CSV_Writer.cpp
index 85ef914..91b88a9 100755
--- a/Version_Max_07_05_2018_CMake/src/CSV_Writer.cpp
+++ b/Version_Max_07_05_2018_CMake/src/CSV_Writer.cpp
@@ -1,104 +1,112 @@
#include "CSV_Writer.h"
//#include <string>
//#include <iostream>
#define STRINGLENGTH 5000
-void CSV_Writer :: initialize_csv_writer(const char* filepath_write) {
+void CSV_Writer ::initialize_csv_writer(std::string filepath_write) {
//printf("init ... %s\n", filepath_write);
if(!this->valid_fp) {
- this->fpointer_write = fopen(filepath_write, "w");
- //fopen_s(&fpointer_write, filepath_write, "w");
+#ifdef _WIN32
+ fopen_s(&fpointer_write, filepath_write.c_str(), "w");
+#else
+ this->fpointer_write = fopen(filepath_write.c_str(), "w");
+#endif
+
}else {
close_file();
- this->fpointer_write = fopen(filepath_write, "w");
+#ifdef _WIN32
+ fopen_s(&(this->fpointer_write), filepath_write.c_str(), "w");
+#else
+ this->fpointer_write = fopen(filepath_write.c_str(), "w");
+#endif
}
if(this->fpointer_write != nullptr){
this->valid_fp = true;
}
}
-CSV_Writer :: CSV_Writer(char* filepath_write) {
+CSV_Writer ::CSV_Writer(std::string filepath_write) {
CSV_Writer(NO_NAME, filepath_write);
}
-CSV_Writer :: CSV_Writer(char* name, char* filepath_write) {
+CSV_Writer ::CSV_Writer(std::string name, std::string filepath_write) {
this->valid_fp = false;
set_name(name);
initialize_csv_writer(filepath_write);
}
bool CSV_Writer :: write_field(int dataset) {
if(fpointer_write) {
fprintf(fpointer_write, "%i", dataset);
return true;
}
return false;
}
bool CSV_Writer :: write_field(float dataset) {
if(fpointer_write) {
fprintf(fpointer_write, "%f", dataset);
return true;
}
return false;
}
-bool CSV_Writer :: write_field(char* dataset) {
+bool CSV_Writer :: write_field(std::string dataset) {
if(fpointer_write) {
- fprintf(fpointer_write, "%s", dataset);
+ fprintf(fpointer_write, "%s", dataset.c_str());
return true;
}
return false;
}
bool CSV_Writer :: make_new_field() {
if(fpointer_write) {
fprintf(fpointer_write, ",");
return true;
}
return false;
}
bool CSV_Writer :: make_new_line() {
if(fpointer_write) {
fprintf(fpointer_write, "\n");
return true;
}
return false;
}
bool CSV_Writer :: write_row_data(unsigned int num_of_datasets, float* datasets) {
if(fpointer_write) {
for(unsigned int d_ix=0; d_ix<num_of_datasets; d_ix++) {
fprintf(fpointer_write, "%f", datasets[d_ix]);
if(d_ix < num_of_datasets-1)
fprintf(fpointer_write, ",");
}
fprintf(fpointer_write, "\n");
return true;
}
return false;
}
void CSV_Writer :: reset_fpointer(std::string filepath_write) {
initialize_csv_writer(filepath_write.c_str());
}
void CSV_Writer :: close_file() {
if(fpointer_write) {
fclose(fpointer_write);
this->valid_fp = false;
}
}
CSV_Writer :: ~CSV_Writer()
{
}
diff --git a/Version_Max_07_05_2018_CMake/src/CSV_Writer.h b/Version_Max_07_05_2018_CMake/src/CSV_Writer.h
index 03f0d2f..50bb786 100755
--- a/Version_Max_07_05_2018_CMake/src/CSV_Writer.h
+++ b/Version_Max_07_05_2018_CMake/src/CSV_Writer.h
@@ -1,40 +1,40 @@
#ifndef CSV_WRITER_HEADERFILE
#define CSV_WRITER_HEADERFILE
#include "Module.h"
#include <fstream>
#include <string>
#define MAX_LENGTH_OF_NAMES_TO_WRITE 50
class CSV_Writer : public Module {
private:
FILE *fpointer_write;
- unsigned int num_of_datasets;
- float datasets[MAX_NUM_OF_DATA_SETS];
+ //unsigned int num_of_datasets;
+ //float datasets[MAX_NUM_OF_DATA_SETS];
bool valid_fp;
- void initialize_csv_writer(const char* filepath_write);
+ void initialize_csv_writer(std::string filepath_write);
public:
- CSV_Writer(char* filepath_write);
- CSV_Writer(char* name, char* filepath_write);
+ CSV_Writer(std::string filepath_write);
+ CSV_Writer(std::string name, std::string filepath_write);
bool write_field(int dataset);
bool write_field(float dataset);
- bool write_field(char* dataset);
+ bool write_field(std::string dataset);
bool make_new_field();
bool make_new_line();
bool write_row_data(unsigned int num_of_datasets, float* datasets);
void reset_fpointer(std::string filepath_write);
void close_file();
~CSV_Writer();
};
#endif
diff --git a/Version_Max_07_05_2018_CMake/src/CSVreaderModule.cpp b/Version_Max_07_05_2018_CMake/src/CSVreaderModule.cpp
index f652c26..79ca0a1 100755
--- a/Version_Max_07_05_2018_CMake/src/CSVreaderModule.cpp
+++ b/Version_Max_07_05_2018_CMake/src/CSVreaderModule.cpp
@@ -1,235 +1,236 @@
#include "CSVreaderModule.h"
#include "file_util.h"
#include <string>
#include <string.h>
#include <iostream>
#define STRINGLENGTH 5000
/*
void CSV_Reader :: initialize_csvreader(char* filepath_read, unsigned int num_of_datasets, unsigned int* list_of_datasets, unsigned int start_row) {
//fpointer_read = fopen(filepath_read, "r");
fopen_s(&fpointer_read, filepath_read, "r");
this->num_of_datasets = num_of_datasets;
//TODO: sort.. falls es nicht in aufsteigender folge kommt
for(unsigned int d_ix=0; d_ix<num_of_datasets; d_ix++) {
this->list_of_datasets[d_ix] = list_of_datasets[d_ix];
}
row = 1;
this->start_row = start_row;
}
*/
void CSVreaderModule :: initialize_csvreader(FILE* fpointer, unsigned int column, unsigned int start_row) {
//fpointer_read = fopen(filepath_read, "r");
//TODO: file ponter schon aus CSV-Reader Creator Funktion �bergeben.. dann kann man n�mlich ausgeben, wenn da was nicht erstellt werden kann
//bool file_opened = fopen_s(&fpointer_read, filepath_read, "r");
//TODO: etwas mit flag
this->fpointer = fpointer;
this->row = 1;
this->column = column;
this->start_row = start_row;
flag_csv_reader_configured = true;
}
/*
CSV_Reader :: CSV_Reader(char* filepath_read, unsigned int num_of_data_sets, unsigned int* list_of_datasets, unsigned int start_row) {
set_name(NO_NAME);
initialize_csvreader(filepath_read, num_of_data_sets, list_of_datasets, start_row);
}
CSV_Reader :: CSV_Reader(char* name, char* filepath_read, unsigned int num_of_data_sets, unsigned int* list_of_datasets, unsigned int start_row) {
set_name(name);
initialize_csvreader(filepath_read, num_of_data_sets, list_of_datasets, start_row);
}
*/
CSVreaderModule :: CSVreaderModule() {
set_name(NO_NAME);
flag_csv_reader_configured = false;
}
-CSVreaderModule :: CSVreaderModule(char* name) {
+CSVreaderModule ::CSVreaderModule(std::string name) {
set_name(name);
flag_csv_reader_configured = false;
}
CSVreaderModule :: CSVreaderModule(FILE* fpointer, unsigned int column, unsigned int start_row) {
set_name(NO_NAME);
if(fpointer) {
initialize_csvreader(fpointer, column, start_row);
}
else {
flag_csv_reader_configured = false;
}
}
-CSVreaderModule :: CSVreaderModule(char* name, FILE* fpointer, unsigned int column, unsigned int start_row) {
+CSVreaderModule ::CSVreaderModule(std::string name, FILE *fpointer,
+ unsigned int column, unsigned int start_row) {
set_name(name);
if(fpointer) {
initialize_csvreader(fpointer, column, start_row);
}
else {
flag_csv_reader_configured = false;
}
}
/*
CSV_Reader :: CSV_Reader(char* name, char* filepath_read, int column, int start_row) {
}
*/
//XXX: Wird nicht mehr benutzt
//TODO: �berarbeiten nach folgendem Beispiel https://msdn.microsoft.com/en-us/library/ftsafwz3.aspx
bool CSVreaderModule :: read_one_row() {
if(fpointer)
{
- char readrow[STRINGLENGTH] = "", electedfield[STRINGLENGTH] = "";
+ char readrow[STRINGLENGTH] = "";
//TODO: move following for-loop to "initialize_csvreader(...)
for(;row<start_row; row++) {
if(!fgets(readrow, STRINGLENGTH, fpointer))
return false;
}
if(fgets (readrow, STRINGLENGTH, fpointer))
{
char *ptr, *next_ptr;
//TODO: make delimiter configurable!
- #ifdef WINDOWS_OS
+ #ifdef _WIN32
ptr = strtok_s(readrow, ",;", &next_ptr); //windows version
- #elif !WINDOWS_OS
+ #else
ptr = strtok_r(readrow, ",;", &next_ptr);
#endif
//OLD: unsigned int dataset_counter = 0;
dataset_counter = 0;
if(list_of_datasets[dataset_counter] == 1) {
data_read[dataset_counter] = std::stof(ptr, NULL);
dataset_counter++;
}
else {
- #ifdef WINDOWS_OS
+ #ifdef _WIN32
ptr = strtok_s(NULL, ",;", &next_ptr); //windows version
- #elif !WINDOWS_OS
+ #else
ptr = strtok_r(NULL, ",;", &next_ptr);
#endif
}
for(;dataset_counter<num_of_datasets;dataset_counter++) {
for(unsigned int c_ix=list_of_datasets[dataset_counter-1]; c_ix<list_of_datasets[dataset_counter]; c_ix++)
{
- #ifdef WINDOWS_OS
+ #ifdef _WIN32
ptr = strtok_s(NULL, ",;", &next_ptr); //windows version
- #elif !WINDOWS_OS
+ #else
ptr = strtok_r(NULL, ",;", &next_ptr);
#endif
}
data_read[dataset_counter] = std::stof(ptr, NULL);
}
return true;
}
}
return false;
}
float CSVreaderModule :: get_value_of_field(unsigned int field) {
//TODO: Bessere Fehlerbehandlung.. also nciht einfach 0 returnen, wenn kein richtiges FEld!!!
if(field < num_of_datasets) {
return data_read[field];
}
return 0.0;
}
//TODO: �berarbeiten nach folgendem Beispiel https://msdn.microsoft.com/en-us/library/ftsafwz3.aspx
bool CSVreaderModule :: read_field() {
if(fpointer)
{
- char readrow[STRINGLENGTH] = "", electedfield[STRINGLENGTH] = "";
+ char readrow[STRINGLENGTH] = "";
//TODO: move following for-loop to "initialize_csvreader(...)
for(;row<start_row; row++) {
if(!fgets(readrow, STRINGLENGTH, fpointer))
return false;
}
if(fgets (readrow, STRINGLENGTH, fpointer))
{
char *ptr, *next_ptr;
//TODO: make delimiter configurable!
- #ifdef WINDOWS_OS
+ #ifdef _WIN32
ptr = strtok_s(readrow, ",;", &next_ptr); //windows version
- #elif !WINDOWS_OS
+ #else
ptr = strtok_r(readrow, ",;", &next_ptr);
#endif
for(unsigned int d_ix=1; d_ix<column; d_ix++) {
- #ifdef WINDOWS_OS
+ #ifdef _WIN32
ptr = strtok_s(NULL, ",;", &next_ptr); //windows version
- #elif !WINDOWS_OS
+ #else
ptr = strtok_r(NULL, ",;", &next_ptr);
#endif
}
input_data = std::stof(ptr, NULL);
return true;
}
}
return false;
}
bool CSVreaderModule :: get_next_value(float* value) {
if(flag_csv_reader_configured) {
if(read_field()) {
*value = input_data;
return true;
}
}
return false;
}
void CSVreaderModule :: reset_row(const int row)
{
this->row = row;
}
void CSVreaderModule:: set_position_fpointer_to_start()
{
long int cur_pos;
if(this->fpointer) {
cur_pos = ftell(this->fpointer);
rewind(this->fpointer);
}
}
//TODO: flag_csv_reader_configured abfragen
void CSVreaderModule :: close_file() {
fclose(fpointer);
}
CSVreaderModule :: ~CSVreaderModule(){
if(fpointer) {
close_file();
}
}
diff --git a/Version_Max_07_05_2018_CMake/src/CSVreaderModule.h b/Version_Max_07_05_2018_CMake/src/CSVreaderModule.h
index 2b1ba30..f07c0c7 100755
--- a/Version_Max_07_05_2018_CMake/src/CSVreaderModule.h
+++ b/Version_Max_07_05_2018_CMake/src/CSVreaderModule.h
@@ -1,52 +1,53 @@
#ifndef CSV_READER_HEADERFILE
#define CSV_READER_HEADERFILE
#include "Module.h"
#include <fstream>
class CSVreaderModule : public Module {
private:
FILE *fpointer;
unsigned int num_of_datasets;
unsigned int list_of_datasets[MAX_NUM_OF_DATA_SETS];
float data_read[MAX_NUM_OF_DATA_SETS];
unsigned int row, start_row, column;
float input_data;
bool flag_csv_reader_configured;
unsigned int dataset_counter;
//private fuctions
//void initialize_csvreader(char* filepath_read, unsigned int num_of_datasets, unsigned int* list_of_datasets, unsigned int start_row);
void initialize_csvreader(FILE* fpointer, unsigned int column, unsigned int start_row);
public:
CSVreaderModule();
- CSVreaderModule(char* name);
+ CSVreaderModule(std::string name);
CSVreaderModule(FILE* fpointer, unsigned int column, unsigned int start_row);
- CSVreaderModule(char* name, FILE* fpointer, unsigned int column, unsigned int start_row);
+ CSVreaderModule(std::string name, FILE *fpointer, unsigned int column,
+ unsigned int start_row);
/*
CSV_Reader(char* filepath_read, unsigned int column, unsigned int start_row);
CSV_Reader(char* name, char* filepath_read, unsigned int column, unsigned int start_row);
*/
bool read_one_row();
bool read_field();
float get_value_of_field(unsigned int field);
//new functions
bool get_next_value(float* value);
void reset_row(const int row);
void set_position_fpointer_to_start();
void close_file();
~CSVreaderModule();
};
#endif
diff --git a/Version_Max_07_05_2018_CMake/src/Channel.cpp b/Version_Max_07_05_2018_CMake/src/Channel.cpp
index fec8a73..4e95c2b 100755
--- a/Version_Max_07_05_2018_CMake/src/Channel.cpp
+++ b/Version_Max_07_05_2018_CMake/src/Channel.cpp
@@ -1,350 +1,360 @@
#include "Channel.h"
#include <stdio.h>
#define MAX_BUFFER_LENGTH 100
void Channel :: init_channel() {
maxBufferLength = MAX_BUFFER_LENGTH;
transferRate = MAX_BUFFER_LENGTH;
}
Channel :: Channel() {
init_channel();
}
-Channel :: Channel(char* name) {
+Channel :: Channel(std::string name) {
set_name(name);
init_channel();
}
bool Channel :: set_maxBufferLength(unsigned int maxBufferLength) {
if(maxBufferLength <= MAX_BUFFER_LENGTH) {
this->maxBufferLength = maxBufferLength;
return true;
}
return false;
}
unsigned int Channel :: get_maxBufferLength() {
return maxBufferLength;
}
unsigned int Channel :: get_avlInputBufferUp() {
return maxBufferLength-lInputMsgBufferUp.size();
}
unsigned int Channel :: get_avlOutputBufferUp() {
return maxBufferLength-lOutputMsgBufferUp.size();
}
unsigned int Channel :: get_avlInputBufferDown() {
return maxBufferLength-lInputMsgBufferDown.size();
}
unsigned int Channel :: get_avlOutputBufferDown() {
return maxBufferLength-lOutputMsgBufferDown.size();
}
bool Channel :: set_transferRate(unsigned int transferRate) {
if(transferRate <= MAX_BUFFER_LENGTH) {
this->transferRate = transferRate;
return true;
}
return false;
}
unsigned int Channel :: get_transferRate() {
return transferRate;
}
bool Channel :: add_msgAtBegin (list<Message*>* buffer, Message* message) {
try {
buffer->push_front(message);
}
catch(bad_alloc& error) {
delete message;
return false;
}
return true;
}
bool Channel :: del_msgAtBegin (list<Message*>* buffer) {
try {
/*
printf("a\n");
getchar();
delete buffer->back();
printf("b\n");
getchar();
*/
Message* first_Message = buffer->front();
delete first_Message;
buffer->pop_front();
/*
printf("c\n");
getchar();
*/
}
catch(bad_alloc& error) {
return false;
}
return true;
}
bool Channel :: add_msgAtEnd (list<Message*>* buffer, Message* message) {
try {
buffer->push_back(message);
}
catch(bad_alloc& error) {
cerr << "bad_alloc caught: " << error.what() << endl;
delete message;
return false;
}
return true;
}
bool del_msgAtEnd (list<Message*>* buffer) {
try {
Message* last_Message = buffer->back();
delete last_Message;
buffer->pop_back();
}
catch(bad_alloc& error) {
return false;
}
return true;
}
bool Channel :: send_MsgUp(Message* message) {
if(message != NULL) {
if(transferRate == 0) {
//TODO: at the moment only one packet (in the front) gets deleted if buffer is full. However, the whole message (instruction+value) should be deleted in case of a full buffer
if(lOutputMsgBufferUp.size() == maxBufferLength) {
del_msgAtBegin(&lOutputMsgBufferUp);
}
return add_msgAtEnd(&lOutputMsgBufferUp, message);
}
else {
if(lInputMsgBufferUp.size() == maxBufferLength) {
//TODO: at the moment only one packet (in the front) gets deleted if buffer is full. However, the whole message (instruction+value) should be deleted in case of a full buffer
del_msgAtBegin(&lInputMsgBufferUp);
}
return add_msgAtEnd(&lInputMsgBufferUp, message);
}
}
+
+ //TODO: check if NULL is a good default return value
+ return NULL;
}
bool Channel :: send_MsgUp(float msg) {
Message* message = new Message(msg);
return send_MsgUp(message);
}
bool Channel :: send_MsgUp(int msg) {
Message* message = new Message(msg);
return send_MsgUp(message);
}
bool Channel :: get_MsgUp(float* msg) {
if(isThereFloatMsgUp()) {
float tempMsg;
if(lOutputMsgBufferUp.front()->getMsg(&tempMsg)) {
*msg = tempMsg;
del_msgAtBegin(&lOutputMsgBufferUp);
return true;
}
}
return false;
}
bool Channel :: get_MsgUp(int* msg) {
if(isThereIntMsgUp()) {
int tempMsg;
if(lOutputMsgBufferUp.front()->getMsg(&tempMsg)) {
*msg = tempMsg;
del_msgAtBegin(&lOutputMsgBufferUp);
return true;
}
}
return false;
}
bool Channel :: isThereFloatMsgUp() {
if(lOutputMsgBufferUp.size() > 0 ) {
if(lOutputMsgBufferUp.front() != NULL) {
return lOutputMsgBufferUp.front()->isMsgFloat();
}
}
return false;
}
bool Channel :: isThereIntMsgUp() {
if(lOutputMsgBufferUp.size() > 0 ) {
if(lOutputMsgBufferUp.front() != NULL) {
return lOutputMsgBufferUp.front()->isMsgInt();
}
}
return false;
}
bool Channel :: send_MsgDown(Message* message) {
if(message != NULL) {
if(transferRate == 0) {
if(lOutputMsgBufferDown.size() == maxBufferLength) {
del_msgAtBegin(&lOutputMsgBufferDown);
}
return add_msgAtEnd(&lOutputMsgBufferDown, message);
}
else {
if(lInputMsgBufferDown.size() == maxBufferLength) {
del_msgAtBegin(&lInputMsgBufferDown);
}
return add_msgAtEnd(&lInputMsgBufferDown, message);
}
}
+
+ // TODO: check if NULL is a good default return value
+ return NULL;
}
bool Channel :: send_MsgDown(float msg) {
Message* message = new Message(msg);
return send_MsgDown(message);
}
bool Channel :: send_MsgDown(int msg) {
Message* message = new Message(msg);
return send_MsgDown(message);
}
bool Channel :: get_MsgDown(float* msg) {
if(isThereFloatMsgDown()) {
float tempMsg;
if(lOutputMsgBufferDown.front()->getMsg(&tempMsg)) {
*msg = tempMsg;
del_msgAtBegin(&lOutputMsgBufferDown);
return true;
}
}
return false;
}
bool Channel :: get_MsgDown(int* msg) {
if(isThereIntMsgDown()) {
int tempMsg;
if(lOutputMsgBufferDown.front()->getMsg(&tempMsg)) {
*msg = tempMsg;
del_msgAtBegin(&lOutputMsgBufferDown);
return true;
}
}
return false;
}
bool Channel :: isThereFloatMsgDown() {
if(lOutputMsgBufferDown.size() > 0 ) {
if(lOutputMsgBufferDown.front() != NULL) {
return lOutputMsgBufferDown.front()->isMsgFloat();
}
}
return false;
}
bool Channel :: isThereIntMsgDown() {
if(lOutputMsgBufferDown.size() > 0 ) {
if(lOutputMsgBufferDown.front() != NULL) {
return lOutputMsgBufferDown.front()->isMsgInt();
}
}
return false;
}
bool Channel :: transferMsgs(list<Message*>* dest_buffer, list<Message*>* src_buffer) {
unsigned int NumOfMsgsToMove;
if(transferRate <= src_buffer->size()) {
NumOfMsgsToMove = transferRate;
}
else {
NumOfMsgsToMove = src_buffer->size();
}
if(NumOfMsgsToMove <= maxBufferLength-dest_buffer->size()) {
for(unsigned int i=0; i<NumOfMsgsToMove; i++) {
if(add_msgAtEnd(dest_buffer, src_buffer->front())) {
if(!del_msgAtBegin(src_buffer)) {
return false;
}
}
else {
return false;
}
}
return true;
}
return false;
}
bool Channel :: trigger() {
bool flag_worked = transferMsgs(&lOutputMsgBufferUp, &lInputMsgBufferUp) && transferMsgs(&lOutputMsgBufferUp, &lInputMsgBufferUp);
//printf("Channel %s: in_up %u, out_up %u, in_dn %u, out_dn %u,\n", name, lInputMsgBufferUp.size(), lOutputMsgBufferUp.size(), lInputMsgBufferDown.size(), lOutputMsgBufferDown.size());
return flag_worked;
}
bool Channel :: delete_all_InputMsgBufferUp()
{
Message* cur_Message;
unsigned int cur_index_Message = 0;
unsigned int size_li_Inp_MsgBufUp = lInputMsgBufferUp.size();
- for(cur_index_Message = 0; cur_index_Message < size_li_Inp_MsgBufUp; cur_index_Message){
+ //changed - "cur_index_Message" to "cur_index_Message++" .. is it right?
+ for(cur_index_Message = 0; cur_index_Message < size_li_Inp_MsgBufUp; cur_index_Message++){
cur_Message = lInputMsgBufferUp.front();
delete cur_Message;
lInputMsgBufferUp.pop_front();
}
return true; //added by Ali, it is an error in VS.
}
bool Channel :: delete_all_OuputMsgBufferUp()
{
Message* cur_Message;
unsigned int cur_index_Message = 0;
unsigned int size_li_Out_MsgBufUp = lOutputMsgBufferUp.size();
- for(cur_index_Message = 0; cur_index_Message < size_li_Out_MsgBufUp; cur_index_Message){
+ //changed - "cur_index_Message" to "cur_index_Message++" .. is it right?
+ for(cur_index_Message = 0; cur_index_Message < size_li_Out_MsgBufUp; cur_index_Message++){
cur_Message = lOutputMsgBufferUp.front();
delete cur_Message;
lOutputMsgBufferUp.pop_front();
}
return true; //added by Ali, it is an error in VS.
}
bool Channel :: delete_all_InputMsgBufferDown()
{
Message* cur_Message;
unsigned int cur_index_Message = 0;
unsigned int size_li_Out_MsgBufDown = lInputMsgBufferDown.size();
- for(cur_index_Message = 0; cur_index_Message < size_li_Out_MsgBufDown; cur_index_Message){
+ // changed - "cur_index_Message" to "cur_index_Message++" .. is it right?
+ for(cur_index_Message = 0; cur_index_Message < size_li_Out_MsgBufDown; cur_index_Message++){
cur_Message = lInputMsgBufferDown.front();
delete cur_Message;
lInputMsgBufferDown.pop_front();
}
return true; //added by Ali, it is an error in VS.
}
bool Channel :: delete_all_OutputMsgBufferDown()
{
Message* cur_Message;
unsigned int cur_index_Message = 0;
unsigned int size_li_Out_MsgBufDown = lOutputMsgBufferDown.size();
- for(cur_index_Message = 0; cur_index_Message < size_li_Out_MsgBufDown; cur_index_Message){
+ //changed - "cur_index_Message" to "cur_index_Message++" .. is it right?
+ for(cur_index_Message = 0; cur_index_Message < size_li_Out_MsgBufDown; cur_index_Message++){
cur_Message = lOutputMsgBufferDown.front();
delete cur_Message;
lOutputMsgBufferDown.pop_front();
}
return true; //added by Ali, it is an error in VS.
}
Channel :: ~Channel()
{
delete_all_InputMsgBufferUp();
delete_all_OuputMsgBufferUp();
delete_all_InputMsgBufferDown();
delete_all_OutputMsgBufferDown();
}
diff --git a/Version_Max_07_05_2018_CMake/src/Channel.h b/Version_Max_07_05_2018_CMake/src/Channel.h
index 9139038..7cb56ad 100755
--- a/Version_Max_07_05_2018_CMake/src/Channel.h
+++ b/Version_Max_07_05_2018_CMake/src/Channel.h
@@ -1,81 +1,81 @@
#ifndef CHANNEL_HEADERFILE
#define CHANNEL_HEADERFILE
#include <list>
#include <new>
#include <iostream>
#include "Message.h"
#include "Module.h"
#define MAX_BUFFER_LENGTH 100
#define OPEN NULL
using namespace std;
class Channel : public Module {
private:
list<Message*> lInputMsgBufferUp;
list<Message*> lOutputMsgBufferUp;
list<Message*> lInputMsgBufferDown;
list<Message*> lOutputMsgBufferDown;
unsigned int maxBufferLength;
unsigned int transferRate;
void init_channel();
bool add_msgAtBegin (list<Message*>* buffer, Message* message);
bool del_msgAtBegin (list<Message*>* buffer);
bool add_msgAtEnd (list<Message*>* buffer, Message* message);
bool del_msgAtEnd (list<Message*>* buffer);
bool delete_all_InputMsgBufferUp();
bool delete_all_OuputMsgBufferUp();
bool delete_all_InputMsgBufferDown();
bool delete_all_OutputMsgBufferDown();
public:
Channel();
- Channel(char* name);
+ Channel(std::string name);
bool set_maxBufferLength(unsigned int maxBufferLength);
unsigned int get_maxBufferLength();
unsigned int get_avlInputBufferUp();
unsigned int get_avlOutputBufferUp();
unsigned int get_avlInputBufferDown();
unsigned int get_avlOutputBufferDown();
bool set_transferRate(unsigned int transferRate);
unsigned int get_transferRate();
bool send_MsgUp(Message* message);
bool send_MsgUp(float msg);
bool send_MsgUp(int msg);
bool get_MsgUp(float* msg);
bool get_MsgUp(int* msg);
bool isThereFloatMsgUp();
bool isThereIntMsgUp();
bool send_MsgDown(Message* message);
bool send_MsgDown(float msg);
bool send_MsgDown(int msg);
bool get_MsgDown(float* msg);
bool get_MsgDown(int* msg);
bool isThereFloatMsgDown();
bool isThereIntMsgDown();
bool trigger();
bool transferMsgs(list<Message*>* dest_buffer, list<Message*>* src_buffer);
~Channel();
};
#endif
diff --git a/Version_Max_07_05_2018_CMake/src/ConfidenceModule.cpp b/Version_Max_07_05_2018_CMake/src/ConfidenceModule.cpp
index 5d9548a..3d2ea9d 100755
--- a/Version_Max_07_05_2018_CMake/src/ConfidenceModule.cpp
+++ b/Version_Max_07_05_2018_CMake/src/ConfidenceModule.cpp
@@ -1,167 +1,168 @@
#include "ConfidenceModule.h"
#include "HistoryModule.h"
#include <stdio.h>
//TODO: at the moment are only positive rates_of_changes allowed!!
void ConfidenceModule :: initialize_confidence_validator(float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist) {
//plausibility
if(lower_bound <= upper_bound) {
this->lower_bound = lower_bound;
this->upper_bound = upper_bound;
this->flag_lower_bound_exist = flag_lower_bound_exist;
this->flag_upper_bound_exist = flag_upper_bound_exist;
}
else {
this->lower_bound = upper_bound;
this->upper_bound = lower_bound;
this->flag_lower_bound_exist = flag_upper_bound_exist;
this->flag_upper_bound_exist = flag_lower_bound_exist;
}
//consistency
this->rates_of_change = rates_of_change;
this->flag_rates_of_change_exist = flag_rates_of_change_exist;
flag_value_got_inconsistence = false;
//TODO: Changes of Other Sensors (e.g. Environment Temperature Sensor)
}
ConfidenceModule :: ConfidenceModule(float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist) {
set_name(NO_NAME);
initialize_confidence_validator(lower_bound, flag_lower_bound_exist, upper_bound, flag_upper_bound_exist, rates_of_change, flag_rates_of_change_exist);
}
ConfidenceModule :: ConfidenceModule(char* name, float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist) {
set_name(name);
initialize_confidence_validator(lower_bound, flag_lower_bound_exist, upper_bound, flag_upper_bound_exist, rates_of_change, flag_rates_of_change_exist);
}
bool ConfidenceModule :: validate_confidence(float input, HistoryModule* historyModule) {
bool flag_confidence = true;
//bounds
if(flag_lower_bound_exist && input < lower_bound) {
flag_confidence = false;
//printf("lb\ninput = %f\n", input);
}
if(flag_upper_bound_exist && input > upper_bound) {
flag_confidence = false;
//printf("ub\n");
}
//rates_of_change
- float trend_abs;
+ //TODO: is 0.0 a good initit value??
+ float trend_abs = 0.0;
//TODO: time_unites and time_base should be configurable and saved for the object
- unsigned int time_units = 2;
+ //unsigned int time_units = 2;
bool got_trend = false; //XXX historyModule->get_history_trend_absolutely(&trend_abs, time_units, TB_SECONDS);
if(got_trend) {
if(trend_abs > rates_of_change) {
flag_confidence = false;
//printf("trend\n");
//VERSUCH
if(flag_value_got_inconsistence == false) {
//printf("setze flag\n");
flag_value_got_inconsistence = true;
value_before_value_got_inconsistence = 0; //XXX historyModule->get_value_ago(time_units);
}
}
}
else {
//printf("no trend\n");
}
if(flag_value_got_inconsistence) {
//TODO: nicht hardcoded
float seconds = 20;
//printf("tradition\n");
if(input == value_before_value_got_inconsistence) {
flag_value_got_inconsistence = false;
}
else if(input < value_before_value_got_inconsistence) {
if(input >= value_before_value_got_inconsistence-rates_of_change*seconds) {
flag_value_got_inconsistence = false;
}
else {
flag_confidence = false;
}
}
else if(input > value_before_value_got_inconsistence) {
if(input <= value_before_value_got_inconsistence+rates_of_change*seconds) {
flag_value_got_inconsistence = false;
}
else {
flag_confidence = false;
}
}
else {
flag_confidence = false;
}
}
confidence = flag_confidence;
return confidence;
}
bool ConfidenceModule :: get_confidence() {
return confidence;
}
void ConfidenceModule :: set_lower_bound(float lower_bound) {
this->lower_bound = lower_bound;
}
float ConfidenceModule :: get_lower_bound() {
return lower_bound;
}
void ConfidenceModule :: set_flag_lower_bound_exist(bool flag) {
this->flag_lower_bound_exist = flag;
}
bool ConfidenceModule :: get_flag_lower_bound_exist() {
return flag_lower_bound_exist;
}
void ConfidenceModule :: set_upper_bound(float upper_bound) {
this->upper_bound = upper_bound;
}
float ConfidenceModule :: get_upper_bound() {
return upper_bound;
}
void ConfidenceModule :: set_flag_upper_bound_exist(bool flag) {
this->flag_upper_bound_exist = flag;
}
bool ConfidenceModule :: get_flag_upper_bound_exist() {
return flag_upper_bound_exist;
}
void ConfidenceModule :: set_rates_of_change(float rates) {
this->rates_of_change = rates;
}
float ConfidenceModule :: get_rates_of_change() {
return rates_of_change;
}
void ConfidenceModule :: set_flag_rates_of_change_exist(bool flag) {
this->flag_rates_of_change_exist = flag;
}
bool ConfidenceModule :: get_flag_rates_of_change_exist() {
return flag_rates_of_change_exist;
}
\ No newline at end of file
diff --git a/Version_Max_07_05_2018_CMake/src/Evaluation.cpp b/Version_Max_07_05_2018_CMake/src/Evaluation.cpp
index db0a16e..07f9318 100755
--- a/Version_Max_07_05_2018_CMake/src/Evaluation.cpp
+++ b/Version_Max_07_05_2018_CMake/src/Evaluation.cpp
@@ -1,163 +1,163 @@
#include "Evaluation.h"
#include <stdio.h>
#include "boundary_check.h"
Evaluation :: Evaluation() {
}
Evaluation :: Evaluation(Agent a) {
agent = a;
}
void Evaluation :: set_agent(Agent a) {
agent = a;
}
Agent Evaluation :: get_agent(){
return agent;
}
//TODO: Timeslot observation
void Evaluation :: evaluate_scores_of_mounted_sensor() {
/*
for(unsigned int s_ix=0; s_ix<agent.get_number_of_mounted_sensors(); s_ix++) {
if(agent.get_flag_mounted_sensor_is_active(s_ix)) {
Sensor* sensor = agent.get_mounted_sensor(s_ix);
unsigned int number_of_scores = sensor->get_number_of_scores();
if(sensor->get_flag_use_learned_data()) {
if(is_it_lower_than_boundary(sensor, 0, LOWER_BOUNDARY)) {
for(unsigned int score=1; score<number_of_scores; score++) {
if(!is_it_lower_than_boundary(sensor, score, LOWER_BOUNDARY)) {
sensor->set_score(score);
break;
}
else {
sensor->set_score(score+1);
}
}
}
else if(is_it_higher_than_boundary(sensor, 0, UPPER_BOUNDARY)) {
for(unsigned int score=1; score<number_of_scores; score++) {
if(!is_it_higher_than_boundary(sensor, score, UPPER_BOUNDARY)) {
sensor->set_score(score);
break;
}
else {
sensor->set_score(score+1);
}
}
}
else {
sensor->set_score(0);
}
}
else {
if(is_it_lower_than_hardcoded_boundary(sensor, 0, LOWER_BOUNDARY)) {
for(unsigned int score=1; score<number_of_scores; score++) {
if(!is_it_lower_than_hardcoded_boundary(sensor, 0, LOWER_BOUNDARY)) {
sensor->set_score(score);
break;
}
else {
sensor->set_score(score+1);
}
}
}
else if(is_it_higher_than_hardcoded_boundary(sensor, 0, UPPER_BOUNDARY)) {
for(unsigned int score=1; score<number_of_scores; score++) {
if(!is_it_higher_than_hardcoded_boundary(sensor, 0, LOWER_BOUNDARY)) {
sensor->set_score(score);
break;
}
else {
sensor->set_score(score+1);
}
}
}
else {
sensor->set_score(0);
}
}
printf("Sensor %s (mounted on Agent %s) has the value %f, which leads to the Sensor Score %u\n", sensor->get_name(), agent.get_name(), sensor->get_sensor_value(), sensor->get_score());
}
}
*/
}
//TODO: Timeslot observation
int Evaluation :: evaluate_score_of_Agent() {
/*
float score = 0;
if(agent.get_score_calculation_way() == ARITHMETIC_MEAN) {
for(unsigned int s_ix=0; s_ix<agent.get_number_of_mounted_sensors(); s_ix++) {
if(agent.get_flag_mounted_sensor_is_active(s_ix)) {
score += agent.get_mounted_sensor(s_ix)->get_score();
}
}
for(unsigned int sa_ix=0; sa_ix<agent.get_num_of_mounted_slaveagents(); sa_ix++) {
if(agent.get_flag_mounted_subagent_is_active(sa_ix)) {
printf("aktiv - subscore: %i\n", agent.get_mounted_subagent(sa_ix)->get_score());
score += agent.get_mounted_subagent(sa_ix)->get_score();
}
}
printf(" < score: %f\n", score);
score = score / (agent.get_number_of_active_mounted_sensors() + agent.get_number_of_active_mounted_subagents());
}
- /*
+
else if(agent->get_score_calculation_way() == GEOMETRIC_MEAN) {
for(unsigned int sensor=0; sensor<MAX_NUM_OF_SENSORS; sensor++) {
if(agent->get_sensor_state(sensor)) {
score *= (agent->get_sensor_scores(sensor)+1); //TODO: is das +1 wirklich ok?
number_of_active_sensors++;
}
}
score = pow(score, 1/number_of_active_sensors) - 1; //und hier das -1...?
}
else if(agent->get_score_calculation_way() == HARMONIC_MEAN) {
for(unsigned int sensor=0; sensor<MAX_NUM_OF_SENSORS; sensor++) {
if(agent->get_sensor_state(sensor)) {
score *= (1 / (agent->get_sensor_scores(sensor)+1)); //TODO: is das +1 wirklich ok?
number_of_active_sensors++;
}
}
score = (number_of_active_sensors / score) - 1; //und hier das -1...?
}
else if(agent->get_score_calculation_way() == WEIGHTED_ARITHMETIC_MEAN) {
for(unsigned int sensor=0; sensor<MAX_NUM_OF_SENSORS; sensor++) {
if(agent->get_sensor_state(sensor) && agent->get_sensor_priority(sensor) > 0.0) {
score += ((agent->get_sensor_scores(sensor) + 1) * agent->get_sensor_priority(sensor)); //TODO: is das +1 wirklich ok?
number_of_active_sensors++;
}
}
score = (score / number_of_active_sensors) - 1; //und hier das -1...?
}
else if(agent->get_score_calculation_way() == WEIGHTED_GEOMETRIC_MEAN) {
}
else if(agent->get_score_calculation_way() == WEIGHTED_HARMONIC_MEAN) {
}
agent->set_agent_score((int)(score+0.5));
if(agent->get_agent_score() > agent->get_number_of_agent_scores()) {
agent->set_agent_score(agent->get_number_of_agent_scores());
}
printf("Total score of this Agent is: %i\n\n", agent->get_agent_score());
*/
//return (int)(score+0.5);
return 1; //dummy zeile
}
diff --git a/Version_Max_07_05_2018_CMake/src/HistoryModule.cpp b/Version_Max_07_05_2018_CMake/src/HistoryModule.cpp
index e73291b..9bfb7b0 100755
--- a/Version_Max_07_05_2018_CMake/src/HistoryModule.cpp
+++ b/Version_Max_07_05_2018_CMake/src/HistoryModule.cpp
@@ -1,442 +1,442 @@
#include "HistoryModule.h"
#include "printError.h"
#include <stdio.h>
#define MAX_HIST_LENGTH 1000
//using namespace std;
void HistoryModule :: initHistoryModule() {
if(MAX_HIST_LENGTH <= vHistory.max_size()) {
historyLength = MAX_HIST_LENGTH;
}
else {
historyLength = vHistory.max_size();
}
delimitationMode = DELIMITATE_MODE_SRWF;
}
HistoryModule :: HistoryModule() {
set_name(NO_NAME);
initHistoryModule();
}
-HistoryModule :: HistoryModule(char* name) {
+HistoryModule ::HistoryModule(std::string name) {
initHistoryModule();
set_name(name);
}
bool HistoryModule :: set_maxHistoryLength(unsigned int length) {
if(length <= MAX_HIST_LENGTH && length <= vHistory.max_size()) {
- this->historyLength = historyLength;
+ this->historyLength = length;
return true;
}
return false;
}
unsigned int HistoryModule :: get_maxHistoryLength() {
return historyLength;
}
bool HistoryModule :: set_delimitationMode(int delimitationMode) {
if(delimitationMode > DELIMITATE_MODE_LBOUND && delimitationMode < DELIMITATE_MODE_UBOUND) {
this->delimitationMode = delimitationMode;
return true;
}
return false;
}
int HistoryModule :: get_delimitationMode() {
return delimitationMode;
}
/*
bool HistoryModule :: add_entry(float entryValue)
{
if(vHistory.size() <= historyLength) {
HistoryEntry* historyEntry = new HistoryEntry();
if(historyEntry != NULL) {
historyEntry->set_entryValue(entryValue);
try {
vHistory.push_back(historyEntry);
return true;
}
catch(bad_alloc& error) {
printError("bad_alloc caught: ", error.what());
}
}
else {
printError("Couldn't create HistoryEntry!");
}
}
else {
switch(delimitationMode) {
case DELIMITATE_MODE_SRWF:
printError("History is already full!");
break;
default :
printError("History is already full! DelimitationMode isn't set!");
break;
}
}
return false;
}
*/
unsigned int HistoryModule :: get_numberOfEntries() {
return vHistory.size();
}
/*
void HistoryModule :: initialize_history(unsigned int history_length, unsigned int recording_frequency, unsigned int delimitation_mode, int* success_indicator) {
history_occupied = 0;
history_pointer = 0;
clk_counter = 1;
if(!set_history_length(history_length)) {
*success_indicator = 1;
}
else if(!set_recording_frequency(recording_frequency)) {
*success_indicator = 2;
}
else if(!set_delimitation_mode(delimitation_mode)) {
*success_indicator = 3;
}
else {
*success_indicator = 0;
}
}
HistoryModule :: HistoryModule(unsigned int history_length, unsigned int recording_frequency, unsigned int delimitation_mode, int* success_indicator) {
set_name(NO_NAME);
initialize_history(history_length, recording_frequency, delimitation_mode, success_indicator);
}
HistoryModule :: HistoryModule(char* name, unsigned int history_length, unsigned int recording_frequency, unsigned int delimitation_mode, int* success_indicator) {
set_name(name);
initialize_history(history_length, recording_frequency, delimitation_mode, success_indicator);
}
bool HistoryModule :: set_history_length(unsigned int history_length) {
if(history_length > 0 && history_length <= MAX_HIST_LENGTH) {
this->history_length = history_length;
return true;
}
this->history_length = 0;
return false;
}
bool HistoryModule :: set_recording_frequency(unsigned int recording_frequency) {
if(recording_frequency <= MAX_REC_FREQU) {
this->recording_frequency = recording_frequency;
return true;
}
this->recording_frequency = 0;
return false;
}
bool HistoryModule :: set_delimitation_mode(unsigned int delimitation_mode) {
if(delimitation_mode > DELIMITATE_MODE_LBOUND && delimitation_mode < DELIMITATE_MODE_UBOUND) {
this->delimitation_mode = delimitation_mode;
return true;
}
this->delimitation_mode = HIST_DELIMITATE_MODE_SRWF;
return false;
}
void HistoryModule :: carry_on_history_pointer() {
if(history_pointer >= history_length-1) {
history_pointer = 0;
}
else {
history_pointer++;
}
}
//TODO: namen überarbeiten
bool HistoryModule :: drop_data(float data) {
if(clk_counter == recording_frequency) {
clk_counter = 1;
return rec_data(data);
}
else {
clk_counter++;
return true;
}
return false;
}
bool HistoryModule :: rec_data(float data) {
if(history_occupied < history_length-1) {
history[history_pointer] = data;
carry_on_history_pointer();
history_occupied++;
return true;
}
else {
if(delimitation_mode == HIST_DELIMITATE_MODE_SRWF) {
return false;
}
else if(delimitation_mode == HIST_DELIMITATE_MODE_FIFO) {
history[history_pointer] = data;
carry_on_history_pointer();
return true;
}
else if(delimitation_mode == HIST_DELIMITATE_MODE_LIFO) {
//TODO: implement!
}
else {
return false;
}
}
return false;
}
bool HistoryModule :: get_latest_value(float* value) {
if(history_occupied > 0) {
if(history_pointer > 0) {
*value = history[history_pointer-1];
}
else {
*value = history[history_length-1];
}
return true;
}
return false;
}
bool HistoryModule :: smooth_history() {
if(history_occupied > 1) {
unsigned int calculation_point;
//TODO: kann man anders verschachteln .. in ein if mit || oder &&
if(history_occupied < MAX_HIST_LENGTH-1) {
calculation_point = 0;
}
else {
if(history_pointer < MAX_HIST_LENGTH-1) {
calculation_point = history_pointer;
}
else {
calculation_point = 0;
}
}
//printf("calculation_point = %u\n", calculation_point);
for(unsigned int t_ix=0; t_ix<=history_occupied-1; t_ix++) {
float value, divider;
if(calculation_point == 0) {
//printf("hier?\n");
if(history_occupied == MAX_HIST_LENGTH-1) {
//printf("ja!\n");
value = history[MAX_HIST_LENGTH-1];
divider = 1;
}
else {
value = 0;
divider = 0;
}
value = value + 2*history[calculation_point];
divider = divider + 2;
//printf("value = %f\ndivider = %f\n", value, divider);
//printf("is er da drinnen?\n");
if(t_ix < history_occupied-1) {
//printf("ja\n");
value = value + history[calculation_point+1];
divider = divider + 1;
}
}
else if(calculation_point == MAX_HIST_LENGTH-1) {
value = history[calculation_point-1] + 2*history[calculation_point];
divider = 3;
if(t_ix < history_occupied-1) {
value = value + history[0];
divider = divider + 1;
}
}
else {
value = history[calculation_point-1] + 2*history[calculation_point];
divider = 3;
//printf("da hoffentlich auch nicht\n");
if(t_ix < history_occupied-1) {
//printf("doch\n");
value = value + history[calculation_point+1];
divider = divider + 1;
}
}
//printf("value = %f\ndivider = %f\ncalculation_point = %u\n", value, divider, calculation_point);
history_smoothed[t_ix] = value/divider;
//printf("history_smoothed[%u] = %f\n", t_ix, history_smoothed[t_ix]);
if(calculation_point < MAX_HIST_LENGTH-1) {
calculation_point++;
}
else {
calculation_point = 0;
}
}
return true;
}
return false;
}
//TODO: TO CHECK: small bug when overflow of history array ???
bool HistoryModule :: get_history_trend(float* trend, unsigned int time_unites, unsigned int time_base) {
- /*
+
float trend_temp, divider;
bool got_smoothed = smooth_history();
if(got_smoothed) {
if(time_unites <= MAX_HIST_LENGTH) {
//TODO: fall wenn andere time base
if(this->time_base == time_base) {
if(time_unites < history_occupied) { //XXX <= oder < ???
//printf("a\n");
trend_temp = history_smoothed[history_occupied-1] - history_smoothed[history_occupied-time_unites]; //xxx -1-time_unites oder nur -time_unites ???
divider = (float)time_unites;
}
else {
//printf("b\nhistory_smoothed[history_occupied-1] = %f mit history_occupied = %u\nhistory_smoothed[0] = %f\n", history_smoothed[history_occupied-1], history_occupied, history_smoothed[0]);
trend_temp = history_smoothed[history_occupied-1] - history_smoothed[0];
divider = (float)history_occupied;
//printf("divider = %f\n", divider);
}
*trend = trend_temp/divider;
//printf("trend = %f\n", *trend);
}
return true;
}
}
*/
/* return false;
}
bool HistoryModule :: get_history_trend_absolutely(float* trend, unsigned int time_unites, unsigned int time_base) {
float trend_temp;
bool got_trend = get_history_trend(&trend_temp, time_unites, time_base);
if(got_trend) {
if(trend_temp < 0) {
trend_temp = trend_temp * -1;
}
*trend = trend_temp;
return true;
}
return false;
}
unsigned int HistoryModule :: get_history_occupied() {
return history_occupied;
}
//TODO: Fehlerbehandlung!
float HistoryModule :: get_value_ago(unsigned int ago) {
if(history_occupied >= ago) {
if(history_pointer < ago) {
return history[MAX_HIST_LENGTH-(ago-history_pointer)]; //TO CHECK .. auch ein -1 dazu??
}
else {
return history[history_pointer-ago];
}
} else if (history_occupied > 0) {
return history[0];
}
else {
printf("\n\n\n\n\n\n\nBOESE");
return 0;
}
}
-/*
+
void History :: set_history(unsigned int point, float value) {
if(point<history_max_length) {
if(next_history_pointer < history_max_length) {
history[next_history_pointer] = value;
next_history_pointer++;
}
else {
//if(flag_ring_memory) //TODO: Option(en) einbauen
history[0] = value;
next_history_pointer = 1;
}
}
else {
printf("Field %i of history array is out of range!\n", point);
}
}
unsigned int History :: get_history(unsigned int point) {
if(point<history_max_length) {
return history[point];
}
else {
printf("Field %i of history array is out of range!\n", point);
return NULL;
}
}
void History :: set_history_max_length(unsigned int max_length) {
history_max_length = max_length;
}
unsigned int History :: get_history_max_length() {
return history_max_length;
}
*/
\ No newline at end of file
diff --git a/Version_Max_07_05_2018_CMake/src/HistoryModule.h b/Version_Max_07_05_2018_CMake/src/HistoryModule.h
index 105e5f3..126e062 100755
--- a/Version_Max_07_05_2018_CMake/src/HistoryModule.h
+++ b/Version_Max_07_05_2018_CMake/src/HistoryModule.h
@@ -1,90 +1,90 @@
#ifndef HISTORYMODULE_HEADERFILE
#define HISTORYMODULE_HEADERFILE
#include "HistoryEntry.h"
#include "Module.h"
#include <vector>
/*
#define MAX_HIST_LENGTH 1000
#define MAX_REC_FREQU 4294967295
*/
#define DELIMITATE_MODE_LBOUND 0
#define DELIMITATE_MODE_SRWF 1 //Stop Recording When Full
#define DELIMITATE_MODE_FIFO 2 //First In First Out
#define DELIMITATE_MODE_LIFO 3 //Last In First Out
#define DELIMITATE_MODE_UBOUND 4
using namespace std;
class HistoryModule : public Module {
private:
vector<HistoryEntry*> vHistory;
unsigned int historyLength;
int delimitationMode;
void initHistoryModule();
public:
HistoryModule();
- HistoryModule(char* name);
+ HistoryModule(std::string name);
bool set_maxHistoryLength(unsigned int length);
unsigned int get_maxHistoryLength();
bool set_delimitationMode(int delimitationMode);
int get_delimitationMode();
//bool add_entry();
unsigned int get_numberOfEntries();
/*
float history[MAX_HIST_LENGTH];
unsigned int history_length;
unsigned int recording_frequency;
unsigned int delimitation_mode;
unsigned int history_occupied;
unsigned int history_pointer;
unsigned int clk_counter;
//unsigned int time_base;
float history_smoothed[MAX_HIST_LENGTH];
//private functions
void initialize_history(unsigned int history_length, unsigned int recording_frequency, unsigned int delimitation_mode, int* success_indicator);
void carry_on_history_pointer();
bool smooth_history();
public:
HistoryModule(unsigned int history_length, unsigned int recording_frequency, unsigned int delimitation_mode, int* success_indicator);
HistoryModule(char* name, unsigned int history_length, unsigned int recording_frequency, unsigned int delimitation_mode, int* success_indicator);
bool set_history_length(unsigned int history_length);
bool set_recording_frequency(unsigned int recording_frequency);
bool set_delimitation_mode(unsigned int delimitation_mode);
bool drop_data(float data);
bool rec_data(float data);
bool get_latest_value(float* value);
bool get_history_trend(float* trend, unsigned int time_unites, unsigned int time_base);
bool get_history_trend_absolutely(float* trend, unsigned int time_unites, unsigned int time_base);
unsigned int get_history_occupied();
float get_value_ago(unsigned int ago);
*/
};
#endif
\ No newline at end of file
diff --git a/Version_Max_07_05_2018_CMake/src/LinearFunctionBlock.cpp b/Version_Max_07_05_2018_CMake/src/LinearFunctionBlock.cpp
index c5fe44f..231eaf5 100755
--- a/Version_Max_07_05_2018_CMake/src/LinearFunctionBlock.cpp
+++ b/Version_Max_07_05_2018_CMake/src/LinearFunctionBlock.cpp
@@ -1,109 +1,132 @@
#include "LinearFunctionBlock.h"
#include <limits>
#define PRINT
LinearFunctionBlock::LinearFunctionBlock() {
#ifdef PRINT
printf(" > Linear Function Block created\n");
#endif // PRINT
}
-LinearFunctionBlock::LinearFunctionBlock(char* name) : Module(name) {
+LinearFunctionBlock::LinearFunctionBlock(std::string name) : Module(name) {
#ifdef PRINT
- printf(" > %s (id:%u) created\n", name, id);
+ printf(" > %s (id:%u) created\n", name.c_str(), id);
#endif // PRINT
}
LinearFunctionBlock::~LinearFunctionBlock() {
LinearFunction* cur_Linear_Function;
unsigned int index_cur_Linear_Function;
unsigned int size_vec_Linear_Functions = vLinearFunctions.size();
for(index_cur_Linear_Function = 0; index_cur_Linear_Function < size_vec_Linear_Functions; index_cur_Linear_Function++){
cur_Linear_Function = vLinearFunctions[index_cur_Linear_Function];
delete cur_Linear_Function;
}
vLinearFunctions.clear();
}
//NOTE: for this time being, linear functions have to be filled beginning from lowest x value
bool LinearFunctionBlock::addLinearFunction(LinearFunction *linearFunction) {
if (vLinearFunctions.empty()) {
//printf("empty\n");
if (!(linearFunction->getDomain()->lowerBoundaryExist())) {
vLinearFunctions.push_back(linearFunction);
#ifdef PRINT
printf(" - added function\n");
#endif // PRINT
return true;
}
}
else
{
//printf("nicht empty\n");
if (vLinearFunctions.back()->getDomain()->upperBoundaryExist() && linearFunction->getDomain()->lowerBoundaryExist()) {
//printf("last function ub = %f, new function lb = %f\n", lLinearFunctions.back()->getDomain()->getUpperBoundary(), linearFunction->getDomain()->getLowerBoundary());
if (vLinearFunctions.back()->getDomain()->getUpperBoundary() == linearFunction->getDomain()->getLowerBoundary()) {
vLinearFunctions.push_back(linearFunction);
#ifdef PRINT
printf(" - added function\n");
#endif // PRINT
return true;
}
}
}
#ifdef PRINT
printf(" - couldn't add function\n");
#endif // PRINT
return false;
}
//NOTE: Specific Function for CAH Project (DATE18)
void LinearFunctionBlock::changeFunctionBlockIncr(float newBoundary) {
vLinearFunctions[1]->setDomain(true, (float)0, true, newBoundary);
vLinearFunctions[1]->setKandD((float)0, (float)0, newBoundary, (float)1);
vLinearFunctions[2]->setDomain(true, newBoundary, false);
}
void LinearFunctionBlock::changeFunctionBlockDecr(float newBoundary) {
vLinearFunctions[1]->setDomain(true, (float)0, true, newBoundary);
vLinearFunctions[1]->setKandD((float)0, (float)1, newBoundary, (float)0);
vLinearFunctions[2]->setDomain(true, newBoundary, false);
}
//TODO: jump discontinuity -> user must have the probability to set the value there
float LinearFunctionBlock::getY(float x) {
for (auto &linearFunction : vLinearFunctions) {
if (linearFunction->getDomain()->lowerBoundaryExist() && linearFunction->getDomain()->upperBoundaryExist()) {
if (x >= linearFunction->getDomain()->getLowerBoundary() && x <= linearFunction->getDomain()->getUpperBoundary()) {
return linearFunction->getY(x);
}
}
else if (linearFunction->getDomain()->lowerBoundaryExist()) {
if (x >= linearFunction->getDomain()->getLowerBoundary()) {
return linearFunction->getY(x);
}
}
else if (linearFunction->getDomain()->upperBoundaryExist()) {
if (x <= linearFunction->getDomain()->getUpperBoundary()) {
return linearFunction->getY(x);
}
}
else {
return linearFunction->getY(x);
}
}
//the next two lines should be deleted, but if you call the function getY you have to check for NaN!
printf("DEFAULT!!!!!!!!!!!\n");
getchar();
- return std::numeric_limits<double>::quiet_NaN();
+ return std::numeric_limits<float>::quiet_NaN();
+}
+
+void LinearFunctionBlock ::printFunctionBlock(std::string name) {
+ printf("Name: %s", name.c_str());
+
+ for (auto &lf : vLinearFunctions) {
+
+ float lowerBoundary;
+ float upperBoundary;
+
+ if (lf->getDomain()->getLowerBoundary(&lowerBoundary))
+ printf("(x,y) %f, %f - ", lowerBoundary, lf->getY(lowerBoundary));
+ else
+ printf("oo - ");
+
+ if (lf->getDomain()->getUpperBoundary(&upperBoundary))
+ printf("%f, %f", upperBoundary, lf->getY(upperBoundary));
+ else
+ printf("oo");
+
+ printf("\n");
+
+ }
}
vector<LinearFunction*>& LinearFunctionBlock::get_all_LinearFunctions()
{
return vLinearFunctions;
}
diff --git a/Version_Max_07_05_2018_CMake/src/LinearFunctionBlock.h b/Version_Max_07_05_2018_CMake/src/LinearFunctionBlock.h
index d85d07a..3fceb15 100755
--- a/Version_Max_07_05_2018_CMake/src/LinearFunctionBlock.h
+++ b/Version_Max_07_05_2018_CMake/src/LinearFunctionBlock.h
@@ -1,35 +1,37 @@
#ifndef LINEARFUNCTIONBLOCK_HEADERFILE
#define LINEARFUNCTIONBLOCK_HEADERFILE
#include <vector>
#include <string>
#include "LinearFunction.h"
#include "Module.h"
#include "stdio.h"
using namespace std;
class LinearFunctionBlock : public Module{
private:
//CHECK: list, vector or other container?
vector<LinearFunction*> vLinearFunctions;
public:
LinearFunctionBlock();
- LinearFunctionBlock(char* name);
+ LinearFunctionBlock(std::string name);
~LinearFunctionBlock();
bool addLinearFunction(LinearFunction *linearFunction);
//NOTE: Specific Function for CAH Project (DATE18)
void changeFunctionBlockIncr(float newBoundary);
void changeFunctionBlockDecr(float newBoundary);
vector<LinearFunction*>& get_all_LinearFunctions();
float getY(float x);
+
+ void printFunctionBlock(std::string name);
};
#endif
diff --git a/Version_Max_07_05_2018_CMake/src/MasterAgentSlotOfAgent.h b/Version_Max_07_05_2018_CMake/src/MasterAgentSlotOfAgent.h
index dd94ad1..0a196b0 100755
--- a/Version_Max_07_05_2018_CMake/src/MasterAgentSlotOfAgent.h
+++ b/Version_Max_07_05_2018_CMake/src/MasterAgentSlotOfAgent.h
@@ -1,17 +1,17 @@
#ifndef MASTERAGENTSLOTOFAGENT_HEADERFILE
#define MASTERAGENTSLOTOFAGENT_HEADERFILE
#include "SlotOfAgent.h"
class MasterAgentSlotOfAgent : public SlotOfAgent {
private:
- MasterAgentSlotOfAgent* masterAgentSlotOfAgent;
+ //MasterAgentSlotOfAgent* masterAgentSlotOfAgent;
public:
MasterAgentSlotOfAgent();
};
#endif
\ No newline at end of file
diff --git a/Version_Max_07_05_2018_CMake/src/Module.cpp b/Version_Max_07_05_2018_CMake/src/Module.cpp
index 51c7b1d..eb2e29a 100755
--- a/Version_Max_07_05_2018_CMake/src/Module.cpp
+++ b/Version_Max_07_05_2018_CMake/src/Module.cpp
@@ -1,19 +1,20 @@
#include "Module.h"
Module :: Module() {
set_name(NO_NAME);
}
-Module :: Module(char* name) {
+Module ::Module(std::string name) {
set_name(name);
}
-void Module :: set_name(char* name) {
- strncpy (this->name, name, MAX_LENGTH_NAME);
+void Module :: set_name(std::string name) {
+ this->name = name;
+ //strncpy (this->name, name, MAX_LENGTH_NAME);
}
-char* Module :: get_name() {
+std::string Module :: get_name() {
return this->name;
}
diff --git a/Version_Max_07_05_2018_CMake/src/Module.h b/Version_Max_07_05_2018_CMake/src/Module.h
index 0fc0f74..cbb0598 100755
--- a/Version_Max_07_05_2018_CMake/src/Module.h
+++ b/Version_Max_07_05_2018_CMake/src/Module.h
@@ -1,20 +1,22 @@
#ifndef MODULE_HEADERFILE
#define MODULE_HEADERFILE
-#include <string.h>
+#include <string>
#include "Unit.h"
class Module : public Unit {
protected:
- char name[MAX_LENGTH_NAME];
+ std::string name;
+ //[MAX_LENGTH_NAME];
public:
Module();
- Module(char* name);
+ Module(std::string name);
+
+ void set_name(std::string name);
+ std::string get_name();
- void set_name(char* name);
- char* get_name();
};
#endif
diff --git a/Version_Max_07_05_2018_CMake/src/Sensor.cpp b/Version_Max_07_05_2018_CMake/src/Sensor.cpp
index 06776da..97c2ba5 100755
--- a/Version_Max_07_05_2018_CMake/src/Sensor.cpp
+++ b/Version_Max_07_05_2018_CMake/src/Sensor.cpp
@@ -1,184 +1,184 @@
#include "Sensor.h"
#include <stdio.h>
//unsigned int Sensor :: number_of_sensors = 0;
void Sensor :: initialize_sensor() {
this->flag_masteragent_is_mounted = UNMOUNTED;
this->flag_masteragent_outputport_is_active = INACTIVE;
this->flag_sensor_value_is_valid = INVALID;
this->flag_sensor_value_has_changed = NO;
this->flag_send_value_only_when_changed = NO;
workingCycleCounter = 1;
}
Sensor :: Sensor() {
set_name(NO_NAME);
initialize_sensor();
}
-Sensor :: Sensor(char* name) {
+Sensor :: Sensor(std::string name) {
set_name(name);
initialize_sensor();
}
// ----- Runtime Functions -----
void Sensor :: set_sensorValue(float sensor_value) {
if (sensor_value != sensor_value) { //If NaN
if (flag_sensor_value_is_valid == true) {
// don't do anything .. just keep old value
}
else {
this->sensor_value = 0; //xxx - don't know if 0 is the best default value.. but in the beginning of a dataset, it most likely won't affact anything
}
}
else {
if (flag_sensor_value_is_valid == true) {
if (this->sensor_value != sensor_value) {
flag_sensor_value_has_changed = YES;
}
}
flag_sensor_value_is_valid = VALID;
this->sensor_value = sensor_value;
}
//printf("Sensor %s updated with: %f\n", name, sensor_value);
}
float Sensor :: get_sensorValue() {
return sensor_value;
}
void Sensor :: trigger() {
if (workingCycleCounter == 1) {
//TODO: difference int and float
if(this->flag_sensor_value_is_valid && this->flag_masteragent_is_mounted && this->flag_masteragent_outputport_is_active){
if(flag_send_value_only_when_changed) {
if(flag_sensor_value_has_changed) {
mounted_masteragent_outputport->send_MsgUp(sensor_value);
flag_sensor_value_has_changed = NO;
}
}
else {
mounted_masteragent_outputport->send_MsgUp(sensor_value);
flag_sensor_value_has_changed = NO;
}
}
}
if (workingCycleCounter < get_workingCycle())
workingCycleCounter++;
else
workingCycleCounter = 1;
}
// ----- Setup Functions -----
bool Sensor :: mount_agent(Channel* outputport) {
if(outputport != NULL) {
this->mounted_masteragent_outputport = outputport;
this->flag_masteragent_is_mounted = MOUNTED;
this->flag_masteragent_outputport_is_active = ACTIVE;
return true;
}
return false;
}
void Sensor :: set_flag_send_value_only_when_changed(bool flag_send_value_only_when_changed) {
this->flag_send_value_only_when_changed = flag_send_value_only_when_changed;
}
bool Sensor :: get_flag_send_value_only_when_changed() {
return this->flag_send_value_only_when_changed;
}
// ----- set/get -----
void Sensor :: set_flag_sensor_value_is_valid(bool flag_sensor_value_is_valid) {
this->flag_sensor_value_is_valid = flag_sensor_value_is_valid;
}
bool Sensor :: get_flag_sensor_value_is_valid() {
return this->flag_sensor_value_is_valid;
}
void Sensor :: set_flag_sensor_value_has_changed(bool flag_sensor_value_has_changed) {
this->flag_sensor_value_has_changed = flag_sensor_value_has_changed;
}
bool Sensor :: get_flag_sensor_value_has_changed() {
return this->flag_sensor_value_has_changed;
}
/*
void Sensor :: set_sensor_id(unsigned int id) {
sensor_id = id;
}
unsigned int Sensor :: get_sensor_id() {
return sensor_id;
}*/
void Sensor :: set_active_state_flag(bool flag) {
active_state_flag = flag;
}
bool Sensor :: get_active_state_flag() {
return active_state_flag;
}
/*
void Sensor :: set_number_of_scores (unsigned int number) {
number_of_scores = number;
}
unsigned int Sensor :: get_number_of_scores() {
return number_of_scores;
}
*/
float Sensor :: get_hardcoded_threshold(unsigned int score, unsigned int boundary) {
return hardcoded_thresholds[score][boundary];
}
void Sensor :: set_hardcoded_threshold(unsigned int score, unsigned int boundary, float value) {
hardcoded_thresholds[score][boundary] = value;
}
float Sensor :: get_learned_threshold(unsigned int score, unsigned int boundary) {
return learned_thresholds[score][boundary];
}
void Sensor :: set_learned_threshold(unsigned int score, unsigned int boundary, float value) {
learned_thresholds[score][boundary] = value;
}
void Sensor :: set_flag_learned_boundary_exist(unsigned int score, unsigned int boundary, bool flag) {
flag_learned_boundary_exist[score][boundary] = flag;
}
bool Sensor :: get_flag_learned_boundary_exist(unsigned int score, unsigned int boundary) {
return flag_learned_boundary_exist[score][boundary];
}
void Sensor :: set_flag_use_learned_data(bool flag) {
flag_use_learned_data = flag;
}
bool Sensor :: get_flag_use_learned_data() {
return flag_use_learned_data;
}
diff --git a/Version_Max_07_05_2018_CMake/src/Sensor.h b/Version_Max_07_05_2018_CMake/src/Sensor.h
index 5619d3d..f525ec5 100755
--- a/Version_Max_07_05_2018_CMake/src/Sensor.h
+++ b/Version_Max_07_05_2018_CMake/src/Sensor.h
@@ -1,119 +1,119 @@
#ifndef SENSOR_HEADERFILE
#define SENSOR_HEADERFILE
#include "project_settings.h"
#include "Node.h"
#include "Channel.h"
#define MAX_NUM_OF_SCORES 10
#define LOWER_BOUNDARY 0
#define UPPER_BOUNDARY 1
#define LEARNED_BOUNDARY_DOES_EXIST true
#define LEARNED_BOUNDARY_DOESNT_EXIST false
#define USE_LEARNED_DATA true
#define DONT_USE_LEARNED_DATA false
#define VALID true
#define INVALID false
class Sensor : public Node {
private:
// ----- Runtime -----
float sensor_value;
bool flag_sensor_value_is_valid;
bool flag_sensor_value_has_changed;
// ----- Setup Master -----
bool flag_masteragent_is_mounted;
Channel* mounted_masteragent_outputport;
bool flag_masteragent_outputport_is_active; //unnötig?
// ----- Setup Behavior -----
bool flag_send_value_only_when_changed;
unsigned int workingCycleCounter;
//noch nicht überarbeitet
bool active_state_flag;
float hardcoded_thresholds[MAX_NUM_OF_SCORES][2];
float learned_thresholds[MAX_NUM_OF_SCORES][2];
bool flag_learned_boundary_exist[MAX_NUM_OF_SCORES][2];
bool flag_use_learned_data;
void initialize_sensor();
public:
Sensor();
- Sensor(char* name);
+ Sensor(std::string name);
// ----- Runtime Functions -----
void set_sensorValue(float sensor_value);
float get_sensorValue();
void trigger();
// ----- Setup -----
bool mount_agent(Channel* outputport);
void set_flag_send_value_only_when_changed(bool flag_send_value_only_when_changed);
bool get_flag_send_value_only_when_changed();
/*
void set_sensor_id(unsigned int id);
unsigned int get_sensor_id();
*/
// ----- set/get -----
void set_flag_sensor_value_is_valid(bool flag_sensor_value_is_valid);
bool get_flag_sensor_value_is_valid();
void set_flag_sensor_value_has_changed(bool flag_sensor_value_has_changed);
bool get_flag_sensor_value_has_changed();
void set_active_state_flag(bool flag);
bool get_active_state_flag();
float get_hardcoded_threshold(unsigned int score, unsigned int boundary);
void set_hardcoded_threshold(unsigned int score, unsigned int boundary, float value);
float get_learned_threshold(unsigned int score, unsigned int boundary);
void set_learned_threshold(unsigned int score, unsigned int boundary, float value);
void set_flag_learned_boundary_exist(unsigned int score, unsigned int boundary, bool flag);
bool get_flag_learned_boundary_exist(unsigned int score, unsigned int boundary);
void set_flag_use_learned_data(bool flag);
bool get_flag_use_learned_data();
};
#endif
\ No newline at end of file
diff --git a/Version_Max_07_05_2018_CMake/src/SlaveAgentSlotOfAgent.cpp b/Version_Max_07_05_2018_CMake/src/SlaveAgentSlotOfAgent.cpp
index 12ae84f..82fa5d2 100755
--- a/Version_Max_07_05_2018_CMake/src/SlaveAgentSlotOfAgent.cpp
+++ b/Version_Max_07_05_2018_CMake/src/SlaveAgentSlotOfAgent.cpp
@@ -1,225 +1,225 @@
#include "SlaveAgentSlotOfAgent.h"
#include "stdio.h"
#include "printError.h"
#include "relationChecker.h"
SlaveAgentSlotOfAgent :: SlaveAgentSlotOfAgent() {
flagSlaveAgentValueIsSet = false;
/*
flagSlaveAgentValueHasChanged = false;
flagSlaveAgentValueChangeIsSet = false;
- /*
+
activeState = NULL;
backupState = NULL;
*/
}
void SlaveAgentSlotOfAgent :: setSlaveAgentValue(float slaveAgentValue) {
this->slaveAgentValue = slaveAgentValue;
flagSlaveAgentValueIsSet = true;
/*
if(flagSlaveAgentValueIsSet == false) {
this->slaveAgentValue = slaveAgentValue;
flagSlaveAgentValueIsSet = true;
flagSlaveAgentValueHasChanged = true;
}
else {
if(this->slaveAgentValue != slaveAgentValue) {
flagSlaveAgentValueHasChanged = true;
flagSlaveAgentValueChangeIsSet = true;
slaveAgentValueChange = slaveAgentValue - this->slaveAgentValue;
this->slaveAgentValue = slaveAgentValue;
}
else {
flagSlaveAgentValueHasChanged = false;
flagSlaveAgentValueChangeIsSet = true;
slaveAgentValueChange = 0;
}
}
*/
//printf("slaveAgentSlot updated with: %f\n", this->slaveAgentValue);
}
bool SlaveAgentSlotOfAgent :: get_slaveAgentValue(float* slaveAgentValue) {
if(flagSlaveAgentValueIsSet == true) {
*slaveAgentValue = this->slaveAgentValue;
return true;
}
return false;
}
bool SlaveAgentSlotOfAgent :: get_flagSlaveAgentValueIsSet() {
return flagSlaveAgentValueIsSet;
}
//TODO: move these functions into -> HistoryHandler
bool SlaveAgentSlotOfAgent::saveValueInHistory() {
if (flagSlaveAgentValueIsSet) {
try {
//printf("history saving - value: %f\n", slaveAgentValue);
lSlaveAgentHistory.push_back(slaveAgentValue);
return true;
}
catch (bad_alloc& error) {
printError("bad_alloc caught: ", error.what());
}
}
return false;
}
unsigned int SlaveAgentSlotOfAgent::getHistoryLength() {
return lSlaveAgentHistory.size();
}
bool SlaveAgentSlotOfAgent::deleteOldestHistoryEntry() {
if (!lSlaveAgentHistory.empty()) {
lSlaveAgentHistory.pop_front();
return true;
}
return false;
}
unsigned int SlaveAgentSlotOfAgent::getNumberOfRelativesToActualValue(float threshold) {
unsigned int numberOfRelativesToActualValue = 0;
for (auto &entry : lSlaveAgentHistory) {
if (valueIsRelatedToReferenceValue(slaveAgentValue, entry, threshold)) {
numberOfRelativesToActualValue++;
}
}
return numberOfRelativesToActualValue;
}
//DATE18
list<float> SlaveAgentSlotOfAgent::getHistory() {
return lSlaveAgentHistory;
}
void SlaveAgentSlotOfAgent::printHistory() {
printf("History: ");
for (auto &entry : lSlaveAgentHistory) {
printf("%f, ", entry);
}
printf("\n");
}
SlaveAgentSlotOfAgent :: ~SlaveAgentSlotOfAgent()
{
- int i = 0;
+ //int i = 0;
}
/*
bool SlaveAgentSlotOfAgent :: get_flagSlaveAgentValueHasChanged() {
return flagSlaveAgentValueHasChanged;
}
bool SlaveAgentSlotOfAgent :: get_slaveAgentValueChangingRate(float* slaveAgentValueChangingRate) {
if(flagSlaveAgentValueChangeIsSet) {
*slaveAgentValueChangingRate = this->slaveAgentValueChange;
return true;
}
return false;
}
-/*
+
bool SlaveAgentSlotOfAgent :: addStateToStatesVector(State* state) {
if (state != NULL) {
try {
vStates.push_back(state);
return true;
}
catch (bad_alloc& error) {
printError("bad_alloc caught: ", error.what());
delete state;
}
}
return false;
}
vector<State*>* SlaveAgentSlotOfAgent :: getStatesVector() {
return &vStates;
}
bool SlaveAgentSlotOfAgent :: createNewStateAndMakeItActive() {
State* state = new State();
if (addStateToStatesVector(state)) {
backupState = activeState;
activeState = state;
return true;
}
return false;
}
bool SlaveAgentSlotOfAgent :: injectValueInActiveState() {
if (activeState == NULL) {
if (createNewStateAndMakeItActive()) {
return activeState->injectValue(slaveAgentValue);
}
}
return activeState->injectValue(slaveAgentValue);
}
int SlaveAgentSlotOfAgent :: getIndexOfRelatedState(unsigned int startIndex, float thresholdToAverage) {
if (startIndex >= vStates.size())
return -2;
int index = 0;
for (vector<State*>::iterator state = vStates.begin() + startIndex; state < vStates.end(); state++, index++) {
if ((*state)->valueIsRelated(slaveAgentValue, thresholdToAverage)) {
return index;
}
}
return -1;
}
bool SlaveAgentSlotOfAgent :: relatedToActiveState(float thresholdToAverage) {
printf("a\n");
if (activeState == NULL) {
printf("b\n");
createNewStateAndMakeItActive();
return true;
}
return activeState->valueIsRelated(slaveAgentValue, thresholdToAverage);
}
bool SlaveAgentSlotOfAgent :: valueIsRelated(unsigned int index, float thresholdToAverage) {
return vStates[index]->valueIsRelated(slaveAgentValue, thresholdToAverage);
}
State* SlaveAgentSlotOfAgent :: getActiveState() {
return activeState;
}
void SlaveAgentSlotOfAgent :: deleteActiveState() {
//if(vStates.empty() == false)
vStates.back()->deleteState();
vStates.pop_back();
if (backupState != NULL) {
activeState = backupState;
backupState = NULL;
}
}
bool SlaveAgentSlotOfAgent :: setActiveState(unsigned int index) {
if (vStates.size() > index) {
activeState = vStates.at(index);
return true;
}
return false;
}
unsigned int SlaveAgentSlotOfAgent::getNumberOfStates() {
if (!vStates.empty())
printf("%u - ", activeState->getNumberOfInjections());
return vStates.size();
}
*/
diff --git a/Version_Max_07_05_2018_CMake/src/SlaveAgentSlotOfAgent.h b/Version_Max_07_05_2018_CMake/src/SlaveAgentSlotOfAgent.h
index dfc9269..b772f34 100755
--- a/Version_Max_07_05_2018_CMake/src/SlaveAgentSlotOfAgent.h
+++ b/Version_Max_07_05_2018_CMake/src/SlaveAgentSlotOfAgent.h
@@ -1,83 +1,42 @@
#ifndef SLAVEAGENTSLOTOFAGENT_HEADERFILE
#define SLAVEAGENTSLOTOFAGENT_HEADERFILE
#include "SlotOfAgent.h"
//#include "State.h"
class SlaveAgentSlotOfAgent : public SlotOfAgent {
private:
//TODO: set- and get function for maxNumOf_mountedSensors;
float slaveAgentValue;
list<float> lSlaveAgentHistory;
bool flagSlaveAgentValueIsSet;
- /*
- //XXX - next 3 variables needed?
- bool flagSlaveAgentValueHasChanged;
- bool flagSlaveAgentValueChangeIsSet;
- float slaveAgentValueChange;
- */
-
-
-
- /*
- vector<State*> vStates;
- State* activeState;
- State* backupState;
-
- bool
- ateToStatesVector(State* state);
- */
public:
SlaveAgentSlotOfAgent();
void setSlaveAgentValue(float slaveAgentValue);
bool get_slaveAgentValue(float* slaveAgentValue);
bool get_flagSlaveAgentValueIsSet();
//TODO: move these functions into -> HistoryHandler
bool saveValueInHistory();
unsigned int getHistoryLength();
bool deleteOldestHistoryEntry();
unsigned int getNumberOfRelativesToActualValue(float threshold);
//DATE18
list<float> getHistory();
void printHistory();
~SlaveAgentSlotOfAgent();
-
- /*
- bool get_flagSlaveAgentValueHasChanged();
-
- bool get_slaveAgentValueChangingRate(float* slaveAgentValueChangingRate);
-
- /*
- vector<State*>* getStatesVector();
- bool createNewStateAndMakeItActive();
- bool injectValueInActiveState();
- int getIndexOfRelatedState(unsigned int startIndex, float thresholdToAverage);
-
- bool relatedToActiveState(float thresholdToAverage);
- bool valueIsRelated(unsigned int index, float thresholdToAverage);
-
- State* getActiveState();
- void deleteActiveState();
- bool setActiveState(unsigned int index);
- unsigned int getNumberOfStates();
- */
- /*
- vector<State*>* getStatesVector();
- State* getActiveState();
- */
};
#endif
diff --git a/Version_Max_07_05_2018_CMake/src/StateHandler.cpp b/Version_Max_07_05_2018_CMake/src/StateHandler.cpp
index 61793f0..89a4c7e 100755
--- a/Version_Max_07_05_2018_CMake/src/StateHandler.cpp
+++ b/Version_Max_07_05_2018_CMake/src/StateHandler.cpp
@@ -1,1832 +1,1848 @@
#include "StateHandler.h"
#include "config.h"
#include <algorithm>
#include "printError.h"
#include "rlutil.h"
#include "relationChecker.h"
#include "minmaxzeug.h"
#include "file_util.h"
#include <iostream>
#include <ctime>
//CHANGE ALSO BOTH FUZZY FUNCTION!!!
// is used for the history length of the number of values which will be compared
//to the current value
#define MAX_STATE_HISTORY_LENGTH 10 //10
#define STOP_WHEN_BROKEN
-//#define STOP_AFTER_BROKEN
-//#define STOP_WHEN_DRIFT
-//#define STOP_WHEN_STATE_VALID
+#define STOP_AFTER_BROKEN
+#define STOP_WHEN_DRIFT
+#define STOP_WHEN_STATE_VALID
#define PRINT
//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
//three different status are for the system possible
#define STATUS_BROKEN 1
#define STATUS_DRIFT 2
#define STATUS_OKAY 3
using namespace rlutil;
-
+//TODO überladen mit Parameter CSV-Writer Name. :-) Bitte, nur für dich Maxi.
void StateHandler::initStateHandler() {
csv_writer = NULL;
flagVariablesWereStable = false;
slidingWindowBufferSize = SLIDINGWINDOWSIZE;
minNumOfRelatedValuesToBeStable = STABLENUMBER;
thresholdToBeStable = STABLETHRESHOLD;
thresholdToBeRelated = RELATEDTHRESHOLD;
discreteAveragePartitionSize = INJECTIONPARTITIONING;
compareDistanceDiscreteAveragePartition = CMPDISTANCE;
thresholdNotDrift = THDRIFT;
minNumToBeValidState = MINNUMTOBEVALIDSTATE;
activeState = NULL;
maxStateHistoryLength = MAX_STATE_HISTORY_LENGTH;
time_t rawtime;
- struct tm * timeinfo;
- char output_file_name[200];
+
+ struct tm timeinfo;
+ //char output_file_name[200];
char datetime[80];
const std::string output_directory_name = "../data/out/"; // "./output_data_csv/Opel/2018-08-09/"; there is no impact if we change it!
std::string output_file_name_str;
time(&rawtime);
- timeinfo = localtime(&rawtime);
+ //timeinfo = localtime(&rawtime);
+ localtime_s(&timeinfo, &rawtime);
- strftime(datetime, sizeof(datetime), "%Y-%m-%d_%I-%M-%S", timeinfo);
+ strftime(datetime, sizeof(datetime), "%Y-%m-%d_%I-%M-%S", &timeinfo);
#ifndef INPUT_FILE_NAME
output_file_name_str = output_directory_name + "output" + datetime + ".csv";
#else
output_file_name_str = output_directory_name + INPUT_FILE_NAME + datetime + ".csv";
#endif //INPUT_FILE_NAME
cout << output_file_name_str << endl;
//XXX - only for now:
//Ali printf("\n csv_Writer is not NULL, but it is not initialized!! \n");
+ /*
if (csv_writer == NULL) {
csv_writer = new CSV_Writer("CSV Writer", (char*)output_file_name_str.c_str());
}
-
+ */
//DATE18
confidenceStableInput = 0;
confidenceStableOutput = 0;
confidenceStable = 0;
confStableAdjustableThreshold = 0.5;
confidenceUnstableInput = 0;
confidenceUnstableOutput = 0;
confidenceUnstable = 0;
confidenceUnstableAdjustableThreshold = 0.5;
confidenceSameStateInput = 0;
confSameStateInputAdjustableThreshold = 0.5;
confidenceSameStateOutput = 0;
confSameStateOutputAdjustableThreshold = 0.5;
confidenceValidState = 0;
confValidStateAdjustableThreshold = 0.5;
brokenCounter = 0;
confidenceBroken = 0;
confidenceBrokenAdjustableThreshold = 0.5;
driftCounter = 0;
confidenceDrift = 0;
confidenceDriftAdjustableThreshold = 0.5;
}
StateHandler::StateHandler() {
set_name(NO_NAME);
initStateHandler();
}
-StateHandler::StateHandler(char* name) {
+StateHandler::StateHandler(std::string name) {
set_name(name);
initStateHandler();
}
+StateHandler::StateHandler(std::string name, std::string csvWriterPath) {
+ set_name(name);
+ initStateHandler();
+ csv_writer = new CSV_Writer("CSV Writer", csvWriterPath);
+}
+
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::delete_all_OuputVariables()
{
SlaveAgentSlotOfAgent* cur_sl_ag_sl_ag;
unsigned int index_v_OutVar;
unsigned int size_v_OutVar = vOutputVariables.size();
for(index_v_OutVar = 0; index_v_OutVar < size_v_OutVar; index_v_OutVar++) {
cur_sl_ag_sl_ag = vOutputVariables[index_v_OutVar];
delete cur_sl_ag_sl_ag;
}
vOutputVariables.clear();
return true; //added by Ali, it is an error in VS.
}
bool StateHandler::delete_all_InputVariables()
{
SlaveAgentSlotOfAgent* cur_sl_ag_sl_ag;
unsigned int index_v_InpVar;
unsigned int size_v_InpVar = vInputVariables.size();
for(index_v_InpVar = 0; index_v_InpVar < size_v_InpVar; index_v_InpVar++) {
cur_sl_ag_sl_ag = vInputVariables[index_v_InpVar];
delete cur_sl_ag_sl_ag;
}
vInputVariables.clear();
return true; //added by Ali, it is an error in VS.
}
bool StateHandler::delete_allStates()
{
State* cur_state;
unsigned int index_v_State;
unsigned int size_v_State = vStates.size();
for(index_v_State = 0; index_v_State < size_v_State; index_v_State++) {
cur_state = vStates[index_v_State];
delete cur_state;
}
vStates.clear();
return true; //added by Ali, it is an error in VS.
}
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::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;
}
//Sorting with bigger Value in Front
struct descending
{
template<class T>
bool operator()(T const &a, T const &b) const { return a > b; }
};
//DATE18
float StateHandler::getConfVariableIsStable(SlaveAgentSlotOfAgent* variable) {
float bestConfOf1Var = 0;
float sample;
if (variable->get_slaveAgentValue(&sample)) {
list<float> lHistoryTemporary = variable->getHistory();
vector<float> vDeviations;
for (auto &h : lHistoryTemporary)
vDeviations.push_back(deviationValueReferenceValue(sample, h));
std::sort(std::begin(vDeviations), std::end(vDeviations));
//all adaptabilities within the history of one variable
for (unsigned int numOfHistSamplesIncluded = 1; numOfHistSamplesIncluded <= vDeviations.size(); numOfHistSamplesIncluded++) {
float worstConfOfHistSampleSet = 1;
unsigned int histSampleCounter = 0;
for (auto &deviation : vDeviations) {
if (histSampleCounter >= numOfHistSamplesIncluded)
break;
worstConfOfHistSampleSet = minValueOf2Values(worstConfOfHistSampleSet, StabDeviation->getY(deviation));
histSampleCounter++;
}
bestConfOf1Var = maxValueOf2Values(bestConfOf1Var, minValueOf2Values(worstConfOfHistSampleSet, StabSamples->getY((float)histSampleCounter)));
}
}
return bestConfOf1Var;
}
//DATE18
float StateHandler::getConfVariablesAreStable(vector<SlaveAgentSlotOfAgent*>* vVariables) {
float worstConfOfAllVariables = 1;
for (auto &slot : *vVariables)
worstConfOfAllVariables = minValueOf2Values(worstConfOfAllVariables, getConfVariableIsStable(slot));
return worstConfOfAllVariables;
}
//DATE18
float StateHandler::getConfVariableIsUnstable(SlaveAgentSlotOfAgent* variable) {
float bestConfOf1Var = 0;
float sample;
if (variable->get_slaveAgentValue(&sample)) {
list<float> lHistoryTemporary = variable->getHistory();
vector<float> vDeviations;
for (auto &h : lHistoryTemporary)
vDeviations.push_back(deviationValueReferenceValue(sample, h));
sort(begin(vDeviations), end(vDeviations), descending());
//all adaptabilities within the history of one variable
for (unsigned int numOfHistSamplesIncluded = 1; numOfHistSamplesIncluded <= vDeviations.size(); numOfHistSamplesIncluded++) {
//float bestConfOfHistSampleSet = 1;
float bestConfOfHistSampleSet = 0;
unsigned int histSampleCounter = 0;
for (auto &deviation : vDeviations) {
if (histSampleCounter >= numOfHistSamplesIncluded)
break;
//bestConfOfHistSampleSet = minValueOf2Values(bestConfOfHistSampleSet, UnstabDeviation->getY(deviation));
bestConfOfHistSampleSet = maxValueOf2Values(bestConfOfHistSampleSet, UnstabDeviation->getY(deviation));
histSampleCounter++;
}
bestConfOf1Var = maxValueOf2Values(bestConfOf1Var, minValueOf2Values(bestConfOfHistSampleSet, StabSamples->getY((float)histSampleCounter)));
}
}
return bestConfOf1Var;
}
//DATE18 - Is there one unstable variable?
float StateHandler::getConfVariablesAreUnstable(vector<SlaveAgentSlotOfAgent*>* vVariables) {
float bestConfOfAllVariables = 0;
for (auto &slot : *vVariables)
bestConfOfAllVariables = maxValueOf2Values(bestConfOfAllVariables, getConfVariableIsUnstable(slot));
return bestConfOfAllVariables;
}
-
+/*
bool StateHandler::getConfAndUnconfVariableIsMatching(State* state, LinearFunctionBlock* confDeviation, LinearFunctionBlock* confTime, float* conf, float* unconf) {
float bestUnconfOf1Var = 0;
float worstConfOf1Var = 1;
if (state != NULL) {
}
- /*
+
float sample;
if (variable->get_slaveAgentValue(&sample)) {
list<float> lHistoryTemporary = variable->getHistory();
vector<float> vDeviations;
for (auto &h : lHistoryTemporary)
vDeviations.push_back(deviationValueReferenceValue(sample, h));
sort(begin(vDeviations), end(vDeviations), descending());
//all adaptabilities within the history of one variable
for (unsigned int numOfHistSamplesIncluded = 1; numOfHistSamplesIncluded <= vDeviations.size(); numOfHistSamplesIncluded++) {
//float bestConfOfHistSampleSet = 1;
float bestConfOfHistSampleSet = 0;
unsigned int histSampleCounter = 0;
for (auto &deviation : vDeviations) {
if (histSampleCounter >= numOfHistSamplesIncluded)
break;
//bestConfOfHistSampleSet = minValueOf2Values(bestConfOfHistSampleSet, UnstabDeviation->getY(deviation));
bestConfOfHistSampleSet = maxValueOf2Values(bestConfOfHistSampleSet, UnstabDeviation->getY(deviation));
histSampleCounter++;
}
bestConfOf1Var = maxValueOf2Values(bestConfOf1Var, minValueOf2Values(bestConfOfHistSampleSet, StabSamples->getY((float)histSampleCounter)));
}
}
return bestConfOf1Var;
- */
+
return 0;
}
-
+*/
/*
bool StateHandler::getConfAndUnconfVariablesAreMatching(vector<SlaveAgentSlotOfAgent*>* vVariables, LinearFunctionBlock* confDeviation, LinearFunctionBlock* confTime, float* conf, float* unconf) {
float bestUnconfOfAllVariables = 0;
float worstConfOfAllVariables = 1;
for (auto &variable :* vVariables) {
bestUnconfOfAllVariables = maxValueOf2Values(bestUnconfOfAllVariables, getConfAndUnconfVariableIsMatching(variable, confDeviation, confTime, conf, unconf));
worstConfOfAllVariables = minValueOf2Values(worstConfOfAllVariables, getConfAndUnconfVariableIsMatching(variable, confDeviation, confTime, conf, unconf));
}
*conf = worstConfOfAllVariables;
*unconf = bestUnconfOfAllVariables;
return true;
}
*/
State* StateHandler::makeNewState() {
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() {
#ifdef PRINT
printf(" >> Save Active State\n");
#endif //PRINT
if (activeState != NULL) {
for (auto &state : vStates) {
if (state == activeState)
return true;
}
#ifdef STOP_WHEN_STATE_VALID
getchar();
#endif // STOP_WHEN_STATE_VALID
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);
}
}
*/
}
void StateHandler :: reset_States()
{
this->delete_allStates();
this->activeState = NULL;
}
void StateHandler :: reset_States_and_Slave_Agents()
{
reset_States();
this->delete_all_InputVariables();
this->delete_all_OuputVariables();
}
+void StateHandler ::setMaxStateHistoryLength(
+ unsigned int maxStateHistoryLength) {
+ this->maxStateHistoryLength = maxStateHistoryLength;
+}
+
+
+
StateHandler :: ~StateHandler()
{
delete_all_OuputVariables();
delete_all_InputVariables();
delete_allStates();
//delete csv_writer;
}
//XXX - only for now
bool test = true;
unsigned int brokenCounter = 0, driftCounter = 0;
void printDrift() {
driftCounter++;
setColor(TXTCOLOR_YELLOW);
printf(" >> DRIFT\n");
setColor(TXTCOLOR_GREY);
test = true;
}
void printBroken() {
brokenCounter++;
setColor(TXTCOLOR_LIGHTRED);
printf(" >> BROKEN\n");
setColor(TXTCOLOR_GREY);
test = true;
}
//XXX - only for now
unsigned int old_cycle = 1;
int brokentest = 0;
/*
* makes a new state and reports if there is a anomaly = hearth piece of CAM :-)
*/
void StateHandler::trigger(unsigned int cycle) {
#ifdef PRINT
printf("cycle: %u\n", cycle);
#endif // PRINT
bool flagGotValues = true;
#ifdef PRINT
printf("Input Sample Values:\n");
#endif // PRINT
for (auto &slot : vInputVariables) {
float sampleValue;
if (!(slot->get_slaveAgentValue(&sampleValue)))
flagGotValues = false; //program never executes this line of code
#ifdef PRINT
- printf("In, %s: %f\n", slot->get_comPort()->get_name(), sampleValue);
+ printf("In, %s: %f\n", slot->get_comPort()->get_name().c_str(), sampleValue);
#endif // PRINT
if (cycle == 1)
- csv_writer->write_field(slot->get_comPort()->get_name());
+ csv_writer->write_field(slot->get_comPort()->get_name().c_str());
else
csv_writer->write_field(sampleValue);
csv_writer->make_new_field();
}
#ifdef PRINT
printf("Output Sample Values:\n");
#endif // PRINT
for (auto &slot : vOutputVariables) {
float sampleValue;
if (!(slot->get_slaveAgentValue(&sampleValue)))
flagGotValues = false; //program never executes this line of code
#ifdef PRINT
- printf("Out, %s: %f\n", slot->get_comPort()->get_name(), sampleValue);
+ printf("Out, %s: %f\n", slot->get_comPort()->get_name().c_str(), sampleValue);
#endif // PRINT
if (cycle == 1)
- csv_writer->write_field(slot->get_comPort()->get_name());
+ csv_writer->write_field(slot->get_comPort()->get_name().c_str());
else
csv_writer->write_field(sampleValue);
csv_writer->make_new_field();
}
if (cycle == 1){
csv_writer->write_field("State Nr");
csv_writer->make_new_field();
csv_writer->write_field("Conf State Valid");
csv_writer->make_new_field();
csv_writer->write_field("Conf State Invalid");
csv_writer->make_new_field();
csv_writer->write_field("Conf Input unchanged");
csv_writer->make_new_field();
csv_writer->write_field("Conf Input changed");
csv_writer->make_new_field();
csv_writer->write_field("Conf Output unchanged");
csv_writer->make_new_field();
csv_writer->write_field("Conf Output changed");
csv_writer->make_new_field();
csv_writer->write_field("Status");
csv_writer->make_new_field();
csv_writer->write_field("Conf Status");
csv_writer->make_new_field();
}
else {
//in the beginning, a active state has to be created
if (activeState == NULL && vStates.empty()) {
brokenCounter = 0;
#ifdef PRINT
printf(" > new active state\n");
#endif // PRINT
makeNewActiveState();
if (activeState->insertValueInState(FuncBlockConfValStateDev, FuncBlockConfInvStateDev, FuncBlockConfValStateTime, FuncBlockConfInvStateTime, maxStateHistoryLength, discreteAveragePartitionSize))
addActiveStateToStateVector();
//NEW - Adjust FuncBlockConfSim2StateTime and FuncBlockConfDif2StateTime
float newBoundary = (float)activeState->getLengthOfHistory();
FuncBlockConfSim2StateTime->changeFunctionBlockIncr(newBoundary);
FuncBlockConfDif2StateTime->changeFunctionBlockDecr(newBoundary);
csv_writer->write_field((int)vStates.size() + 1);
csv_writer->make_new_field();
csv_writer->write_field(activeState->getConfStateValid());
csv_writer->make_new_field();
csv_writer->write_field(activeState->getConfStateInvalid());
csv_writer->make_new_field();
csv_writer->write_field(0); //confInputVarAreSim2ActiveState
csv_writer->make_new_field();
csv_writer->write_field(0); //confInputVarAreDif2ActiveState
csv_writer->make_new_field();
csv_writer->write_field(0); //confOutputVarAreSim2ActiveState
csv_writer->make_new_field();
csv_writer->write_field(0); //confOutputVarAreDif2ActiveState
csv_writer->make_new_field();
csv_writer->write_field(STATUS_OKAY);
csv_writer->make_new_field();
csv_writer->write_field(0); //Status Conf
csv_writer->make_new_field();
}
//there is an active state and/or other states
else {
float confInputVarAreSim2ActiveState = activeState->getConfInputVarAreSim2State(FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime);
float confInputVarAreDif2ActiveState = activeState->getConfInputVarAreDif2State(FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime);
float confOutputVarAreSim2ActiveState = activeState->getConfOutputVarAreSim2State(FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime);
float confOutputVarAreDif2ActiveState = activeState->getConfOutputVarAreDif2State(FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime);
- float confInputIsSteady = confInputVarAreSim2ActiveState - confInputVarAreDif2ActiveState;
- float confOutputIsSteady = confOutputVarAreSim2ActiveState - confOutputVarAreDif2ActiveState;
+ //float confInputIsSteady = confInputVarAreSim2ActiveState - confInputVarAreDif2ActiveState;
+ //float confOutputIsSteady = confOutputVarAreSim2ActiveState - confOutputVarAreDif2ActiveState;
printf("input (sim/dif) %f/%f\noutput (sim/dif) %f/%f\n", confInputVarAreSim2ActiveState, confInputVarAreDif2ActiveState, confOutputVarAreSim2ActiveState, confOutputVarAreDif2ActiveState);
//same state
if ((confInputVarAreSim2ActiveState > confInputVarAreDif2ActiveState) && (confOutputVarAreSim2ActiveState > confOutputVarAreDif2ActiveState)) {
brokenCounter = 0;
#ifdef PRINT
printf(" > same state\n");
//printf("\nPROOF:\nconfInputVarAreSim2ActiveState = %f\nconfInputVarAreDif2ActiveState = %f\nconfOutputVarAreSim2ActiveState = %f\nconfOutputVarAreDif2ActiveState = %f\n", confInputVarAreSim2ActiveState, confInputVarAreDif2ActiveState, confOutputVarAreSim2ActiveState, confOutputVarAreDif2ActiveState);
#endif // PRINT
if (activeState->insertValueInState(FuncBlockConfValStateDev, FuncBlockConfInvStateDev, FuncBlockConfValStateTime, FuncBlockConfInvStateTime, maxStateHistoryLength, discreteAveragePartitionSize))
addActiveStateToStateVector();
//NEW - Adjust FuncBlockConfSim2StateTime and FuncBlockConfDif2StateTime
float newBoundary = (float)activeState->getLengthOfHistory();
FuncBlockConfSim2StateTime->changeFunctionBlockIncr(newBoundary);
FuncBlockConfDif2StateTime->changeFunctionBlockDecr(newBoundary);
//print state number
if(activeState->isStateValid())
csv_writer->write_field((int)vStates.size());
else
csv_writer->write_field((int)vStates.size()+1);
csv_writer->make_new_field();
//print conf valid
csv_writer->write_field(activeState->getConfStateValid());
csv_writer->make_new_field();
csv_writer->write_field(activeState->getConfStateInvalid());
csv_writer->make_new_field();
//print conf statechange
csv_writer->write_field(confInputVarAreSim2ActiveState);
csv_writer->make_new_field();
csv_writer->write_field(confInputVarAreDif2ActiveState);
csv_writer->make_new_field();
csv_writer->write_field(confOutputVarAreSim2ActiveState);
csv_writer->make_new_field();
csv_writer->write_field(confOutputVarAreDif2ActiveState);
csv_writer->make_new_field();
confidenceDrift = activeState->checkAllVariablesForDriftingFuzzy(discreteAveragePartitionSize, DriftDeviation);
float confidenceNoDrift = 1 - confidenceDrift;
/*
//print conf drift
csv_writer->write_field(confidenceNoDrift);
csv_writer->make_new_field();
csv_writer->write_field(confidenceDrift);
csv_writer->make_new_field();
*/
if (confidenceDrift > 0.5) {
#ifdef PRINT
setColor(TXTCOLOR_YELLOW);
printf("DRIFT\n");
setColor(TXTCOLOR_GREY);
#endif // PRINT
#ifdef STOP_WHEN_DRIFT
getchar();
#endif // STOP_WHEN_DRIFT
setColor(TXTCOLOR_GREY);
//print drift
csv_writer->write_field(STATUS_DRIFT);
csv_writer->make_new_field();
//calc and print conf
float conf = fuzzyAND(fuzzyAND(confidenceDrift, activeState->getConfStateValid()), fuzzyAND(confInputVarAreSim2ActiveState, confOutputVarAreSim2ActiveState));
csv_writer->write_field(conf);
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTGREEN);
printf("OK\n");
setColor(TXTCOLOR_GREY);
#endif // PRINT
//print ok
csv_writer->write_field(STATUS_OKAY);
csv_writer->make_new_field();
//calc and print conf
float conf = fuzzyAND(fuzzyAND(confInputVarAreSim2ActiveState, confOutputVarAreSim2ActiveState), fuzzyAND(activeState->getConfStateValid(), confidenceNoDrift));
csv_writer->write_field(conf);
}
csv_writer->make_new_field();
}
//state change
else {
//was Valid
if (activeState->isStateValid()) {
//only one sub set changed
if (((confInputVarAreSim2ActiveState > confInputVarAreDif2ActiveState) && (confOutputVarAreSim2ActiveState <= confOutputVarAreDif2ActiveState)) || ((confInputVarAreSim2ActiveState <= confInputVarAreDif2ActiveState) && (confOutputVarAreSim2ActiveState > confOutputVarAreDif2ActiveState))) {
//print state number
if (activeState->isStateValid())
csv_writer->write_field((int)vStates.size());
else
csv_writer->write_field((int)vStates.size() + 1);
csv_writer->make_new_field();
//print conf valid
csv_writer->write_field(activeState->getConfStateValid());
csv_writer->make_new_field();
csv_writer->write_field(activeState->getConfStateInvalid());
csv_writer->make_new_field();
//print conf statechange
csv_writer->write_field(confInputVarAreSim2ActiveState);
csv_writer->make_new_field();
csv_writer->write_field(confInputVarAreDif2ActiveState);
csv_writer->make_new_field();
csv_writer->write_field(confOutputVarAreSim2ActiveState);
csv_writer->make_new_field();
csv_writer->write_field(confOutputVarAreDif2ActiveState);
csv_writer->make_new_field();
brokenCounter++;
printf("brokenCounter: %u\n", brokenCounter);
confidenceBroken = FuncBlockConfBrokenSamples->getY((float) brokenCounter);
float confidenceOK = 1 - confidenceBroken;
if (confidenceBroken > 0.5) {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
printf("BROKEN\n");
setColor(TXTCOLOR_GREY);
#endif // PRINT
#ifdef STOP_AFTER_BROKEN
brokentest = 1;
#endif // STOP_AFTER_BROKEN
#ifdef STOP_WHEN_BROKEN
getchar();
#endif // STOP_WHEN_BROKEN
//print broken
csv_writer->write_field(STATUS_BROKEN);
csv_writer->make_new_field();
//calculate and print conf
float conf = fuzzyAND(fuzzyOR(confInputVarAreDif2ActiveState, confOutputVarAreDif2ActiveState), fuzzyAND(confidenceBroken, activeState->getConfStateValid()));
csv_writer->write_field(conf);
//csv_writer->make_new_field();
}
else {
//print ok
csv_writer->write_field(STATUS_OKAY);
csv_writer->make_new_field();
//calculate and print conf
float conf = fuzzyAND(fuzzyOR(fuzzyAND(confInputVarAreSim2ActiveState, confOutputVarAreSim2ActiveState), fuzzyAND(confInputVarAreDif2ActiveState, confOutputVarAreDif2ActiveState)), fuzzyAND(confidenceOK, activeState->getConfStateValid()));
csv_writer->write_field(conf);
}
}
//In- and output changed
else {
brokenCounter = 0;
printf(" > delete active state\n");
activeState = NULL;
printf(" > new active state\n");
// search in vector for matching state //TODO in future: look for the best matching, Not for the first matching
bool flagFoundMatchingState = false;
float confInputVarAreSim2ActiveState;
float confInputVarAreDif2ActiveState;
float confOutputVarAreSim2ActiveState;
float confOutputVarAreDif2ActiveState;
for (auto &state : vStates) {
confInputVarAreSim2ActiveState = state->getConfInputVarAreSim2State(FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime);
confInputVarAreDif2ActiveState = state->getConfInputVarAreDif2State(FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime);
confOutputVarAreSim2ActiveState = state->getConfOutputVarAreSim2State(FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime);
confOutputVarAreDif2ActiveState = state->getConfOutputVarAreDif2State(FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime);
if ((confInputVarAreSim2ActiveState > confInputVarAreDif2ActiveState) && (confOutputVarAreSim2ActiveState > confOutputVarAreDif2ActiveState)) {
activeState = state;
flagFoundMatchingState = true;
}
}
if (flagFoundMatchingState == false) {
makeNewActiveState();
confInputVarAreSim2ActiveState = 0;
confInputVarAreDif2ActiveState = 0;
confOutputVarAreSim2ActiveState = 0;
confOutputVarAreDif2ActiveState = 0;
}
//insert in activeState
if (activeState->insertValueInState(FuncBlockConfValStateDev, FuncBlockConfInvStateDev, FuncBlockConfValStateTime, FuncBlockConfInvStateTime, maxStateHistoryLength, discreteAveragePartitionSize))
addActiveStateToStateVector();
//NEW - Adjust FuncBlockConfSim2StateTime and FuncBlockConfDif2StateTime
float newBoundary = (float)activeState->getLengthOfHistory();
FuncBlockConfSim2StateTime->changeFunctionBlockIncr(newBoundary);
FuncBlockConfDif2StateTime->changeFunctionBlockDecr(newBoundary);
//print state number
if (activeState->isStateValid())
csv_writer->write_field((int)vStates.size());
else
csv_writer->write_field((int)vStates.size() + 1);
csv_writer->make_new_field();
//print conf valid
csv_writer->write_field(activeState->getConfStateValid());
csv_writer->make_new_field();
csv_writer->write_field(activeState->getConfStateInvalid());
csv_writer->make_new_field();
//print conf statechange
csv_writer->write_field(confInputVarAreSim2ActiveState);
csv_writer->make_new_field();
csv_writer->write_field(confInputVarAreDif2ActiveState);
csv_writer->make_new_field();
csv_writer->write_field(confOutputVarAreSim2ActiveState);
csv_writer->make_new_field();
csv_writer->write_field(confOutputVarAreDif2ActiveState);
csv_writer->make_new_field();
confidenceDrift = activeState->checkAllVariablesForDriftingFuzzy(discreteAveragePartitionSize, DriftDeviation);
float confidenceNoDrift = 1 - confidenceDrift;
if (confidenceDrift > 0.5) {
setColor(TXTCOLOR_YELLOW);
printf("DRIFT\n");
#ifdef STOP_WHEN_DRIFT
getchar();
#endif // STOP_WHEN_DRIFT
setColor(TXTCOLOR_GREY);
//print drift
csv_writer->write_field(STATUS_DRIFT);
csv_writer->make_new_field();
//calc and print conf
float conf = fuzzyAND(confidenceDrift, activeState->getConfStateValid());
csv_writer->write_field(conf);
}
else {
setColor(TXTCOLOR_LIGHTGREEN);
printf("OK\n");
setColor(TXTCOLOR_GREY);
//print ok
csv_writer->write_field(STATUS_OKAY);
csv_writer->make_new_field();
//calc and print conf
float conf = fuzzyAND(fuzzyAND(confInputVarAreDif2ActiveState, confOutputVarAreDif2ActiveState), fuzzyAND(activeState->getConfStateValid(), confidenceNoDrift));
csv_writer->write_field(conf);
}
csv_writer->make_new_field();
}
}
//was NOT Valid
else {
brokenCounter = 0;
printf(" > delete active state\n");
delete activeState;
activeState = NULL;
printf(" > new active state\n");
// search in vector for matching state //TODO in future: look for the best matching, Not for the first matching
bool flagFoundMatchingState = false;
float confInputVarAreSim2ActiveState;
float confInputVarAreDif2ActiveState;
float confOutputVarAreSim2ActiveState;
float confOutputVarAreDif2ActiveState;
for (auto &state : vStates) {
confInputVarAreSim2ActiveState = state->getConfInputVarAreSim2State(FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime);
confInputVarAreDif2ActiveState = state->getConfInputVarAreDif2State(FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime);
confOutputVarAreSim2ActiveState = state->getConfOutputVarAreSim2State(FuncBlockConfSim2StateDev, FuncBlockConfSim2StateTime);
confOutputVarAreDif2ActiveState = state->getConfOutputVarAreDif2State(FuncBlockConfDif2StateDev, FuncBlockConfDif2StateTime);
if ((confInputVarAreSim2ActiveState > confInputVarAreDif2ActiveState) && (confOutputVarAreSim2ActiveState > confOutputVarAreDif2ActiveState)) {
activeState = state;
flagFoundMatchingState = true;
}
}
if (flagFoundMatchingState == false) {
makeNewActiveState();
confInputVarAreSim2ActiveState = 0;
confInputVarAreDif2ActiveState = 0;
confOutputVarAreSim2ActiveState = 0;
confOutputVarAreDif2ActiveState = 0;
}
//insert in active state
if (activeState->insertValueInState(FuncBlockConfValStateDev, FuncBlockConfInvStateDev, FuncBlockConfValStateTime, FuncBlockConfInvStateTime, maxStateHistoryLength, discreteAveragePartitionSize))
addActiveStateToStateVector();
//NEW - Adjust FuncBlockConfSim2StateTime and FuncBlockConfDif2StateTime
float newBoundary = (float)activeState->getLengthOfHistory();
FuncBlockConfSim2StateTime->changeFunctionBlockIncr(newBoundary);
FuncBlockConfDif2StateTime->changeFunctionBlockDecr(newBoundary);
//print state number
if (activeState->isStateValid())
csv_writer->write_field((int)vStates.size());
else
csv_writer->write_field((int)vStates.size() + 1);
csv_writer->make_new_field();
//print conf valid
csv_writer->write_field(activeState->getConfStateValid());
csv_writer->make_new_field();
csv_writer->write_field(activeState->getConfStateInvalid());
csv_writer->make_new_field();
//print conf statechange
csv_writer->write_field(confInputVarAreSim2ActiveState);
csv_writer->make_new_field();
csv_writer->write_field(confInputVarAreDif2ActiveState);
csv_writer->make_new_field();
csv_writer->write_field(confOutputVarAreSim2ActiveState);
csv_writer->make_new_field();
csv_writer->write_field(confOutputVarAreDif2ActiveState);
csv_writer->make_new_field();
confidenceDrift = activeState->checkAllVariablesForDriftingFuzzy(discreteAveragePartitionSize, DriftDeviation);
float confidenceNoDrift = 1 - confidenceDrift;
if (confidenceDrift > 0.5) {
setColor(TXTCOLOR_YELLOW);
printf("DRIFT\n");
#ifdef STOP_WHEN_DRIFT
getchar();
#endif // STOP_WHEN_DRIFT
setColor(TXTCOLOR_GREY);
//print drift
csv_writer->write_field(2);
csv_writer->make_new_field();
//calc and print conf
float conf = fuzzyAND(confidenceDrift, activeState->getConfStateValid());
csv_writer->write_field(conf);
}
else {
setColor(TXTCOLOR_LIGHTGREEN);
printf("OK\n");
setColor(TXTCOLOR_GREY);
//print ok
csv_writer->write_field(STATUS_OKAY);
csv_writer->make_new_field();
//calc and print conf
float conf = fuzzyAND(fuzzyAND(confInputVarAreDif2ActiveState, confOutputVarAreDif2ActiveState), fuzzyAND(activeState->getConfStateValid(), confidenceNoDrift));
csv_writer->write_field(conf);
}
csv_writer->make_new_field();
}
}
#ifdef PRINT
printf("STATES: %u\n", vStates.size());
#endif // PRINT
}
}
csv_writer->make_new_line();
if (brokentest)
getchar();
/*
//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;
confidenceStableInput = getConfVariablesAreStable(&vInputVariables);
confidenceStableOutput = getConfVariablesAreStable(&vOutputVariables);
confidenceStable = minValueOf2Values(confidenceStableInput, confidenceStableOutput);
printf("confidence stable: %f\n", confidenceStable);
confidenceUnstableInput = getConfVariablesAreUnstable(&vInputVariables);
confidenceUnstableOutput = getConfVariablesAreUnstable(&vOutputVariables);
printf("unstable In: %f, Out: %f\n", confidenceUnstableInput, confidenceUnstableOutput);
confidenceUnstable = maxValueOf2Values(confidenceUnstableInput, confidenceUnstableOutput);
printf("confidence unstable: %f\n", confidenceUnstable);
if (confidenceUnstableInput > 0) {
printf("jetzt\n");
getchar();
}
//TEST
if (confidenceStable > confidenceUnstable) {
setColor(TXTCOLOR_LIGHTBLUE);
printf("jetzt\n");
setColor(TXTCOLOR_GREY);
getchar();
}
//getchar();
if (confidenceStable > confidenceUnstable) {
//if (false) {
printf(" > stable\n");
//for the beginning (there is no state available/created) -> create state
if (activeState == NULL && vStates.empty()) {
printf(" > new state\n");
makeNewActiveState();
activeState->injectValues(discreteAveragePartitionSize);
confidenceValidState = ValidState->getY((float)activeState->getNumOfInjections());
}
//there is an active state
else if (activeState != NULL) {
//caclulate confidences of deciding for same state
float confidenceSameStateInput = activeState->inputVariablesAreRelatedFuzzy(SameState);
float confidenceSameStateOutput = activeState->outputVariablesAreRelatedFuzzy(SameState);
printf("ConfSameState\nIn: %f\nout: %f\n", confidenceSameStateInput, confidenceSameStateOutput);
//In- and Outputs are unchanged
if ((confidenceSameStateInput > confSameStateInputAdjustableThreshold) && (confidenceSameStateOutput > confSameStateOutputAdjustableThreshold)) {
printf(" > same state\n");
//inject values
activeState->injectValues(discreteAveragePartitionSize);
//calculate the confidence to have a validState
confidenceValidState = ValidState->getY((float)activeState->getNumOfInjections());
//TODO DATE
//check for drifting!!!
//printDrift();
}
//In- and Outputs have changed
else if ((confidenceSameStateInput <= confSameStateInputAdjustableThreshold) && (confidenceSameStateOutput <= confSameStateOutputAdjustableThreshold)) {
printf(" > change state\n");
getchar();
//active state is/was valid
if (confidenceValidState > confValidStateAdjustableThreshold) {
printf("speicher\n");
getchar();
addActiveStateToStateVector();
//TODO DATE
//search for matching state
//or
printf(" > new state\n");
//create an new active state
makeNewActiveState();
//inject values
activeState->injectValues(discreteAveragePartitionSize);
//calculate the confidence to have a validState
confidenceValidState = ValidState->getY((float)activeState->getNumOfInjections());
//TODO DATE
//check for drifting!!!
//printDrift();
}
}
//Only in- or outputs have changed
else {
//active state is/was valid
if (confidenceValidState > confValidStateAdjustableThreshold) {
addActiveStateToStateVector();
printf(" > broken\n");
brokenCounter++;
confidenceBroken = BrokenCounterSamples->getY(brokenCounter);
//getchar();
//TODO DATE??
//Save State
}
}
}
//there is no active state, but there is/are state(s)
else {
printf(" > old or new state\n");
//getchar();
//TODO DATE
//search for matching state
//or
printf(" > new state\n");
makeNewActiveState();
activeState->injectValues(discreteAveragePartitionSize);
confidenceValidState = ValidState->getY((float)activeState->getNumOfInjections());
//TODO DATE
//check for drifting!!!
//printDrift();
}
if (activeState != NULL) {
confidenceDrift = activeState->checkAllVariablesForDriftingFuzzy(discreteAveragePartitionSize, DriftDeviation);
}
//getchar();
}
//unstable
else {
printf(" > unstable\n");
//there is/was an active state
if (activeState != NULL) {
//delete activeState;
if (confidenceValidState > confValidStateAdjustableThreshold)
addActiveStateToStateVector();
activeState = NULL;
}
}
//DATE TODO
//STABLE CONFIDENCE MITEINBEZIEHEN
if ((confidenceBroken >= confidenceBroken) && (confidenceBroken > confidenceBrokenAdjustableThreshold)) {
setColor(TXTCOLOR_LIGHTRED);
printf(" >> BROKEN - confidence %f\n", confidenceBroken);
setColor(TXTCOLOR_GREY);
getchar();
}
else if (confidenceDrift > confidenceDriftAdjustableThreshold) {
setColor(TXTCOLOR_YELLOW);
printf(" >> DRIFT - confidence %f\n", confidenceDrift);
setColor(TXTCOLOR_GREY);
//XXXXXXXXXX ????????????????????????????????????
if (brokenCounter > 0)
brokenCounter--;
getchar();
}
else {
setColor(TXTCOLOR_LIGHTGREEN);
float confidenceOK;
if (confidenceDrift > confidenceBroken)
confidenceOK = 1 - confidenceDrift;
else
confidenceOK = 1 - confidenceBroken;
printf(" >> SYSTEM OK - confidence %f\n", confidenceOK);
setColor(TXTCOLOR_GREY);
}
printf("brokenCounter %u\n", brokenCounter);
printf("number of states: %i\n", vStates.size());
*/
/*
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();
}
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();
}
string StateHandler::create_Output_File_Name(string cfg_parameter)
{
time_t rawtime;
struct tm * timeinfo;
- char output_file_name[200];
+ //char output_file_name[200];
char datetime[80];
std::string output_file_name_str;
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(datetime, sizeof(datetime), "%Y-%m-%d_%I-%M-%S", timeinfo);
#ifndef INPUT_FILE_NAME
output_file_name_str = output_directory_name + "output" + datetime + cfg_parameter + ".csv";
#else
string out_dir = "../data/out/";
output_file_name_str = out_dir + INPUT_FILE_NAME + datetime + cfg_parameter + ".csv";
#endif // INPUT_FILE_NAME
return output_file_name_str;
}
void StateHandler::set_CSV_Writer_parameter(string cfg_parameter)
{
string cur_Output_File_Name = this->create_Output_File_Name(cfg_parameter);
csv_writer->reset_fpointer(cur_Output_File_Name);
}
/*
void StateHandler :: initStateHandler() {
//activeState = NULL;
thresholdToAverage = THRESHOLDTOAVG;
minNumOfChangedForValidStateChange = MINNUMCHANGEDFORVALIDSTATECHANGE;
minimumInjectionsForBeingState = MININJFORBEINGSTATE;
}
StateHandler :: StateHandler() {
set_name(NO_NAME);
initStateHandler();
}
StateHandler :: StateHandler(char* name) {
set_name(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;
}
*/
diff --git a/Version_Max_07_05_2018_CMake/src/StateHandler.h b/Version_Max_07_05_2018_CMake/src/StateHandler.h
index 6d07826..e8e64a2 100755
--- a/Version_Max_07_05_2018_CMake/src/StateHandler.h
+++ b/Version_Max_07_05_2018_CMake/src/StateHandler.h
@@ -1,195 +1,198 @@
#ifndef STATEHANDLER_HEADERFILE
#define STATEHANDLER_HEADERFILE
#include "Module.h"
#include "SlaveAgentSlotOfAgent.h"
#include "State.h"
#include "StateVariable.h"
#include <vector>
//XXX - only for now
#include "CSV_Writer.h"
#include "LinearFunctionBlock.h"
using namespace std;
class StateHandler : public Module {
public:
LinearFunctionBlock* StabSamples;
LinearFunctionBlock* StabDeviation;
LinearFunctionBlock* UnstabDeviation;
LinearFunctionBlock* SameState;
LinearFunctionBlock* DriftDeviation;
LinearFunctionBlock* BrokenCounterSamples;
LinearFunctionBlock* ValidState;
//NEU:
//compare
LinearFunctionBlock* FuncBlockConfSim2StateDev;
LinearFunctionBlock* FuncBlockConfDif2StateDev;
LinearFunctionBlock* FuncBlockConfSim2StateTime;
LinearFunctionBlock* FuncBlockConfDif2StateTime;
//insert
LinearFunctionBlock* FuncBlockConfValStateDev;
LinearFunctionBlock* FuncBlockConfInvStateDev;
LinearFunctionBlock* FuncBlockConfValStateTime;
LinearFunctionBlock* FuncBlockConfInvStateTime;
LinearFunctionBlock* FuncBlockConfBrokenSamples;
private:
//DATE18
//XXX - >0,5?
//discreate Average Partition Size adjustable?
float confidenceStableInput;
float confidenceStableOutput;
float confidenceStable;
float confStableAdjustableThreshold;
float confidenceUnstableInput;
float confidenceUnstableOutput;
float confidenceUnstable;
float confidenceUnstableAdjustableThreshold;
float confidenceSameStateInput;
float confSameStateInputAdjustableThreshold;
float confidenceSameStateOutput;
float confSameStateOutputAdjustableThreshold;
float confidenceValidState;
float confValidStateAdjustableThreshold;
unsigned int brokenCounter;
float confidenceBroken;
float confidenceBrokenAdjustableThreshold;
unsigned int driftCounter;
float confidenceDrift;
float confidenceDriftAdjustableThreshold;
//XXX - Maybe Object "StateVariable" between StateHandler and Slot?!
vector<SlaveAgentSlotOfAgent*> vInputVariables;
vector<SlaveAgentSlotOfAgent*> vOutputVariables;
vector<State*> vStates;
State* activeState;
unsigned int minNumToBeValidState;
bool flagVariablesWereStable;
unsigned int slidingWindowBufferSize;
unsigned int minNumOfRelatedValuesToBeStable;
float thresholdToBeStable;
float thresholdToBeRelated;
unsigned int discreteAveragePartitionSize;
unsigned int compareDistanceDiscreteAveragePartition;
float thresholdNotDrift;
unsigned int maxStateHistoryLength;
void initStateHandler();
bool addVariable(vector<SlaveAgentSlotOfAgent*>* vVariables, SlaveAgentSlotOfAgent* slot);
bool variablesAreStable(vector<SlaveAgentSlotOfAgent*>* vVariables);
//DATE18
float getConfVariableIsStable(SlaveAgentSlotOfAgent* variable);
float getConfVariablesAreStable(vector<SlaveAgentSlotOfAgent*>* vVariables);
float getConfVariableIsUnstable(SlaveAgentSlotOfAgent* variable);
float getConfVariablesAreUnstable(vector<SlaveAgentSlotOfAgent*>* vVariables);
//bool getConfAndUnconfVariableIsMatching(SlaveAgentSlotOfAgent* variable, LinearFunctionBlock* confDeviation, LinearFunctionBlock* confTime, float* conf, float* unconf);
- bool getConfAndUnconfVariableIsMatching(State* state, LinearFunctionBlock* confDeviation, LinearFunctionBlock* confTime, float* conf, float* unconf);
- bool getConfAndUnconfVariablesAreMatching(vector<SlaveAgentSlotOfAgent*>* vVariables, LinearFunctionBlock* confDeviation, LinearFunctionBlock* confTime, float* conf, float* unconf);
+ //bool getConfAndUnconfVariableIsMatching(State* state, LinearFunctionBlock* confDeviation, LinearFunctionBlock* confTime, float* conf, float* unconf);
+ //bool getConfAndUnconfVariablesAreMatching(vector<SlaveAgentSlotOfAgent*>* vVariables, LinearFunctionBlock* confDeviation, LinearFunctionBlock* confTime, float* conf, float* unconf);
State* makeNewState();
string create_Output_File_Name(string cfg_Parameter);
bool addActiveStateToStateVector();
//bool addStateAndMakeItActive();
bool makeNewActiveState();
State* findRelatedState();
bool findRelatedStateAndMakeItActive();
void eraseStatesWithLessInjections();
bool delete_all_OuputVariables();
bool delete_all_InputVariables();
bool delete_allStates();
//XXX - only for now:
CSV_Writer *csv_writer;
public:
StateHandler();
- StateHandler(char* name);
+ StateHandler(std::string name);
+ StateHandler(std::string name, std::string csvWriterPath);
bool setDiscreteAveragePartitionSize(unsigned int discreteAverage);
unsigned int getDiscreteAveragePartitionSize();
bool addInputVariable(SlaveAgentSlotOfAgent* slot);
bool addOutputVariable(SlaveAgentSlotOfAgent* slot);
bool setSlidingWindowBufferSize(unsigned int slidingWindowBufferSize);
bool setMinNumOfRelatedValuesToBeStable(unsigned int minNumOfRelatedValuesToBeStable);
bool setThresholdToBeStable(float thresholdToBeStable);
bool setThresholdToBeRelated(float thresholdToBeRelated);
void trigger(unsigned int cycle);
//XXX - only for now
void closeCsvFile();
void set_CSV_Writer_parameter(string cfg_parameter);
void reset_States();
void reset_States_and_Slave_Agents();
+ void setMaxStateHistoryLength(unsigned int maxStateHistoryLength);
+
~StateHandler();
/*
private:
vector<SlaveAgentSlotOfAgent*> vSlots;
unsigned int minNumOfChangedForValidStateChange;
unsigned int minimumInjectionsForBeingState;
void initStateHandler();
public:
StateHandler();
StateHandler(char* name);
bool setMinimumInjectionsForBeingState(unsigned int minimumInjectionsForBeingState);
unsigned int getMinimumInjectionsForBeingState();
//TODO: function for deleting slot and function with the whole vector as parameter
bool add_slot(SlaveAgentSlotOfAgent* slot);
void set_minNumOfChangedForValidStateChange(unsigned int minNumOfChangedForValidStateChange);
unsigned int get_minNumOfChangedForValidStateChange();
bool trigger();
*/
};
#endif
diff --git a/Version_Max_07_05_2018_CMake/src/StateVariable.h b/Version_Max_07_05_2018_CMake/src/StateVariable.h
index 31e3413..2c1386b 100755
--- a/Version_Max_07_05_2018_CMake/src/StateVariable.h
+++ b/Version_Max_07_05_2018_CMake/src/StateVariable.h
@@ -1,19 +1,19 @@
#ifndef STATEVARIABLE_HEADERFILE
#define STATEVARIABLE_HEADERFILE
#include "SlaveAgentSlotOfAgent.h"
class StateVariable {
private:
//TODO: for all slots ... generalize slot (not SlavAgent and Sensor)
- SlaveAgentSlotOfAgent* slot;
+ //SlaveAgentSlotOfAgent* slot;
public:
StateVariable();
};
#endif
\ No newline at end of file
diff --git a/Version_Max_07_05_2018_CMake/src/Testbench.cpp b/Version_Max_07_05_2018_CMake/src/Testbench.cpp
index 90a7c3e..241488e 100755
--- a/Version_Max_07_05_2018_CMake/src/Testbench.cpp
+++ b/Version_Max_07_05_2018_CMake/src/Testbench.cpp
@@ -1,1026 +1,1026 @@
#include "Testbench.h"
#include "printError.h"
#include <stdio.h>
using namespace std;
void Testbench :: init_testbench() {
//TODO
//some init source code to add, if necessary
}
Testbench :: Testbench() {
set_name(NO_NAME);
}
-Testbench :: Testbench(char* name) {
+Testbench :: Testbench(std::string name) {
set_name(name);
}
bool Testbench :: register_agent(Agent* agent) {
AgentSlotOfTestbench* agentSlot = new AgentSlotOfTestbench();
if(agentSlot != NULL) {
if(agentSlot->set_agent(agent)) {
try {
if(vector_registeredAgents.size() < MAXNUM_OF_REGISTERED_AGENTS) {
vector_registeredAgents.push_back(agentSlot);
}
else {
printError("Max number of registered agents is already reached!");
return false;
}
}
catch(bad_alloc& error) {
printError("bad_alloc caught: ", error.what());
return false;
}
return true;
}
else {
printError("Agent is not set!");
vector_registeredAgents.pop_back(); //TODO: check if it is right?!?!
return false;
}
}
else {
printError("Couldn't create AgentSlot!");
return false;
}
}
bool Testbench :: register_sensor(Sensor* sensor) {
SensorSlotOfTestbench* sensorSlot = new SensorSlotOfTestbench();
if(sensorSlot != NULL) {
if(sensorSlot->set_sensor(sensor)) {
try {
if(vector_registeredSensors.size() < MAXNUM_OF_REGISTERED_SENSORS) {
vector_registeredSensors.push_back(sensorSlot);
}
else {
printError("Max number of registered sensors is already reached!");
return false;
}
}
catch(bad_alloc& error) {
printError("bad_alloc caught: ", error.what());
return false;
}
return true;
}
else {
printError("Input port is no set!");
vector_registeredSensors.pop_back(); //TODO: check if it is right?!?!
return false;
}
}
else {
printError("Couldn't create SensorSlot!");
return false;
}
}
SensorSlotOfTestbench* Testbench :: get_sensorSlotAddressOfTestbench(Sensor* sensor) {
for(auto &sensorSlot : vector_registeredSensors) {
if(sensorSlot->get_sensor() == sensor) {
return sensorSlot;
}
}
return NULL;
}
bool Testbench :: register_channel(Channel* channel) {
ChannelSlotOfTestbench* channelSlot = new ChannelSlotOfTestbench();
if(channelSlot != NULL) {
if(channelSlot->set_channel(channel)) {
try {
if(vector_registeredChannels.size() < MAXNUM_OF_REGISTERED_CHANNELS) {
vector_registeredChannels.push_back(channelSlot);
}
else {
printError("Max number of registered channels is already reached!");
return false;
}
}
catch(bad_alloc& error) {
printError("bad_alloc caught: ", error.what());
return false;
}
return true;
}
else {
printError("Channel is not set!");
vector_registeredChannels.pop_back(); //TODO: check if it is right?!?!
return false;
}
}
else {
printError("Couldn't create ChannelSlot!");
return false;
}
}
bool Testbench :: register_testbench_config(Testbench_Config* tb_config)
{
vector_registered_Configs.push_back(tb_config);
return true; //added by Ali, it is an error in VS.
}
vector<Testbench_Config*>& Testbench :: get_all_registered_testbench_configs()
{
return vector_registered_Configs;
}
void Testbench :: simulate(unsigned int rounds) {
for(unsigned int cycle = 1; cycle <=rounds; cycle++) {
if (cycle == 312) {
printf("DEBUG: Break point");
}
//printf("cycle %u\n", sec);
//update sensor values
for(auto &sensorSlot : vector_registeredSensors) {
Sensor *sensor = sensorSlot->get_sensor();
- printf("Name of Sensor %s \n", sensor->get_name());
+ //printf("Name of Sensor %s \n", sensor->get_name().c_str());
if(sensor != NULL) {
CSVreaderModule *csvReader = sensorSlot->get_csvReaderModule();
if(csvReader != NULL) {
float inputValue;
if(csvReader->get_next_value(&inputValue)) {
sensor->set_sensorValue(inputValue);
}
}
}
}
//trigger sensors
for(auto &sensorSlot : vector_registeredSensors) {
Sensor *sensor = sensorSlot->get_sensor();
if(sensor != NULL) {
sensor->trigger();
}
}
//trigger channels
for(auto &channelSlot : vector_registeredChannels) {
Channel *channel = channelSlot->get_channel();
if(channel != NULL) {
channel->trigger();
}
}
//trigger agents
for(auto &agentSlot : vector_registeredAgents) {
Agent *agent = agentSlot->get_agent();
if(agent != NULL) {
agent->trigger(cycle);
}
}
//if(sec % 500 == 0)
//getchar();
}
//XXX - only for now
for (auto &agentSlot : vector_registeredAgents) {
Agent *agent = agentSlot->get_agent();
if (agent != NULL) {
StateHandler *stateHandler = agent->get_stateHandler2();
if (stateHandler != NULL) {
stateHandler->closeCsvFile();
}
}
}
}
vector<AgentSlotOfTestbench*>& Testbench :: get_all_registeredAgents()
{
return vector_registeredAgents;
}
void Testbench :: set_current_tb_config_index(const int index)
{
Testbench_Config::set_active_Config(index);
}
void Testbench :: remove_all_Testbench_Configs()
{
unsigned int index_tb_conf = 0;
unsigned int size_vec_tb_conf = vector_registered_Configs.size();
for(index_tb_conf = 0; index_tb_conf < size_vec_tb_conf; index_tb_conf++) {
Testbench_Config* cur_config = vector_registered_Configs[index_tb_conf];
delete cur_config;
}
vector_registered_Configs.clear();
}
void Testbench :: remove_all_Agents()
{
AgentSlotOfTestbench* cur_AgentSlot;
unsigned int index_ag;
unsigned int size_vec_reg_ag = vector_registeredAgents.size();
for(index_ag = 0; index_ag < size_vec_reg_ag; index_ag++) {
cur_AgentSlot = vector_registeredAgents[index_ag];
delete cur_AgentSlot;
}
vector_registeredAgents.clear();
}
void Testbench :: remove_all_Channels()
{
unsigned int index_ch;
unsigned int size_vec_reg_chan = vector_registeredChannels.size();
for(index_ch = 0; index_ch < size_vec_reg_chan; index_ch++) {
ChannelSlotOfTestbench* cur_ChaSlot = vector_registeredChannels[index_ch];
delete cur_ChaSlot;
}
vector_registeredChannels.clear();
}
void Testbench :: remove_all_Sensors()
{
unsigned int index_sen;
unsigned int size_vec_reg_sens = vector_registeredSensors.size();
for(index_sen = 0; index_sen < size_vec_reg_sens; index_sen++) {
SensorSlotOfTestbench* cur_SenSlot = vector_registeredSensors[index_sen];
delete cur_SenSlot;
}
vector_registeredSensors.clear();
}
bool Testbench :: free_resources()
{
AgentSlotOfTestbench* cur_Ag_Sl_Tb;
unsigned int index_reg_Agents;
unsigned int size_vec_reg_Agents = vector_registeredAgents.size();
for(index_reg_Agents = 0; index_reg_Agents < size_vec_reg_Agents; index_reg_Agents++)
{
cur_Ag_Sl_Tb = vector_registeredAgents[index_reg_Agents];
- Agent* cur_Ag = cur_Ag_Sl_Tb->get_agent();
+ //Agent* cur_Ag = cur_Ag_Sl_Tb->get_agent();
//cur_Ag->del_stateHandler();
}
return true; //added by Ali, it is an error in VS.
}
void Testbench::set_CSV_Writer_parameter()
{
unsigned int size_of_vec_reg_Agents = vector_registeredAgents.size();
AgentSlotOfTestbench* viability_slot_Agent = vector_registeredAgents[size_of_vec_reg_Agents - 1];
Agent* viability_Agent = viability_slot_Agent->get_agent();
StateHandler* cur_state_Handl = viability_Agent->get_stateHandler();
Testbench_Config* cur_tb_cfg;
string tb_cfg;
cur_tb_cfg = get_current_Testbench_config();
if(cur_tb_cfg != NULL) {
tb_cfg = cur_tb_cfg->get_Config_as_String();
cur_state_Handl->set_CSV_Writer_parameter(tb_cfg);
}
}
Testbench_Config* Testbench :: get_current_Testbench_config()
{
unsigned int index_cur_tb_cfg = 0;
unsigned int size_tb_cfg = vector_registered_Configs.size();
Testbench_Config* cur_tb_cfg;
for(index_cur_tb_cfg = 0; index_cur_tb_cfg < size_tb_cfg; index_cur_tb_cfg++){
cur_tb_cfg = vector_registered_Configs[index_cur_tb_cfg];
if(cur_tb_cfg->get_own_index() == Testbench_Config::get_active_Config()){
return cur_tb_cfg;
}
}
return NULL;
}
void Testbench :: set_config_values_in_linear_functions()
{
- unsigned int index_reg_Agents = 0;
+ //unsigned int index_reg_Agents = 0;
unsigned int size_of_vec_reg_Agents;
vector<AgentSlotOfTestbench*> vec_reg_Agents = this->get_all_registeredAgents();
size_of_vec_reg_Agents = vec_reg_Agents.size();
AgentSlotOfTestbench* viability_slot_Agent = vec_reg_Agents[vec_reg_Agents.size()-1];
Agent* viability_Agent = viability_slot_Agent->get_agent();
StateHandler* cur_state_Handl = viability_Agent->get_stateHandler();
set_parameters_FuncBlockConfSim2StateDev(cur_state_Handl->FuncBlockConfSim2StateDev);
set_parameters_FuncBlockConfDif2StateDev(cur_state_Handl->FuncBlockConfDif2StateDev);
set_parameters_FuncBlockConfSim2StateTime(cur_state_Handl->FuncBlockConfSim2StateTime);
set_parameters_FuncBlockConfDif2StateTime(cur_state_Handl->FuncBlockConfDif2StateTime);
set_parameters_FuncBlockConfValStateDev(cur_state_Handl->FuncBlockConfValStateDev);
set_parameters_FuncBlockConfInvStateDev(cur_state_Handl->FuncBlockConfInvStateDev);
set_parameters_FuncBlockConfValStateTime(cur_state_Handl->FuncBlockConfValStateTime);
set_parameters_FuncBlockConfInvStateTime(cur_state_Handl->FuncBlockConfInvStateTime);
set_parameters_DriftDeviation(cur_state_Handl->DriftDeviation);
set_parameters_FuncBlockConfBrokenSamples(cur_state_Handl->FuncBlockConfBrokenSamples);
}
void Testbench :: set_parameters_FuncBlockConfSim2StateDev(LinearFunctionBlock* FuncBlockConfSim2StateDev)
{
LinearFunction* cur_Lin_Fun;
vector<LinearFunction*> vec_Lin_Fun = FuncBlockConfSim2StateDev->get_all_LinearFunctions();
unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size();
unsigned int index_cur_Lin_Fun = 0;
Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config();
for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++)
{
One_Config_t cur_values = cur_Tb_cfg->get_Config();
cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun];
if(cur_Lin_Fun->getName() == CONF_SIM2_STATE_DEV_1) {
cur_Lin_Fun->setDomain(false, true, (float)-cur_values.outter_bound_sim_dif);
cur_Lin_Fun->setKandD((float)0, (float)0);
}else if (cur_Lin_Fun->getName() == CONF_SIM2_STATE_DEV_2) {
cur_Lin_Fun->setDomain(true, (float)-cur_values.outter_bound_sim_dif, true, (float)-cur_values.inner_bound_sim_dif);
cur_Lin_Fun->setKandD((float)-cur_values.outter_bound_sim_dif, (float)0, (float)-cur_values.inner_bound_sim_dif, (float)1);
}else if (cur_Lin_Fun->getName() == CONF_SIM2_STATE_DEV_3) {
cur_Lin_Fun->setDomain(true, (float)-cur_values.inner_bound_sim_dif, true, (float)cur_values.inner_bound_sim_dif);
cur_Lin_Fun->setKandD((float)0, (float)1);
}else if(cur_Lin_Fun->getName() == CONF_SIM2_STATE_DEV_4){
cur_Lin_Fun->setDomain(true, (float)cur_values.inner_bound_sim_dif, true, (float)cur_values.outter_bound_sim_dif);
cur_Lin_Fun->setKandD((float)cur_values.inner_bound_sim_dif, (float)1, (float)cur_values.outter_bound_sim_dif, (float)0);
}else if(cur_Lin_Fun->getName() == CONF_SIM2_STATE_DEV_5){
cur_Lin_Fun->setDomain(true, (float)cur_values.outter_bound_sim_dif, false);
cur_Lin_Fun->setKandD((float)0, (float)0);
}
}
}
void Testbench :: set_parameters_FuncBlockConfDif2StateDev(LinearFunctionBlock* FuncBlockConfDif2StateDev)
{
LinearFunction* cur_Lin_Fun;
vector<LinearFunction*> vec_Lin_Fun = FuncBlockConfDif2StateDev->get_all_LinearFunctions();
unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size();
unsigned int index_cur_Lin_Fun = 0;
Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config();
for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++)
{
One_Config_t cur_values = cur_Tb_cfg->get_Config();
cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun];
if(cur_Lin_Fun->getName() == CONF_DIF2_STATE_DEV_1) {
cur_Lin_Fun->setDomain(false, true, (float)-cur_values.outter_bound_sim_dif);
cur_Lin_Fun->setKandD((float)0, (float)1);
}else if (cur_Lin_Fun->getName() == CONF_DIF2_STATE_DEV_2) {
cur_Lin_Fun->setDomain(true, (float)-cur_values.outter_bound_sim_dif, true, (float)-cur_values.inner_bound_sim_dif);
cur_Lin_Fun->setKandD((float)-cur_values.outter_bound_sim_dif, (float)1, (float)-cur_values.inner_bound_sim_dif, (float)0);
}else if (cur_Lin_Fun->getName() == CONF_DIF2_STATE_DEV_3) {
cur_Lin_Fun->setDomain(true, (float)-cur_values.inner_bound_sim_dif, true, (float)cur_values.inner_bound_sim_dif);
cur_Lin_Fun->setKandD((float)0, (float)0);
}else if(cur_Lin_Fun->getName() == CONF_DIF2_STATE_DEV_4){
cur_Lin_Fun->setDomain(true, (float)cur_values.inner_bound_sim_dif, true, (float)cur_values.outter_bound_sim_dif);
cur_Lin_Fun->setKandD((float)cur_values.inner_bound_sim_dif, (float)0, (float)cur_values.outter_bound_sim_dif, (float)1);
}else if(cur_Lin_Fun->getName() == CONF_DIF2_STATE_DEV_5){
cur_Lin_Fun->setDomain(true, (float)cur_values.outter_bound_sim_dif, false);
cur_Lin_Fun->setKandD((float)0, (float)1);
}
}
}
void Testbench :: set_parameters_FuncBlockConfSim2StateTime(LinearFunctionBlock* FuncBlockConfSim2StateTime)
{
LinearFunction* cur_Lin_Fun;
vector<LinearFunction*> vec_Lin_Fun = FuncBlockConfSim2StateTime->get_all_LinearFunctions();
unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size();
unsigned int index_cur_Lin_Fun = 0;
Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config();
for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++)
{
One_Config_t cur_values = cur_Tb_cfg->get_Config();
cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun];
if(cur_Lin_Fun->getName() == CONF_SIM2_STATE_TIME_1) {
cur_Lin_Fun->setDomain(false, true, (float)0);
cur_Lin_Fun->setKandD((float)0, (float)0);
}else if (cur_Lin_Fun->getName() == CONF_SIM2_STATE_TIME_2) {
cur_Lin_Fun->setDomain(true, (float)0, true, (float)cur_values.length);
cur_Lin_Fun->setKandD((float)0, (float)0, (float)cur_values.length, (float)1);
}else if (cur_Lin_Fun->getName() == CONF_SIM2_STATE_TIME_3) {
cur_Lin_Fun->setDomain(true, (float)cur_values.length, false);
cur_Lin_Fun->setKandD((float)0, (float)1);
}
}
}
void Testbench :: set_parameters_FuncBlockConfDif2StateTime(LinearFunctionBlock* FuncBlockConfDif2StateTime)
{
LinearFunction* cur_Lin_Fun;
vector<LinearFunction*> vec_Lin_Fun = FuncBlockConfDif2StateTime->get_all_LinearFunctions();
unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size();
unsigned int index_cur_Lin_Fun = 0;
Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config();
for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++)
{
One_Config_t cur_values = cur_Tb_cfg->get_Config();
cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun];
if(cur_Lin_Fun->getName() == CONF_DIF2_STATE_TIME_1) {
cur_Lin_Fun->setDomain(false, true, (float)0);
cur_Lin_Fun->setKandD((float)0, (float)1);
}else if (cur_Lin_Fun->getName() == CONF_DIF2_STATE_TIME_2) {
cur_Lin_Fun->setDomain(true, (float)0, true, (float)cur_values.length);
cur_Lin_Fun->setKandD((float)0, (float)1, (float)cur_values.length, (float)0);
}else if (cur_Lin_Fun->getName() == CONF_DIF2_STATE_TIME_3) {
cur_Lin_Fun->setDomain(true, (float)cur_values.length, false);
cur_Lin_Fun->setKandD((float)0, (float)0);
}
}
}
void Testbench :: set_parameters_FuncBlockConfValStateDev(LinearFunctionBlock* FuncBlockConfValStateDev)
{
LinearFunction* cur_Lin_Fun;
vector<LinearFunction*> vec_Lin_Fun = FuncBlockConfValStateDev->get_all_LinearFunctions();
unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size();
unsigned int index_cur_Lin_Fun = 0;
Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config();
for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++)
{
One_Config_t cur_values = cur_Tb_cfg->get_Config();
cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun];
if(cur_Lin_Fun->getName() == CONF_VALID_STATE_DEV_1) {
cur_Lin_Fun->setDomain(false, true, (float)-cur_values.outter_bound_sim_dif);
cur_Lin_Fun->setKandD((float)0, (float)0);
}else if (cur_Lin_Fun->getName() == CONF_VALID_STATE_DEV_2) {
cur_Lin_Fun->setDomain(true, (float)-cur_values.outter_bound_sim_dif, true, (float)-cur_values.inner_bound_sim_dif);
cur_Lin_Fun->setKandD((float)-cur_values.outter_bound_sim_dif, (float)0, (float)-cur_values.inner_bound_sim_dif, (float)1);
}else if (cur_Lin_Fun->getName() == CONF_VALID_STATE_DEV_3) {
cur_Lin_Fun->setDomain(true, (float)-cur_values.inner_bound_sim_dif, true, (float)cur_values.inner_bound_sim_dif);
cur_Lin_Fun->setKandD((float)0, (float)1);
}else if(cur_Lin_Fun->getName() == CONF_VALID_STATE_DEV_4){
cur_Lin_Fun->setDomain(true, (float)cur_values.inner_bound_sim_dif, true, (float)cur_values.outter_bound_sim_dif);
cur_Lin_Fun->setKandD((float)cur_values.inner_bound_sim_dif, (float)1, (float)cur_values.outter_bound_sim_dif, (float)0);
}else if(cur_Lin_Fun->getName() == CONF_VALID_STATE_DEV_5){
cur_Lin_Fun->setDomain(true, (float)cur_values.outter_bound_sim_dif, false);
cur_Lin_Fun->setKandD((float)0, (float)0);
}
}
}
void Testbench :: set_parameters_FuncBlockConfInvStateDev(LinearFunctionBlock* FuncBlockConfInvStateDev)
{
LinearFunction* cur_Lin_Fun;
vector<LinearFunction*> vec_Lin_Fun = FuncBlockConfInvStateDev->get_all_LinearFunctions();
unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size();
unsigned int index_cur_Lin_Fun = 0;
Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config();
for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++)
{
One_Config_t cur_values = cur_Tb_cfg->get_Config();
cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun];
if(cur_Lin_Fun->getName() == CONF_INVALID_STATE_DEV_1) {
cur_Lin_Fun->setDomain(false, true, (float)-cur_values.outter_bound_sim_dif);
cur_Lin_Fun->setKandD((float)0, (float)1);
}else if (cur_Lin_Fun->getName() == CONF_INVALID_STATE_DEV_2) {
cur_Lin_Fun->setDomain(true, (float)-cur_values.outter_bound_sim_dif, true, (float)-cur_values.inner_bound_sim_dif);
cur_Lin_Fun->setKandD((float)-cur_values.outter_bound_sim_dif, (float)1, (float)-cur_values.inner_bound_sim_dif, (float)0);
}else if (cur_Lin_Fun->getName() == CONF_INVALID_STATE_DEV_3) {
cur_Lin_Fun->setDomain(true, (float)-cur_values.inner_bound_sim_dif, true, (float)cur_values.inner_bound_sim_dif);
cur_Lin_Fun->setKandD((float)0, (float)0);
}else if(cur_Lin_Fun->getName() == CONF_INVALID_STATE_DEV_4){
cur_Lin_Fun->setDomain(true, (float)cur_values.inner_bound_sim_dif, true, (float)cur_values.outter_bound_sim_dif);
cur_Lin_Fun->setKandD((float)cur_values.inner_bound_sim_dif, (float)0, (float)cur_values.outter_bound_sim_dif, (float)1);
}else if(cur_Lin_Fun->getName() == CONF_INVALID_STATE_DEV_5){
cur_Lin_Fun->setDomain(true, (float)cur_values.outter_bound_sim_dif, false);
cur_Lin_Fun->setKandD((float)0, (float)1);
}
}
}
void Testbench :: set_parameters_FuncBlockConfValStateTime(LinearFunctionBlock* FuncBlockConfValStateTime)
{
LinearFunction* cur_Lin_Fun;
vector<LinearFunction*> vec_Lin_Fun = FuncBlockConfValStateTime->get_all_LinearFunctions();
unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size();
unsigned int index_cur_Lin_Fun = 0;
Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config();
for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++)
{
One_Config_t cur_values = cur_Tb_cfg->get_Config();
cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun];
if(cur_Lin_Fun->getName() == VALID_STATE_TIME_1) {
cur_Lin_Fun->setDomain(false, true, (float)0);
cur_Lin_Fun->setKandD((float)0, (float)0);
}else if (cur_Lin_Fun->getName() == VALID_STATE_TIME_2) {
cur_Lin_Fun->setDomain(true, (float)0, true, (float)cur_values.length);
cur_Lin_Fun->setKandD((float)0, (float)0, (float)cur_values.length, (float)1);
}else if (cur_Lin_Fun->getName() == VALID_STATE_TIME_3) {
cur_Lin_Fun->setDomain(true, (float)cur_values.length, false);
cur_Lin_Fun->setKandD((float)0, (float)1);
}
}
}
void Testbench :: set_parameters_FuncBlockConfInvStateTime(LinearFunctionBlock* FuncBlockConfInvStateTime)
{
LinearFunction* cur_Lin_Fun;
vector<LinearFunction*> vec_Lin_Fun = FuncBlockConfInvStateTime->get_all_LinearFunctions();
unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size();
unsigned int index_cur_Lin_Fun = 0;
Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config();
for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++)
{
One_Config_t cur_values = cur_Tb_cfg->get_Config();
cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun];
if(cur_Lin_Fun->getName() == INVALID_STATE_TIME_1) {
cur_Lin_Fun->setDomain(false, true, (float)0);
cur_Lin_Fun->setKandD((float)0, (float)1);
}else if (cur_Lin_Fun->getName() == INVALID_STATE_TIME_2) {
cur_Lin_Fun->setDomain(true, (float)0, true, (float)cur_values.length);
cur_Lin_Fun->setKandD((float)0, (float)1, (float)cur_values.length, (float)0);
}else if (cur_Lin_Fun->getName() == INVALID_STATE_TIME_3) {
cur_Lin_Fun->setDomain(true, (float)cur_values.length, false);
cur_Lin_Fun->setKandD((float)0, (float)0);
}
}
}
void Testbench :: set_parameters_DriftDeviation(LinearFunctionBlock* DriftDeviation)
{
LinearFunction* cur_Lin_Fun;
vector<LinearFunction*> vec_Lin_Fun = DriftDeviation->get_all_LinearFunctions();
unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size();
unsigned int index_cur_Lin_Fun = 0;
Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config();
for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++)
{
One_Config_t cur_values = cur_Tb_cfg->get_Config();
cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun];
if(cur_Lin_Fun->getName() == CONFIDENCE_DRIFT_DEVIATION_1) {
cur_Lin_Fun->setDomain(false, true, (float)-cur_values.outter_bound_drift);
cur_Lin_Fun->setKandD((float)0, (float)1);
}else if (cur_Lin_Fun->getName() == CONFIDENCE_DRIFT_DEVIATION_2) {
cur_Lin_Fun->setDomain(true, (float)-cur_values.outter_bound_drift, true, (float)-cur_values.inner_bound_drift);
cur_Lin_Fun->setKandD((float)-cur_values.inner_bound_drift, (float)1, (float)-cur_values.inner_bound_drift, (float)0);
}else if (cur_Lin_Fun->getName() == CONFIDENCE_DRIFT_DEVIATION_3) {
//this line causes a small deviation between the old solution with define and the new one
//I didn't figure out how to get an totally equal result.
cur_Lin_Fun->setDomain(true,(float) -cur_values.inner_bound_drift, true,(float) cur_values.inner_bound_drift);
cur_Lin_Fun->setKandD((float)0, (float)0);
}else if(cur_Lin_Fun->getName() == CONFIDENCE_DRIFT_DEVIATION_4){
cur_Lin_Fun->setDomain(true, (float)cur_values.inner_bound_drift, true, (float)cur_values.outter_bound_drift);
cur_Lin_Fun->setKandD((float)cur_values.inner_bound_drift, (float)0, (float)cur_values.outter_bound_drift, (float)1);
}else if(cur_Lin_Fun->getName() == CONFIDENCE_DRIFT_DEVIATION_5){
cur_Lin_Fun->setDomain(true, (float)cur_values.outter_bound_drift, false);
cur_Lin_Fun->setKandD((float)0, (float)1);
}
}
}
void Testbench :: set_parameters_FuncBlockConfBrokenSamples(LinearFunctionBlock* FuncBlockConfBrokenSamples)
{
LinearFunction* cur_Lin_Fun;
vector<LinearFunction*> vec_Lin_Fun = FuncBlockConfBrokenSamples->get_all_LinearFunctions();
unsigned int size_vec_Lin_Fun = vec_Lin_Fun.size();
unsigned int index_cur_Lin_Fun = 0;
Testbench_Config* cur_Tb_cfg = this->get_current_Testbench_config();
for(index_cur_Lin_Fun = 0; index_cur_Lin_Fun < size_vec_Lin_Fun; index_cur_Lin_Fun++)
{
One_Config_t cur_values = cur_Tb_cfg->get_Config();
cur_Lin_Fun = vec_Lin_Fun[index_cur_Lin_Fun];
if(cur_Lin_Fun->getName() == CONFIDENCE_BROKEN_1) {
cur_Lin_Fun->setDomain(false, true, (float)0);
cur_Lin_Fun->setKandD((float)0, (float)0);
}else if (cur_Lin_Fun->getName() == CONFIDENCE_BROKEN_2) {
cur_Lin_Fun->setDomain(true, (float)0, true, (float)cur_values.bound_broken);
cur_Lin_Fun->setKandD((float)0, (float)0, (float)cur_values.bound_broken, (float)1);
}else if (cur_Lin_Fun->getName() == CONFIDENCE_BROKEN_3) {
cur_Lin_Fun->setDomain(true, (float)cur_values.bound_broken, false);
cur_Lin_Fun->setKandD((float)0, (float)1);
}
}
}
void Testbench :: set_CSV_Reader_row(const int start_row)
{
unsigned int size_of_vec_reg_Sens = vector_registeredSensors.size();
SensorSlotOfTestbench* cur_sens_Slot;
unsigned int index_cur_Slot = 0;
CSVreaderModule* assigned_CSVReader;
for(index_cur_Slot = 0; index_cur_Slot < size_of_vec_reg_Sens; index_cur_Slot++){
cur_sens_Slot = vector_registeredSensors[index_cur_Slot];
assigned_CSVReader = cur_sens_Slot->get_csvReaderModule();
assigned_CSVReader->reset_row(start_row);
}
}
void Testbench :: set_CSV_Reader_to_beginning()
{
unsigned int size_of_vec_reg_Sens = vector_registeredSensors.size();
SensorSlotOfTestbench* cur_sens_Slot;
unsigned int index_cur_Slot = 0;
CSVreaderModule* assigned_CSVReader;
- unsigned const int START_ROW = 1;
+ //unsigned const int START_ROW = 1;
for(index_cur_Slot = 0; index_cur_Slot < size_of_vec_reg_Sens; index_cur_Slot++){
cur_sens_Slot = vector_registeredSensors[index_cur_Slot];
assigned_CSVReader = cur_sens_Slot->get_csvReaderModule();
assigned_CSVReader->set_position_fpointer_to_start();
}
}
void Testbench:: reset_States()
{
unsigned int size_of_vec_reg_Agents = vector_registeredAgents.size();
AgentSlotOfTestbench* viability_slot_Agent = vector_registeredAgents[size_of_vec_reg_Agents - 1];
Agent* viability_Agent = viability_slot_Agent->get_agent();
StateHandler* cur_state_Handl = viability_Agent->get_stateHandler();
cur_state_Handl->reset_States();
}
void Testbench:: reset_States_and_Slave_Agents()
{
unsigned int size_of_vec_reg_Agents = vector_registeredAgents.size();
AgentSlotOfTestbench* viability_slot_Agent = vector_registeredAgents[size_of_vec_reg_Agents - 1];
Agent* viability_Agent = viability_slot_Agent->get_agent();
StateHandler* cur_state_Handl = viability_Agent->get_stateHandler();
cur_state_Handl->reset_States_and_Slave_Agents();
}
Testbench :: ~Testbench()
{
remove_all_Testbench_Configs();
remove_all_Agents();
remove_all_Channels();
remove_all_Sensors();
}
/*
Testbench :: Testbench() {
num_of_registered_agents = 0;
num_of_registered_sensors = 0;
num_of_registered_channels = 0;
this->id = num_of_units;
num_of_units++;
this->set_name(NO_NAME);
//csv
flag_csv_reader_exist = false;
flag_csv_writer_exist = false;
}
Testbench :: Testbench(char* name) {
num_of_registered_agents = 0;
num_of_registered_sensors = 0;
num_of_registered_channels = 0;
this->id = num_of_units;
num_of_units++;
this->set_name(name);
//csv
flag_csv_reader_exist = false;
flag_csv_writer_exist = false;
}
void Testbench :: simulate() {
if(flag_csv_writer_exist) {
csv_writer->write_field("second");
csv_writer->make_new_field();
for(unsigned int s_ix=0; s_ix<num_of_registered_sensors; s_ix++) {
csv_writer->write_field(registered_sensors[s_ix]->get_name());
csv_writer->make_new_field();
}
for(unsigned int a_ix=0; a_ix<num_of_registered_agents; a_ix++) {
csv_writer->write_field(registered_agents[a_ix]->get_name());
csv_writer->make_new_field();
}
csv_writer->write_field("confidence counter");
csv_writer->make_new_field();
csv_writer->make_new_line();
}
//TODO: HIER ENDLOSSCHLEIFE ODER SO - Irgendwas, dass stoppt, wenn file zu ende
for(unsigned int sec=1; sec<=29208; sec++) {
printf("second %u\n", sec);
if(flag_csv_writer_exist) {
csv_writer->write_field((int)sec);
csv_writer->make_new_field();
}
//Update Sensor Values
for(unsigned int s_ix = 0; s_ix < num_of_registered_sensors; s_ix++) {
//TODO: make possibility of non-registered csv-reader
if(flag_sensor_has_csvr[s_ix]) {
float value_from_csv;
if(registered_sensors_csvr[s_ix] != NULL) {
if(registered_sensors_csvr[s_ix]->get_next_value(&value_from_csv)) {
registered_sensors[s_ix]->update_sensor_value(value_from_csv);
//printf("field of %s: %f", registered_sensors[s_ix]->get_name(), value_from_csv);
}
}
}
}
for(unsigned int s_ix = 0; s_ix < num_of_registered_sensors; s_ix++) {
registered_sensors[s_ix]->trigger();
if(flag_csv_writer_exist) {
if(registered_sensors[s_ix]->get_flag_sensor_value_is_valid()) {
csv_writer->write_field(registered_sensors[s_ix]->get_sensor_value());
}
csv_writer->make_new_field();
}
}
for(unsigned int c_ix = 0; c_ix < num_of_registered_channels; c_ix++) {
//printf("\n\n\nTRIGGER CHANNELS\n");
registered_channels[c_ix]->trigger();
}
for(unsigned int a_ix = 0; a_ix < num_of_registered_agents; a_ix++) {
registered_agents[a_ix]->trigger();
if(flag_csv_writer_exist) {
if(registered_agents[a_ix]->get_flag_bunched_score_exist()) {
csv_writer->write_field(registered_agents[a_ix]->get_bunched_score());
csv_writer->make_new_field();
csv_writer->write_field((int)registered_agents[a_ix]->get_bunch_score_confidency());
}
else if(registered_agents[a_ix]->get_flag_abstracted_sensor_score_exist(0)) {
csv_writer->write_field(registered_agents[a_ix]->get_abstracted_sensor_score(0));
}
if(a_ix < num_of_registered_agents-1) {
csv_writer->make_new_field();
}
}
}
if(flag_csv_writer_exist) {
csv_writer->make_new_line();
}
getchar();
}
if(flag_csv_writer_exist) {
csv_writer->close_file();
}
}
//for agents:
unsigned int Testbench :: get_num_of_registered_agents() {
return num_of_registered_agents;
}
bool Testbench :: register_agent(Agent *agent) {
if(num_of_registered_agents < MAX_NUM_OF_AGENTS) {
registered_agents[num_of_registered_agents] = agent;
num_of_registered_agents++;
return true;
}
return false;
}
bool Testbench :: deregister_agent(Agent *agent) {
unsigned int agent_ix;
if(get_ix_of_agent(agent, &agent_ix)) {
return deregister_agent(agent_ix);
}
return false;
}
bool Testbench :: deregister_agent(unsigned int agent_ix) {
if(agent_ix < num_of_registered_agents) {
for(unsigned int a_ix=agent_ix; a_ix<num_of_registered_agents-1; a_ix++) {
registered_agents[a_ix] = registered_agents[a_ix+1];
}
num_of_registered_agents--;
return true;
}
return false;
}
bool Testbench :: get_ix_of_agent(Agent *agent, unsigned int *agent_ix) {
for(unsigned int a_ix=0; a_ix<num_of_registered_agents; a_ix++) {
if(registered_agents[a_ix] == agent) {
*agent_ix = a_ix;
return true;
}
}
return false;
}
//for sensors:
unsigned int Testbench :: get_num_of_registered_sensors() {
return num_of_registered_sensors;
}
bool Testbench :: register_sensor(Sensor* sensor) {
if(num_of_registered_sensors < MAX_NUM_OF_SENSORS) {
registered_sensors[num_of_registered_sensors] = sensor;
num_of_registered_sensors++;
return true;
}
return false;
}
bool Testbench :: register_sensor(Sensor* sensor, CSV_Reader *csvr) {
if(num_of_registered_sensors < MAX_NUM_OF_SENSORS) {
registered_sensors[num_of_registered_sensors] = sensor;
registered_sensors_csvr[num_of_registered_sensors] = csvr;
flag_sensor_has_csvr[num_of_registered_sensors] = true;
num_of_registered_sensors++;
return true;
}
return false;
}
bool Testbench :: deregister_sensor(Sensor* sensor) {
unsigned int sensor_ix;
if(get_ix_of_sensor(sensor, &sensor_ix)) {
return deregister_sensor(sensor_ix);
}
return false;
}
bool Testbench :: deregister_sensor(unsigned int sensor_ix) {
if(sensor_ix < num_of_registered_sensors) {
for(unsigned int s_ix=sensor_ix; s_ix<num_of_registered_sensors-1; s_ix++) {
registered_sensors[s_ix] = registered_sensors[s_ix+1];
//todo: next 2 lines are untested - test then
registered_sensors_csvr[s_ix] = registered_sensors_csvr[s_ix+1];
flag_sensor_has_csvr[s_ix] = flag_sensor_has_csvr[s_ix+1];
}
num_of_registered_sensors--;
return true;
}
return false;
}
bool Testbench :: get_ix_of_sensor(Sensor* sensor, unsigned int *sensor_ix) {
for(unsigned int s_ix=0; s_ix<num_of_registered_sensors; s_ix++) {
if(registered_sensors[s_ix] == sensor) {
*sensor_ix = s_ix;
return true;
}
}
return false;
}
bool Testbench :: get_flag_sensor_has_csvr(unsigned int sensor_ix) {
return flag_sensor_has_csvr[sensor_ix];
}
CSV_Reader* Testbench :: get_registered_sensors_csvr(unsigned int sensor_ix) {
if(flag_sensor_has_csvr[sensor_ix]) {
return registered_sensors_csvr[sensor_ix];
}
return NULL;
}
//TODO: test following function! ...until now it is untested
CSV_Reader* Testbench :: get_registered_sensors_csvr(Sensor* sensor) {
unsigned int sensor_ix;
if(get_ix_of_sensor(sensor, &sensor_ix)) {
if(flag_sensor_has_csvr[sensor_ix]) {
return registered_sensors_csvr[sensor_ix];
}
}
return NULL;
}
//for channels:
unsigned int Testbench :: get_num_of_registered_channels() {
return num_of_registered_channels;
}
bool Testbench :: register_channel(Channel* channel) {
if(num_of_registered_channels < MAX_NUM_OF_CHANNELS) {
registered_channels[num_of_registered_channels] = channel;
num_of_registered_channels++;
return true;
}
return false;
}
bool Testbench :: deregister_channel(Channel* channel) {
unsigned int channel_ix;
if(get_ix_of_channel(channel, &channel_ix)) {
return deregister_channel(channel_ix);
}
return false;
}
bool Testbench :: deregister_channel(unsigned int channel_ix) {
if(channel_ix < num_of_registered_channels) {
for(unsigned int c_ix=channel_ix; c_ix<num_of_registered_channels-1; c_ix++) {
registered_channels[channel_ix] = registered_channels[channel_ix+1];
}
num_of_registered_channels--;
return true;
}
return false;
}
bool Testbench :: get_ix_of_channel(Channel* channel, unsigned int *channel_ix) {
for(unsigned int c_ix=0; c_ix<num_of_registered_channels; c_ix++) {
if(registered_channels[c_ix] == channel) {
*channel_ix = c_ix;
return true;
}
}
return false;
}
bool Testbench :: register_csv_reader(CSV_Reader* csv_reader) {
if(csv_reader != NULL) {
this->csv_reader = csv_reader;
flag_csv_reader_exist = true;
return true;
}
return false;
}
bool Testbench :: register_csv_writer(CSV_Writer* csv_writer) {
if(csv_writer != NULL) {
this->csv_writer = csv_writer;
flag_csv_writer_exist = true;
return true;
}
return false;
}
*/
diff --git a/Version_Max_07_05_2018_CMake/src/Testbench.h b/Version_Max_07_05_2018_CMake/src/Testbench.h
index d219b2e..7ad9dfc 100755
--- a/Version_Max_07_05_2018_CMake/src/Testbench.h
+++ b/Version_Max_07_05_2018_CMake/src/Testbench.h
@@ -1,219 +1,219 @@
#ifndef TESTBENCH_HEADERFILE
#define TESTBENCH_HEADERFILE
#include <vector>
#include "AgentSlotOfTestbench.h"
#include "ChannelSlotOfTestbench.h"
#include "CSVreaderModule.h"
#include "SensorSlotOfTestbench.h"
#include "Unit.h"
#include "Agent.h"
#include "Testbench_Config.h"
/*
#include "Agent.h"
#include "Channel.h"
#include "CSVreader.h"
#include "CSV_Writer.h"
#define MAX_NUM_OF_AGENTS 20
#define MAX_NUM_OF_CHANNELS 80
#define MAX_NUM_OF_SENSORS 20
*/
using namespace std;
//definitions for the linear function blocks, with their associated linear function names
//first name of the linear function block and then the names of the linear functions registered
//within this function block, is later used to identify the right linear function
//to parameterize it correctly.
const string FUNC_BLOCK_NAME_SAME_STATE_DEV = "funcBlock:confSim2StateDev";
const string CONF_SIM2_STATE_DEV_1 = "ConfSim2StateDev1";
const string CONF_SIM2_STATE_DEV_2 = "ConfSim2StateDev2";
const string CONF_SIM2_STATE_DEV_3 = "ConfSim2StateDev3";
const string CONF_SIM2_STATE_DEV_4 = "ConfSim2StateDev4";
const string CONF_SIM2_STATE_DEV_5 = "ConfSim2StateDev5";
const string FUNC_BLOCK_NAME_ANOTHER_STATE_DEV = "funcBlock:confDif2StateDev";
const string CONF_DIF2_STATE_DEV_1 = "ConfDif2StateDev1";
const string CONF_DIF2_STATE_DEV_2 = "ConfDif2StateDev2";
const string CONF_DIF2_STATE_DEV_3 = "ConfDif2StateDev3";
const string CONF_DIF2_STATE_DEV_4 = "ConfDif2StateDev4";
const string CONF_DIF2_STATE_DEV_5 = "ConfDif2StateDev5";
const string FUNC_BLOCK_NAME_SAME_TIME = "funcBlock:confSim2StateTime";
const string CONF_SIM2_STATE_TIME_1 = "ConfSim2StateTime1";
const string CONF_SIM2_STATE_TIME_2 = "ConfSim2StateTime2";
const string CONF_SIM2_STATE_TIME_3 = "ConfSim2StateTime3";
const string FUNC_BLOCK_NAME_ANOTHER_STATE_TIME = "funcBlock:confDif2StateTime";
const string CONF_DIF2_STATE_TIME_1 = "ConfDif2StateTime1";
const string CONF_DIF2_STATE_TIME_2 = "ConfDif2StateTime2";
const string CONF_DIF2_STATE_TIME_3 = "ConfDif2StateTime3";
const string FUNC_BLOCK_NAME_VAILD_STATE_DEV = "funcBlock:confValidStateDev";
const string CONF_VALID_STATE_DEV_1 = "ConfValidStateDev1";
const string CONF_VALID_STATE_DEV_2 = "ConfValidStateDev2";
const string CONF_VALID_STATE_DEV_3 = "ConfValidStateDev3";
const string CONF_VALID_STATE_DEV_4 = "ConfValidStateDev4";
const string CONF_VALID_STATE_DEV_5 = "ConfValidStateDev5";
const string FUNC_BLOCK_NAME_INVALID_STATE_DEV = "funcBlock:confInvalidStateDev";
const string CONF_INVALID_STATE_DEV_1 = "ConfInvalidStateDev1";
const string CONF_INVALID_STATE_DEV_2 = "ConfInvalidStateDev2";
const string CONF_INVALID_STATE_DEV_3 = "ConfInvalidStateDev3";
const string CONF_INVALID_STATE_DEV_4 = "ConfInvalidStateDev4";
const string CONF_INVALID_STATE_DEV_5 = "ConfInvalidStateDev5";
const string FUNC_BLOCK_NAME_VALID_STATE_TIME = "funcBlock:confValidStateTime";
const string VALID_STATE_TIME_1 = "ValidStateTime1";
const string VALID_STATE_TIME_2 = "ValidStateTime2";
const string VALID_STATE_TIME_3 = "ValidStateTime3";
const string FUNC_BLOCK_NAME_INVALID_STATE_TIME = "funcBlock:confInvalidStateTime";
const string INVALID_STATE_TIME_1 = "InvalidStateTime1";
const string INVALID_STATE_TIME_2 = "InvalidStateTime2";
const string INVALID_STATE_TIME_3 = "InvalidStateTime3";
const string FUNC_BLOCK_NAME_CONFIDENCE_STATE_DRIFTS = "confidence:confStateDrifts";
const string CONFIDENCE_DRIFT_DEVIATION_1 = "ConfidenceDriftDeviation1";
const string CONFIDENCE_DRIFT_DEVIATION_2 = "ConfidenceDriftDeviation2";
const string CONFIDENCE_DRIFT_DEVIATION_3 = "ConfidenceDriftDeviation3";
const string CONFIDENCE_DRIFT_DEVIATION_4 = "ConfidenceDriftDeviation4";
const string CONFIDENCE_DRIFT_DEVIATION_5 = "ConfidenceDriftDeviation5";
const string FUNC_BLOCK_NAME_CONFIDENCE_BROKEN = "confidence:broken";
const string CONFIDENCE_BROKEN_1 = "ConfidenceBroken1";
const string CONFIDENCE_BROKEN_2 = "ConfidenceBroken2";
const string CONFIDENCE_BROKEN_3 = "ConfidenceBroken3";
class Testbench : public Module {
private:
//TODO: set- and get function for maxNumOf_registeredAgents;
vector<AgentSlotOfTestbench*> vector_registeredAgents;
//TODO: set- and get function for maxNumOf_registeredChannels;
vector<ChannelSlotOfTestbench*> vector_registeredChannels;
//TODO: set- and get function for maxNumOf_registeredSensors;
vector<SensorSlotOfTestbench*> vector_registeredSensors;
vector<Testbench_Config*> vector_registered_Configs;
void remove_all_Testbench_Configs();
void remove_all_Agents();
void remove_all_Channels();
void remove_all_Sensors();
void set_parameters_FuncBlockConfSim2StateDev(LinearFunctionBlock* FuncBlockConfSim2StateDev);
void set_parameters_FuncBlockConfDif2StateDev(LinearFunctionBlock* FuncBlockConfDif2StateDev);
void set_parameters_FuncBlockConfSim2StateTime(LinearFunctionBlock* FuncBlockConfSim2StateTime);
void set_parameters_FuncBlockConfDif2StateTime(LinearFunctionBlock* FuncBlockConfDif2StateTime);
void set_parameters_FuncBlockConfValStateDev(LinearFunctionBlock* FuncBlockConfValStateDev);
void set_parameters_FuncBlockConfInvStateDev(LinearFunctionBlock* FuncBlockConfInvStateDev);
void set_parameters_FuncBlockConfValStateTime(LinearFunctionBlock* FuncBlockConfValStateTime);
void set_parameters_FuncBlockConfInvStateTime(LinearFunctionBlock* FuncBlockConfInvStateTime);
void set_parameters_DriftDeviation(LinearFunctionBlock* DriftDeviation);
void set_parameters_FuncBlockConfBrokenSamples(LinearFunctionBlock* FuncBlockConfBrokenSamples);
public:
static const unsigned int MAXNUM_OF_REGISTERED_AGENTS = 1000;
static const unsigned int MAXNUM_OF_REGISTERED_CHANNELS = 1000;
static const unsigned int MAXNUM_OF_REGISTERED_SENSORS = 1000;
Testbench();
- Testbench(char* name);
+ Testbench(std::string name);
void init_testbench();
bool register_agent(Agent* agent);
bool register_sensor(Sensor* sensor);
SensorSlotOfTestbench* get_sensorSlotAddressOfTestbench(Sensor* sensor);
bool register_channel(Channel* channel);
bool register_testbench_config(Testbench_Config* tb_config);
vector<Testbench_Config*>& get_all_registered_testbench_configs();
void set_current_tb_config_index(const int index);
Testbench_Config* get_current_Testbench_config();
void set_config_values_in_linear_functions();
bool free_resources();
void set_CSV_Writer_parameter();
void set_CSV_Reader_row(const int start_row);
void set_CSV_Reader_to_beginning();
void reset_States();
void reset_States_and_Slave_Agents();
void simulate(unsigned int rounds);
vector<AgentSlotOfTestbench*>& get_all_registeredAgents();
~Testbench();
/*
private:
unsigned int num_of_registered_agents;
Agent* registered_agents[MAX_NUM_OF_AGENTS];
unsigned int num_of_registered_channels;
Channel* registered_channels[MAX_NUM_OF_CHANNELS];
unsigned int num_of_registered_sensors;
Sensor* registered_sensors[MAX_NUM_OF_SENSORS];
CSV_Reader* registered_sensors_csvr[MAX_NUM_OF_SENSORS];
bool flag_sensor_has_csvr[MAX_NUM_OF_SENSORS];
//csv
CSV_Reader* csv_reader;
bool flag_csv_reader_exist;
CSV_Writer* csv_writer;
bool flag_csv_writer_exist;
public:
Testbench();
Testbench(char* name);
void simulate();
//for agents:
unsigned int get_num_of_registered_agents();
bool register_agent(Agent* agent);
bool deregister_agent(Agent* agent);
bool deregister_agent(unsigned int agent_ix);
bool get_ix_of_agent(Agent* agent, unsigned int *agent_ix);
//for sensors:
unsigned int get_num_of_registered_sensors();
bool register_sensor(Sensor* sensor);
bool register_sensor(Sensor* sensor, CSV_Reader *csvr);
bool deregister_sensor(Sensor* sensor);
bool deregister_sensor(unsigned int sensor_ix);
bool get_ix_of_sensor(Sensor* sensor, unsigned int *sensor_ix);
bool get_flag_sensor_has_csvr(unsigned int sensor_ix);
CSV_Reader* get_registered_sensors_csvr(unsigned int sensor_ix);
CSV_Reader* get_registered_sensors_csvr(Sensor* sensor);
//for channels:
unsigned int get_num_of_registered_channels();
bool register_channel(Channel* channel);
bool deregister_channel(Channel* channel);
bool deregister_channel(unsigned int channel_ix);
bool get_ix_of_channel(Channel* channel, unsigned int *channel_ix);
//csv
bool register_csv_reader(CSV_Reader* csv_reader);
bool register_csv_writer(CSV_Writer* csv_writer);
*/
};
#endif
diff --git a/Version_Max_07_05_2018_CMake/src/Testbench_Config.cpp b/Version_Max_07_05_2018_CMake/src/Testbench_Config.cpp
index 5bfe52d..2aefc48 100755
--- a/Version_Max_07_05_2018_CMake/src/Testbench_Config.cpp
+++ b/Version_Max_07_05_2018_CMake/src/Testbench_Config.cpp
@@ -1,228 +1,234 @@
/*
* Testbench_Config.cpp
*
* Created on: 26.06.2018
* Author: edwin
*/
#include "Testbench_Config.h"
vector<Testbench_Config*> Testbench_Config::s_vec_all_created_Configs;
int Testbench_Config::s_counter_of_all_created_configs = 0;
int Testbench_Config::s_active_Config = 0;
/*
*
*/
void Testbench_Config::register_Config()
{
if(s_vec_all_created_Configs.max_size() > s_vec_all_created_Configs.size()){
s_vec_all_created_Configs.push_back(this);
this->m_current_index = s_counter_of_all_created_configs;
s_counter_of_all_created_configs = s_counter_of_all_created_configs + 1;
} else {
cout << "It is not possible to add an Testbench_Config to vector, Testbench_Config not registered" << endl;
}
}
/*
*
*/
void Testbench_Config::deregister_Config()
{
if (!s_vec_all_created_Configs.empty()) {
int index = 0;
int old_max_index = 0;
std::vector<Testbench_Config*>::iterator it = s_vec_all_created_Configs.begin();
for (; index != this->m_current_index; it++) {
index = index + 1;
}
old_max_index = s_vec_all_created_Configs.size() -1;
if (index == this->m_current_index) {
s_vec_all_created_Configs.erase(it);
}
if(index < old_max_index) {
adapt_Indices(index);
}
this->m_current_index = s_object_is_deleted;
s_counter_of_all_created_configs = s_counter_of_all_created_configs - 1;
}
}
/*
*
*/
void Testbench_Config::adapt_Indices(int from_index_to_change)
{
int index = 0;
for(index = 0; index < s_vec_all_created_Configs.size(); index++){
if(index >= from_index_to_change) {
Testbench_Config* cur_config = s_vec_all_created_Configs[index];
cur_config->m_current_index = cur_config->m_current_index - 1;
}
}
}
Testbench_Config::Testbench_Config()
{
this->configuration.bound_broken = float(2);
- this->configuration.outter_bound_sim_dif = 0.20;
- this->configuration.inner_bound_sim_dif = 0.01;
+ this->configuration.outter_bound_sim_dif = (float)0.20;
+ this->configuration.inner_bound_sim_dif = (float)0.01;
this->configuration.outter_bound_drift = 3 * this->configuration.outter_bound_sim_dif;
this->configuration.inner_bound_drift = this->configuration.outter_bound_sim_dif;
this->configuration.length = (float) 10;
register_Config();
}
/*
*
*/
Testbench_Config::Testbench_Config(One_Config_t& a_config)
{
this->configuration = a_config;
register_Config();
}
/*
* return the index of the object in the static class vector
*/
int Testbench_Config::get_own_index()
{
return this->m_current_index;
}
/*
*
*/
One_Config_t Testbench_Config::get_Config()
{
- if(this != NULL && this->m_current_index != s_object_is_deleted){
+ One_Config_t dummy_config;
+ //if(this != NULL && this->m_current_index != s_object_is_deleted){
+ if (this->m_current_index != s_object_is_deleted) {
+ this->configuration.valid = true;
return this->configuration;
}
+ dummy_config.valid = false;
+ return dummy_config;
}
/*
*
*/
void Testbench_Config::print()
{
- if(this != NULL && this->m_current_index != s_object_is_deleted) {
+ //if (this != NULL && this->m_current_index != s_object_is_deleted) {
+ if (this->m_current_index != s_object_is_deleted) {
std::cout << "Index of the configuration: " << this->m_current_index;
std::cout << "The values of the configuration are: ";
std::cout << "Broken boundary: " << this->configuration.bound_broken << " ";
std::cout << "Inner boundary similar state: " << this->configuration.inner_bound_sim_dif << " ";
std::cout << "Outter boundary similar state: " << this->configuration.outter_bound_sim_dif << " ";
std::cout << "Inner boundary drift: " << this->configuration.inner_bound_drift << " ";
std::cout << "Outter boundary drift: " << this->configuration.outter_bound_drift << " ";
std::cout << "Length: " << this->configuration.length << " ";
std::cout << std::endl;
}else {
std::cout << "Object points to NULL" << std::endl;
}
}
/**
* returns the index of the active config of the Testbench.
*/
int Testbench_Config::get_active_Config()
{
return s_active_Config;
}
/**
* Sets the index for the current config used.
* @param index value >= 0, -1 = Invalid Index
*
*/
void Testbench_Config::set_active_Config(const int index)
{
if(index < s_counter_of_all_created_configs) {
s_active_Config = index;
}else {
s_active_Config = s_INVALID_INDEX;
}
}
void Testbench_Config::cut_number_of_decimal_digits(std::string & str_number)
{ const std::string delimeter = ".";
const std::string zero = "0";
std::string str_temp;
std::size_t first_pos;
std::size_t length;
std::size_t first_not_zero;
std::size_t index;
length = str_number.length();
first_pos = str_number.find_first_of(delimeter);
if (first_pos != std::string::npos)
{
//0 is the start of the string, add 1 to get also the delimeter into the string
str_temp =str_number.substr(0, first_pos + 1);
length = length - first_pos - 1;
str_number = str_number.substr(first_pos + 1, length);
first_not_zero = str_number.find_first_not_of(zero);
if(first_not_zero == std::string::npos)
{
str_number = str_temp + str_number[0] + str_number[1];
}
else
{
for(index = 0; index <= first_not_zero; index++){
str_temp = str_temp + str_number[index];
}
str_number = str_temp;
}
}
}
/**
* returns all parameters of the config as a string.
* B_b means bound broken border, I_B_d means inner bound drift border
* O_B_d means outter bound drift border, I_B_s_d means inner bound simular signal border
* O_B_s_d means outter bound simular signalr border
*/
std::string Testbench_Config::get_Config_as_String()
{
//Ali for file name compatebility in Windows, all ':' chars converted to '-', also blanks removed or changed to '_'
std::string config;
std::string str_part;
str_part = std::to_string(this->configuration.bound_broken);
cut_number_of_decimal_digits(str_part);
config = "_B_b-" + str_part;
str_part = std::to_string(this->configuration.inner_bound_drift);
cut_number_of_decimal_digits(str_part);
config = config + "_I_B_d-"+ str_part;
str_part = std::to_string(this->configuration.outter_bound_drift);
cut_number_of_decimal_digits(str_part);
config = config + "_O_B_d-" + str_part;
str_part = std::to_string(this->configuration.inner_bound_sim_dif);
cut_number_of_decimal_digits(str_part);
config = config + "_I_B_s_d-" + str_part;
str_part = std::to_string(this->configuration.outter_bound_sim_dif);
cut_number_of_decimal_digits(str_part);
config = config + "_O_B_s_d-" + str_part + "";
config = config + "_Length-" + std::to_string(this->configuration.length) + "";
return config;
}
/*
*
*/
Testbench_Config::~Testbench_Config()
{
deregister_Config();
}
diff --git a/Version_Max_07_05_2018_CMake/src/Testbench_Config.h b/Version_Max_07_05_2018_CMake/src/Testbench_Config.h
index b4af2cd..14877bd 100755
--- a/Version_Max_07_05_2018_CMake/src/Testbench_Config.h
+++ b/Version_Max_07_05_2018_CMake/src/Testbench_Config.h
@@ -1,72 +1,74 @@
/*
* Testbench_Config.h
*
* Created on: 26.06.2018
* Author: edwin
*/
#ifndef TESTBENCH_CONFIG_H_
#define TESTBENCH_CONFIG_H_
#include <iostream>
#include <cstddef>
#include <vector>
#include <string>
#include <stdio.h>
using namespace std;
typedef struct One_Config {
///parameter of outter boundary for similar function
float outter_bound_sim_dif;
///parameter of inner boundary for similar function
float inner_bound_sim_dif;
///parameters of outter boundary for drift.
float outter_bound_drift;
///parameters of inner boundary for drift.
float inner_bound_drift;
///timer telling, after downsampling how many samples after input has changed it is allowed
///that output is changing, for very slow system high value and for fast system low value
float bound_broken;
///length where fuzzy function raises from 0 to 1 or 1 to 0 for the complementery.
///history of the data depends of it, and should change, if it changes.
int length;
+ //to show if the config was parameterised correctly.
+ bool valid;
} One_Config_t;
class Testbench_Config {
private:
static vector<Testbench_Config*> s_vec_all_created_Configs;
static int s_counter_of_all_created_configs;
static int s_active_Config;
const static int s_object_is_deleted = -1;
const static int s_INVALID_INDEX = -1;
const static int s_MAX_LENGTH_FLOAT_STRING = 20;
int m_current_index;
One_Config_t configuration;
void register_Config();
void deregister_Config();
void adapt_Indices(int from_index_to_change);
void cut_number_of_decimal_digits(std::string & str_number);
public:
Testbench_Config();
Testbench_Config(One_Config_t& a_config);
int get_own_index();
One_Config_t get_Config();
void print();
string get_Config_as_String();
~Testbench_Config();
static int get_active_Config();
static void set_active_Config(const int index);
};
#endif /* TESTBENCH_CONFIG_H_ */
diff --git a/Version_Max_07_05_2018_CMake/src/attach_modules.cpp b/Version_Max_07_05_2018_CMake/src/attach_modules.cpp
index fd915b9..c4d6f21 100755
--- a/Version_Max_07_05_2018_CMake/src/attach_modules.cpp
+++ b/Version_Max_07_05_2018_CMake/src/attach_modules.cpp
@@ -1,60 +1,60 @@
#include "attach_modules.h"
#include "rlutil.h"
#define PRINT
using namespace rlutil;
bool attach_historyModuleToSensorSlotInAgent(Agent* agent, Sensor* sensor, Channel* inputPort, HistoryModule* historyModule) {
if(agent != NULL && inputPort != NULL && historyModule != NULL) {
SensorSlotOfAgent* sensorSlotOfAgent = agent->get_sensorHandlerOfAgent()->get_sensorSlotAddress(inputPort);
if(sensorSlotOfAgent != NULL) {
#ifdef PRINT
printf(" > HistoryModule ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", historyModule->get_name());
+ printf("%s ", historyModule->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", historyModule->get_id());
#endif // PRINT
if(sensorSlotOfAgent->set_historyModule(historyModule)) {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTGREEN);
printf("attached ");
setColor(TXTCOLOR_GREY);
printf("to Sensor ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", sensor->get_name());
+ printf("%s ", sensor->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u) in Agent ", sensor->get_id());
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", agent->get_name());
+ printf("%s ", agent->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", agent->get_id());
#endif // PRINT
return true;
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
printf("Couldn't attach the HistoryModule!\n");
setColor(TXTCOLOR_GREY);
#endif // PRINT
}
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
- printf(" > Couldn't attach the HistoryModule because Sensor isn't mounted in %s (id: %03u)!\n", agent->get_name(), agent->get_id());
+ printf(" > Couldn't attach the HistoryModule because Sensor isn't mounted in %s (id: %03u)!\n", agent->get_name().c_str(), agent->get_id());
setColor(TXTCOLOR_GREY);
#endif // PRINT
}
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
printf(" > Couldn't attach the HistoryModule because Agent, Channel, or HistoryModule is not valid!\n");
setColor(TXTCOLOR_GREY);
#endif // PRINT
}
return false;
}
\ No newline at end of file
diff --git a/Version_Max_07_05_2018_CMake/src/attach_modulesToTestbench.cpp b/Version_Max_07_05_2018_CMake/src/attach_modulesToTestbench.cpp
index 91c1c8a..d90ffe6 100755
--- a/Version_Max_07_05_2018_CMake/src/attach_modulesToTestbench.cpp
+++ b/Version_Max_07_05_2018_CMake/src/attach_modulesToTestbench.cpp
@@ -1,62 +1,62 @@
#include "attach_modulesToTestbench.h"
#include "rlutil.h"
#include "SensorSlotOfTestbench.h"
#define PRINT
using namespace rlutil;
bool attach_csvReaderModuleToSensorSlotInAgent(Testbench* testbench, Sensor* sensor, CSVreaderModule* csvReaderModule) {
if(testbench != NULL && sensor != NULL && csvReaderModule != NULL) {
SensorSlotOfTestbench* sensorSlot = testbench->get_sensorSlotAddressOfTestbench(sensor);
if(sensorSlot != NULL) {
#ifdef PRINT
printf(" > CSV-Reader ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", csvReaderModule->get_name());
+ printf("%s ", csvReaderModule->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", csvReaderModule->get_id());
#endif // PRINT
if(sensorSlot->set_csvReaderModule(csvReaderModule)) {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTGREEN);
printf("attached ");
setColor(TXTCOLOR_GREY);
printf("to Sensor ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", sensor->get_name());
+ printf("%s ", sensor->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u) in Testbench ", sensor->get_id());
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", testbench->get_name());
+ printf("%s ", testbench->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", testbench->get_id());
#endif // PRINT
return true;
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
printf("Couldn't attach the CSVreaderModule!\n");
setColor(TXTCOLOR_GREY);
#endif // PRINT
}
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
- printf(" > Couldn't attach the CSVreaderModule because Sensor isn't registered in %s (id: %03u)!\n", testbench->get_name(), testbench->get_id());
+ printf(" > Couldn't attach the CSVreaderModule because Sensor isn't registered in %s (id: %03u)!\n", testbench->get_name().c_str(), testbench->get_id());
setColor(TXTCOLOR_GREY);
#endif // PRINT
}
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
printf(" > Couldn't attach the CSVreaderModule because Testbench, Sensorm or CSVreaderModule is not valid!\n");
setColor(TXTCOLOR_GREY);
#endif // PRINT
}
return false;
}
\ No newline at end of file
diff --git a/Version_Max_07_05_2018_CMake/src/configCAMforNewMotor.cpp b/Version_Max_07_05_2018_CMake/src/configCAMforNewMotor.cpp
index a8ca1e2..177f483 100644
--- a/Version_Max_07_05_2018_CMake/src/configCAMforNewMotor.cpp
+++ b/Version_Max_07_05_2018_CMake/src/configCAMforNewMotor.cpp
@@ -1 +1,517 @@
-// test 123
\ No newline at end of file
+#include "Agent.h"
+#include "CSVreaderModule.h"
+#include "Channel.h"
+#include "Sensor.h"
+#include "Testbench.h"
+#include "create_unit.h"
+#include "file_util.h"
+#include "inAgentsRegistrations.h"
+#include "mount_nodes.h"
+#include "register_in_testbench.h"
+#include "setupNode.h"
+
+#include "LinearFunction.h"
+#include "LinearFunctionBlock.h"
+
+
+#define PRINT
+#define STOP_BEFORE_SIMULATING
+
+
+void configAndStartNewMotorExperiment(
+ char *destinationPath, char *datasetPath, char *datasetName,
+ unsigned int datasetLength, float innerBoundSimDif, float outerBoundSimDif,
+ int boundTimeInSamples, float innerBoundDrift, float outerBoundDrift,
+ int boundBrokenTime, int downSamplingFactor) {
+
+ //config starts here
+ // create agents
+ // low level agents - inputs
+ Agent* a_statorVoltage = create_agent("Stator Voltage");
+ setWorkingCycleOfAgent(a_statorVoltage, downSamplingFactor);
+ Agent* a_inputFrequency = create_agent("Input Frequency");
+ setWorkingCycleOfAgent(a_inputFrequency, downSamplingFactor);
+ Agent* a_mechanicalTorque = create_agent("Mechanical Torque");
+ setWorkingCycleOfAgent(a_mechanicalTorque, downSamplingFactor);
+ // low level agents - outputs
+ Agent* a_statorCurrent = create_agent("Stator Current");
+ setWorkingCycleOfAgent(a_statorCurrent, downSamplingFactor);
+ Agent* a_electromagneticTorque = create_agent("Electromagnetic Torque");
+ setWorkingCycleOfAgent(a_electromagneticTorque, downSamplingFactor);
+ Agent* a_speed = create_agent("Speed");
+ setWorkingCycleOfAgent(a_speed, downSamplingFactor);
+ // high level agent
+ Agent* a_viabilityMonitor = create_agent("Viability Monitor");
+ setWorkingCycleOfAgent(a_viabilityMonitor, downSamplingFactor);
+
+ // create sensors
+ // inputs
+ Sensor* s_statorVoltage = create_sensor("Stator Voltage");
+ setWorkingCycleOfSensor(s_statorVoltage, downSamplingFactor);
+ Sensor* s_inputFrequency = create_sensor("Input Frequency");
+ setWorkingCycleOfSensor(s_inputFrequency, downSamplingFactor);
+ Sensor* s_mechanicalTorque = create_sensor("Mechanical Torque");
+ setWorkingCycleOfSensor(s_mechanicalTorque, downSamplingFactor);
+ // outputs
+ Sensor* s_statorCurrent = create_sensor("Stator Current");
+ setWorkingCycleOfSensor(s_statorCurrent, downSamplingFactor);
+ Sensor* s_electromagneticTorque = create_sensor("Electromagnetic Torque");
+ setWorkingCycleOfSensor(s_electromagneticTorque, downSamplingFactor);
+ Sensor* s_speed = create_sensor("Speed");
+ setWorkingCycleOfSensor(s_speed, downSamplingFactor);
+
+ // create channels for sensors
+ // inputs
+ Channel* c_sa_statorVoltage = create_channel("Stator Voltage (SA)", 0);
+ Channel* c_sa_inputFrequency = create_channel("Input Frequency (SA)", 0);
+ Channel* c_sa_mechanicalTorque = create_channel("Mechanical Torque (SA)", 0);
+ // outputs
+ Channel* c_sa_statorCurrent = create_channel("Stator Current (SA)", 0);
+ Channel* c_sa_electromagneticTorque =
+ create_channel("Electromagnetic Torque (SA)", 0);
+ Channel* c_sa_speed = create_channel("Speed Sensor (SA)", 0);
+
+ // create channels for sensors
+ // inputs
+ Channel* c_aa_statorVoltage =
+ create_channel("Stator Voltage (AA-UP)", MAX_BUFFER_LENGTH);
+ Channel* c_aa_inputFrequency =
+ create_channel("Input Frequency (AA-UP)", MAX_BUFFER_LENGTH);
+ Channel* c_aa_mechanicalTorque =
+ create_channel("Mechanical Torque (AA-UP)", MAX_BUFFER_LENGTH);
+ // outputs
+ Channel* c_aa_statorCurrent =
+ create_channel("Stator Current (AA-UP)", MAX_BUFFER_LENGTH);
+ Channel* c_aa_electromagneticTorque =
+ create_channel("Electromagnetic Torque (AA-UP)", MAX_BUFFER_LENGTH);
+ Channel* c_aa_speed =
+ create_channel("Speed Sensor (AA-UP)", MAX_BUFFER_LENGTH);
+
+
+
+
+
+
+
+
+
+ // mount sensors in agents
+ // inputs
+ mount_sensorInAgent(a_statorVoltage, s_statorVoltage, c_sa_statorVoltage);
+ mount_sensorInAgent(a_inputFrequency, s_inputFrequency,
+ c_sa_inputFrequency);
+ mount_sensorInAgent(a_mechanicalTorque, s_mechanicalTorque,
+ c_sa_mechanicalTorque);
+ // outputs
+ mount_sensorInAgent(a_statorCurrent, s_statorCurrent, c_sa_statorCurrent);
+ mount_sensorInAgent(a_electromagneticTorque, s_electromagneticTorque,
+ c_sa_electromagneticTorque);
+ mount_sensorInAgent(a_speed, s_speed, c_sa_speed);
+
+ // mount agents in agent(s)
+ // inputs
+ mount_agentInAgent(a_viabilityMonitor, a_statorVoltage,
+ c_aa_statorVoltage);
+ mount_agentInAgent(a_viabilityMonitor, a_inputFrequency,
+ c_aa_inputFrequency);
+ mount_agentInAgent(a_viabilityMonitor, a_mechanicalTorque,
+ c_aa_mechanicalTorque);
+ // outputs
+ mount_agentInAgent(a_viabilityMonitor, a_statorCurrent,
+ c_aa_statorCurrent);
+ mount_agentInAgent(a_viabilityMonitor, a_electromagneticTorque,
+ c_aa_electromagneticTorque);
+ mount_agentInAgent(a_viabilityMonitor, a_speed, c_aa_speed);
+
+ // register agents in agents' stateHandler
+ // inputs
+ registerSlaveAgentAsInputVariableInStateHandler(a_viabilityMonitor,
+ c_aa_statorVoltage);
+ registerSlaveAgentAsInputVariableInStateHandler(a_viabilityMonitor,
+ c_aa_inputFrequency);
+ registerSlaveAgentAsInputVariableInStateHandler(a_viabilityMonitor,
+ c_aa_mechanicalTorque);
+ // outputs
+ registerSlaveAgentAsOutputVariableInStateHandler(a_viabilityMonitor,
+ c_aa_statorCurrent);
+ registerSlaveAgentAsOutputVariableInStateHandler(a_viabilityMonitor,
+ c_aa_electromagneticTorque);
+ registerSlaveAgentAsOutputVariableInStateHandler(a_viabilityMonitor,
+ c_aa_speed);
+
+ // SAME STATE DEVIATION
+ LinearFunctionBlock confSim2StateDev("funcBlock:confSim2StateDev");
+ LinearFunction funcConfSim2StateDev1;
+ funcConfSim2StateDev1.setDomain(false, true, -1 * outerBoundSimDif);
+ funcConfSim2StateDev1.setKandD((float)0, (float)0);
+ confSim2StateDev.addLinearFunction(&funcConfSim2StateDev1);
+ LinearFunction funcConfSim2StateDev2;
+ funcConfSim2StateDev2.setDomain(true, -1 * outerBoundSimDif, true,
+ -1 * innerBoundSimDif);
+ funcConfSim2StateDev2.setKandD(-1 * outerBoundSimDif, (float)0,
+ -1 * innerBoundSimDif, (float)1);
+ confSim2StateDev.addLinearFunction(&funcConfSim2StateDev2);
+ LinearFunction funcConfSim2StateDev3;
+ funcConfSim2StateDev3.setDomain(true, -1 * innerBoundSimDif, true,
+ innerBoundSimDif);
+ funcConfSim2StateDev3.setKandD((float)0, (float)1);
+ confSim2StateDev.addLinearFunction(&funcConfSim2StateDev3);
+ LinearFunction funcConfSim2StateDev4;
+ funcConfSim2StateDev4.setDomain(true, innerBoundSimDif, true,
+ outerBoundSimDif);
+ funcConfSim2StateDev4.setKandD(innerBoundSimDif, (float)1, outerBoundSimDif,
+ (float)0);
+ confSim2StateDev.addLinearFunction(&funcConfSim2StateDev4);
+ LinearFunction funcConfSim2StateDev5;
+ funcConfSim2StateDev5.setDomain(true, outerBoundSimDif, false);
+ funcConfSim2StateDev5.setKandD((float)0, (float)0);
+ confSim2StateDev.addLinearFunction(&funcConfSim2StateDev5);
+#ifdef PRINT
+ confSim2StateDev.printFunctionBlock("funcBlock:confSim2StateDev");
+#endif // PRINT
+
+ // ANOTHER STATE DEVIATION
+ LinearFunctionBlock confDif2StateDev("funcBlock:confDif2StateDev");
+ LinearFunction funcConfDif2StateDev1;
+ funcConfDif2StateDev1.setDomain(false, true, -1 * outerBoundSimDif);
+ funcConfDif2StateDev1.setKandD((float)0, (float)1);
+ confDif2StateDev.addLinearFunction(&funcConfDif2StateDev1);
+ LinearFunction funcConfDif2StateDev2;
+ funcConfDif2StateDev2.setDomain(true, -1 * outerBoundSimDif, true,
+ -1 * innerBoundSimDif);
+ funcConfDif2StateDev2.setKandD(-1 * outerBoundSimDif, (float)1,
+ -1 * innerBoundSimDif, (float)0);
+ confDif2StateDev.addLinearFunction(&funcConfDif2StateDev2);
+ LinearFunction funcConfDif2StateDev3;
+ funcConfDif2StateDev3.setDomain(true, -1 * innerBoundSimDif, true,
+ innerBoundSimDif);
+ funcConfDif2StateDev3.setKandD((float)0, (float)0);
+ confDif2StateDev.addLinearFunction(&funcConfDif2StateDev3);
+ LinearFunction funcConfDif2StateDev4;
+ funcConfDif2StateDev4.setDomain(true, innerBoundSimDif, true,
+ outerBoundSimDif);
+ funcConfDif2StateDev4.setKandD(innerBoundSimDif, (float)0, outerBoundSimDif,
+ (float)1);
+ confDif2StateDev.addLinearFunction(&funcConfDif2StateDev4);
+ LinearFunction funcConfDif2StateDev5;
+ funcConfDif2StateDev5.setDomain(true, outerBoundSimDif, false);
+ funcConfDif2StateDev5.setKandD((float)0, (float)1);
+ confDif2StateDev.addLinearFunction(&funcConfDif2StateDev5);
+#ifdef PRINT
+ confDif2StateDev.printFunctionBlock("funcBlock:confDif2StateDev");
+#endif // PRINT
+
+ // SAME STATE TIME
+ LinearFunctionBlock confSim2StateTime("funcBlock:confSim2StateTime");
+ LinearFunction funcConfSim2StateTime1;
+ funcConfSim2StateTime1.setDomain(false, true, (float)0);
+ funcConfSim2StateTime1.setKandD((float)0, (float)0);
+ confSim2StateTime.addLinearFunction(&funcConfSim2StateTime1);
+ LinearFunction funcConfSim2StateTime2;
+ funcConfSim2StateTime2.setDomain(true, (float)0, true,
+ (float)boundTimeInSamples);
+ funcConfSim2StateTime2.setKandD((float)0, (float)0, (float)boundTimeInSamples,
+ (float)1);
+ confSim2StateTime.addLinearFunction(&funcConfSim2StateTime2);
+ LinearFunction funcConfSim2StateTime3;
+ funcConfSim2StateTime3.setDomain(true, (float)boundTimeInSamples, false);
+ funcConfSim2StateTime3.setKandD((float)0, (float)1);
+ confSim2StateTime.addLinearFunction(&funcConfSim2StateTime3);
+#ifdef PRINT
+ confSim2StateTime.printFunctionBlock("funcBlock:confSim2StateTime");
+#endif // PRINT
+
+ // ANOTHER STATE TIME
+ LinearFunctionBlock confDif2StateTime("funcBlock:confDif2StateTime");
+ LinearFunction funcConfDif2StateTime1;
+ funcConfDif2StateTime1.setDomain(false, true, (float)0);
+ funcConfDif2StateTime1.setKandD((float)0, (float)1);
+ confDif2StateTime.addLinearFunction(&funcConfDif2StateTime1);
+ LinearFunction funcConfDif2StateTime2;
+ funcConfDif2StateTime2.setDomain(true, (float)0, true,
+ (float)boundTimeInSamples);
+ funcConfDif2StateTime2.setKandD((float)0, (float)1, (float)boundTimeInSamples,
+ (float)0);
+ confDif2StateTime.addLinearFunction(&funcConfDif2StateTime2);
+ LinearFunction funcConfDif2StateTime3;
+ funcConfDif2StateTime3.setDomain(true, (float)boundTimeInSamples, false);
+ funcConfDif2StateTime3.setKandD((float)0, (float)0);
+ confDif2StateTime.addLinearFunction(&funcConfDif2StateTime3);
+#ifdef PRINT
+ confDif2StateTime.printFunctionBlock("funcBlock:confDif2StateTime");
+#endif // PRINT
+
+ /************************ FunctionBlocks Val/Inv State (NEU)
+ * ************************/
+
+ // VALID STATE DEVIATION
+ LinearFunctionBlock confValidStateDev("funcBlock:confValidStateDev");
+ LinearFunction funcConfValidStateDev1;
+ funcConfValidStateDev1.setDomain(false, true, -1 * outerBoundSimDif);
+ funcConfValidStateDev1.setKandD((float)0, (float)0);
+ confValidStateDev.addLinearFunction(&funcConfValidStateDev1);
+ LinearFunction funcConfValidStateDev2;
+ funcConfValidStateDev2.setDomain(true, -1 * outerBoundSimDif, true,
+ -1 * innerBoundSimDif);
+ funcConfValidStateDev2.setKandD(-1 * outerBoundSimDif, (float)0,
+ -1 * innerBoundSimDif, (float)1);
+ confValidStateDev.addLinearFunction(&funcConfValidStateDev2);
+ LinearFunction funcConfValidStateDev3;
+ funcConfValidStateDev3.setDomain(true, -1 * innerBoundSimDif, true,
+ innerBoundSimDif);
+ funcConfValidStateDev3.setKandD((float)0, (float)1);
+ confValidStateDev.addLinearFunction(&funcConfValidStateDev3);
+ LinearFunction funcConfValidStateDev4;
+ funcConfValidStateDev4.setDomain(true, innerBoundSimDif, true,
+ outerBoundSimDif);
+ funcConfValidStateDev4.setKandD(innerBoundSimDif, (float)1, outerBoundSimDif,
+ (float)0);
+ confValidStateDev.addLinearFunction(&funcConfValidStateDev4);
+ LinearFunction funcConfValidStateDev5;
+ funcConfValidStateDev5.setDomain(true, outerBoundSimDif, false);
+ funcConfValidStateDev5.setKandD((float)0, (float)0);
+ confValidStateDev.addLinearFunction(&funcConfValidStateDev5);
+#ifdef PRINT
+ confValidStateDev.printFunctionBlock("funcBlock:confValidStateDev");
+#endif // PRINT
+
+ // INVALID STATE DEVIATION
+ LinearFunctionBlock confInvalidStateDev("funcBlock:confInvalidStateDev");
+ LinearFunction funcConfInvalidStateDev1;
+ funcConfInvalidStateDev1.setDomain(false, true, -1 * outerBoundSimDif);
+ funcConfInvalidStateDev1.setKandD((float)0, (float)1);
+ confInvalidStateDev.addLinearFunction(&funcConfInvalidStateDev1);
+ LinearFunction funcConfInvalidStateDev2;
+ funcConfInvalidStateDev2.setDomain(true, -1 * outerBoundSimDif, true,
+ -1 * innerBoundSimDif);
+ funcConfInvalidStateDev2.setKandD(-1 * outerBoundSimDif, (float)1,
+ -1 * innerBoundSimDif, (float)0);
+ confInvalidStateDev.addLinearFunction(&funcConfInvalidStateDev2);
+ LinearFunction funcConfInvalidStateDev3;
+ funcConfInvalidStateDev3.setDomain(true, -1 * innerBoundSimDif, true,
+ innerBoundSimDif);
+ funcConfInvalidStateDev3.setKandD((float)0, (float)0);
+ confInvalidStateDev.addLinearFunction(&funcConfInvalidStateDev3);
+ LinearFunction funcConfInvalidStateDev4;
+ funcConfInvalidStateDev4.setDomain(true, innerBoundSimDif, true,
+ outerBoundSimDif);
+ funcConfInvalidStateDev4.setKandD(innerBoundSimDif, (float)0,
+ outerBoundSimDif, (float)1);
+ confInvalidStateDev.addLinearFunction(&funcConfInvalidStateDev4);
+ LinearFunction funcConfInvalidStateDev5;
+ funcConfInvalidStateDev5.setDomain(true, outerBoundSimDif, false);
+ funcConfInvalidStateDev5.setKandD((float)0, (float)1);
+ confInvalidStateDev.addLinearFunction(&funcConfInvalidStateDev5);
+#ifdef PRINT
+ confInvalidStateDev.printFunctionBlock("funcBlock:confInvalidStateDev");
+#endif // PRINT
+
+ // VALID STATE TIME
+ LinearFunctionBlock confValidStateTime("funcBlock:confValidStateTime");
+ LinearFunction funcConfValidStateTime1;
+ funcConfValidStateTime1.setDomain(false, true, (float)0);
+ funcConfValidStateTime1.setKandD((float)0, (float)0);
+ confValidStateTime.addLinearFunction(&funcConfValidStateTime1);
+ LinearFunction funcConfValidStateTime2;
+ funcConfValidStateTime2.setDomain(true, (float)0, true,
+ (float)boundTimeInSamples); // 10
+ funcConfValidStateTime2.setKandD((float)0, (float)0,
+ (float)boundTimeInSamples, (float)1);
+ confValidStateTime.addLinearFunction(&funcConfValidStateTime2);
+ LinearFunction funcConfValidStateTime3;
+ funcConfValidStateTime3.setDomain(true, (float)boundTimeInSamples, false);
+ funcConfValidStateTime3.setKandD((float)0, (float)1);
+ confValidStateTime.addLinearFunction(&funcConfValidStateTime3);
+#ifdef PRINT
+ confValidStateTime.printFunctionBlock("funcBlock:confValidStateTime");
+#endif // PRINT
+
+ // INVALID STATE TIME
+ LinearFunctionBlock confInvalidStateTime("funcBlock:confInvalidStateTime");
+ LinearFunction funcConfInvalidStateTime1;
+ funcConfInvalidStateTime1.setDomain(false, true, (float)0);
+ funcConfInvalidStateTime1.setKandD((float)0, (float)1);
+ confInvalidStateTime.addLinearFunction(&funcConfInvalidStateTime1);
+ LinearFunction funcConfInvalidStateTime2;
+ funcConfInvalidStateTime2.setDomain(true, (float)0, true,
+ (float)boundTimeInSamples);
+ funcConfInvalidStateTime2.setKandD((float)0, (float)1,
+ (float)boundTimeInSamples,
+ (float)0);
+ confInvalidStateTime.addLinearFunction(&funcConfInvalidStateTime2);
+ LinearFunction funcConfInvalidStateTime3;
+ funcConfInvalidStateTime3.setDomain(true, (float)boundTimeInSamples, false);
+ funcConfInvalidStateTime3.setKandD((float)0, (float)0);
+ confInvalidStateTime.addLinearFunction(&funcConfInvalidStateTime3);
+#ifdef PRINT
+ confInvalidStateTime.printFunctionBlock("funcBlock:confInvalidStateTime");
+#endif // PRINT
+
+ /********************************** Functions NOT OK
+ * **********************************/
+
+ LinearFunctionBlock confStateDrifts("confidence:confStateDrifts");
+ LinearFunction functionConfidenceDriftDeviation1;
+ functionConfidenceDriftDeviation1.setDomain(false, true,
+ -1 * outerBoundDrift);
+ functionConfidenceDriftDeviation1.setKandD((float)0, (float)1);
+ confStateDrifts.addLinearFunction(&functionConfidenceDriftDeviation1);
+ LinearFunction functionConfidenceDriftDeviation2;
+ functionConfidenceDriftDeviation2.setDomain(true, -1 * outerBoundDrift, true,
+ -1 * outerBoundDrift);
+ functionConfidenceDriftDeviation2.setKandD(-1 * outerBoundDrift, (float)1,
+ -1 * outerBoundDrift, (float)0);
+ confStateDrifts.addLinearFunction(&functionConfidenceDriftDeviation2);
+ LinearFunction functionConfidenceDriftDeviation3;
+ functionConfidenceDriftDeviation3.setDomain(true, -1 * outerBoundDrift, true,
+ outerBoundDrift);
+ functionConfidenceDriftDeviation3.setKandD((float)0, (float)0);
+ confStateDrifts.addLinearFunction(&functionConfidenceDriftDeviation3);
+ LinearFunction functionConfidenceDriftDeviation4;
+ functionConfidenceDriftDeviation4.setDomain(true, outerBoundDrift, true,
+ outerBoundDrift);
+ functionConfidenceDriftDeviation4.setKandD(outerBoundDrift, (float)0,
+ outerBoundDrift, (float)1);
+ confStateDrifts.addLinearFunction(&functionConfidenceDriftDeviation4);
+ LinearFunction functionConfidenceDriftDeviation5;
+ functionConfidenceDriftDeviation5.setDomain(true, outerBoundDrift, false);
+ functionConfidenceDriftDeviation5.setKandD((float)0, (float)1);
+ confStateDrifts.addLinearFunction(&functionConfidenceDriftDeviation5);
+#ifdef PRINT
+ confStateDrifts.printFunctionBlock("confidence:confStateDrifts");
+#endif // PRINT
+
+ LinearFunctionBlock confBroken("confidence:broken");
+ LinearFunction functionConfidenceBroken1;
+ functionConfidenceBroken1.setDomain(false, true, (float)0);
+ functionConfidenceBroken1.setKandD((float)0, (float)0);
+ confBroken.addLinearFunction(&functionConfidenceBroken1);
+ LinearFunction functionConfidenceBroken2;
+ functionConfidenceBroken2.setDomain(true, (float)0, true,
+ (float)boundBrokenTime);
+ functionConfidenceBroken2.setKandD((float)0, (float)0, (float)boundBrokenTime,
+ (float)1);
+ confBroken.addLinearFunction(&functionConfidenceBroken2);
+ LinearFunction functionConfidenceBroken3;
+ functionConfidenceBroken3.setDomain(true, (float)boundBrokenTime, false);
+ functionConfidenceBroken3.setKandD((float)0, (float)1);
+ confBroken.addLinearFunction(&functionConfidenceBroken3);
+#ifdef PRINT
+ confBroken.printFunctionBlock("confidence:broken");
+#endif // PRINT
+
+
+
+
+
+/********************************** Mount Functions
+ * **********************************/
+//TODO: make FuncBlockConfSim2StateDev etc. private and write a setFunction!
+
+ //aaaaaaaaaa
+ a_viabilityMonitor->set_stateHandler("CSVW:CAMoutput", destinationPath);
+
+ a_viabilityMonitor->get_stateHandler()->FuncBlockConfSim2StateDev =
+ &confSim2StateDev;
+ a_viabilityMonitor->get_stateHandler()->FuncBlockConfDif2StateDev =
+ &confDif2StateDev;
+ a_viabilityMonitor->get_stateHandler()->FuncBlockConfSim2StateTime =
+ &confSim2StateTime;
+ a_viabilityMonitor->get_stateHandler()->FuncBlockConfDif2StateTime =
+ &confDif2StateTime;
+
+ a_viabilityMonitor->get_stateHandler()->FuncBlockConfValStateDev =
+ &confValidStateDev;
+ a_viabilityMonitor->get_stateHandler()->FuncBlockConfInvStateDev =
+ &confInvalidStateDev;
+ a_viabilityMonitor->get_stateHandler()->FuncBlockConfValStateTime =
+ &confValidStateTime;
+ a_viabilityMonitor->get_stateHandler()->FuncBlockConfInvStateTime =
+ &confInvalidStateTime;
+
+ // HIIIIIIIIIIIIIIERRRRRRRRRRRR SCH种种种种种种种种种諲ER MACHEN
+ a_viabilityMonitor->get_stateHandler()->DriftDeviation = &confStateDrifts;
+ a_viabilityMonitor->get_stateHandler()->FuncBlockConfBrokenSamples =
+ &confBroken;
+
+ a_viabilityMonitor->get_stateHandler()->setMaxStateHistoryLength(
+ boundTimeInSamples);
+
+ //a_viabilityMonitor->get_stateHandler()->setCSVwriter(destinationPath);
+
+ // New for Revision CAM
+ // a_viabilityMonitor.get_stateHandler()->FuncBlockConfBrokenSamplesChangeInOldState
+ // = &confBrokenChangeInOldState;
+
+ // create testbench
+ Testbench* tb = create_testbench("testbench");
+
+ // create CSV reader modules
+ unsigned int ROW = 2;
+ // inputs
+ CSVreaderModule* csvr_statorVoltage =
+ create_CSVreaderModule("CSVR:StatorVoltage", datasetPath, 3, ROW);
+ CSVreaderModule* csvr_inputFrequency =
+ create_CSVreaderModule("CSVR:InputFrequency", datasetPath, 6, ROW);
+ CSVreaderModule* csvr_mechanicalTorque =
+ create_CSVreaderModule("CSVR:mTorque", datasetPath, 7, ROW);
+ // outputs
+ CSVreaderModule* csvr_statorCurrent =
+ create_CSVreaderModule("CSVR:StatorCurrent", datasetPath, 8, ROW);
+ CSVreaderModule* csvr_electromagneticTorque =
+ create_CSVreaderModule("CSVR:eTorque", datasetPath, 11, ROW);
+ CSVreaderModule* csvr_speed =
+ create_CSVreaderModule("CSVR:Speed", datasetPath, 12, ROW);
+
+ // register agents
+ // low level agents - inputs
+ register_agentInTestbench(tb, a_statorVoltage);
+ register_agentInTestbench(tb, a_inputFrequency);
+ register_agentInTestbench(tb, a_mechanicalTorque);
+ // low level agents - outputs
+ register_agentInTestbench(tb, a_statorCurrent);
+ register_agentInTestbench(tb, a_electromagneticTorque);
+ register_agentInTestbench(tb, a_speed);
+ // high level agent
+ register_agentInTestbench(tb, a_viabilityMonitor);
+
+ // register sensors with their csv-readers
+ // inputs
+ register_sensorInTestbench(tb, s_statorVoltage, csvr_statorVoltage);
+ register_sensorInTestbench(tb, s_inputFrequency, csvr_inputFrequency);
+ register_sensorInTestbench(tb, s_mechanicalTorque, csvr_mechanicalTorque);
+ // outputs
+ register_sensorInTestbench(tb, s_statorCurrent, csvr_statorCurrent);
+ register_sensorInTestbench(tb, s_electromagneticTorque,
+ csvr_electromagneticTorque);
+ register_sensorInTestbench(tb, s_speed, csvr_speed);
+
+ // register sensor channels
+ // sensor-agent channels
+ // inputs
+ register_channelInTestbench(tb, c_sa_statorVoltage);
+ register_channelInTestbench(tb, c_sa_inputFrequency);
+ register_channelInTestbench(tb, c_sa_mechanicalTorque);
+ // outputs
+ register_channelInTestbench(tb, c_sa_statorCurrent);
+ register_channelInTestbench(tb, c_sa_electromagneticTorque);
+ register_channelInTestbench(tb, c_sa_speed);
+
+ // agent-agent channels
+ // inputs
+ register_channelInTestbench(tb, c_aa_statorVoltage);
+ register_channelInTestbench(tb, c_aa_inputFrequency);
+ register_channelInTestbench(tb, c_aa_mechanicalTorque);
+ // ouputs
+ register_channelInTestbench(tb, c_aa_statorCurrent);
+ register_channelInTestbench(tb, c_aa_speed);
+ register_channelInTestbench(tb, c_aa_electromagneticTorque);
+
+#ifdef STOP_BEFORE_SIMULATING
+ getchar();
+#endif
+
+
+ tb->simulate(datasetLength);
+
+}
diff --git a/Version_Max_07_05_2018_CMake/src/configCAMforNewMotor.h b/Version_Max_07_05_2018_CMake/src/configCAMforNewMotor.h
new file mode 100644
index 0000000..7902c5d
--- /dev/null
+++ b/Version_Max_07_05_2018_CMake/src/configCAMforNewMotor.h
@@ -0,0 +1,10 @@
+#ifndef HEADER_NEWMOTOR_CONFIG
+#define HEADER_NEWMOTOR_CONFIG
+
+void configAndStartNewMotorExperiment(
+ char *destinationPath, char *datasetPath, char *datasetName,
+ unsigned int datasetLength, float innerBoundSimDif, float outerBoundSimDif,
+ int boundTimeInSamples, float innerBoundDrift, float outerBoundDrift,
+ int boundBrokenTime, int downSamplingFactor);
+
+#endif
\ No newline at end of file
diff --git a/Version_Max_07_05_2018_CMake/src/create_unit.cpp b/Version_Max_07_05_2018_CMake/src/create_unit.cpp
index be16f5f..448176c 100755
--- a/Version_Max_07_05_2018_CMake/src/create_unit.cpp
+++ b/Version_Max_07_05_2018_CMake/src/create_unit.cpp
@@ -1,416 +1,419 @@
#include "create_unit.h"
-#include <stdio.h>
#include "errno.h"
#include "rlutil.h"
+#include <stdio.h>
using namespace rlutil;
#define PRINT
-void print_agent(Agent agent) {
-
-}
+void print_agent(Agent agent) {}
-Agent* create_agent() {
- return create_agent(NO_NAME);
-}
+Agent *create_agent() { return create_agent(NO_NAME); }
-Agent* create_agent(char* name) {
- Agent* agent = new Agent(name);
-#ifdef PRINT
- printf(" > Agent ");
- setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", agent->get_name());
- setColor(TXTCOLOR_GREY);
- printf("(id: %03u) ", agent->get_id());
- setColor(TXTCOLOR_LIGHTGREEN);
- printf("created\n");
- setColor(TXTCOLOR_GREY);
+Agent *create_agent(std::string name) {
+ Agent *agent = new Agent(name);
+#ifdef PRINT
+ printf(" > Agent ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", agent->get_name().c_str());
+ setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", agent->get_id());
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("created\n");
+ setColor(TXTCOLOR_GREY);
#endif // PRINT
- return agent;
+ return agent;
}
+Sensor *create_sensor() { return create_sensor(NO_NAME); }
-Sensor* create_sensor() {
- return create_sensor(NO_NAME);
-}
-
-Sensor* create_sensor(char* name) {
- Sensor* sensor = new Sensor(name);
-#ifdef PRINT
- printf(" > Sensor ");
- setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", sensor->get_name());
- setColor(TXTCOLOR_GREY);
- printf("(id: %03u) ", sensor->get_id());
- setColor(TXTCOLOR_LIGHTGREEN);
- printf("created\n");
- setColor(TXTCOLOR_GREY);
+Sensor *create_sensor(std::string name) {
+ Sensor *sensor = new Sensor(name);
+#ifdef PRINT
+ printf(" > Sensor ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", sensor->get_name().c_str());
+ setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", sensor->get_id());
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("created\n");
+ setColor(TXTCOLOR_GREY);
#endif // PRINT
- return sensor;
+ return sensor;
}
-
-HistoryModule create_historyModule(unsigned int history_length, int delimitation_mode) {
- return create_historyModule(NO_NAME, history_length, delimitation_mode);
+HistoryModule create_historyModule(unsigned int history_length,
+ int delimitation_mode) {
+ return create_historyModule(NO_NAME, history_length, delimitation_mode);
}
-HistoryModule create_historyModule(char* name, unsigned int history_length, int delimitation_mode) {
-
- HistoryModule historyModule(name);
-#ifdef PRINT
- printf(" > History ");
- setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", historyModule.get_name());
- setColor(TXTCOLOR_GREY);
- printf("(id: %03u) ", historyModule.get_id());
- setColor(TXTCOLOR_LIGHTGREEN);
- printf("created\n");
- setColor(TXTCOLOR_GREY);
+HistoryModule create_historyModule(std::string name,
+ unsigned int history_length,
+ int delimitation_mode) {
+
+ HistoryModule historyModule(name);
+#ifdef PRINT
+ printf(" > History ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", historyModule.get_name().c_str());
+ setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", historyModule.get_id());
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("created\n");
+ setColor(TXTCOLOR_GREY);
#endif // PRINT
- if(historyModule.set_maxHistoryLength(history_length)) {
+ if (historyModule.set_maxHistoryLength(history_length)) {
#ifdef PRINT
- printf(" > History length ");
- setColor(TXTCOLOR_LIGHTGREEN);
- printf("set ");
- setColor(TXTCOLOR_GREY);
- printf("to %u\n", history_length);
+ printf(" > History length ");
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("set ");
+ setColor(TXTCOLOR_GREY);
+ printf("to %u\n", history_length);
#endif // PRINT
- }
- else {
- setColor(TXTCOLOR_LIGHTRED);
- printf(" > historyLength could not set (out of allowed range).");
- setColor(TXTCOLOR_GREY);
- }
- if(historyModule.set_delimitationMode(delimitation_mode)) {
+ } else {
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > historyLength could not set (out of allowed range).");
+ setColor(TXTCOLOR_GREY);
+ }
+ if (historyModule.set_delimitationMode(delimitation_mode)) {
#ifdef PRINT
- printf(" > Delimitation Mode ");
- setColor(TXTCOLOR_LIGHTGREEN);
- printf("set ");
- setColor(TXTCOLOR_GREY);
- printf("to %u\n", delimitation_mode);
+ printf(" > Delimitation Mode ");
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("set ");
+ setColor(TXTCOLOR_GREY);
+ printf("to %u\n", delimitation_mode);
#endif // PRINT
- }
- else {
- setColor(TXTCOLOR_LIGHTRED);
- printf(" > Delimitation Mode could not set (out of allowed range).");
- setColor(TXTCOLOR_GREY);
- }
-
- return historyModule;
+ } else {
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Delimitation Mode could not set (out of allowed range).");
+ setColor(TXTCOLOR_GREY);
+ }
+
+ return historyModule;
}
-Channel* create_channel(unsigned int transfer_rate) {
- return create_channel(NO_NAME, transfer_rate);
+Channel *create_channel(unsigned int transfer_rate) {
+ return create_channel(NO_NAME, transfer_rate);
}
-Channel* create_channel(char* name, unsigned int transfer_rate) {
+Channel *create_channel(std::string name, unsigned int transfer_rate) {
- Channel* channel = new Channel(name);
+ Channel *channel = new Channel(name);
#ifdef PRINT
- printf(" > Channel ");
- setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", channel->get_name());
- setColor(TXTCOLOR_GREY);
- printf("(id: %03u) ", channel->get_id());
- setColor(TXTCOLOR_LIGHTGREEN);
- printf("created\n");
- setColor(TXTCOLOR_GREY);
+ printf(" > Channel ");
+ setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", channel->get_name().c_str());
+ setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", channel->get_id());
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("created\n");
+ setColor(TXTCOLOR_GREY);
#endif // PRINT
- if(channel->set_transferRate(transfer_rate)) {
- if(transfer_rate != 0) {
-#ifdef PRINT
- printf(" > transfer rate ");
- setColor(TXTCOLOR_LIGHTGREEN);
- printf("set ");
- setColor(TXTCOLOR_GREY);
- printf("to %i\n", transfer_rate);
+ if (channel->set_transferRate(transfer_rate)) {
+ if (transfer_rate != 0) {
+#ifdef PRINT
+ printf(" > transfer rate ");
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("set ");
+ setColor(TXTCOLOR_GREY);
+ printf("to %i\n", transfer_rate);
#endif // PRINT
- }
- else {
-#ifdef PRINT
- printf(" > transfer ");
- setColor(TXTCOLOR_LIGHTGREEN);
- printf("set ");
- setColor(TXTCOLOR_GREY);
- printf("to immediately transportation\n");
+ } else {
+#ifdef PRINT
+ printf(" > transfer ");
+ setColor(TXTCOLOR_LIGHTGREEN);
+ printf("set ");
+ setColor(TXTCOLOR_GREY);
+ printf("to immediately transportation\n");
#endif // PRINT
- }
- }
- else {
-#ifdef PRINT
- setColor(TXTCOLOR_LIGHTRED);
- printf(" > Transfer Rate out of allowed bounds!\n");
- setColor(TXTCOLOR_GREY);
+ }
+ } else {
+#ifdef PRINT
+ setColor(TXTCOLOR_LIGHTRED);
+ printf(" > Transfer Rate out of allowed bounds!\n");
+ setColor(TXTCOLOR_GREY);
#endif // PRINT
- }
+ }
- return channel;
+ return channel;
}
+Testbench *create_testbench() { return create_testbench(NO_NAME); }
-
-
-Testbench* create_testbench() {
- return create_testbench(NO_NAME);
-}
-
-Testbench* create_testbench(char* name) {
- Testbench* testbench = new Testbench(name);
+Testbench *create_testbench(std::string name) {
+ Testbench *testbench = new Testbench(name);
#ifdef PRINT
- printf(" > ");
- rlutil::setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", testbench->get_name());
- rlutil::setColor(TXTCOLOR_GREY);
- printf("(id: %03u) ", testbench->get_id());
- rlutil::setColor(TXTCOLOR_LIGHTGREEN);
- printf("created\n");
- rlutil::setColor(TXTCOLOR_GREY);
+ printf(" > ");
+ rlutil::setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", testbench->get_name().c_str());
+ rlutil::setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", testbench->get_id());
+ rlutil::setColor(TXTCOLOR_LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(TXTCOLOR_GREY);
#endif // PRINT
- testbench->init_testbench();
- return testbench;
+ testbench->init_testbench();
+ return testbench;
}
/*
Lookuptable create_lookuptable() {
- Lookuptable lut;
-
- printf(" > ");
- rlutil::setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", lut.get_name());
- rlutil::setColor(TXTCOLOR_GREY);
- printf("(id: %03u) ", lut.get_id());
- rlutil::setColor(TXTCOLOR_LIGHTGREEN);
- printf("created\n");
- rlutil::setColor(TXTCOLOR_GREY);
-
- return lut;
+ Lookuptable lut;
+
+ printf(" > ");
+ rlutil::setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", lut.get_name());
+ rlutil::setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", lut.get_id());
+ rlutil::setColor(TXTCOLOR_LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(TXTCOLOR_GREY);
+
+ return lut;
}
Lookuptable create_lookuptable(char* name) {
- Lookuptable lut(name);
-
- printf(" > ");
- rlutil::setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", lut.get_name());
- rlutil::setColor(TXTCOLOR_GREY);
- printf("(id: %03u) ", lut.get_id());
- rlutil::setColor(TXTCOLOR_LIGHTGREEN);
- printf("created\n");
- rlutil::setColor(TXTCOLOR_GREY);
-
- return lut;
+ Lookuptable lut(name);
+
+ printf(" > ");
+ rlutil::setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", lut.get_name());
+ rlutil::setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", lut.get_id());
+ rlutil::setColor(TXTCOLOR_LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(TXTCOLOR_GREY);
+
+ return lut;
}
void print_confidence_validator(Confidence_Validator conf_valid) {
- printf(" > ");
- rlutil::setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", conf_valid.get_name());
- rlutil::setColor(TXTCOLOR_GREY);
- printf("(id: %03u) ", conf_valid.get_id());
- rlutil::setColor(TXTCOLOR_LIGHTGREEN);
- printf("created\n");
- rlutil::setColor(TXTCOLOR_GREY);
-
- printf(" - range of validity ");
- if(conf_valid.get_flag_lower_bound_exist())
- printf("[ %.3f, ", conf_valid.get_lower_bound());
- else
- printf("] -inf, ");
- if(conf_valid.get_flag_upper_bound_exist())
- printf("%.3f ] ", conf_valid.get_upper_bound());
- else
- printf("+inf [ ");
- rlutil::setColor(TXTCOLOR_LIGHTGREEN);
- printf("set\n");
- rlutil::setColor(TXTCOLOR_GREY);
-
- if(conf_valid.get_flag_rates_of_change_exist()) {
- printf(" - validity for rates of change of ");
- printf("%.3f ", conf_valid.get_rates_of_change());
- rlutil::setColor(TXTCOLOR_LIGHTGREEN);
- printf("set\n");
- rlutil::setColor(TXTCOLOR_GREY);
- }
+ printf(" > ");
+ rlutil::setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", conf_valid.get_name());
+ rlutil::setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", conf_valid.get_id());
+ rlutil::setColor(TXTCOLOR_LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(TXTCOLOR_GREY);
+
+ printf(" - range of validity ");
+ if(conf_valid.get_flag_lower_bound_exist())
+ printf("[ %.3f, ", conf_valid.get_lower_bound());
+ else
+ printf("] -inf, ");
+ if(conf_valid.get_flag_upper_bound_exist())
+ printf("%.3f ] ", conf_valid.get_upper_bound());
+ else
+ printf("+inf [ ");
+ rlutil::setColor(TXTCOLOR_LIGHTGREEN);
+ printf("set\n");
+ rlutil::setColor(TXTCOLOR_GREY);
+
+ if(conf_valid.get_flag_rates_of_change_exist()) {
+ printf(" - validity for rates of change of ");
+ printf("%.3f ", conf_valid.get_rates_of_change());
+ rlutil::setColor(TXTCOLOR_LIGHTGREEN);
+ printf("set\n");
+ rlutil::setColor(TXTCOLOR_GREY);
+ }
}
-Confidence_Validator create_confidence_validator(float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist) {
- Confidence_Validator conf_valid(lower_bound, flag_lower_bound_exist, upper_bound, flag_upper_bound_exist, rates_of_change, flag_rates_of_change_exist);
- print_confidence_validator(conf_valid);
+Confidence_Validator create_confidence_validator(float lower_bound, bool
+flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float
+rates_of_change, bool flag_rates_of_change_exist) { Confidence_Validator
+conf_valid(lower_bound, flag_lower_bound_exist, upper_bound,
+flag_upper_bound_exist, rates_of_change, flag_rates_of_change_exist);
+ print_confidence_validator(conf_valid);
- return conf_valid;
+ return conf_valid;
}
-Confidence_Validator create_confidence_validator(char* name, float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist) {
- Confidence_Validator conf_valid(name, lower_bound, flag_lower_bound_exist, upper_bound, flag_upper_bound_exist, rates_of_change, flag_rates_of_change_exist);
- print_confidence_validator(conf_valid);
+Confidence_Validator create_confidence_validator(char* name, float lower_bound,
+bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist,
+float rates_of_change, bool flag_rates_of_change_exist) { Confidence_Validator
+conf_valid(name, lower_bound, flag_lower_bound_exist, upper_bound,
+flag_upper_bound_exist, rates_of_change, flag_rates_of_change_exist);
+ print_confidence_validator(conf_valid);
- return conf_valid;
+ return conf_valid;
}
void print_abstraction_module(Abstraction abstraction) {
- printf(" > ");
- rlutil::setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", abstraction.get_name());
- rlutil::setColor(TXTCOLOR_GREY);
- printf("(id: %03u) ", abstraction.get_id());
- rlutil::setColor(TXTCOLOR_LIGHTGREEN);
- printf("created\n");
- rlutil::setColor(TXTCOLOR_GREY);
-
- //TODO: abstraction method printen
- printf(" - abstraction method %u ", abstraction.get_abstraction_method());
- rlutil::setColor(TXTCOLOR_LIGHTGREEN);
- printf("set\n");
- rlutil::setColor(TXTCOLOR_GREY);
-
- //TODO: auch das hier bissl sch�ner machen
- if(abstraction.get_flag_lookuptable_exist(0)) {
- printf(" - position 0 connected mit Look up Table ");
- rlutil::setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", abstraction.get_lookuptable(0)->get_name());
- rlutil::setColor(TXTCOLOR_GREY);
- printf("(id: %03u) ", abstraction.get_lookuptable(0)->get_id());
- rlutil::setColor(TXTCOLOR_LIGHTGREEN);
- printf("set\n");
- rlutil::setColor(TXTCOLOR_GREY);
- }
-}
-
-Abstraction create_abstraction_module(Lookuptable* lut, unsigned int abstraction_method) {
- Abstraction abstraction(lut, abstraction_method);
- print_abstraction_module(abstraction);
-
- return abstraction;
+ printf(" > ");
+ rlutil::setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", abstraction.get_name());
+ rlutil::setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", abstraction.get_id());
+ rlutil::setColor(TXTCOLOR_LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(TXTCOLOR_GREY);
+
+ //TODO: abstraction method printen
+ printf(" - abstraction method %u ",
+abstraction.get_abstraction_method()); rlutil::setColor(TXTCOLOR_LIGHTGREEN);
+ printf("set\n");
+ rlutil::setColor(TXTCOLOR_GREY);
+
+ //TODO: auch das hier bissl sch�ner machen
+ if(abstraction.get_flag_lookuptable_exist(0)) {
+ printf(" - position 0 connected mit Look up Table ");
+ rlutil::setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", abstraction.get_lookuptable(0)->get_name());
+ rlutil::setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", abstraction.get_lookuptable(0)->get_id());
+ rlutil::setColor(TXTCOLOR_LIGHTGREEN);
+ printf("set\n");
+ rlutil::setColor(TXTCOLOR_GREY);
+ }
+}
+
+Abstraction create_abstraction_module(Lookuptable* lut, unsigned int
+abstraction_method) { Abstraction abstraction(lut, abstraction_method);
+ print_abstraction_module(abstraction);
+
+ return abstraction;
}
-Abstraction create_abstraction_module(char* name, Lookuptable* lut, unsigned int abstraction_method) {
- Abstraction abstraction(name, lut, abstraction_method);
- print_abstraction_module(abstraction);
+Abstraction create_abstraction_module(char* name, Lookuptable* lut, unsigned int
+abstraction_method) { Abstraction abstraction(name, lut, abstraction_method);
+ print_abstraction_module(abstraction);
- return abstraction;
+ return abstraction;
}
void print_bunch_module(Bunch_Module bunch_module) {
- printf(" > ");
- rlutil::setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", bunch_module.get_name());
- rlutil::setColor(TXTCOLOR_GREY);
- printf("(id: %03u) ", bunch_module.get_id());
- rlutil::setColor(TXTCOLOR_LIGHTGREEN);
- printf("created\n");
- rlutil::setColor(TXTCOLOR_GREY);
-
- //TODO: abstraction method printen
- printf(" - abstraction method %u ", bunch_module.get_bunch_method());
- rlutil::setColor(TXTCOLOR_LIGHTGREEN);
- printf("set\n");
- rlutil::setColor(TXTCOLOR_GREY);
-}
+ printf(" > ");
+ rlutil::setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", bunch_module.get_name());
+ rlutil::setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) ", bunch_module.get_id());
+ rlutil::setColor(TXTCOLOR_LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(TXTCOLOR_GREY);
+
+ //TODO: abstraction method printen
+ printf(" - abstraction method %u ", bunch_module.get_bunch_method());
+ rlutil::setColor(TXTCOLOR_LIGHTGREEN);
+ printf("set\n");
+ rlutil::setColor(TXTCOLOR_GREY);
+}
Bunch_Module create_bunch_module(unsigned int bunch_method) {
- Bunch_Module bunch_module(bunch_method);
- print_bunch_module(bunch_module);
+ Bunch_Module bunch_module(bunch_method);
+ print_bunch_module(bunch_module);
- return bunch_module;
+ return bunch_module;
}
Bunch_Module create_bunch_module(char* name, unsigned int bunch_method) {
- Bunch_Module bunch_module(name, bunch_method);
- print_bunch_module(bunch_module);
+ Bunch_Module bunch_module(name, bunch_method);
+ print_bunch_module(bunch_module);
- return bunch_module;
+ return bunch_module;
}
*/
-FILE* make_file_pointer(const char* filepath, int mode) {
-
- FILE* fpointer = nullptr;
-
- if(mode == CSV_MODE_READ) {
- // file_opened = fopen_s(&fpointer, filepath, "r"); //only windows compatible
- fpointer = fopen(filepath, "r");
- }
- else if(mode == CSV_MODE_WRITE) {
- // file_opened = fopen_s(&fpointer, filepath, "w"); //only windows compatible
- fpointer = fopen(filepath, "w");
- }
- else {
+FILE *make_file_pointer(const char *filepath, int mode) {
+
+ bool file_opened;
+ FILE *fpointer = nullptr;
+
+ if (mode == CSV_MODE_READ) {
+#ifdef _WIN32
+ file_opened = fopen_s(&fpointer, filepath, "r"); // only windows compatible
+#else
+ fpointer = fopen(filepath, "r");
+#endif
+ } else if (mode == CSV_MODE_WRITE) {
+#ifdef _WIN32
+ file_opened = fopen_s(&fpointer, filepath, "w"); // only windows compatible
+#else
+ fpointer = fopen(filepath, "w");
+#endif
+ } else {
#ifdef PRINT
- printf("File pointer mode for \"%s\" ", filepath);
- rlutil::setColor(TXTCOLOR_LIGHTRED);
- printf("is not supported!\n");
- rlutil::setColor(TXTCOLOR_GREY);
+ printf("File pointer mode for \"%s\" ", filepath);
+ rlutil::setColor(TXTCOLOR_LIGHTRED);
+ printf("is not supported!\n");
+ rlutil::setColor(TXTCOLOR_GREY);
#endif // PRINT
- return NULL;
- }
+ return NULL;
+ }
- //if(file_opened == 0) {
- if(fpointer != nullptr) {
- return fpointer;
- }
+ // if(file_opened == 0) {
+ if (fpointer != nullptr && file_opened == 0) {
+ return fpointer;
+ }
#ifdef PRINT
- printf("File pointer \"%s\" ", filepath);
- rlutil::setColor(TXTCOLOR_LIGHTRED);
- printf("could not created!\n");
- rlutil::setColor(TXTCOLOR_GREY);
+ printf("File pointer \"%s\" ", filepath);
+ rlutil::setColor(TXTCOLOR_LIGHTRED);
+ printf("could not created!\n");
+ rlutil::setColor(TXTCOLOR_GREY);
#endif // PRINT
- return NULL;
+ return NULL;
}
-void print_csv_reader(CSVreaderModule* csvReaderModule,const char* filepath) {
- printf(" > ");
- rlutil::setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", csvReaderModule->get_name());
- rlutil::setColor(TXTCOLOR_GREY);
- printf("(id: %03u) for \"%s\" ", csvReaderModule->get_id(), filepath);
- rlutil::setColor(TXTCOLOR_LIGHTGREEN);
- printf("created\n");
- rlutil::setColor(TXTCOLOR_GREY);
-}
-
-CSVreaderModule* create_CSVreaderModule(const char* filepath, unsigned int column, unsigned int start_row) {
-
- FILE* fpointer = make_file_pointer(filepath, CSV_MODE_READ);
-
- if(fpointer) {
- CSVreaderModule* csvr = new CSVreaderModule(fpointer, column, start_row);
- print_csv_reader(csvr, filepath);
-
- return csvr;
- }
- else {
- CSVreaderModule* csvr = new CSVreaderModule();
-
- return csvr;
- }
+void print_csv_reader(CSVreaderModule *csvReaderModule, const char *filepath) {
+ printf(" > ");
+ rlutil::setColor(TXTCOLOR_LIGHTCYAN);
+ printf("%s ", csvReaderModule->get_name().c_str());
+ rlutil::setColor(TXTCOLOR_GREY);
+ printf("(id: %03u) for \"%s\" ", csvReaderModule->get_id(), filepath);
+ rlutil::setColor(TXTCOLOR_LIGHTGREEN);
+ printf("created\n");
+ rlutil::setColor(TXTCOLOR_GREY);
}
-CSVreaderModule* create_CSVreaderModule(char* name,const char* filepath, unsigned int column, unsigned int start_row) {
-
- FILE* fpointer = make_file_pointer(filepath, CSV_MODE_READ);
+CSVreaderModule *create_CSVreaderModule(const char *filepath,
+ unsigned int column,
+ unsigned int start_row) {
- if(fpointer) {
- CSVreaderModule* csvr = new CSVreaderModule(name, fpointer, column, start_row);
-#ifdef PRINT
- print_csv_reader(csvr, filepath);
-#endif // PRINT
- return csvr;
- }
- else {
- CSVreaderModule* csvr = new CSVreaderModule;
+ FILE *fpointer = make_file_pointer(filepath, CSV_MODE_READ);
- return csvr;
- }
+ if (fpointer) {
+ CSVreaderModule *csvr = new CSVreaderModule(fpointer, column, start_row);
+ print_csv_reader(csvr, filepath);
+
+ return csvr;
+ } else {
+ CSVreaderModule *csvr = new CSVreaderModule();
+
+ return csvr;
+ }
}
+CSVreaderModule *create_CSVreaderModule(std::string name, const char *filepath,
+ unsigned int column,
+ unsigned int start_row) {
+
+ FILE *fpointer = make_file_pointer(filepath, CSV_MODE_READ);
+
+ if (fpointer == NULL) {
+ printf("DA IS DER HUND\n");
+ } else {
+ printf("ALLES GUT\n");
+ }
-StateHandler create_stateHandler() {
- return create_stateHandler(NO_NAME);
+ if (fpointer) {
+ CSVreaderModule *csvr =
+ new CSVreaderModule(name, fpointer, column, start_row);
+#ifdef PRINT
+ print_csv_reader(csvr, filepath);
+#endif // PRINT
+ return csvr;
+ } else {
+ CSVreaderModule *csvr = new CSVreaderModule;
+
+ return csvr;
+ }
}
-StateHandler create_stateHandler(char* name) {
- StateHandler stateHandler(name);
- return stateHandler;
+StateHandler create_stateHandler() { return create_stateHandler(NO_NAME); }
+
+StateHandler create_stateHandler(std::string name) {
+ StateHandler stateHandler(name);
+ return stateHandler;
}
diff --git a/Version_Max_07_05_2018_CMake/src/create_unit.h b/Version_Max_07_05_2018_CMake/src/create_unit.h
index c9934e8..daeeadb 100755
--- a/Version_Max_07_05_2018_CMake/src/create_unit.h
+++ b/Version_Max_07_05_2018_CMake/src/create_unit.h
@@ -1,62 +1,64 @@
#ifndef CREATE_UNIT_HEADERFILE
#define CREATE_UNIT_HEADERFILE
#include <memory>
#include "Agent.h"
#include "CSVreaderModule.h"
#include "HistoryModule.h"
#include "Sensor.h"
#include "Testbench.h"
+#include <string>
+
/*
#include "Testbench.h"
#include "Lookuptable.h"
#include "ConfidenceModule.h"
#include "Bunch_Module.h"
*/
#define CSV_MODE_READ 0
#define CSV_MODE_WRITE 1
Agent* create_agent();
-Agent* create_agent(char* name);
+Agent* create_agent(std::string name);
/*
Agent create_agent(unsigned int abstraction_method);
Agent create_agent(char* name, unsigned int abstraction_method);
*/
Sensor* create_sensor();
-Sensor* create_sensor(char* name);
+Sensor* create_sensor(std::string name);
HistoryModule create_historyModule(unsigned int history_length, int delimitation_mode);
-HistoryModule create_historyModule(char* name, unsigned int history_length, int delimitation_mode);
+HistoryModule create_historyModule(std::string name, unsigned int history_length, int delimitation_mode);
Channel* create_channel(unsigned int transfer_rate);
-Channel* create_channel(char* name, unsigned int transfer_rate);
+Channel* create_channel(std::string, unsigned int transfer_rate);
Testbench* create_testbench();
-Testbench* create_testbench(char* name);
+Testbench* create_testbench(std::string name);
/*
Lookuptable create_lookuptable();
Lookuptable create_lookuptable(char* name);
ConfidenceModule create_confidence_validator(float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist);
ConfidenceModule create_confidence_validator(char* name, float lower_bound, bool flag_lower_bound_exist, float upper_bound, bool flag_upper_bound_exist, float rates_of_change, bool flag_rates_of_change_exist);
AbstractionModule create_abstraction_module(Lookuptable* lut, unsigned int abstraction_method);
AbstractionModule create_abstraction_module(char* name, Lookuptable* lut, unsigned int abstraction_method);
Bunch_Module create_bunch_module(unsigned int bunch_method);
Bunch_Module create_bunch_module(char* name, unsigned int bunch_method);
*/
CSVreaderModule* create_CSVreaderModule(const char* filepath, unsigned int column, unsigned int start_row);
-CSVreaderModule* create_CSVreaderModule(char* name,const char* filepath, unsigned int column, unsigned int start_row);
+CSVreaderModule* create_CSVreaderModule(std::string name,const char* filepath, unsigned int column, unsigned int start_row);
StateHandler create_stateHandler();
-StateHandler create_stateHandler(char* name);
+StateHandler create_stateHandler(std::string name);
#endif
diff --git a/Version_Max_07_05_2018_CMake/src/csvparser.c b/Version_Max_07_05_2018_CMake/src/csvparser.c
deleted file mode 100755
index 4be5c91..0000000
--- a/Version_Max_07_05_2018_CMake/src/csvparser.c
+++ /dev/null
@@ -1,239 +0,0 @@
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <errno.h>
-
-#include "csvparser.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-CsvParser *CsvParser_new(const char *filePath, const char *delimiter, int firstLineIsHeader) {
- CsvParser *csvParser = (CsvParser*)malloc(sizeof(CsvParser));
- if (filePath == NULL) {
- csvParser->filePath_ = NULL;
- } else {
- int filePathLen = strlen(filePath);
- csvParser->filePath_ = (char*)malloc((filePathLen + 1));
- strcpy(csvParser->filePath_, filePath);
- }
- csvParser->firstLineIsHeader_ = firstLineIsHeader;
- csvParser->errMsg_ = NULL;
- if (delimiter == NULL) {
- csvParser->delimiter_ = ',';
- } else if (_CsvParser_delimiterIsAccepted(delimiter)) {
- csvParser->delimiter_ = *delimiter;
- } else {
- csvParser->delimiter_ = '\0';
- }
- csvParser->header_ = NULL;
- csvParser->fileHandler_ = NULL;
- csvParser->fromString_ = 0;
- csvParser->csvString_ = NULL;
- csvParser->csvStringIter_ = 0;
-
- return csvParser;
-}
-
-CsvParser *CsvParser_new_from_string(const char *csvString, const char *delimiter, int firstLineIsHeader) {
- CsvParser *csvParser = CsvParser_new(NULL, delimiter, firstLineIsHeader);
- csvParser->fromString_ = 1;
- if (csvString != NULL) {
- int csvStringLen = strlen(csvString);
- csvParser->csvString_ = (char*)malloc(csvStringLen + 1);
- strcpy(csvParser->csvString_, csvString);
- }
- return csvParser;
-}
-
-void CsvParser_destroy(CsvParser *csvParser) {
- if (csvParser == NULL) {
- return;
- }
- if (csvParser->filePath_ != NULL) {
- free(csvParser->filePath_);
- }
- if (csvParser->errMsg_ != NULL) {
- free(csvParser->errMsg_);
- }
- if (csvParser->fileHandler_ != NULL) {
- fclose(csvParser->fileHandler_);
- }
- if (csvParser->header_ != NULL) {
- CsvParser_destroy_row(csvParser->header_);
- }
- if (csvParser->csvString_ != NULL) {
- free(csvParser->csvString_);
- }
- free(csvParser);
-}
-
-void CsvParser_destroy_row(CsvRow *csvRow) {
- int i;
- for (i = 0 ; i < csvRow->numOfFields_ ; i++) {
- free(csvRow->fields_[i]);
- }
- free(csvRow->fields_);
- free(csvRow);
-}
-
-CsvRow *CsvParser_getHeader(CsvParser *csvParser) {
- if (! csvParser->firstLineIsHeader_) {
- _CsvParser_setErrorMessage(csvParser, "Cannot supply header, as current CsvParser object does not support header");
- return NULL;
- }
- if (csvParser->header_ == NULL) {
- csvParser->header_ = _CsvParser_getRow(csvParser);
- }
- return csvParser->header_;
-}
-
-CsvRow *CsvParser_getRow(CsvParser *csvParser) {
- if (csvParser->firstLineIsHeader_ && csvParser->header_ == NULL) {
- csvParser->header_ = _CsvParser_getRow(csvParser);
- }
- return _CsvParser_getRow(csvParser);
-}
-
-int CsvParser_getNumFields(CsvRow *csvRow) {
- return csvRow->numOfFields_;
-}
-
-const char **CsvParser_getFields(CsvRow *csvRow) {
- return (const char**)csvRow->fields_;
-}
-
-CsvRow *_CsvParser_getRow(CsvParser *csvParser) {
- int numRowRealloc = 0;
- int acceptedFields = 64;
- int acceptedCharsInField = 64;
- if (csvParser->filePath_ == NULL && (! csvParser->fromString_)) {
- _CsvParser_setErrorMessage(csvParser, "Supplied CSV file path is NULL");
- return NULL;
- }
- if (csvParser->csvString_ == NULL && csvParser->fromString_) {
- _CsvParser_setErrorMessage(csvParser, "Supplied CSV string is NULL");
- return NULL;
- }
- if (csvParser->delimiter_ == '\0') {
- _CsvParser_setErrorMessage(csvParser, "Supplied delimiter is not supported");
- return NULL;
- }
- if (! csvParser->fromString_) {
- if (csvParser->fileHandler_ == NULL) {
- csvParser->fileHandler_ = fopen(csvParser->filePath_, "r");
- if (csvParser->fileHandler_ == NULL) {
- int errorNum = errno;
- const char *errStr = strerror(errorNum);
- char *errMsg = (char*)malloc(1024 + strlen(errStr));
- strcpy(errMsg, "");
- sprintf(errMsg, "Error opening CSV file for reading: %s : %s", csvParser->filePath_, errStr);
- _CsvParser_setErrorMessage(csvParser, errMsg);
- free(errMsg);
- return NULL;
- }
- }
- }
- CsvRow *csvRow = (CsvRow*)malloc(sizeof(CsvRow));
- csvRow->fields_ = (char**)malloc(acceptedFields * sizeof(char*));
- csvRow->numOfFields_ = 0;
- int fieldIter = 0;
- char *currField = (char*)malloc(acceptedCharsInField);
- int inside_complex_field = 0;
- int currFieldCharIter = 0;
- int seriesOfQuotesLength = 0;
- int lastCharIsQuote = 0;
- int isEndOfFile = 0;
- while (1) {
- char currChar = (csvParser->fromString_) ? csvParser->csvString_[csvParser->csvStringIter_] : fgetc(csvParser->fileHandler_);
- csvParser->csvStringIter_++;
- int endOfFileIndicator;
- if (csvParser->fromString_) {
- endOfFileIndicator = (currChar == '\0');
- } else {
- endOfFileIndicator = feof(csvParser->fileHandler_);
- }
- if (endOfFileIndicator) {
- if (currFieldCharIter == 0 && fieldIter == 0) {
- _CsvParser_setErrorMessage(csvParser, "Reached EOF");
- free(currField);
- CsvParser_destroy_row(csvRow);
- return NULL;
- }
- currChar = '\n';
- isEndOfFile = 1;
- }
- if (currChar == '\r') {
- continue;
- }
- if (currFieldCharIter == 0 && ! lastCharIsQuote) {
- if (currChar == '\"') {
- inside_complex_field = 1;
- lastCharIsQuote = 1;
- continue;
- }
- } else if (currChar == '\"') {
- seriesOfQuotesLength++;
- inside_complex_field = (seriesOfQuotesLength % 2 == 0);
- if (inside_complex_field) {
- currFieldCharIter--;
- }
- } else {
- seriesOfQuotesLength = 0;
- }
- if (isEndOfFile || ((currChar == csvParser->delimiter_ || currChar == '\n') && ! inside_complex_field) ){
- currField[lastCharIsQuote ? currFieldCharIter - 1 : currFieldCharIter] = '\0';
- csvRow->fields_[fieldIter] = (char*)malloc(currFieldCharIter + 1);
- strcpy(csvRow->fields_[fieldIter], currField);
- free(currField);
- csvRow->numOfFields_++;
- if (currChar == '\n') {
- return csvRow;
- }
- if (csvRow->numOfFields_ != 0 && csvRow->numOfFields_ % acceptedFields == 0) {
- csvRow->fields_ = (char**)realloc(csvRow->fields_, ((numRowRealloc + 2) * acceptedFields) * sizeof(char*));
- numRowRealloc++;
- }
- acceptedCharsInField = 64;
- currField = (char*)malloc(acceptedCharsInField);
- currFieldCharIter = 0;
- fieldIter++;
- inside_complex_field = 0;
- } else {
- currField[currFieldCharIter] = currChar;
- currFieldCharIter++;
- if (currFieldCharIter == acceptedCharsInField - 1) {
- acceptedCharsInField *= 2;
- currField = (char*)realloc(currField, acceptedCharsInField);
- }
- }
- lastCharIsQuote = (currChar == '\"') ? 1 : 0;
- }
-}
-
-int _CsvParser_delimiterIsAccepted(const char *delimiter) {
- char actualDelimiter = *delimiter;
- if (actualDelimiter == '\n' || actualDelimiter == '\r' || actualDelimiter == '\0' ||
- actualDelimiter == '\"') {
- return 0;
- }
- return 1;
-}
-
-void _CsvParser_setErrorMessage(CsvParser *csvParser, const char *errorMessage) {
- if (csvParser->errMsg_ != NULL) {
- free(csvParser->errMsg_);
- }
- int errMsgLen = strlen(errorMessage);
- csvParser->errMsg_ = (char*)malloc(errMsgLen + 1);
- strcpy(csvParser->errMsg_, errorMessage);
-}
-
-const char *CsvParser_getErrorMessage(CsvParser *csvParser) {
- return csvParser->errMsg_;
-}
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/Version_Max_07_05_2018_CMake/src/csvparser.h b/Version_Max_07_05_2018_CMake/src/csvparser.h
deleted file mode 100755
index 9d08966..0000000
--- a/Version_Max_07_05_2018_CMake/src/csvparser.h
+++ /dev/null
@@ -1,52 +0,0 @@
-#ifndef CSVPARSER_H
-#define CSVPARSER_H
-
-#include <stdio.h>
-
-#define _CRT_SECURE_NO_WARNINGS
-
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct CsvRow {
- char **fields_;
- int numOfFields_;
-} CsvRow;
-
-typedef struct CsvParser {
- char *filePath_;
- char delimiter_;
- int firstLineIsHeader_;
- char *errMsg_;
- CsvRow *header_;
- FILE *fileHandler_;
- int fromString_;
- char *csvString_;
- int csvStringIter_;
-} CsvParser;
-
-
-// Public
-CsvParser *CsvParser_new(const char *filePath, const char *delimiter, int firstLineIsHeader);
-CsvParser *CsvParser_new_from_string(const char *csvString, const char *delimiter, int firstLineIsHeader);
-void CsvParser_destroy(CsvParser *csvParser);
-void CsvParser_destroy_row(CsvRow *csvRow);
-CsvRow *CsvParser_getHeader(CsvParser *csvParser);
-CsvRow *CsvParser_getRow(CsvParser *csvParser);
-int CsvParser_getNumFields(CsvRow *csvRow);
-const char **CsvParser_getFields(CsvRow *csvRow);
-const char* CsvParser_getErrorMessage(CsvParser *csvParser);
-
-// Private
-CsvRow *_CsvParser_getRow(CsvParser *csvParser);
-int _CsvParser_delimiterIsAccepted(const char *delimiter);
-void _CsvParser_setErrorMessage(CsvParser *csvParser, const char *errorMessage);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/Version_Max_07_05_2018_CMake/src/inAgentsRegistrations.cpp b/Version_Max_07_05_2018_CMake/src/inAgentsRegistrations.cpp
index ccad09b..ab19d98 100755
--- a/Version_Max_07_05_2018_CMake/src/inAgentsRegistrations.cpp
+++ b/Version_Max_07_05_2018_CMake/src/inAgentsRegistrations.cpp
@@ -1,105 +1,105 @@
#include "inAgentsRegistrations.h"
#include "rlutil.h"
#define PRINT
using namespace rlutil;
bool registerSlaveAgentAsInputVariableInStateHandler(Agent* masteragent, Channel* channel) {
- if(masteragent != NULL, channel != NULL) {
+ if(masteragent != NULL || channel != NULL) {
SlaveAgentSlotOfAgent* slot = masteragent->get_slaveAgentHandlerOfAgent()->get_slaveAgentSlotAddress(channel);
if(slot != NULL) {
if(masteragent->get_stateHandler()->addInputVariable(slot)){
#ifdef PRINT
printf(" > Channel ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", channel->get_name());
+ printf("%s ", channel->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", channel->get_id());
setColor(TXTCOLOR_LIGHTGREEN);
printf("registered ");
setColor(TXTCOLOR_GREY);
printf("as ");
setColor(TXTCOLOR_LIGHTGREEN);
printf("Input Variable ");
setColor(TXTCOLOR_GREY);
printf("in stateHandler of ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", masteragent->get_name());
+ printf("%s ", masteragent->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", masteragent->get_id());
#endif // PRINT
return true;
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
- printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->get_name(), channel->get_id(), masteragent->get_name(), masteragent->get_id());
+ printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->get_name().c_str(), channel->get_id(), masteragent->get_name().c_str(), masteragent->get_id());
#endif // PRINT
}
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
- printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->get_name(), channel->get_id(), masteragent->get_name(), masteragent->get_id());
+ printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->get_name().c_str(), channel->get_id(), masteragent->get_name().c_str(), masteragent->get_id());
#endif // PRINT
}
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
printf(" > Agent or Channel is not valid\n");
#endif // PRINT
}
return false;
}
bool registerSlaveAgentAsOutputVariableInStateHandler(Agent* masteragent, Channel* channel) {
- if (masteragent != NULL, channel != NULL) {
+ if (masteragent != NULL || channel != NULL) {
SlaveAgentSlotOfAgent* slot = masteragent->get_slaveAgentHandlerOfAgent()->get_slaveAgentSlotAddress(channel);
if (slot != NULL) {
if (masteragent->get_stateHandler()->addOutputVariable(slot)) {
#ifdef PRINT
printf(" > Channel ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", channel->get_name());
+ printf("%s ", channel->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", channel->get_id());
setColor(TXTCOLOR_LIGHTGREEN);
printf("registered ");
setColor(TXTCOLOR_GREY);
printf("as ");
setColor(TXTCOLOR_LIGHTGREEN);
printf("Output Variable ");
setColor(TXTCOLOR_GREY);
printf("in stateHandler of ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", masteragent->get_name());
+ printf("%s ", masteragent->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", masteragent->get_id());
#endif // PRINT
return true;
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
- printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->get_name(), channel->get_id(), masteragent->get_name(), masteragent->get_id());
+ printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->get_name().c_str(), channel->get_id(), masteragent->get_name().c_str(), masteragent->get_id());
#endif // PRINT
}
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
- printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->get_name(), channel->get_id(), masteragent->get_name(), masteragent->get_id());
+ printf(" > Channel %s (id: %03u) is not connected to Agent %s (id: %03u)\n", channel->get_name().c_str(), channel->get_id(), masteragent->get_name().c_str(), masteragent->get_id());
#endif // PRINT
}
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
printf(" > Agent or Channel is not valid\n");
#endif // PRINT
}
return false;
}
\ No newline at end of file
diff --git a/Version_Max_07_05_2018_CMake/src/main.cpp b/Version_Max_07_05_2018_CMake/src/main.cpp
index f3045be..704c00a 100755
--- a/Version_Max_07_05_2018_CMake/src/main.cpp
+++ b/Version_Max_07_05_2018_CMake/src/main.cpp
@@ -1,1128 +1,112 @@
-/*
- * main.cpp
- *
- * Created on: 25.05.2018
- * Author: edwin willegger, edwin.willegger@tuwien.ac.at
- * This file is used to generate output data from measurements
- * from OMV for SAVE project.
- * In this case the data of the 18.12.2017 is analyzed.
- * Based on the implementation of Maximilian Götzinger.
- */
-
-#include "Agent.h"
-#include "Channel.h"
-#include "create_unit.h"
-#include "CSVreaderModule.h"
-#include "inAgentsRegistrations.h"
-#include "mount_nodes.h"
-#include "register_in_testbench.h"
-#include "Sensor.h"
-#include "setupNode.h"
#include <stdio.h>
-#include <iostream>
-#include <vector>
-#include <string>
-#include <cstring>
-#include "Testbench.h"
-#include "file_util.h"
-
-#include "LinearFunction.h"
-#include "LinearFunctionBlock.h"
-
-#include "Testbench_Config.h"
-
-using namespace std;
-
-/**********************************************************************************************************************
- ************************************************begin of global definitions of variables and constants ***************
- **********************************************************************************************************************/
-
-//every n-th SAMBLING value will be read in from the CSV-Data-Input-Files.
-#define SAMPLING 1
-
-//global vectors for the different elements
-static vector<Agent*> vec_of_Agents;
-static vector<Sensor*> vec_of_Sensors;
-static vector<Channel*> vec_of_Channels_for_Sensors;
-static vector<Channel*> vec_of_Channels_for_Agents;
-static vector<LinearFunctionBlock*> vec_of_linear_Function_Blocks;
-static vector<Testbench*> vec_of_test_benches;
-static vector<CSVreaderModule*> vec_of_csv_readers;
-
-//names of the measured data
-const string FIRST_MEASURED_DATA_NAME = "FC6504_Y"; //Input
-const string SECOND_MEASURED_DATA_NAME = "FC6504"; //Output
-const string THIRD_MEASURED_DATA_NAME = "FC6504_SP"; //Input
-const string FOURTH_MEASURED_DATA_NAME = "PI6584"; //Input
-
-
-//viability monitor
-const string VIABILITY_MONITOR = "ViabilityMonitor";
-//index number of output
-const int INDEX_OUTPUT = 1;
-
-//name for the channels of the sensors and agents
-const string APPENDIX_FOR_CHANNEL_SENSOR_NAME = "(SA)";
-const string FIRST_MEASURED_CHANNEL_SENSOR_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME;
-const string SECOND_MEASURED_CHANNEL_SENSOR_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME;
-const string THIRD_MEASURED_CHANNEL_SENSOR_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME;
-const string FOURTH_MEASURED_CHANNEL_SENSOR_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME;
-const string APPENDIX_FOR_CHANNEL_AGENT_NAME = "(AA-UP)";
-const string FIRST_MEASURED_CHANNEL_AGENT_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME;
-const string SECOND_MEASURED_CHANNEL_AGENT_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME;
-const string THIRD_MEASURED_CHANNEL_AGENT_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME;
-const string FOURTH_MEASURED_CHANNEL_AGENT_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME;
-
-#define TRANSFER_RATE_CHANNEL_SENSOR 0
-#define TRANSFER_RATE_CHANNEL_AGENT MAX_BUFFER_LENGTH
-
-
-//////////////////////////////////////////////
-/*
-//out of the outer_bound the function is 0 or 1 and within 1 or 0 depending on function or complementery.
- inner_bound_xxx = /----------=1----|------=1---------\ = inner_bound_xxxx
- outer_bound_xxx = / | \
- / | \
- 0=__________/ | \ = outer_bound_xxxx ______ = 0
---------------------------------------------------------------------------
-*/
-
-//parameters of boundary for similar function
-#define OUTTER_BOUND_SIM_DIF 0.20 //outer bound e. g. 0.14 = 14 percent; testested with 0.20, 0.14, 0.06,
-#define INNER_BOUND_SIM_DIF 0.01 //inner bound e. g. 0.01 = 1 percent
-
-//same way as above but shows drift.
-#define OUTTER_BOUND_DRIFT OUTTER_BOUND_SIM_DIF * 3
-#define INNER_BOUND_DRIFT OUTTER_BOUND_SIM_DIF
-
-//timer sagt, dass nach dem DOWNSAMPLING der Ausgang bis zu
-//n Werte später sich ändern darf, nachdem Sich der Eingang geändert hat.
-#define BOUND_BROKEN 2
-
-//length where fuzzy function raises from 0 to 1 or 1 to 0 for the complementery.
-//history of the data depends of it, and should change, if it changes.
-#define LENGTH 10
-
-
-//definitions for the testbench
-const string TEST_BENCH = "testbench";
-
-//defintions for the csv-reader-modules
-const string APPENDIX_CSV_MODULES = " CSV-Reader";
-const string FIRST_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES;
-const string SECOND_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES;
-const string THIRD_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES;
-const string FOURTH_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES;
-
-
-//to switch between different file configurations change the
-//DEFINES in file_util.h
-
-/**********************************************************************************************************************
- ************************************************end of global definitions of variables and constants *****************
- **********************************************************************************************************************/
-
-/**********************************************************************************************************************
- ************************************************begin of function prototypes *****************************************
- **********************************************************************************************************************/
-void create_and_register_all_Testbench_Configs(Testbench* current_tb);
-
-void create_and_register_All_Agents();
-void set_working_cycle_of_All_Agents();
-
-void create_and_register_All_Sensors();
-void set_working_cycle_of_All_Sensors();
-
-void create_and_register_channels();
-void create_and_register_channels_for_sensors();
-void create_and_register_channels_for_agents();
-
-void mount_sensors_in_agents();
-void mount_agents_in_agents();
-
-void register_data_agents_in_agent_state_Handler();
-
-void create_linear_function_blocks();
-void create_same_state_deviation_function_block();
-void create_another_state_deviation_function_block();
-void create_state_time_function_block();
-void create_another_state_time_function_block();
-void create_valid_state_deviation_function_block();
-void create_invalid_state_deviation_function_block();
-void create_valid_state_time_function_block();
-void create_invalid_state_time_function_block();
-void create_confidence_state_drift_function_block();
-void create_confidence_broken_function_block();
-void mount_function_blocks_to_viability_monitor();
-
-void create_all_testbenches();
-
-void create_csvr_modules();
-
-void register_agents_in_testbenches();
-
-void register_sensors_in_testbenches();
-
-void register_channels_in_testbenches();
-void register_channels_of_sensors_in_testbenches();
-void register_channels_of_actors_in_testbenches();
-
-void set_config_values_in_linear_functions(Testbench* current_tb);
-void set_parameters_LinearFunctionBlock(LinearFunctionBlock* cur_lin_func_block);
-void set_parameters_LinearFunction(vector<LinearFunction*> vec_Lin_Func);
-
-void set_CSV_Writer_parameter(Testbench* current_tb);
-
-void run_simulation_of_all_testbenches();
-
-void close_file_pointers();
-
-void empty_static_vectors();
-void empty_vec_Agent();
-void empty_vec_Channel_Agent();
-void empty_vec_Channel_Sensor();
-void empty_vec_Sensors();
-void empty_vec_csv_raders();
-void empty_vec_linear_func_Blocks();
-void empty_vec_TestBench();
-
-
-/**********************************************************************************************************************
- ************************************************end of function prototypes *******************************************
- **********************************************************************************************************************/
-
-int main()
-{
- cout << "This program processes test data from OMV Steam Cracker furnaces." << endl;
-
- create_and_register_All_Agents();
- set_working_cycle_of_All_Agents();
-
-
- create_and_register_All_Sensors();
- set_working_cycle_of_All_Sensors();
-
- create_and_register_channels();
-
- mount_sensors_in_agents();
-
- mount_agents_in_agents();
-
- register_data_agents_in_agent_state_Handler();
-
- create_linear_function_blocks();
-
- mount_function_blocks_to_viability_monitor();
-
- create_all_testbenches();
-
- create_csvr_modules();
-
- register_agents_in_testbenches();
-
- register_sensors_in_testbenches();
-
- register_channels_in_testbenches();
-
-
-
- run_simulation_of_all_testbenches();
-
- //close_file_pointers();
- //TODO memory free of all objects.
- empty_static_vectors();
-
- cout << "Program finished successfully" << endl;
- return 0;
-}
-
-void create_and_register_all_Testbench_Configs(Testbench* current_tb)
-{
-
- One_Config_t one;
- one.bound_broken = 2;
- one.inner_bound_sim_dif = 0.02;
- one.outter_bound_sim_dif = 0.08;
- one.inner_bound_drift = 3 * one.outter_bound_sim_dif;
- one.inner_bound_drift = one.outter_bound_sim_dif;
- one.length = 10;
- Testbench_Config* cfg = new Testbench_Config(one);
- cfg->print();
- current_tb->register_testbench_config(cfg);
-}
-
-
-
-/*
- * creates all the agents used in the measurement
- * and stores them into the global vector
- */
-void create_and_register_All_Agents()
-{
- cout << "Creating Agents" << endl;
- char* c_name_of_current_agent = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_agent, FIRST_MEASURED_DATA_NAME.c_str());
- Agent* a_FC6504_Y = create_agent(c_name_of_current_agent);
- strcpy(c_name_of_current_agent, SECOND_MEASURED_DATA_NAME.c_str());
- Agent* a_FC6504 = create_agent(c_name_of_current_agent);
- strcpy(c_name_of_current_agent, THIRD_MEASURED_DATA_NAME.c_str());
- Agent* a_FC6504_SP = create_agent(c_name_of_current_agent);
- strcpy(c_name_of_current_agent, FOURTH_MEASURED_DATA_NAME.c_str());
- Agent* a_PI6584 = create_agent(c_name_of_current_agent);
- strcpy(c_name_of_current_agent, VIABILITY_MONITOR.c_str());
- Agent* a_viabilityMonitor = create_agent(c_name_of_current_agent);
- vec_of_Agents.push_back(a_FC6504_Y);
- vec_of_Agents.push_back(a_FC6504);
- vec_of_Agents.push_back(a_FC6504_SP);
- vec_of_Agents.push_back(a_PI6584);
- vec_of_Agents.push_back(a_viabilityMonitor);
- cout << vec_of_Agents.size() << " agents were created" << endl;
- delete c_name_of_current_agent;
-}
-
-/*
- * the working_cycle for all registered agents is set
- */
-void set_working_cycle_of_All_Agents()
-{
- unsigned int working_Cyle = SAMPLING;
- unsigned int size_of_vec_of_Agents = 0;
- unsigned int index = 0;
- Agent* current_Agent;
- size_of_vec_of_Agents = vec_of_Agents.size();
- for(index = 0; index < size_of_vec_of_Agents; index++) {
- current_Agent = vec_of_Agents[index];
- setWorkingCycleOfAgent(current_Agent, working_Cyle);
- }
-}
-
-/*
- * all necessary sensors are created and registered
- */
-void create_and_register_All_Sensors()
-{
- cout << "Creating Sensors" << endl;
- char* c_name_of_current_sensor = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_sensor, FIRST_MEASURED_DATA_NAME.c_str());
- Sensor* s_FC6504_Y = create_sensor(c_name_of_current_sensor);
- strcpy(c_name_of_current_sensor, SECOND_MEASURED_DATA_NAME.c_str());
- Sensor* s_FC6504 = create_sensor(c_name_of_current_sensor);
- strcpy(c_name_of_current_sensor, THIRD_MEASURED_DATA_NAME.c_str());
- Sensor* s_FC6504_SP = create_sensor(c_name_of_current_sensor);
- strcpy(c_name_of_current_sensor, FOURTH_MEASURED_DATA_NAME.c_str());
- Sensor* s_PI6584 = create_sensor(c_name_of_current_sensor);
- vec_of_Sensors.push_back(s_FC6504_Y);
- vec_of_Sensors.push_back(s_FC6504);
- vec_of_Sensors.push_back(s_FC6504_SP);
- vec_of_Sensors.push_back(s_PI6584);
- cout << vec_of_Sensors.size() << " sensors were created." << endl;
- delete c_name_of_current_sensor;
-}
-
-/*
- * working cycle of all registered sensors is set
- */
-void set_working_cycle_of_All_Sensors()
-{
- unsigned int working_Cyle = SAMPLING;
- unsigned int size_of_vec_of_Sensors = 0;
- unsigned int index = 0;
- Sensor* current_Sensor;
-
- size_of_vec_of_Sensors = vec_of_Sensors.size();
- for(index = 0; index < size_of_vec_of_Sensors; index++) {
- current_Sensor = vec_of_Sensors[index];
- setWorkingCycleOfSensor(current_Sensor, working_Cyle);
- }
-}
-
-/*
- * creating and registering all channels
- */
-void create_and_register_channels()
-{
- create_and_register_channels_for_sensors();
- create_and_register_channels_for_agents();
-}
-
-/*
- * creating and registering the channels for the sensors.
- */
-void create_and_register_channels_for_sensors()
-{
- cout << "Creating and registering channels for sensors" << endl;
- char* c_name_of_current_channel = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_channel, FIRST_MEASURED_CHANNEL_SENSOR_NAME.c_str());
- Channel* c_sa_FC6504_Y = create_channel(c_name_of_current_channel, 0);
- strcpy(c_name_of_current_channel, SECOND_MEASURED_CHANNEL_SENSOR_NAME.c_str());
- Channel* c_sa_FC6504 = create_channel(c_name_of_current_channel, 0);
- strcpy(c_name_of_current_channel, THIRD_MEASURED_CHANNEL_SENSOR_NAME.c_str());
- Channel* c_sa_FC6504_SP = create_channel(c_name_of_current_channel, 0);
- strcpy(c_name_of_current_channel, FOURTH_MEASURED_CHANNEL_SENSOR_NAME.c_str());
- Channel* c_sa_PI6584 = create_channel(c_name_of_current_channel, 0);
-
- vec_of_Channels_for_Sensors.push_back(c_sa_FC6504_Y);
- vec_of_Channels_for_Sensors.push_back(c_sa_FC6504);
- vec_of_Channels_for_Sensors.push_back(c_sa_FC6504_SP);
- vec_of_Channels_for_Sensors.push_back(c_sa_PI6584);
- cout << vec_of_Channels_for_Sensors.size() << " channels for sensors were created" << endl;
-
- delete c_name_of_current_channel;
-}
-
-/*
- * creating and registering the channels for the agents
- */
-void create_and_register_channels_for_agents()
-{
- cout << "Creating and registering channels for agents" << endl;
- char* c_name_of_current_channel = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_channel, FIRST_MEASURED_CHANNEL_AGENT_NAME.c_str());
- Channel* c_aa_FC6504_Y = create_channel(c_name_of_current_channel, MAX_BUFFER_LENGTH);
- strcpy(c_name_of_current_channel, SECOND_MEASURED_CHANNEL_AGENT_NAME.c_str());
- Channel* c_aa_FC6504 = create_channel(c_name_of_current_channel, MAX_BUFFER_LENGTH);
- strcpy(c_name_of_current_channel, THIRD_MEASURED_CHANNEL_AGENT_NAME.c_str());
- Channel* c_aa_FC6504_SP = create_channel(c_name_of_current_channel, MAX_BUFFER_LENGTH);
- strcpy(c_name_of_current_channel, FOURTH_MEASURED_CHANNEL_AGENT_NAME.c_str());
- Channel* c_aa_PI6584 = create_channel(c_name_of_current_channel, MAX_BUFFER_LENGTH);
-
- vec_of_Channels_for_Agents.push_back(c_aa_FC6504_Y);
- vec_of_Channels_for_Agents.push_back(c_aa_FC6504);
- vec_of_Channels_for_Agents.push_back(c_aa_FC6504_SP);
- vec_of_Channels_for_Agents.push_back(c_aa_PI6584);
-
- cout << vec_of_Channels_for_Agents.size() << " channels for agents were created" << endl;
-
- delete c_name_of_current_channel;
-}
-
-void mount_sensors_in_agents()
-{
- Agent* current_agent;
- Sensor* current_sensor;
- Channel* current_sensor_channel;
- unsigned int size_of_vec_sensor = 0;
- unsigned int index = 0;
-
- size_of_vec_sensor = vec_of_Sensors.size();
- cout << "mounting sensors in agents." << endl;
- //it is assumed that the corresponding sensors and agents and channels are always at the same
- //position in the different vectors, if not then you have to add an search algorithm for it.
- for(index = 0; index < size_of_vec_sensor; index++)
- {
- current_agent = vec_of_Agents[index];
- current_sensor = vec_of_Sensors[index];
- current_sensor_channel = vec_of_Channels_for_Sensors[index];
- mount_sensorInAgent(current_agent, current_sensor, current_sensor_channel);
- }
- cout << size_of_vec_sensor << " sensors in agents were mounted" << endl;
-}
-
-void mount_agents_in_agents()
-{
- Agent* current_agent;
- Agent* viability_Monitor;
- Channel* current_agent_channel;
- unsigned int size_of_vec_agents = 0;
- unsigned int index = 0;
-
- size_of_vec_agents = vec_of_Agents.size();
- //it is assumed that the viability agent is at the last position in the vector
- viability_Monitor = vec_of_Agents[size_of_vec_agents-1];
- //all agents and channels are registered to the viabilityMonitor agent
- //so you have to subtract the viabilityMonitor from the number of elements to register
- //it is assumed that all the corresponding channels and agents are placed at the same index
- for(index = 0; index < size_of_vec_agents -1; index++)
- {
- current_agent = vec_of_Agents[index];
- current_agent_channel = vec_of_Channels_for_Agents[index];
- //only register if the agent is not the viability_monitor, otherwise you would register the viability monitor to itself.
- if(current_agent != viability_Monitor) {
- mount_agentInAgent(viability_Monitor, current_agent, current_agent_channel);
- }
- }
- cout << size_of_vec_agents -1 << "agents were registered to the viability monitor" << endl;
-}
-
-/*
- * registers the channels for the data agents to the viability monitor
- */
-void register_data_agents_in_agent_state_Handler()
-
-{
- Agent* viability_Monitor;
- Channel* current_agent_channel;
- unsigned int size_of_vec_channel_agents = 0;
- unsigned int index = 0;
-
- size_of_vec_channel_agents = vec_of_Channels_for_Agents.size();
- //get the agent for the viabilityMonitor, it is assumed that it is at the last position
- viability_Monitor = vec_of_Agents[vec_of_Agents.size()-1];
- //register all the channels to the viability monitor
- for(index = 0; index < size_of_vec_channel_agents; index++) {
- current_agent_channel = vec_of_Channels_for_Agents[index];
- if(index != INDEX_OUTPUT) {
- registerSlaveAgentAsInputVariableInStateHandler(viability_Monitor, current_agent_channel);
- }
- else{
- registerSlaveAgentAsOutputVariableInStateHandler(viability_Monitor, current_agent_channel);
+#include <stdlib.h>
+
+#include "configCAMforNewMotor.h"
+
+#define CAM_FOR_FLUID 1
+#define CAM_FOR_NEWMOTOR 2
+
+#define PRINT
+#define STOP_AFTER_SUMMARY
+
+
+
+int main(int argc, char *argv[]) {
+
+ // paths config
+ //TODO: maybe change char[] to String
+ char datasetPath[700];
+ char destinationPath[700];
+
+ // dataset config
+ char datasetName[200];
+ unsigned int datasetLength;
+
+ // CAM System config
+ int camConfigOption;
+
+ // CAM Values config (fuzzy functions etc.)
+ float innerBoundSimDif;
+ float outerBoundSimDif;
+ int boundTimeInSamples;
+ float innerBoundDrift;
+ float outerBoundDrift;
+ int boundBrokenTime;
+ int downSamplingFactor;
+
+
+ //if the only argument is the name of the executable itself.
+ if (argc <= 1) {
+ //configure here everything out of the C++ code.
+
+
+
+ }
+ else if (argc > 12) {
+ // paths config
+ sprintf_s(destinationPath, "%s", argv[1]);
+ sprintf_s(datasetPath, "%s", argv[2]);
+
+ // dataset config
+ sprintf_s(datasetName, "%s", argv[3]);
+ datasetLength = (unsigned int)atoi(argv[4]);
+
+ // CAM System config
+ camConfigOption = atoi(argv[5]);
+
+ // CAM Values config (fuzzy functions etc.)
+ innerBoundSimDif = atof(argv[6]);
+ outerBoundSimDif = atof(argv[7]);
+ boundTimeInSamples = atoi(argv[8]);
+ innerBoundDrift = atof(argv[9]);
+ outerBoundDrift = atof(argv[10]);
+ boundBrokenTime = atoi(argv[11]);
+ downSamplingFactor = atoi(argv[12]);
+
+
+
+
+
+#ifdef PRINT
+ printf("destinationPath: %s\n\n", destinationPath);
+ printf("datasetPath: %s\n", datasetPath);
+ printf("datasetName: %s\n", datasetName);
+ printf("datasetLength: %u\n", datasetLength);
+
+ printf("innerBoundSimDif: %f\n", innerBoundSimDif);
+ printf("outerBoundSimDif: %f\n", outerBoundSimDif);
+ printf("boundTimeInSamples: %i\n", boundTimeInSamples);
+ printf("innerBoundDrift: %f\n", innerBoundDrift);
+ printf("outerBoundDrift: %f\n", outerBoundDrift);
+ printf("boundBrokenTime: %i\n", boundBrokenTime);
+ printf("downSamplingFactor: %i\n", downSamplingFactor);
+
+
+
+#ifdef STOP_AFTER_SUMMARY
+ getchar();
+#endif // STOP_AFTER_SUMMARY
+#endif
+
+ if (camConfigOption == CAM_FOR_FLUID) {
+ //start Fluid CAM config
+ /*
+ configAndStartFluidExperiment(
+ destinationPath, datasetPath, datasetName,
+ datasetLength, innerBoundSimDif, outerBoundSimDif,
+ boundTimeInSamples, innerBoundDrift,
+ outerBoundDrift, boundBrokenTime,
+ downSamplingFactor);
+ */
+ }
+ else if (camConfigOption == CAM_FOR_NEWMOTOR) {
+ //start newMotor CAM config
+ configAndStartNewMotorExperiment(
+ destinationPath, datasetPath, datasetName,
+ datasetLength, innerBoundSimDif, outerBoundSimDif,
+ boundTimeInSamples, innerBoundDrift,
+ outerBoundDrift, boundBrokenTime,
+ downSamplingFactor);
}
}
}
-
-/*
- * creates and register all the different linear function blocks
- */
-void create_linear_function_blocks()
-{
- //don't change the sequence, because later it is assumed that the functions are
- //registered int the vector in this sequence
- //if you change it you have also to change the sequence in the function mount_function_blocks_to_viability_monitor
- create_same_state_deviation_function_block();
- create_another_state_deviation_function_block();
- create_state_time_function_block();
- create_another_state_time_function_block();
- create_valid_state_deviation_function_block();
- create_invalid_state_deviation_function_block();
- create_valid_state_time_function_block();
- create_invalid_state_time_function_block();
- create_confidence_state_drift_function_block();
- create_confidence_broken_function_block();
-}
-
-/*
- * creates and register the linear function block for same state deviation
- */
-void create_same_state_deviation_function_block()
-{
- char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_SAME_STATE_DEV.c_str());
- LinearFunctionBlock* confSim2StateDev = new LinearFunctionBlock(c_name_of_current_func_block);
- LinearFunction* funcConfSim2StateDev1 = new LinearFunction(CONF_SIM2_STATE_DEV_1);
- funcConfSim2StateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF);
- funcConfSim2StateDev1->setKandD((float)0, (float)0);
- confSim2StateDev->addLinearFunction(funcConfSim2StateDev1);
- LinearFunction* funcConfSim2StateDev2 = new LinearFunction(CONF_SIM2_STATE_DEV_2);
- funcConfSim2StateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF);
- funcConfSim2StateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)0, (float)-INNER_BOUND_SIM_DIF, (float)1);
- confSim2StateDev->addLinearFunction(funcConfSim2StateDev2);
- LinearFunction* funcConfSim2StateDev3 = new LinearFunction(CONF_SIM2_STATE_DEV_3);
- funcConfSim2StateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF);
- funcConfSim2StateDev3->setKandD((float)0, (float)1);
- confSim2StateDev->addLinearFunction(funcConfSim2StateDev3);
- LinearFunction* funcConfSim2StateDev4 = new LinearFunction(CONF_SIM2_STATE_DEV_4);
- funcConfSim2StateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF);
- funcConfSim2StateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)1, (float)OUTTER_BOUND_SIM_DIF, (float)0);
- confSim2StateDev->addLinearFunction(funcConfSim2StateDev4);
- LinearFunction* funcConfSim2StateDev5 = new LinearFunction(CONF_SIM2_STATE_DEV_5);
- funcConfSim2StateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false);
- funcConfSim2StateDev5->setKandD((float)0, (float)0);
- confSim2StateDev->addLinearFunction(funcConfSim2StateDev5);
-
- vec_of_linear_Function_Blocks.push_back(confSim2StateDev);
-
- delete c_name_of_current_func_block;
-}
-
-/*
- * creates and register another state deviation function block
- */
-void create_another_state_deviation_function_block()
-{
- char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_ANOTHER_STATE_DEV.c_str());
- LinearFunctionBlock* confDif2StateDev = new LinearFunctionBlock(c_name_of_current_func_block);
- LinearFunction* funcConfDif2StateDev1 = new LinearFunction(CONF_DIF2_STATE_DEV_1);
- funcConfDif2StateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF);
- funcConfDif2StateDev1->setKandD((float)0, (float)1);
- confDif2StateDev->addLinearFunction(funcConfDif2StateDev1);
- LinearFunction* funcConfDif2StateDev2 = new LinearFunction(CONF_DIF2_STATE_DEV_2);
- funcConfDif2StateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF);
- funcConfDif2StateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)1, (float)-INNER_BOUND_SIM_DIF, (float)0);
- confDif2StateDev->addLinearFunction(funcConfDif2StateDev2);
- LinearFunction* funcConfDif2StateDev3 = new LinearFunction(CONF_DIF2_STATE_DEV_3);
- funcConfDif2StateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF);
- funcConfDif2StateDev3->setKandD((float)0, (float)0);
- confDif2StateDev->addLinearFunction(funcConfDif2StateDev3);
- LinearFunction* funcConfDif2StateDev4 = new LinearFunction(CONF_DIF2_STATE_DEV_4);
- funcConfDif2StateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF);
- funcConfDif2StateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)0, (float)OUTTER_BOUND_SIM_DIF, (float)1);
- confDif2StateDev->addLinearFunction(funcConfDif2StateDev4);
- LinearFunction* funcConfDif2StateDev5 = new LinearFunction(CONF_DIF2_STATE_DEV_5);
- funcConfDif2StateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false);
- funcConfDif2StateDev5->setKandD((float)0, (float)1);
- confDif2StateDev->addLinearFunction(funcConfDif2StateDev5);
-
- vec_of_linear_Function_Blocks.push_back(confDif2StateDev);
-
- delete c_name_of_current_func_block;
-}
-
-void create_state_time_function_block()
-{
- char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_SAME_TIME.c_str());
- LinearFunctionBlock* confSim2StateTime = new LinearFunctionBlock(c_name_of_current_func_block);
- LinearFunction* funcConfSim2StateTime1 = new LinearFunction(CONF_SIM2_STATE_TIME_1);
- funcConfSim2StateTime1->setDomain(false, true, (float)0);
- funcConfSim2StateTime1->setKandD((float)0, (float)0);
- confSim2StateTime->addLinearFunction(funcConfSim2StateTime1);
- LinearFunction* funcConfSim2StateTime2 = new LinearFunction(CONF_SIM2_STATE_TIME_2);
- funcConfSim2StateTime2->setDomain(true, (float)0, true, (float)LENGTH);
- funcConfSim2StateTime2->setKandD((float)0, (float)0, (float)LENGTH, (float)1);
- confSim2StateTime->addLinearFunction(funcConfSim2StateTime2);
- LinearFunction* funcConfSim2StateTime3 = new LinearFunction(CONF_SIM2_STATE_TIME_3);
- funcConfSim2StateTime3->setDomain(true, (float)LENGTH, false);
- funcConfSim2StateTime3->setKandD((float)0, (float)1);
- confSim2StateTime->addLinearFunction(funcConfSim2StateTime3);
-
- vec_of_linear_Function_Blocks.push_back(confSim2StateTime);
-
- delete c_name_of_current_func_block;
-}
-
-void create_another_state_time_function_block()
-{
- char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_ANOTHER_STATE_TIME.c_str());
- LinearFunctionBlock* confDif2StateTime = new LinearFunctionBlock(c_name_of_current_func_block);
- LinearFunction* funcConfDif2StateTime1 = new LinearFunction(CONF_DIF2_STATE_TIME_1);
- funcConfDif2StateTime1->setDomain(false, true, (float)0);
- funcConfDif2StateTime1->setKandD((float)0, (float)1);
- confDif2StateTime->addLinearFunction(funcConfDif2StateTime1);
- LinearFunction* funcConfDif2StateTime2 = new LinearFunction(CONF_DIF2_STATE_TIME_2);
- funcConfDif2StateTime2->setDomain(true, (float)0, true, (float)LENGTH);
- funcConfDif2StateTime2->setKandD((float)0, (float)1, (float)LENGTH, (float)0);
- confDif2StateTime->addLinearFunction(funcConfDif2StateTime2);
- LinearFunction* funcConfDif2StateTime3 = new LinearFunction(CONF_DIF2_STATE_TIME_3);
- funcConfDif2StateTime3->setDomain(true, (float)LENGTH, false);
- funcConfDif2StateTime3->setKandD((float)0, (float)0);
- confDif2StateTime->addLinearFunction(funcConfDif2StateTime3);
-
- vec_of_linear_Function_Blocks.push_back(confDif2StateTime);
-
- delete c_name_of_current_func_block;
-}
-
-void create_valid_state_deviation_function_block()
-{
- char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_VAILD_STATE_DEV.c_str());
- LinearFunctionBlock* confValidStateDev = new LinearFunctionBlock(c_name_of_current_func_block);
- LinearFunction* funcConfValidStateDev1 = new LinearFunction(CONF_VALID_STATE_DEV_1);
- funcConfValidStateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF);
- funcConfValidStateDev1->setKandD((float)0, (float)0);
- confValidStateDev->addLinearFunction(funcConfValidStateDev1);
- LinearFunction* funcConfValidStateDev2 = new LinearFunction(CONF_VALID_STATE_DEV_2);
- funcConfValidStateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF);
- funcConfValidStateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)0, (float)-INNER_BOUND_SIM_DIF, (float)1);
- confValidStateDev->addLinearFunction(funcConfValidStateDev2);
- LinearFunction* funcConfValidStateDev3 = new LinearFunction(CONF_VALID_STATE_DEV_3);
- funcConfValidStateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF);
- funcConfValidStateDev3->setKandD((float)0, (float)1);
- confValidStateDev->addLinearFunction(funcConfValidStateDev3);
- LinearFunction* funcConfValidStateDev4 = new LinearFunction(CONF_VALID_STATE_DEV_4);
- funcConfValidStateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF);
- funcConfValidStateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)1, (float)OUTTER_BOUND_SIM_DIF, (float)0);
- confValidStateDev->addLinearFunction(funcConfValidStateDev4);
- LinearFunction* funcConfValidStateDev5 = new LinearFunction(CONF_VALID_STATE_DEV_5);
- funcConfValidStateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false);
- funcConfValidStateDev5->setKandD((float)0, (float)0);
- confValidStateDev->addLinearFunction(funcConfValidStateDev5);
-
- vec_of_linear_Function_Blocks.push_back(confValidStateDev);
-
- delete c_name_of_current_func_block;
-}
-
-void create_invalid_state_deviation_function_block()
-{
- char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_INVALID_STATE_DEV.c_str());
- LinearFunctionBlock* confInvalidStateDev = new LinearFunctionBlock(c_name_of_current_func_block);
- LinearFunction* funcConfInvalidStateDev1 = new LinearFunction(CONF_INVALID_STATE_DEV_1);
- funcConfInvalidStateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF);
- funcConfInvalidStateDev1->setKandD((float)0, (float)1);
- confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev1);
- LinearFunction* funcConfInvalidStateDev2 = new LinearFunction(CONF_INVALID_STATE_DEV_2);
- funcConfInvalidStateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF);
- funcConfInvalidStateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)1, (float)-INNER_BOUND_SIM_DIF, (float)0);
- confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev2);
- LinearFunction* funcConfInvalidStateDev3 = new LinearFunction(CONF_INVALID_STATE_DEV_3);
- funcConfInvalidStateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF);
- funcConfInvalidStateDev3->setKandD((float)0, (float)0);
- confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev3);
- LinearFunction* funcConfInvalidStateDev4 = new LinearFunction(CONF_INVALID_STATE_DEV_4);
- funcConfInvalidStateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF);
- funcConfInvalidStateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)0, (float)OUTTER_BOUND_SIM_DIF, (float)1);
- confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev4);
- LinearFunction* funcConfInvalidStateDev5 = new LinearFunction(CONF_INVALID_STATE_DEV_5);
- funcConfInvalidStateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false);
- funcConfInvalidStateDev5->setKandD((float)0, (float)1);
- confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev5);
-
- vec_of_linear_Function_Blocks.push_back(confInvalidStateDev);
-
- delete c_name_of_current_func_block;
-}
-
-void create_valid_state_time_function_block()
-{
- char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_VALID_STATE_TIME.c_str());
- LinearFunctionBlock* confValidStateTime = new LinearFunctionBlock(c_name_of_current_func_block);
- LinearFunction* funcConfValidStateTime1 = new LinearFunction(VALID_STATE_TIME_1);
- funcConfValidStateTime1->setDomain(false, true, (float)0);
- funcConfValidStateTime1->setKandD((float)0, (float)0);
- confValidStateTime->addLinearFunction(funcConfValidStateTime1);
- LinearFunction* funcConfValidStateTime2 = new LinearFunction(VALID_STATE_TIME_2);
- funcConfValidStateTime2->setDomain(true, (float)0, true, (float)LENGTH); //10
- funcConfValidStateTime2->setKandD((float)0, (float)0, (float)LENGTH, (float)1);
- confValidStateTime->addLinearFunction(funcConfValidStateTime2);
- LinearFunction* funcConfValidStateTime3 = new LinearFunction(VALID_STATE_TIME_3);
- funcConfValidStateTime3->setDomain(true, (float)LENGTH, false);
- funcConfValidStateTime3->setKandD((float)0, (float)1);
- confValidStateTime->addLinearFunction(funcConfValidStateTime3);
-
- vec_of_linear_Function_Blocks.push_back(confValidStateTime);
-
- delete c_name_of_current_func_block;
-}
-void create_invalid_state_time_function_block()
-{
- char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_INVALID_STATE_TIME.c_str());
- LinearFunctionBlock* confInvalidStateTime = new LinearFunctionBlock(c_name_of_current_func_block);
- LinearFunction* funcConfInvalidStateTime1 = new LinearFunction(INVALID_STATE_TIME_1);
- funcConfInvalidStateTime1->setDomain(false, true, (float)0);
- funcConfInvalidStateTime1->setKandD((float)0, (float)1);
- confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime1);
- LinearFunction* funcConfInvalidStateTime2 = new LinearFunction(INVALID_STATE_TIME_2);
- funcConfInvalidStateTime2->setDomain(true, (float)0, true, (float)LENGTH);
- funcConfInvalidStateTime2->setKandD((float)0, (float)1, (float)LENGTH, (float)0);
- confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime2);
- LinearFunction* funcConfInvalidStateTime3 = new LinearFunction(INVALID_STATE_TIME_3);
- funcConfInvalidStateTime3->setDomain(true, (float)LENGTH, false);
- funcConfInvalidStateTime3->setKandD((float)0, (float)0);
- confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime3);
-
- vec_of_linear_Function_Blocks.push_back(confInvalidStateTime);
-
- delete c_name_of_current_func_block;
-}
-
-void create_confidence_state_drift_function_block()
-{
- char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_CONFIDENCE_STATE_DRIFTS.c_str());
- LinearFunctionBlock* confStateDrifts = new LinearFunctionBlock(c_name_of_current_func_block);
- LinearFunction* functionConfidenceDriftDeviation1 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_1);
- functionConfidenceDriftDeviation1->setDomain(false, true, (float)-OUTTER_BOUND_DRIFT);
- functionConfidenceDriftDeviation1->setKandD((float)0, (float)1);
- confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation1);
- LinearFunction* functionConfidenceDriftDeviation2 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_2);
- functionConfidenceDriftDeviation2->setDomain(true, (float)-OUTTER_BOUND_DRIFT, true, (float)-INNER_BOUND_DRIFT);
- functionConfidenceDriftDeviation2->setKandD((float)-INNER_BOUND_DRIFT, (float)1, (float)-INNER_BOUND_DRIFT, (float)0);
- confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation2);
- LinearFunction* functionConfidenceDriftDeviation3 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_3);
- functionConfidenceDriftDeviation3->setDomain(true, (float)-INNER_BOUND_DRIFT, true, (float)INNER_BOUND_DRIFT);
- functionConfidenceDriftDeviation3->setKandD((float)0, (float)0);
- confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation3);
- LinearFunction* functionConfidenceDriftDeviation4 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_4);
- functionConfidenceDriftDeviation4->setDomain(true, (float)INNER_BOUND_DRIFT, true, (float)OUTTER_BOUND_DRIFT);
- functionConfidenceDriftDeviation4->setKandD((float)INNER_BOUND_DRIFT, (float)0, (float)OUTTER_BOUND_DRIFT, (float)1);
- confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation4);
- LinearFunction* functionConfidenceDriftDeviation5 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_5);
- functionConfidenceDriftDeviation5->setDomain(true, (float)OUTTER_BOUND_DRIFT, false);
- functionConfidenceDriftDeviation5->setKandD((float)0, (float)1);
- confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation5);
-
- vec_of_linear_Function_Blocks.push_back(confStateDrifts);
-
- delete c_name_of_current_func_block;
-}
-
-void create_confidence_broken_function_block()
-{
- char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_CONFIDENCE_BROKEN.c_str());
- LinearFunctionBlock* confBroken = new LinearFunctionBlock(c_name_of_current_func_block);
- LinearFunction* functionConfidenceBroken1 = new LinearFunction(CONFIDENCE_BROKEN_1);
- functionConfidenceBroken1->setDomain(false, true, (float)0);
- functionConfidenceBroken1->setKandD((float)0, (float)0);
- confBroken->addLinearFunction(functionConfidenceBroken1);
- LinearFunction* functionConfidenceBroken2 = new LinearFunction(CONFIDENCE_BROKEN_2);
- functionConfidenceBroken2->setDomain(true, (float)0, true, (float)BOUND_BROKEN);
- functionConfidenceBroken2->setKandD((float)0, (float)0, (float)BOUND_BROKEN, (float)1);
- confBroken->addLinearFunction(functionConfidenceBroken2);
- LinearFunction* functionConfidenceBroken3 = new LinearFunction(CONFIDENCE_BROKEN_3);
- functionConfidenceBroken3->setDomain(true, (float)BOUND_BROKEN, false);
- functionConfidenceBroken3->setKandD((float)0, (float)1);
- confBroken->addLinearFunction(functionConfidenceBroken3);
-
- vec_of_linear_Function_Blocks.push_back(confBroken);
-
- delete c_name_of_current_func_block;
-}
-
-/*
- * mount the different function blocks to the viability monitor agent
- */
-void mount_function_blocks_to_viability_monitor()
-{
- Agent* viability_Monitor;
- LinearFunctionBlock* current_Linear_Function_Bock;
- unsigned int size_of_vec_lin_func_block = vec_of_linear_Function_Blocks.size();
- unsigned int index = 0;
-
- //it is assumed that the viability monitor is at the last position of the vector of agents
- viability_Monitor = vec_of_Agents[vec_of_Agents.size()-1];
- for(index = 0; index < size_of_vec_lin_func_block; index++) {
- current_Linear_Function_Bock = vec_of_linear_Function_Blocks[index];
- //it is assumed that the function blocks are added into the vector in the following sequence
- switch(index) {
- case 0:
- viability_Monitor->get_stateHandler()->FuncBlockConfSim2StateDev = current_Linear_Function_Bock;
- break;
- case 1:
- viability_Monitor->get_stateHandler()->FuncBlockConfDif2StateDev = current_Linear_Function_Bock;
- break;
- case 2:
- viability_Monitor->get_stateHandler()->FuncBlockConfSim2StateTime = current_Linear_Function_Bock;
- break;
- case 3:
- viability_Monitor->get_stateHandler()->FuncBlockConfDif2StateTime = current_Linear_Function_Bock;
- break;
- case 4:
- viability_Monitor->get_stateHandler()->FuncBlockConfValStateDev = current_Linear_Function_Bock;
- break;
- case 5:
- viability_Monitor->get_stateHandler()->FuncBlockConfInvStateDev = current_Linear_Function_Bock;
- break;
- case 6:
- viability_Monitor->get_stateHandler()->FuncBlockConfValStateTime = current_Linear_Function_Bock;
- break;
- case 7:
- viability_Monitor->get_stateHandler()->FuncBlockConfInvStateTime = current_Linear_Function_Bock;
- break;
- case 8:
- viability_Monitor->get_stateHandler()->DriftDeviation = current_Linear_Function_Bock;
- break;
- case 9:
- viability_Monitor->get_stateHandler()->FuncBlockConfBrokenSamples = current_Linear_Function_Bock;
- break;
- }
- }
-}
-
-
-void create_all_testbenches() {
- char* c_name_of_current_testbench = new char[MAX_LENGTH_NAME];
- strcpy(c_name_of_current_testbench, TEST_BENCH.c_str());
- cout << "Creating test bench" << endl;
- Testbench* tb = create_testbench(c_name_of_current_testbench);
- create_and_register_all_Testbench_Configs(tb);
- vec_of_test_benches.push_back(tb);
-
- delete c_name_of_current_testbench;
-}
-
-void create_csvr_modules()
-{
- //sets the row in which the data starts, maybe row one contains the headers
- unsigned int row = 2;
- char* c_name_of_current_csv_module = new char[MAX_LENGTH_NAME];
- string current_reader_path_and_file_name;
- cout << "Creating CSV Reader Modules" << endl;
-
- current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA;
- strcpy(c_name_of_current_csv_module, FIRST_MEASURED_DATA_CSV_NAME.c_str());
- CSVreaderModule* csvr_FC6504_Y = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),3,row);
-
- current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA;
- strcpy(c_name_of_current_csv_module, SECOND_MEASURED_DATA_CSV_NAME.c_str());
- CSVreaderModule* csvr_FC6504 = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),4,row);
-
- current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA;
- strcpy(c_name_of_current_csv_module, THIRD_MEASURED_DATA_CSV_NAME.c_str());
- CSVreaderModule* csvr_FC6504_SP = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),5,row);
-
- current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA;
- strcpy(c_name_of_current_csv_module, FOURTH_MEASURED_DATA_CSV_NAME.c_str());
- CSVreaderModule* csvr_PI6584 = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),6,row);
-
- vec_of_csv_readers.push_back(csvr_FC6504_Y);
- vec_of_csv_readers.push_back(csvr_FC6504);
- vec_of_csv_readers.push_back(csvr_FC6504_SP);
- vec_of_csv_readers.push_back(csvr_PI6584);
-
- delete c_name_of_current_csv_module;
-}
-
-/*
- * all agents would be registered to all testbenches
- */
-void register_agents_in_testbenches()
-{
- Testbench* current_tb;
- unsigned int size_of_vec_test_benches = vec_of_test_benches.size();
- unsigned int index_tb = 0;
- Agent* current_ag;
- unsigned int size_of_vec_agents = vec_of_Agents.size();
- unsigned int index_agents = 0;
-
- cout << "registering agents in testbenches" << endl;
- for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) {
- current_tb = vec_of_test_benches[index_tb];
- for(index_agents = 0; index_agents < size_of_vec_agents; index_agents++) {
- current_ag = vec_of_Agents[index_agents];
- register_agentInTestbench(current_tb, current_ag);
- }
- }
- cout << size_of_vec_agents << " agents were registered in every of the " << size_of_vec_test_benches << " testbenches" << endl;
-}
-
-/*
- * registering the sensors and the corresponding csv-readers in the testbenches
- * it is assumed that the csv readers and the sensors are at the same index position
- * in the vectors.
- */
-void register_sensors_in_testbenches()
-{
- Testbench* current_tb;
- unsigned int size_of_vec_test_benches = vec_of_test_benches.size();
- unsigned int index_tb = 0;
- Sensor* current_se;
- unsigned int size_of_vec_sensors = vec_of_Sensors.size();
- unsigned int index_sensors = 0;
- CSVreaderModule* current_csv_reader;
- unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size();
-
- if(size_of_vec_csv_reader != size_of_vec_sensors) {
- cout << "Error, in sequence of data processing";
- cout << "Number of csv-readers should be equal to number of sensors" << endl;
- }
- else {
- cout << "Registering sensors and their csv-readers in testbenches " << endl;
- for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) {
- current_tb = vec_of_test_benches[index_tb];
- for(index_sensors = 0; index_sensors < size_of_vec_sensors; index_sensors++) {
- current_se = vec_of_Sensors[index_sensors];
- //it is assumed that the sensor and the corresponding csv-reader is stored
- //at the same position in the two different vectors
- current_csv_reader = vec_of_csv_readers[index_sensors];
- register_sensorInTestbench(current_tb, current_se, current_csv_reader);
- }
- }
- cout << size_of_vec_sensors << " Sensors and their csv-readers were registered to ";
- cout << "every of the " << size_of_vec_test_benches << " testbenches" << endl;
- }
-}
-
-void register_channels_in_testbenches()
-{
- register_channels_of_sensors_in_testbenches();
-
- register_channels_of_actors_in_testbenches();
-}
-
-void register_channels_of_sensors_in_testbenches()
-{
- Testbench* current_tb;
- unsigned int size_of_vec_test_benches = vec_of_test_benches.size();
- unsigned int index_tb = 0;
- Channel* current_se_ch;
- unsigned int size_of_vec_se_channel = vec_of_Channels_for_Sensors.size();
- unsigned int index_se_ch = 0;
-
- cout << "Registering channels of sensors in testbench" << endl;
- for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) {
- current_tb = vec_of_test_benches[index_tb];
- for(index_se_ch = 0; index_se_ch < size_of_vec_se_channel; index_se_ch++) {
- current_se_ch = vec_of_Channels_for_Sensors[index_se_ch];
- register_channelInTestbench(current_tb, current_se_ch);
- }
- }
- cout << size_of_vec_se_channel << " channels of sensors were registered in ";
- cout << size_of_vec_test_benches << " testbenches." << endl;
-
-}
-
-void register_channels_of_actors_in_testbenches()
-{
- Testbench* current_tb;
- unsigned int size_of_vec_test_benches = vec_of_test_benches.size();
- unsigned int index_tb = 0;
- Channel* current_se_ch;
- unsigned int size_of_vec_ag_channel = vec_of_Channels_for_Agents.size();
- unsigned int index_se_ch = 0;
-
- cout << "Registering channels of agents in testbench" << endl;
- for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) {
- current_tb = vec_of_test_benches[index_tb];
- for(index_se_ch = 0; index_se_ch < size_of_vec_ag_channel; index_se_ch++) {
- current_se_ch = vec_of_Channels_for_Agents[index_se_ch];
- register_channelInTestbench(current_tb, current_se_ch);
- }
- }
- cout << size_of_vec_ag_channel << " channels of agents were registered in ";
- cout << size_of_vec_test_benches << " testbenches." << endl;
-}
-
-void run_simulation_of_all_testbenches()
-{
-
- string pressed_key;
- Testbench* current_tb;
- vector<Testbench_Config*> vec_tb_configs;
- Testbench_Config* current_tb_config;
- unsigned int size_of_vec_test_benches = vec_of_test_benches.size();
- unsigned int index_tb = 0;
- unsigned int size_of_vec_test_bench_config;
- unsigned int index_tb_cfg = 0;
- unsigned int sim_rounds = -1;
- const int start_row = 1;
- if (FILE_NAME_OF_ENTIRE_DATA == "2017_01_07__05_46_fc6504.csv") {
- sim_rounds = 720;
- }
-
- cout << "Press any key to start the simulation of all testbenches." << endl;
- getline(cin, pressed_key);
-
- for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++){
- current_tb = vec_of_test_benches[index_tb];
- index_tb_cfg = 0;
- vec_tb_configs = current_tb->get_all_registered_testbench_configs();
- size_of_vec_test_bench_config = vec_tb_configs.size();
- for(index_tb_cfg = 0; index_tb_cfg < size_of_vec_test_bench_config; index_tb_cfg++){
- current_tb_config = vec_tb_configs[index_tb_cfg];
- current_tb->set_current_tb_config_index(index_tb_cfg);
- current_tb->set_CSV_Writer_parameter();
- current_tb->set_config_values_in_linear_functions();
- //have to open new file first! with the CSV-Writer, for every round > 0
- current_tb->simulate(sim_rounds);
- if(index_tb_cfg < size_of_vec_test_bench_config - 1) {
- current_tb->set_CSV_Reader_row(start_row);
- current_tb->set_CSV_Reader_to_beginning();
- current_tb->reset_States();
- }
- }
- }
- cout << "Simulation of " << size_of_vec_test_benches << " testbenches successfully finished" << endl;
-}
-
-void close_file_pointers()
-{
- CSVreaderModule* current_csv_reader;
- unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size();
- unsigned int index_csv_reader;
- for(index_csv_reader = 0; index_csv_reader < size_of_vec_csv_reader; index_csv_reader++) {
- current_csv_reader = vec_of_csv_readers[index_csv_reader];
- current_csv_reader->close_file();
- }
-}
-
-void empty_static_vectors()
-{
-
- empty_vec_Agent();
- empty_vec_Channel_Agent();
- empty_vec_Channel_Sensor();
- empty_vec_Sensors();
- empty_vec_csv_raders();
- empty_vec_linear_func_Blocks();
- empty_vec_TestBench();
-
- vec_of_Channels_for_Agents.clear();
- vec_of_Channels_for_Sensors.clear();
- vec_of_Sensors.clear();
- vec_of_csv_readers.clear();
- vec_of_linear_Function_Blocks.clear();
-}
-
-void empty_vec_Agent()
-{
- Agent* cur_Agent;
- unsigned int size_of_vec_Agent = vec_of_Agents.size();
- unsigned int index_Agent;
- for(index_Agent = 0; index_Agent < size_of_vec_Agent; index_Agent++){
- cur_Agent = vec_of_Agents[index_Agent];
- delete cur_Agent;
- }
- vec_of_Agents.clear();
-}
-
-void empty_vec_Channel_Agent()
-{
- Channel* cur_Channel;
- unsigned int size_of_vec_Chan_Agent = vec_of_Channels_for_Agents.size();
- unsigned int index_Channel;
- for(index_Channel = 0; index_Channel < size_of_vec_Chan_Agent; index_Channel++){
- cur_Channel = vec_of_Channels_for_Agents[index_Channel];
- //delete cur_Channel;
- }
- vec_of_Channels_for_Agents.clear();
-}
-
-void empty_vec_Channel_Sensor()
-{
- Channel* cur_Channel;
- unsigned int size_of_vec_Chan_Sensor = vec_of_Channels_for_Sensors.size();
- unsigned int index_Channel;
- for(index_Channel = 0; index_Channel < size_of_vec_Chan_Sensor; index_Channel++){
- cur_Channel = vec_of_Channels_for_Sensors[index_Channel];
- delete cur_Channel;
- }
- vec_of_Channels_for_Sensors.clear();
-}
-
-void empty_vec_Sensors()
-{
- Sensor* cur_Sensor;
- unsigned int size_of_vec_Chan_Sensor = vec_of_Sensors.size();
- unsigned int index_Sensor;
- for(index_Sensor = 0; index_Sensor < size_of_vec_Chan_Sensor; index_Sensor++){
- cur_Sensor = vec_of_Sensors[index_Sensor];
- delete cur_Sensor;
- }
- vec_of_Sensors.clear();
-}
-
-void empty_vec_csv_raders()
-{
- CSVreaderModule* cur_csv_reader;
- unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size();
- unsigned int index_csv_reader;
- for(index_csv_reader = 0; index_csv_reader < size_of_vec_csv_reader; index_csv_reader++){
- cur_csv_reader = vec_of_csv_readers[index_csv_reader];
- delete cur_csv_reader;
- }
- vec_of_csv_readers.clear();
-}
-
-void empty_vec_linear_func_Blocks()
-{
- LinearFunctionBlock* cur_lin_fun_block;
- unsigned int size_of_vec_lin_fun_block= vec_of_linear_Function_Blocks.size();
- unsigned int index_lin_fun_block;
- for(index_lin_fun_block = 0; index_lin_fun_block < size_of_vec_lin_fun_block; index_lin_fun_block++){
- cur_lin_fun_block = vec_of_linear_Function_Blocks[index_lin_fun_block];
- delete cur_lin_fun_block;
- }
- vec_of_linear_Function_Blocks.clear();
-}
-
-void empty_vec_TestBench()
-{
- Testbench* current_tb;
- unsigned int size_of_vec_test_benches = vec_of_test_benches.size();
- unsigned int index_tb = 0;
-
- for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++){
- current_tb = vec_of_test_benches[index_tb];
- current_tb->free_resources();
- delete current_tb;
- }
- vec_of_test_benches.clear();
-}
-
diff --git a/Version_Max_07_05_2018_CMake/src/main.cpp b/Version_Max_07_05_2018_CMake/src/main_backup.cpp
old mode 100755
new mode 100644
similarity index 99%
copy from Version_Max_07_05_2018_CMake/src/main.cpp
copy to Version_Max_07_05_2018_CMake/src/main_backup.cpp
index f3045be..75d87d9
--- a/Version_Max_07_05_2018_CMake/src/main.cpp
+++ b/Version_Max_07_05_2018_CMake/src/main_backup.cpp
@@ -1,1128 +1,1129 @@
/*
* main.cpp
*
* Created on: 25.05.2018
* Author: edwin willegger, edwin.willegger@tuwien.ac.at
* This file is used to generate output data from measurements
* from OMV for SAVE project.
* In this case the data of the 18.12.2017 is analyzed.
* Based on the implementation of Maximilian Götzinger.
*/
#include "Agent.h"
#include "Channel.h"
#include "create_unit.h"
#include "CSVreaderModule.h"
#include "inAgentsRegistrations.h"
#include "mount_nodes.h"
#include "register_in_testbench.h"
#include "Sensor.h"
#include "setupNode.h"
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include "Testbench.h"
#include "file_util.h"
#include "LinearFunction.h"
#include "LinearFunctionBlock.h"
#include "Testbench_Config.h"
using namespace std;
/**********************************************************************************************************************
************************************************begin of global definitions of variables and constants ***************
**********************************************************************************************************************/
//every n-th SAMBLING value will be read in from the CSV-Data-Input-Files.
#define SAMPLING 1
//global vectors for the different elements
static vector<Agent*> vec_of_Agents;
static vector<Sensor*> vec_of_Sensors;
static vector<Channel*> vec_of_Channels_for_Sensors;
static vector<Channel*> vec_of_Channels_for_Agents;
static vector<LinearFunctionBlock*> vec_of_linear_Function_Blocks;
static vector<Testbench*> vec_of_test_benches;
static vector<CSVreaderModule*> vec_of_csv_readers;
//names of the measured data
const string FIRST_MEASURED_DATA_NAME = "FC6504_Y"; //Input
const string SECOND_MEASURED_DATA_NAME = "FC6504"; //Output
const string THIRD_MEASURED_DATA_NAME = "FC6504_SP"; //Input
const string FOURTH_MEASURED_DATA_NAME = "PI6584"; //Input
//viability monitor
const string VIABILITY_MONITOR = "ViabilityMonitor";
//index number of output
const int INDEX_OUTPUT = 1;
//name for the channels of the sensors and agents
const string APPENDIX_FOR_CHANNEL_SENSOR_NAME = "(SA)";
const string FIRST_MEASURED_CHANNEL_SENSOR_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME;
const string SECOND_MEASURED_CHANNEL_SENSOR_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME;
const string THIRD_MEASURED_CHANNEL_SENSOR_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME;
const string FOURTH_MEASURED_CHANNEL_SENSOR_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_SENSOR_NAME;
const string APPENDIX_FOR_CHANNEL_AGENT_NAME = "(AA-UP)";
const string FIRST_MEASURED_CHANNEL_AGENT_NAME = FIRST_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME;
const string SECOND_MEASURED_CHANNEL_AGENT_NAME = SECOND_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME;
const string THIRD_MEASURED_CHANNEL_AGENT_NAME = THIRD_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME;
const string FOURTH_MEASURED_CHANNEL_AGENT_NAME = FOURTH_MEASURED_DATA_NAME + APPENDIX_FOR_CHANNEL_AGENT_NAME;
#define TRANSFER_RATE_CHANNEL_SENSOR 0
#define TRANSFER_RATE_CHANNEL_AGENT MAX_BUFFER_LENGTH
//////////////////////////////////////////////
/*
//out of the outer_bound the function is 0 or 1 and within 1 or 0 depending on function or complementery.
inner_bound_xxx = /----------=1----|------=1---------\ = inner_bound_xxxx
outer_bound_xxx = / | \
/ | \
0=__________/ | \ = outer_bound_xxxx ______ = 0
--------------------------------------------------------------------------
*/
//parameters of boundary for similar function
#define OUTTER_BOUND_SIM_DIF 0.20 //outer bound e. g. 0.14 = 14 percent; testested with 0.20, 0.14, 0.06,
#define INNER_BOUND_SIM_DIF 0.01 //inner bound e. g. 0.01 = 1 percent
//same way as above but shows drift.
#define OUTTER_BOUND_DRIFT OUTTER_BOUND_SIM_DIF * 3
#define INNER_BOUND_DRIFT OUTTER_BOUND_SIM_DIF
//timer sagt, dass nach dem DOWNSAMPLING der Ausgang bis zu
//n Werte später sich ändern darf, nachdem Sich der Eingang geändert hat.
#define BOUND_BROKEN 2
//length where fuzzy function raises from 0 to 1 or 1 to 0 for the complementery.
//history of the data depends of it, and should change, if it changes.
#define LENGTH 10
//definitions for the testbench
const string TEST_BENCH = "testbench";
//defintions for the csv-reader-modules
const string APPENDIX_CSV_MODULES = " CSV-Reader";
const string FIRST_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES;
const string SECOND_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES;
const string THIRD_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES;
const string FOURTH_MEASURED_DATA_CSV_NAME = FILE_NAME_OF_ENTIRE_DATA + APPENDIX_CSV_MODULES;
//to switch between different file configurations change the
//DEFINES in file_util.h
/**********************************************************************************************************************
************************************************end of global definitions of variables and constants *****************
**********************************************************************************************************************/
/**********************************************************************************************************************
************************************************begin of function prototypes *****************************************
**********************************************************************************************************************/
void create_and_register_all_Testbench_Configs(Testbench* current_tb);
void create_and_register_All_Agents();
void set_working_cycle_of_All_Agents();
void create_and_register_All_Sensors();
void set_working_cycle_of_All_Sensors();
void create_and_register_channels();
void create_and_register_channels_for_sensors();
void create_and_register_channels_for_agents();
void mount_sensors_in_agents();
void mount_agents_in_agents();
void register_data_agents_in_agent_state_Handler();
void create_linear_function_blocks();
void create_same_state_deviation_function_block();
void create_another_state_deviation_function_block();
void create_state_time_function_block();
void create_another_state_time_function_block();
void create_valid_state_deviation_function_block();
void create_invalid_state_deviation_function_block();
void create_valid_state_time_function_block();
void create_invalid_state_time_function_block();
void create_confidence_state_drift_function_block();
void create_confidence_broken_function_block();
void mount_function_blocks_to_viability_monitor();
void create_all_testbenches();
void create_csvr_modules();
void register_agents_in_testbenches();
void register_sensors_in_testbenches();
void register_channels_in_testbenches();
void register_channels_of_sensors_in_testbenches();
void register_channels_of_actors_in_testbenches();
void set_config_values_in_linear_functions(Testbench* current_tb);
void set_parameters_LinearFunctionBlock(LinearFunctionBlock* cur_lin_func_block);
void set_parameters_LinearFunction(vector<LinearFunction*> vec_Lin_Func);
void set_CSV_Writer_parameter(Testbench* current_tb);
void run_simulation_of_all_testbenches();
void close_file_pointers();
void empty_static_vectors();
void empty_vec_Agent();
void empty_vec_Channel_Agent();
void empty_vec_Channel_Sensor();
void empty_vec_Sensors();
void empty_vec_csv_raders();
void empty_vec_linear_func_Blocks();
void empty_vec_TestBench();
/**********************************************************************************************************************
************************************************end of function prototypes *******************************************
**********************************************************************************************************************/
int main()
{
+
cout << "This program processes test data from OMV Steam Cracker furnaces." << endl;
create_and_register_All_Agents();
set_working_cycle_of_All_Agents();
create_and_register_All_Sensors();
set_working_cycle_of_All_Sensors();
create_and_register_channels();
mount_sensors_in_agents();
mount_agents_in_agents();
register_data_agents_in_agent_state_Handler();
create_linear_function_blocks();
mount_function_blocks_to_viability_monitor();
create_all_testbenches();
create_csvr_modules();
register_agents_in_testbenches();
register_sensors_in_testbenches();
register_channels_in_testbenches();
run_simulation_of_all_testbenches();
//close_file_pointers();
//TODO memory free of all objects.
empty_static_vectors();
cout << "Program finished successfully" << endl;
return 0;
}
void create_and_register_all_Testbench_Configs(Testbench* current_tb)
{
One_Config_t one;
one.bound_broken = 2;
one.inner_bound_sim_dif = 0.02;
one.outter_bound_sim_dif = 0.08;
one.inner_bound_drift = 3 * one.outter_bound_sim_dif;
one.inner_bound_drift = one.outter_bound_sim_dif;
one.length = 10;
Testbench_Config* cfg = new Testbench_Config(one);
cfg->print();
current_tb->register_testbench_config(cfg);
}
/*
* creates all the agents used in the measurement
* and stores them into the global vector
*/
void create_and_register_All_Agents()
{
cout << "Creating Agents" << endl;
char* c_name_of_current_agent = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_agent, FIRST_MEASURED_DATA_NAME.c_str());
Agent* a_FC6504_Y = create_agent(c_name_of_current_agent);
strcpy(c_name_of_current_agent, SECOND_MEASURED_DATA_NAME.c_str());
Agent* a_FC6504 = create_agent(c_name_of_current_agent);
strcpy(c_name_of_current_agent, THIRD_MEASURED_DATA_NAME.c_str());
Agent* a_FC6504_SP = create_agent(c_name_of_current_agent);
strcpy(c_name_of_current_agent, FOURTH_MEASURED_DATA_NAME.c_str());
Agent* a_PI6584 = create_agent(c_name_of_current_agent);
strcpy(c_name_of_current_agent, VIABILITY_MONITOR.c_str());
Agent* a_viabilityMonitor = create_agent(c_name_of_current_agent);
vec_of_Agents.push_back(a_FC6504_Y);
vec_of_Agents.push_back(a_FC6504);
vec_of_Agents.push_back(a_FC6504_SP);
vec_of_Agents.push_back(a_PI6584);
vec_of_Agents.push_back(a_viabilityMonitor);
cout << vec_of_Agents.size() << " agents were created" << endl;
delete c_name_of_current_agent;
}
/*
* the working_cycle for all registered agents is set
*/
void set_working_cycle_of_All_Agents()
{
unsigned int working_Cyle = SAMPLING;
unsigned int size_of_vec_of_Agents = 0;
unsigned int index = 0;
Agent* current_Agent;
size_of_vec_of_Agents = vec_of_Agents.size();
for(index = 0; index < size_of_vec_of_Agents; index++) {
current_Agent = vec_of_Agents[index];
setWorkingCycleOfAgent(current_Agent, working_Cyle);
}
}
/*
* all necessary sensors are created and registered
*/
void create_and_register_All_Sensors()
{
cout << "Creating Sensors" << endl;
char* c_name_of_current_sensor = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_sensor, FIRST_MEASURED_DATA_NAME.c_str());
Sensor* s_FC6504_Y = create_sensor(c_name_of_current_sensor);
strcpy(c_name_of_current_sensor, SECOND_MEASURED_DATA_NAME.c_str());
Sensor* s_FC6504 = create_sensor(c_name_of_current_sensor);
strcpy(c_name_of_current_sensor, THIRD_MEASURED_DATA_NAME.c_str());
Sensor* s_FC6504_SP = create_sensor(c_name_of_current_sensor);
strcpy(c_name_of_current_sensor, FOURTH_MEASURED_DATA_NAME.c_str());
Sensor* s_PI6584 = create_sensor(c_name_of_current_sensor);
vec_of_Sensors.push_back(s_FC6504_Y);
vec_of_Sensors.push_back(s_FC6504);
vec_of_Sensors.push_back(s_FC6504_SP);
vec_of_Sensors.push_back(s_PI6584);
cout << vec_of_Sensors.size() << " sensors were created." << endl;
delete c_name_of_current_sensor;
}
/*
* working cycle of all registered sensors is set
*/
void set_working_cycle_of_All_Sensors()
{
unsigned int working_Cyle = SAMPLING;
unsigned int size_of_vec_of_Sensors = 0;
unsigned int index = 0;
Sensor* current_Sensor;
size_of_vec_of_Sensors = vec_of_Sensors.size();
for(index = 0; index < size_of_vec_of_Sensors; index++) {
current_Sensor = vec_of_Sensors[index];
setWorkingCycleOfSensor(current_Sensor, working_Cyle);
}
}
/*
* creating and registering all channels
*/
void create_and_register_channels()
{
create_and_register_channels_for_sensors();
create_and_register_channels_for_agents();
}
/*
* creating and registering the channels for the sensors.
*/
void create_and_register_channels_for_sensors()
{
cout << "Creating and registering channels for sensors" << endl;
char* c_name_of_current_channel = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_channel, FIRST_MEASURED_CHANNEL_SENSOR_NAME.c_str());
Channel* c_sa_FC6504_Y = create_channel(c_name_of_current_channel, 0);
strcpy(c_name_of_current_channel, SECOND_MEASURED_CHANNEL_SENSOR_NAME.c_str());
Channel* c_sa_FC6504 = create_channel(c_name_of_current_channel, 0);
strcpy(c_name_of_current_channel, THIRD_MEASURED_CHANNEL_SENSOR_NAME.c_str());
Channel* c_sa_FC6504_SP = create_channel(c_name_of_current_channel, 0);
strcpy(c_name_of_current_channel, FOURTH_MEASURED_CHANNEL_SENSOR_NAME.c_str());
Channel* c_sa_PI6584 = create_channel(c_name_of_current_channel, 0);
vec_of_Channels_for_Sensors.push_back(c_sa_FC6504_Y);
vec_of_Channels_for_Sensors.push_back(c_sa_FC6504);
vec_of_Channels_for_Sensors.push_back(c_sa_FC6504_SP);
vec_of_Channels_for_Sensors.push_back(c_sa_PI6584);
cout << vec_of_Channels_for_Sensors.size() << " channels for sensors were created" << endl;
delete c_name_of_current_channel;
}
/*
* creating and registering the channels for the agents
*/
void create_and_register_channels_for_agents()
{
cout << "Creating and registering channels for agents" << endl;
char* c_name_of_current_channel = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_channel, FIRST_MEASURED_CHANNEL_AGENT_NAME.c_str());
Channel* c_aa_FC6504_Y = create_channel(c_name_of_current_channel, MAX_BUFFER_LENGTH);
strcpy(c_name_of_current_channel, SECOND_MEASURED_CHANNEL_AGENT_NAME.c_str());
Channel* c_aa_FC6504 = create_channel(c_name_of_current_channel, MAX_BUFFER_LENGTH);
strcpy(c_name_of_current_channel, THIRD_MEASURED_CHANNEL_AGENT_NAME.c_str());
Channel* c_aa_FC6504_SP = create_channel(c_name_of_current_channel, MAX_BUFFER_LENGTH);
strcpy(c_name_of_current_channel, FOURTH_MEASURED_CHANNEL_AGENT_NAME.c_str());
Channel* c_aa_PI6584 = create_channel(c_name_of_current_channel, MAX_BUFFER_LENGTH);
vec_of_Channels_for_Agents.push_back(c_aa_FC6504_Y);
vec_of_Channels_for_Agents.push_back(c_aa_FC6504);
vec_of_Channels_for_Agents.push_back(c_aa_FC6504_SP);
vec_of_Channels_for_Agents.push_back(c_aa_PI6584);
cout << vec_of_Channels_for_Agents.size() << " channels for agents were created" << endl;
delete c_name_of_current_channel;
}
void mount_sensors_in_agents()
{
Agent* current_agent;
Sensor* current_sensor;
Channel* current_sensor_channel;
unsigned int size_of_vec_sensor = 0;
unsigned int index = 0;
size_of_vec_sensor = vec_of_Sensors.size();
cout << "mounting sensors in agents." << endl;
//it is assumed that the corresponding sensors and agents and channels are always at the same
//position in the different vectors, if not then you have to add an search algorithm for it.
for(index = 0; index < size_of_vec_sensor; index++)
{
current_agent = vec_of_Agents[index];
current_sensor = vec_of_Sensors[index];
current_sensor_channel = vec_of_Channels_for_Sensors[index];
mount_sensorInAgent(current_agent, current_sensor, current_sensor_channel);
}
cout << size_of_vec_sensor << " sensors in agents were mounted" << endl;
}
void mount_agents_in_agents()
{
Agent* current_agent;
Agent* viability_Monitor;
Channel* current_agent_channel;
unsigned int size_of_vec_agents = 0;
unsigned int index = 0;
size_of_vec_agents = vec_of_Agents.size();
//it is assumed that the viability agent is at the last position in the vector
viability_Monitor = vec_of_Agents[size_of_vec_agents-1];
//all agents and channels are registered to the viabilityMonitor agent
//so you have to subtract the viabilityMonitor from the number of elements to register
//it is assumed that all the corresponding channels and agents are placed at the same index
for(index = 0; index < size_of_vec_agents -1; index++)
{
current_agent = vec_of_Agents[index];
current_agent_channel = vec_of_Channels_for_Agents[index];
//only register if the agent is not the viability_monitor, otherwise you would register the viability monitor to itself.
if(current_agent != viability_Monitor) {
mount_agentInAgent(viability_Monitor, current_agent, current_agent_channel);
}
}
cout << size_of_vec_agents -1 << "agents were registered to the viability monitor" << endl;
}
/*
* registers the channels for the data agents to the viability monitor
*/
void register_data_agents_in_agent_state_Handler()
{
Agent* viability_Monitor;
Channel* current_agent_channel;
unsigned int size_of_vec_channel_agents = 0;
unsigned int index = 0;
size_of_vec_channel_agents = vec_of_Channels_for_Agents.size();
//get the agent for the viabilityMonitor, it is assumed that it is at the last position
viability_Monitor = vec_of_Agents[vec_of_Agents.size()-1];
//register all the channels to the viability monitor
for(index = 0; index < size_of_vec_channel_agents; index++) {
current_agent_channel = vec_of_Channels_for_Agents[index];
if(index != INDEX_OUTPUT) {
registerSlaveAgentAsInputVariableInStateHandler(viability_Monitor, current_agent_channel);
}
else{
registerSlaveAgentAsOutputVariableInStateHandler(viability_Monitor, current_agent_channel);
}
}
}
/*
* creates and register all the different linear function blocks
*/
void create_linear_function_blocks()
{
//don't change the sequence, because later it is assumed that the functions are
//registered int the vector in this sequence
//if you change it you have also to change the sequence in the function mount_function_blocks_to_viability_monitor
create_same_state_deviation_function_block();
create_another_state_deviation_function_block();
create_state_time_function_block();
create_another_state_time_function_block();
create_valid_state_deviation_function_block();
create_invalid_state_deviation_function_block();
create_valid_state_time_function_block();
create_invalid_state_time_function_block();
create_confidence_state_drift_function_block();
create_confidence_broken_function_block();
}
/*
* creates and register the linear function block for same state deviation
*/
void create_same_state_deviation_function_block()
{
char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_SAME_STATE_DEV.c_str());
LinearFunctionBlock* confSim2StateDev = new LinearFunctionBlock(c_name_of_current_func_block);
LinearFunction* funcConfSim2StateDev1 = new LinearFunction(CONF_SIM2_STATE_DEV_1);
funcConfSim2StateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF);
funcConfSim2StateDev1->setKandD((float)0, (float)0);
confSim2StateDev->addLinearFunction(funcConfSim2StateDev1);
LinearFunction* funcConfSim2StateDev2 = new LinearFunction(CONF_SIM2_STATE_DEV_2);
funcConfSim2StateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF);
funcConfSim2StateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)0, (float)-INNER_BOUND_SIM_DIF, (float)1);
confSim2StateDev->addLinearFunction(funcConfSim2StateDev2);
LinearFunction* funcConfSim2StateDev3 = new LinearFunction(CONF_SIM2_STATE_DEV_3);
funcConfSim2StateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF);
funcConfSim2StateDev3->setKandD((float)0, (float)1);
confSim2StateDev->addLinearFunction(funcConfSim2StateDev3);
LinearFunction* funcConfSim2StateDev4 = new LinearFunction(CONF_SIM2_STATE_DEV_4);
funcConfSim2StateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF);
funcConfSim2StateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)1, (float)OUTTER_BOUND_SIM_DIF, (float)0);
confSim2StateDev->addLinearFunction(funcConfSim2StateDev4);
LinearFunction* funcConfSim2StateDev5 = new LinearFunction(CONF_SIM2_STATE_DEV_5);
funcConfSim2StateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false);
funcConfSim2StateDev5->setKandD((float)0, (float)0);
confSim2StateDev->addLinearFunction(funcConfSim2StateDev5);
vec_of_linear_Function_Blocks.push_back(confSim2StateDev);
delete c_name_of_current_func_block;
}
/*
* creates and register another state deviation function block
*/
void create_another_state_deviation_function_block()
{
char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_ANOTHER_STATE_DEV.c_str());
LinearFunctionBlock* confDif2StateDev = new LinearFunctionBlock(c_name_of_current_func_block);
LinearFunction* funcConfDif2StateDev1 = new LinearFunction(CONF_DIF2_STATE_DEV_1);
funcConfDif2StateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF);
funcConfDif2StateDev1->setKandD((float)0, (float)1);
confDif2StateDev->addLinearFunction(funcConfDif2StateDev1);
LinearFunction* funcConfDif2StateDev2 = new LinearFunction(CONF_DIF2_STATE_DEV_2);
funcConfDif2StateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF);
funcConfDif2StateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)1, (float)-INNER_BOUND_SIM_DIF, (float)0);
confDif2StateDev->addLinearFunction(funcConfDif2StateDev2);
LinearFunction* funcConfDif2StateDev3 = new LinearFunction(CONF_DIF2_STATE_DEV_3);
funcConfDif2StateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF);
funcConfDif2StateDev3->setKandD((float)0, (float)0);
confDif2StateDev->addLinearFunction(funcConfDif2StateDev3);
LinearFunction* funcConfDif2StateDev4 = new LinearFunction(CONF_DIF2_STATE_DEV_4);
funcConfDif2StateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF);
funcConfDif2StateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)0, (float)OUTTER_BOUND_SIM_DIF, (float)1);
confDif2StateDev->addLinearFunction(funcConfDif2StateDev4);
LinearFunction* funcConfDif2StateDev5 = new LinearFunction(CONF_DIF2_STATE_DEV_5);
funcConfDif2StateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false);
funcConfDif2StateDev5->setKandD((float)0, (float)1);
confDif2StateDev->addLinearFunction(funcConfDif2StateDev5);
vec_of_linear_Function_Blocks.push_back(confDif2StateDev);
delete c_name_of_current_func_block;
}
void create_state_time_function_block()
{
char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_SAME_TIME.c_str());
LinearFunctionBlock* confSim2StateTime = new LinearFunctionBlock(c_name_of_current_func_block);
LinearFunction* funcConfSim2StateTime1 = new LinearFunction(CONF_SIM2_STATE_TIME_1);
funcConfSim2StateTime1->setDomain(false, true, (float)0);
funcConfSim2StateTime1->setKandD((float)0, (float)0);
confSim2StateTime->addLinearFunction(funcConfSim2StateTime1);
LinearFunction* funcConfSim2StateTime2 = new LinearFunction(CONF_SIM2_STATE_TIME_2);
funcConfSim2StateTime2->setDomain(true, (float)0, true, (float)LENGTH);
funcConfSim2StateTime2->setKandD((float)0, (float)0, (float)LENGTH, (float)1);
confSim2StateTime->addLinearFunction(funcConfSim2StateTime2);
LinearFunction* funcConfSim2StateTime3 = new LinearFunction(CONF_SIM2_STATE_TIME_3);
funcConfSim2StateTime3->setDomain(true, (float)LENGTH, false);
funcConfSim2StateTime3->setKandD((float)0, (float)1);
confSim2StateTime->addLinearFunction(funcConfSim2StateTime3);
vec_of_linear_Function_Blocks.push_back(confSim2StateTime);
delete c_name_of_current_func_block;
}
void create_another_state_time_function_block()
{
char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_ANOTHER_STATE_TIME.c_str());
LinearFunctionBlock* confDif2StateTime = new LinearFunctionBlock(c_name_of_current_func_block);
LinearFunction* funcConfDif2StateTime1 = new LinearFunction(CONF_DIF2_STATE_TIME_1);
funcConfDif2StateTime1->setDomain(false, true, (float)0);
funcConfDif2StateTime1->setKandD((float)0, (float)1);
confDif2StateTime->addLinearFunction(funcConfDif2StateTime1);
LinearFunction* funcConfDif2StateTime2 = new LinearFunction(CONF_DIF2_STATE_TIME_2);
funcConfDif2StateTime2->setDomain(true, (float)0, true, (float)LENGTH);
funcConfDif2StateTime2->setKandD((float)0, (float)1, (float)LENGTH, (float)0);
confDif2StateTime->addLinearFunction(funcConfDif2StateTime2);
LinearFunction* funcConfDif2StateTime3 = new LinearFunction(CONF_DIF2_STATE_TIME_3);
funcConfDif2StateTime3->setDomain(true, (float)LENGTH, false);
funcConfDif2StateTime3->setKandD((float)0, (float)0);
confDif2StateTime->addLinearFunction(funcConfDif2StateTime3);
vec_of_linear_Function_Blocks.push_back(confDif2StateTime);
delete c_name_of_current_func_block;
}
void create_valid_state_deviation_function_block()
{
char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_VAILD_STATE_DEV.c_str());
LinearFunctionBlock* confValidStateDev = new LinearFunctionBlock(c_name_of_current_func_block);
LinearFunction* funcConfValidStateDev1 = new LinearFunction(CONF_VALID_STATE_DEV_1);
funcConfValidStateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF);
funcConfValidStateDev1->setKandD((float)0, (float)0);
confValidStateDev->addLinearFunction(funcConfValidStateDev1);
LinearFunction* funcConfValidStateDev2 = new LinearFunction(CONF_VALID_STATE_DEV_2);
funcConfValidStateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF);
funcConfValidStateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)0, (float)-INNER_BOUND_SIM_DIF, (float)1);
confValidStateDev->addLinearFunction(funcConfValidStateDev2);
LinearFunction* funcConfValidStateDev3 = new LinearFunction(CONF_VALID_STATE_DEV_3);
funcConfValidStateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF);
funcConfValidStateDev3->setKandD((float)0, (float)1);
confValidStateDev->addLinearFunction(funcConfValidStateDev3);
LinearFunction* funcConfValidStateDev4 = new LinearFunction(CONF_VALID_STATE_DEV_4);
funcConfValidStateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF);
funcConfValidStateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)1, (float)OUTTER_BOUND_SIM_DIF, (float)0);
confValidStateDev->addLinearFunction(funcConfValidStateDev4);
LinearFunction* funcConfValidStateDev5 = new LinearFunction(CONF_VALID_STATE_DEV_5);
funcConfValidStateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false);
funcConfValidStateDev5->setKandD((float)0, (float)0);
confValidStateDev->addLinearFunction(funcConfValidStateDev5);
vec_of_linear_Function_Blocks.push_back(confValidStateDev);
delete c_name_of_current_func_block;
}
void create_invalid_state_deviation_function_block()
{
char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_INVALID_STATE_DEV.c_str());
LinearFunctionBlock* confInvalidStateDev = new LinearFunctionBlock(c_name_of_current_func_block);
LinearFunction* funcConfInvalidStateDev1 = new LinearFunction(CONF_INVALID_STATE_DEV_1);
funcConfInvalidStateDev1->setDomain(false, true, (float)-OUTTER_BOUND_SIM_DIF);
funcConfInvalidStateDev1->setKandD((float)0, (float)1);
confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev1);
LinearFunction* funcConfInvalidStateDev2 = new LinearFunction(CONF_INVALID_STATE_DEV_2);
funcConfInvalidStateDev2->setDomain(true, (float)-OUTTER_BOUND_SIM_DIF, true, (float)-INNER_BOUND_SIM_DIF);
funcConfInvalidStateDev2->setKandD((float)-OUTTER_BOUND_SIM_DIF, (float)1, (float)-INNER_BOUND_SIM_DIF, (float)0);
confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev2);
LinearFunction* funcConfInvalidStateDev3 = new LinearFunction(CONF_INVALID_STATE_DEV_3);
funcConfInvalidStateDev3->setDomain(true, (float)-INNER_BOUND_SIM_DIF, true, (float)INNER_BOUND_SIM_DIF);
funcConfInvalidStateDev3->setKandD((float)0, (float)0);
confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev3);
LinearFunction* funcConfInvalidStateDev4 = new LinearFunction(CONF_INVALID_STATE_DEV_4);
funcConfInvalidStateDev4->setDomain(true, (float)INNER_BOUND_SIM_DIF, true, (float)OUTTER_BOUND_SIM_DIF);
funcConfInvalidStateDev4->setKandD((float)INNER_BOUND_SIM_DIF, (float)0, (float)OUTTER_BOUND_SIM_DIF, (float)1);
confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev4);
LinearFunction* funcConfInvalidStateDev5 = new LinearFunction(CONF_INVALID_STATE_DEV_5);
funcConfInvalidStateDev5->setDomain(true, (float)OUTTER_BOUND_SIM_DIF, false);
funcConfInvalidStateDev5->setKandD((float)0, (float)1);
confInvalidStateDev->addLinearFunction(funcConfInvalidStateDev5);
vec_of_linear_Function_Blocks.push_back(confInvalidStateDev);
delete c_name_of_current_func_block;
}
void create_valid_state_time_function_block()
{
char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_VALID_STATE_TIME.c_str());
LinearFunctionBlock* confValidStateTime = new LinearFunctionBlock(c_name_of_current_func_block);
LinearFunction* funcConfValidStateTime1 = new LinearFunction(VALID_STATE_TIME_1);
funcConfValidStateTime1->setDomain(false, true, (float)0);
funcConfValidStateTime1->setKandD((float)0, (float)0);
confValidStateTime->addLinearFunction(funcConfValidStateTime1);
LinearFunction* funcConfValidStateTime2 = new LinearFunction(VALID_STATE_TIME_2);
funcConfValidStateTime2->setDomain(true, (float)0, true, (float)LENGTH); //10
funcConfValidStateTime2->setKandD((float)0, (float)0, (float)LENGTH, (float)1);
confValidStateTime->addLinearFunction(funcConfValidStateTime2);
LinearFunction* funcConfValidStateTime3 = new LinearFunction(VALID_STATE_TIME_3);
funcConfValidStateTime3->setDomain(true, (float)LENGTH, false);
funcConfValidStateTime3->setKandD((float)0, (float)1);
confValidStateTime->addLinearFunction(funcConfValidStateTime3);
vec_of_linear_Function_Blocks.push_back(confValidStateTime);
delete c_name_of_current_func_block;
}
void create_invalid_state_time_function_block()
{
char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_INVALID_STATE_TIME.c_str());
LinearFunctionBlock* confInvalidStateTime = new LinearFunctionBlock(c_name_of_current_func_block);
LinearFunction* funcConfInvalidStateTime1 = new LinearFunction(INVALID_STATE_TIME_1);
funcConfInvalidStateTime1->setDomain(false, true, (float)0);
funcConfInvalidStateTime1->setKandD((float)0, (float)1);
confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime1);
LinearFunction* funcConfInvalidStateTime2 = new LinearFunction(INVALID_STATE_TIME_2);
funcConfInvalidStateTime2->setDomain(true, (float)0, true, (float)LENGTH);
funcConfInvalidStateTime2->setKandD((float)0, (float)1, (float)LENGTH, (float)0);
confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime2);
LinearFunction* funcConfInvalidStateTime3 = new LinearFunction(INVALID_STATE_TIME_3);
funcConfInvalidStateTime3->setDomain(true, (float)LENGTH, false);
funcConfInvalidStateTime3->setKandD((float)0, (float)0);
confInvalidStateTime->addLinearFunction(funcConfInvalidStateTime3);
vec_of_linear_Function_Blocks.push_back(confInvalidStateTime);
delete c_name_of_current_func_block;
}
void create_confidence_state_drift_function_block()
{
char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_CONFIDENCE_STATE_DRIFTS.c_str());
LinearFunctionBlock* confStateDrifts = new LinearFunctionBlock(c_name_of_current_func_block);
LinearFunction* functionConfidenceDriftDeviation1 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_1);
functionConfidenceDriftDeviation1->setDomain(false, true, (float)-OUTTER_BOUND_DRIFT);
functionConfidenceDriftDeviation1->setKandD((float)0, (float)1);
confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation1);
LinearFunction* functionConfidenceDriftDeviation2 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_2);
functionConfidenceDriftDeviation2->setDomain(true, (float)-OUTTER_BOUND_DRIFT, true, (float)-INNER_BOUND_DRIFT);
functionConfidenceDriftDeviation2->setKandD((float)-INNER_BOUND_DRIFT, (float)1, (float)-INNER_BOUND_DRIFT, (float)0);
confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation2);
LinearFunction* functionConfidenceDriftDeviation3 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_3);
functionConfidenceDriftDeviation3->setDomain(true, (float)-INNER_BOUND_DRIFT, true, (float)INNER_BOUND_DRIFT);
functionConfidenceDriftDeviation3->setKandD((float)0, (float)0);
confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation3);
LinearFunction* functionConfidenceDriftDeviation4 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_4);
functionConfidenceDriftDeviation4->setDomain(true, (float)INNER_BOUND_DRIFT, true, (float)OUTTER_BOUND_DRIFT);
functionConfidenceDriftDeviation4->setKandD((float)INNER_BOUND_DRIFT, (float)0, (float)OUTTER_BOUND_DRIFT, (float)1);
confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation4);
LinearFunction* functionConfidenceDriftDeviation5 = new LinearFunction(CONFIDENCE_DRIFT_DEVIATION_5);
functionConfidenceDriftDeviation5->setDomain(true, (float)OUTTER_BOUND_DRIFT, false);
functionConfidenceDriftDeviation5->setKandD((float)0, (float)1);
confStateDrifts->addLinearFunction(functionConfidenceDriftDeviation5);
vec_of_linear_Function_Blocks.push_back(confStateDrifts);
delete c_name_of_current_func_block;
}
void create_confidence_broken_function_block()
{
char* c_name_of_current_func_block = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_func_block, FUNC_BLOCK_NAME_CONFIDENCE_BROKEN.c_str());
LinearFunctionBlock* confBroken = new LinearFunctionBlock(c_name_of_current_func_block);
LinearFunction* functionConfidenceBroken1 = new LinearFunction(CONFIDENCE_BROKEN_1);
functionConfidenceBroken1->setDomain(false, true, (float)0);
functionConfidenceBroken1->setKandD((float)0, (float)0);
confBroken->addLinearFunction(functionConfidenceBroken1);
LinearFunction* functionConfidenceBroken2 = new LinearFunction(CONFIDENCE_BROKEN_2);
functionConfidenceBroken2->setDomain(true, (float)0, true, (float)BOUND_BROKEN);
functionConfidenceBroken2->setKandD((float)0, (float)0, (float)BOUND_BROKEN, (float)1);
confBroken->addLinearFunction(functionConfidenceBroken2);
LinearFunction* functionConfidenceBroken3 = new LinearFunction(CONFIDENCE_BROKEN_3);
functionConfidenceBroken3->setDomain(true, (float)BOUND_BROKEN, false);
functionConfidenceBroken3->setKandD((float)0, (float)1);
confBroken->addLinearFunction(functionConfidenceBroken3);
vec_of_linear_Function_Blocks.push_back(confBroken);
delete c_name_of_current_func_block;
}
/*
* mount the different function blocks to the viability monitor agent
*/
void mount_function_blocks_to_viability_monitor()
{
Agent* viability_Monitor;
LinearFunctionBlock* current_Linear_Function_Bock;
unsigned int size_of_vec_lin_func_block = vec_of_linear_Function_Blocks.size();
unsigned int index = 0;
//it is assumed that the viability monitor is at the last position of the vector of agents
viability_Monitor = vec_of_Agents[vec_of_Agents.size()-1];
for(index = 0; index < size_of_vec_lin_func_block; index++) {
current_Linear_Function_Bock = vec_of_linear_Function_Blocks[index];
//it is assumed that the function blocks are added into the vector in the following sequence
switch(index) {
case 0:
viability_Monitor->get_stateHandler()->FuncBlockConfSim2StateDev = current_Linear_Function_Bock;
break;
case 1:
viability_Monitor->get_stateHandler()->FuncBlockConfDif2StateDev = current_Linear_Function_Bock;
break;
case 2:
viability_Monitor->get_stateHandler()->FuncBlockConfSim2StateTime = current_Linear_Function_Bock;
break;
case 3:
viability_Monitor->get_stateHandler()->FuncBlockConfDif2StateTime = current_Linear_Function_Bock;
break;
case 4:
viability_Monitor->get_stateHandler()->FuncBlockConfValStateDev = current_Linear_Function_Bock;
break;
case 5:
viability_Monitor->get_stateHandler()->FuncBlockConfInvStateDev = current_Linear_Function_Bock;
break;
case 6:
viability_Monitor->get_stateHandler()->FuncBlockConfValStateTime = current_Linear_Function_Bock;
break;
case 7:
viability_Monitor->get_stateHandler()->FuncBlockConfInvStateTime = current_Linear_Function_Bock;
break;
case 8:
viability_Monitor->get_stateHandler()->DriftDeviation = current_Linear_Function_Bock;
break;
case 9:
viability_Monitor->get_stateHandler()->FuncBlockConfBrokenSamples = current_Linear_Function_Bock;
break;
}
}
}
void create_all_testbenches() {
char* c_name_of_current_testbench = new char[MAX_LENGTH_NAME];
strcpy(c_name_of_current_testbench, TEST_BENCH.c_str());
cout << "Creating test bench" << endl;
Testbench* tb = create_testbench(c_name_of_current_testbench);
create_and_register_all_Testbench_Configs(tb);
vec_of_test_benches.push_back(tb);
delete c_name_of_current_testbench;
}
void create_csvr_modules()
{
//sets the row in which the data starts, maybe row one contains the headers
unsigned int row = 2;
char* c_name_of_current_csv_module = new char[MAX_LENGTH_NAME];
string current_reader_path_and_file_name;
cout << "Creating CSV Reader Modules" << endl;
current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA;
strcpy(c_name_of_current_csv_module, FIRST_MEASURED_DATA_CSV_NAME.c_str());
CSVreaderModule* csvr_FC6504_Y = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),3,row);
current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA;
strcpy(c_name_of_current_csv_module, SECOND_MEASURED_DATA_CSV_NAME.c_str());
CSVreaderModule* csvr_FC6504 = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),4,row);
current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA;
strcpy(c_name_of_current_csv_module, THIRD_MEASURED_DATA_CSV_NAME.c_str());
CSVreaderModule* csvr_FC6504_SP = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),5,row);
current_reader_path_and_file_name = PATH_TO_CSV_DATA_FILES + PATH_TO_DATE_OF_MEASUREMENT + PATH_TO_AN_MEASURMENT + FILE_NAME_OF_ENTIRE_DATA;
strcpy(c_name_of_current_csv_module, FOURTH_MEASURED_DATA_CSV_NAME.c_str());
CSVreaderModule* csvr_PI6584 = create_CSVreaderModule(c_name_of_current_csv_module,current_reader_path_and_file_name.c_str(),6,row);
vec_of_csv_readers.push_back(csvr_FC6504_Y);
vec_of_csv_readers.push_back(csvr_FC6504);
vec_of_csv_readers.push_back(csvr_FC6504_SP);
vec_of_csv_readers.push_back(csvr_PI6584);
delete c_name_of_current_csv_module;
}
/*
* all agents would be registered to all testbenches
*/
void register_agents_in_testbenches()
{
Testbench* current_tb;
unsigned int size_of_vec_test_benches = vec_of_test_benches.size();
unsigned int index_tb = 0;
Agent* current_ag;
unsigned int size_of_vec_agents = vec_of_Agents.size();
unsigned int index_agents = 0;
cout << "registering agents in testbenches" << endl;
for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) {
current_tb = vec_of_test_benches[index_tb];
for(index_agents = 0; index_agents < size_of_vec_agents; index_agents++) {
current_ag = vec_of_Agents[index_agents];
register_agentInTestbench(current_tb, current_ag);
}
}
cout << size_of_vec_agents << " agents were registered in every of the " << size_of_vec_test_benches << " testbenches" << endl;
}
/*
* registering the sensors and the corresponding csv-readers in the testbenches
* it is assumed that the csv readers and the sensors are at the same index position
* in the vectors.
*/
void register_sensors_in_testbenches()
{
Testbench* current_tb;
unsigned int size_of_vec_test_benches = vec_of_test_benches.size();
unsigned int index_tb = 0;
Sensor* current_se;
unsigned int size_of_vec_sensors = vec_of_Sensors.size();
unsigned int index_sensors = 0;
CSVreaderModule* current_csv_reader;
unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size();
if(size_of_vec_csv_reader != size_of_vec_sensors) {
cout << "Error, in sequence of data processing";
cout << "Number of csv-readers should be equal to number of sensors" << endl;
}
else {
cout << "Registering sensors and their csv-readers in testbenches " << endl;
for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) {
current_tb = vec_of_test_benches[index_tb];
for(index_sensors = 0; index_sensors < size_of_vec_sensors; index_sensors++) {
current_se = vec_of_Sensors[index_sensors];
//it is assumed that the sensor and the corresponding csv-reader is stored
//at the same position in the two different vectors
current_csv_reader = vec_of_csv_readers[index_sensors];
register_sensorInTestbench(current_tb, current_se, current_csv_reader);
}
}
cout << size_of_vec_sensors << " Sensors and their csv-readers were registered to ";
cout << "every of the " << size_of_vec_test_benches << " testbenches" << endl;
}
}
void register_channels_in_testbenches()
{
register_channels_of_sensors_in_testbenches();
register_channels_of_actors_in_testbenches();
}
void register_channels_of_sensors_in_testbenches()
{
Testbench* current_tb;
unsigned int size_of_vec_test_benches = vec_of_test_benches.size();
unsigned int index_tb = 0;
Channel* current_se_ch;
unsigned int size_of_vec_se_channel = vec_of_Channels_for_Sensors.size();
unsigned int index_se_ch = 0;
cout << "Registering channels of sensors in testbench" << endl;
for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) {
current_tb = vec_of_test_benches[index_tb];
for(index_se_ch = 0; index_se_ch < size_of_vec_se_channel; index_se_ch++) {
current_se_ch = vec_of_Channels_for_Sensors[index_se_ch];
register_channelInTestbench(current_tb, current_se_ch);
}
}
cout << size_of_vec_se_channel << " channels of sensors were registered in ";
cout << size_of_vec_test_benches << " testbenches." << endl;
}
void register_channels_of_actors_in_testbenches()
{
Testbench* current_tb;
unsigned int size_of_vec_test_benches = vec_of_test_benches.size();
unsigned int index_tb = 0;
Channel* current_se_ch;
unsigned int size_of_vec_ag_channel = vec_of_Channels_for_Agents.size();
unsigned int index_se_ch = 0;
cout << "Registering channels of agents in testbench" << endl;
for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++) {
current_tb = vec_of_test_benches[index_tb];
for(index_se_ch = 0; index_se_ch < size_of_vec_ag_channel; index_se_ch++) {
current_se_ch = vec_of_Channels_for_Agents[index_se_ch];
register_channelInTestbench(current_tb, current_se_ch);
}
}
cout << size_of_vec_ag_channel << " channels of agents were registered in ";
cout << size_of_vec_test_benches << " testbenches." << endl;
}
void run_simulation_of_all_testbenches()
{
string pressed_key;
Testbench* current_tb;
vector<Testbench_Config*> vec_tb_configs;
Testbench_Config* current_tb_config;
unsigned int size_of_vec_test_benches = vec_of_test_benches.size();
unsigned int index_tb = 0;
unsigned int size_of_vec_test_bench_config;
unsigned int index_tb_cfg = 0;
unsigned int sim_rounds = -1;
const int start_row = 1;
if (FILE_NAME_OF_ENTIRE_DATA == "2017_01_07__05_46_fc6504.csv") {
sim_rounds = 720;
}
cout << "Press any key to start the simulation of all testbenches." << endl;
getline(cin, pressed_key);
for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++){
current_tb = vec_of_test_benches[index_tb];
index_tb_cfg = 0;
vec_tb_configs = current_tb->get_all_registered_testbench_configs();
size_of_vec_test_bench_config = vec_tb_configs.size();
for(index_tb_cfg = 0; index_tb_cfg < size_of_vec_test_bench_config; index_tb_cfg++){
current_tb_config = vec_tb_configs[index_tb_cfg];
current_tb->set_current_tb_config_index(index_tb_cfg);
current_tb->set_CSV_Writer_parameter();
current_tb->set_config_values_in_linear_functions();
//have to open new file first! with the CSV-Writer, for every round > 0
current_tb->simulate(sim_rounds);
if(index_tb_cfg < size_of_vec_test_bench_config - 1) {
current_tb->set_CSV_Reader_row(start_row);
current_tb->set_CSV_Reader_to_beginning();
current_tb->reset_States();
}
}
}
cout << "Simulation of " << size_of_vec_test_benches << " testbenches successfully finished" << endl;
}
void close_file_pointers()
{
CSVreaderModule* current_csv_reader;
unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size();
unsigned int index_csv_reader;
for(index_csv_reader = 0; index_csv_reader < size_of_vec_csv_reader; index_csv_reader++) {
current_csv_reader = vec_of_csv_readers[index_csv_reader];
current_csv_reader->close_file();
}
}
void empty_static_vectors()
{
empty_vec_Agent();
empty_vec_Channel_Agent();
empty_vec_Channel_Sensor();
empty_vec_Sensors();
empty_vec_csv_raders();
empty_vec_linear_func_Blocks();
empty_vec_TestBench();
vec_of_Channels_for_Agents.clear();
vec_of_Channels_for_Sensors.clear();
vec_of_Sensors.clear();
vec_of_csv_readers.clear();
vec_of_linear_Function_Blocks.clear();
}
void empty_vec_Agent()
{
Agent* cur_Agent;
unsigned int size_of_vec_Agent = vec_of_Agents.size();
unsigned int index_Agent;
for(index_Agent = 0; index_Agent < size_of_vec_Agent; index_Agent++){
cur_Agent = vec_of_Agents[index_Agent];
delete cur_Agent;
}
vec_of_Agents.clear();
}
void empty_vec_Channel_Agent()
{
Channel* cur_Channel;
unsigned int size_of_vec_Chan_Agent = vec_of_Channels_for_Agents.size();
unsigned int index_Channel;
for(index_Channel = 0; index_Channel < size_of_vec_Chan_Agent; index_Channel++){
cur_Channel = vec_of_Channels_for_Agents[index_Channel];
//delete cur_Channel;
}
vec_of_Channels_for_Agents.clear();
}
void empty_vec_Channel_Sensor()
{
Channel* cur_Channel;
unsigned int size_of_vec_Chan_Sensor = vec_of_Channels_for_Sensors.size();
unsigned int index_Channel;
for(index_Channel = 0; index_Channel < size_of_vec_Chan_Sensor; index_Channel++){
cur_Channel = vec_of_Channels_for_Sensors[index_Channel];
delete cur_Channel;
}
vec_of_Channels_for_Sensors.clear();
}
void empty_vec_Sensors()
{
Sensor* cur_Sensor;
unsigned int size_of_vec_Chan_Sensor = vec_of_Sensors.size();
unsigned int index_Sensor;
for(index_Sensor = 0; index_Sensor < size_of_vec_Chan_Sensor; index_Sensor++){
cur_Sensor = vec_of_Sensors[index_Sensor];
delete cur_Sensor;
}
vec_of_Sensors.clear();
}
void empty_vec_csv_raders()
{
CSVreaderModule* cur_csv_reader;
unsigned int size_of_vec_csv_reader = vec_of_csv_readers.size();
unsigned int index_csv_reader;
for(index_csv_reader = 0; index_csv_reader < size_of_vec_csv_reader; index_csv_reader++){
cur_csv_reader = vec_of_csv_readers[index_csv_reader];
delete cur_csv_reader;
}
vec_of_csv_readers.clear();
}
void empty_vec_linear_func_Blocks()
{
LinearFunctionBlock* cur_lin_fun_block;
unsigned int size_of_vec_lin_fun_block= vec_of_linear_Function_Blocks.size();
unsigned int index_lin_fun_block;
for(index_lin_fun_block = 0; index_lin_fun_block < size_of_vec_lin_fun_block; index_lin_fun_block++){
cur_lin_fun_block = vec_of_linear_Function_Blocks[index_lin_fun_block];
delete cur_lin_fun_block;
}
vec_of_linear_Function_Blocks.clear();
}
void empty_vec_TestBench()
{
Testbench* current_tb;
unsigned int size_of_vec_test_benches = vec_of_test_benches.size();
unsigned int index_tb = 0;
for(index_tb = 0; index_tb < size_of_vec_test_benches; index_tb++){
current_tb = vec_of_test_benches[index_tb];
current_tb->free_resources();
delete current_tb;
}
vec_of_test_benches.clear();
}
diff --git a/Version_Max_07_05_2018_CMake/src/mount_nodes.cpp b/Version_Max_07_05_2018_CMake/src/mount_nodes.cpp
index 81d1a17..79e3609 100755
--- a/Version_Max_07_05_2018_CMake/src/mount_nodes.cpp
+++ b/Version_Max_07_05_2018_CMake/src/mount_nodes.cpp
@@ -1,408 +1,408 @@
#include "attach_modules.h"
#include "mount_nodes.h"
#include "rlutil.h"
#include <stdio.h>
#define PRINT
using namespace rlutil;
bool mount_sensorInAgent(Agent* agent, Sensor* sensor, Channel* channel) {
if(agent != NULL && sensor != NULL && channel != NULL) {
#ifdef PRINT
printf(" > Sensor ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", sensor->get_name());
+ printf("%s ", sensor->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", sensor->get_id());
#endif // PRINT
if(agent->get_sensorHandlerOfAgent()->mount_sensorIntoSensorSlot(channel) && sensor->mount_agent(channel)) {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTGREEN);
printf("mounted ");
setColor(TXTCOLOR_GREY);
printf("in Agent ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", agent->get_name());
+ printf("%s ", agent->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", agent->get_id());
#endif // PRINT
return true;
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
- printf("couldn't be mounted in %s (id: %03u)\n", agent->get_name(), agent->get_id());
+ printf("couldn't be mounted in %s (id: %03u)\n", agent->get_name().c_str(), agent->get_id());
setColor(TXTCOLOR_GREY);
#endif // PRINT
}
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
printf(" > Agent, Sensor, or Channel is not valid\n");
setColor(TXTCOLOR_GREY);
#endif // PRINT
}
return false;
}
/*
void mount_sensor_in_agent(Agent* agent, Sensor* sensor, Channel* sensor_to_slave, unsigned int position) {
printf(" > ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", sensor->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", sensor->get_id());
if(agent->mount_sensor(sensor_to_slave, position) && sensor->mount_agent(sensor_to_slave)) {
rlutil::setColor(TXTCOLOR_LIGHTGREEN);
printf("mounted ");
rlutil::setColor(TXTCOLOR_GREY);
printf("in ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", agent->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n - on position %u\n", agent->get_id(), position);
}
else {
rlutil::setColor(TXTCOLOR_LIGHTRED);
printf("couldn't be mounted in %s (id: %03u) on position %u\n", agent->get_name(), agent->get_id(), position);
rlutil::setColor(TXTCOLOR_GREY);
}
}
*/
/*
void mount_sensor_in_agent(Agent* agent, Sensor* sensor, Channel* sensor_to_slave, Abstraction* abstraction) {
printf(" > ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", sensor->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", sensor->get_id());
if(agent->mount_sensor(sensor_to_slave, abstraction) && sensor->mount_agent(sensor_to_slave)) {
rlutil::setColor(TXTCOLOR_LIGHTGREEN);
printf("mounted ");
rlutil::setColor(TXTCOLOR_GREY);
printf("in ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", agent->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n - ", agent->get_id());
rlutil::setColor(TXTCOLOR_LIGHTGREEN);
printf("connected ");
rlutil::setColor(TXTCOLOR_GREY);
printf("with Abstraction Module ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", abstraction->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", abstraction->get_id());
}
else {
rlutil::setColor(TXTCOLOR_LIGHTRED);
printf("couldn't be mounted in %s (id: %03u) connected with Abstraction Module %s (id: %03u)\n", agent->get_name(), agent->get_id(), abstraction->get_name(), abstraction->get_id());
rlutil::setColor(TXTCOLOR_GREY);
}
}
*/
/*
void mount_sensor_in_agent(Agent* agent, Sensor* sensor, Channel* sensor_to_slave, Confidence_Validator* confidence_validator) {
printf(" > ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", sensor->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", sensor->get_id());
if(agent->mount_sensor(sensor_to_slave, confidence_validator) && sensor->mount_agent(sensor_to_slave)) {
rlutil::setColor(TXTCOLOR_LIGHTGREEN);
printf("mounted ");
rlutil::setColor(TXTCOLOR_GREY);
printf("in ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", agent->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n - ", agent->get_id());
rlutil::setColor(TXTCOLOR_LIGHTGREEN);
printf("connected ");
rlutil::setColor(TXTCOLOR_GREY);
printf("with Range of Validity ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", confidence_validator->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", confidence_validator->get_id());
}
else {
rlutil::setColor(TXTCOLOR_LIGHTRED);
printf("couldn't be mounted in %s (id: %03u) connected with Look up Table %s (id: %03u)\n", agent->get_name(), agent->get_id(), confidence_validator->get_name(), confidence_validator->get_id());
rlutil::setColor(TXTCOLOR_GREY);
}
}
*/
bool mount_sensorInAgent(Agent* agent, Sensor* sensor, Channel* channel, HistoryModule* historyModule) {
if(agent != NULL && sensor != NULL && channel != NULL && historyModule != NULL) {
if(mount_sensorInAgent(agent, sensor, channel)) {
return attach_historyModuleToSensorSlotInAgent(agent, sensor, channel, historyModule);
}
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
printf("Agent, Sensor, Channel, or HistoryModule is not valid\n");
setColor(TXTCOLOR_GREY);
#endif // PRINT
}
return false;
}
/*
void mount_sensor_in_agent(Agent* agent, Sensor* sensor, Channel* sensor_to_slave, Confidence_Validator* confidence_validator, Abstraction* abstraction) {
printf(" > ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", sensor->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", sensor->get_id());
if(agent->mount_sensor(sensor_to_slave, confidence_validator, abstraction) && sensor->mount_agent(sensor_to_slave)) {
rlutil::setColor(TXTCOLOR_LIGHTGREEN);
printf("mounted ");
rlutil::setColor(TXTCOLOR_GREY);
printf("in ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", agent->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n - ", agent->get_id());
rlutil::setColor(TXTCOLOR_LIGHTGREEN);
printf("connected ");
rlutil::setColor(TXTCOLOR_GREY);
printf("with Range of Validity ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", confidence_validator->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n - ", confidence_validator->get_id());
rlutil::setColor(TXTCOLOR_LIGHTGREEN);
printf("connected ");
rlutil::setColor(TXTCOLOR_GREY);
printf("with Abstraction Module ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", abstraction->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", abstraction->get_id());
}
else {
rlutil::setColor(TXTCOLOR_LIGHTRED);
printf("couldn't be mounted in %s (id: %03u) connected with Look up Table %s (id: %03u) and Abstraction Module %s (id: %03u)\n", agent->get_name(), agent->get_id(), confidence_validator->get_name(), confidence_validator->get_id(), abstraction->get_name(), abstraction->get_id());
rlutil::setColor(TXTCOLOR_GREY);
}
}
*/
bool mount_agentInAgent(Agent *masteragent, Agent* slaveagent, Channel* channel) {
if(masteragent != NULL && slaveagent != NULL && channel != NULL) {
if(masteragent->get_slaveAgentHandlerOfAgent()->mount_slaveAgentIntoSlaveAgentSlot(channel)) {
if(slaveagent->get_masterAgentHandlerOfAgent()->mount_masterAgentIntoSlaveAgentSlot(channel)) {
#ifdef PRINT
printf(" > Agent ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", slaveagent->get_name());
+ printf("%s ", slaveagent->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", slaveagent->get_id());
setColor(TXTCOLOR_LIGHTGREEN);
printf("mounted ");
setColor(TXTCOLOR_GREY);
printf("in Agent ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", masteragent->get_name());
+ printf("%s ", masteragent->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", masteragent->get_id());
#endif // PRINT
return true;
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
- printf(" > Could not mount Master Agent %s (id: %03u) in Slave Agent %s (id: %03u)\n", masteragent->get_name(), masteragent->get_id(), slaveagent->get_name(), slaveagent->get_id());
+ printf(" > Could not mount Master Agent %s (id: %03u) in Slave Agent %s (id: %03u)\n", masteragent->get_name().c_str(), masteragent->get_id(), slaveagent->get_name().c_str(), slaveagent->get_id());
setColor(TXTCOLOR_GREY);
#endif // PRINT
masteragent->get_slaveAgentHandlerOfAgent()->demount_slaveAgentIntoSlaveAgentSlot(channel);
}
}
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
printf(" > One of the Agents or Channel not valid\n");
setColor(TXTCOLOR_GREY);
#endif // PRINT
}
return false;
/*
if(masteragent->mount_slaveagent(slave_to_master, master_to_slave) && slaveagent->mount_masteragent(master_to_slave, slave_to_master)) {
setColor(TXTCOLOR_LIGHTGREEN);
printf("mounted ");
setColor(TXTCOLOR_GREY);
printf("in Agent ");
setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", masteragent->get_name());
setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", masteragent->get_id());
if(master_to_slave != NULL && slave_to_master != NULL) {
printf(" > bidirectional communication ");
}
else {
printf(" > unidirectional communication ");
if(master_to_slave != NULL) {
printf("(Master to Slave: ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", master_to_slave->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)) ", master_to_slave->get_id());
}
if(slave_to_master != NULL) {
printf("(Slave to Master: ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", slave_to_master->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)) ", slave_to_master->get_id());
}
}
setColor(TXTCOLOR_LIGHTGREEN);
printf("set\n");
setColor(TXTCOLOR_GREY);
}
else {
setColor(TXTCOLOR_LIGHTRED);
printf("couldn't be mounted in Agent %s (id: %03u)\n", masteragent->get_name(), masteragent->get_id());
setColor(TXTCOLOR_GREY);
}
*/
}
/*
void mount_slaveagent_in_agent(Agent *masteragent, Agent* slaveagent, Channel* master_to_slave, Channel* slave_to_master, unsigned int position) {
printf(" > Slave - ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", slaveagent->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", slaveagent->get_id());
if(masteragent->mount_slaveagent(slave_to_master, master_to_slave, position) && slaveagent->mount_masteragent(master_to_slave, slave_to_master)) {
rlutil::setColor(TXTCOLOR_LIGHTGREEN);
printf("mounted ");
rlutil::setColor(TXTCOLOR_GREY);
printf("in Master - ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", masteragent->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n - on position %u\n - ", masteragent->get_id(), position);
if(master_to_slave != NULL && slave_to_master != NULL)
printf("bidirectional communication\n");
else
printf("unidirectional communication\n");
if(master_to_slave != NULL) {
printf(" - Master to Slave: ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", master_to_slave->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", master_to_slave->get_id());
}
if(slave_to_master != NULL) {
printf(" - Slave to Master: ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", slave_to_master->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", slave_to_master->get_id());
}
}
else {
rlutil::setColor(TXTCOLOR_LIGHTRED);
printf("couldn't be mounted in Master - %s (id: %03u) on position %u\n", masteragent->get_name(), masteragent->get_id(), position);
rlutil::setColor(TXTCOLOR_GREY);
}
}
*/
/*
void mount_slaveagent_in_agent(Agent *masteragent, Agent* slaveagent, Channel* master_to_slave, Channel* slave_to_master, Cross_Confidence_Validator* ccv) {
printf(" > Slave - ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", slaveagent->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", slaveagent->get_id());
if(masteragent->mount_slaveagent(slave_to_master, master_to_slave, ccv) && slaveagent->mount_masteragent(master_to_slave, slave_to_master)) {
rlutil::setColor(TXTCOLOR_LIGHTGREEN);
printf("mounted ");
rlutil::setColor(TXTCOLOR_GREY);
printf("in Master - ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", masteragent->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n - ", masteragent->get_id());
rlutil::setColor(TXTCOLOR_LIGHTGREEN);
printf("connected ");
rlutil::setColor(TXTCOLOR_GREY);
printf("with Cross Confidence Validator ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", ccv->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n - ", ccv->get_id());
if(master_to_slave != NULL && slave_to_master != NULL)
printf("bidirectional communication\n");
else
printf("unidirectional communication\n");
if(master_to_slave != NULL) {
printf(" - Master to Slave: ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", master_to_slave->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", master_to_slave->get_id());
}
if(slave_to_master != NULL) {
printf(" - Slave to Master: ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", slave_to_master->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", slave_to_master->get_id());
}
}
else {
rlutil::setColor(TXTCOLOR_LIGHTRED);
printf("couldn't be mounted in Master - %s (id: %03u) with Cross Confidence Validator %s (id: %03u)\n", masteragent->get_name(), masteragent->get_id(), ccv->get_name(), ccv->get_id());
rlutil::setColor(TXTCOLOR_GREY);
}
}
*/
/*
void mount_bunchmodule_in_agent(Agent *agent, Bunch_Module* bunch_module) {
printf(" > ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", bunch_module->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", bunch_module->get_id());
if(agent->mount_bunch_module(bunch_module)) {
rlutil::setColor(TXTCOLOR_LIGHTGREEN);
printf("mounted ");
rlutil::setColor(TXTCOLOR_GREY);
printf("in ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
printf("%s ", agent->get_name());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", agent->get_id());
}
else {
rlutil::setColor(TXTCOLOR_LIGHTRED);
printf("couldn't be mounted in %s (id: %03u)\n", agent->get_name(), agent->get_id());
rlutil::setColor(TXTCOLOR_GREY);
}
}
*/
diff --git a/Version_Max_07_05_2018_CMake/src/printError.cpp b/Version_Max_07_05_2018_CMake/src/printError.cpp
index e9bb053..e849f14 100755
--- a/Version_Max_07_05_2018_CMake/src/printError.cpp
+++ b/Version_Max_07_05_2018_CMake/src/printError.cpp
@@ -1,16 +1,16 @@
#include <stdio.h>
#include "printError.h"
#define PC_MODE
-void printError(char* errorMsg) {
+void printError(std::string errorMsg) {
#ifdef PC_MODE
- printf("%s\n", errorMsg);
+ printf("%s\n", errorMsg.c_str());
#endif
}
-void printError(char* errorMsg, const char* additionalInfo) {
+void printError(std::string errorMsg, const char *additionalInfo) {
#ifdef PC_MODE
- printf("%s: %s\n", errorMsg, additionalInfo);
+ printf("%s: %s\n", errorMsg.c_str(), additionalInfo);
#endif
}
diff --git a/Version_Max_07_05_2018_CMake/src/printError.h b/Version_Max_07_05_2018_CMake/src/printError.h
index fea2169..22ce522 100755
--- a/Version_Max_07_05_2018_CMake/src/printError.h
+++ b/Version_Max_07_05_2018_CMake/src/printError.h
@@ -1,7 +1,9 @@
#ifndef H_PRINT_HEADERFILE
#define H_PRINT_HEADERFILE
-void printError(char*);
-void printError(char* errorMsg, const char* additionalInfo);
+#include <string>
+
+void printError(std::string errorMsg);
+void printError(std::string errorMsg, const char *additionalInfo);
#endif
\ No newline at end of file
diff --git a/Version_Max_07_05_2018_CMake/src/register_in_testbench.cpp b/Version_Max_07_05_2018_CMake/src/register_in_testbench.cpp
index 79ec1a4..49bc5d0 100755
--- a/Version_Max_07_05_2018_CMake/src/register_in_testbench.cpp
+++ b/Version_Max_07_05_2018_CMake/src/register_in_testbench.cpp
@@ -1,130 +1,130 @@
#include "register_in_testbench.h"
#include "attach_modulesToTestbench.h"
#include "rlutil.h"
#include <stdio.h>
#define PRINT
using namespace rlutil;
bool register_agentInTestbench(Testbench *tb, Agent *agent) {
if(tb != NULL && agent != NULL) {
#ifdef PRINT
printf(" > Agent ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", agent->get_name());
+ printf("%s ", agent->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", agent->get_id());
#endif // PRINT
if(tb->register_agent(agent)) {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTGREEN);
printf("registered ");
setColor(TXTCOLOR_GREY);
printf("in Testbench ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s\n", tb->get_name());
+ printf("%s\n", tb->get_name().c_str());
setColor(TXTCOLOR_GREY);
#endif // PRINT
return true;
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
- printf("couldn't be registered in %s", tb->get_name());
+ printf("couldn't be registered in %s", tb->get_name().c_str());
#endif // PRINT
}
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
printf(" > Testbench or Agent is not valid\n");
#endif // PRINT
}
setColor(TXTCOLOR_GREY);
return false;
}
bool register_sensorInTestbench(Testbench *tb, Sensor *sensor) {
if(tb != NULL && sensor != NULL) {
#ifdef PRINT
printf(" > Sensor ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", sensor->get_name());
+ printf("%s ", sensor->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", sensor->get_id());
#endif // PRINT
if(tb->register_sensor(sensor)) {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTGREEN);
printf("registered ");
setColor(TXTCOLOR_GREY);
printf("in ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s\n", tb->get_name());
+ printf("%s\n", tb->get_name().c_str());
setColor(TXTCOLOR_GREY);
#endif // PRINT
return true;
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
- printf("couldn't be registered in %s\n", tb->get_name());
+ printf("couldn't be registered in %s\n", tb->get_name().c_str());
#endif // PRINT
}
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
printf(" > Testbench or sensor is not valid\n");
#endif // PRINT
}
setColor(TXTCOLOR_GREY);
return false;
}
bool register_sensorInTestbench(Testbench *tb, Sensor *sensor, CSVreaderModule *csvReaderModule) {
if(tb != NULL && sensor != NULL && csvReaderModule != NULL) {
if(register_sensorInTestbench(tb, sensor)) {
return attach_csvReaderModuleToSensorSlotInAgent(tb, sensor, csvReaderModule);
}
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
printf("Testbench or sensor is not valid\n");
#endif // PRINT
}
setColor(TXTCOLOR_GREY);
return false;
}
bool register_channelInTestbench(Testbench *tb, Channel *channel) {
#ifdef PRINT
printf(" > Channel ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", channel->get_name());
+ printf("%s ", channel->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", channel->get_id());
#endif // PRINT
if(tb->register_channel(channel)){
#ifdef PRINT
setColor(TXTCOLOR_LIGHTGREEN);
printf("registered ");
setColor(TXTCOLOR_GREY);
printf("in Testbench ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s\n", tb->get_name());
+ printf("%s\n", tb->get_name().c_str());
#endif // PRINT
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
- printf("couldn't be registered in %s\n", tb->get_name());
+ printf("couldn't be registered in %s\n", tb->get_name().c_str());
#endif // PRINT
}
setColor(TXTCOLOR_GREY);
return false;
}
diff --git a/Version_Max_07_05_2018_CMake/src/rlutil.h b/Version_Max_07_05_2018_CMake/src/rlutil.h
index 7f79138..2c5ea7a 100755
--- a/Version_Max_07_05_2018_CMake/src/rlutil.h
+++ b/Version_Max_07_05_2018_CMake/src/rlutil.h
@@ -1,779 +1,779 @@
#pragma once
/**
* File: rlutil.h
*
* About: Description
* This file provides some useful utilities for console mode
* roguelike game development with C and C++. It is aimed to
* be cross-platform (at least Windows and Linux).
*
* About: Copyright
* (C) 2010 Tapio Vierros
*
* About: Licensing
* See <License>
*/
//#ifndef RLUTIL_HEADERFILE
//#define RLUTIL_HEADERFILE
/// Define: RLUTIL_USE_ANSI
/// Define this to use ANSI escape sequences also on Windows
/// (defaults to using WinAPI instead).
#if 0
#define RLUTIL_USE_ANSI
#endif
/// Define: RLUTIL_STRING_T
/// Define/typedef this to your preference to override rlutil's string type.
///
/// Defaults to std::string with C++ and char* with C.
#if 0
#define RLUTIL_STRING_T char*
#endif
#ifndef RLUTIL_INLINE
#ifdef _MSC_VER
#define RLUTIL_INLINE __inline
#else
#define RLUTIL_INLINE static __inline__
#endif
#endif
#ifdef __cplusplus
/// Common C++ headers
#include <iostream>
#include <string>
#include <cstdio> // for getch()
/// Namespace forward declarations
namespace rlutil {
RLUTIL_INLINE void locate(int x, int y);
}
//Work Arround (atartpoint)
#define TXTCOLOR_BLACK 0
#define TXTCOLOR_BLUE 1
#define TXTCOLOR_GREEN 2
#define TXTCOLOR_CYAN 3
#define TXTCOLOR_RED 4
#define TXTCOLOR_MAGENTA 5
#define TXTCOLOR_BROWN 6
#define TXTCOLOR_GREY 7
#define TXTCOLOR_DARKGREY 8
#define TXTCOLOR_LIGHTBLUE 9
#define TXTCOLOR_LIGHTGREEN 10
#define TXTCOLOR_LIGHTCYAN 11
#define TXTCOLOR_LIGHTRED 12
#define TXTCOLOR_LIGHTMAGENTA 13
#define TXTCOLOR_YELLOW 14
#define TXTCOLOR_WHITE 15
#else
#include <stdio.h> // for getch() / printf()
#include <string.h> // for strlen()
RLUTIL_INLINE void locate(int x, int y); // Forward declare for C to avoid warnings
#endif // __cplusplus
#ifdef _WIN32
#include <windows.h> // for WinAPI and Sleep()
#define _NO_OLDNAMES // for MinGW compatibility
#include <conio.h> // for getch() and kbhit()
#define getch _getch
#define kbhit _kbhit
#else
#include <termios.h> // for getch() and kbhit()
#include <unistd.h> // for getch(), kbhit() and (u)sleep()
#include <sys/ioctl.h> // for getkey()
#include <sys/types.h> // for kbhit()
#include <sys/time.h> // for kbhit()
/// Function: getch
/// Get character without waiting for Return to be pressed.
/// Windows has this in conio.h
RLUTIL_INLINE int getch(void) {
// Here be magic.
struct termios oldt, newt;
int ch;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
}
/// Function: kbhit
/// Determines if keyboard has been hit.
/// Windows has this in conio.h
RLUTIL_INLINE int kbhit(void) {
// Here be dragons.
static struct termios oldt, newt;
int cnt = 0;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
newt.c_iflag = 0; // input mode
newt.c_oflag = 0; // output mode
newt.c_cc[VMIN] = 1; // minimum time to wait
newt.c_cc[VTIME] = 1; // minimum characters to wait for
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ioctl(0, FIONREAD, &cnt); // Read count
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 100;
select(STDIN_FILENO+1, NULL, NULL, NULL, &tv); // A small time delay
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return cnt; // Return number of characters
}
#endif // _WIN32
#ifndef gotoxy
/// Function: gotoxy
/// Same as <rlutil.locate>.
RLUTIL_INLINE void gotoxy(int x, int y) {
#ifdef __cplusplus
rlutil::
#endif
locate(x,y);
}
#endif // gotoxy
#ifdef __cplusplus
/// Namespace: rlutil
/// In C++ all functions except <getch>, <kbhit> and <gotoxy> are arranged
/// under namespace rlutil. That is because some platforms have them defined
/// outside of rlutil.
namespace rlutil {
#endif
/**
* Defs: Internal typedefs and macros
* RLUTIL_STRING_T - String type depending on which one of C or C++ is used
* RLUTIL_PRINT(str) - Printing macro independent of C/C++
*/
#ifdef __cplusplus
#ifndef RLUTIL_STRING_T
typedef std::string RLUTIL_STRING_T;
#endif // RLUTIL_STRING_T
#define RLUTIL_PRINT(st) do { std::cout << st; } while(false)
#else // __cplusplus
#ifndef RLUTIL_STRING_T
typedef const char* RLUTIL_STRING_T;
#endif // RLUTIL_STRING_T
#define RLUTIL_PRINT(st) printf("%s", st)
#endif // __cplusplus
/**
* Enums: Color codes
*
* BLACK - Black
* BLUE - Blue
* GREEN - Green
* CYAN - Cyan
* RED - Red
* MAGENTA - Magenta / purple
* BROWN - Brown / dark yellow
* GREY - Grey / dark white
* DARKGREY - Dark grey / light black
* LIGHTBLUE - Light blue
* LIGHTGREEN - Light green
* LIGHTCYAN - Light cyan
* LIGHTRED - Light red
* LIGHTMAGENTA - Light magenta / light purple
* YELLOW - Yellow (bright)
* WHITE - White (bright)
*/
enum {
BLACK,
BLUE,
GREEN,
CYAN,
RED,
MAGENTA,
BROWN,
GREY,
DARKGREY,
LIGHTBLUE,
LIGHTGREEN,
LIGHTCYAN,
LIGHTRED,
LIGHTMAGENTA,
YELLOW,
WHITE
};
/**
* Consts: ANSI escape strings
*
* ANSI_CLS - Clears screen
* ANSI_CONSOLE_TITLE_PRE - Prefix for changing the window title, print the window title in between
* ANSI_CONSOLE_TITLE_POST - Suffix for changing the window title, print the window title in between
* ANSI_ATTRIBUTE_RESET - Resets all attributes
* ANSI_CURSOR_HIDE - Hides the cursor
* ANSI_CURSOR_SHOW - Shows the cursor
* ANSI_CURSOR_HOME - Moves the cursor home (0,0)
* ANSI_BLACK - Black
* ANSI_RED - Red
* ANSI_GREEN - Green
* ANSI_BROWN - Brown / dark yellow
* ANSI_BLUE - Blue
* ANSI_MAGENTA - Magenta / purple
* ANSI_CYAN - Cyan
* ANSI_GREY - Grey / dark white
* ANSI_DARKGREY - Dark grey / light black
* ANSI_LIGHTRED - Light red
* ANSI_LIGHTGREEN - Light green
* ANSI_YELLOW - Yellow (bright)
* ANSI_LIGHTBLUE - Light blue
* ANSI_LIGHTMAGENTA - Light magenta / light purple
* ANSI_LIGHTCYAN - Light cyan
* ANSI_WHITE - White (bright)
* ANSI_BACKGROUND_BLACK - Black background
* ANSI_BACKGROUND_RED - Red background
* ANSI_BACKGROUND_GREEN - Green background
* ANSI_BACKGROUND_YELLOW - Yellow background
* ANSI_BACKGROUND_BLUE - Blue background
* ANSI_BACKGROUND_MAGENTA - Magenta / purple background
* ANSI_BACKGROUND_CYAN - Cyan background
* ANSI_BACKGROUND_WHITE - White background
*/
const RLUTIL_STRING_T ANSI_CLS = "\033[2J\033[3J";
const RLUTIL_STRING_T ANSI_CONSOLE_TITLE_PRE = "\033]0;";
const RLUTIL_STRING_T ANSI_CONSOLE_TITLE_POST = "\007";
const RLUTIL_STRING_T ANSI_ATTRIBUTE_RESET = "\033[0m";
const RLUTIL_STRING_T ANSI_CURSOR_HIDE = "\033[?25l";
const RLUTIL_STRING_T ANSI_CURSOR_SHOW = "\033[?25h";
const RLUTIL_STRING_T ANSI_CURSOR_HOME = "\033[H";
const RLUTIL_STRING_T ANSI_BLACK = "\033[22;30m";
const RLUTIL_STRING_T ANSI_RED = "\033[22;31m";
const RLUTIL_STRING_T ANSI_GREEN = "\033[22;32m";
const RLUTIL_STRING_T ANSI_BROWN = "\033[22;33m";
const RLUTIL_STRING_T ANSI_BLUE = "\033[22;34m";
const RLUTIL_STRING_T ANSI_MAGENTA = "\033[22;35m";
const RLUTIL_STRING_T ANSI_CYAN = "\033[22;36m";
const RLUTIL_STRING_T ANSI_GREY = "\033[22;37m";
const RLUTIL_STRING_T ANSI_DARKGREY = "\033[01;30m";
const RLUTIL_STRING_T ANSI_LIGHTRED = "\033[01;31m";
const RLUTIL_STRING_T ANSI_LIGHTGREEN = "\033[01;32m";
const RLUTIL_STRING_T ANSI_YELLOW = "\033[01;33m";
const RLUTIL_STRING_T ANSI_LIGHTBLUE = "\033[01;34m";
const RLUTIL_STRING_T ANSI_LIGHTMAGENTA = "\033[01;35m";
const RLUTIL_STRING_T ANSI_LIGHTCYAN = "\033[01;36m";
const RLUTIL_STRING_T ANSI_WHITE = "\033[01;37m";
const RLUTIL_STRING_T ANSI_BACKGROUND_BLACK = "\033[40m";
const RLUTIL_STRING_T ANSI_BACKGROUND_RED = "\033[41m";
const RLUTIL_STRING_T ANSI_BACKGROUND_GREEN = "\033[42m";
const RLUTIL_STRING_T ANSI_BACKGROUND_YELLOW = "\033[43m";
const RLUTIL_STRING_T ANSI_BACKGROUND_BLUE = "\033[44m";
const RLUTIL_STRING_T ANSI_BACKGROUND_MAGENTA = "\033[45m";
const RLUTIL_STRING_T ANSI_BACKGROUND_CYAN = "\033[46m";
const RLUTIL_STRING_T ANSI_BACKGROUND_WHITE = "\033[47m";
// Remaining colors not supported as background colors
/**
* Enums: Key codes for keyhit()
*
* KEY_ESCAPE - Escape
* KEY_ENTER - Enter
* KEY_SPACE - Space
* KEY_INSERT - Insert
* KEY_HOME - Home
* KEY_END - End
* KEY_DELETE - Delete
* KEY_PGUP - PageUp
* KEY_PGDOWN - PageDown
* KEY_UP - Up arrow
* KEY_DOWN - Down arrow
* KEY_LEFT - Left arrow
* KEY_RIGHT - Right arrow
* KEY_F1 - F1
* KEY_F2 - F2
* KEY_F3 - F3
* KEY_F4 - F4
* KEY_F5 - F5
* KEY_F6 - F6
* KEY_F7 - F7
* KEY_F8 - F8
* KEY_F9 - F9
* KEY_F10 - F10
* KEY_F11 - F11
* KEY_F12 - F12
* KEY_NUMDEL - Numpad del
* KEY_NUMPAD0 - Numpad 0
* KEY_NUMPAD1 - Numpad 1
* KEY_NUMPAD2 - Numpad 2
* KEY_NUMPAD3 - Numpad 3
* KEY_NUMPAD4 - Numpad 4
* KEY_NUMPAD5 - Numpad 5
* KEY_NUMPAD6 - Numpad 6
* KEY_NUMPAD7 - Numpad 7
* KEY_NUMPAD8 - Numpad 8
* KEY_NUMPAD9 - Numpad 9
*/
enum {
KEY_ESCAPE = 0,
KEY_ENTER = 1,
KEY_SPACE = 32,
KEY_INSERT = 2,
KEY_HOME = 3,
KEY_PGUP = 4,
KEY_DELETE = 5,
KEY_END = 6,
KEY_PGDOWN = 7,
KEY_UP = 14,
KEY_DOWN = 15,
KEY_LEFT = 16,
KEY_RIGHT = 17,
KEY_F1 = 18,
KEY_F2 = 19,
KEY_F3 = 20,
KEY_F4 = 21,
KEY_F5 = 22,
KEY_F6 = 23,
KEY_F7 = 24,
KEY_F8 = 25,
KEY_F9 = 26,
KEY_F10 = 27,
KEY_F11 = 28,
KEY_F12 = 29,
KEY_NUMDEL = 30,
KEY_NUMPAD0 = 31,
KEY_NUMPAD1 = 127,
KEY_NUMPAD2 = 128,
KEY_NUMPAD3 = 129,
KEY_NUMPAD4 = 130,
KEY_NUMPAD5 = 131,
KEY_NUMPAD6 = 132,
KEY_NUMPAD7 = 133,
KEY_NUMPAD8 = 134,
KEY_NUMPAD9 = 135
};
/// Function: getkey
/// Reads a key press (blocking) and returns a key code.
///
/// See <Key codes for keyhit()>
///
/// Note:
/// Only Arrows, Esc, Enter and Space are currently working properly.
RLUTIL_INLINE int getkey(void) {
#ifndef _WIN32
int cnt = kbhit(); // for ANSI escapes processing
#endif
int k = getch();
switch(k) {
case 0: {
int kk;
switch (kk = getch()) {
case 71: return KEY_NUMPAD7;
case 72: return KEY_NUMPAD8;
case 73: return KEY_NUMPAD9;
case 75: return KEY_NUMPAD4;
case 77: return KEY_NUMPAD6;
case 79: return KEY_NUMPAD1;
case 80: return KEY_NUMPAD2;
case 81: return KEY_NUMPAD3;
case 82: return KEY_NUMPAD0;
case 83: return KEY_NUMDEL;
default: return kk-59+KEY_F1; // Function keys
}}
case 224: {
int kk;
switch (kk = getch()) {
case 71: return KEY_HOME;
case 72: return KEY_UP;
case 73: return KEY_PGUP;
case 75: return KEY_LEFT;
case 77: return KEY_RIGHT;
case 79: return KEY_END;
case 80: return KEY_DOWN;
case 81: return KEY_PGDOWN;
case 82: return KEY_INSERT;
case 83: return KEY_DELETE;
default: return kk-123+KEY_F1; // Function keys
}}
case 13: return KEY_ENTER;
#ifdef _WIN32
case 27: return KEY_ESCAPE;
#else // _WIN32
case 155: // single-character CSI
case 27: {
// Process ANSI escape sequences
if (cnt >= 3 && getch() == '[') {
switch (k = getch()) {
case 'A': return KEY_UP;
case 'B': return KEY_DOWN;
case 'C': return KEY_RIGHT;
case 'D': return KEY_LEFT;
}
} else return KEY_ESCAPE;
}
#endif // _WIN32
default: return k;
}
}
/// Function: nb_getch
/// Non-blocking getch(). Returns 0 if no key was pressed.
RLUTIL_INLINE int nb_getch(void) {
if (kbhit()) return getch();
else return 0;
}
/// Function: getANSIColor
/// Return ANSI color escape sequence for specified number 0-15.
///
/// See <Color Codes>
RLUTIL_INLINE RLUTIL_STRING_T getANSIColor(const int c) {
switch (c) {
case BLACK : return ANSI_BLACK;
case BLUE : return ANSI_BLUE; // non-ANSI
case GREEN : return ANSI_GREEN;
case CYAN : return ANSI_CYAN; // non-ANSI
case RED : return ANSI_RED; // non-ANSI
case MAGENTA : return ANSI_MAGENTA;
case BROWN : return ANSI_BROWN;
case GREY : return ANSI_GREY;
case DARKGREY : return ANSI_DARKGREY;
case LIGHTBLUE : return ANSI_LIGHTBLUE; // non-ANSI
case LIGHTGREEN : return ANSI_LIGHTGREEN;
case LIGHTCYAN : return ANSI_LIGHTCYAN; // non-ANSI;
case LIGHTRED : return ANSI_LIGHTRED; // non-ANSI;
case LIGHTMAGENTA: return ANSI_LIGHTMAGENTA;
case YELLOW : return ANSI_YELLOW; // non-ANSI
case WHITE : return ANSI_WHITE;
default: return "";
}
}
/// Function: getANSIBackgroundColor
/// Return ANSI background color escape sequence for specified number 0-15.
///
/// See <Color Codes>
RLUTIL_INLINE RLUTIL_STRING_T getANSIBackgroundColor(const int c) {
switch (c) {
case BLACK : return ANSI_BACKGROUND_BLACK;
case BLUE : return ANSI_BACKGROUND_BLUE;
case GREEN : return ANSI_BACKGROUND_GREEN;
case CYAN : return ANSI_BACKGROUND_CYAN;
case RED : return ANSI_BACKGROUND_RED;
case MAGENTA: return ANSI_BACKGROUND_MAGENTA;
case BROWN : return ANSI_BACKGROUND_YELLOW;
case GREY : return ANSI_BACKGROUND_WHITE;
default: return "";
}
}
/// Function: setColor
/// Change color specified by number (Windows / QBasic colors).
/// Don't change the background color
///
/// See <Color Codes>
RLUTIL_INLINE void setColor(int c) {
#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hConsole, &csbi);
SetConsoleTextAttribute(hConsole, (csbi.wAttributes & 0xFFF0) | (WORD)c); // Foreground colors take up the least significant byte
#else
RLUTIL_PRINT(getANSIColor(c));
#endif
}
/// Function: setBackgroundColor
/// Change background color specified by number (Windows / QBasic colors).
/// Don't change the foreground color
///
/// See <Color Codes>
RLUTIL_INLINE void setBackgroundColor(int c) {
#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hConsole, &csbi);
SetConsoleTextAttribute(hConsole, (csbi.wAttributes & 0xFF0F) | (((WORD)c) << 4)); // Background colors take up the second-least significant byte
#else
RLUTIL_PRINT(getANSIBackgroundColor(c));
#endif
}
/// Function: saveDefaultColor
/// Call once to preserve colors for use in resetColor()
/// on Windows without ANSI, no-op otherwise
///
/// See <Color Codes>
/// See <resetColor>
RLUTIL_INLINE int saveDefaultColor(void) {
#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
static char initialized = 0; // bool
static WORD attributes;
if (!initialized) {
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
attributes = csbi.wAttributes;
initialized = 1;
}
return (int)attributes;
#else
return -1;
#endif
}
/// Function: resetColor
/// Reset color to default
/// Requires a call to saveDefaultColor() to set the defaults
///
/// See <Color Codes>
/// See <setColor>
/// See <saveDefaultColor>
RLUTIL_INLINE void resetColor(void) {
#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), (WORD)saveDefaultColor());
#else
RLUTIL_PRINT(ANSI_ATTRIBUTE_RESET);
#endif
}
/// Function: cls
/// Clears screen, resets all attributes and moves cursor home.
RLUTIL_INLINE void cls(void) {
#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
// Based on https://msdn.microsoft.com/en-us/library/windows/desktop/ms682022%28v=vs.85%29.aspx
const HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
const COORD coordScreen = {0, 0};
DWORD cCharsWritten;
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hConsole, &csbi);
const DWORD dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
FillConsoleOutputCharacter(hConsole, (TCHAR)' ', dwConSize, coordScreen, &cCharsWritten);
GetConsoleScreenBufferInfo(hConsole, &csbi);
FillConsoleOutputAttribute(hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten);
SetConsoleCursorPosition(hConsole, coordScreen);
#else
RLUTIL_PRINT(ANSI_CLS);
RLUTIL_PRINT(ANSI_CURSOR_HOME);
#endif
}
/// Function: locate
/// Sets the cursor position to 1-based x,y.
RLUTIL_INLINE void locate(int x, int y) {
#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
COORD coord;
// TODO: clamping/assert for x/y <= 0?
coord.X = (SHORT)(x - 1);
coord.Y = (SHORT)(y - 1); // Windows uses 0-based coordinates
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
#else // _WIN32 || USE_ANSI
#ifdef __cplusplus
RLUTIL_PRINT("\033[" << y << ";" << x << "H");
#else // __cplusplus
char buf[32];
sprintf(buf, "\033[%d;%df", y, x);
RLUTIL_PRINT(buf);
#endif // __cplusplus
#endif // _WIN32 || USE_ANSI
}
/// Function: setString
/// Prints the supplied string without advancing the cursor
#ifdef __cplusplus
RLUTIL_INLINE void setString(const RLUTIL_STRING_T & str_) {
//Work Around (startpoint)
- const char * const str_temp = str_.data(); //Changed: "str" -> "str_temp"
+ //const char * str_temp = str_.data(); //Changed: "str" -> "str_temp"
wchar_t* str=new wchar_t[4096]; //Add this line
//MultiByteToWideChar(CP_ACP, 0, str_temp, -1, str, 4096); //Add this line
//Work Around (endpoint)
unsigned int len = str_.size();
#else // __cplusplus
RLUTIL_INLINE void setString(RLUTIL_STRING_T str) {
unsigned int len = strlen(str);
#endif // __cplusplus
#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
DWORD numberOfCharsWritten;
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hConsoleOutput, &csbi);
WriteConsoleOutputCharacter(hConsoleOutput, str, len, csbi.dwCursorPosition, &numberOfCharsWritten);
#else // _WIN32 || USE_ANSI
RLUTIL_PRINT(str);
#ifdef __cplusplus
RLUTIL_PRINT("\033[" << len << 'D');
#else // __cplusplus
char buf[3 + 20 + 1]; // 20 = max length of 64-bit unsigned int when printed as dec
sprintf(buf, "\033[%uD", len);
RLUTIL_PRINT(buf);
#endif // __cplusplus
#endif // _WIN32 || USE_ANSI
}
/// Function: setChar
/// Sets the character at the cursor without advancing the cursor
RLUTIL_INLINE void setChar(char ch) {
const char buf[] = {ch, 0};
setString(buf);
}
/// Function: setCursorVisibility
/// Shows/hides the cursor.
RLUTIL_INLINE void setCursorVisibility(char visible) {
#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
HANDLE hConsoleOutput = GetStdHandle( STD_OUTPUT_HANDLE );
CONSOLE_CURSOR_INFO structCursorInfo;
GetConsoleCursorInfo( hConsoleOutput, &structCursorInfo ); // Get current cursor size
structCursorInfo.bVisible = (visible ? TRUE : FALSE);
SetConsoleCursorInfo( hConsoleOutput, &structCursorInfo );
#else // _WIN32 || USE_ANSI
RLUTIL_PRINT((visible ? ANSI_CURSOR_SHOW : ANSI_CURSOR_HIDE));
#endif // _WIN32 || USE_ANSI
}
/// Function: hidecursor
/// Hides the cursor.
RLUTIL_INLINE void hidecursor(void) {
setCursorVisibility(0);
}
/// Function: showcursor
/// Shows the cursor.
RLUTIL_INLINE void showcursor(void) {
setCursorVisibility(1);
}
/// Function: msleep
/// Waits given number of milliseconds before continuing.
RLUTIL_INLINE void msleep(unsigned int ms) {
#ifdef _WIN32
Sleep(ms);
#else
// usleep argument must be under 1 000 000
if (ms > 1000) sleep(ms/1000000);
usleep((ms % 1000000) * 1000);
#endif
}
/// Function: trows
/// Get the number of rows in the terminal window or -1 on error.
RLUTIL_INLINE int trows(void) {
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
return -1;
else
return csbi.srWindow.Bottom - csbi.srWindow.Top + 1; // Window height
// return csbi.dwSize.Y; // Buffer height
#else
#ifdef TIOCGSIZE
struct ttysize ts;
ioctl(STDIN_FILENO, TIOCGSIZE, &ts);
return ts.ts_lines;
#elif defined(TIOCGWINSZ)
struct winsize ts;
ioctl(STDIN_FILENO, TIOCGWINSZ, &ts);
return ts.ws_row;
#else // TIOCGSIZE
return -1;
#endif // TIOCGSIZE
#endif // _WIN32
}
/// Function: tcols
/// Get the number of columns in the terminal window or -1 on error.
RLUTIL_INLINE int tcols(void) {
#ifdef _WIN32
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
return -1;
else
return csbi.srWindow.Right - csbi.srWindow.Left + 1; // Window width
// return csbi.dwSize.X; // Buffer width
#else
#ifdef TIOCGSIZE
struct ttysize ts;
ioctl(STDIN_FILENO, TIOCGSIZE, &ts);
return ts.ts_cols;
#elif defined(TIOCGWINSZ)
struct winsize ts;
ioctl(STDIN_FILENO, TIOCGWINSZ, &ts);
return ts.ws_col;
#else // TIOCGSIZE
return -1;
#endif // TIOCGSIZE
#endif // _WIN32
}
/// Function: anykey
/// Waits until a key is pressed.
/// In C++, it either takes no arguments
/// or a template-type-argument-deduced
/// argument.
/// In C, it takes a const char* representing
/// the message to be displayed, or NULL
/// for no message.
#ifdef __cplusplus
RLUTIL_INLINE void anykey() {
getch();
}
template <class T> void anykey(const T& msg) {
RLUTIL_PRINT(msg);
#else
RLUTIL_INLINE void anykey(RLUTIL_STRING_T msg) {
if (msg)
RLUTIL_PRINT(msg);
#endif // __cplusplus
getch();
}
RLUTIL_INLINE void setConsoleTitle(RLUTIL_STRING_T title) {
const char * true_title =
#ifdef __cplusplus
title.c_str();
#else // __cplusplus
title;
#endif // __cplusplus
#if defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
SetConsoleTitleA(true_title);
#else
RLUTIL_PRINT(ANSI_CONSOLE_TITLE_PRE);
RLUTIL_PRINT(true_title);
RLUTIL_PRINT(ANSI_CONSOLE_TITLE_POST);
#endif // defined(_WIN32) && !defined(RLUTIL_USE_ANSI)
}
// Classes are here at the end so that documentation is pretty.
#ifdef __cplusplus
/// Class: CursorHider
/// RAII OOP wrapper for <rlutil.hidecursor>.
/// Hides the cursor and shows it again
/// when the object goes out of scope.
struct CursorHider {
CursorHider() { hidecursor(); }
~CursorHider() { showcursor(); }
};
} // namespace rlutil
#endif
//#endif
\ No newline at end of file
diff --git a/Version_Max_07_05_2018_CMake/src/setupNode.cpp b/Version_Max_07_05_2018_CMake/src/setupNode.cpp
index 4d906f3..1705db2 100755
--- a/Version_Max_07_05_2018_CMake/src/setupNode.cpp
+++ b/Version_Max_07_05_2018_CMake/src/setupNode.cpp
@@ -1,54 +1,54 @@
#include "setupNode.h"
#include "rlutil.h"
#define PRINT
using namespace rlutil;
void setWorkingCycleOfSensor(Sensor* sensor, unsigned int workingCycle) {
if (sensor->set_workingCycle(workingCycle)) {
#ifdef PRINT
printf(" > WorkingCycle of Sensor ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", sensor->get_name());
+ printf("%s ", sensor->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", sensor->get_id());
setColor(TXTCOLOR_LIGHTGREEN);
printf("set ");
setColor(TXTCOLOR_GREY);
printf("to %u\n", workingCycle);
#endif // PRINT
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
- printf(" > Couldn't set WorkingCycle of Sensor %s (id: %03u)\n", sensor->get_name(), sensor->get_id());
+ printf(" > Couldn't set WorkingCycle of Sensor %s (id: %03u)\n", sensor->get_name().c_str(), sensor->get_id());
setColor(TXTCOLOR_GREY);
#endif // PRINT
}
}
void setWorkingCycleOfAgent(Agent* agent, unsigned int workingCycle) {
if (agent->set_workingCycle(workingCycle)) {
#ifdef PRINT
printf(" > WorkingCycle of Agent ");
setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", agent->get_name());
+ printf("%s ", agent->get_name().c_str());
setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", agent->get_id());
setColor(TXTCOLOR_LIGHTGREEN);
printf("set ");
setColor(TXTCOLOR_GREY);
printf("to %u\n", workingCycle);
#endif // PRINT
}
else {
#ifdef PRINT
setColor(TXTCOLOR_LIGHTRED);
- printf(" > Couldn't set WorkingCycle of Sensor %s (id: %03u)\n", agent->get_name(), agent->get_id());
+ printf(" > Couldn't set WorkingCycle of Sensor %s (id: %03u)\n", agent->get_name().c_str(), agent->get_id());
setColor(TXTCOLOR_GREY);
#endif // PRINT
}
}
\ No newline at end of file
diff --git a/Version_Max_07_05_2018_CMake/src/setup_lookuptable.cpp b/Version_Max_07_05_2018_CMake/src/setup_lookuptable.cpp
index f1061b9..30300f4 100755
--- a/Version_Max_07_05_2018_CMake/src/setup_lookuptable.cpp
+++ b/Version_Max_07_05_2018_CMake/src/setup_lookuptable.cpp
@@ -1,52 +1,52 @@
#include "setup_lookuptable.h"
#include <stdio.h>
#include "rlutil.h"
void fill_lookuptable(Lookuptable* lut, int score, float lower_boundary, bool flag_lower_boundary_included, float upper_boundary, bool flag_upper_boundary_included) {
printf(" > Score %i with Range ", score);
if(flag_lower_boundary_included)
printf("[");
else
printf("]");
printf("%6.2f,%6.2f ", lower_boundary, upper_boundary);
if(flag_upper_boundary_included)
printf("] ");
else
printf("[ ");
if(lut->add_range_to_lookuptable(score, lower_boundary, flag_lower_boundary_included, upper_boundary, flag_upper_boundary_included)) {
printf("was ");
rlutil::setColor(TXTCOLOR_LIGHTGREEN);
printf("added ");
rlutil::setColor(TXTCOLOR_GREY);
printf("to ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", lut->get_name());
+ printf("%s ", lut->get_name().c_str());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u)\n", lut->get_id());
}
else {
rlutil::setColor(TXTCOLOR_LIGHTRED);
- printf("couldn't be added to %s (id: %03u)\n", lut->get_name(), lut->get_id());
+ printf("couldn't be added to %s (id: %03u)\n", lut->get_name().c_str(), lut->get_id());
rlutil::setColor(TXTCOLOR_GREY);
}
}
void check_and_activate_lookuptable(Lookuptable* lut) {
printf(" > ");
rlutil::setColor(TXTCOLOR_LIGHTCYAN);
- printf("%s ", lut->get_name());
+ printf("%s ", lut->get_name().c_str());
rlutil::setColor(TXTCOLOR_GREY);
printf("(id: %03u) ", lut->get_id());
if(lut->check_sort_and_activate()) {
printf("seems to be ");
rlutil::setColor(TXTCOLOR_LIGHTGREEN);
printf("correct\n");
}
else {
rlutil::setColor(TXTCOLOR_LIGHTRED);
- printf("is not correct\n", lut->get_name(), lut->get_id());
+ printf("is not correct\n");
}
rlutil::setColor(TXTCOLOR_GREY);
}
\ No newline at end of file

File Metadata

Mime Type
text/x-diff
Expires
Sun, Apr 27, 2:09 PM (1 d, 6 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
134519
Default Alt Text
(452 KB)

Event Timeline