How to insert c++ find into a while loop? - c++

I use a while loop with the find function in c++ but I need to use the position found like the condition of the while loop but Visual Studio shome me
An unhandled exception of type 'System.Runtime.InteropServices.SEHException' occured in Test.exe
Additional information: External component has thrown an exception.
I use this code:
int dim=myString.length();
while (dim>=0)
{
size_t pos1 = myString.find("<article");
size_t pos2 = myString.find("</article>");
std::string buf = myString.substr(pos1, pos2 - pos1 + 10);
myString = myString.substr(pos2 + 10);
ofstream myfile("body.txt");
if (myfile.is_open())
{
myfile << myString;
myfile.close();
}
else cout << "Unable to open file";
//cout << myString << endl;
ptree xmlTree;
string title[1000];
int j = 0;
try
{
stringstream ss;
ss << buf;
read_xml(ss, xmlTree);
const ptree & formats = xmlTree.get_child("article", empty_ptree());
BOOST_FOREACH(const ptree::value_type & f, formats)
{
string at = f.first + ATTR_SET;
const ptree & attributes = f.second.get_child("<xmlattr>", empty_ptree());
//cout << "Extracting attributes from " << at << ":" << endl;
BOOST_FOREACH(const ptree::value_type &v, attributes)
{
string first = v.first.data();
//cout << "First: " << v.first.data() << " Second: " << v.second.data() << endl;
if (first == "title")
{
title[j] = v.second.data();
j++;
}
}
}
for (int a = 0; a < j; a++)
{
cout << title[a] << endl;
}
}
catch (xml_parser_error &e) {
cout << "Failed to read config xml " << e.what() << endl;
}
catch (...) {
cout << "Failed to read config xml with unknown error" << endl;
}
dim = dim - pos2;
}
what is the problem?

I resolve my problem thanks to the help of PaulMcKenzie. I modify my code to insert a boolean variable and to control if pos1 and pos2 find the correct string which are <article and </article>.
This is the code:
int dim = myString.length();
boolean in=true;
while (in==true)
{
size_t pos1 = myString.find("<article");
size_t pos2 = myString.find("</article>");
if (pos1 != std::string::npos && pos2 != std::string::npos)
{
std::string buf = myString.substr(pos1, pos2 - pos1 + 10);
myString = myString.substr(pos2 + 10);
ofstream myfile("body.txt");
if (myfile.is_open())
{
myfile << myString;
myfile.close();
}
else cout << "Unable to open file";
//some code
dim = dim - myString.length();
in = true;
}
else
{
in = false;
cout << " - - - - - - - - - - " << endl;
}
}

Related

Infinity Loop in Lexical Analyzer in C++

int main(int argc, char *argv[]) {
ifstream inFile;
int numOfLines = 0, numOfTokens = 0, numOfStrings = 0, maxStringLength = 0, l = 0, fileCount=0, mostCommonCount=0;
string inputFile, mostCommonList="", word;
for(int i = 1; i < argc; i++){
if(strpbrk(argv[i] , "-")){
if(flags.find(string(argv[i]))!=flags.end()) flags[string(argv[i])] = true;
else{
cerr << "INVALID FLAG " << argv[i] << endl;
exit(1);
}
}
else{
inFile.open(argv[i]);
fileCount++;
if(!inFile && fileCount==1){
cerr << "UNABLE TO OPEN " << argv[i] << endl;
exit(1);
}
else{
string line;
while(getline(inFile, line)) inputFile+=line+='\n';
if(fileCount>1){
cerr << "TOO MANY FILE NAMES" << endl;
exit(1);
}
}
}
}
int linenum = 0;
TType tt;
Token tok;
while((tok = getNextToken(&inFile, &linenum))!=DONE && tok != ERR){
tt = tok.GetTokenType();
word = tok.GetLexeme();
if(flags["-v"]==true){
(tt == ICONST||tt==SCONST||tt==IDENT) ? cout<<enumTypes[tok.GetTokenType()]<<"("<< tok.GetLexeme()<<")"<<endl : cout<< enumTypes[tok.GetTokenType()]<<endl;
}
if(flags["-mci"]==true){
if(tt==IDENT){
(identMap.find(word)!=identMap.end()) ? identMap[word]++ : identMap[word]=1;
if(identMap[word]>mostCommonCount) mostCommonCount = identMap[word];
}
}
if(flags["-sum"]==true){
numOfTokens++;
if(tt==SCONST){
numOfStrings++;
l = word.length();
if(l > maxStringLength) maxStringLength = l;
}
}
}
if(tok==ERR){
cout << "Error on line" << tok.GetLinenum()<<"("<<tok.GetLexeme()<<")"<<endl;
return 0;
}
if(flags["-mci"]==true){
cout << "Most Common Identifier: ";
if(!identMap.empty()){
word ="";
for(auto const& it : identMap){
if(it.second==mostCommonCount) word += it.first + ",";
}
word.pop_back();
cout << word << endl;
}
}
if(flags["-sum"]){
numOfLines = tok.GetLinenum();
numOfLines = tok.GetLinenum();
cout << "Total lines: " << numOfLines << endl;
cout << "Total tokens: " << numOfTokens << endl;
cout << "Total strings: " << numOfStrings << endl;
cout << "Length of longest string: " << maxStringLength << endl;
}
inFile.close();
return 0;
}
For some reason this code is running infinitely. I cannot figure out the source of error. I also do not know whether this file or the other linked file is causing this error so I posted the main program code. I think is one of the switch statements that causing this error but I am not sure. FYI: I am supposed to make a lexical analyzer so I had three files one lexigh.h (contains all the data types and all the functions), getToken.cpp(file that defines the functions from lexigh.h) and the main program which calls the methods and tests it.

