int main(int argc, char* argv[])
{
    parseCommandLineArgs(argc, argv);

    // check we have enough arguments
    if( argc - optind < 1 ) {
	printUsage();
	exit (0);
    }

    // open infile for input
    std::ifstream infile( argv[ optind ], std::ios::in );
    if( !infile ) {
	std::cerr << "\aError: could not open file " << argv[ optind ] << std::endl;
	return 1;
    }
    
    std::stringstream sstream;    // stringstream to hold past context stream
    Simulator simulator(new SimulatorPresageCallback(sstream), sstream, config);
    simulator.silentMode(silent_mode);

    ForwardTokenizer tokenizer(infile,
			       DEFAULT_BLANKSPACE_CHARS,
			       DEFAULT_SEPARATOR_CHARS);
    tokenizer.lowercaseMode(case_insensitive);
    while(tokenizer.hasMoreTokens()) {
	simulator.simulate(tokenizer.nextToken());
    }
		
    simulator.results();

    infile.close();

    return 0;
}
Example #2
0
void QDesigner::initialize()
{
    // initialize the sub components
    QStringList files;
    QString resourceDir = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
    parseCommandLineArgs(files, resourceDir);

    QTranslator *translator = new QTranslator(this);
    QTranslator *qtTranslator = new QTranslator(this);

    const QString localSysName = QLocale::system().name();
    QString  translatorFileName = QStringLiteral("designer_");
    translatorFileName += localSysName;
    translator->load(translatorFileName, resourceDir);

    translatorFileName = QStringLiteral("qt_");
    translatorFileName += localSysName;
    qtTranslator->load(translatorFileName, resourceDir);
    installTranslator(translator);
    installTranslator(qtTranslator);

    if (QLibraryInfo::licensedProducts() == QStringLiteral("Console")) {
        QMessageBox::information(0, tr("Qt Designer"),
                tr("This application cannot be used for the Console edition of Qt"));
        QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection);
        return;
    }

    m_workbench = new QDesignerWorkbench();

    emit initialized();
    previousMessageHandler = qInstallMessageHandler(designerMessageHandler); // Warn when loading faulty forms
    Q_ASSERT(previousMessageHandler);

    m_suppressNewFormShow = m_workbench->readInBackup();

    if (!files.empty()) {
        const QStringList::const_iterator cend = files.constEnd();
        for (QStringList::const_iterator it = files.constBegin(); it != cend; ++it) {
            // Ensure absolute paths for recent file list to be unique
            QString fileName = *it;
            const QFileInfo fi(fileName);
            if (fi.exists() && fi.isRelative())
                fileName = fi.absoluteFilePath();
            m_workbench->readInForm(fileName);
        }
    }
    if ( m_workbench->formWindowCount())
        m_suppressNewFormShow = true;

    // Show up error box with parent now if something went wrong
    if (m_initializationErrors.isEmpty()) {
        if (!m_suppressNewFormShow && QDesignerSettings(m_workbench->core()).showNewFormOnStartup())
            QTimer::singleShot(100, this, SLOT(callCreateForm())); // won't show anything if suppressed
    } else {
        showErrorMessageBox(m_initializationErrors);
        m_initializationErrors.clear();
    }
}
Example #3
0
PlayPG::PlayPG(int argc, char *argv[]) :
		        APG::SDLGame("PlayPG", 1280u, 720u, 4, 5),
		        addr { argc > 1 ? argv[1] : "localhost" },
		        socket { addr, port } {
	PlayPG::logger = el::Loggers::getLogger("PlayPG");

	parseCommandLineArgs(argc, argv);
}
Example #4
0
int main(int argc, char *argv[]) {
    bool ret = true;

    s3ext_loglevel = EXT_ERROR;
    s3ext_logtype = STDERR_LOG;

    if (argc == 1) {
        printUsage(stderr);
        exit(EXIT_FAILURE);
    }

    /* Prepare to receive interrupts */
    registerSignalHandler();

    map<char, string> optionPairs = parseCommandLineArgs(argc, argv);

    validateCommandLineArgs(optionPairs);

    if (!optionPairs.empty()) {
        const char *arg = optionPairs.begin()->second.c_str();

        switch (optionPairs.begin()->first) {
            case 'c':
                ret = checkConfig(arg);
                break;
            case 'd':
                ret = downloadS3(arg);
                break;
            case 'u':
            case 'f':
                ret = uploadS3(optionPairs['u'].c_str(), optionPairs['f'].c_str());
                break;
            case 'h':
                printUsage(stdout);
                break;
            case 't':
                printTemplate();
                break;
            default:
                printUsage(stderr);
                exit(EXIT_FAILURE);
        }
    }

    // Abort should not print the failed info
    if (ret || S3QueryIsAbortInProgress()) {
        exit(EXIT_SUCCESS);
    } else {
        fprintf(stderr, "Failed. Please check the arguments and configuration file.\n\n");
        printUsage(stderr);
        exit(EXIT_FAILURE);
    }
}
Example #5
0
File: util.cpp Project: h4tr3d/qavr
QStringList q_parseCommandLineArgs(const QString &args)
{
    std::list<std::string> list;
    std::list<std::string>::iterator it;
    list = parseCommandLineArgs(args.toStdString());
    QStringList ret;

    for (it = list.begin(); it != list.end(); it++)
    {
        ret.push_back(QString::fromStdString(*it));
    }

    return ret;
}
Example #6
0
int main(int argc, char **argv)
{
	char *finName = 0;
	char *foutName = 0;
	char *assemblyName = 0;

	FILE *fin;
	FILE *fout;

	Instruction text[MAX_CODE_LENGTH+1];

	parseCommandLineArgs(argc, argv, &foutName, &finName,
        "A virtual machine for running p-code.");

    fin = modified_fopen(finName, "r", stdin, NULL);
    fout = modified_fopen(foutName, "w", stdout, NULL);
	
	/* Read instructions into internal buffer */
	int i=0;
	for (;;)
	{
		int items = fscanf(fin, "%d %d %d", &text[i].op, &text[i].l, &text[i].m);
		if(feof(fin))
			break;

        if (items != 3)
        {
            char message[25];
            int c = fgetc(fin);
            sprintf(message, "Illigal character 0x%02x", c);
            die(ERR_ILLIGAL_CHAR, message);
        }
		i++;
		if (i >= MAX_CODE_LENGTH)
        {
            char message[70];
            sprintf(message, "This machine cannot run more "
                    "than %d instructions\n", MAX_CODE_LENGTH);
            die(ERR_CODE_TOO_LARGE, message);
        }
	}
	text[i].op = 0;
	text[i].l = 0;
	text[i].m = 0;

	disassemble(fout, text);
	run(fout, text);

	return EXIT_SUCCESS;
}
Example #7
0
int main(int argc, char **argv)
{
    // Pseudo command-line args; uncomment the following lines and replace the
    // main function's signature with "int main(void)" in order to hard-code
    // the file paths to input.txt and output.txt.
#if 0
    int argc = 5;
    char* argv[] = {"./plscan", "-i", "input.txt", "-o", "output.txt"};
#endif

    char *finName = NULL;
    char *foutName = NULL;

    FILE *fin;
    FILE *fout;

    parseCommandLineArgs(argc, argv, &foutName, &finName,
                         "A scanner for the PL/0 language.");

    fin = modified_fopen(finName, "r", stdin, NULL);
    fout = modified_fopen(foutName, "w", stdout, NULL);

    FileBuffer *file_buffer = createFileBuffer(fin);
    fclose(fin);

    TokenBuffer *token_buffer = tokenize(file_buffer);

    fputs("Source Program:\n", fout);
    printFileBuffer(file_buffer, fout);
    fputs("\n", fout);
    freeFileBuffer(file_buffer);

    printTokenTable(token_buffer, fout);
    fputs("\n", fout);

    printTokenList(token_buffer, fout);
    fputs("\n", fout);

    fclose(fout);
    freeTokenBuffer(token_buffer);
    return EXIT_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
    bool doCPU = false;
    bool doGPU = false;
    bool doMultiGPU = false;
    bool doCPUGPU = false;
    bool doRef = false;
    int numSources = 100;
    int generateVerts = 100000;
    int generateEdgesPerVert = 10;

    parseCommandLineArgs(argc, argv, doCPU, doGPU,
                         doMultiGPU, doCPUGPU, doRef,
                         &numSources, &generateVerts, &generateEdgesPerVert);

    cl_platform_id platform;
    cl_context gpuContext;
    cl_context cpuContext;
    cl_int errNum;

    // First, select an OpenCL platform to run on.  For this example, we
    // simply choose the first available platform.  Normally, you would
    // query for all available platforms and select the most appropriate one.
    cl_uint numPlatforms;
    errNum = clGetPlatformIDs(1, &platform, &numPlatforms);
    printf("Number of OpenCL Platforms: %d\n", numPlatforms);
    if (errNum != CL_SUCCESS || numPlatforms <= 0)
    {
        printf("Failed to find any OpenCL platforms.\n");
        return 1;
    }

    // create the OpenCL context on available GPU devices
    gpuContext = clCreateContextFromType(0, CL_DEVICE_TYPE_GPU, NULL, NULL, &errNum);
    if (errNum != CL_SUCCESS)
    {
        printf("No GPU devices found.\n");
    }

    // Create an OpenCL context on available CPU devices
    cpuContext = clCreateContextFromType(0, CL_DEVICE_TYPE_CPU, NULL, NULL, &errNum);
    if (errNum != CL_SUCCESS)
    {
        printf("No CPU devices found.\n");
    }

    // Allocate memory for arrays
    GraphData graph;
    generateRandomGraph(&graph, generateVerts, generateEdgesPerVert);

    printf("Vertex Count: %d\n", graph.vertexCount);
    printf("Edge Count: %d\n", graph.edgeCount);

    std::vector<int> sourceVertices;


    for(int source = 0; source < numSources; source++)
    {
        sourceVertices.push_back(source % graph.vertexCount);
    }

    int *sourceVertArray = (int*) malloc(sizeof(int) * sourceVertices.size());
    std::copy(sourceVertices.begin(), sourceVertices.end(), sourceVertArray);

    float *results = (float*) malloc(sizeof(float) * sourceVertices.size() * graph.vertexCount);


    // Run Dijkstra's algorithm
    pt::ptime startTimeCPU = pt::microsec_clock::local_time();
    if (doCPU)
    {
        runDijkstra(cpuContext, getMaxFlopsDev(cpuContext), &graph, sourceVertArray,
                    results, sourceVertices.size() );
    }
    pt::time_duration timeCPU = pt::microsec_clock::local_time() - startTimeCPU;

    pt::ptime startTimeGPU = pt::microsec_clock::local_time();
    if (doGPU)
    {
        runDijkstra(gpuContext, getMaxFlopsDev(gpuContext), &graph, sourceVertArray,
                    results, sourceVertices.size() );
    }
    pt::time_duration timeGPU = pt::microsec_clock::local_time() - startTimeGPU;

    pt::ptime startTimeMultiGPU = pt::microsec_clock::local_time();
    if (doMultiGPU)
    {
        runDijkstraMultiGPU(gpuContext, &graph, sourceVertArray,
                            results, sourceVertices.size() );
    }
    pt::time_duration timeMultiGPU = pt::microsec_clock::local_time() - startTimeMultiGPU;


    pt::ptime startTimeGPUCPU = pt::microsec_clock::local_time();
    if (doCPUGPU)
    {
        runDijkstraMultiGPUandCPU(gpuContext, cpuContext, &graph, sourceVertArray,
                                  results, sourceVertices.size() );
    }
    pt::time_duration timeGPUCPU = pt::microsec_clock::local_time() - startTimeGPUCPU;

    pt::ptime startTimeRef = pt::microsec_clock::local_time();
    if (doRef)
    {
        runDijkstraRef( &graph, sourceVertArray,
                        results, sourceVertices.size() );
    }
    pt::time_duration timeRef = pt::microsec_clock::local_time() - startTimeRef;


    if (doCPU)
    {
        printf("\nrunDijkstra - CPU Time:               %f s\n", (float)timeCPU.total_milliseconds() / 1000.0f);
    }

    if (doGPU)
    {
        printf("\nrunDijkstra - Single GPU Time:        %f s\n", (float)timeGPU.total_milliseconds() / 1000.0f);
    }

    if (doMultiGPU)
    {
        printf("\nrunDijkstra - Multi GPU Time:         %f s\n", (float)timeMultiGPU.total_milliseconds() / 1000.0f);
    }

    if (doCPUGPU)
    {
        printf("\nrunDijkstra - Multi GPU and CPU Time: %f s\n", (float)timeGPUCPU.total_milliseconds() / 1000.0f);
    }

    if (doRef)
    {
        printf("\nrunDijkstra - Reference (CPU):        %f s\n", (float)timeRef.total_milliseconds() / 1000.0f);
    }

    free(sourceVertArray);
    free(results);

    clReleaseContext(gpuContext);

    // finish
    //shrEXIT(argc, argv);
 }
