int main()
{
	//create an input stream object
	std::ifstream ifs;

	//open file for input
	std::string fileName = "regDB.csv";
	ifs.open(fileName, std::ios::in);
	checkFile(ifs);

	//parse data and read from file
	std::cout << "*** Reading from " << fileName << " ***\n\n";
	std::vector<std::string> data = parseInputFile(ifs);

	//print parsed data to stdout
	int j = 0;
	for (auto i = data.begin(); i != data.end(); ++i) {
		std::cout << *i;
		if (!(++j % 3)) //print a newrecord after processing three fields
			std::cout << '\n';
		else
			std::cout << ' ';
	}

	ifs.close();
}
Пример #2
0
int main()
{
	INTVEC conf = parseInputFile();
	/*
	for(INTVEC_CITER iter = conf.begin(); iter != conf.end(); ++iter)
	{
	std::cout << *iter << " ";
	}
	std::cout << std::endl;
	*/

	std::cout << "Create BinaryTree!" << std::endl;
	pNode pRoot = CreateBinaryTree(conf, 0, conf.size());

	std::cout << "Print BinaryTree!" << std::endl;
	printBinaryTree(pRoot, 0);
	for(std::map<int, INTVEC>::const_iterator mciter = m_tmp.begin(); mciter != m_tmp.end(); ++mciter)
	{
		for(INTVEC_CITER iter = mciter->second.begin(); iter != mciter->second.end(); ++iter)
		{
			std::cout << *iter << " ";
		}
		std::cout << std::endl;
	}
	return 0; 

}
Пример #3
0
int main(int argc, char** argv)
{
	try
	{
		std::cout << "Reading data and loading (generating) matrixes..." << std::endl;
		parseArguments(argc, argv);
		parseInputFile();
		std::cout << "Matrixes loaded." << std::endl << std::endl;
		tbb::tick_count before, after;

		/*
		std::cout << "Serial Multiplication Simple started\nThis may take a minute...\n\n";
		before = tbb::tick_count::now();
		serialMultiplySimple();
		after = tbb::tick_count::now();
		std::cout << "Serial multiplication Simple finished!" << std::endl
			<< "Calculating took " << (after - before).seconds() << " seconds.\n\n";
		*/

		if (ApplicationData::getInstance()->shouldDoSerial())
		{
			std::cout << "Serial Multiplication started\nThis may take a minute...\n\n";
			before = tbb::tick_count::now();
			serialMultiply();
			after = tbb::tick_count::now();
			std::cout << "Serial multiplication finished!" << std::endl
				<< "Calculating took " << (after - before).seconds() << " seconds.\n\n";
		}

		if (ApplicationData::getInstance()->shouldDoParallel())
		{
			std::cout << "Parallel Multiplication started \nThis may take a minute...\n\n";
			before = tbb::tick_count::now();
			parallelMultiply();
			after = tbb::tick_count::now();
			std::cout << "Parallel multiplication finished!" << std::endl
				<< "Calculating took " << (after - before).seconds() << " seconds.\n\n";
		}

		
		std::cout << "Writting data to output file." << std::endl;
		writeToFile();
		std::cout << "Data writting finished.\n Check results in file which you passed through command line arguments.\n";
	}
	catch (std::runtime_error& e)
	{
		std::cout << e.what() << std::endl;
	}
	return 0;
}
//	~~~~~~~~~~~~~~~~~~~	Main ~~~~~~~~~~~~~~~~~~~
int main( int argc, char * * argv )
{
	char * inputFile = argv[1];

	int i = 0;
	for( i = 0; i < argc; i++ )
	{
		printf( "%s\n", argv[i] );
	}

	//	Parsing Input, Generate Graph and Output
	parseInputFile( inputFile );

	return 0;
}
Пример #5
0
void Parser::parseFile(const std::string& file) {
	try {
		/* Parse the data with the child class */
		parseInputFile(file);
	} catch(Parser::KeywordParserError& keyerror) {
		size_t file_line = seachKeyWords(file,keyerror.getKeys());
		if(file_line) {
			/* If there is a line that match the error, throw a message with that line */
			throw(ParserError("Error parsing file " + file + " on line " + toString(file_line + 1) + " : " +  keyerror.what()));
		}
		else {
			Log::error() << keyerror.what() << Log::endl;
		}
	}
}
Пример #6
0
/**
 * Create [gnuplot](http://www.gnuplot.info/) ".gpl" file from ".dat" binary file with header section.
 * This program is developed to plot the input file of [maxximino/dpacalc](https://github.com/maxximino/dpacalc)
 */