Where can I use OpenMP in my C++ code

I am writing a C++ code to calculate the code coverage and I want to used the OpenMP to help enhance my code by minimizing the overall run time by making the functions work in parallel so I can get less run time.
Can someone please tell me how and where to use the OpenMP?
int _tmain(int argc, _TCHAR* argv[])
{
std::clock_t start;
start = std::clock();
char inputFilename[] = "Test-Case-3.cs"; // Test Case File
char outputFilename[] = "Result.txt"; // Result File
int totalNumberOfLines = 0;
int numberOfBranches = 0;
int statementsCovered = 0;
float statementCoveragePercentage = 0;
double overallRuntime = 0;
ifstream inFile; // object for reading from a file
ofstream outFile; // object for writing to a file
inFile.open(inputFilename, ios::in);
if (!inFile) {
cerr << "Can't open input file " << inputFilename << endl;
exit(1);
}
totalNumberOfLines = NoOfLines(inFile);
inFile.clear(); // reset
inFile.seekg(0, ios::beg);
numberOfBranches = NoOfBranches(inFile);
inFile.close();
statementsCovered = totalNumberOfLines - numberOfBranches;
statementCoveragePercentage = (float)statementsCovered * 100/ totalNumberOfLines;
outFile.open(outputFilename, ios::out);
if (!outFile) {
cerr << "Can't open output file " << outputFilename << endl;
exit(1);
}
outFile << "Total Number of Lines" << " : " << totalNumberOfLines << endl;
outFile << "Number of Branches" << " : " << numberOfBranches << endl;
outFile << "Statements Covered" << " : " << statementsCovered << endl;
outFile << "Statement Coverage Percentage" << " : " << statementCoveragePercentage <<"%"<< endl;
overallRuntime = (std::clock() - start) / (double)CLOCKS_PER_SEC;
outFile << "Overall Runtime" << " : " << overallRuntime << " Seconds"<< endl;
outFile.close();
}
i want to minimize the time taken to count the number of branches by allowing multiple threads to work in parallel to calculate the number faster? how can i edit the code so that i can use the open mp and here you can find my functions:bool is_only_ascii_whitespace(const std::string& str)
{
auto it = str.begin();
do {
if (it == str.end()) return true;
} while (*it >= 0 && *it <= 0x7f && std::isspace(*(it++)));
// one of these conditions will be optimized away by the compiler,
// which one depends on whether char is signed or not
return false;
}
// Function 1
int NoOfLines(ifstream& inFile)
{
//char line[1000];
string line;
int lines = 0;
while (!inFile.eof()) {
getline(inFile, line);
//cout << line << endl;
if ((line.find("//") == std::string::npos)) // Remove Comments
{
if (!is_only_ascii_whitespace(line)) // Remove Blank
{
lines++;
}
}
//cout << line << "~" <<endl;
}
return lines;
}
// Function 2
int NoOfBranches(ifstream& inFile)
{
//char line[1000];
string line;
int branches = 0;
while (!inFile.eof()) {
getline(inFile, line);
if ((line.find("if") != std::string::npos) || (line.find("else") != std::string::npos))
{
branches++;
}
}
return branches;
}

segfault variable creation c++