Example #9
0
int main(int argc, char *argv[]) {
  std::string usage = "Usage: runClassifier [options] optionFile testFile numTrainingInstances";
  parseCommandLineArgs(&argc,&argv,usage,3,3);

  std::string optionFile = argv[1];
  std::string testFile   = argv[2];
  unsigned int numTrainingInstances = boost::lexical_cast<unsigned int>(argv[3]);

  Json::Value options;

  if (! readJson(optionFile,options))
    return 1;

  ClassifierPtr classifier = createClassifier(options);
  
  std::ifstream testIn(testFile.c_str());
  ArffReader testReader(testIn);
  for (unsigned int count = 0; count < numTrainingInstances; count++) {
    if (testReader.isDone()) {
      std::cerr << "ERROR: Insufficient training data" << std::endl;
      std::cerr << "Found " << count << " instances, expected " << numTrainingInstances << std::endl;
      exit(2);
    }
    InstancePtr instance = testReader.next();
    classifier->addData(instance);
  }
  double trainingTime = 0.0;
  if (FLAGS_train) {
    double startTime = getTime();
    classifier->train(false);
    trainingTime = getTime() - startTime;
    std::cout << "Training time: " << trainingTime << std::endl;
  }
  
  std::cout << "------------------------------------------" << std::endl;
  //std::cout << *classifier << std::endl;

  double correct = 0.0;
  int correctCount = 0;
  int count;
  for (count = 0; !testReader.isDone(); count++) {
    InstancePtr instance = testReader.next();
    Classification c;
    classifier->classify(instance,c);
    //std::cout << *instance << std::endl;
    //std::cout << "  ";
    //for (unsigned int i = 0; i < c.size(); i++)
      //std::cout << c[i] << " ";
    //std::cout << std::endl;
    // calculate the fraction correct
    correct += c[instance->label];
    // calculate whether most probable was correct
    unsigned int maxInd = vectorMaxInd(c);
    if (maxInd == instance->label)
      correctCount++;
  }
  testIn.close();

  std::cout << "------------------------------------------" << std::endl;
  std::cout << "Target Training Insts: " << numTrainingInstances << std::endl;
  std::cout << "Testing Insts: " << count << std::endl;
  std::cout << "Frac  Correct: " << correct << "(" << correct / count << ")" << std::endl;
  std::cout << "Num   Correct: " << correctCount << "(" << correctCount / (float)count << ")" << std::endl;
  std::cout << "Training time: " << trainingTime << std::endl;

  return 0;
}
Example #10
0
int main(int argc, char **argv) {
  cf = &cfg;
  config_init(cf);
  
  if (!config_read_file(cf, "./pmaxd.conf")) {
            fprintf(stderr, "%s:%d - %s\n",
                config_error_file(cf),
                config_error_line(cf),
                config_error_text(cf));
            config_destroy(cf);
            return(EXIT_FAILURE);
        }

        

         
  /* Our process ID and Session ID */
  pid_t pid = 0, sid = 0;        
  
  int helpOption = 0;
   
  int j=0;
  int k=0;
  struct PlinkBuffer testbuffer;
 
  parseCommandLineArgs(argc, argv); 
        
  /* Fork off the parent process */
  if  (foregroundOption==0) pid = fork();
  if (pid < 0) {
    exit(EXIT_FAILURE);
  }
  /* If we got a good PID, then
  we can exit the parent process. */
  if (pid > 0) {
    exit(EXIT_SUCCESS);
  }
  /* Change the file mode mask */
  umask(0);
        

  initLog(verboseLevel);
       
  DEBUG (LOG_NOTICE, "Program started by User %d", getuid ());
        
  DEBUG (LOG_INFO, "Setting SID"); 
                                     
  /* Create a new SID for the child process */
  if  (foregroundOption==0) sid = setsid();
  if (sid < 0) {
    /* Log the failure */
    DEBUG (LOG_INFO, "Cannot set SID");
    exit(EXIT_FAILURE);
  }

  /* Change the current working directory */
  if ((chdir("/")) < 0) {
    /* Log the failure */
    exit(EXIT_FAILURE);
  }
  
  /* Close out the standard file descriptors */
  if  (foregroundOption==0) {
    DEBUG (LOG_INFO, "Closing std file descriptor");
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);
  }
   
  /* Daemon-specific initialization goes here */
          
        
	struct timeval  tvLastSerialCharTime,tvCurrentTime;
	double          lastSerialCharTime,currentTime;
 	struct PlinkBuffer commandBuffer;
 	commandBuffer.size=0;
 	
 	int eop=0;
	int loop=0;
	unsigned char *bufptr;  /* Current char in buffer */
 	
	DEBUG(LOG_NOTICE,"Starting......");

	gettimeofday(&tvLastSerialCharTime, NULL);
	lastSerialCharTime = tvLastSerialCharTime.tv_sec*1000000 + (tvLastSerialCharTime.tv_usec);  
  
 	initXpl();
	initSocket();
