Exemple #1
0
void readoption(int argc, char *argv[], bool *convertDir,
                QString *filename, QString *dir, QString *path)
{
    /* 1. CREATE AN OBJECT */
    AnyOption *opt = new AnyOption();

    /* 2. SET PREFERENCES  */
    //opt->noPOSIX(); /* do not check for POSIX style character options */
    //opt->setVerbose(); /* print warnings about unknown options */
    //opt->autoUsagePrint(true); /* print usage for bad options */

    /* 3. SET THE USAGE/HELP   */
    opt->addUsage( "" );
    opt->addUsage( "Usage: " );
    opt->addUsage( "" );
    opt->addUsage( " -h  --help               Prints this help " );
    opt->addUsage( " -f  --filename FILENAME  Filename to be converted " );
    opt->addUsage( " -d  --dir DIRECTORY      File dir to be converted " );
    opt->addUsage( " -p  --path PATH          Path where converted file saves " );
    opt->addUsage( "" );

    /* 4. SET THE OPTION STRINGS/CHARACTERS */

    /* by default all  options  will be checked on the command line and from option/resource file */
    opt->setFlag(  "help", 'h' );   /* a flag (takes no argument), supporting long and short form */
    opt->setOption(  "filename", 'f' ); /* an option (takes an argument), supporting long and short form */
    opt->setOption(  "dir", 'd' ); /* an option (takes an argument), supporting long and short form */
    opt->setOption(  "path", 'p' ); /* an option (takes an argument), supporting long and short form */

    /* 5. PROCESS THE COMMANDLINE AND RESOURCE FILE */

    /* go through the command line and get the options  */
    opt->processCommandArgs( argc, argv );

    if( ! opt->hasOptions()) { /* print usage if no options */
        opt->printUsage();
        delete opt;
        return;
    }

    /* 6. GET THE VALUES */
    if( opt->getFlag( "help" ) || opt->getFlag( 'h' ) )
        opt->printUsage();
    if( opt->getValue( 'f' ) != NULL  || opt->getValue( "filename" ) != NULL  ) {
        *convertDir = false;
        filename->append(QString(opt->getValue( 'f' )));
    }
    if( opt->getValue( 'd' ) != NULL  || opt->getValue( "dir" ) != NULL  ) {
        *convertDir = true;
        dir->append(QString(opt->getValue( 'd' )));
    }
    if( opt->getValue( 'p' ) != NULL  || opt->getValue( "path" ) != NULL  ) {
        path->append(QString(opt->getValue( 'p' )));
    }

    /* 8. DONE */
    delete opt;
}
void UpdaterOptions::parse(int argc, char** argv)
{
	AnyOption parser;
	parser.setOption("install-dir");
	parser.setOption("package-dir");
	parser.setOption("script");
	parser.setOption("wait");
	parser.setOption("mode");
	parser.setFlag("version");
	parser.setFlag("force-elevated");
	parser.setFlag("auto-close");

	parser.processCommandArgs(argc,argv);

	if (parser.getValue("mode"))
	{
		mode = stringToMode(parser.getValue("mode"));
	}
	if (parser.getValue("install-dir"))
	{
		installDir = parser.getValue("install-dir");
	}
	if (parser.getValue("package-dir"))
	{
		packageDir = parser.getValue("package-dir");
	}
	if (parser.getValue("script"))
	{
		scriptPath = parser.getValue("script");
	}
	if (parser.getValue("wait"))
	{
		waitPid = static_cast<PLATFORM_PID>(atoll(parser.getValue("wait")));
	}

	showVersion = parser.getFlag("version");
	forceElevated = parser.getFlag("force-elevated");
	autoClose = parser.getFlag("auto-close");
		
	if (installDir.empty())
	{
		// if no --install-dir argument is present, try parsing
		// the command-line arguments in the old format (which uses
		// a list of 'Key=Value' args)
		parseOldFormatArgs(argc,argv);
	}
}
Exemple #3
0
int main(int argc, char* argv[])
{
    AnyOption opt;

    // Usage
    opt.addUsage( "Example: " );
    opt.addUsage( "  cppbitmessage -p 8444" );
    opt.addUsage( " " );
    opt.addUsage( "Usage: " );
    opt.addUsage( "" );
    opt.addUsage( "  -p --port                 Port to listen on");
    opt.addUsage( "  -V --version              Show version number");
    opt.addUsage( "     --help                 Show help");
    opt.addUsage( "" );

    opt.setOption(  "port", 'p' );
    opt.setFlag(  "version", 'V' );
    opt.setFlag(  "help" );

    opt.processCommandArgs(argc, argv);

    if ((!opt.hasOptions()) || (opt.getFlag( "help" )))
    {
		// print usage if no options
        opt.printUsage();
        return 0;
	}

    if ((opt.getFlag("version")) || (opt.getFlag('V')))
    {
        std::cout << "Version " << VERSION << std::endl;
        return 0;
	}

	int port = 8444;
    if ((opt.getValue("port") != NULL) || (opt.getValue('p')))
    {
        std::stringstream ss;
        ss << opt.getValue("port");
        ss >> port;
	}	
Exemple #4
0
void
simple( int argc, char* argv[] )
{

        AnyOption *opt = new AnyOption();
        opt->noPOSIX(); /* use simpler option type */

        opt->setOption(  "width" );
        opt->setOption(  "height" );
        opt->setFlag( "convert");
        opt->setCommandOption(  "name" );
        opt->setFileOption(  "title" );

        if (  ! opt->processFile( "sample.txt" ) )
                cout << "Failed processing the resource file" << endl ;
        opt->processCommandArgs( argc, argv );

	cout << "THE OPTIONS : " << endl << endl ;
	if( opt->getValue( "width" ) != NULL )
        	cout << "width  : " << opt->getValue( "width" ) << endl ;
	if( opt->getValue( "height" ) != NULL )
        	cout << "height : " << opt->getValue( "height" ) << endl ;
	if( opt->getValue( "name" ) != NULL )
        	cout << "name   : " << opt->getValue( "name" ) << endl ;
	if( opt->getValue( "title" ) != NULL )
        	cout << "title  : " << opt->getValue( "title" ) << endl ;
        if( opt->getFlag( "convert" ) )  
		cout << "convert : set " << endl ;
        cout << endl ;

	cout << "THE ARGUMENTS : " << endl << endl ;
	for( int i = 0 ; i < opt->getArgc() ; i++ ){
		cout << opt->getArgv( i ) << endl  ;
	}
	cout << endl;

        delete opt;

}
Exemple #5
0
int main(int argc, char** argv)
{
    QApplication app(argc, argv);

    AnyOption options;
    options.addUsage(QString("Usage: %1 --help | --console | [--output path --prefix prefixName --suffix suffixName --type typeName").arg(argv[0]).toAscii());
    options.addUsage("");
    options.addUsage("--help                Displays this message.");
    options.addUsage("--console             Run the gui version.");
    options.addUsage("--output [path]       Output directory for the plugin skeleton.");
    options.addUsage("--prefix [prefixName] Prefix to use for the plugin.");
    options.addUsage("--suffix [suffixName] Suffix to use for the plugin.");
    options.addUsage("--type [typeName]     Type to use for the plugin.");
    options.addUsage("--quiet               Process quietly (non gui generation only).");

    options.setFlag("help");
    options.setFlag("console");

    options.setOption("output");
    options.setOption("prefix");
    options.setOption("suffix");
    options.setOption("type");
    options.setOption("quiet");

    options.processCommandArgs(argc, argv);

    if(options.getFlag("help")) {
        options.printUsage();
        return 0;
    }

    if(options.getFlag("console")) {

        bool paramsOk = options.getValue("output") && options.getValue("prefix") && options.getValue("type") && options.getValue("suffix");

        if( !paramsOk ) {
            options.printUsage();
            return 1;
        }

        if(!options.getFlag("quiet")) {
            qDebug() << "output = " << options.getValue("output");
            qDebug() << "prefix = " << options.getValue("prefix");
            qDebug() << "suffix = " << options.getValue("suffix");
            qDebug() << "type = " << options.getValue("type");
        }

        dtkPluginGenerator generator;
        generator.setOutputDirectory(options.getValue("output"));
        generator.setPrefix(options.getValue("prefix"));
        generator.setSuffix(options.getValue("suffix"));
        generator.setType(options.getValue("type"));

        bool resultGenerator = generator.run();

        if(!options.getFlag("quiet")) {
            if(resultGenerator)
                qDebug() << "Generation succeeded.";
            else
                qDebug() << "Plugin generation: Generation failed.";
        }

    } else {

        dtkPluginGeneratorMainWindow generator;
        generator.show();
	generator.raise();
        return app.exec();
        
    }
}
Exemple #6
0
/**
 * @brief Read in a list of array and check for each of the arrays whether they are in LMC form or not
 * @param argc
 * @param argv[]
 * @return
 */
int main (int argc, char *argv[]) {
        char *fname;
        int correct = 0, wrong = 0;

        /* parse command line options */
        AnyOption opt;
        opt.setFlag ("help", 'h'); /* a flag (takes no argument), supporting long and short form */
        opt.setOption ("loglevel", 'l');
        opt.setOption ("oaconfig", 'c');
        opt.setOption ("check");
        opt.setOption ("strength", 's');
        opt.setOption ("prune", 'p');
        opt.setOption ("output", 'o');
        opt.setOption ("mode", 'm');

        opt.addUsage ("oacheck: Check arrays for LMC form or reduce to LMC form");
        opt.addUsage ("Usage: oacheck [OPTIONS] [ARRAYFILE]");
        opt.addUsage ("");
        opt.addUsage (" -h  --help  			Prints this help");
        opt.addUsage (" -l [LEVEL]  --loglevel [LEVEL]	Set loglevel to number");
        opt.addUsage (" -s [STRENGTH]  --strength [STRENGTH] Set strength to use in checking");
        std::string ss = " --check [MODE]			Select mode: ";
        ss +=
            printfstring ("%d (default: check ), %d (reduce to LMC form), %d (apply random transformation and reduce)",
                          MODE_CHECK, MODE_REDUCE, MODE_REDUCERANDOM); //
        for (int i = 3; i < ncheckopts; ++i)
                ss += printfstring (", %d (%s)", static_cast< checkmode_t > (i), modeString ((checkmode_t)i).c_str ());
        opt.addUsage (ss.c_str ());
        opt.addUsage (" -o [OUTPUTFILE] Output file for LMC reduction");

        opt.processCommandArgs (argc, argv);

        algorithm_t algmethod = (algorithm_t)opt.getIntValue ("mode", MODE_AUTOSELECT);

        int loglevel = NORMAL;
        if (opt.getValue ("loglevel") != NULL || opt.getValue ('l') != NULL)
                loglevel = atoi (opt.getValue ('l')); // set custom loglevel
        setloglevel (loglevel);

        if (checkloglevel (QUIET)) {
                print_copyright ();
        }

        if (opt.getFlag ("help") || opt.getFlag ('h') || opt.getArgc () == 0) {
                opt.printUsage ();
                return 0;
        }

        checkmode_t mode = MODE_CHECK;
        if (opt.getValue ("check") != NULL)
                mode = (checkmode_t)atoi (opt.getValue ("check")); // set custom loglevel
        if (mode >= ncheckopts)
                mode = MODE_CHECK;

        logstream (QUIET) << "#time start: " << currenttime () << std::endl;

        double t = get_time_ms ();
        t = 1e3 * (t - floor (t));
        srand (t);

        int prune = opt.getIntValue ('p', 0);

        fname = opt.getArgv (0);
        setloglevel (loglevel);

        int strength = opt.getIntValue ('s', 2);
        if (strength < 1 || strength > 10) {
                printf ("Strength specfied (t=%d) is invalid\n", strength);
                exit (1);
        } else {
                log_print (NORMAL, "Using strength %d to increase speed of checking arrays\n", strength);
        }

        arraylist_t outputlist;
        char *outputfile = 0;
        bool writeoutput = false;
        if (opt.getValue ("output") != NULL) {
                writeoutput = true;
                outputfile = opt.getValue ('o');
        }

        arrayfile_t *afile = new arrayfile_t (fname);
        if (!afile->isopen ()) {
                printf ("Problem opening %s\n", fname);
                exit (1);
        }

        logstream (NORMAL) << "Check mode: " << mode << " (" << modeString (mode) << ")" << endl;

        /* start checking */
        double Tstart = get_time_ms (), dt;

        int index;
        array_link al (afile->nrows, afile->ncols, -1);
        for (int i = 0; i < afile->narrays; i++) {

                index = afile->read_array (al);
                array_t *array = al.array;

                arraydata_t arrayclass = arraylink2arraydata (al, 0, strength);
                arrayclass.lmc_overflow_check ();

                OAextend oaextend;

                lmc_t result = LMC_NONSENSE;

                LMCreduction_t *reduction = new LMCreduction_t (&arrayclass);
                LMCreduction_t *randtest = new LMCreduction_t (&arrayclass);
				array_link test_arraylink = al.clone();
				array_t *testarray = test_arraylink.array;
                randtest->transformation->randomize ();
                reduction->setArray ( al); 
                /* variables needed within the switch statement */
                switch (mode) {
                case MODE_CHECK:
				{
					/* LMC test with reduction code */
					reduction->mode = OA_TEST;
					result = LMCcheck(al, arrayclass, oaextend, *reduction);
					break;
				}
                case MODE_CHECKJ4: {
                        /* LMC test with special code */
                        reduction->mode = OA_TEST;
                        reduction->init_state = COPY;
                        oaextend.setAlgorithm (MODE_J4, &arrayclass);
                        result = LMCcheck (al, arrayclass, oaextend, *reduction);
                        break;
                }
                case MODE_REDUCEJ4: {
                        /* LMC test with special code */
                        reduction->mode = OA_REDUCE;
                        reduction->setArray (al);
                        result = LMCcheckj4 (al, arrayclass, *reduction, oaextend);
                        break;
                }
                case MODE_CHECK_SYMMETRY: {
					myprintf("MODE_CHECK_SYMMETRY not supported any more");
					exit(1);
                }
                case MODE_CHECKJ5X: {
                        oaextend.setAlgorithm (MODE_J5ORDERX, &arrayclass);

                        /* LMC test with special code */
                        reduction->mode = OA_TEST;
                        reduction->init_state = COPY;

                        result = LMCcheck (al, arrayclass, oaextend, *reduction);
                        break;
                }
                case MODE_CHECKJ5XFAST: {
                        oaextend.setAlgorithm (MODE_J5ORDERX, &arrayclass);

                        /* LMC test with special code */
                        reduction->mode = OA_TEST;
                        reduction->init_state = COPY;
                        if (1) {
                                array_link al (array, arrayclass.N, arrayclass.ncols, al.INDEX_NONE);
                                reduction->updateSDpointer (al);
                        }
                        result = LMCcheck (al, arrayclass, oaextend, *reduction);
                        break;
                }
                case MODE_REDUCEJ5X: {
                        OAextend oaextend;
                        oaextend.setAlgorithm (MODE_J5ORDERX, &arrayclass);

                        /* LMC test with special code */
                        printf ("oacheck: WARNING: MODE_CHECKJ5X: untested code, not complete\n");
                        reduction->mode = OA_REDUCE;
                        result = LMCcheck (al, arrayclass, oaextend, *reduction);
                        break;
                }

                case MODE_REDUCE:
                        /* LMC reduction */
				{
					reduction->mode = OA_REDUCE;
					copy_array(array, reduction->array, arrayclass.N, arrayclass.ncols);
					dyndata_t dynd = dyndata_t(arrayclass.N);

					result = LMCreduction(array, array, &arrayclass, &dynd, reduction, oaextend);
					break;
				}
				case MODE_REDUCERANDOM: 
					{
						/* random LMC reduction */
						oaextend.setAlgorithm(MODE_ORIGINAL, &arrayclass);
						reduction->mode = OA_REDUCE;
						randtest->transformation->apply(array, testarray);
						copy_array(testarray, reduction->array, arrayclass.N, arrayclass.ncols);
						reduction->init_state = INIT;
						array_link alp = arrayclass.create_root(arrayclass.ncols, 1000);
						reduction->setArray(alp);
						dyndata_t dynd = dyndata_t(arrayclass.N);

						result = LMCreduction(testarray, testarray, &arrayclass, &dynd, reduction, oaextend);

						if (log_print(NORMAL, "")) {
							reduction->transformation->show();
						}
					} break;
				
                case MODE_REDUCETRAIN:
                        /* LMC reduction with train*/
                        reduction->mode = OA_REDUCE;
                        result = LMCreduction_train (al, &arrayclass, reduction, oaextend);
                        break;
                case MODE_REDUCETRAINRANDOM:
                        /* random LMC reduction with train*/
                        reduction->mode = OA_REDUCE;

                        randtest->transformation->apply (array, testarray);
                        result = LMCreduction_train (test_arraylink, &arrayclass, reduction, oaextend);
                        break;
                case MODE_HADAMARD:
						myprintf("MODE_HADAMARD not supported any more\n");
						exit(1);
                default:
                        result = LMC_NONSENSE;
                        std::cout << "function " << __FUNCTION__ << "line " << __LINE__ << "Unknown mode" << std::endl;
                        exit (1);
                        break;
                }

                bool aequal;
                switch (mode) {
                case MODE_CHECK:
                        if (result == LMC_LESS) {
                                ++wrong;
                                log_print (NORMAL, "Found array nr %i/%i NOT in lmc form:\n", i, afile->narrays);
                        } else {
                                ++correct;
                                log_print (NORMAL, "Found array nr %i/%i in lmc form.\n", i, afile->narrays);
                        }

                        break;
                case MODE_CHECKJ4:
                case MODE_CHECKJ5X:
                case MODE_CHECKJ5XFAST:
                case MODE_CHECK_SYMMETRY:
                        if (result == LMC_LESS) {
                                ++wrong;
                                log_print (NORMAL, "Found array nr %i/%i NOT in minimal form:\n", i, afile->narrays);
                        } else {
                                ++correct;
                                log_print (NORMAL, "Found array nr %i/%i in minimal form.\n", i, afile->narrays);
                        }

                        break;
                case MODE_REDUCE:
                case MODE_REDUCEJ4:
                case MODE_REDUCEJ5X:
                case MODE_REDUCETRAIN:
                        aequal = std::equal (array, array + arrayclass.N * arrayclass.ncols, reduction->array);

                        if ((!aequal) || reduction->state == REDUCTION_CHANGED) {
                                ++wrong;
                                log_print (QUIET, "Reduced array %i/%i to lmc form.\n", i, afile->narrays);
                                if (checkloglevel (NORMAL)) {
                                        log_print (QUIET, "Original:\n");
										
                                        print_array (array, afile->nrows, afile->ncols);
                                        print_array ("Reduction:\n", reduction->array, afile->nrows, afile->ncols);
                                        printf ("---------------\n");
                                }
                                if (checkloglevel (DEBUG)) {
                                        cout << "Transformation: " << endl;
                                        reduction->transformation->show (cout);

                                        rowindex_t row;
                                        colindex_t column;
                                        array_diff (array, reduction->array, arrayclass.N, arrayclass.ncols, row, column);
                                        cout << "Difference at: ";
                                        printf (" row %d, col %d\n", row, column);
                                }
                        } else {
                                ++correct;
                                log_print (QUIET, "Array %i/%i was already in lmc form:\n", i, afile->narrays);
                        }
                        break;
                case MODE_REDUCETRAINRANDOM:
                case MODE_REDUCERANDOM:
                case MODE_REDUCEJ4RANDOM:
                        aequal = std::equal (array, array + arrayclass.N * arrayclass.ncols, reduction->array);

                        if (!aequal) {
                                ++wrong;
                                log_print (SYSTEM,
                                           "Array %i/%i: reduced random transformation not equal to original (BUG!)\n",
                                           i, afile->narrays);
                                if (checkloglevel (NORMAL)) {
                                        print_array ("Original:\n", array, afile->nrows, afile->ncols);
                                        print_array ("Randomized:\n", testarray, afile->nrows, afile->ncols);
                                        print_array ("Reduction:\n", reduction->array, afile->nrows, afile->ncols);
                                        printf ("---------------\n");
                                }
                        } else {
                                ++correct;
                                log_print (QUIET, "Array %i/%i: reduced random transformation to original\n", i,
                                           afile->narrays);
                        }

                        break;
                case MODE_HADAMARD:
                        break;
                default:
                        std::cout << "function " << __FUNCTION__ << "line " << __LINE__ << "unknown mode" << std::endl;
                        break;
                }

                array_link al = array_link ((carray_t *)reduction->array, afile->nrows, afile->ncols, -1);
                if (result == LMC_MORE || !prune) {
                        outputlist.push_back (al);
                }
                delete randtest;
                delete reduction;
                destroy_array (testarray);
        }

        afile->closefile ();
        delete afile;

        if (writeoutput) {
                logstream (NORMAL) << "Writing output (" << outputlist.size () << " arrays)" << endl;
                writearrayfile (outputfile, outputlist);
        }

        logstream (QUIET) << "#time end: " << currenttime () << std::endl;

        return 0;
}
Exemple #7
0
int   main(int argc, char **argv)
{
    AnyOption *opt = new AnyOption();

    opt->addUsage("");
    opt->addUsage("Usage: ");
    opt->addUsage("");
    opt->addUsage(" -h  --help          Print usage ");
    opt->addUsage(" -L  --subsecLet     Letter of Subsector (A-P) to generate, if omitted will generate entire sector ");
    opt->addUsage(" -d  --detail       %|zero|rift|sparse|scattered|dense ");
    opt->addUsage(" -m  --maturity      Tech level, backwater|frontier|mature|cluster ");
    opt->addUsage(" -a  --ac            Two-letter system alignment code ");
    opt->addUsage(" -s  --secName       Name of sector. For default output file name and sectorName_names.txt file");
    opt->addUsage(" -p  --path          Path to sectorName_names.txt file ");
    opt->addUsage(" -o  --outFormat     1|2|3|4|5|6 : v1.0, v2.0, v2.1 v2.1b, v2.2, v2.5 ");
    opt->addUsage(" -u  --outPath       Path and name of output file ");
    opt->addUsage("");

    opt->setCommandFlag("main", 'm');
    opt->setCommandFlag("system", 'S');
    opt->setCommandFlag("sector", 's');
    opt->setCommandFlag("subsector", 'u');
    opt->setCommandFlag("help", 'h');
    opt->setCommandOption("", 'x');
    opt->setCommandOption("", 'y');
    opt->setCommandOption("", 'z');
    opt->setCommandOption("detail", 'd');
    opt->setCommandOption("seed");

    //opt->setVerbose(); /* print warnings about unknown options */
    //opt->autoUsagePrint(true); /* print usage for bad options */

    opt->processCommandArgs(argc, argv);
#if 0
    if(! opt->hasOptions()) {  /* print usage if no options */
        opt->printUsage();
        delete opt;
        return 0;
    }
#endif
    if(opt->getFlag("help") || opt->getFlag('h')) {
        opt->printUsage();
        delete opt;
        return 0;
    }
    //long seed = 12345;
    long x = 0;
    long y = 10;
    long z = 0;
    int detail = 3;
    if(opt->getValue('x') != NULL) {
        x = atol(opt->getValue('x'));
    }
    if(opt->getValue('y') != NULL) {
        y = atol(opt->getValue('y'));
    }
    if(opt->getValue('z') != NULL) {
        z = atol(opt->getValue('z'));
    }
    if(opt->getValue("seed") != NULL) {
        //seed = atol(opt->getValue("seed"));
    }
    if(opt->getValue("detail") != NULL) {
        detail = atol(opt->getValue("detail"));
    }

    long startX, startY, startZ;
    long endX, endY, endZ;
    long sectorX = 8 * 4;
    long sectorY = 10 * 4;
    long sectorZ = 1;
    if(opt->getFlag("sector")) {
        startX = x / sectorX;
        endX = startX + sectorX - 1;
        startY = y / sectorY;
        endY = startY + sectorY - 1;
        startZ = z / sectorZ;
        endZ = startZ + sectorZ - 1;
    } else {
        startX = x;
        endX = x;
        startY = y;
        endY = y;
        startZ = z;
        endZ = z;
    }

    for(int i = startX; i <= endX; i++) {
        for(int j = startY; j <= endY; j++) {
            for(int k = startZ; k <= endZ; k++) {
                printSystem(x, y, z, detail);
            }
        }
    }

}
Exemple #8
0
//+----------------------------------------------------------------------------+
//| main()                                                                     |
//-----------------------------------------------------------------------------+
int
main(int argc, char** argv)
{
  common::PathFileString pfs(argv[0]);
  //////////////////////////////////////////////////////////////////////////////
  // User command line parser
  AnyOption *opt = new AnyOption();
  opt->autoUsagePrint(true);

  opt->addUsage( "" );
  opt->addUsage( "Usage: " );
  char buff[256];
  sprintf(buff, "       Example: %s -r example1_noisy.cfg", pfs.getFileName().c_str());
  opt->addUsage( buff );
  opt->addUsage( " -h  --help                 Prints this help" );
  opt->addUsage( " -r  --readfile <filename>  Reads the polyhedra description file" );
  opt->addUsage( " -t  --gltopic <topic name> (opt) ROS Topic to send OpenGL commands " );
  opt->addUsage( "" );

  opt->setFlag(  "help", 'h' );
  opt->setOption(  "readfile", 'r' );

  opt->processCommandArgs( argc, argv );

  if( opt->getFlag( "help" ) || opt->getFlag( 'h' ) ) {opt->printUsage(); delete opt; return(1);}

  std::string gltopic("OpenGLRosComTopic");
  if( opt->getValue( 't' ) != NULL  || opt->getValue( "gltopic" ) != NULL  ) gltopic = opt->getValue( 't' );
	std::cerr << "[OpenGL communication topic is set to : \"" << gltopic << "\"]\n";

  std::string readfile;
	if( opt->getValue( 'r' ) != NULL  || opt->getValue( "readfile" ) != NULL  )
	{
    readfile = opt->getValue( 'r' );
    std::cerr << "[ World description is read from \"" << readfile << "\"]\n";
	}
	else{opt->printUsage(); delete opt; return(-1);}

  delete opt;
  //
  //////////////////////////////////////////////////////////////////////////////

  //////////////////////////////////////////////////////////////////////////////
  // Initialize ROS and OpenGLRosCom node (visualization)
  std::cerr << "["<<pfs.getFileName()<<"]:" << "[Initializing ROS]"<< std::endl;
  ros::init(argc, argv, pfs.getFileName().c_str());
  if(ros::isInitialized())
    std::cerr << "["<<pfs.getFileName()<<"]:" << "[Initializing ROS]:[OK]\n"<< std::endl;
  else{
    std::cerr << "["<<pfs.getFileName()<<"]:" << "[Initializing ROS]:[FAILED]\n"<< std::endl;
    return(1);
  }
  COpenGLRosCom glNode;
  glNode.CreateNode(gltopic);
  //
  //////////////////////////////////////////////////////////////////////////////

  //////////////////////////////////////////////////////////////////////////////
  // Reading the input file
  std::cerr << "Reading the input file..." << std::endl;
  ShapeVector shapes;
  PoseVector  poses;
  IDVector    ID;
  if(ReadPolyhedraConfigFile(readfile, shapes, poses, ID)==false)
  {
    std::cerr << "["<<pfs.getFileName()<<"]:" << "Error reading file \"" << readfile << "\"\n";
    return(-1);
  }
  std::cerr << "Read " << poses.size() << " poses of " << shapes.size() << " shapes with " << ID.size() << " IDs.\n";
  //
  //////////////////////////////////////////////////////////////////////////////

  //////////////////////////////////////////////////////////////////////////////
  // Visualizing the configuration of objects
  std::cerr << "Visualizing the configuration of objects..." << std::endl;
  for(unsigned int i=0; i<shapes.size(); i++)
  {
    for(size_t j=0; j<shapes[i].F.size(); j++)
    {
      glNode.LineWidth(1.0f);
      glNode.AddColor3(0.3f, 0.6f, 0.5f);
      glNode.AddBegin("LINE_LOOP");
      for(size_t k=0; k<shapes[i].F[j].Idx.size(); k++)
      {
        int idx = shapes[i].F[j].Idx[k];
        Eigen::Matrix<Real,3,1> Vt = poses[i]*shapes[i].V[ idx ];
        glNode.AddVertex(Vt.x(), Vt.y(), Vt.z());
      }
      glNode.AddEnd();
    }
  }
  glNode.SendCMDbuffer();
  ros::spinOnce();
  common::PressEnterToContinue();
  //
  //////////////////////////////////////////////////////////////////////////////

  //////////////////////////////////////////////////////////////////////////////
  // Running PROMTS with A* search algorithm
  std::cerr << "Running PROMTS with Depth Limited search algorithm..." << std::endl;
  promts::ProblemDataStruct pds("Depth-Limited Search");
  pds.m_glNodePtr = &glNode;
  PoseVector refined_poses(shapes.size());
  refinePoses_DLSearch(shapes, poses, ID, refined_poses, pds);
  //
  //////////////////////////////////////////////////////////////////////////////

  return(0);
}
Exemple #9
0
int main(int argc, char * argv[], MPI_Comm commWorld)
{
#else
int main(int argc, char * argv[])
{
 MPI_Comm commWorld;
#endif

  std::string fileName;
  int reduceDM    =  10;
  int reduceS=  1;
#ifndef PARTICLESRENDERER
  std::string fullScreenMode    = "";
  bool stereo     = false;
#endif
  int nmaxsample = 200000;
  std::string display;

  bool inSitu = false;
  bool quickSync = true;
  int sleeptime = 1;

  {
    AnyOption opt;

#define ADDUSAGE(line) {{std::stringstream oss; oss << line; opt.addUsage(oss.str());}}

    ADDUSAGE(" ");
    ADDUSAGE("Usage:");
    ADDUSAGE(" ");
    ADDUSAGE(" -h  --help             Prints this help ");
    ADDUSAGE(" -i  --infile #         Input snapshot filename ");
    ADDUSAGE(" -I  --insitu          Enable in-situ rendering ");
    ADDUSAGE("     --sleep  #        start up sleep in sec [1]  ");
    ADDUSAGE("     --noquicksync      disable syncing with simulation [enabled] ");
    ADDUSAGE("     --reduceDM    #    cut down DM dataset by # factor [10]. 0-disable DM");
    ADDUSAGE("     --reduceS     #    cut down stars dataset by # factor [1]. 0-disable S");
#ifndef PARTICLESRENDERER
    ADDUSAGE("     --fullscreen  #    set fullscreen mode string");
    ADDUSAGE("     --stereo           enable stereo rendering");
#endif
    ADDUSAGE(" -s  --nmaxsample   #   set max number of samples for DD [" << nmaxsample << "]");
    ADDUSAGE(" -D  --display      #   set DISPLAY=display, otherwise inherited from environment");


    opt.setFlag  ( "help" ,        'h');
    opt.setOption( "infile",       'i');
    opt.setFlag  ( "insitu",       'I');
    opt.setOption( "reduceDM");
    opt.setOption( "sleep");
    opt.setOption( "reduceS");
    opt.setOption( "fullscreen");
    opt.setFlag("stereo");
    opt.setOption("nmaxsample", 's');
    opt.setOption("display", 'D');
    opt.setFlag  ( "noquicksync");

    opt.processCommandArgs( argc, argv );


    if( ! opt.hasOptions() ||  opt.getFlag( "help" ) || opt.getFlag( 'h' ) )
    {
      /* print usage if no options or requested help */
      opt.printUsage();
      ::exit(0);
    }

    char *optarg = NULL;
    if (opt.getFlag("insitu"))  inSitu = true;
    if ((optarg = opt.getValue("infile")))       fileName           = std::string(optarg);
    if ((optarg = opt.getValue("reduceDM"))) reduceDM       = atoi(optarg);
    if ((optarg = opt.getValue("reduceS"))) reduceS       = atoi(optarg);
#ifndef PARTICLESRENDERER
    if ((optarg = opt.getValue("fullscreen")))	 fullScreenMode     = std::string(optarg);
    if (opt.getFlag("stereo"))  stereo = true;
#endif
    if ((optarg = opt.getValue("nmaxsample"))) nmaxsample = atoi(optarg);
    if ((optarg = opt.getValue("display"))) display = std::string(optarg);
    if ((optarg = opt.getValue("sleep"))) sleeptime = atoi(optarg);
    if (opt.getValue("noquicksync")) quickSync = false;

    if ((fileName.empty() && !inSitu) ||
        reduceDM < 0 || reduceS < 0)
    {
      opt.printUsage();
      ::exit(0);
    }

#undef ADDUSAGE
  }

  MPI_Comm comm = MPI_COMM_WORLD;
  int mpiInitialized = 0;
  MPI_Initialized(&mpiInitialized);
  if (!mpiInitialized)
    MPI_Init(&argc, &argv);
  else
    comm = commWorld;

  int nranks, rank;
  MPI_Comm_size(comm, &nranks);
  MPI_Comm_rank(comm, &rank);

  char processor_name[MPI_MAX_PROCESSOR_NAME];
  int namelen;
  MPI_Get_processor_name(processor_name,&namelen);
  fprintf(stderr, "bonsai_renderer:: Proc id: %d @ %s , total processes: %d (mpiInit) \n", rank, processor_name, nranks);

  if (rank == 0)
  {
    char hostname[256];
    gethostname(hostname,256);
    char * display = getenv("DISPLAY");
    fprintf(stderr, "root: %s  display: %s \n", hostname, display);
  }

  if (!display.empty())
  {
    std::string var="DISPLAY="+display;
    putenv((char*)var.c_str());
  }

  if (rank == 0)
    fprintf(stderr, " Sleeping for %d seconds \n", sleeptime);
  sleep(sleeptime);



  using BonsaiCatalystDataT = BonsaiCatalystData;
  BonsaiCatalystDataT *rDataPtr;
  if (inSitu)
  {
    rDataPtr = new BonsaiCatalystDataT(rank,nranks,comm);
  }
  else
  {
    if ((rDataPtr = readBonsai<BonsaiCatalystDataT>(rank, nranks, comm, fileName, reduceDM, reduceS)))
    {}
    else
    {
      if (rank == 0)
        fprintf(stderr, " I don't recognize the format ... please try again , or recompile to use with old tipsy if that is what you use ..\n");
      MPI_Finalize();
      ::exit(-1);
    }
    rDataPtr->computeMinMax();
    rDataPtr->setNewData();
  }

  assert(rDataPtr != 0);


  auto callbackFunc = [&](const int code) 
  {
    int quitL = (code == -1) || terminateRenderer;  /* exit code */
    int quitG;
    MPI_Allreduce(&quitL, &quitG, 1, MPI_INT, MPI_SUM, comm);
    if (quitG)
    {
      MPI_Finalize();
      ::exit(0);
    }

    if (inSitu )
      if (fetchSharedData(quickSync, *rDataPtr, rank, nranks, comm, reduceDM, reduceS))
      {
        rDataPtr->setNewData();
      }
  };

  bonsaistd::function<void(int)> callback = callbackFunc;
  callback(0);  /* init data set */

  renderer(
      argc, argv, 
      rank, nranks, comm,
      *rDataPtr,
      fullScreenMode.c_str(), 
      stereo,
      callback);

//  while(1) {}
  return 0;
}
Exemple #10
0
/**
	Utilizing AnyOption class, take the command line and parse it for valid options. Handle usage printout as well.
	@param argc argc from main()
	@param char**argv array of char* directly from main()
	@returns If an error occurs, return false. Currently no errors. Always returns true.
 */
bool parsecmd(int argc, char**argv)
{
    stringstream str;
    // Setup all default values if not already set by simple strings and values above.

    if (getenv("WEBRTC_SERVER"))
        mainserver = xGetDefaultServerName();

    if (getenv("WEBRTC_CONNECT"))
    {
        stunserver = "STUN ";
        stunserver += xGetPeerConnectionString();
    }
    
    peername = xGetPeerName();
    
	AnyOption *opt = new AnyOption();

	opt->addUsage("Usage: ");
	opt->addUsage("");
	opt->addUsage(" -h  --help                    Prints this help ");
    opt->addUsage(" --server <servername|IP>[:<serverport>]      Main sever and optional port.");
	opt->addUsage(
			" --stun <stunserver|IP>[:<port>]      STUN server (and optionally port).\n   Default is " STUNSERVER_DEFAULT);
	opt->addUsage(
			" --peername <Name>     Use this name as my client/peer name online.");
    opt->addUsage(" --avopts <none|audio|video|audiovideo>      Enable audio, video, or audiovideo.");
	opt->addUsage("");
    opt->addUsage("Environment variables can be used as defaults as well.");
    opt->addUsage("  WEBRTC_SERVER - Main server name.");
    opt->addUsage("  WEBRTC_CONNECT - STUN server name with port.");
    opt->addUsage("  USERNAME - Peer user name.");
	opt->addUsage("");

	opt->setFlag("help", 'h');
	opt->setOption("server");
	opt->setOption("stun");
	opt->setOption("peername");
	opt->setOption("avopts");

	opt->processCommandArgs(argc, argv);

	/* 6. GET THE VALUES */
	if (opt->getFlag("help") || opt->getFlag('h'))
	{
		opt->printUsage();
		exit(1);
	}

    if (opt->getValue("server"))
    {
        cout << "New main server is " << opt->getValue("server") << endl;
        
        string serverloc = opt->getValue("server");
        size_t colonpos = serverloc.find(':');
        mainserver = serverloc.substr(0,colonpos);
        
        if(colonpos != string::npos)
        {
            stringstream sstrm;
            sstrm << serverloc.substr(colonpos+1);
            sstrm >> mainserver_port;
        }
Exemple #11
0
/// parse the command line options for the program
AnyOption *parseOptions (int argc, char *argv[], algorithm_t &algorithm) {
        AnyOption *opt = new AnyOption;

        /* parse command line options */
        opt->setFlag ("help", 'h'); /* a flag (takes no argument), supporting long and short form */
        opt->setOption ("loglevel", 'l');
        opt->setOption ("sort", 's');
        opt->setFlag ("x", 'x'); /* special debugging flag */
        opt->setOption ("restart", 'r');
        opt->setOption ("oaconfig", 'c');    /* file that specifies the design */
        opt->setOption ("output", 'o');      /* prefix for output files */
        opt->setFlag ("generate", 'g');      /* only generate extensions, do not perform LMC check */
        opt->setFlag ("coptions");           /* print compile time options */
        opt->setOption ("format", 'f');      /* format to write to */
        opt->setOption ("mode", 'm');        /* algorithm method */
        opt->setOption ("maxk", 'K');        /* max number of columns to extend to */
        opt->setOption ("rowsymmetry", 'R'); /* max number of columns to extend to */

        opt->setFlag ("streaming"); /* operate in streaming mode */

        opt->setOption ("initcolprev", 'I'); /* algorithm method */

        opt->addUsage ("Orthonal Arrays: extend orthogonal arrays");
#ifdef OAEXTEND_SINGLECORE
        opt->addUsage ("Usage: oaextendmpi [OPTIONS]");
#else
        opt->addUsage ("Usage: oaextendsingle [OPTIONS]");
#endif

        opt->addUsage ("");
        opt->addUsage (" -h  --help  			Prints this help ");
        opt->addUsage (" --coptions			Show compile time options used ");
        opt->addUsage (" -r [FILE]  --restart [FILE]	Restart with results file ");
        opt->addUsage (" -l [LEVEL] --loglevel [LEVEL]	Set loglevel to number ");
        opt->addUsage (" -s [INTEGER] --sort [INTEGER]	Sort input and output arrays (default: 1) ");
        opt->addUsage (" -c [FILE]  --oaconfig [FILE]	Set file with design specification");
        opt->addUsage (" -g  --generate [FILE]		Only generate arrays, do not perform LMC check");
        opt->addUsage ("  --rowsymmetry [VALUE]		Use row symmetry in generation");
        opt->addUsage (" -o [STR]  --output [FILE]	Set prefix for output (default: result) ");
        opt->addUsage (" -f [FORMAT]			Output format (default: TEXT, or BINARY, D, Z). Format D is "
                       "binary difference, format Z is binary with zero-difference ");
        opt->addUsage (" --initcolprev [INTEGER]	Initialization method of new column (default: 1)");
        opt->addUsage (
            " --maxk [INTEGER] Maximum number of columns to exten to (default: extracted from config file) ");
        opt->addUsage (
            " --streaming			Operate in streaming mode. Generated arrays will be written to disk "
            "immediately. ");

        std::string ss = printfstring (" -m [MODE]			Algorithm (") + algorithm_t_list () + ")\n";
        opt->addUsage (ss.c_str ());
        // opt->printUsage();
        opt->addUsage ("");
        opt->addUsage ("Example: ./oaextendsingle -l 2");

        opt->processCommandArgs (argc, argv);

        if (opt->getValue ("mode") != NULL || opt->getValue ('m') != NULL) {
                int vv = atoi (opt->getValue ('m')); // set custom loglevel
                algorithm = (algorithm_t)vv;
        } else {
                algorithm = MODE_AUTOSELECT;
        }

        return opt;
}
Exemple #12
0
/**
 * @brief Main function for oaextendmpi and oaextendsingle
 * @param argc
 * @param argv[]
 * @return
 */
int main (int argc, char *argv[]) {
#ifdef OAEXTEND_SINGLECORE
        const int n_processors = 1;
        const int this_rank = 0;
#else
        MPI::Init (argc, argv);

        const int n_processors = MPI::COMM_WORLD.Get_size ();
        const int this_rank = MPI::COMM_WORLD.Get_rank ();
#endif

        // printf("MPI: this_rank %d\n", this_rank);

        /*----------SET STARTING ARRAY(S)-----------*/
        if (this_rank != MASTER) {
#ifdef OAEXTEND_MULTICORE
                slave_print (QUIET, "M: running core %d/%d\n", this_rank, n_processors);
#endif
                algorithm_t algorithm = MODE_INVALID;
                AnyOption *opt = parseOptions (argc, argv, algorithm);
                OAextend oaextend;
                oaextend.setAlgorithm (algorithm);

#ifdef OAEXTEND_MULTICORE
                log_print (NORMAL, "slave: receiving algorithm int\n");
                algorithm = (algorithm_t)receive_int_slave ();
                oaextend.setAlgorithm (algorithm);
// printf("slave %d: receive algorithm %d\n", this_rank, algorithm);
#endif

                extend_slave_code (this_rank, oaextend);

                delete opt;
        } else {
                double Tstart = get_time_ms ();
                int nr_extensions;
                arraylist_t solutions, extensions;

                algorithm_t algorithm = MODE_INVALID;
                AnyOption *opt = parseOptions (argc, argv, algorithm);
                print_copyright ();

                int loglevel = opt->getIntValue ('l', NORMAL);
                setloglevel (loglevel);

                int dosort = opt->getIntValue ('s', 1);
                int userowsymm = opt->getIntValue ("rowsymmetry", 1);
                int maxk = opt->getIntValue ("maxk", 100000);
                int initcolprev = opt->getIntValue ("initcolprev", 1);

                const bool streaming = opt->getFlag ("streaming");

                bool restart = false;
                if (opt->getValue ("restart") != NULL || opt->getValue ('r') != NULL) {
                        restart = true;
                }

                const char *oaconfigfile = opt->getStringValue ('c', "oaconfig.txt");
                const char *resultprefix = opt->getStringValue ('o', "result");

                arrayfile::arrayfilemode_t mode = arrayfile_t::parseModeString (opt->getStringValue ('f', "T"));

                OAextend oaextend;
                oaextend.setAlgorithm (algorithm);

                if (streaming) {
                        logstream (SYSTEM) << "operating in streaming mode, sorting of arrays will not work "
                                           << std::endl;
                        oaextend.extendarraymode = OAextend::STOREARRAY;
                }

                // J5_45
                int xx = opt->getFlag ('x');
                if (xx) {
                        oaextend.j5structure = J5_45;
                }

                if (userowsymm == 0) {
                        oaextend.use_row_symmetry = userowsymm;
                        printf ("use row symmetry -> %d\n", oaextend.use_row_symmetry);
                }
                if (opt->getFlag ('g')) {
                        std::cout << "only generating arrays (no LMC check)" << endl;
                        oaextend.checkarrays = 0;
                }

                if (opt->getFlag ("help") || (opt->getValue ("coptions") != NULL)) {
                        if (opt->getFlag ("help")) {
                                opt->printUsage ();
                        }
                        if (opt->getValue ("coptions") != NULL) {
                                print_options (cout);
                        }
                } else {
                        logstream (QUIET) << "#time start: " << currenttime () << std::endl;

                        arraydata_t *ad;
                        ad = readConfigFile (oaconfigfile);
                        ad->lmc_overflow_check ();

                        if (ad == 0) {
                                return 1;
                        }

                        log_print (NORMAL, "Using design file: %s (runs %d, strength %d)\n", oaconfigfile, ad->N,
                                   ad->strength);

                        if (oaextend.getAlgorithm () == MODE_AUTOSELECT) {
                                oaextend.setAlgorithmAuto (ad);
                        }

#ifdef OAEXTEND_SINGLECORE
                        if (initcolprev == 0) {
                                log_print (NORMAL, "setting oaextend.init_column_previous to %d\n", INITCOLUMN_ZERO);
                                oaextend.init_column_previous = INITCOLUMN_ZERO;
                        }
#endif

#ifdef OAEXTEND_MULTICORE
                        int alg = oaextend.getAlgorithm ();
                        for (int i = 0; i < n_processors; i++) {
                                if (i == MASTER) {
                                        continue;
                                }
                                log_print (NORMAL, "MASTER: sending algorithm %d to slave %d\n", alg, i);
                                send_int (alg, i);
                        }
#endif
                        colindex_t col_start;

                        log_print (SYSTEM, "using algorithm %d (%s)\n", oaextend.getAlgorithm (),
                                   oaextend.getAlgorithmName ().c_str ());
                        if (log_print (NORMAL, "")) {
                                cout << oaextend.__repr__ ();
                        }

                        if (restart) { // start from result file
                                int initres = init_restart (opt->getValue ('r'), col_start, solutions);
                                if (initres == 1) { // check if restarting went OK
                                        logstream (SYSTEM) << "Problem with restart from " << opt->getValue ('r') << ""
                                                           << endl;

#ifdef OAEXTEND_MPI
                                        MPI_Abort (MPI_COMM_WORLD, 1);
#endif
                                        exit (1);
                                }

                                if (dosort) {
                                        double Ttmp = get_time_ms ();
                                        sort (solutions.begin (), solutions.end ()); // solutions.sort();

                                        log_print (QUIET, "   sorting of initial solutions: %.3f [s]\n",
                                                   get_time_ms () - Ttmp);
                                }

                                // check that oaconfig agrees with loaded arrays
                                if (solutions.size () > 0) {
                                        if (ad->N != solutions[0].n_rows) {
                                                printf ("Problem: oaconfig does not agree with loaded arrays!\n");
                                                // free_sols(solutions); ??
                                                solutions.clear ();
                                        }
                                }

                        } else {
                                // starting with root
                                if (check_divisibility (ad) == false) { 
                                        log_print (SYSTEM, "ERROR: Failed divisibility test!\n");

#ifdef OAEXTEND_MPI
                                        MPI_Abort (MPI_COMM_WORLD, 1);
#endif
                                        exit (1);
                                }
                                create_root (ad, solutions);
                                col_start = ad->strength;
                        }

                        /*-----------MAIN EXTENSION LOOP-------------*/

                        log_print (SYSTEM, "M: running with %d procs\n", n_processors);

                        maxk = std::min (maxk, ad->ncols);

                        time_t seconds;
                        for (colindex_t current_col = col_start; current_col < maxk; current_col++) {
                                fflush (stdout);
                                arraydata_t *adcol = new arraydata_t (ad, current_col + 1);

                                if (streaming) {

                                        string fname = resultprefix;
                                        fname += "-streaming";
                                        fname += "-" + oafilestring (ad);
                                        logstream (NORMAL) << "oaextend: streaming mode: create file " << fname
                                                           << std::endl;
                                        int nb = arrayfile_t::arrayNbits (*ad);

                                        oaextend.storefile.createfile (fname, adcol->N, ad->ncols, -1, ABINARY, nb);
                                }

                                log_print (SYSTEM, "Starting with column %d (%d, total time: %.2f [s])\n",
                                           current_col + 1, (int)solutions.size (), get_time_ms () - Tstart);
                                nr_extensions = 0;
                                arraylist_t::const_iterator cur_extension;

                                int csol = 0;
                                for (cur_extension = solutions.begin (); cur_extension != solutions.end ();
                                     cur_extension++) {
                                        print_progress (csol, solutions, extensions, Tstart, current_col);
                                        logstream (NORMAL) << cur_extension[0];

                                        if (n_processors == 1) {
                                                nr_extensions += extend_array (*cur_extension, adcol,
                                                                               current_col, extensions, oaextend);
                                        } else {
#ifdef OAEXTEND_MPI
                                                throw_runtime_exception("mpi version of oextend is no longer supported");
                                                double Ttmp = get_time_ms ();
                                                int slave = collect_solutions_single (extensions, adcol);
                                                log_print (DEBUG, "   time: %.2f, collect time %.2f\n",
                                                           (get_time_ms () - Tstart), (get_time_ms () - Ttmp));

                                                /* OPTIMIZE: send multiple arrays to slave 1 once step */
                                                extend_array_mpi (cur_extension->array, 1, adcol, current_col, slave);
#endif
                                        }

#ifdef OAEXTEND_MPI
                                        if ((csol + 1) % nsolsync == 0) {
                                                collect_solutions_all (extensions, adcol);
                                        }
#endif
                                        // OPTIMIZE: periodically write part of the solutions to disk
                                        csol++; /* increase current solution */
                                }
#ifdef OAEXTEND_MPI
                                collect_solutions_all (extensions, adcol);
#endif

                                if (checkloglevel (NORMAL)) {
                                        csol = 0;
                                        for (cur_extension = extensions.begin (); cur_extension != extensions.end ();
                                             cur_extension++) {
                                                log_print (DEBUG, "%i: -----\n", ++csol);
                                                logstream (DEBUG) << cur_extension[0];
                                        }
                                }
                                if (dosort) {
                                        log_print (DEBUG, "Sorting solutions, necessary for multi-processor code\n");
                                        double Ttmp = get_time_ms ();
                                        sort (extensions.begin (), extensions.end ());
                                        log_print (DEBUG, "   sorting time: %.3f [s]\n", get_time_ms () - Ttmp);
                                }

                                save_arrays (extensions, adcol, resultprefix, mode);
                                solutions.swap (extensions); // swap old and newly found solutions
                                extensions.clear ();         // clear old to free up space for new extensions

                                log_print (SYSTEM, "Done with column %i, total of %i solutions (time %.2f s))\n",
                                           current_col + 1, (int)solutions.size (), get_time_ms () - Tstart);

                                delete adcol;

#ifdef OAANALYZE_DISCR
                                logstream (NORMAL) << "Discriminant: " << endl;
                                print_discriminant (ad->N, current_col + 1);
#endif
                        }
                        /*------------------------*/
                        time (&seconds);
                        struct tm *tminfo;
                        tminfo = localtime (&seconds);
                        log_print (SYSTEM, "TIME: %.2f s, %s", get_time_ms () - Tstart, asctime (tminfo));
                        logstream (QUIET) << "#time end: " << currenttime () << std::endl;
                        logstream (QUIET) << "#time total: " << printfstring ("%.1f", get_time_ms () - Tstart)
                                          << " [s]" << std::endl;

                        solutions.clear ();
                        delete ad;

#ifdef OAEXTEND_MPI
                        stop_slaves ();
#endif
                }

                delete opt;
        } /* end of master code */

#ifdef OAEXTEND_MPI
        MPI_Finalize ();
#endif

        return 0;
}
int main(int argc, char** argv)
#endif
/*
#else
int WinMain(
    HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPSTR lpCmdLine,
    int nCmdShow)
#endif
*/
{
	string datapath;

	AnyOption *opt = new AnyOption();
	
    opt->addUsage( "" );
    opt->addUsage( "Usage: " );
    opt->addUsage( "" );
    opt->addUsage( " -h  --help  				Prints this help " );
    opt->addUsage( " -d  --data-path /dir		Data files path " );
    opt->addUsage( "" );

	opt->setFlag(  "help", 'h' );
	opt->setOption(  "data-path", 'd' );

	opt->processCommandArgs( argc, argv );

    if( opt->getFlag( "help" ) || opt->getFlag( 'h' ) ) 
	{
    	GWDBG_OUTPUT("Usage")
        opt->printUsage();
		delete opt;
		return 0;
	}
	if( opt->getValue( 'd' ) != NULL  || opt->getValue( "data-size" ) != NULL  )
		datapath = opt->getValue('d');

	delete opt;

    try
    {
#ifdef GP2X
        GW_PlatformGP2X platform;
#elif defined(GW_PLAT_PANDORA)
        GW_PlatformPandora platform;
#elif defined(GW_PLAT_S60)
        GW_PlatformS60 platform;
#elif defined(GW_PLAT_WIZ)
        GW_PlatformWIZ platform;
#elif defined(GW_PLAT_ANDROID)
        GW_PlatformAndroid platform;
#elif defined(GW_PLAT_IOS)
        GW_PlatformIOS platform;
#else
        GW_PlatformSDL platform(640, 480);
#endif
		if (!datapath.empty())
			platform.datapath_set(datapath);

        platform.initialize();

        GW_GameList gamelist(&platform);

        GW_Menu menu(&platform, &gamelist);
        menu.Run();

        platform.finalize();
    } catch (GW_Exception &e) {
    	GWDBG_OUTPUT(e.what().c_str())
        fprintf(stderr, "%s\n", e.what().c_str());
        return 1;
    }

    return 0;
}
Exemple #14
0
Fichier : main.cpp Projet : jksr/xu
int process_option(int argc, char* argv[]){
	AnyOption *opt = new AnyOption();
	opt->setVerbose();
	opt->addUsage( "" );
	opt->addUsage( "Usage: " );
	opt->addUsage( "" );
	opt->addUsage( "--S0" );
	opt->addUsage( "--G0" );
	opt->addUsage( "--RhoGEF0" );
	opt->addUsage( "--RhoA0" );
	opt->addUsage( "--Inhibitor0" );
	opt->addUsage( "--kg1" );
	opt->addUsage( "--kg2" );
	opt->addUsage( "--kf1" );
	opt->addUsage( "--kfd" );
	opt->addUsage( "--kg3" );
	opt->addUsage( "--kgd" );
	opt->addUsage( "--kf2" );
	opt->addUsage( "--ka1" );
	opt->addUsage( "--ka2" );
	opt->addUsage( "--ki1" );
	opt->addUsage( "--kid" );
	opt->addUsage( "" );

	opt->setOption( "S0" );
	opt->setOption( "G0" );
	opt->setOption( "RhoGEF0" );
	opt->setOption( "RhoA0" );
	opt->setOption( "Inhibitor0" );
	opt->setOption( "kg1" );
	opt->setOption( "kg2" );
	opt->setOption( "kf1" );
	opt->setOption( "kfd" );
	opt->setOption( "kg3" );
	opt->setOption( "kgd" );
	opt->setOption( "kf2" );
	opt->setOption( "ka1" );
	opt->setOption( "ka2" );
	opt->setOption( "ki1" );
	opt->setOption( "kid" );
	

	opt->processCommandArgs( argc, argv );
	if( opt->getValue( "S0" ) != NULL  ){
		S0 = atof(opt->getValue( "S0" ));
	}
	if( opt->getValue( "G0" ) != NULL  ){
		G0 = atof(opt->getValue( "G0" ));
	}
	if( opt->getValue( "RhoGEF0" ) != NULL  ){
		RhoGEF0 = atof(opt->getValue( "RhoGEF0" ));
	}
	if( opt->getValue( "RhoA0" ) != NULL  ){
		RhoA0 = atof(opt->getValue( "RhoA0" ));
	}
	if( opt->getValue( "Inhibitor0" ) != NULL  ){
		Inhibitor0 = atof(opt->getValue( "Inhibitor0" ));
	}
	if( opt->getValue( "kg1" ) != NULL  ){
		kg1 = atof(opt->getValue( "kg1" ));
	}
	if( opt->getValue( "kg2" ) != NULL  ){
		kg2 = atof(opt->getValue( "kg2" ));
	}
	if( opt->getValue( "kf1" ) != NULL  ){
		kf1 = atof(opt->getValue( "kf1" ));
	}
	if( opt->getValue( "kfd" ) != NULL  ){
		kfd = atof(opt->getValue( "kfd" ));
	}
	if( opt->getValue( "kg3" ) != NULL  ){
		kg3 = atof(opt->getValue( "kg3" ));
	}
	if( opt->getValue( "kgd" ) != NULL  ){
		kgd = atof(opt->getValue( "kgd" ));
	}
	if( opt->getValue( "kf2" ) != NULL  ){
		kf2 = atof(opt->getValue( "kf2" ));
	}
	if( opt->getValue( "ka1" ) != NULL  ){
		ka1 = atof(opt->getValue( "ka1" ));
	}
	if( opt->getValue( "ka2" ) != NULL  ){
		ka2 = atof(opt->getValue( "ka2" ));
	}
	if( opt->getValue( "ki1" ) != NULL  ){
		ki1 = atof(opt->getValue( "ki1" ));
	}
	if( opt->getValue( "kid" ) != NULL  ){
		kid = atof(opt->getValue( "kid" ));
	}
	return 0;
}
Exemple #15
0
void
detailed( int argc, char* argv[] )
{

        /* 1. CREATE AN OBJECT */
        AnyOption *opt = new AnyOption();

        /* 2. SET PREFERENCES  */
        //opt->noPOSIX(); /* do not check for POSIX style character options */
        //opt->setVerbose(); /* print warnings about unknown options */
        //opt->noUsage(); /* stop printing Usage */

        /* 3. SET THE USAGE/HELP   */
        opt->addUsage( "Usage: foo [OPTIONS]... [IMAGE FOLDER] " );
        opt->addUsage( "Unknown options/arguments encountered " );
        opt->addUsage( "Use -h or --help for a complete list of options" );

        /* 4. SET THE OPTION STRINGS/CHARACTERS */
        opt->setFlag(  "help", 'h' ); /* for help */
        opt->setOption(  "width", 'w' );
        opt->setOption(  "height" );
        opt->setFlag( "convert");
        opt->setCommandOption(  "name", 'n' );
        opt->setCommandFlag(  "help" );
        opt->setFileOption(  "title" );

        /* 5. PROVIDE THE COMMANDLINE AND RESOURCE FILE */
        if (  ! opt->processFile( "sample.txt" ) )
                cout << "Failed processing the resource file" << endl ;
        opt->processCommandArgs( argc, argv );

        /* 6. GET THE VALUES */
        /* help */
        if( opt->getFlag( "help" ) || opt->getFlag( 'h' ) ){
                opt->printUsage();
		/* print help here */
        }
	cout << "THE OPTIONS : " << endl << endl ;
	if( opt->getValue( 'w' ) != NULL )
        	cout << "w      : " << opt->getValue( 'w' ) << endl ;
	if( opt->getValue( "width" ) != NULL )
        	cout << "width  : " << opt->getValue( "width" ) << endl ;
	if( opt->getValue( "height" ) != NULL )
        	cout << "height : " << opt->getValue( "height" ) << endl ;
	if( opt->getValue( "name" ) != NULL )
       	 	cout << "name   : " << opt->getValue( "name" ) << endl ;
	if( opt->getValue( 'n' ) != NULL )
        	cout << "n      : " << opt->getValue( 'n' ) << endl ;
	if( opt->getValue( "title" ) != NULL )
        	cout << "title  : " << opt->getValue( "title" ) << endl ;
        if( opt->getFlag( "convert" ) )  
		cout << "convert : set " << endl ;
        cout << endl ;

	/* 7. GET THE ACTUAL ARGUMNETS AFTER THE OPTIONS */
	cout << "THE ARGUMENTS : " << endl << endl ;
	for( int i = 0 ; i < opt->getArgc() ; i++ ){
		cout << opt->getArgv( i ) << endl ;
	}
	cout << endl;

        /* 7. DONE */
        delete opt;

}
Exemple #16
0
int main (int argc, char *argv[]) {
        AnyOption opt;
        /* parse command line options */
        opt.setFlag ("help", 'h'); /* a flag (takes no argument), supporting long and short form */
        opt.setOption ("output", 'o');
        opt.setOption ("input", 'I');
        opt.setOption ("rand", 'r');
        opt.setOption ("verbose", 'v');
        opt.setOption ("ii", 'i');
        opt.setOption ("jj");
        opt.setOption ("xx", 'x');
        opt.setOption ("dverbose", 'd');
        opt.setOption ("rows");
        opt.setOption ("cols");
        opt.setOption ("nrestarts");
        opt.setOption ("niter");
        opt.setOption ("mdebug", 'm');
        opt.setOption ("oaconfig", 'c'); /* file that specifies the design */

        opt.addUsage ("Orthonal Array: oatest: testing platform");
        opt.addUsage ("Usage: oatest [OPTIONS] [FILE]");
        opt.addUsage ("");
        opt.addUsage (" -h --help  			Prints this help ");
        opt.processCommandArgs (argc, argv);

        double t0 = get_time_ms (), dt = 0;
        int randvalseed = opt.getIntValue ('r', 1);
        int ix = opt.getIntValue ('i', 1);
        int r = opt.getIntValue ('r', 1);
        int jj = opt.getIntValue ("jj", 5);

        int xx = opt.getIntValue ('x', 0);
        int niter = opt.getIntValue ("niter", 10);
        int verbose = opt.getIntValue ("verbose", 1);

        const char *input = opt.getValue ('I');
        if (input == 0)
                input = "test.oa";

        srand (randvalseed);
        if (randvalseed == -1) {
                randvalseed = time (NULL);
                printf ("random seed %d\n", randvalseed);
                srand (randvalseed);
        }



		array_link array = exampleArray(0);
		lmc_t lmc_type = LMCcheck(array);


		array = array.randomperm();
		array.showarray();
		array_link reduced_array = reduceLMCform(array);
		reduced_array.showarray();
		exit(0);

		try {
			array_link al = exampleArray(r);
			al.show();
			al.showarray();

			std::vector<int> sizes = array2modelmatrix_sizes(al);
			display_vector(sizes); myprintf("\n");
			MatrixFloat modelmatrix = array2modelmatrix(al, "i", 1);
			array_link modelmatrixx = modelmatrix;
			modelmatrixx.show();
			modelmatrixx.showarray();

			modelmatrix = array2modelmatrix(al, "main", 1);
			modelmatrixx = modelmatrix;
			modelmatrixx.show();
			modelmatrixx.showarray();

			exit(0);

		}
		catch (const std::exception &e) {
			std::cerr << e.what() << std::endl;
			throw;
		}

        {
                array_link al = exampleArray (r);

                array_transformation_t tt = reduceOAnauty (al);
                array_link alx = tt.apply (al);
                exit (0);
        }



        return 0;
}
Exemple #17
0
int main( int argc, char **argv ) {

	AnyOption *opt = parseInputOptions( argc, argv );
	
	// Declare and populate variables
	// First, file type
	enum AtmosphericFileType { ATMOSFILE, JETFILE, SLICEFILE };   // Expand this enum as we put in more file types
	AtmosphericFileType filetype;
	int numTypesDeclared = 0;
	string atmosfile = "";
	if ( opt->getValue( "jetfile" ) != NULL ) {
                atmosfile = opt->getValue( "jetfile" );
                filetype = JETFILE;
                numTypesDeclared++;
        }
	if ( opt->getValue( "atmosfile" ) != NULL ) {
                atmosfile = opt->getValue( "atmosfile" );
                filetype = ATMOSFILE;
                numTypesDeclared++;
        }
        if (opt->getValue( "slicefile" ) != NULL ) {
		atmosfile = opt->getValue( "slicefile" );
		filetype = SLICEFILE;
		numTypesDeclared++;
	}

	// Make sure only one file type was requested
	if (numTypesDeclared != 1) {
		delete opt;
		throw invalid_argument( "Atmospheric file must be specified!");
	}

	// Parse arguments based on file type selected and set defaults
	double elev0 = 0, maxelev = 0, delev = 1, azimuth0 = -1, maxazimuth = -1, dazimuth = 1,
		maxraylength = 0, stepsize = 0.01, maxrange = 1e12, sourceheight = -1, maxheight = 150;
	//double lat = 0, lon = 0;
	unsigned int maxskips = 0;
	bool inMPS = true;

	// Elevation angle parameters
	if (opt->getValue( "elev" ) != NULL) {
		elev0 = atof( opt->getValue("elev") );
	} else {
		delete opt;
		throw invalid_argument( "Option --elev is required!" );
	}
	if (fabs(elev0) >= 90.0) {
		delete opt;
		throw invalid_argument( "Option --elev must be in the range (-90,90)!" );
	}
	maxelev = elev0;
	if (opt->getValue( "maxelev" ) != NULL) {
		maxelev = atof( opt->getValue( "maxelev" ) );
	}
	if (opt->getValue( "delev" ) != NULL) {
		delev = atof( opt->getValue( "delev" ) );
	}

	// Convert elevation angles to radians
	elev0 = deg2rad( elev0 );
	delev = deg2rad( delev );
	maxelev = deg2rad( maxelev );

	// Azimuth angle parameters.  We'll keep azimuths in degrees cause that's what they are, 
	// and convert when necessary
	if (filetype != SLICEFILE) {
		if (opt->getValue( "azimuth" ) != NULL) {
			azimuth0 = atof( opt->getValue("azimuth") );
		} else {
			delete opt;
			throw invalid_argument( "Option --azimuth is required!" );
		}

		while (azimuth0 >= 360.0) {
			azimuth0 -= 360.0;
		}
		while (azimuth0 < 0.0) {
			azimuth0 += 360.0;
		}
		maxazimuth = azimuth0;
		if (opt->getValue( "maxazimuth" ) != NULL) {
			maxazimuth = atof( opt->getValue( "maxazimuth" ) );
		}
		if (opt->getValue( "dazimuth" ) != NULL) {
			dazimuth = atof( opt->getValue( "dazimuth" ) );
		}
		while (maxazimuth >= 360.0) {
			maxazimuth -= 360.0;
		}
		while (maxazimuth < 0.0) {
			maxazimuth += 360.0;
		}
	}
	
	// Calculation parameters
	maxraylength = -1.0;
	if (opt->getValue( "maxraylength" ) != NULL) {
		maxraylength = atof( opt->getValue( "maxraylength" ) );
	} else {
		delete opt;
		throw invalid_argument( "Option --maxraylength is required!" );
	}
	/*
	if (opt->getValue( "lat" ) != NULL) {
		lat = atof( opt->getValue( "lat" ) );
	} 
	if (opt->getValue( "lon" ) != NULL) {
		lon = atof( opt->getValue( "lon" ) );
	}
	*/
	if (opt->getValue( "stepsize" ) != NULL) {
		stepsize = atof( opt->getValue( "stepsize" ) );
	}
	if (opt->getValue( "maxrange" ) != NULL) {
		maxrange = atof( opt->getValue( "maxrange" ) );
	}
	sourceheight = -10;
	if (opt->getValue( "sourceheight" ) != NULL) {
		sourceheight = atof( opt->getValue( "sourceheight" ) );
	}
	maxheight = 150;
	if (opt->getValue( "maxheight" ) != NULL) {
		maxheight = atof( opt->getValue( "maxheight" ) );
	}
	if (opt->getValue( "skips" ) != NULL) {
		int tempskips = atoi( opt->getValue( "skips" ));
		maxskips = tempskips < 0 ? 0 : (unsigned int)tempskips;
	}
	if (opt->getValue( "wind_units" ) != NULL) {
		if (strcmp(opt->getValue( "wind_units" ),"kmpersec") == 0) {
			inMPS = false;
		}
	}
	
	// Process azimuth vector.  Since azimuths can wrap around from 360 to 0, we can't
	// easily put it into a for loop.
	int naz = 0;
	double *azvec;
	if (filetype != SLICEFILE) {
		bool azwraps = (maxazimuth < azimuth0);
		if (azwraps) {
			maxazimuth += 360.0;
		}
		naz = (int)floor((maxazimuth-azimuth0)/dazimuth + 0.5) + 1;
		azvec = new double[ naz ];
		int i = 0;
		for (double d = azimuth0; d <= maxazimuth; d += dazimuth) {
			azvec[ i++ ] = (d >= 360.0 ? d - 360.0 : d );
		}
		if (azwraps) {
			maxazimuth -= 360.0;
		}
	}
	

	// Flags
	//bool rangeDependent = !opt->getFlag( "norange" );
	bool rangeDependent = false; // this will be set to true depending on the type of atmosphere used
	bool partial = opt->getFlag( "partial" );
	
	// Initialize the atmospheric profile
	AtmosphericSpecification *spec = 0;
	
	// Declare these but don't allocate yet.  We'll only use one of them, but if we declare
	// them inside the switch statement then they go out of scope too fast.
	JetProfile *jet;
	SampledProfile *sound;
	Slice *slice;
	string order;
	int skiplines;
	
	switch (filetype) {
		case JETFILE:
			jet = new JetProfile( atmosfile );
			spec = new Sounding( jet );
			break;
			
		case ATMOSFILE:
			skiplines = 0;
			if (opt->getValue("skiplines") != NULL) {
				skiplines = atoi( opt->getValue( "skiplines" ) );
			}
			if (opt->getValue( "atmosfileorder" ) != NULL) {
				order = opt->getValue( "atmosfileorder" );
			} else {
				delete opt;
				throw invalid_argument( "Option --atmosfileorder is required for ATMOSFILE files!" );
			}
			sound = new SampledProfile( atmosfile, order.c_str(), skiplines, inMPS );  // Will be deleted when spec is deleted
			//sound->resample( 0.01 * stepsize );
			spec = new Sounding( sound );
			break;
			
		case SLICEFILE:
			slice = new Slice();
			slice->readSummaryFile( atmosfile );
			slice->strict(true);
			spec = slice;
			naz = 1;
			azvec = new double[ 1 ];
			azvec[ 0 ] = normalizeAzimuth( slice->pathAzimuth() );
			rangeDependent = true;
			break;
	}

	// Adjust the source height to ground level
	if (sourceheight < spec->z0(0,0)) {
		sourceheight = spec->z0(0,0);
	}
	
	// semi-secret flag: output the atmosphere on a 1-meter resolution if requested
	if (opt->getFlag( "atmosout" )) {
		ofstream atmosoutfile("atmospheric_profile.out",ofstream::out);
		atmosoutfile << "z t u v w p rho ceff dtdz dudz dvdz dwdz dpdz drhodz dtdx dudx dvdx dwdx dpdx drhodx dtdy dudy dvdy dwdy dpdy drhody" << endl;
		for (double za = sourceheight; za <= 150.0; za += 0.001) {
			atmosoutfile << 
				za << " " << 
				spec->t(0,0,za) << " " << 
				spec->u(0,0,za) << " " << 
				spec->v(0,0,za) << " " << 
				spec->w(0,0,za) << " " << 
				spec->p(0,0,za) << " " << 
				spec->rho(0,0,za) << " " << 
				spec->c0(0,0,za) << " " <<
				spec->dtdz(0,0,za) << " " << 
				spec->dudz(0,0,za) << " " << 
				spec->dvdz(0,0,za) << " " << 
				spec->dwdz(0,0,za) << " " << 
				spec->dpdz(0,0,za) << " " << 
				spec->drhodz(0,0,za) << " " << 
				spec->dtdx(0,0,za) << " " << 
				spec->dudx(0,0,za) << " " << 
				spec->dvdx(0,0,za) << " " << 
				spec->dwdx(0,0,za) << " " << 
				spec->dpdx(0,0,za) << " " << 
				spec->drhodx(0,0,za) << " " << 
				spec->dtdy(0,0,za) << " " << 
				spec->dudy(0,0,za) << " " << 
				spec->dvdy(0,0,za) << " " << 
				spec->dwdy(0,0,za) << " " << 
				spec->dpdy(0,0,za) << " " << 
				spec->drhody(0,0,za) << " " << endl;
				
		}
		atmosoutfile.close();
	}
	



	// Calculation-related variables
	int k = 0;                                 //use k to track loop progressions
	int steps = maxraylength/stepsize;   //set number of steps for the calculation
	double range, turningHeight;

	// Set up break conditions
	//ODESystemBreakCondition *condition1 = 0, *condition2 = 0, *condition3 = 0, *condition4 = 0;
	ODESystemBreakCondition *condition;
	vector< ODESystemBreakCondition * > breakConditions;
	ReflectionCondition2D *bouncer = new ReflectionCondition2D( spec, azimuth0, maxskips );
	//condition1 = new MinimumBreakCondition( 1, 0, "Ray hit the ground." );
	breakConditions.push_back( bouncer );
	/*
		condition = new HitGroundCondition( spec, 0, -1, 1, "Ray hit the ground." );
		breakConditions.push_back( condition );
	*/
	//condition = new UpwardRefractionCondition( 1, "Ray turned back upward", skips );
	//breakConditions.push_back( condition );
	condition = new MaximumBreakCondition( 1, maxheight, "Ray entering thermosphere...stopping solver." );
	breakConditions.push_back( condition );
        condition = new MaximumRangeCondition( 0, -1, 1, maxrange, "Ray reached maximum length." );
	breakConditions.push_back( condition );

	
	// Initialize the solution matrix.  We'll only have to do this once, and we won't
	// need to zero it out between runs because the solver doesn't add to what's 
	// already there.  The solver returns the number of steps taken, so we don't have
	// to worry about accidentally running over into old solutions either.
	//double c0 = profile->c( x, y, zmin, az );
	double *initialConditions;
	int zindex;   // which variable is z?
	Acoustic2DEquationSet *equations = new Acoustic2DEquationSet( spec, elev0, azimuth0, rangeDependent );
	initialConditions = new double[ 6 ];
	zindex = 1;

	// Pass the equations on to the System solver
	//ODESystem *system = new GSL_ODESystem( equations );
	ODESystem *system = new ODESystem( equations );
	
	double **solution = new double*[ steps + 1 ];
        for (int i = 0; i <= steps; i++) {
                solution[ i ] = new double[ equations->numberOfEquations() ];
        }

        // Output to screen the parameters under which we'll be working
	cout 	<< "Ray Trace Parameters:" << endl
		<< "Atmospheric File Name: " << atmosfile << endl
		<< "Maximum Height: " << maxheight << " km" << endl;
	if (naz > 1) {
		cout << "Launch Azimuth: [" << azvec[ 0 ] << "," << dazimuth << "," << azvec[ naz-1 ] 
			<< "]" << endl;
	} else {
		cout << "Launch Azimuth: " << azvec[ 0 ] << endl;
	}
	if (delev > 0) {
		cout << "Launch Elevation: [" << rad2deg(elev0) << "," << rad2deg(delev) << "," << rad2deg(maxelev) << "]" << endl;
	} else {
		cout << "Launch Elevation: " << rad2deg(elev0) << endl;
	}
	cout << endl;
	cout << "Starting calculation..." << endl;

	// loop through the range of elevation angles and azimuths
	for (int azind = 0; azind < naz; azind++) {

		equations->changeAzimuth( azvec[ azind ] );
		bouncer->setLaunchAzimuthDegrees( azvec[ azind ] );
		double c0 = spec->ceff( 0, 0, sourceheight, azvec[ azind ] );

		for (double theta = elev0; theta <= maxelev; theta += delev) {

			// Set up the system of equations to be solved
			double raymin = 0.0;
			equations->changeTakeoffAngle( theta );
			bouncer->setLaunchAngleRadians( theta );
	
			// Initial conditions change when you change the takeoff or azimuth angles
			//equations->setupInitialConditions( initialConditions, sourceheight );
			equations->setupInitialConditions( initialConditions, sourceheight, c0 );
			cout << endl << endl << "Calculating theta = " << rad2deg(theta) << " degrees..." << endl;
			
			// the magic happens here
			k = system->rk4( equations, solution, steps, initialConditions, raymin, maxraylength, breakConditions ); 
			
			// get set up to analyze the results for turning height, amplitude, etc.
			bool therm = false;
			ostringstream fileholder("");
			ostringstream currentSkip("");
			turningHeight = 0.0;
			//int caustics = 0;
			//double *jac = new double[ k+1 ];
			double *amp = new double[ k+1 ];
			double A0 = 0.0, dist1km = 1e15;
			int k_end = 0;
			unsigned int skips = 0;
			
			// Iterate through the solution to output the raypath to a file and do some summary calculations
			for (int i = 0; i <= k; i++) {
				
				if (i > 1 && solution[ i-2 ][ 1 ] > solution[ i-1 ][ 1 ] && solution[ i ][ 1 ] > solution[ i-1 ][ 1 ]) {
					fileholder << currentSkip.str();
					currentSkip.str("");
					k_end = i-1;
					skips++;
				}
				
				// Output (r,z) or (x,y) to buffer
				currentSkip << solution[ i ][ 0 ] << "   " << solution[ i ][ 1 ];
				
				// Calculate the relative amplitude
				amp[ i ] = equations->calculateAmplitude(solution, i);

					
				// Output the relative amplitude to the raypath file
				currentSkip << "   " << amp[ i ];
				
				// Get distance from 1km reference point and see if it's the closest point yet
				if (fabs( solution[i][0] - 1 ) < dist1km) {
					dist1km = fabs(solution[i][0] - 1);
					A0 = amp[ i ];
				}
				currentSkip << endl;
				
				// Check for the highest point in the raypath
				if (solution[i][zindex] > turningHeight) {
					turningHeight = solution[i][zindex];
				}
			}
			
			// report partially-complete bounces if requested
			if (partial || k_end == 0 || bouncer->triggered()) {
				fileholder << currentSkip.str();
				currentSkip.str("");
				k_end = k;
			}
			
			// If the ray died in the thermosphere, there is no applicable range
			if(turningHeight > maxheight || solution[ k ][zindex] > maxheight){
				range = 0.0;
				therm  = true;
			} else {
				// otherwise read or calculate the range of the endpoint
				range = solution[k_end][0];
			}

			// name and open the raypath file
			char pathfile[4096];
			sprintf(pathfile,"raypath_az%06.2f_elev%06.2f.txt",azvec[azind],rad2deg(theta));
			ofstream raypath(pathfile,ios_base::out);

			double tau = equations->calculateTravelTime( solution, k_end, stepsize, azvec[ azind ] );
			double A = amp[ k_end ];
			//double dB = 20 * log10( A / A0 );
			double refDist = 1.0;   // normalize amplitudes to 1 km
			double dB = equations->transmissionLoss( solution, k_end, refDist );
			//double arrival_az = 0, deviation = 0;
			/*
			if (in3d) {
				arrival_az = ((Acoustic3DEquationSet *)equations)->calculateArrivalAzimuth( solution, k, 5 );
				deviation = arrival_az - azvec[ azind ];
				if (deviation > 180.0)
					deviation -= 360.0;
			}
			*/
			
			// Output summary to screen for immediate sanity check
	        	cout << "Ray trace for angle theta = " << theta*180/Pi << " completed." << endl
				<< "Max Turning Height: " << turningHeight << " km" << endl
				<< "Skips: " << bouncer->countBounces() << endl;
			if (!therm) {
		     		cout << "Range: " << range << " km" << endl
				<< "Travel Time: " << tau << " seconds (" << tau / 60.0 << " minutes)" << endl
				<< "Celerity: " << range / tau << " km/s" << endl;
				
				if (spec->rho(0,0,sourceheight) > 0) {
					cout << "Transmission Loss re ~1km: " << dB << " dB" << endl;
					//cout << "Amplitude: " << A << " Pa (" << dB1 << " dB transmission loss re " << refDist << " km)" << endl;
				}
			}
			
			// Output quantities to file
			raypath << "# Azimuth: " << azvec[ azind ] << endl
				<< "# Elevation: " << theta * 180/Pi << endl;
			if (!therm) {
				raypath << "# Turning Height: " << turningHeight << endl
					<< "# Range: " << range << endl 
					<< "# Travel Time: " << tau << endl
					<< "# Celerity: " << range/tau << endl
					<< "# Skips: " << bouncer->countBounces() << endl;
				
				if (spec->rho(0,0,sourceheight) > 0) {
					raypath << "# Final Amplitude: " << A << endl
						<< "# Amplitude @ ~1km: " << A0 << endl
						<< "# Transmission Loss (re 1 km): " << dB << endl;
				}
			}
			
			// Now output the raypath itself
			raypath << fileholder.str() << endl;
			
			raypath.close();
			bouncer->reset();
			//delete [] jac;
			delete [] amp;
			
			// If we died in the thermosphere, we can stop the calculation
			if (therm) break;

		}
	}

	// Clean up memory allocations
	delete system;
	delete equations;
	for (unsigned int j = 0; j < breakConditions.size(); j++) {
		delete breakConditions[ j ];
	}
	for (int j = 0; j <= steps; j++) {
		delete [] solution[j];
        }
	delete [] solution;
	delete [] azvec;
	delete [] initialConditions;
	
	delete spec;
}
Exemple #18
0
int main(int argc, char **argv){
	// nekonstantni nastaveni generatoru nahodnych cisel
	srand((unsigned int)time(0));
	// server cast
	clock_t t1, t2;
	t1 = clock();	

	int NP = 50;
	double F = 0.7; 
	double CR = 0.6; 
	int Generations = 10; 
	int pocet_neuronu = 5; 
	char *nejlepsi_jedinec = "nejlepsi_jedinec.txt";
	char *data = "data.txt";
	int tichy = 0;

	// parsovani parametru
	AnyOption *opt = new AnyOption();
	opt->setVerbose(); /* print warnings about unknown options */
    opt->autoUsagePrint(true); /* print usage for bad options */

	opt->addUsage( "" );
	opt->addUsage( "NNSA (Neural Network Space Arcade) - Testovani rekuretni neuronove site na jednoduche arkade" );
    opt->addUsage( "" );
	opt->addUsage( "Pouziti: " );
    opt->addUsage( "" );
    opt->addUsage( " -h   --help		Zobrazi tuto napovedu " );    
	opt->addUsage( " -n jedinec.txt	Nejlepsi jedinec " ); 
	opt->addUsage( " -d data.txt		Udaje o jednotlivych generacich " ); 
	opt->addUsage( " " );
	opt->addUsage( "      --NP 60	Velikost populace " );
	opt->addUsage( "      --F 0.7	Mutacni konstanta " );
	opt->addUsage( "      --CR 0.8	Prah krizeni " );
	opt->addUsage( "      --generations 100	Pocet kol slechteni populace " );
	opt->addUsage( "      --neurons 4	Pocet neuronu v neuronove siti " );
	opt->addUsage( "      --quiet 1		Neukecany rezim " );
    opt->addUsage( "" );

	opt->setFlag( "help", 'h');   /* a flag (takes no argument), supporting long and short form */
	opt->setOption('n');
	opt->setOption('d');
	opt->setOption("NP");
	opt->setOption("F");
	opt->setOption("CR");
	opt->setOption("generations");
	opt->setOption("neurons");
	opt->setOption("quiet");
	
	opt->processCommandArgs(argc, argv);

	NP = atoi(opt->getValue("NP"));
	F = atof(opt->getValue("F"));
	CR = atof(opt->getValue("CR")); 
	Generations = atoi(opt->getValue("generations"));
	pocet_neuronu = atoi(opt->getValue("neurons"));
	nejlepsi_jedinec = opt->getValue('n');
	data = opt->getValue('d');
	tichy = atoi(opt->getValue("quiet"));

	cout << "Parametry diferencialni evoluce:" << endl;
	cout << " -> Velikost populace NP = " << NP << endl;
	cout << " -> Mutacni konstanta F = " << F  << endl;
	cout << " -> Prah krizeni CR = " << CR << endl;
	cout << " -> Pocet generaci = " << Generations << endl;
	cout << " -> Pocet neuronu = " << pocet_neuronu << endl;

	DiferencialniEvoluce *d1 = new DiferencialniEvoluce(NP, F, CR, Generations, pocet_neuronu, &ohodnoceni, tichy, data);
	d1->UlozNejlepsiJedinec(nejlepsi_jedinec);
	

	// 32bit - pretece cca po 36 minutach
	t2 = clock();
	cout << "Doba behu programu: " << ((double) (t2 - t1))/CLOCKS_PER_SEC << endl;


	return 0;
}