So I'm having some troubles with a segfault right now.
The problem appears to be on line 122
file_stream.read(binaryData, fileSizeInt);
The message seems to be unable to create variable object.
I'm using the debugger on CLion, if this is of any help.
I'm fairly new to C++ so please bear with me on this. I've included my source code below, since I have no idea what will and wont be relevant.
#include <fstream>
#include <iostream>
#include <math.h>
using namespace std;
//string dataLocation = "/dev/rdisk2"; // Variable for the mounting point of the SD Card.
string dataLocation = "/Volumes/Untitled/data/smith_data_backup.dat"; // Test location
int sectorSize = 512;
int bytesRead = 0;
string outDir = "/Volumes/Untitled/data/readData/";
char data_stop[10] = "Data_Stop";
char* findHeader(char* inputData) {
int i = 1;
//look for the end of the header
while(true) {
//cout << data[i] << '\n';
if (inputData[i] == '}') {
// found the end of the header
cout << "found the end of the header" << '\n';
break;
}
if (i > 200) { // don't get into an infinite loop here
cout << "something went wrong here" << '\n';
break;
}
i++;
}
// copy the header to a new char array
char* header = new char[i+1];
memcpy(header, &inputData[0], (size_t) (i +1));
return header;
}
int main() {
ifstream file_stream;
file_stream.open(dataLocation);
for( int j = 0; j < 10; j++ ) {
char data[sectorSize]; // figure out a decent size for this.....
string date = "";
string time = "";
string site = "";
string intId = "";
string totalFiles = "";
string fileNo = "";
string fileSize = "";
try {
// read the data file... this will be fun
cout << "Reading the data file" << '\n';
file_stream.read(data, sectorSize);
bytesRead += sectorSize;
if (data[0] == '{') {
char *header = findHeader(data);
cout << header << '\n';
//loop over the header to find the date, time, site ID, Instrument ID, and expected file size.
int commasFound = 0;
for(int i = 1; header[i] != '}', i++;) {
// increment the number of commas that have been found
if (header[i] == ',') {
commasFound ++;
continue;
}
//check for the end f the header
if (header[i] == '}') {
break;
}
//for some reason the first one never gets added
if (i==2) {
date += header[1];
}
// append to appropriate strings based on the number of commas that have been passed in the header
if (commasFound == 0) {
date += header[i];
}
if (commasFound == 1 && time.length() < 6) {
time += header[i];
}
if (commasFound == 2) {
fileNo += header[i];
}
if (commasFound == 6) {
site += header[i];
}
if (commasFound == 8) {
intId += header[i];
}
if (commasFound == 16) {
fileSize += header[i];
}
if (commasFound == 17) {
totalFiles += header[i];
}
//paranoia of infinite loops
if (i > 150) {
break;
}
}
string formattedDate = "20" + date.substr(4,2) + date.substr(2,2) + date.substr(0,2);
cout << formattedDate << " " << time << " " << " " << site << " " << intId << " " << fileSize << " " << totalFiles<< " " << '\n';
// Read in the data size
int fileSizeInt = atoi(fileSize.c_str()) * atoi(fileSize.c_str());
char binaryData[fileSizeInt];
file_stream.read(binaryData, fileSizeInt);
bytesRead += fileSizeInt;
string dateDir = outDir + formattedDate.substr(0,4) + "/" + date.substr(2,2) + "/" + site + "/" + date.substr(0,2) + "/";
string fileName = dateDir + formattedDate + "_" + time + "_" + site + "_" + intId + "_Full_Data.dat";
//cout << fileName << '\n';
//create the directory with the date.
string mkdirCommand = "mkdir -p " + dateDir;
system(mkdirCommand.c_str());
cout << "size " << sizeof(binaryData) << '\n';
//write data to file
try {
cout << "Write the data file " << '\n';
cout << header << " " << strlen(header) << '\n';
ofstream outFile;
outFile.open(fileName.c_str());
outFile.write(header, strlen(header));
outFile.write(binaryData, sizeof(binaryData));
outFile.write(data_stop, sizeof(data_stop));
outFile.close();
} catch (ofstream::failure e ) {
cout << "Unable to write the file " << fileName << '\n';
}
//read till the start of the next sector
int nextSector = (int) ceil(((double) bytesRead)/512.0);
int startOfNextSector = nextSector * 512;
cout << startOfNextSector << '\n';
int bytesToRead = startOfNextSector - bytesRead;
char dump[bytesToRead];
file_stream.read(dump, bytesToRead);
bytesRead += bytesToRead;
// The first block may be empty, quick check to see if the first block needs to be skipped
} else if (j == 0 && data[0] != '{') {
cout << "Skipping the first block" << '\n';
continue;
} else {
//cout << "no start here....." << bytesRead << '\n';
}
}
catch (ifstream::failure& e) {
cout << "Error" << "\n";
break;
}
}
file_stream.close();
return 0;
}

C++ ifstream working but not ofstream

Basically when I close the program the vectors are put in a txt file and when the program starts it reads from that file.
If I put some information in the txt file and start the program, it works fine (ifstream works)
But I cannot add things to the file/create a file if there is not a file already (ofstream does not work)
Here is my code:
Library::Library()
{
ifstream fin("libBooks.txt");
string inputLine;
if (fin.fail())
{
lastBookIDUsed = 0;
}
getline(fin, inputLine);
lastBookIDUsed = stringToInt(inputLine);
while (!fin.eof())
{
getline(fin, inputLine);
if ((!fin.eof())&&(inputLine.length()!=0))
{
vector<string> token = tokenize(inputLine);
addBook(token[1], token[2], token[3], stringToInt(token[0]), stringToInt(token[4]));
}
else
{
break;
}
}
fin.close();
ifstream finPatron("libPatrons.txt");
string inputLinePatron;
if (finPatron.fail())
{
lastPatronIDUsed = 0;
}
getline(finPatron, inputLinePatron);
lastPatronIDUsed = stringToInt(inputLinePatron);
while (!finPatron.eof())
{
getline(finPatron, inputLinePatron);
if ((!finPatron.eof()) && (inputLinePatron.length() != 0))
{
vector<string> token = tokenize(inputLinePatron);
vector<int> TEMPbooksCheckedOutID;
//Create a vector for the IDs of books this patron has
int numOfBooksCheckedOut = token.size() - 5;
if (numOfBooksCheckedOut < 1)
{
for (int i = 0; i < numOfBooksCheckedOut; i++)
{
TEMPbooksCheckedOutID.push_back(stringToInt(token[4 + i]));
}
}
addPatron(token[1], token[2], token[3], stringToInt(token[0]), TEMPbooksCheckedOutID, stringToInt(token[4 + numOfBooksCheckedOut]));
}
else
{
break;
}
}
finPatron.close();
}
Library::~Library()
{
ofstream fout("libBooks.txt");
if (!fout.is_open())
std::cout << "Could not open libBooks" << endl;
fout << lastBookIDUsed << endl;
vector<Book>::iterator iter;
iter = vBook.begin();
while (iter != vBook.end())
{
if (!(*iter).isDeleted)
{
fout << (*iter).id << " ";
fout << (*iter).name << ";";
fout << (*iter).author << ";";
fout << (*iter).subject << ";";
fout << (*iter).checkOutBy << endl;
}
iter++;
}
fout.close();
ofstream foutPatron("libPatrons.txt");
if (!foutPatron.is_open())
std::cout << "Could not open libPatrons" << endl;
foutPatron << lastPatronIDUsed << endl;
vector<Patron>::iterator iterPatron;
iterPatron = vPatron.begin();
while (iterPatron != vPatron.end())
{
if (!(*iterPatron).isDeleted)
{
foutPatron << (*iterPatron).id << " ";
foutPatron << (*iterPatron).name << ";";
foutPatron << (*iterPatron).phoneNumber << ";";
foutPatron << (*iterPatron).email << ";";
vector<int>::iterator iter2;
iter2 = (*iterPatron).booksCheckedOutID.begin();
while (iter2 != (*iterPatron).booksCheckedOutID.end())
{
foutPatron << (*iter2) << ";";
iter2++;
}
foutPatron << (*iterPatron).hasAtLeastOneBook << endl;
}
iterPatron++;
}
foutPatron.close();
}
Thanks!