//  initSerialPort();  
	PmaxInit(); 

	DEBUG(LOG_DEBUG,"Starting main loop....");
	

/* read characters into our string buffer until timeout */  
  while (!loop) {
	int maxMsgLength = MAX_BUFFER_SIZE;
   
    if (foregroundOption==1)  //manage keypress if interactive mode
      KeyPressHandling();
       
  	while ((read(fd, commandBuffer.size+commandBuffer.buffer, 1) == 1) && commandBuffer.size < maxMsgLength) {
		DEBUG(LOG_DEBUG, "Received char 0x%02x buf position %d", (int) (commandBuffer.size+commandBuffer.buffer)[0], commandBuffer.size);
		commandBuffer.size++;
		
		/* for "known" messages, limit read to corresponding size */
		if (commandBuffer.size == 2) switch (commandBuffer.buffer[1]) {
			case 0x02:
			case 0x08:
				maxMsgLength = 5;
				break;
			case 0xA5:
			case 0xA7:
			case 0xAA:
				maxMsgLength = 15;
				break;
		}

		gettimeofday(&tvLastSerialCharTime, NULL);
		lastSerialCharTime = tvLastSerialCharTime.tv_sec*1000000 + (tvLastSerialCharTime.tv_usec);
		eop=1;
	}
	
	gettimeofday(&tvCurrentTime, NULL);
	currentTime = tvCurrentTime.tv_sec*1000000 + (tvCurrentTime.tv_usec);
	
	if (eop==1) {
      
		// if timeout, assume packet is finished, and manage it (check format/ deformat/......) 
		if ((currentTime-lastSerialCharTime)> PACKET_TIMEOUT || commandBuffer.size == maxMsgLength) {
			DEBUG(LOG_DEBUG, "Interpreting packet");
			packetManager(&commandBuffer);
			maxMsgLength = MAX_BUFFER_SIZE;
			eop=0;
		}
    }   

	/* check if activity in the last MAX_IDLE_TIME (at the very least should be heartbeat message) */
	if ((currentTime-lastSerialCharTime) > MAX_IDLE_TIME) {
		
		/* try to re-start the TCP connection */
		DEBUG(LOG_INFO, "Reseting TCP connection");
		initSocket();
		lastSerialCharTime = currentTime;
	}

    usleep(IDLE_TIME);
    xPL_processMessages(0);
  }
  
  closelog ();
  exit(EXIT_SUCCESS);
}
Example #11
0
/*
 * Main function
 * @pram int argc
 * @pram char** argv
 */