int main(int argc, char** argv) {

    parseParams(argc, argv);
   
    openFiles();
    
    parseInputFile();
        
    createDat();
    createGpl();
        
    closeFiles();
        
    cout << endl << "[FINISHED]" << endl << endl;
    
    return 0;
}
int main(int argc, char** argv)
{
    char *inputFile;
    char *traceFileName = NULL;
    int len;

    if (parseOptions(argc, argv) || argc - optind != 2) {
        fprintf(stderr, "Usage: %s [-v version] input_file trace_prefix\n",
                argv[0]);
        exit(1);
    }

    inputFile = argv[optind++];
    parseInputFile(inputFile);
    traceFileName = argv[optind++];

    writeTrace(traceFileName);

    return 0;
}
Пример #8
0
int main(int argc, char** argv) {

	int randomSwaps = 0;
	int seed = 0;

	if (argc < 2) {
		cerr << "Error: Missing filename! Use " << argv[0] << " <filename>" << std::endl;
		return -1;
	}

	if (argc > 3 && std::string(argv[2]) == "-swap") randomSwaps = atoi(argv[3]);
	if (argc > 4 && std::string(argv[2]) == "-swap") seed = atoi(argv[4]);
	else {
		std::random_device rd;
		seed = rd();
	}

	parseInputFile(argv[1]);
//	for (auto& x : commonvars::allBlocks)
//		x.print();

	cout << "Found " << commonvars::allBlocks.size() << " blocks." << endl;
	cout << "Found a max of " << commonvars::maxNetNum << " nets." << endl;

	init_graphics("Analytical Placer", WHITE);
	set_visible_world(0, 0, 1010, 1010);

	for (int i = 1; i <= commonvars::maxNetNum; i++) {
		commonvars::allNets.emplace_back(i);
		commonvars::allNets.back().buildBlockList(&commonvars::allBlocks);
//		commonvars::allNets.back().print();
	}

	//Part 2 - random IO swaps
	std::mt19937 mt(seed);
	for (int i = 0; i < randomSwaps; i++) {
		doRandomSwaps(&mt);
//		event_loop(NULL, NULL, NULL, drawscreen);
	}
	commonvars::tempRouting.clear();

	for (auto& x : commonvars::allNets) {
		x.buildConnections();// &commonvars::allBlocks);
	}

	initialPlace(&commonvars::allBlocks);
    cout << "Used "<< wireusage(&commonvars::allNets) << " units of wiring. " << endl;

	event_loop(NULL, NULL, NULL, drawscreen);

	simpleOverlap();

	cout << "Used " << wireusage(&commonvars::allNets) << " units of wiring. (basic spread)" << endl;

	event_loop(NULL, NULL, NULL, drawscreen);

#if DO_FULL_SPREADING
	recurseRemoveOverlap(&commonvars::allBlocks, 2);

	cout << "Used " << wireusage(&commonvars::allNets) << " units of wiring. (full spread)" << endl;

	event_loop(NULL, NULL, NULL, drawscreen);
#endif
	return 0;
}
Пример #9
0
void main(int argc,char* argv[])
{
	semID = semget((key_t)SEMAPHORE_KEY,6,IPC_CREAT|0666);
	float probability;

	if(argc!=2)
	{
		printf("Please provide probability as argument ! \n");
		exit(1);
	}
	else
	{
		sscanf(argv[1],"%f",&probability);
		if(probability < 0 || probability > 1)
		{
			printf("Please run the program with valid probability value : [0-1] \n");
			exit(1);
		}
	}

	char train_sequence[MAX_SEQUENCE_LENGTH];

	int N,M=4;

	if((N=parseInputFile(train_sequence))==-1)
	{
		printf("Error : Cannot open sequence.txt !\n");
		exit(0);
	}

	printf("The sequence scanned from file : %s, N = %d\n",train_sequence,N);

	initializeAllSubSemaphoreValues();

	initializeMatrixFile(N,M);

	srand(time(NULL));

	int sequence_counter = 0,flag=0;

	while(1)
	{
		if(flag)
		{
			sleep(1);
			if(checkForDeadlock(N,M))
				break;
			continue;
		}

		if( ( (float)(rand()%1000) / 1000.0) < probability )
		{
			if(checkForDeadlock(N,M))
				break;
		}
		else
		{
			if(sequence_counter==N)
				flag = 1;
			else
			{
				char c = train_sequence[sequence_counter];
				sequence_counter++;
				if(c!='N' && c!='S' && c!='W' && c!='E')
				{
					printf("Invalid Sequence in sequence.txt !\n");
					exit(1);
				}
				else
				{
					/*
					char command[50];
					sprintf(command,"./train %c %d &",c,sequence_counter-1);
					pid_arr[sequence_counter-1] = pid;
					direction_arr[sequence_counter-1] = getDirString(c);
					system(command);
					*/
					
					int pid = fork();
					if(pid == 0)
					{
						//char command[50];
						//sprintf(command,"./train %d %c %d",N,c,sequence_counter-1);
						
						char** argv = malloc(4*sizeof(char*));
						int y;
						for(y=0;y<4;y++) argv[y] = malloc(10*sizeof(char));
						strcpy(argv[0],"./train");
						sprintf(argv[1],"%d",N);
						sprintf(argv[2],"%c",c);
						sprintf(argv[3],"%d",sequence_counter-1);

						int retv = execvp(*argv,argv);
						if(retv == -1) {perror("Error in execvp ! \n"); exit(1);}
						exit(0);
					}
					printf("Train %d: %s Train started\n",pid,getDirString(c));
					pid_arr[sequence_counter-1] = pid;
					//printf("pid_arr[%d] = %d\n",sequence_counter-1,pid );
					direction_arr[sequence_counter-1] = getDirString(c);
					//printf("direction_arr[%d] = %s\n",sequence_counter-1,getDirString(c) );
					
				}
			}
			
		}
	}

}
void ResourceCompiler::compile()
{
    // parse input file (resource <-> file mapping)
    parseInputFile();

    // load the binary files (resource <-> data mapping)
    loadBinaryData();

    // temporary variables
    ostringstream resourceIdentifierInitializer;
    ostringstream resourceIndexInitializer;
    ostringstream resourceStorageInitializer;

    map<string, vector<unsigned char> >::iterator mapPos;
    vector<unsigned char>::iterator dataPos;
    size_t currentIndex = 0;

    // store total amount of resources
    resourceIndexInitializer << "{0x" << hex << m_ResourceDataMap.size() << ", 0x0},";

    // iterate over all resource data mappings we have
    for(mapPos = m_ResourceDataMap.begin(); mapPos != m_ResourceDataMap.end(); ++mapPos) {

        // store identifier
        resourceIdentifierInitializer << "\"" << mapPos->first << "\",";

        // store data base index
        resourceIndexInitializer << "{0x" << hex << currentIndex << ",";
        resourceIndexInitializer << "0x" << hex << mapPos->second.size() << "},";
        currentIndex += mapPos->second.size();

        // iterate over the data content byte by byte
        for(dataPos = mapPos->second.begin(); dataPos != mapPos->second.end(); ++dataPos) {
            // store byte value as part of array initializer
            resourceStorageInitializer << "0x" << hex << (size_t)*dataPos << ",";
        }
    }

    // open the output code file
    ofstream outputFile(m_ResourceCodeFile.c_str(), ios::out);
    if(!outputFile) {
        cerr << "Couldn't open output file \"" <<  m_ResourceCodeFile << "\"!" << endl,
        exit(1);
    }

    // let's get some exceptions
    outputFile.exceptions(ios::failbit | ios::badbit);

    try {
        // write header
        outputFile << "#include <string>" << endl << endl;

        // write code file contents (remove trailing commas)
        string output = resourceIdentifierInitializer.str();
        outputFile << "extern const std::string c_ResourceIdentifiers[] = {" << endl;
        outputFile << output.substr(0, output.length() - 1);
        outputFile << endl << "};" << endl << endl;

        output = resourceIndexInitializer.str();
        outputFile << "extern const size_t c_ResourceIndex[][2] = {" << endl;
        outputFile << output.substr(0, output.length() - 1);
        outputFile << endl << "};" << endl << endl;

        output = resourceStorageInitializer.str();
        outputFile << "extern const unsigned char c_ResourceStorage[] = {" << endl;
        outputFile << output.substr(0, output.length() - 1);
        outputFile << endl << "};" << endl << endl;
    }
    catch(const ios::failure& error) {
        cerr << "Error during output file processing: " << error.what() << endl;
    }
    catch(const std::logic_error& error) {
            cerr << "Error during output file processing: " << error.what() << endl;
    }

    // clean up and clode file
    outputFile.flush();
    outputFile.close();
}
Пример #11
0
int main (int argc, char **argv) {

  IloEnv env;

  try {
    IloCplex cplex(env);
    IloTimer timer(env);

    const IloNum startTime = cplex.getCplexTime();

    parseCommandLine(argc, argv);
    printCommandLine(argc, argv);

    // set all default constraint weights as zero
    consWts["NonOperatorsAtMostOnce"]           = 0;
    consWts["StackDepthUpperBound"]             = 0;
    consWts["ExactlyOneUnknown"]                = 0;
    consWts["NoTwoConsecutiveMultiplications"]  = 0;  // note: this may be disabled if word "dozen" appears
    consWts["NoTwoConsecutiveDivisions"]        = 0;
    consWts["NoConsecutiveMultAndDiv"]          = 0;
    consWts["NoNegatives"]                      = 0;
    consWts["TypeConsistency"]                  = 0;
    consWts["EqualityFirstOrLast"]              = 0;
    consWts["IntConstantsImplyIntUnknown"]      = 0;
    consWts["PreserveOrderingInText"]           = 0;
    consWts["UnknownFirstOrLast"]               = 0;
    consWts["EqualityNextToUnknown"]            = 0;
    consWts["HasAddition"]                      = 0;
    consWts["HasSubtraction"]                   = 0;
    consWts["HasMultiplication"]                = 0;
    consWts["HasDivision"]                      = 0;

    // parse config file defining constraint weights
    parseConfigFile(param_wts_config_file);

    cout << "Starting IloTimer" << endl;
    timer.start();

    // parse arithmetic model parameters; note: this may override previously
    // set constraint weights
    if (strlen(arith_filename) > 0)
      parseInputFile(arith_filename);

    // set cplex paramters
    setCplexParameters(cplex);

    // import or build the model
    IloModel       model(env);
    IloObjective   obj(env);
    IloNumVarArray corevars(env);
    IloRangeArray  rngs(env);

    if (strlen(mip_filename) > 0) {
      cout << "------- Importing the model -------" << endl;
      cplex.importModel(model, mip_filename, obj, corevars, rngs);
      cout << "Model imported at " << (cplex.getCplexTime() - startTime) << " sec" << endl;
    }
    else {
      cout << "------- Building the model -------" << endl;
      buildArithmeticModel(model, obj, corevars, rngs);
    }

    int nvars = corevars.getSize();
    cout << "Number of Core Variables: " << nvars << endl;

    cplex.extract(model);
    cout << "Model extracted at " << (cplex.getCplexTime() - startTime) << " sec" << endl;

    // save the MIP model to a file, if desired
    if (!param_savemodel.empty()) {
      cout << endl << "Saving generated MIP model to " << param_savemodel << endl << endl;
      cplex.exportModel(param_savemodel.c_str());
    }

    // find out whether it is a minimization problem or a maximization one
    bool isMinimization = true;
    if (cplex.getObjective().getSense() == IloObjective::Maximize)
      isMinimization = false;

    // ask cplex to use MIPInfoCallback
    cplex.use(MIPInfoCallback(env, isMinimization, cplex, startTime));

    cout << "------- Solving the extracted model -------" << endl;
    //const bool solutionFound = cplex.solve();
    const bool solutionFound = (param_nsolutions > 1 ? cplex.populate() : cplex.solve());
    const int nSolutionsFound = cplex.getSolnPoolNsolns();

    cout << "Stopping IloTimer" << endl;
    timer.stop();
    const IloNum endTime = cplex.getCplexTime();

    cout << "-------------------------------------------" << endl;
    printCommandLine(argc, argv);
    cout << "-------------------------------------------" << endl;
    cout << "Number of cplex nodes        = " << cplex.getNnodes() << endl;
    cout << "Number of cplex iterations   = " << cplex.getNiterations() << endl;
    cout << "Aggregated CPU time          = " << timer.getTime() << " seconds" << endl;
    cout << "Elapsed wall clock time      = " << endTime - startTime << " seconds" << endl;
    cout << "Number of threads used       = " << param_threads << endl;
    cout << "Solution status              = " << cplex.getStatus() << endl;

    if (solutionFound) {
      cout << "Solution value               = " << cplex.getObjValue() << endl;
      cout << "Optimality Gap (in %)        = " << fabs((cplex.getBestObjValue() - cplex.getObjValue()) / (1.0 * cplex.getObjValue())) * 100 << endl;
      //cout << "Maximum bound violation      = " << cplex.getQuality(IloCplex::MaxPrimalInfeas) << endl;
    }
    cout << endl << "parameters: n=" << n << " l=" << l << " k=" << k << " p=" << p << " q=" << q << " m=" << m << endl;
    if (solutionFound) {
      cout << "TOTAL " << nSolutionsFound << " solutions found" << endl;
      int nAllowedSolutionsFound = 0;
      if (param_printexpr || param_printanswer || param_printsoln) {
        IloNumArray objValues(env, nSolutionsFound);
        vector<pair<IloNum,unsigned> > sortedIndex(nSolutionsFound);  // to sort solutions by objective value
        vector<FormattedExpr> expressions(nSolutionsFound);
        // extract all solutions as formatted expressions
        for (int s=0; s<nSolutionsFound; s++) {
          IloNumArray vals(env);
          cplex.getValues(vals, corevars, s);
          // convert solution values to integers; note: simple int cast may lead to errors!
          IloIntArray intvals(env, vals.getSize());
          for (int i=0; i<vals.getSize(); i++)
            intvals[i] = IloRound(vals[i]);  // use IloRound rather than std::round
          if (param_printsoln)
            prettyPrintSoln(intvals);
          objValues[s] = cplex.getObjValue(s);
          expressions[s] = getFormattedExpr(intvals);
          sortedIndex[s] = pair<IloNum,unsigned> (objValues[s],s);
        }
        // sort solutions by increasing objective value
        std::stable_sort(sortedIndex.begin(), sortedIndex.end());
        // identify which expressions are unique (ignoring type differences);
        // prefer to keep those that appear earlier in the above sorted order
        set<int>    uniqueExprIndices;
        set<string> seenExpressions;
        if (!param_allowdupes) {
          for (int s=0; s<nSolutionsFound; s++) {
            const int sId = sortedIndex[s].second;
            const string & exprPf = expressions[sId].postfix;
            if (seenExpressions.find(exprPf) == seenExpressions.end()) {
              uniqueExprIndices.insert(sId);
              seenExpressions.insert(exprPf);
            }
          }
        }
        // evaluate all expressions with a single call to Python's SymPy package
        if (param_printanswer)
          solveExpressionsWithSymPy(expressions);
        // print expressions if desired, in sorted order
        if (param_printexpr) {
          cout << "SOLN: CORRECT | POS/NEG | INT/FRA | OBJ-SCORE | TRUE-ANS | ANS | INFIX | POSTFIX | TYPED-POSTFIX" << endl;
          for (int s=0; s<nSolutionsFound; s++) {
            const int sId = sortedIndex[s].second;
            if (!param_allowdupes && uniqueExprIndices.find(sId) == uniqueExprIndices.end())
              continue;
            const FormattedExpr & expr = expressions[sId];
            const double answerValue = atof(expr.answer.c_str());
            const bool isCorrect = (fabs(answerValue - trueAnswer) < epsilon);
            const bool isAnswerNegative = answerValue < 0;
            const bool isAnswerInteger = isInt(answerValue);
            if (!isAnswerNegative && (!allIntConstants || consWts["IntConstantsImplyIntUnknown"] == 0 || isAnswerInteger)) {
              ++nAllowedSolutionsFound;
              cout << "EXPR: " << isCorrect
                   << " | " << (isAnswerNegative ? "NEG" : "POS")
                   << " | " << (isAnswerInteger ? "INT" : "FRA")
                   << " | " << objValues[sId]
                   << " | " << trueAnswer
                   << " | " << expr.answer
                   << " | " << expr.infix
                   << " | " << expr.postfix
                   << " | " << expr.typedPostfix
                   << endl;
            }
          }
        }
      }
      const string solnProperty = (param_allowdupes ? "" : " unique,")
        + string(" non-negative")
        + (allIntConstants && consWts["IntConstantsImplyIntUnknown"] != 0 ? ", integer-valued " : " ");
      cout << "NET " << nAllowedSolutionsFound << solnProperty << "solutions found out of "
           << nSolutionsFound << " total solutions" << endl;
    }

    cout << "-------------------------------------------" << endl;
    cout << "RESULT:"
         << " NODES " << cplex.getNnodes()
         << " | ITERATIONS " << cplex.getNiterations()
         << " | CPUTIME " << timer.getTime()
         << " | WALLTIME " << endTime - startTime
         << " | THREADS " << param_threads
         << " | STATUS " << cplex.getStatus();
    if (solutionFound)
      cout << " | SOLUTION " << cplex.getObjValue()
           << " | OPTGAP " << fabs((cplex.getBestObjValue() - cplex.getObjValue()) / (1.0 * cplex.getObjValue())) * 100;
    else
      cout << " | SOLUTION - | OPTGAP -";
    cout << endl;

    //try {     // basis may not exist
    //  IloCplex::BasisStatusArray cstat(env);
    //  cplex.getBasisStatuses(cstat, vars);
    //  cout << "Basis statuses               = " << cstat << endl;
    //}
    //catch (...) {
    //}


  }
  catch (IloException& e) {
    cerr << "Concert exception caught: " << e << endl;
  }
  catch (...) {
    cerr << "Unknown exception caught" << endl;
  }

  env.end();
  return 0;
}  // END main