std::out of range in a noxim code

Im starting with some SystemC coding and i'm trying to use a Network-on-chip simulator called "Noxim", which i've heard is very smooth and simple. However, im getting this common error when I'm trying to "make" some part of the simulation
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::substr
Abort
I think it comes from a cpp code, which I DO NOT own and, sincerely, dont fully understand. The code can be found bellow, and the full Noxim distribution can be found here: https://github.com/alexayin/Noxim
The code is at Noxim/other/
Noxim_explorer.cpp and sim.cfg are strongly related to the lab im trying to do.
Please, if someone has solved this problem or have any idea, it would be very helpful.
FOR THE RECORD: I got stucked when trying to follow this lab http://access.ee.ntu.edu.tw/noxim/Lab2.pdf, 'cause I couldnt get any info in the matlab file
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <string>
#include <cassert>
#include <cstdlib>
#include <sys/time.h>
using namespace std;
//---------------------------------------------------------------------------
#define DEFAULT_KEY "default"
#define AGGREGATION_KEY "aggregation"
#define EXPLORER_KEY "explorer"
#define SIMULATOR_LABEL "simulator"
#define REPETITIONS_LABEL "repetitions"
#define TMP_DIR_LABEL "tmp"
#define DEF_SIMULATOR "./noxim"
#define DEF_REPETITIONS 5
#define DEF_TMP_DIR "./"
#define TMP_FILE_NAME ".noxim_explorer.tmp"
#define RPACKETS_LABEL "% Total received packets:"
#define RFLITS_LABEL "% Total received flits:"
#define AVG_DELAY_LABEL "% Global average delay (cycles):"
#define AVG_THROUGHPUT_LABEL "% Global average throughput (flits/cycle):"
#define THROUGHPUT_LABEL "% Throughput (flits/cycle/IP):"
#define MAX_DELAY_LABEL "% Max delay (cycles):"
#define TOTAL_ENERGY_LABEL "% Total energy (J):"
#define MATLAB_VAR_NAME "data"
#define MATRIX_COLUMN_WIDTH 15
//---------------------------------------------------------------------------
typedef unsigned int uint;
// parameter values
typedef vector<string> TParameterSpace;
// parameter name, parameter space
typedef map<string, TParameterSpace> TParametersSpace;
// parameter name, parameter value
typedef vector<pair<string, string> > TConfiguration;
typedef vector<TConfiguration> TConfigurationSpace;
struct TExplorerParams
{
string simulator;
string tmp_dir;
int repetitions;
};
struct TSimulationResults
{
double avg_delay;
double throughput;
double avg_throughput;
double max_delay;
double total_energy;
unsigned int rpackets;
unsigned int rflits;
};
//---------------------------------------------------------------------------
double GetCurrentTime()
{
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_sec + (tv.tv_usec * 1.0e-6);
}
//---------------------------------------------------------------------------
void TimeToFinish(double elapsed_sec,
int completed, int total,
int& hours, int& minutes, int &seconds)
{
double total_time_sec = (elapsed_sec * total)/completed;
double remain_time_sec = total_time_sec - elapsed_sec;
seconds = (int)remain_time_sec % 60;
minutes = ((int)remain_time_sec / 60) % 60;
hours = (int)remain_time_sec / 3600;
}
//---------------------------------------------------------------------------
bool IsComment(const string& s)
{
return (s == "" || s.at(0) == '%');
}
//---------------------------------------------------------------------------
string TrimLeftAndRight(const string& s)
{
int len = s.length();
int i, j;
for (i=0; i<len && s.at(i) == ' '; i++) ;
for (j=len-1; j>=0 && s.at(j) == ' '; j--) ;
return s.substr(i,j-i+1);
}
//---------------------------------------------------------------------------
bool ExtractParameter(const string& s, string& parameter)
{
uint i = s.find("[");
if (i != string::npos)
{
uint j = s.rfind("]");
if (j != string::npos)
{
parameter = s.substr(i+1, j-i-1);
return true;
}
}
return false;
}
//---------------------------------------------------------------------------
bool GetNextParameter(ifstream& fin, string& parameter)
{
bool found = false;
while (!fin.eof() && !found)
{
string s;
getline(fin, s);
if (!IsComment(s))
found = ExtractParameter(s, parameter);
}
return found;
}
//---------------------------------------------------------------------------w
string MakeStopParameterTag(const string& parameter)
{
string sparameter = "[/" + parameter + "]";
return sparameter;
}
//---------------------------------------------------------------------------
bool ManagePlainParameterSet(ifstream& fin,
const string& parameter,
TParametersSpace& params_space,
string& error_msg)
{
string str_stop = MakeStopParameterTag(parameter);
bool stop = false;
while (!fin.eof() && !stop)
{
string s;
getline(fin, s);
if (!IsComment(s))
{
if (s.find(str_stop) != string::npos)
stop = true;
else
params_space[parameter].push_back(TrimLeftAndRight(s));
}
}
return true;
}
//---------------------------------------------------------------------------
bool ExpandInterval(const string& sint,
TParameterSpace& ps,
string& error_msg)
{
istringstream iss(sint);
double min, max, step;
iss >> min;
iss >> max;
iss >> step;
string param_suffix;
getline(iss, param_suffix);
for (double v=min; v<=max; v+=step)
{
ostringstream oss;
oss << v;
ps.push_back(oss.str() + param_suffix);
}
return true;
}
//---------------------------------------------------------------------------
bool ManageCompressedParameterSet(ifstream& fin,
const string& parameter,
TParametersSpace& params_space,
string& error_msg)
{
string str_stop = MakeStopParameterTag(parameter);
bool stop = false;
while (!fin.eof() && !stop)
{
string s;
getline(fin, s);
if (!IsComment(s))
{
if (s.find(str_stop) != string::npos)
stop = true;
else
{
if (!ExpandInterval(s, params_space[parameter], error_msg))
return false;
}
}
}
return true;
}
//---------------------------------------------------------------------------
bool ManageParameter(ifstream& fin,
const string& parameter,
TParametersSpace& params_space,
string& error_msg)
{
bool err;
if (parameter == "pir")
err = ManageCompressedParameterSet(fin, parameter, params_space, error_msg);
else
err = ManagePlainParameterSet(fin, parameter, params_space, error_msg);
return err;
}
//---------------------------------------------------------------------------
bool ParseConfigurationFile(const string& fname,
TParametersSpace& params_space,
string& error_msg)
{
ifstream fin(fname.c_str(), ios::in);
if (!fin)
{
error_msg = "Cannot open " + fname;
return false;
}
while (!fin.eof())
{
string parameter;
if ( GetNextParameter(fin, parameter) )
{
if (!ManageParameter(fin, parameter, params_space, error_msg))
return false;
}
}
return true;
}
//---------------------------------------------------------------------------
bool LastCombination(const vector<pair<int,int> >& indexes)
{
for (uint i=0; i<indexes.size(); i++)
if (indexes[i].first < indexes[i].second-1)
return false;
return true;
}
//---------------------------------------------------------------------------
bool IncrementCombinatorialIndexes(vector<pair<int,int> >& indexes)
{
for (uint i=0; i<indexes.size(); i++)
{
if (indexes[i].first < indexes[i].second - 1)
{
indexes[i].first++;
return true;
}
indexes[i].first = 0;
}
return false;
}
//---------------------------------------------------------------------------
TConfigurationSpace Explore(const TParametersSpace& params_space)
{
TConfigurationSpace conf_space;
vector<pair<int,int> > indexes; // <index, max_index>
for (TParametersSpace::const_iterator psi=params_space.begin();
psi!=params_space.end(); psi++)
indexes.push_back(pair<int,int>(0, psi->second.size()));
do
{
int i = 0;
TConfiguration conf;
for (TParametersSpace::const_iterator psi=params_space.begin();
psi!=params_space.end(); psi++)
{
conf.push_back( pair<string,string>(psi->first,
psi->second[indexes[i].first]));
i++;
}
conf_space.push_back(conf);
}
while (IncrementCombinatorialIndexes(indexes));
return conf_space;
}
//---------------------------------------------------------------------------
bool RemoveParameter(TParametersSpace& params_space,
const string& param_name,
TParameterSpace& param_space,
string& error_msg)
{
TParametersSpace::iterator i = params_space.find(param_name);
if (i == params_space.end())
{
error_msg = "Cannot extract parameter '" + param_name + "'";
return false;
}
param_space = params_space[param_name];
params_space.erase(i);
return true;
}
//---------------------------------------------------------------------------
bool RemoveAggregateParameters(TParametersSpace& params_space,
TParameterSpace& aggregated_params,
TParametersSpace& aggragated_params_space,
string& error_msg)
{
for (uint i=0; i<aggregated_params.size(); i++)
{
string param_name = aggregated_params[i];
TParameterSpace param_space;
if (!RemoveParameter(params_space, param_name, param_space, error_msg))
return false;
aggragated_params_space[param_name] = param_space;
}
return true;
}
//---------------------------------------------------------------------------
string ParamValue2Cmd(const pair<string,string>& pv)
{
string cmd;
if (pv.first == "topology")
{
istringstream iss(pv.second);
int width, height;
char times;
iss >> width >> times >> height;
ostringstream oss;
oss << "-dimx " << width << " -dimy " << height;
cmd = oss.str();
}
else
cmd = "-" + pv.first + " " + pv.second;
return cmd;
}
//---------------------------------------------------------------------------
string Configuration2CmdLine(const TConfiguration& conf)
{
string cl;
for (uint i=0; i<conf.size(); i++)
cl = cl + ParamValue2Cmd(conf[i]) + " ";
return cl;
}
//---------------------------------------------------------------------------
string Configuration2FunctionName(const TConfiguration& conf)
{
string fn;
for (uint i=0; i<conf.size(); i++)
fn = fn + conf[i].first + "_" + conf[i].second + "__";
// Replace " ", "-", ".", "/" with "_"
int len = fn.length();
for (int i=0; i<len; i++)
if (fn.at(i) == ' ' || fn.at(i) == '.' || fn.at(i) == '-' || fn.at(i) == '/')
fn[i] = '_';
return fn;
}
//---------------------------------------------------------------------------
bool ExtractExplorerParams(const TParameterSpace& explorer_params,
TExplorerParams& eparams,
string& error_msg)
{
eparams.simulator = DEF_SIMULATOR;
eparams.tmp_dir = DEF_TMP_DIR;
eparams.repetitions = DEF_REPETITIONS;
for (uint i=0; i<explorer_params.size(); i++)
{
istringstream iss(explorer_params[i]);
string label;
iss >> label;
if (label == SIMULATOR_LABEL)
iss >> eparams.simulator;
else if (label == REPETITIONS_LABEL)
iss >> eparams.repetitions;
else if (label == TMP_DIR_LABEL)
iss >> eparams.tmp_dir;
else
{
error_msg = "Invalid explorer option '" + label + "'";
return false;
}
}
return true;
}
//---------------------------------------------------------------------------
bool PrintHeader(const string& fname,
const TExplorerParams& eparams,
const string& def_cmd_line, const string& conf_cmd_line,
ofstream& fout,
string& error_msg)
{
fout.open(fname.c_str(), ios::out);
if (!fout)
{
error_msg = "Cannot create " + fname;
return false;
}
fout << "% fname: " << fname << endl
<< "% " << eparams.simulator << " "
<< conf_cmd_line << " " << def_cmd_line
<< endl << endl;
return true;
}
//---------------------------------------------------------------------------
bool PrintMatlabFunction(const string& mfname,
ofstream& fout,
string& error_msg)
{
fout << "function [max_pir, max_throughput, min_delay] = " << mfname << "(symbol)" << endl
<< endl;
return true;
}
//---------------------------------------------------------------------------
bool ReadResults(const string& fname,
TSimulationResults& sres,
string& error_msg)
{
ifstream fin(fname.c_str(), ios::in);
if (!fin)
{
error_msg = "Cannot read " + fname;
return false;
}
int nread = 0;
while (!fin.eof())
{
string line;
getline(fin, line);
uint pos;
pos = line.find(RPACKETS_LABEL);
if (pos != string::npos)
{
nread++;
istringstream iss(line.substr(pos + string(RPACKETS_LABEL).size()));
iss >> sres.rpackets;
continue;
}
pos = line.find(RFLITS_LABEL);
if (pos != string::npos)
{
nread++;
istringstream iss(line.substr(pos + string(RFLITS_LABEL).size()));
iss >> sres.rflits;
continue;
}
pos = line.find(AVG_DELAY_LABEL);
if (pos != string::npos)
{
nread++;
istringstream iss(line.substr(pos + string(AVG_DELAY_LABEL).size()));
iss >> sres.avg_delay;
continue;
}
pos = line.find(AVG_THROUGHPUT_LABEL);
if (pos != string::npos)
{
nread++;
istringstream iss(line.substr(pos + string(AVG_THROUGHPUT_LABEL).size()));
iss >> sres.avg_throughput;
continue;
}
pos = line.find(THROUGHPUT_LABEL);
if (pos != string::npos)
{
nread++;
istringstream iss(line.substr(pos + string(THROUGHPUT_LABEL).size()));
iss >> sres.throughput;
continue;
}
pos = line.find(MAX_DELAY_LABEL);
if (pos != string::npos)
{
nread++;
istringstream iss(line.substr(pos + string(MAX_DELAY_LABEL).size()));
iss >> sres.max_delay;
continue;
}
pos = line.find(TOTAL_ENERGY_LABEL);
if (pos != string::npos)
{
nread++;
istringstream iss(line.substr(pos + string(TOTAL_ENERGY_LABEL).size()));
iss >> sres.total_energy;
continue;
}
}
if (nread != 7)
{
error_msg = "Output file " + fname + " corrupted";
return false;
}
return true;
}
//---------------------------------------------------------------------------
bool RunSimulation(const string& cmd_base,
const string& tmp_dir,
TSimulationResults& sres,
string& error_msg)
{
string tmp_fname = tmp_dir + TMP_FILE_NAME;
// string cmd = cmd_base + " >& " + tmp_fname; // this works only with csh and bash
string cmd = cmd_base + " >" + tmp_fname + " 2>&1"; // this works with sh, csh, and bash!
cout << cmd << endl;
system(cmd.c_str());
if (!ReadResults(tmp_fname, sres, error_msg))
return false;
string rm_cmd = string("rm -f ") + tmp_fname;
system(rm_cmd.c_str());
return true;
}
//---------------------------------------------------------------------------
string ExtractFirstField(const string& s)
{
istringstream iss(s);
string sfirst;
iss >> sfirst;
return sfirst;
}
//---------------------------------------------------------------------------
bool RunSimulations(double start_time,
pair<uint,uint>& sim_counter,
const string& cmd, const string& tmp_dir, const int repetitions,
const TConfiguration& aggr_conf,
ofstream& fout,
string& error_msg)
{
int h, m, s;
for (int i=0; i<repetitions; i++)
{
cout << "# simulation " << (++sim_counter.first) << " of " << sim_counter.second;
if (i != 0)
cout << ", estimated time to finish " << h << "h " << m << "m " << s << "s";
cout << endl;
TSimulationResults sres;
if (!RunSimulation(cmd, tmp_dir, sres, error_msg))
return false;
double current_time = GetCurrentTime();
TimeToFinish(current_time-start_time, sim_counter.first, sim_counter.second, h, m, s);
// Print aggragated parameters
fout << " ";
for (uint i=0; i<aggr_conf.size(); i++)
fout << setw(MATRIX_COLUMN_WIDTH) << ExtractFirstField(aggr_conf[i].second); // this fix the problem with pir
// fout << setw(MATRIX_COLUMN_WIDTH) << aggr_conf[i].second;
// Print results;
fout << setw(MATRIX_COLUMN_WIDTH) << sres.avg_delay
<< setw(MATRIX_COLUMN_WIDTH) << sres.throughput
<< setw(MATRIX_COLUMN_WIDTH) << sres.max_delay
<< setw(MATRIX_COLUMN_WIDTH) << sres.total_energy
<< setw(MATRIX_COLUMN_WIDTH) << sres.rpackets
<< setw(MATRIX_COLUMN_WIDTH) << sres.rflits
<< endl;
}
return true;
}
//---------------------------------------------------------------------------
bool PrintMatlabVariableBegin(const TParametersSpace& aggragated_params_space,
ofstream& fout, string& error_msg)
{
fout << MATLAB_VAR_NAME << " = [" << endl;
fout << "% ";
for (TParametersSpace::const_iterator i=aggragated_params_space.begin();
i!=aggragated_params_space.end(); i++)
fout << setw(MATRIX_COLUMN_WIDTH) << i->first;
fout << setw(MATRIX_COLUMN_WIDTH) << "avg_delay"
<< setw(MATRIX_COLUMN_WIDTH) << "throughput"
<< setw(MATRIX_COLUMN_WIDTH) << "max_delay"
<< setw(MATRIX_COLUMN_WIDTH) << "total_energy"
<< setw(MATRIX_COLUMN_WIDTH) << "rpackets"
<< setw(MATRIX_COLUMN_WIDTH) << "rflits";
fout << endl;
return true;
}
//---------------------------------------------------------------------------
bool GenMatlabCode(const string& var_name,
const int fig_no,
const int repetitions, const int column,
ofstream& fout, string& error_msg)
{
fout << var_name << " = [];" << endl
<< "for i = 1:rows/" << repetitions << "," << endl
<< " ifirst = (i - 1) * " << repetitions << " + 1;" << endl
<< " ilast = ifirst + " << repetitions << " - 1;" << endl
<< " tmp = " << MATLAB_VAR_NAME << "(ifirst:ilast, cols-6+" << column << ");" << endl
<< " avg = mean(tmp);" << endl
<< " [h sig ci] = ttest(tmp, 0.1);" << endl
<< " ci = (ci(2)-ci(1))/2;" << endl
<< " " << var_name << " = [" << var_name << "; " << MATLAB_VAR_NAME << "(ifirst, 1:cols-6), avg ci];" << endl
<< "end" << endl
<< endl;
fout << "figure(" << fig_no << ");" << endl
<< "hold on;" << endl
<< "plot(" << var_name << "(:,1), " << var_name << "(:,2), symbol);" << endl
<< endl;
return true;
}
//---------------------------------------------------------------------------
bool GenMatlabCodeSaturationAnalysis(const string& var_name,
ofstream& fout, string& error_msg)
{
fout << endl
<< "%-------- Saturation Analysis -----------" << endl
<< "slope=[];" << endl
<< "for i=2:size(" << var_name << "_throughput,1)," << endl
<< " slope(i-1) = (" << var_name << "_throughput(i,2)-" << var_name << "_throughput(i-1,2))/(" << var_name << "_throughput(i,1)-" << var_name << "_throughput(i-1,1));" << endl
<< "end" << endl
<< endl
<< "for i=2:size(slope,2)," << endl
<< " if slope(i) < (0.95*mean(slope(1:i)))" << endl
<< " max_pir = " << var_name << "_throughput(i, 1);" << endl
<< " max_throughput = " << var_name << "_throughput(i, 2);" << endl
<< " min_delay = " << var_name << "_delay(i, 2);" << endl
<< " break;" << endl
<< " end" << endl
<< "end" << endl;
return true;
}
//---------------------------------------------------------------------------
bool PrintMatlabVariableEnd(const int repetitions,
ofstream& fout, string& error_msg)
{
fout << "];" << endl << endl;
fout << "rows = size(" << MATLAB_VAR_NAME << ", 1);" << endl
<< "cols = size(" << MATLAB_VAR_NAME << ", 2);" << endl
<< endl;
if (!GenMatlabCode(string(MATLAB_VAR_NAME) + "_delay", 1,
repetitions, 1, fout, error_msg))
return false;
if (!GenMatlabCode(string(MATLAB_VAR_NAME) + "_throughput", 2,
repetitions, 2, fout, error_msg))
return false;
if (!GenMatlabCode(string(MATLAB_VAR_NAME) + "_maxdelay", 3,
repetitions, 3, fout, error_msg))
return false;
if (!GenMatlabCode(string(MATLAB_VAR_NAME) + "_totalenergy", 4,
repetitions, 4, fout, error_msg))
return false;
if (!GenMatlabCodeSaturationAnalysis(string(MATLAB_VAR_NAME), fout, error_msg))
return false;
return true;
}
//---------------------------------------------------------------------------
bool RunSimulations(const TConfigurationSpace& conf_space,
const TParameterSpace& default_params,
const TParametersSpace& aggragated_params_space,
const TParameterSpace& explorer_params,
string& error_msg)
{
TExplorerParams eparams;
if (!ExtractExplorerParams(explorer_params, eparams, error_msg))
return false;
// Make dafault parameters string
string def_cmd_line;
for (uint i=0; i<default_params.size(); i++)
def_cmd_line = def_cmd_line + default_params[i] + " ";
// Explore configuration space
TConfigurationSpace aggr_conf_space = Explore(aggragated_params_space);
pair<uint,uint> sim_counter(0, conf_space.size() * aggr_conf_space.size() * eparams.repetitions);
double start_time = GetCurrentTime();
for (uint i=0; i<conf_space.size(); i++)
{
string conf_cmd_line = Configuration2CmdLine(conf_space[i]);
string mfname = Configuration2FunctionName(conf_space[i]);
string fname = mfname + ".m";
ofstream fout;
if (!PrintHeader(fname, eparams,
def_cmd_line, conf_cmd_line, fout, error_msg))
return false;
if (!PrintMatlabFunction(mfname, fout, error_msg))
return false;
if (!PrintMatlabVariableBegin(aggragated_params_space, fout, error_msg))
return false;
for (uint j=0; j<aggr_conf_space.size(); j++)
{
string aggr_cmd_line = Configuration2CmdLine(aggr_conf_space[j]);
/*
string cmd = eparams.simulator + " "
+ def_cmd_line + " "
+ conf_cmd_line + " "
+ aggr_cmd_line;
*/
string cmd = eparams.simulator + " "
+ aggr_cmd_line + " "
+ def_cmd_line + " "
+ conf_cmd_line;
if (!RunSimulations(start_time,
sim_counter, cmd, eparams.tmp_dir, eparams.repetitions,
aggr_conf_space[j], fout, error_msg))
return false;
}
if (!PrintMatlabVariableEnd(eparams.repetitions, fout, error_msg))
return false;
}
return true;
}
//---------------------------------------------------------------------------
bool RunSimulations(const string& script_fname,
string& error_msg)
{
TParametersSpace ps;
if (!ParseConfigurationFile(script_fname, ps, error_msg))
return false;
TParameterSpace default_params;
if (!RemoveParameter(ps, DEFAULT_KEY, default_params, error_msg))
cout << "Warning: " << error_msg << endl;
TParameterSpace aggregated_params;
TParametersSpace aggragated_params_space;
if (!RemoveParameter(ps, AGGREGATION_KEY, aggregated_params, error_msg))
cout << "Warning: " << error_msg << endl;
else
if (!RemoveAggregateParameters(ps, aggregated_params,
aggragated_params_space, error_msg))
return false;
TParameterSpace explorer_params;
if (!RemoveParameter(ps, EXPLORER_KEY, explorer_params, error_msg))
cout << "Warning: " << error_msg << endl;
TConfigurationSpace conf_space = Explore(ps);
if (!RunSimulations(conf_space, default_params,
aggragated_params_space, explorer_params, error_msg))
return false;
return true;
}
//---------------------------------------------------------------------------
int main(int argc, char **argv)
{
if (argc < 2)
{
cout << "Usage: " << argv[0] << " <cfg file> [<cfg file>]" << endl;
return -1;
}
for (int i=1; i<argc; i++)
{
string fname(argv[i]);
cout << "# Exploring configuration space " << fname << endl;
string error_msg;
if (!RunSimulations(fname, error_msg))
cout << "Error: " << error_msg << endl;
cout << endl;
}
return 0;
}
//---------------------------------------------------------------------------
U are probably using a 64 bit pc
At Noxim_explorer.cpp
change
///////////////////////////////
uint pos;
pos = line.find(RPACKETS_LABEL);
///////////////////////////////
to ...
///////////////////////////////
std::size_t pos = line.find(RPACKETS_LABEL);
///////////////////////////////
It should work .. and generate the matlab file