int main(int argc, char * argv[])
{
    /*
     *Configure the program to use the command line args
     */
    srand(time(NULL));
    parseCommandLineArgs(argc, argv, 0);
    
    /*
     * Timing Variables
     */
    std::clock_t time_start;
    std::clock_t time_end;
	
	/*
	 *	Input/Result containers
	 */
	int total_comparisons;
    std::vector<IsoRank_Result> isoRank_results;
    std::vector<DenseMatrix1D<DataType>* >input_graphs;
    
    if(G_PRINT)
        std::cout << "Reading " << G_NUMBER_OF_FILES << " graphs from: " << G_DIR_PATH << std::endl;
    std::ostringstream itos_converter;
    time_start = std::clock();
    /*
     * Reading the graphs and storing them
     */
    for(int i = 1; i <= G_NUMBER_OF_FILES; i++)
    {
        try
        {
            itos_converter << G_DIR_PATH << i << G_FILE_EXTENSION;
            input_graphs.push_back(new DenseMatrix1D<DataType>(itos_converter.str()));
            itos_converter.str(""); //clearing the stream
            itos_converter.clear();
        }
        catch (std::exception& e)
        {
            std::cerr <<"Exception: " << e.what() << '\n' << std::endl;
            itos_converter.str("");
            itos_converter.clear();
        }
    }
    total_comparisons = (0.5*(input_graphs.size()-1)*input_graphs.size());
    time_end = std::clock();
    if(G_PRINT)
        std::cout << input_graphs.size() << " of " << G_NUMBER_OF_FILES << " graphs were successfully read in "
        << timeElapsed(time_start, time_end) << "(ms)." << std::endl;
    
    time_start = std::clock();
    for (int i = 0; i < input_graphs.size(); i++)
    {
        for (int j = i +1; j < input_graphs.size(); j++)
        {
            try
            {
                if (G_USE_ISORANK)
                {
                    isoRank_results.push_back(isoRank(*input_graphs[i], *input_graphs[j], G_GRAPH_MATCHING_ALGORITHM));
                }
                if (G_USE_GPGM)
                {
                    //GPGM(mat1,mat2);
                }
                
            }
            catch (std::exception& e)
            {
                std::cerr << " Exception: " << e.what() << std::endl;
            }
        }
    }
    time_end = std::clock();
    
	
    //printing the results
    if (G_PRINT)
    {
        std::cout << "Computed IsoRank successfully for " << G_NUMBER_OF_FILES << " graphs in "
        << timeElapsed(time_start, time_end) << "(ms)." << std::endl;
        
        std::cout << "Frob_norms: ";
        for (int i=0; i < isoRank_results.size(); i++)
        {
            std::cout<< isoRank_results[i].frob_norm << ", ";
        }
        std::cout<<std::endl;
    }
    
    typename std::vector<IsoRank_Result>::iterator res_it;
    for ( res_it = isoRank_results.begin() ; res_it < isoRank_results.end(); ++res_it )
    {
        delete [] res_it->assignments;
    }
    
    typename std::vector<DenseMatrix1D<DataType>* >::iterator graph_it;
    for ( graph_it = input_graphs.begin() ; graph_it < input_graphs.end(); ++graph_it )
    {
        delete  *graph_it;
    }
    return 0;
}
Example #12
0
/*
 * Main function
 * @pram int argc
 * @pram char** argv
 */
int main(int argc, char * argv[])
{
    srand(time(NULL));
	/*
	 * MPI Variables
	 */  
	int num_procs;
    int ID;
 	MPI_Status stat;

 	/*
 	 *	MPI constant Tags
 	 */
 	const int MASTER_ID = 0;
    const int TAG_1 = 4;
    const int TAG_2 = 10;
    const int TAG_3 = 15;

    /*
     * MPI Initialization calls 
     */
    if (MPI_Init(&argc, &argv) != MPI_SUCCESS)
    {
        std::cout << "Failed To Initialize MPI" << std::endl;
        //MPI_Abort();
    }
    MPI_Comm_size (MPI_COMM_WORLD, &num_procs);
    MPI_Comm_rank (MPI_COMM_WORLD, &ID);
        
    /*
     *Configure the program to use the command line args
     */
    parseCommandLineArgs(argc, argv, ID);
    
    /*
     * Timing Variables
     */
    std::clock_t time_start;
    std::clock_t time_end;
	
	/*
	 *	Result variables
	 */
	int total_comparisons; 
	int number_of_graphs;
    std::vector<IsoRank_Result> isoRank_results;

//======================================================================*MASTER NODE*==============================================================================
    if (ID == MASTER_ID)
    {
    	if(G_PRINT)
    		std::cout << "Reading " << G_NUMBER_OF_FILES << " graphs from: " << G_DIR_PATH << std::endl;
    	time_start = std::clock();
    	std::ostringstream itos_converter;
    	std::vector<SymMatrix<DataType>* >input_graphs;

    	/*
    	 * Reading the graphs and storing them
    	 */
		for(int i = 1; i <= G_NUMBER_OF_FILES; i++)
		{
			try
			{
				itos_converter << G_DIR_PATH << i << G_FILE_EXTENSION;
				input_graphs.push_back(new SymMatrix<DataType>(itos_converter.str()));
				itos_converter.str(""); //clearing the stream
				itos_converter.clear();
			}
			catch (std::exception& e)
			{
				std::cerr <<"Exception: " << e.what() << '\n' << std::endl;
				itos_converter.str("");
				itos_converter.clear();
			}
		}
		number_of_graphs = input_graphs.size();
		total_comparisons = (0.5*(number_of_graphs-1)*number_of_graphs);
		time_end = std::clock();
		if(G_PRINT)
			std::cout << input_graphs.size() << " of " << G_NUMBER_OF_FILES << " graphs were successfully read in "
			<< timeElapsed(time_start, time_end) << "(ms)." << std::endl;

		/*
    	 * Sending the graphs to worker nodes.
    	 */
		time_start = std::clock();
		MPI_Bcast (&number_of_graphs, 1 , MPI_INT, MASTER_ID, MPI_COMM_WORLD);
		if(G_DEBUG)
			std::cout <<"Master: sending "<<number_of_graphs << " graphs to all"<< std::endl;
		for (int i = 0; i < input_graphs.size(); i++)
		{
			input_graphs[i]->MPI_Bcast_Send_Matrix(MASTER_ID);
		}
		
		/*
		 * Collecting the results from the worker nodes.
		 */
		int recv_counter = 0;
		while (recv_counter < total_comparisons)
		{
			int dest;
			//Recv workers ID
			MPI_Recv(&dest, 1, MPI_INT, MPI_ANY_SOURCE, TAG_1 + TAG_2, MPI_COMM_WORLD,&stat);
			if(G_DEBUG)
				std::cout <<"Master: received signal to receive result from: "<< dest<< std::endl;

			//Collect the result from worker
			isoRank_results.push_back(MPI_Recv_IsoRank_Result(dest, TAG_1 * dest + TAG_3, stat));
			recv_counter++;
			if(G_DEBUG)
				std::cout <<"Master: results were received."<< dest<< std::endl;
		}
		
 		time_end = std::clock();

		//printing the results 
		if (G_PRINT)
		{
			std::cout << "Master: Computed IsoRank successfully for " << G_NUMBER_OF_FILES << " graphs in "
												<< timeElapsed(time_start, time_end) << "(ms)." << std::endl;
												
			std::cout<< "Master: " << isoRank_results.size() << " results were received.\n frob_norms: ";
			for (int i=0; i < isoRank_results.size(); i++)
			{
				std::cout<< isoRank_results[i].frob_norm << ", ";
			}
			std::cout<<std::endl;
		}
		
		typename std::vector<IsoRank_Result>::iterator res_it;
		for ( res_it = isoRank_results.begin() ; res_it < isoRank_results.end(); ++res_it )
		{
			delete [] res_it->assignments;
		}
		
		typename std::vector<SymMatrix<DataType>* >::iterator graph_it;
		for ( graph_it = input_graphs.begin() ; graph_it < input_graphs.end(); ++graph_it )
		{
			delete  *graph_it;
		}
    }
//======================================================================*WORKER NODES*==============================================================================
    else
    {
    	
    	std::vector<DenseMatrix1D<DataType>* > recv_graphs;
    	
    	MPI_Bcast (&number_of_graphs, 1, MPI_INT, MASTER_ID, MPI_COMM_WORLD);
    	for (int i = 0; i < number_of_graphs; i++)
    	{
    		recv_graphs.push_back(new DenseMatrix1D<DataType>(MASTER_ID, stat));
    	}

		if (G_DEBUG)
			std::cout << "Process "<< ID << " : received " << number_of_graphs << " graphs from master"<< std::endl;
	
        Offset offset;
        offset.setValues(ID, num_procs, number_of_graphs);
        int A, B;
		for (int i = offset.i_start; i <= offset.i_end; i++)
		{	
            if (i == offset.i_start)
            {
                A = offset.j_start;
            }
            else
            {
                A = i+1;
            }

            if (i == offset.i_end)
            {
                B = offset.j_end;
            }
            else 
            {
                B = number_of_graphs - 1;
            }

			for (int j = A; j <= B; j++)
			{	
				struct IsoRank_Result result;
				try
				{
					if (G_USE_ISORANK)
					{	
						if (G_DEBUG)
							std::cout << "Process " << ID << ": isoRank: started."  << i << " " << j << std::endl;
						result = isoRank(*recv_graphs[i], *recv_graphs[j], G_GRAPH_MATCHING_ALGORITHM);
						if (G_DEBUG)
							std::cout << "Process " << ID << ": isoRank: end." << std::endl;
					}
					if (G_USE_GPGM)
					{
						//GPGM(mat1,mat2);
					}
						
					//Sending the ID to master for more graphs
					MPI_Send(&ID, 1, MPI_INT, MASTER_ID, TAG_1 + TAG_2, MPI_COMM_WORLD);

					if (G_DEBUG)
					  std::cout << "Process "<< ID << " :sending result to master" << std::endl;
					  
					//Sending results to master
					MPI_Send_IsoRank_Result(result, MASTER_ID , TAG_1 * ID + TAG_3);
					delete []result.assignments;
				}
				catch (std::exception& e)
				{
					std::cerr << "Process "<< ID << " Exception: " << e.what() << std::endl;
				}
			}
		}
		typename std::vector<DenseMatrix1D<DataType>* >::iterator graph_it;
		for ( graph_it = recv_graphs.begin() ; graph_it < recv_graphs.end(); ++graph_it )
		{
			delete  *graph_it;
		}
	}			
		
	
	if(G_PRINT)
    	std::cout << "Process: "<< ID << " terminated." << std::endl; 

    MPI_Finalize();
    return 0;
}
Example #13
0
/*
 * Main function
 * @pram int argc
 * @pram char** argv
 */
int main(int argc, char * argv[])
{
    srand(time(NULL));
	/*
	 * MPI Variables
	 */
    int num_procs;
    int ID;
 	MPI_Status stat;
    
 	/*
 	 * MPI constant Tags
 	 */
 	const int MASTER_ID = 0;
    const int TAG_1 = 4;
    const int TAG_2 = 10;
    const int TAG_3 = 15;
    
    /*
     * MPI Initialization calls
     */
    if (MPI_Init(&argc, &argv) != MPI_SUCCESS)
    {
        std::cout << "Failed To Initialize MPI" << std::endl;
        //MPI_Abort();
    }
    MPI_Comm_size (MPI_COMM_WORLD, &num_procs);
    MPI_Comm_rank (MPI_COMM_WORLD, &ID);
    
    /*
     *Configure the program to use the command line args
     */
    parseCommandLineArgs(argc, argv, ID);
    
    /*
     * Timing Variables
     */
    std::clock_t time_start;
    std::clock_t time_end;
	
	/*
	 *	Result variables
	 */
	int total_comparisons;
    std::vector<IsoRank_Result> isoRank_results;
    
    //======================================================================*MASTER NODE*==============================================================================
    if (ID == MASTER_ID)
    {
    	if(G_PRINT)
    		std::cout << "Reading " << G_NUMBER_OF_FILES << " graphs from: " << G_DIR_PATH << std::endl;
    	time_start = std::clock();
    	std::ostringstream itos_converter;
    	std::vector<SymMatrix<DataType>* >input_graphs;
        
    	/*
    	 * Reading the graphs and storing them
    	 */
		for(int i = 1; i <= G_NUMBER_OF_FILES; i++)
		{
			try
			{
				itos_converter << G_DIR_PATH << i << G_FILE_EXTENSION;
				input_graphs.push_back(new SymMatrix<DataType>(itos_converter.str()));
				itos_converter.str(""); //clearing the stream
				itos_converter.clear();
			}
			catch (std::exception& e)
			{
				std::cerr <<"Exception: " << e.what() << '\n' << std::endl;
				itos_converter.str("");
				itos_converter.clear();
			}
		}
		total_comparisons = (0.5*(input_graphs.size()-1)*input_graphs.size());
		time_end = std::clock();
		if(G_PRINT)
			std::cout << input_graphs.size() << " of " << G_NUMBER_OF_FILES << " graphs were successfully read in "
			<< timeElapsed(time_start, time_end) << "(ms)." << std::endl;
        
        /*
    	 * Sending the graphs to worker nodes.
    	 */
		time_start = std::clock();
		int dest_ID = 1;
		int recv_counter = 0;
		for (int i = 0; i < input_graphs.size(); i++)
		{
			for(int j = i + 1; j <  input_graphs.size(); j++)
			{
				// Send a pair of graphs to all the worker nodes
				if (dest_ID < num_procs)
				{
					input_graphs[i]->MPI_Send_Matrix(dest_ID, TAG_1 * dest_ID);
					input_graphs[j]->MPI_Send_Matrix(dest_ID, TAG_1 * dest_ID + TAG_2);
					
					if(G_DEBUG)
						std::cout <<"Master: sending matrix to ID: " << dest_ID << std::endl;
                    
					dest_ID++;
				}
				// Send additional pairs upon worker node's request
				else
				{
					int dest;
					//Recv workers ID
					MPI_Recv(&dest, 1, MPI_INT, MPI_ANY_SOURCE, TAG_1 + TAG_2, MPI_COMM_WORLD,&stat);
					if(G_DEBUG)
						std::cout <<"Master: received request for more graphs from: "<< dest<< std::endl;
                    
					//Collect the result from worker
					isoRank_results.push_back(MPI_Recv_IsoRank_Result(dest, TAG_1 * dest + TAG_3, stat));
					recv_counter++;
					if(G_DEBUG)
						std::cout <<"Master: results were received "<< dest<< std::endl;
                    
					//Send more graphs to worker node
					input_graphs[i]->MPI_Send_Matrix(dest, TAG_1 * dest);
					input_graphs[j]->MPI_Send_Matrix(dest, TAG_1 * dest + TAG_2);
					if(G_DEBUG)
						std::cout <<"Master: sending more graphs to: "<< dest<< std::endl;
				}
			}
		}
		// Recv the remaining result
		while (recv_counter < total_comparisons)
		{
			int dest;
			//Recv workers ID
			MPI_Recv(&dest, 1, MPI_INT, MPI_ANY_SOURCE, TAG_1 + TAG_2, MPI_COMM_WORLD,&stat);
			if(G_DEBUG)
				std::cout <<"Master: received request for more graphs from: "<< dest<< std::endl;
            
			//Collect the result from worker
			isoRank_results.push_back(MPI_Recv_IsoRank_Result(dest, TAG_1 * dest + TAG_3, stat));
			recv_counter++;
			if(G_DEBUG)
				std::cout <<"Master: results were received."<< dest<< std::endl;
		}
		
		//Terminating the slaves by sending a 0*0 matrix to nodes
 		for(int i=1; i < num_procs; i++)
 		{
 			SymMatrix<DataType> emptyMat(0);
 			emptyMat.MPI_Send_Matrix (i, TAG_1*i);
 			emptyMat.MPI_Send_Matrix (i, TAG_1*i+ TAG_2);
 			if (G_DEBUG)
 				std::cout <<"Master: sending terminate signal to ID: " << i << std::endl;
 		}
 		time_end = std::clock();
        
		//printing the results
		if (G_PRINT)
		{
			std::cout << "Master: Computed IsoRank successfully for " << G_NUMBER_OF_FILES << " graphs in "
            << timeElapsed(time_start, time_end) << "(ms)." << std::endl;
            
			std::cout<< "Master: " <<isoRank_results.size() << " results were received.\n frob_norms: ";
			for (int i=0; i < isoRank_results.size(); i++)
			{
				std::cout<< isoRank_results[i].frob_norm << ", ";
			}
			std::cout<<std::endl;
		}
		
		typename std::vector<IsoRank_Result>::iterator res_it;
         for ( res_it = isoRank_results.begin() ; res_it < isoRank_results.end(); ++res_it )
         {
         delete [] res_it->assignments;
         }
         
         typename std::vector<SymMatrix<DataType>* >::iterator graph_it;
         for ( graph_it = input_graphs.begin() ; graph_it < input_graphs.end(); ++graph_it )
         {
         delete  *graph_it;
         }
    }
    //======================================================================*WORKER NODES*==============================================================================
    else
    {
    	while(true)
    	{
    		//Recv graphs from the master
    		DenseMatrix1D<DataType> mat1 (MASTER_ID, TAG_1 * ID ,stat);
    		DenseMatrix1D<DataType> mat2 (MASTER_ID, TAG_1 * ID + TAG_2 ,stat);
            
    		if (G_DEBUG)
    			std::cout << "Process "<< ID << " : received graphs from master"<< std::endl;
            
    		//Terminating the while loop if the matrices are 0*0
			if (mat1.getNumberOfRows() == 0 && mat2.getNumberOfRows() == 0)
			{
				if (G_DEBUG)
					std::cout << "Process "<< ID << ": received terminate signal from master"<< std::endl;
				break;
			}

			struct IsoRank_Result result;
			try
			{
				if (G_USE_ISORANK)
				{
					if (G_DEBUG)
						std::cout << "Process " << ID << ": isoRank: started." << std::endl;
			  		result = isoRank(mat1, mat2, G_GRAPH_MATCHING_ALGORITHM);
			  		if (G_DEBUG)
						std::cout << "Process " << ID << ": isoRank: end." << std::endl;
				}
				if (G_USE_GPGM)
				{
					//GPGM(mat1,mat2);
				}
                
				if (G_DEBUG)
					std::cout << "Process "<< ID << " :requesting for more graphs from master" << std::endl;
				//Sending the ID to master for more graphs
				MPI_Send(&ID, 1, MPI_INT, MASTER_ID, TAG_1 + TAG_2, MPI_COMM_WORLD);
                
				if (G_DEBUG)
                    std::cout << "Process "<< ID << ": :sending result to master" << std::endl;
				//Sending results to master
				MPI_Send_IsoRank_Result(result, MASTER_ID , TAG_1 * ID + TAG_3);
                delete [] result.assignments;
				
			}
			catch (std::exception& e)
			{
				std::cerr << "Process "<< ID << " Exception: " << e.what() << std::endl;
			}
		}
		
	}
	
	if(G_PRINT)
    	std::cout << "Process: "<< ID << " terminated." << std::endl;
    
    MPI_Finalize();
    return 0;
}
Example #14
0
/** Demo program using curses.
 *
 * This demo displays the text entered in a top windows that stretches
 * across the screen. The current prediction is displayed immediately
 * underneath the text window, at the leftmost position.
 *
 * The previous predictions are displayed in cronological order to the
 * right of the current prediction.
 *
 * Subsequent predictions shifted to the right, so that the current
 * prediction is always on the left hand side.
 * Context switches are marked in some way (either a vertical bar or a
 * box enclosing the other prediction boxes).
 *
 */
int main(int argc, char** argv)
{
    parseCommandLineArgs(argc, argv);

    // magic starts here
    PresageCallback* callback = new PresageDemoCallback(buffer); 
    Presage presage(callback, config);

    // configuration variable may be read and written programmatically
    if (suggestions.empty()) {
	suggestions = presage.config("Presage.Selector.SUGGESTIONS");
    } else {
	presage.config("Presage.Selector.SUGGESTIONS", suggestions);
    }

    // curses 
    initscr();
    noecho();
    cbreak();
    keypad(stdscr, TRUE);
    clear();
    refresh();

    disclaimer();

    // curses title window
    const int TITLE_WIN_HEIGHT  = 6;
    const int TITLE_WIN_WIDTH   = COLS;
    const int TITLE_WIN_BEGIN_Y = 0;
    const int TITLE_WIN_BEGIN_X = 0;
    WINDOW* title_win = newwin(TITLE_WIN_HEIGHT, TITLE_WIN_WIDTH, TITLE_WIN_BEGIN_Y, TITLE_WIN_BEGIN_X);
    draw_title_win(title_win);

    // curses context window
    const int CONTEXT_WIN_HEIGHT  = 5;
    const int CONTEXT_WIN_WIDTH   = COLS;
    const int CONTEXT_WIN_BEGIN_Y = TITLE_WIN_BEGIN_Y + TITLE_WIN_HEIGHT + 1;
    const int CONTEXT_WIN_BEGIN_X = 0;
    WINDOW* context_win = newwin(CONTEXT_WIN_HEIGHT, CONTEXT_WIN_WIDTH, CONTEXT_WIN_BEGIN_Y, CONTEXT_WIN_BEGIN_X);
    draw_context_win(context_win, std::string(""));

    // curses function keys window
    const int FUNCTION_WIN_HEIGHT  = atoi(suggestions.c_str()) + 2;
    const int FUNCTION_WIN_WIDTH   = 4;
    const int FUNCTION_WIN_BEGIN_Y = CONTEXT_WIN_BEGIN_Y + CONTEXT_WIN_HEIGHT + 1;
    const int FUNCTION_WIN_BEGIN_X = 0;
    WINDOW* function_win = newwin(FUNCTION_WIN_HEIGHT, FUNCTION_WIN_WIDTH, FUNCTION_WIN_BEGIN_Y, FUNCTION_WIN_BEGIN_X);
    draw_function_keys(function_win);

    mvprintw(LINES - 1, 0, "Press F12 to quit.");
    refresh();


    std::vector<std::string> words;
    int c = ' ';
    do {
	size_t size = words.size();
	if ((KEY_F0 < c) && (c <= KEY_F(size)) && (c - KEY_F0 <= size)) {
	    // prediction was successful. user pressed the function
	    // key corresponding to desired token. selecting
	    // suggestion.
	    std::string message = "Last selected word: " + words[c - KEY_F0 - 1];
	    mvprintw(LINES - 3, 0, message.c_str());
            clrtoeol();
	    move(LINES, COLS);

	    // update buffer with prediction completion
	    buffer << presage.completion(words[c - KEY_F0 - 1]);
	    // ask presage to predict next token
	    words = presage.predict();

	} else {
	    // prediction unsuccessful. get next character from user
	    // and elaborate a new prediction.
	    buffer << static_cast<char>(c);
	    words = presage.predict();

	    // refresh curses screen
	    refresh();
	}
	draw_context_win(context_win, presage.context());
	draw_previous_suggestions(words,
				  presage.context_change(),
                                  CONTEXT_WIN_BEGIN_Y + CONTEXT_WIN_HEIGHT + 1,
                                  FUNCTION_WIN_BEGIN_X + FUNCTION_WIN_WIDTH + 1 );
        c = getch();

    } while( c != KEY_F(12) );


    delwin(title_win);
    delwin(context_win);
    delwin(function_win);
    endwin();

    return 0;
}