Esempio n. 1
0
int hpx_main(boost::program_options::variables_map& vm)
{
    using hpx::lcos::local::dataflow;

    boost::uint64_t nt = vm["nt"].as<boost::uint64_t>();   // Number of steps.
    boost::uint64_t nx = vm["nx"].as<boost::uint64_t>();   // Number of grid points.
    boost::uint64_t np = vm["np"].as<boost::uint64_t>();   // Number of partitions.

    if (vm.count("no-header"))
        header = false;

    std::vector<hpx::id_type> localities = hpx::find_all_localities();
    std::size_t nl = localities.size();                    // Number of localities

    if (np < nl)
    {
        std::cout << "The number of partitions should not be smaller than "
                     "the number of localities" << std::endl;
        return hpx::finalize();
    }

    // Create the local stepper instance, register it
    stepper step;

    // Measure execution time.
    boost::uint64_t t = hpx::util::high_resolution_clock::now();

    // Perform all work and wait for it to finish
    hpx::future<stepper_server::space> result = step.do_work(np/nl, nx, nt);

    // Gather results from all localities
    if (0 == hpx::get_locality_id())
    {
        boost::uint64_t elapsed = 0;
        hpx::future<std::vector<stepper_server::space> > overall_result =
            hpx::lcos::gather_here(gather_basename, std::move(result), nl);

        // Print the solution at time-step 'nt'.
        if (vm.count("results"))
        {
            std::vector<stepper_server::space> solution = overall_result.get();
            elapsed = hpx::util::high_resolution_clock::now() - t;

            for (std::size_t i = 0; i != nl; ++i)
            {
                stepper_server::space const& s = solution[i];
                for (std::size_t j = 0; j != np; ++j)
                {
                    std::cout << "U[" << i*np + j << "] = "
                        << s[j].get_data(partition_server::middle_partition).get()
                        << std::endl;
                }
            }
        }
        else
        {
            overall_result.wait();
            elapsed = hpx::util::high_resolution_clock::now() - t;
        }

    
        boost::uint64_t const os_thread_count = hpx::get_os_thread_count();
        print_time_results(os_thread_count, elapsed, nx, np, nt, header);
    }
    else
    {
        hpx::lcos::gather_there(gather_basename, std::move(result)).wait();
    }

    return hpx::finalize();
}
Esempio n. 2
0
void parseArguments(const char* parametersFileName, int ac, char** av,
		    po::variables_map& vm, po::variables_map& vm_file){

  char** argv;
  int argc;
  if( parametersFileName )
    argc = loadParametersFile(parametersFileName,&argv);
  else{ 
    argc = 0;
    argv = NULL;
  }
  po::options_description desc("Allowed options ");
  desc.add_options()
	("help", "produce help message")
	("compression", po::value<int>(), "set compression level")
	("seed", po::value<int>(), "set the global seed of the pseudo random generator")
	("popSize",po::value<int>(),"set the population size")
	("nbOffspring",po::value<int>(),"set the offspring population size")
	("survivingParents",po::value<float>(),"set the reduction size for parent population")
	("survivingOffspring",po::value<float>(),"set the reduction size for offspring population")
	("elite",po::value<int>(),"Nb of elite parents (absolute), 0 for no elite")
	("eliteType",po::value<int>(),"Strong (1) or weak (0)")
	("nbGen",po::value<int>(),"Set the number of generation")
	("timeLimit",po::value<int>(),"Set the timeLimit, (0) to deactivate")
	("selectionOperator",po::value<string>(),"Set the Selection Operator (default : Tournament)")
	("selectionPressure",po::value<float>(),"Set the Selection Pressure (default : 2.0)")
	("reduceParentsOperator",po::value<string>(),"Set the Parents Reducing Operator (default : Tournament)")
	("reduceParentsPressure",po::value<float>(),"Set the Parents Reducing Pressure (default : 2.0)")
	("reduceOffspringOperator",po::value<string>(),"Set the Offspring Reducing Operator (default : Tournament)")
	("reduceOffspringPressure",po::value<float>(),"Set the Offspring Reducing Pressure (default : 2.0)")	
	("reduceFinalOperator",po::value<string>(),"Set the Final Reducing Operator (default : Tournament)")
	("reduceFinalPressure",po::value<float>(),"Set the Final Reducing Pressure (default : 2.0)")
	("optimiseIterations",po::value<int>(),"Set the number of optimisation iterations (default : 100)")
	("baldwinism",po::value<int>(),"Only keep fitness (default : 0)")
	("remoteIslandModel",po::value<int>(),"Boolean to activate the individual exachange with remote islands (default : 0)")
	("ipFile",po::value<string>(),"File containing all the IPs of the remote islands)")
	("migrationProbability", po::value<float>(),"Probability to send an individual each generation")
    ("serverPort", po::value<int>(),"Port of the Server")
	("outputfile",po::value<string>(),"Set an output file for the final population (default : none)")
	("inputfile",po::value<string>(),"Set an input file for the initial population (default : none)")
	("printStats",po::value<int>(),"Print the Stats (default : 1)")
	("plotStats",po::value<int>(),"Plot the Stats (default : 0)")
	("generateCSVFile",po::value<int>(),"Print the Stats to a CSV File (Filename: ProjectName.dat) (default : 0)")
	("generatePlotScript",po::value<int>(),"Generates a Gnuplot script to plat the Stats (Filename: ProjectName.plot) (default : 0)")
	("generateRScript",po::value<int>(),"Generates a R script to plat the Stats (Filename: ProjectName.r) (default : 0)")
//	("printStatsFile",po::value<int>(),"Print the Stats to a File (Filename: ProjectName.dat) (default : 0)")
	("printInitialPopulation",po::value<int>(),"Prints the initial population (default : 0)")
	("printFinalPopulation",po::value<int>(),"Prints the final population (default : 0)")
	("savePopulation",po::value<int>(),"Saves population at the end (default : 0)")
	("startFromFile",po::value<int>(),"Loads the population from a .pop file (default : 0")
	("u1",po::value<string>(),"User defined parameter 1")
	("u2",po::value<string>(),"User defined parameter 2")
	("u3",po::value<int>(),"User defined parameter 3")
	("u4",po::value<int>(),"User defined parameter 4")
	("u5",po::value<int>(),"User defined parameter 5")
	;

  try{
    po::store(po::parse_command_line(ac, av, desc,0), vm);
    if( parametersFileName )
      po::store(po::parse_command_line(argc, argv, desc,0), vm_file);
  }
  catch(po::unknown_option& e){
    cerr << "Unknown option  : " << e.what() << endl;
    cout << desc << endl;
    exit(1);
  }

  po::notify(vm);
  po::notify(vm_file);

  if (vm.count("help")) {
    cout << desc << "\n";
    exit(1);
  }

  for( int i = 0 ; i<argc ; i++ )
    free(argv[i]);
  if( argv )
    free(argv);

}
Esempio n. 3
0
INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo) 
{
	WCHAR namePath[MAX_PATH];
	GetModuleFileName(NULL, namePath, MAX_PATH);
	WCHAR *progName = PathFindFileName(namePath);

	po::options_description desc;

	desc.add_options()
		("help,h", "Print help message and exit")
		("version,V", "Print version and exit")
		("debug,d", "Verbose/Debug output")
		("warning,w", po::wvalue<std::wstring>(), "Warning threshold")
		("critical,c", po::wvalue<std::wstring>(), "Critical threshold")
		("unit,u", po::wvalue<std::wstring>(), "The unit to use for display (default MB)")
		;

	po::basic_command_line_parser<WCHAR> parser(ac, av);

	try {
		po::store(
			parser
			.options(desc)
			.style(
			po::command_line_style::unix_style |
			po::command_line_style::allow_long_disguise)
			.run(),
			vm);
		vm.notify();
	} catch (std::exception& e) {
		std::cout << e.what() << '\n' << desc << '\n';
		return 3;
	}

	if (vm.count("help")) {
		std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
		wprintf(
			L"%s is a simple program to check a machines swap in percent.\n"
			L"You can use the following options to define its behaviour:\n\n", progName);
		std::cout << desc;
		wprintf(
			L"\nIt will then output a string looking something like this:\n\n"
			L"\tSWAP WARNING - 20%% free | swap=2000B;3000;500;0;10000\n\n"
			L"\"SWAP\" being the type of the check, \"WARNING\" the returned status\n"
			L"and \"20%%\" is the returned value.\n"
			L"The performance data is found behind the \"|\", in order:\n"
			L"returned value, warning threshold, critical threshold, minimal value and,\n"
			L"if applicable, the maximal value. Performance data will only be displayed when\n"
			L"you set at least one threshold\n\n"
			L"%s' exit codes denote the following:\n"
			L" 0\tOK,\n\tNo Thresholds were broken or the programs check part was not executed\n"
			L" 1\tWARNING,\n\tThe warning, but not the critical threshold was broken\n"
			L" 2\tCRITICAL,\n\tThe critical threshold was broken\n"
			L" 3\tUNKNOWN, \n\tThe program experienced an internal or input error\n\n"
			L"Threshold syntax:\n\n"
			L"-w THRESHOLD\n"
			L"warn if threshold is broken, which means VALUE > THRESHOLD\n"
			L"(unless stated differently)\n\n"
			L"-w !THRESHOLD\n"
			L"inverts threshold check, VALUE < THRESHOLD (analogous to above)\n\n"
			L"-w [THR1-THR2]\n"
			L"warn is VALUE is inside the range spanned by THR1 and THR2\n\n"
			L"-w ![THR1-THR2]\n"
			L"warn if VALUE is outside the range spanned by THR1 and THR2\n\n"
			L"-w THRESHOLD%%\n"
			L"if the plugin accepts percentage based thresholds those will be used.\n"
			L"Does nothing if the plugin does not accept percentages, or only uses\n"
			L"percentage thresholds. Ranges can be used with \"%%\", but both range values need\n"
			L"to end with a percentage sign.\n\n"
			L"All of these options work with the critical threshold \"-c\" too.\n"
			, progName);
		std::cout << '\n';
		return 0;
	}

	if (vm.count("version"))
		std::wcout << L"Version: " << VERSION << '\n';

	if (vm.count("warning")) {
		try {
			printInfo.warn = threshold(vm["warning"].as<std::wstring>());
		} catch (std::invalid_argument& e) {
			std::cout << e.what() << '\n';
			return 3;
		}
		printInfo.warn.legal = !printInfo.warn.legal;
	}

	if (vm.count("critical")) {
		try {
			printInfo.crit = threshold(vm["critical"].as<std::wstring>());
		} catch (std::invalid_argument& e) {
			std::cout << e.what() << '\n';
			return 3;
		}
		printInfo.crit.legal = !printInfo.crit.legal;
	}

	if (vm.count("debug"))
		debug = TRUE;

	if (vm.count("unit")) {
		try {
			printInfo.unit = parseBUnit(vm["unit"].as<std::wstring>());
		} catch (std::invalid_argument& e) {
			std::cout << e.what() << '\n';
			return 3;
		}
	}

	return -1;
}
	int getCount( const std::string &name ) { return _variablesMap.count( name ); }
Esempio n. 5
0
int hpx_main(boost::program_options::variables_map& vm)
{
    /* Number of partitions dynamically determined
    // Number of partitions.
    // boost::uint64_t np = vm["np"].as<boost::uint64_t>();
    */

    // Number of grid points.
    boost::uint64_t nx = vm["nx"].as<boost::uint64_t>();
    // Number of steps.
    boost::uint64_t nt = vm["nt"].as<boost::uint64_t>();
    // Number of runs (repartition between runs).
    boost::uint64_t nr = vm["nr"].as<boost::uint64_t>();

    if (vm.count("no-header"))
        header = false;

    // Find divisors of nx
    std::vector<boost::uint64_t> divisors;
    for(boost::uint64_t i = 1; i < std::sqrt(nx); ++i) {
        if(nx % i == 0) {
            divisors.push_back(i);
            divisors.push_back(nx/i);
        }
    }
    divisors.push_back(static_cast<boost::uint64_t>(std::sqrt(nx)));
    std::sort(divisors.begin(), divisors.end());

    // Set up APEX tuning
    // The tunable parameter -- how many partitions to divide data into
    long np_index = 1;
    long * tune_params[1] = { 0L };
    long num_params = 1;
    long mins[1]  = { 0 };
    long maxs[1]  = { (long)divisors.size() };
    long steps[1] = { 1 };
    tune_params[0] = &np_index;
    apex::setup_custom_tuning(get_idle_rate, end_iteration_event, num_params,
            tune_params, mins, maxs, steps);

    // Create the stepper object
    stepper step;
    boost::uint64_t const os_thread_count = hpx::get_os_thread_count();

    std::vector<double> data;
    for(boost::uint64_t i = 0; i < nr; ++i)
    {
        boost::uint64_t parts = divisors[np_index];
        boost::uint64_t size_per_part = nx / parts;
        boost::uint64_t total_size = parts * size_per_part;

        //std::cerr << "parts: " << parts << " Per part: " << size_per_part
        //std::cerr << " Overall: " << total_size << std::endl;

        // Measure execution time.
        boost::uint64_t t = hpx::util::high_resolution_clock::now();

        // Execute nt time steps on nx grid points and print the final solution.
        hpx::future<stepper::space> result =
            step.do_work(parts, size_per_part, nt, data);

        stepper::space solution = result.get();
        hpx::wait_all(solution);

        boost::uint64_t elapsed = hpx::util::high_resolution_clock::now() - t;

        // Get new partition size
        apex::custom_event(end_iteration_event, 0);

        // Gather data together
        data.resize(total_size);
        for(boost::uint64_t partition = 0; partition != parts; ++partition) {
            solution[partition].get().copy_into_array(
                data, partition*size_per_part);
        }

        // Print the final solution
        if (vm.count("results"))
        {
            for (boost::uint64_t i = 0; i != parts; ++i)
                std::cout << "U[" << i << "] = " << solution[i].get() << std::endl;
        }

        print_time_results(os_thread_count, elapsed, size_per_part, parts, nt, header);
        header = false; // only print header once
    }

    return hpx::finalize();
}
Esempio n. 6
0
static void onSigOptionsParsed(boost::program_options::variables_map& v)
{
    if(v.count("start-simulation")){
        callLater(std::bind(static_cast<void(SimulationBar::*)(bool)>(&SimulationBar::startSimulation), instance_, true));
    }
}
Esempio n. 7
0
    bool CmdLine::store( int argc , char ** argv ,
                         boost::program_options::options_description& visible,
                         boost::program_options::options_description& hidden,
                         boost::program_options::positional_options_description& positional,
                         boost::program_options::variables_map &params ) {


        {
            // setup binary name
            cmdLine.binaryName = argv[0];
            size_t i = cmdLine.binaryName.rfind( '/' );
            if ( i != string::npos )
                cmdLine.binaryName = cmdLine.binaryName.substr( i + 1 );
            
            // setup cwd
            char buffer[1024];
#ifdef _WIN32
            verify( _getcwd( buffer , 1000 ) );
#else
            verify( getcwd( buffer , 1000 ) );
#endif
            cmdLine.cwd = buffer;
        }
        

        /* don't allow guessing - creates ambiguities when some options are
         * prefixes of others. allow long disguises and don't allow guessing
         * to get away with our vvvvvvv trick. */
        int style = (((po::command_line_style::unix_style ^
                       po::command_line_style::allow_guessing) |
                      po::command_line_style::allow_long_disguise) ^
                     po::command_line_style::allow_sticky);


        try {

            po::options_description all;
            all.add( visible );
            all.add( hidden );

            po::store( po::command_line_parser(argc, argv)
                       .options( all )
                       .positional( positional )
                       .style( style )
                       .run(),
                       params );

            if ( params.count("config") ) {
                ifstream f( params["config"].as<string>().c_str() );
                if ( ! f.is_open() ) {
                    cout << "ERROR: could not read from config file" << endl << endl;
                    cout << visible << endl;
                    return false;
                }

                stringstream ss;
                CmdLine::parseConfigFile( f, ss );
                po::store( po::parse_config_file( ss , all ) , params );
                f.close();
            }

            po::notify(params);
        }
        catch (po::error &e) {
            cout << "error command line: " << e.what() << endl;
            cout << "use --help for help" << endl;
            //cout << visible << endl;
            return false;
        }

        if (params.count("verbose")) {
            logLevel = 1;
        }

        for (string s = "vv"; s.length() <= 12; s.append("v")) {
            if (params.count(s)) {
                logLevel = s.length();
            }
        }

        if (params.count("quiet")) {
            cmdLine.quiet = true;
        }

        if (params.count("traceExceptions")) {
            DBException::traceExceptions = true;
        }

        if ( params.count( "maxConns" ) ) {
            int newSize = params["maxConns"].as<int>();
            if ( newSize < 5 ) {
                out() << "maxConns has to be at least 5" << endl;
                ::_exit( EXIT_BADOPTIONS );
            }
            else if ( newSize >= 10000000 ) {
                out() << "maxConns can't be greater than 10000000" << endl;
                ::_exit( EXIT_BADOPTIONS );
            }
            connTicketHolder.resize( newSize );
        }

        if (params.count("objcheck")) {
            cmdLine.objcheck = true;
        }

        if (params.count("bind_ip")) {
            // passing in wildcard is the same as default behavior; remove and warn
            if ( cmdLine.bind_ip ==  "0.0.0.0" ) {
                cout << "warning: bind_ip of 0.0.0.0 is unnecessary; listens on all ips by default" << endl;
                cmdLine.bind_ip = "";
            }
        }

        string logpath;

#ifndef _WIN32
        if (params.count("unixSocketPrefix")) {
            cmdLine.socket = params["unixSocketPrefix"].as<string>();
            if (!fs::is_directory(cmdLine.socket)) {
                cout << cmdLine.socket << " must be a directory" << endl;
                ::_exit(-1);
            }
        }

        if (params.count("nounixsocket")) {
            cmdLine.noUnixSocket = true;
        }

        if (params.count("fork") && !params.count("shutdown")) {
            cmdLine.doFork = true;
            if ( ! params.count( "logpath" ) && ! params.count( "syslog" ) ) {
                cout << "--fork has to be used with --logpath or --syslog" << endl;
                ::_exit(EXIT_BADOPTIONS);
            }

            if ( params.count( "logpath" ) ) {
                // test logpath
                logpath = params["logpath"].as<string>();
                verify( logpath.size() );
                if ( logpath[0] != '/' ) {
                    logpath = cmdLine.cwd + "/" + logpath;
                }
                bool exists = boost::filesystem::exists( logpath );
                FILE * test = fopen( logpath.c_str() , "a" );
                if ( ! test ) {
                    cout << "can't open [" << logpath << "] for log file: " << errnoWithDescription() << endl;
                    ::_exit(-1);
                }
                fclose( test );
                // if we created a file, unlink it (to avoid confusing log rotation code)
                if ( ! exists ) {
                    unlink( logpath.c_str() );
                }
            }

            cout.flush();
            cerr.flush();
            
            cmdLine.parentProc = getpid();
            
            // facilitate clean exit when child starts successfully
            setupLaunchSignals();

            pid_t c = fork();
            if ( c ) {
                int pstat;
                waitpid(c, &pstat, 0);

                if ( WIFEXITED(pstat) ) {
                    if ( ! WEXITSTATUS(pstat) ) {
                        cout << "child process started successfully, parent exiting" << endl;
                    }

                    _exit( WEXITSTATUS(pstat) );
                }

                _exit(50);
            }

            if ( chdir("/") < 0 ) {
                cout << "Cant chdir() while forking server process: " << strerror(errno) << endl;
                ::_exit(-1);
            }
            setsid();
            
            cmdLine.leaderProc = getpid();

            pid_t c2 = fork();
            if ( c2 ) {
                int pstat;
                cout << "forked process: " << c2 << endl;
                waitpid(c2, &pstat, 0);

                if ( WIFEXITED(pstat) ) {
                    _exit( WEXITSTATUS(pstat) );
                }

                _exit(51);
            }

            // stdout handled in initLogging
            //fclose(stdout);
            //freopen("/dev/null", "w", stdout);

            fclose(stderr);
            fclose(stdin);

            FILE* f = freopen("/dev/null", "w", stderr);
            if ( f == NULL ) {
                cout << "Cant reassign stderr while forking server process: " << strerror(errno) << endl;
                ::_exit(-1);
            }

            f = freopen("/dev/null", "r", stdin);
            if ( f == NULL ) {
                cout << "Cant reassign stdin while forking server process: " << strerror(errno) << endl;
                ::_exit(-1);
            }
        }
        setupSignals( true );

        if (params.count("syslog")) {
            StringBuilder sb;
            sb << cmdLine.binaryName << "." << cmdLine.port;
            Logstream::useSyslog( sb.str().c_str() );
        }
#endif
        if (params.count("logpath") && !params.count("shutdown")) {
            if ( params.count("syslog") ) {
                cout << "Cant use both a logpath and syslog " << endl;
                ::_exit(EXIT_BADOPTIONS);
            }
            
            if ( logpath.size() == 0 )
                logpath = params["logpath"].as<string>();
            uassert( 10033 ,  "logpath has to be non-zero" , logpath.size() );
            initLogging( logpath , params.count( "logappend" ) );
        }

        if ( params.count("pidfilepath")) {
            writePidFile( params["pidfilepath"].as<string>() );
        }

        if (params.count("keyFile")) {
            const string f = params["keyFile"].as<string>();

            if (!setUpSecurityKey(f)) {
                // error message printed in setUpPrivateKey
                ::_exit(EXIT_BADOPTIONS);
            }

            cmdLine.keyFile = true;
            noauth = false;
        }
        else {
            cmdLine.keyFile = false;
        }

#ifdef MONGO_SSL
        if (params.count("sslOnNormalPorts") ) {
            cmdLine.sslOnNormalPorts = true;

            if ( cmdLine.sslPEMKeyPassword.size() == 0 ) {
                log() << "need sslPEMKeyPassword" << endl;
                ::_exit(EXIT_BADOPTIONS);
            }
            
            if ( cmdLine.sslPEMKeyFile.size() == 0 ) {
                log() << "need sslPEMKeyFile" << endl;
                ::_exit(EXIT_BADOPTIONS);
            }
            
            cmdLine.sslServerManager = new SSLManager( false );
            if ( ! cmdLine.sslServerManager->setupPEM( cmdLine.sslPEMKeyFile , cmdLine.sslPEMKeyPassword ) ) {
                ::_exit(EXIT_BADOPTIONS);
            }
        }
        else if ( cmdLine.sslPEMKeyFile.size() || cmdLine.sslPEMKeyPassword.size() ) {
            log() << "need to enable sslOnNormalPorts" << endl;
            ::_exit(EXIT_BADOPTIONS);
        }
#endif
        
        {
            BSONObjBuilder b;
            for (po::variables_map::const_iterator it(params.begin()), end(params.end()); it != end; it++){
                if (!it->second.defaulted()){
                    const string& key = it->first;
                    const po::variable_value& value = it->second;
                    const type_info& type = value.value().type();

                    if (type == typeid(string)){
                        if (value.as<string>().empty())
                            b.appendBool(key, true); // boost po uses empty string for flags like --quiet
                        else {
                            if ( key == "servicePassword" || key == "sslPEMKeyPassword" ) {
                                b.append( key, "<password>" );
                            }
                            else {
                                b.append( key, value.as<string>() );
                            }
                        }
                    }
                    else if (type == typeid(int))
                        b.append(key, value.as<int>());
                    else if (type == typeid(double))
                        b.append(key, value.as<double>());
                    else if (type == typeid(bool))
                        b.appendBool(key, value.as<bool>());
                    else if (type == typeid(long))
                        b.appendNumber(key, (long long)value.as<long>());
                    else if (type == typeid(unsigned))
                        b.appendNumber(key, (long long)value.as<unsigned>());
                    else if (type == typeid(unsigned long long))
                        b.appendNumber(key, (long long)value.as<unsigned long long>());
                    else if (type == typeid(vector<string>))
                        b.append(key, value.as<vector<string> >());
                    else
                        b.append(key, "UNKNOWN TYPE: " + demangleName(type));
                }
            }
            parsedOpts = b.obj();
        }

        {
            BSONArrayBuilder b;
            for (int i=0; i < argc; i++) {
                b << argv[i];
                if ( mongoutils::str::equals(argv[i], "--sslPEMKeyPassword")
                     || mongoutils::str::equals(argv[i], "-sslPEMKeyPassword")
                     || mongoutils::str::equals(argv[i], "--servicePassword")
                     || mongoutils::str::equals(argv[i], "-servicePassword")) {
                    b << "<password>";
                    i++;

                    // hide password from ps output
                    char* arg = argv[i];
                    while (*arg) {
                        *arg++ = 'x';
                    }
                }
            }
            argvArray = b.arr();
        }

        return true;
    }
Esempio n. 8
0
int main(int argc, char** argv)
{
    try
    {
        po::options_description description{"Options"};
        description.add_options()
            ("adult_selection", po::value<std::string>()->default_value("full"), "Adult selection (full/mixed/over)")
            ("child_count", po::value<unsigned>()->default_value(150), "Child count used in mixed/over adult selection")
            ("crossover_points", po::value<unsigned>()->default_value(1), "Crossover points")
            ("crossover_rate", po::value<double>()->default_value(1.0), "Crossover rate")
            ("epsilon", po::value<double>()->default_value(0.1), "Tournament probability of selecting random winner")
            ("generations", po::value<unsigned>()->default_value(1000), "Generation count")
            ("group_size", po::value<unsigned>()->default_value(10), "Tournament group size")
            ("mutation_rate", po::value<double>()->default_value(0.001), "Mutation rate")
            ("parent_selection", po::value<std::string>()->default_value("proportionate"), "Parent selection (proportionate/rank/sigma/tournament)")
            ("population_size", po::value<unsigned>()->default_value(100), "Population size")
            ("problem_size", po::value<unsigned>()->default_value(40), "Problem size")
            ("random_target", "Random target string")
            ("rank_max", po::value<double>()->default_value(1.5), "Rank selection pressure ('max')");

        po::store(po::parse_command_line(argc, argv, description), variables);

        target_value = vi::ea::dynamic_bit_vector{variables["problem_size"].as<unsigned>()};

        if (variables.count("random_target"))
        {
            auto random_generator   = std::default_random_engine{std::random_device{}()};
            auto value_distribution = std::bernoulli_distribution{};

            for (vi::ea::dynamic_bit_vector::size_type i = 0; i != target_value.size(); ++i)
            {
                target_value[i] = value_distribution(random_generator);
            }
        }
        else
        {
            target_value.set();
        }

        const auto adult_selection  = variables["adult_selection"].as<std::string>();
        const auto parent_selection = variables["parent_selection"].as<std::string>();

        if (adult_selection == "full" and parent_selection == "proportionate")
        {
            run_system(BUILD_SYSTEM(
                vi::ea::parent_selection::fitness_proportionate{},
                vi::ea::adult_selection::full_generational_replacement{}));
        }
        else if (adult_selection == "full" and parent_selection == "rank")
        {
            run_system(BUILD_SYSTEM(
                vi::ea::parent_selection::rank{variables["rank_max"].as<double>()},
                vi::ea::adult_selection::full_generational_replacement{}));
        }
        else if (adult_selection == "full" and parent_selection == "sigma")
        {
            run_system(BUILD_SYSTEM(
                vi::ea::parent_selection::sigma{},
                vi::ea::adult_selection::full_generational_replacement{}));
        }
        else if (adult_selection == "full" and parent_selection == "tournament")
        {
            auto parent_selection = vi::ea::parent_selection::tournament{
                variables["group_size"].as<unsigned>(),
                variables["epsilon"].as<double>()};

            run_system(BUILD_SYSTEM(parent_selection, vi::ea::adult_selection::full_generational_replacement{}));
        }
        else if (adult_selection == "mixed" and parent_selection == "proportionate")
        {
            run_system(BUILD_SYSTEM(
                vi::ea::parent_selection::fitness_proportionate{},
                vi::ea::adult_selection::generational_mixing{variables["child_count"].as<unsigned>()}));
        }
        else if (adult_selection == "mixed" and parent_selection == "rank")
        {
            run_system(BUILD_SYSTEM(
                vi::ea::parent_selection::rank{variables["rank_max"].as<double>()},
                vi::ea::adult_selection::generational_mixing{variables["child_count"].as<unsigned>()}));
        }
        else if (adult_selection == "mixed" and parent_selection == "sigma")
        {
            run_system(BUILD_SYSTEM(
                vi::ea::parent_selection::sigma{},
                vi::ea::adult_selection::generational_mixing{variables["child_count"].as<unsigned>()}));
        }
        else if (adult_selection == "mixed" and parent_selection == "tournament")
        {
            auto parent_selection = vi::ea::parent_selection::tournament{
                variables["group_size"].as<unsigned>(),
                variables["epsilon"].as<double>()};

            run_system(BUILD_SYSTEM(
                parent_selection,
                vi::ea::adult_selection::generational_mixing{variables["child_count"].as<unsigned>()}));
        }
        else if (adult_selection == "over" and parent_selection == "proportionate")
        {
            run_system(BUILD_SYSTEM(
                vi::ea::parent_selection::fitness_proportionate{},
                vi::ea::adult_selection::overproduction{variables["child_count"].as<unsigned>()}));
        }
        else if (adult_selection == "over" and parent_selection == "rank")
        {
            run_system(BUILD_SYSTEM(
                vi::ea::parent_selection::rank{variables["rank_max"].as<double>()},
                vi::ea::adult_selection::overproduction{variables["child_count"].as<unsigned>()}));
        }
        else if (adult_selection == "over" and parent_selection == "sigma")
        {
            run_system(BUILD_SYSTEM(
                vi::ea::parent_selection::sigma{},
                vi::ea::adult_selection::overproduction{variables["child_count"].as<unsigned>()}));
        }
        else if (adult_selection == "over" and parent_selection == "tournament")
        {
            auto parent_selection = vi::ea::parent_selection::tournament{
                variables["group_size"].as<unsigned>(),
                variables["epsilon"].as<double>()};

            run_system(BUILD_SYSTEM(
                parent_selection,
                vi::ea::adult_selection::overproduction{variables["child_count"].as<unsigned>()}));
        }
    }
    catch (const po::error& error)
    {
        std::cerr << "error: " << error.what() << std::endl;
        return EXIT_FAILURE;
    }

    return solution_found ? 1 : 0;
}
Esempio n. 9
0
///////////////////////////////////////////////////////////////////////////////
//  do the actual preprocessing
int 
do_actual_work (std::string file_name, po::variables_map const &vm)
{
// current file position is saved for exception handling
boost::wave::util::file_position_type current_position;

    try {
    // process the given file
    ifstream instream(file_name.c_str());
    string instring;

        if (!instream.is_open()) {
            cerr << "waveidl: could not open input file: " << file_name << endl;
            return -1;
        }
        instream.unsetf(std::ios::skipws);
        
#if defined(BOOST_NO_TEMPLATED_ITERATOR_CONSTRUCTORS)
        // this is known to be very slow for large files on some systems
        copy (istream_iterator<char>(instream),
              istream_iterator<char>(), 
              inserter(instring, instring.end()));
#else
        instring = string(istreambuf_iterator<char>(instream.rdbuf()),
                          istreambuf_iterator<char>());
#endif 

    //  This sample uses the lex_token type predefined in the Wave library, but 
    //  but uses a custom lexer type.
        typedef boost::wave::idllexer::lex_iterator<
                boost::wave::cpplexer::lex_token<> >
            lex_iterator_type;
        typedef boost::wave::context<std::string::iterator, lex_iterator_type> 
            context_type;

    // The C++ preprocessor iterators shouldn't be constructed directly. They 
    // are to be generated through a boost::wave::context<> object. This 
    // boost::wave::context object is additionally to be used to initialize and 
    // define different parameters of the actual preprocessing.
    // The preprocessing of the input stream is done on the fly behind the 
    // scenes during iteration over the context_type::iterator_type stream.
    context_type ctx (instring.begin(), instring.end(), file_name.c_str());

    // add include directories to the system include search paths
        if (vm.count("sysinclude")) {
            vector<string> const &syspaths = 
                vm["sysinclude"].as<vector<string> >();
            vector<string>::const_iterator end = syspaths.end();
            for (vector<string>::const_iterator cit = syspaths.begin(); 
                 cit != end; ++cit)
            {
                ctx.add_sysinclude_path((*cit).c_str());
            }
        }
        
    // add include directories to the include search paths
        if (vm.count("include")) {
            cmd_line_util::include_paths const &ip = 
                vm["include"].as<cmd_line_util::include_paths>();
            vector<string>::const_iterator end = ip.paths.end();

            for (vector<string>::const_iterator cit = ip.paths.begin(); 
                 cit != end; ++cit)
            {
                ctx.add_include_path((*cit).c_str());
            }

        // if on the command line was given -I- , this has to be propagated
            if (ip.seen_separator) 
                ctx.set_sysinclude_delimiter();
                 
        // add system include directories to the include path
            vector<string>::const_iterator sysend = ip.syspaths.end();
            for (vector<string>::const_iterator syscit = ip.syspaths.begin(); 
                 syscit != sysend; ++syscit)
            {
                ctx.add_sysinclude_path((*syscit).c_str());
            }
        }
    
    // add additional defined macros 
        if (vm.count("define")) {
            vector<string> const &macros = vm["define"].as<vector<string> >();
            vector<string>::const_iterator end = macros.end();
            for (vector<string>::const_iterator cit = macros.begin(); 
                 cit != end; ++cit)
            {
                ctx.add_macro_definition(*cit);
            }
        }

    // add additional predefined macros 
        if (vm.count("predefine")) {
            vector<string> const &predefmacros = 
                vm["predefine"].as<vector<string> >();
            vector<string>::const_iterator end = predefmacros.end();
            for (vector<string>::const_iterator cit = predefmacros.begin(); 
                 cit != end; ++cit)
            {
                ctx.add_macro_definition(*cit, true);
            }
        }

    // undefine specified macros
        if (vm.count("undefine")) {
            vector<string> const &undefmacros = 
                vm["undefine"].as<vector<string> >();
            vector<string>::const_iterator end = undefmacros.end();
            for (vector<string>::const_iterator cit = undefmacros.begin(); 
                 cit != end; ++cit)
            {
                ctx.remove_macro_definition((*cit).c_str(), true);
            }
        }

    // open the output file
    std::ofstream output;
    
        if (vm.count("output")) {
        // try to open the file, where to put the preprocessed output
        string out_file (vm["output"].as<string>());
        
            output.open(out_file.c_str());
            if (!output.is_open()) {
                cerr << "waveidl: could not open output file: " << out_file 
                     << endl;
                return -1;
            }
        }
        else {
        // output the preprocessed result to std::cout
            output.copyfmt(cout);
            output.clear(cout.rdstate());
            static_cast<std::basic_ios<char> &>(output).rdbuf(cout.rdbuf());
        }

    // analyze the input file
    context_type::iterator_type first = ctx.begin();
    context_type::iterator_type last = ctx.end();
    
    // loop over all generated tokens outputing the generated text 
        while (first != last) {
        // print out the string representation of this token (skip comments)
            using namespace boost::wave;

        // store the last known good token position
            current_position = (*first).get_position();

        token_id id = token_id(*first);

            if (T_CPPCOMMENT == id || T_NEWLINE == id) {
            // C++ comment tokens contain the trailing newline
                output << endl;
            }
            else if (id != T_CCOMMENT) {
            // print out the current token value
                output << (*first).get_value();
            }
            ++first;        // advance to the next token
        }
    }
    catch (boost::wave::cpp_exception const& e) {
    // some preprocessing error
        cerr 
            << e.file_name() << "(" << e.line_no() << "): "
            << e.description() << endl;
        return 1;
    }
    catch (boost::wave::cpplexer::lexing_exception const& e) {
    // some lexing error
        cerr 
            << e.file_name() << "(" << e.line_no() << "): "
            << e.description() << endl;
        return 2;
    }
    catch (std::exception const& e) {
    // use last recognized token to retrieve the error position
        cerr 
            << current_position.get_file() 
            << "(" << current_position.get_line() << "): "
            << "exception caught: " << e.what()
            << endl;
        return 3;
    }
    catch (...) {
    // use last recognized token to retrieve the error position
        cerr 
            << current_position.get_file() 
            << "(" << current_position.get_line() << "): "
            << "unexpected exception caught." << endl;
        return 4;
    }
    return 0;
}
Esempio n. 10
0
// ----------------------------------------------------------------------------
int hpx_main(boost::program_options::variables_map &vm)
{
    namespace process = hpx::components::process;
    namespace fs = boost::filesystem;

    // find where the HPX core libraries are located
    fs::path base_dir = hpx::util::find_prefix();
    base_dir /= "bin";

    fs::path exe = base_dir / "launched_process_test" HPX_EXECUTABLE_EXTENSION;

    std::string launch_target;
    if (vm.count("launch"))
    {
        launch_target = vm["launch"].as<std::string>();
        std::cout << "using launch: " << launch_target << std::endl;
        exe = launch_target;
    }
    else
    {
        std::cout << "using launch (default): " << exe << std::endl;
    }

    // set up command line for launched executable
    std::vector<std::string> args;
    args.push_back(exe.string());
    args.push_back("--exit_code=42");
    args.push_back("--component=test_server");
    args.push_back("--set_message=accessed");
    args.push_back("--hpx:ignore-batch-env");

    // set up environment for launched executable
    std::vector<std::string> env = get_environment();   // current environment

    // Pass along the console parcelport address
    env.push_back("HPX_AGAS_SERVER_ADDRESS=" +
        hpx::get_config_entry("hpx.agas.address", HPX_INITIAL_IP_ADDRESS));
    env.push_back("HPX_AGAS_SERVER_PORT=" +
        hpx::get_config_entry("hpx.agas.port",
            std::to_string(HPX_INITIAL_IP_PORT)));

    // Pass along the parcelport address which should be used by the launched
    // executable

    // The launched executable will run on the same host as this test
    int port = 42;  // each launched HPX locality needs to be assigned a
                    // unique port

    env.push_back("HPX_PARCEL_SERVER_ADDRESS=" +
        hpx::get_config_entry("hpx.agas.address", HPX_INITIAL_IP_ADDRESS));
    env.push_back("HPX_PARCEL_SERVER_PORT=" +
        std::to_string(HPX_CONNECTING_IP_PORT - port));

    // Instruct new locality to connect back on startup using the given name.
    env.push_back("HPX_ON_STARTUP_WAIT_ON_LATCH=launch_process");

    // launch test executable
    process::child c = process::execute(
            hpx::find_here(),
            process::run_exe(exe.string()),
            process::set_args(args),
            process::set_env(env),
            process::start_in_dir(base_dir.string()),
            process::throw_on_error(),
            process::wait_on_latch("launch_process")   // same as above!
        );

    {
        // now create an instance of the test_server component
        hpx::components::client<launch_process::test_server> t =
            hpx::new_<launch_process::test_server>(hpx::find_here());

        hpx::future<std::string> f =
            hpx::async(launch_process_get_message_action(), t);
        HPX_TEST_EQ(f.get(), std::string("initialized"));

        // register the component instance with AGAS
        t.register_as("test_server");       // same as --component=<> above

        // wait for the HPX locality to be up and running
        c.wait();
        HPX_TEST(c);

        // the launched executable should have connected back as a new locality
        HPX_TEST_EQ(hpx::find_all_localities().size(), std::size_t(2));

        // wait for it to exit, we know it returns 42 (see --exit_code=<> above)
        int exit_code = c.wait_for_exit(hpx::launch::sync);
        HPX_TEST_EQ(exit_code, 42);

        // make sure the launched process has set the message in the component
        // this should be the same as --set_message=<> above
        f = hpx::async(launch_process_get_message_action(), t);
        HPX_TEST_EQ(f.get(), std::string("accessed"));

    }   // release the component

    // the new locality should have disconnected now
    HPX_TEST_EQ(hpx::find_all_localities().size(), std::size_t(1));

    return hpx::finalize();
}
Esempio n. 11
0
int hpx_main(boost::program_options::variables_map& vm)
{
    boost::uint64_t order = vm["matrix_size"].as<boost::uint64_t>();
    boost::uint64_t iterations = vm["iterations"].as<boost::uint64_t>();
    boost::uint64_t tile_size = order;

    if(vm.count("tile_size"))
      tile_size = vm["tile_size"].as<boost::uint64_t>();

    verbose = vm.count("verbose");

    boost::uint64_t bytes = 2.0 * sizeof(double) * order * order;

    std::vector<double> A(order * order);
    std::vector<double> B(order * order);

    std::cout
        << "Serial Matrix transpose: B = A^T\n"
        << "Matrix order          = " << order << "\n";
    if(tile_size < order)
        std::cout << "Tile size             = " << tile_size << "\n";
    else
        std::cout << "Untiled\n";
    std::cout
        << "Number of iterations  = " << iterations << "\n";

    using hpx::parallel::for_each;
    using hpx::parallel::par;

    const boost::uint64_t start = 0;

    // Fill the original matrix, set transpose to known garbage value.
    auto range = boost::irange(start, order);
    // parallel for
    for_each(par, boost::begin(range), boost::end(range),
        [&](boost::uint64_t i)
        {
            for(boost::uint64_t j = 0; j < order; ++j)
            {
                A[i * order + j] = COL_SHIFT * j + ROW_SHIFT * i;
                B[i * order + j] = -1.0;
            }
        }
    );

    double errsq = 0.0;
    double avgtime = 0.0;
    double maxtime = 0.0;
    double mintime = 366.0 * 24.0*3600.0; // set the minimum time to a large value;
                                         // one leap year should be enough
    for(boost::uint64_t iter = 0; iter < iterations; ++iter)
    {
        hpx::util::high_resolution_timer t;
        if(tile_size < order)
        {
            auto range = boost::irange(start, order+tile_size, tile_size);
            // parallel for
            for_each(par, boost::begin(range), boost::end(range),
                [&](boost::uint64_t i)
                {
                    for(boost::uint64_t j = 0; j < order; j += tile_size)
                    {
                        for(boost::uint64_t it = i; it < (std::min)(order, i + tile_size); ++it)
                        {
                            for(boost::uint64_t jt = j; jt < (std::min)(order, j + tile_size); ++jt)
                            {
                                B[it + order * jt] = A[jt + order * it];
                            }
                        }
                    }
                }
            );
        }
        else
        {
            auto range = boost::irange(start, order);
            // parallel for
            for_each(par, boost::begin(range), boost::end(range),
                [&](boost::uint64_t i)
                {
                    for(boost::uint64_t j = 0; j < order; ++j)
                    {
                        B[i + order * j] = A[j + order * i];
                    }
                }
            );
        }

        double elapsed = t.elapsed();

        if(iter > 0 || iterations == 1) // Skip the first iteration
        {
            avgtime = avgtime + elapsed;
            maxtime = (std::max)(maxtime, elapsed);
            mintime = (std::min)(mintime, elapsed);
        }

        errsq += test_results(order, B);
    } // end of iter loop

    // Analyze and output results

    double epsilon = 1.e-8;
    if(errsq < epsilon)
    {
        std::cout << "Solution validates\n";
        avgtime = avgtime/static_cast<double>((std::max)(iterations-1, static_cast<boost::uint64_t>(1)));
        std::cout
          << "Rate (MB/s): " << 1.e-6 * bytes/mintime << ", "
          << "Avg time (s): " << avgtime << ", "
          << "Min time (s): " << mintime << ", "
          << "Max time (s): " << maxtime << "\n";

        if(verbose)
          std::cout << "Squared errors: " << errsq << "\n";
    }
    else
    {
        std::cout
          << "ERROR: Aggregate squared error " << errsq
          << " exceeds threshold " << epsilon << "\n";
        hpx::terminate();
    }

    return hpx::finalize();
}
Esempio n. 12
0
int
parseParameters( boost::program_options::variables_map _vm, int ruleGen, execMyRuleInp_t *execMyRuleInp, char *inBuf ) {
    strArray_t strArray;
    int status, i, j;
    char *value;
    char line[MAX_NAME_LEN];
    int promptF = 0;
    int labelF = 0;

    if ( inBuf == NULL || strcmp( inBuf, "null" ) == 0 ) {
        execMyRuleInp->inpParamArray = NULL;
        return 0;
    }

    memset( &strArray, 0, sizeof( strArray ) );

    status = splitMultiStr( inBuf, &strArray );

    if ( status < 0 ) {
        rodsLog( LOG_ERROR,
                 "parseMsInputParam: parseMultiStr error, status = %d", status );
        execMyRuleInp->inpParamArray = NULL;
        return status;
    }

    status = 0;

    resizeStrArray( &strArray, MAX_NAME_LEN );
    value = strArray.value;

    if ( _vm.count( "file" ) ) {
        if ( _vm.count( "parameters" ) ) {
            std::vector< std::string > parameters;
            try {
                parameters = _vm["parameters"].as< std::vector< std::string > >();
            } catch ( boost::bad_any_cast& e ) {
                std::cerr << "Bad parameter list provided to parseParameters\n";
                std::cerr << "Use -h or --help for help\n";
                return -1;
            }

            for ( size_t inx = 0; inx < parameters.size(); ++inx ) {
                std::string param = parameters.at(inx);
                /* using the values from the input line following -F <filename> */
                /* each string is supposed to have to format label=value */

                if ( param == "prompt" ) {
                    promptF = 1;
                    break;
                }

                if ( param == "default" || param.length() == 0 ) {
                    continue;
                }
                else if ( param.at(0) == '*' ) {
                    size_t eqInx;
                    std::string tmpStr;
                    if ( inx > 0 && labelF == 0 ) {
                        return CAT_INVALID_ARGUMENT;
                    }
                    labelF = 1;
                    if ( ( eqInx = param.find( "=" ) ) == std::string::npos ) {
                        return CAT_INVALID_ARGUMENT;
                    }

                    tmpStr = param.substr( 0, eqInx );
                    for ( j = 0; j < strArray.len; j++ ) {
                        if ( strstr( &value[j * strArray.size], tmpStr.c_str() ) == &value[j * strArray.size] ) {
                            char *val = quoteString( param.c_str(), _vm.count( "string" ), 1 );
                            rstrcpy( &value[j * strArray.size], val, strArray.size );
                            free( val );
                            break;
                        }
                    }
                    if ( j == strArray.len ) {
                        printf( "Ignoring Argument \"%s\"\n", param.c_str() );
                    }
                } else {
                    char *valPtr = &value[inx * strArray.size];
                    char *tmpPtr;

                    if ( labelF == 1 ) {
                        return CAT_INVALID_ARGUMENT;
                    }
                    if ( ( tmpPtr = strstr( valPtr, "=" ) ) != NULL ) {
                        tmpPtr++;
                        char *val = quoteString( param.c_str(), _vm.count( "string" ), 0 );
                        rstrcpy( tmpPtr, val,
                                strArray.size - ( tmpPtr - valPtr + 1 ) );
                        free( val );
                    }
                }
            }
        }
    }

    for ( i = 0; i < strArray.len; i++ ) {
        char *valPtr = &value[i * strArray.size];
        char *tmpPtr;

        if ( ( tmpPtr = strstr( valPtr, "=" ) ) != NULL ) {
            *tmpPtr = '\0';
            tmpPtr++;
            if ( *tmpPtr == '$' ) {
                /* If $ is used as a value in the input file for label=value then
                 the remaining command line arguments are taken as values.
                 If no command line arguments are given then the user is prompted
                 for the input value
                 */
                printf( "Default %s=%s\n    New %s=", valPtr, tmpPtr + 1, valPtr );
                if ( fgets( line, MAX_NAME_LEN, stdin ) == NULL ) {
                    return CAT_INVALID_ARGUMENT;
                }
                size_t line_len = strlen( line );
                if ( line_len > 0 && '\n' == line[line_len - 1] ) {
                    line[line_len - 1] = '\0';
                    line_len--;
                }
                char *val = line_len > 0 ?
                            quoteString( line, _vm.count( "string" ) && ruleGen, 0 ) :
                            strdup( tmpPtr + 1 );
                addMsParam( execMyRuleInp->inpParamArray, valPtr, STR_MS_T,
                            val, NULL );
            }
            else if ( promptF == 1 ) {
                /* the user has asked for prompting */
                printf( "Current %s=%s\n    New %s=", valPtr, tmpPtr, valPtr );
                if ( fgets( line, MAX_NAME_LEN, stdin ) == NULL ) {
                    return CAT_INVALID_ARGUMENT;
                }
                size_t line_len = strlen( line );
                if ( line_len > 0 && '\n' == line[line_len - 1] ) {
                    line[line_len - 1] = '\0';
                    line_len--;
                }
                char *val = line_len > 0 ?
                            quoteString( line, _vm.count( "string" ) && ruleGen, 0 ) :
                            strdup( tmpPtr );
                addMsParam( execMyRuleInp->inpParamArray, valPtr, STR_MS_T,
                            val, NULL );
            }
            else if ( *tmpPtr == '\\' ) {
                /* first '\'  is skipped.
                 If you need to use '\' in the first letter add an additional '\'
                 if you have to use '$' in the first letter add a '\'  before that
                 */
                tmpPtr++;
                char *param = quoteString( tmpPtr, _vm.count( "string" ) && ruleGen, 0 );
                if ( !ruleGen ) {
                    trimQuotes( param );
                }

                addMsParam( execMyRuleInp->inpParamArray, valPtr, STR_MS_T,
                            param, NULL );
            }
            else {
                char *param = quoteString( tmpPtr, _vm.count( "string" ) && ruleGen, 0 );
                if ( !ruleGen ) {
                    trimQuotes( param );
                }

                addMsParam( execMyRuleInp->inpParamArray, valPtr, STR_MS_T,
                            param, NULL );
            }
        }
        else {
            rodsLog( LOG_ERROR,
                     "parseMsInputParam: inpParam %s format error", valPtr );
            status = CAT_INVALID_ARGUMENT;
        }
    }

    return status;
}
Esempio n. 13
0
	configuration::configuration(const boost::program_options::variables_map& vars, logger::logger& log) : basic_configuration(vars, log), pimpl(std::make_unique<impl>())
	{
		if (vars.count("input"))
			set_input_filename(vars.at("input").as<std::string>());
	}
Esempio n. 14
0
void compile(boost::program_options::variables_map vm,
			 string out_file_name,
			 string routine_name,
			 map<string,type*>& inputs,
			 map<string,type*>& inouts,
			 map<string,type*>& outputs,
			 vector<stmt*> const& prog)
{
    // set up signal to end search after certain amount of time
    int sMinutes = vm["limit"].as<int>();
    if (sMinutes > 0) {
        int sSeconds = sMinutes * 60;
        signal(SIGALRM, sig_alarm_handler);
        alarm(sSeconds);
    }
    
	// search strategy
	enum search_strategy {exhaustive, orthogonal, random, 
		hybrid_orthogonal, ga, debug, thread};

	search_strategy strat = ga;
	if (vm["search"].as<std::string>().compare("ex") == 0) {
		strat = exhaustive;
	} 
    else if (vm["search"].as<std::string>().compare("debug") == 0) {
		strat = debug;
	}
	else if (vm["search"].as<std::string>().compare("orthogonal") == 0) {
		strat = orthogonal;
	}
	else if (vm["search"].as<std::string>().compare("random") == 0) {
		strat = random;
	}
	else if (vm["search"].as<std::string>().compare("hybrid_orthogonal") == 0) {
		strat = hybrid_orthogonal;
	}
	else if (vm["search"].as<std::string>().compare("ga") == 0) {
		strat = ga;
	}
    else if (vm["search"].as<std::string>().compare("thread") == 0) {
        strat = thread;
    }
	else {
		std::cout << "Error: unknown search strategy (--search):" << vm["search"].as<std::string>() << "\n\n";
		exit(0);
	}
	
	// which backend
	bool noptr;
	if (vm["backend"].as<std::string>().compare("noptr") == 0) {
		noptr = true;
	} else {
		noptr = false;
	}
	std::cout << noptr << std::endl;
	
	// partitiong FIXME can't turn off anymore?
	/*
	bool partitionSet = true;
	if (vm.count("partition_off")) {
		partitionSet = false;
	}
	*/

	bool mpi = false;
	if (vm.count("distributed")) {
		mpi = true;
	}
	
	string pathToTop = getcwd(NULL,0);	
	pathToTop += "/";
	// std::cout << pathToTop << std::endl;
	
	// set up temporary workspace
	string tmpPath, fileName, path;
	if (setUpWorkSpace(out_file_name, fileName, path, tmpPath, pathToTop,
                       vm.count("delete_tmp"))) {
		std::cout << "Failed to set up temporary directory for unique implementations\n";
		return;
	}
	
	// set all work to be performed in temporary work directory
	out_file_name = tmpPath + fileName;
	
	
	// {{{ COST MODELS
	std::list<versionData*> orderedVersions;
	string testParam = vm["test_param"].as<std::string>();
	string start, stop, step;
	
	string::size_type pos = testParam.find_first_of(":");
	if (pos != string::npos)
		start = testParam.substr(0, pos);
	string::size_type last = pos+1;
	pos = testParam.find_first_of(":",last);
	if (pos != string::npos)
		stop = testParam.substr(last, pos-last);
	step = testParam.substr(pos+1,string::npos);
	
	if (boost::lexical_cast<int>(start) > boost::lexical_cast<int>(stop)) {
		std::cout << "Test parameters are illegal (start > stop)\n";
		std::cout << "\tstart: " << start << "\n";
		std::cout << "\tstop:  " << stop << "\n";
		return;
	}
	
	modelMsg msg(boost::lexical_cast<int>(start),
				 boost::lexical_cast<int>(stop),
				 boost::lexical_cast<int>(step));
	msg.pathToTop = pathToTop;
	// build_machine 0 -> parallel, 1 -> serial
	// msg.parallelArch = build_machine((char*)(pathToTop.c_str()),0);
	if (msg.parallelArch == NULL) {
		std:: cout << "Error attempting to get cost with parallel analytic model\n";
		//return;
	}
	// msg.serialArch = build_machine((char*)(pathToTop.c_str()),1);
	// if (msg.serialArch == NULL) {
		// std:: cout << "Error attempting to get cost with parallel analytic model\n";
		//return;
	// }
	
	// analyticSerial, tempCount, analyticParallel, symbolic, noModel			
	vector<model_typ> models;
	models.clear();
	// the model we want to rank with should go first in this list
	//models.push_back(noModel);
	models.push_back(analyticParallel);
	//models.push_back(analyticSerial);
	//models.push_back(tempCount);
	// }}}
	
	
	precision_type = vm["precision"].as<std::string>();
	
#ifdef MODEL_TIME
	// time spent in memmodel routines
	boost::timer memmodelTimer;
	double memmodelTotal = 0.0;
#endif
	
	
	/* Model deprecated
	double threshold;
	if (vm.count("use_model")) {
		std::cout << "\nAnalytic model enabled\n";
		threshold = vm["threshold"].as<double>();
	}
	*/
	
	std::vector<std::pair<int, double> >::iterator itr;
    
	graph g;
	
	std::vector<algo> algos;
	//std::cerr << "finished parsing" << std::endl;
	program2graph(prog, inputs, inouts, outputs, g);  
	//std::cerr << "graph created" << std::endl;
    //std::ofstream out44("lower0.dot");
    //print_graph(out44, g);
	//out44.close();
	//use yices to compute types externally
//#define TYPES
#ifdef TYPES
    std::ofstream out("lower0.dot");
    print_graph(out, g); 
	out.close();
    generate_constraints(g);
#endif
	compute_types(g);
#ifdef TYPES
    std::ofstream out("lower1.dot");
    print_graph(out, g);
	out.close();
    exit(0);
#endif
    
	update_sizes(g);
	update_dim_info(g);
    
	init_algos(algos);
		
	assign_algorithms(algos, g);
	//std::cerr << "algorithms assigned" << std::endl;
	
	assign_work(algos, g);
	//std::cerr << "work assigned" << std::endl;
	
	rewrite_fun rewriters[] =
    {	flip_transpose,                 //0
		flip_transpose_stride,          //1
		merge_tmp_output,               //2
		merge_tmp_cast_output,          //3
		remove_intermediate_temporary,  //4
		merge_gets,                     //5
		merge_sumto_store,              //6
		move_temporary,                 //7
		remove_cast_to_output,          //8
		remove_input_to_cast,           //9
		remove_cast_to_cast,            //10
		merge_same_cast,                //11
        straighten_top_level_scalar_ops,//12
        reduce_reductions               //13
    };
	
	optim_fun optimizers[] =
    {	fuse_loops,			//0
		fuse_loops_nested,	//1
		merge_scalars,		//2
		pipeline,			//3
        fuse_loops_n        //4
    };

	optim_fun_chk checkers[] =
    {	check_fuse_loops, 
		check_fuse_loops_nested,
		check_merge_scalars,
		check_pipeline,
        check_fuse_loops_n
    };
	
	partition_fun partition[] = {
		part_mult_left_result,	//0
		part_mult_right_result,	//1
		part_mult_left_right, 	//2
		part_mult_scl_row,		//3
		part_mult_scl_col,		//4
		partition_add_col,		//5
		partition_add_row,		//6
		part_mult_scl,			//7
		partition_add			//8
	};
	rewrite_fun part_checkers[] = {
		check_part_mult_left_result,
		check_part_mult_right_result,
		check_part_mult_left_right,
		check_part_mult_scl_row,
		check_part_mult_scl_col,
		check_partition_add_col,
		check_partition_add_row,
		check_part_mult_scl,
		check_partition_add
	};
	
	vector<rewrite_fun> rewrites(rewriters, rewriters + 
								 sizeof(rewriters) / sizeof(rewrite_fun));
	
	vector<optim_fun> optimizations(optimizers, optimizers + 
									sizeof(optimizers) / sizeof(optim_fun));
	vector<optim_fun_chk> checks(checkers, checkers + 
								 sizeof(checkers) / sizeof(optim_fun_chk));
	vector<rewrite_fun> part_checks(part_checkers, part_checkers + 
									sizeof(part_checkers)/sizeof(rewrite_fun));
	vector<partition_fun> partitioners(partition, partition +
									 sizeof(partition) / sizeof(partition_fun));
	
	//std::cerr << "about to start lowering and optimizine" << std::endl;
	
	std::stack<work_item> s;
	string history = "";
	
#ifdef DUMP_DOT_FILES
  	std::ofstream out("lower1.dot");
	print_graph(out, g);
	out.close();
#endif
	
#ifdef DUMP_GRAPHS
	graphToQuery(g,out_file_name,0,0);
#endif
	
	if (vm.count("correctness")) {
		createCorrectnessTest(g, routine_name, out_file_name, inputs, 
                              outputs,msg,noptr);
	}
	
	// keep copy of base graph around
	graph *baseGraph = new graph(g);

	// {{{ Partition Space
	code_generation codetype = threadtile;
	string spec = vm["level1"].as<std::string>();
	if (!spec.empty()) {
		string::size_type pos = spec.find_first_of(" ");
		if (pos == string::npos) {
			std::cout << "Bad format for level1 arg:" << spec << endl;
			exit(0);
		} else {
			string codetype_str = spec.substr(0, pos);
			if (codetype_str == "thread") {
				codetype = threadtile;
			} else if (codetype_str == "cache") {
				codetype = cachetile;
			} else {
				std::cout << "Bad format for level1 arg:" << spec << endl;
				std::cout << "needs to be thread or cache" << endl;
				exit(0);
			}
		}
		int err = parse_range(&partition_bounds[0][0], 
				&partition_bounds[0][1],
				&partition_bounds[0][2],
				spec.substr(pos+1));
		if (err) {
			std::cout << "Couldn't parse range for level1: " << spec << endl;
			exit(0);
		}
		if (partition_bounds[0][0] > partition_bounds[0][1]) {
			std::cout << "Test parameters are illegal (start > stop)\n";
			std::cout << "\tstart: " << partition_bounds[0][0] << "\n";
			std::cout << "\tstop:  " << partition_bounds[0][1] << "\n";
			exit(0);
		}

		// Now level 2
		string spec = vm["level2"].as<std::string>();
		std::cout << "spec:" << spec << endl;
		if (!spec.empty()) {
			MAX_PARTS = 2;
			string::size_type pos = spec.find_first_of(" ");
			cout << "pos = " << pos << endl;
			if (pos == string::npos) {
				std::cout << "Bad format for level2 arg:" << spec << endl;
				exit(0);
			} else {
				string codetype_str = spec.substr(0, pos);
				cout << "codetype_str: '" << codetype_str << "'" << endl;
				if (codetype_str == "thread" && codetype==cachetile) {
					std::cout << "ERROR: threads inside tile loops not supported" << endl;
					std::cout << "consider swapping level1 and level2 args" << endl;
					exit(0);
				} else if (codetype_str == "cache" && codetype==threadtile) {
					codetype = bothtile;
				} else {
					std::cout << "Bad format for level2 arg:" << spec << endl;
					std::cout << "needs to be thread or cache" << endl;
					exit(0);
				}
			}
			int err = parse_range(&partition_bounds[1][0], 
					&partition_bounds[1][1],
					&partition_bounds[1][2],
					spec.substr(pos+1));
			if (err) {
				std::cout << "Couldn't parse range for level2: " << spec.substr(pos) << endl;
				exit(0);
			}
			if (partition_bounds[1][0] > partition_bounds[1][1]) {
				std::cout << "Test parameters are illegal (start > stop)\n";
				std::cout << "\tstart: " << partition_bounds[1][0] << "\n";
				std::cout << "\tstop:  " << partition_bounds[1][1] << "\n";
				exit(0);
			}
		} else {
			// Only 1 level specified
			MAX_PARTS = 1;
		}
	} else {
		// no idea what this will do!
		// Maybe we should just throw an error here?  Or at least a warning?
		std::cout << "WARNING: No threading or cache tiling specified" << endl;
		std::cout << "Performing Loop fusion only, search may get confused" << endl;
		MAX_PARTS = 0;
	}

	// }}}

	// initializing the partition type forest
	// cout << "initializing partition forest..." << endl;
	vector< partitionTree_t* > partitionForest;
    buildForest(partitionForest, g, MAX_PARTS);
	// cout << "success" << endl;

	/*
	for (int i = 0; i < partitionForest.size(); ++i) {
		partitionTree_t *t = partitionForest[i];
		if (t != NULL) {
			stringstream o;
			o << "tree" << i << ".dot";
			ofstream treefile(o.str().c_str());
			printTree(treefile, t);
		}
	}
	*/

	initial_lower(g, algos, rewrites);
	//std::cout << "finished lowering and rewriting" << std::endl;
	
#ifdef DUMP_DOT_FILES
  	std::ofstream out2("lower2.dot");
	print_graph(out2, g);
	out2.close();
#endif
	
#if 0
    for (int i = 0; i < g.num_vertices(); ++i)
        if (g.info(i).op & OP_ANY_ARITHMATIC)
            cout << i << "\t";
    cout << "\n";
#endif
    
	int reps = vm["empirical_reps"].as<int>();
	if (vm.count("distributed")) {
		createMPIEmpiricalTest(g, routine_name, out_file_name, inputs,
                               outputs, noptr, reps);
	} else if (!vm.count("empirical_off")) {
		createEmpiricalTest(g, routine_name, out_file_name, inputs,
                            outputs, noptr, reps);
	}
	
    compile_details_t cDetails(routine_name,tmpPath,fileName,
                               vm.count("correctness"), 
                               vm.count("use_model"),
                               !vm.count("empirical_off"),
                               noptr, mpi, codetype,
                               &inputs, &inouts, &outputs);
    
    build_details_t bDetails(&part_checks, &partitioners,
                             &checks, &optimizations,
                             &algos, &rewrites,
                             &models, &msg);

	// int maxT = max(0,msg.parallelArch->threads);
	// std::cout << "Testing with " << maxT << " threads, step = " << min(4,maxT) << std::endl;
	// int stride = 2;
    
	// {{{ Strategy cases
	switch (strat) {
		case exhaustive:
		{
			std::cout << "entering exhaustive search" << endl;
			//int numVersions = 5;
			int bestVersion = smart_exhaustive(g, *baseGraph, 
                                               cDetails, bDetails);
			// One way or another we have selected a version we are calling the best
			// or we failed
			if (bestVersion < 0) {
				std::cout << "All versions failed to generate or compile\n";
				return;
			}
			else {
				std::cout << "\n----------------------------------\n";
				std::cout << "Best Version: " << fileName + "__" << bestVersion << ".c\n";
			}
			
			// copy best version to same directory as input .m file
			// and report location
			handleBestVersion(fileName,path,tmpPath,bestVersion);
			break;
		}
		case orthogonal:
		{
			std::cout << "entering orthogonal search" << endl;
			//int numVersions = 5;
			int bestVersion = orthogonal_search(g, *baseGraph, 
                                                cDetails, bDetails);
			// One way or another we have selected a version we are calling the best
            
			// or we failed
			if (bestVersion < 0) {
				std::cout << "All versions failed to generate or compile\n";
				return;
			}
			else {
				std::cout << "\n----------------------------------\n";
				std::cout << "Best Version: " << fileName + "__" << bestVersion << ".c\n";
			}
			
			// copy best version to same directory as input .m file
			// and report location
			handleBestVersion(fileName,path,tmpPath,bestVersion);
			break;
		}
		case random:
		{
			std::cout << "entering random search" << endl;
			int seconds = vm["random_count"].as<int>();
			int bestVersion = genetic_algorithm_search(g, *baseGraph,
				partitionForest, 
				seconds, 1, false, cDetails, bDetails).best_version; // pop = 1
			// One way or another we have selected a version we are calling the best
			// or we failed
			if (bestVersion < 0) {
				std::cout << "All versions failed to generate or compile\n";
				return;
			}
			else {
				std::cout << "\n----------------------------------\n";
				std::cout << "Best Version: " << fileName + "__" << bestVersion << ".c\n";
			}
			
			// copy best version to same directory as input .m file
			// and report location
			handleBestVersion(fileName,path,tmpPath,bestVersion);
			break;
		}
		case hybrid_orthogonal:
		{
			std::cout << "entering hybrid orthogonal search " << endl;
			int bestVersion = smart_hybrid_search(g, *baseGraph, 
                                                  cDetails, bDetails);
			// One way or another we have selected a version we are calling the best
			// or we failed
			if (bestVersion < 0) {
				std::cout << "All versions failed to generate or compile\n";
				return;
			}
			else {
				std::cout << "\n----------------------------------\n";
				std::cout << "Best Version: " << fileName + "__" << bestVersion << ".c\n";
			}
			
			// copy best version to same directory as input .m file
			// and report location
			handleBestVersion(fileName,path,tmpPath,bestVersion);
			break;
		}
		case debug:
		{
			std::cout << "entering debug search " << endl;
			int bestVersion = debug_search(g, *baseGraph, partitionForest,
											cDetails, bDetails);
			// One way or another we have selected a version we are calling the best
			// or we failed
			if (bestVersion < 0) {
				std::cout << "All versions failed to generate or compile\n";
				return;
			}
			else {
				std::cout << "\n----------------------------------\n";
				std::cout << "Best Version: " << fileName + "__" << bestVersion << ".c\n";
			}
			
			// copy best version to same directory as input .m file
			// and report location
			handleBestVersion(fileName,path,tmpPath,bestVersion);
			break;
		}
		case ga:
		{
			std::cout << "entering genetic algorithm search " << endl;
			bool gamaxfuse = true;
			if (vm.count("ga_nomaxfuse")) {
				gamaxfuse = false;
			}
			int seconds = vm["ga_timelimit"].as<int>();
			int popsize = vm["ga_popsize"].as<int>();
			int bestVersion = -1;
			if (vm.count("ga_noglobalthread")) {
				bestVersion = genetic_algorithm_search(g, *baseGraph,
					partitionForest, seconds, popsize, gamaxfuse, 
					cDetails, bDetails).best_version;
			} else if (vm.count("ga_exthread")) {
				bestVersion = ga_exthread(g, *baseGraph,
						 partitionForest, seconds, gamaxfuse, popsize, cDetails,
						 bDetails);
			} else { // global thread
				bestVersion = ga_thread(g, *baseGraph,
						 partitionForest, seconds, gamaxfuse, popsize, cDetails,
						 bDetails);
			}
			// One way or another we have selected 
			// a version we are calling the best
			// or we failed
			if (bestVersion < 0) {
				std::cout << "All versions failed to generate or compile\n";
				return;
			}
			else {
				std::cout << "\n----------------------------------\n";
				std::cout << "Best Version: " << fileName + "__" << bestVersion << ".c\n";
			}
			
			// copy best version to same directory as input .m file
			// and report location
			handleBestVersion(fileName,path,tmpPath,bestVersion);
			break;
		}
            
        case thread:
		{
            int thread_search(graph &g, graph &baseGraph, 
                              vector<partitionTree_t*> part_forest,
                              compile_details_t &cDet,
                              build_details_t &bDet);
			std::cout << "entering thread search " << endl;
			thread_search(g, *baseGraph, partitionForest,
                                           cDetails, bDetails);

			break;
		}
	}
	// }}}
    
    deleteForest(partitionForest);
}
Esempio n. 15
0
File: CMT.cpp Progetto: yzliang/vcmi
int main(int argc, char** argv)
#endif
{
#ifdef __APPLE__
	// Correct working dir executable folder (not bundle folder) so we can use executable relative pathes
    std::string executablePath = argv[0];
    std::string workDir = executablePath.substr(0, executablePath.rfind('/'));
    chdir(workDir.c_str());
    
    // Check for updates
    OSX_checkForUpdates();

    // Check that game data is prepared. Otherwise run vcmibuilder helper application
    FILE* check = fopen((VCMIDirs::get().localPath() + "/game_data_prepared").c_str(), "r");
    if (check == nullptr) {
        system("open ./vcmibuilder.app");
        return 0;
    }
    fclose(check);
#endif
    std::cout << "Starting... " << std::endl;
	po::options_description opts("Allowed options");
	opts.add_options()
		("help,h", "display help and exit")
		("version,v", "display version information and exit")
		("battle,b", po::value<std::string>(), "runs game in duel mode (battle-only")
		("start", po::value<std::string>(), "starts game from saved StartInfo file")
		("onlyAI", "runs without human player, all players will be default AI")
		("noGUI", "runs without GUI, implies --onlyAI")
		("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
		("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
		("autoSkip", "automatically skip turns in GUI")
		("disable-video", "disable video player")
		("nointro,i", "skips intro movies");

	if(argc > 1)
	{
		try
		{
			po::store(po::parse_command_line(argc, argv, opts), vm);
		}
		catch(std::exception &e) 
		{
            std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
		}
	}

	po::notify(vm);
	if(vm.count("help"))
	{
		prog_help(opts);
		return 0;
	}
	if(vm.count("version"))
	{
		prog_version();
		return 0;
	}
	if(vm.count("noGUI"))
	{
		gNoGUI = true;
		vm.insert(std::pair<std::string, po::variable_value>("onlyAI", po::variable_value()));
	}

	//Set environment vars to make window centered. Sometimes work, sometimes not. :/
	putenv((char*)"SDL_VIDEO_WINDOW_POS");
	putenv((char*)"SDL_VIDEO_CENTERED=1");

	// Have effect on X11 system only (Linux).
	// For whatever reason in fullscreen mode SDL takes "raw" mouse input from DGA X11 extension
	// (DGA = Direct graphics access). Because this is raw input (before any speed\acceleration proceesing)
	// it may result in very small \ very fast mouse when game in fullscreen mode
	putenv((char*)"SDL_VIDEO_X11_DGAMOUSE=0");

    // Init old logging system and new (temporary) logging system
	CStopWatch total, pomtime;
	std::cout.flags(std::ios::unitbuf);
	console = new CConsoleHandler;
	*console->cb = boost::bind(&processCommand, _1);
	console->start();
	atexit(dispose);

	CBasicLogConfigurator logConfig(VCMIDirs::get().userCachePath() + "/VCMI_Client_log.txt", console);
    logConfig.configureDefault();
	logGlobal->infoStream() <<"Creating console "<<pomtime.getDiff();

    // Init filesystem and settings
	preinitDLL(::console);
    settings.init();

    // Initialize logging based on settings
    logConfig.configure();

	// Some basic data validation to produce better error messages in cases of incorrect install
	auto testFile = [](std::string filename, std::string message) -> bool
	{
		if (CResourceHandler::get()->existsResource(ResourceID(filename)))
			return true;

        logGlobal->errorStream() << "Error: " << message << " was not found!";
		return false;
	};

	if (!testFile("DATA/HELP.TXT", "Heroes III data") &&
	    !testFile("MODS/VCMI/MOD.JSON", "VCMI mod") &&
	    !testFile("DATA/StackQueueBgBig.PCX", "VCMI data"))
		exit(1); // These are unrecoverable errors

	// these two are optional + some installs have them on CD and not in data directory
	testFile("VIDEO/GOOD1A.SMK", "campaign movies");
	testFile("SOUNDS/G1A.WAV", "campaign music"); //technically not a music but voiced intro sounds

	conf.init();
    logGlobal->infoStream() <<"Loading settings: "<<pomtime.getDiff();
    logGlobal->infoStream() << NAME;

	srand ( time(nullptr) );
	

	const JsonNode& video = settings["video"];
	const JsonNode& res = video["screenRes"];

	//something is really wrong...
	if (res["width"].Float() < 100 || res["height"].Float() < 100)
	{
        logGlobal->errorStream() << "Fatal error: failed to load settings!";
        logGlobal->errorStream() << "Possible reasons:";
        logGlobal->errorStream() << "\tCorrupted local configuration file at " << VCMIDirs::get().userConfigPath() << "/settings.json";
        logGlobal->errorStream() << "\tMissing or corrupted global configuration file at " << VCMIDirs::get().userConfigPath() << "/schemas/settings.json";
        logGlobal->errorStream() << "VCMI will now exit...";
		exit(EXIT_FAILURE);
	}

	if(!gNoGUI)
	{
		if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO))
		{
			logGlobal->errorStream()<<"Something was wrong: "<< SDL_GetError();
			exit(-1);
		}
		atexit(SDL_Quit);
		setScreenRes(res["width"].Float(), res["height"].Float(), video["bitsPerPixel"].Float(), video["fullscreen"].Bool());
		logGlobal->infoStream() <<"\tInitializing screen: "<<pomtime.getDiff();
	}


	CCS = new CClientState;
	CGI = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler etc.)
	// Initialize video
#if DISABLE_VIDEO
	CCS->videoh = new CEmptyVideoPlayer;
#else
	if (!gNoGUI && !vm.count("disable-video"))
		CCS->videoh = new CVideoPlayer;
	else
		CCS->videoh = new CEmptyVideoPlayer;
#endif

    logGlobal->infoStream()<<"\tInitializing video: "<<pomtime.getDiff();



	//we can properly play intro only in the main thread, so we have to move loading to the separate thread
	boost::thread loading(init);

	if(!gNoGUI )
	{
		if(!vm.count("battle") && !vm.count("nointro"))
			playIntro();
		SDL_FillRect(screen,nullptr,0);
	}

	CSDL_Ext::update(screen);
	loading.join();
    logGlobal->infoStream()<<"Initialization of VCMI (together): "<<total.getDiff();

	if(!vm.count("battle"))
	{
		Settings session = settings.write["session"];
		session["autoSkip"].Bool()  = vm.count("autoSkip");
		session["oneGoodAI"].Bool() = vm.count("oneGoodAI");

		std::string fileToStartFrom; //none by default
		if(vm.count("start"))
			fileToStartFrom = vm["start"].as<std::string>();

		if(fileToStartFrom.size() && boost::filesystem::exists(fileToStartFrom))
			startGameFromFile(fileToStartFrom); //ommit pregame and start the game using settings from fiel
		else
		{
			if(fileToStartFrom.size())
			{
                logGlobal->warnStream() << "Warning: cannot find given file to start from (" << fileToStartFrom
                    << "). Falling back to main menu.";
			}
			GH.curInt = CGPreGame::create(); //will set CGP pointer to itself
		}
	}
	else
	{
		auto  si = new StartInfo();
		si->mode = StartInfo::DUEL;
		si->mapname = vm["battle"].as<std::string>();
		si->playerInfos[PlayerColor(0)].color = PlayerColor(0);
		si->playerInfos[PlayerColor(1)].color = PlayerColor(1);
		startGame(si);
	}

	if(!gNoGUI)
	{
		mainGUIThread = new boost::thread(&CGuiHandler::run, &GH);
		listenForEvents();
	}
	else
	{
		while(true)
			boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
	}

	return 0;
}
Esempio n. 16
0
bool
Config::applyOptions(
    const po::variables_map& vm,
    bool stopOnError)
{
    bool rc;
    ArgMultiplier v;

    rc = true;

    if (vm.count("function")) {
        if (!setFunction(vm["function"].as<std::string>())) {
            std::cerr << "Invalid function name: " <<
                vm["function"].as<std::string>() << std::endl;
            return false;
        }
    }

    if (vm.count("cpp")) {
        setCpp(vm["cpp"].as<std::string>());
    }
    if (vm.count("cl")) {
        setCl(vm["cl"].as<std::string>());
    }
    if (vm.count("data")) {
        if (!setDataPattern(vm["data"].as<std::string>())) {
            std::cerr << "Invalid data pattern name" << std::endl;
            rc = false;
            if (stopOnError) {
                return false;
            }
        }
    }
    if (vm.count("skip-accuracy")) {
        setSkipAccuracy();
    }

    if (vm.count("platform")) {
        if (!setPlatform(vm["platform"].as<std::string>())) {
            std::cerr << "Invalid platform name" << std::endl;
            rc = false;
            if (stopOnError) {
                return false;
            }
        }
    }
    if (vm.count("device")) {
        if (!setDevice(vm["device"].as<std::string>())) {
            std::cerr << "Invalid device name" << std::endl;
            rc = false;
            if (stopOnError) {
                return false;
            }
        }
    }
    if (vm.count("build-options")) {
        setBuildOptions(vm["build-options"].as<std::string>());
    }

    if (vm.count("order")) {
        setOrder(vm["order"].as<clblasOrder>());
    }
    if (vm.count("side")) {
        setSide(vm["side"].as<clblasSide>());
    }
    if (vm.count("uplo")) {
        setUplo(vm["uplo"].as<clblasUplo>());
    }
    if (vm.count("transA")) {
        setTransA(vm["transA"].as<clblasTranspose>());
    }
    if (vm.count("transB")) {
        setTransB(vm["transB"].as<clblasTranspose>());
    }
    if (vm.count("diag")) {
        setDiag(vm["diag"].as<clblasDiag>());
    }
    if (vm.count("M")) {
        setM(vm["M"].as<size_t>());
    }
    if (vm.count("N")) {
        setN(vm["N"].as<size_t>());
    }
    if (vm.count("K")) {
        setK(vm["K"].as<size_t>());
    }
    if (vm.count("alpha")) {
        if (!parseArgMultiplier(vm["alpha"].as<std::string>(), v)) {
            std::cerr << "in option 'alpha': invalid option value" << std::endl;
            rc = false;
            if (stopOnError) {
                return false;
            }
        }
        setAlpha(v);
    }
    if (vm.count("beta")) {
        if (!parseArgMultiplier(vm["beta"].as<std::string>(), v)) {
            std::cerr << "in option 'beta': invalid option value" << std::endl;
            rc = false;
            if (stopOnError) {
                return false;
            }
        }
        setBeta(v);
    }
    if (vm.count("lda")) {
        setLDA(vm["lda"].as<size_t>());
    }
    if (vm.count("ldb")) {
        setLDB(vm["ldb"].as<size_t>());
    }
    if (vm.count("ldc")) {
        setLDC(vm["ldc"].as<size_t>());
    }
    if (vm.count("offA")) {
        setOffA(vm["offA"].as<size_t>());
    }
    if (vm.count("offBX")) {
        setOffBX(vm["offBX"].as<size_t>());
    }
    if (vm.count("offCY")) {
        setOffCY(vm["offCY"].as<size_t>());
    }
    if (vm.count("incx")) {
        setIncX(vm["incx"].as<int>());
    }
    if (vm.count("incy")) {
        setIncY(vm["incy"].as<int>());
    }

    if (vm.count("decomposition")) {
        if (!parseDecompositionOpt(vm["decomposition"].as<std::string>())) {
            std::cerr << "in option 'decomposition': invalid option value" << std::endl;
            rc = false;
            if (stopOnError) {
                return false;
            }
        }
    }

    if (vm.count("multikernel")) {
        setMultiKernel(vm["multikernel"].as<bool>());
    }

    return rc;
}
Esempio n. 17
0
INT parseArguments(INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo) 
{
	WCHAR namePath[MAX_PATH];
	GetModuleFileName(NULL, namePath, MAX_PATH);
	WCHAR *progName = PathFindFileName(namePath);

	po::options_description desc;

	desc.add_options()
		("help,h", "Print help message and exit")
		("version,V", "Print version and exit")
		("debug,d", "Verbose/Debug output")
		("service,s", po::wvalue<std::wstring>(), "Service to check (required)")
		("warn,w", "Return warning (1) instead of critical (2),\n when service is not running")
		;

	po::basic_command_line_parser<WCHAR> parser(ac, av);

	try {
		po::store(
			parser
			.options(desc)
			.style(
			po::command_line_style::unix_style |
			po::command_line_style::allow_long_disguise)
			.run(),
			vm);
		vm.notify();
	} catch (std::exception& e) {
		std::cout << e.what() << '\n' << desc << '\n';
		return 3;
	}

	if (vm.count("help")) {
		std::wcout << progName << " Help\n\tVersion: " << VERSION << '\n';
		wprintf(
			L"%s is a simple program to check the status of a service.\n"
			L"You can use the following options to define its behaviour:\n\n", progName);
		std::cout << desc;
		wprintf(
			L"\nIt will then output a string looking something like this:\n\n"
			L"\tSERVICE CRITICAL NOT_RUNNING | service=4;!4;!4;1;7\n\n"
			L"\"SERVICE\" being the type of the check, \"CRITICAL\" the returned status\n"
			L"and \"1\" is the returned value.\n"
			L"A service is either running (Code 0x04) or not running (any other).\n"
			L"For more information consult the msdn on service state transitions.\n\n"
			L"%s' exit codes denote the following:\n"
			L" 0\tOK,\n\tNo Thresholds were broken or the programs check part was not executed\n"
			L" 1\tWARNING,\n\tThe warning, but not the critical threshold was broken\n"
			L" 2\tCRITICAL,\n\tThe critical threshold was broken\n"
			L" 3\tUNKNOWN, \n\tThe program experienced an internal or input error\n\n"
			L"%s' thresholds work differently, since a service is either running or not\n"
			L"all \"-w\" and \"-c\" do is say whether a not running service is a warning\n"
			L"or critical state respectively.\n\n"
			, progName, progName);
		std::cout << '\n';
		return 0;
	}

	 if (vm.count("version")) {
		std::cout << "Version: " << VERSION << '\n';
		return 0;
	} 

	if (!vm.count("service")) {
		std::cout << "Missing argument: service" << '\n' << desc << '\n';
		return 3;
	}

	if (vm.count("warn"))
		printInfo.warn = true;
	
	printInfo.service = vm["service"].as<std::wstring>();

	if (vm.count("debug"))
		debug = TRUE;
	
	return -1;
}
Esempio n. 18
0
	void Edit(const po::variables_map& variables, int& retcode)
	{
		retcode = 1;
		if (!variables.count("input"))
		{
			std::wcerr << L"Error parsing options: must have some input files.\n";
			return;
		}

		auto inputs = variables["input"].as<std::vector<std::wstring>>();
		bool noResourceRebuild = variables["no-resource-rebuild"].as<bool>();

		retcode = 0;
		for (auto& input : inputs)
		{
			StripSignature(input, retcode);

			if (!noResourceRebuild)
			{
				HANDLE binaryHandle = NULL;
				{
					PEParser pe(input);
					pe.Open();
					if (!pe.IsValidPE())
					{
						std::wcerr << L"Can't open file for reading or invalid format." << std::endl;
						continue;
					}

					std::vector<std::shared_ptr<BYTE>> data;

					binaryHandle = BeginUpdateResource(input.c_str(), FALSE);
					if (!binaryHandle)
					{
						std::wcerr << L"Can't lock file for updating resources." << std::endl;
						continue;
					}

					ResourceEntryPtr node;
					if (pe.ResourceDirectory())
						node = pe.ResourceDirectory()->AtPath(L"16/1");

					if (!node) 
						continue;

					bool success = true;
					if (node->IsData())
						data.push_back(ProcessNode(binaryHandle, node, variables));
					else
						for (auto& entry : node->Entries())
							data.push_back(ProcessNode(binaryHandle, entry.second, variables));
				}

				if (!EndUpdateResource(binaryHandle, false))
				{
					std::wcerr << L"Failed to update resources" << std::endl;
					retcode = 1;
				}
			}
			else
			{
				PEParser pe(input);
				pe.Open(true);
				if (!pe.IsValidPE())
				{
					std::wcerr << L"Can't open file for reading or invalid format." << std::endl;
					continue;
				}

				VersionString version;
				PEParser::VersionField versionField = PEParser::Both;

				if (variables.count("set-version"))
				{
					version = variables["set-version"].as<std::wstring>();
					versionField = PEParser::Both;
				}
				else if (variables.count("set-file-version"))
				{
					version = variables["set-file-version"].as<std::wstring>();
					versionField = PEParser::FileOnly;
				}
				else if (variables.count("set-product-version"))
				{
					version = variables["set-product-version"].as<std::wstring>();
					versionField = PEParser::ProductOnly;
				}

				if (!pe.SetVersion(version, versionField))
					retcode = 1;

				pe.Close();
			}
		}
	}
Esempio n. 19
0
BOOL ParseArguments(CONST INT ac, WCHAR **av, po::variables_map& vm, printInfoStruct& printInfo)
{
	WCHAR szNamePath[MAX_PATH + 1];
	GetModuleFileName(NULL, szNamePath, MAX_PATH);
	WCHAR *szProgName = PathFindFileName(szNamePath);

	po::options_description desc("Options");
	desc.add_options()
		("help,h", "Print help page and exit")
		("version,V", "Print version and exit")
		("warning,w", po::wvalue<std::wstring>(), "Warning thershold")
		("critical,c", po::wvalue<std::wstring>(), "Critical threshold")
		("performance-counter,P", po::wvalue<std::wstring>(), "The performance counter string to use")
		("performance-wait", po::value<DWORD>(), "Sleep in milliseconds between the two perfomance querries (Default: 1000ms)")
		("fmt-countertype", po::wvalue<std::wstring>(), "Value type of counter: 'double'(default), 'long', 'int64'")
		("print-objects", "Prints all available objects to console")
		("print-object-info", "Prints all available instances and counters of --performance-counter, do not use a full perfomance counter string here")
		;

	po::basic_command_line_parser<wchar_t> parser(ac, av);

	try {
		po::store(
			parser
			.options(desc)
			.style(
			po::command_line_style::unix_style |
			po::command_line_style::allow_long_disguise)
			.run(),
			vm);
		vm.notify();
	} catch (std::exception& e) {
		std::cout << e.what() << '\n' << desc << '\n';
		return FALSE;
	}

	if (vm.count("version")) {
		std::wcout << "Version: " << VERSION << '\n';
		return FALSE;
	}

	if (vm.count("help")) {
		std::wcout << szProgName << " Help\n\tVersion: " << VERSION << '\n';
		wprintf(
			L"%s runs a check against a performance counter.\n"
			L"You can use the following options to define its behaviour:\n\n", szProgName);
		std::cout << desc;
		wprintf(
			L"\nIt will then output a string looking something like this:\n\n"
			L"\tPERFMON CRITICAL \"\\Processor(_Total)\\%% Idle Time\" = 40.34 | "
			L"perfmon=40.34;20;40;; \"\\Processor(_Total)\\%% Idle Time\"=40.34\n\n"
			L"\"tPERFMON\" being the type of the check, \"CRITICAL\" the returned status\n"
			L"and \"40.34\" is the performance counters value.\n"
			L"%s' exit codes denote the following:\n"
			L" 0\tOK,\n\tNo Thresholds were exceeded\n"
			L" 1\tWARNING,\n\tThe warning was broken, but not the critical threshold\n"
			L" 2\tCRITICAL,\n\tThe critical threshold was broken\n"
			L" 3\tUNKNOWN, \n\tNo check could be performed\n\n"
			, szProgName);
		return 0;
	}

	if (vm.count("warning")) {
		try {
			printInfo.tWarn = threshold(vm["warning"].as<std::wstring>());
		} catch (std::invalid_argument& e) {
			std::wcout << e.what() << '\n';
			return FALSE;
		}
	}

	if (vm.count("critical")) {
		try {
			printInfo.tCrit = threshold(vm["critical"].as<std::wstring>());
		} catch (std::invalid_argument& e) {
			std::wcout << e.what() << '\n';
			return FALSE;
		}
	}

	if (vm.count("fmt-countertype")) {
		if (!vm["fmt-countertype"].as<std::wstring>().compare(L"int64"))
			printInfo.dwRequestedType = PDH_FMT_LARGE;
		else if (!vm["fmt-countertype"].as<std::wstring>().compare(L"long"))
			printInfo.dwRequestedType = PDH_FMT_LONG;
		else if (vm["fmt-countertype"].as<std::wstring>().compare(L"double")) {
			std::wcout << "Unknown value type " << vm["fmt-countertype"].as<std::wstring>() << '\n';
			return FALSE;
		}
	}

	if (vm.count("performance-counter"))
		printInfo.wsFullPath = vm["performance-counter"].as<std::wstring>();

	if (vm.count("performance-wait"))
		printInfo.dwPerformanceWait = vm["performance-wait"].as<DWORD>();

	return TRUE;
}
Esempio n. 20
0
int guiMain(const po::variables_map& options) {

    { // by default on Windows the selection is hard to see in the main window, because it's some gray;
        QPalette pal (QApplication::palette());
        pal.setColor(QPalette::Highlight, pal.color(QPalette::Active, QPalette::Highlight));
        pal.setColor(QPalette::HighlightedText, pal.color(QPalette::Active, QPalette::HighlightedText));
        QApplication::setPalette(pal);
    }

    getDefaultFont(); // !!! to initialize the static var

    string strStartSession;
    string strLastSession;

    int nSessCnt;
    bool bOpenLast;
    string strTempSessTempl;
    string strDirSessTempl;
    //bool bIsTempSess (false);
    string strTempSession (getSepTerminatedDir(convStr(QDir::tempPath())) + TEMP_SESS + SessionEditorDlgImpl::SESS_EXT);
    string strFolderSess;
    bool bHideFolderSess (true);

    if (options.count(s_hiddenFolderSessOpt.m_szLongOpt) > 0)
    {
        strFolderSess = options[s_hiddenFolderSessOpt.m_szLongOpt].as<string>();
    }
    else if (options.count(s_loadedFolderSessOpt.m_szLongOpt) > 0)
    {
        strFolderSess = options[s_loadedFolderSessOpt.m_szLongOpt].as<string>();
        bHideFolderSess = false;
    }

    SessEraser sessEraser;

    strLastSession = getActiveSession(options, nSessCnt, bOpenLast, strTempSessTempl, strDirSessTempl);

    if (options.count(s_tempSessOpt.m_szLongOpt) > 0)
    {
        SessEraser::eraseTempSess();

        strStartSession = strTempSession;

        if (strTempSessTempl.empty())
        {
            strTempSessTempl = strLastSession;
        }

        if (!strTempSessTempl.empty())
        {
            try
            {
                copyFile2(strTempSessTempl, strStartSession);
            }
            catch (...)
            { // nothing //ttt2 do more
            }
        }

        string strProcDir (options[s_tempSessOpt.m_szLongOpt].as<string>());
        strProcDir = getNonSepTerminatedDir(convStr(QDir(fromNativeSeparators(convStr(strProcDir))).absolutePath()));
        setFolder(strStartSession, strProcDir);
        bOpenLast = true;
    }
    else if (!strFolderSess.empty())
    {
        string strProcDir = getNonSepTerminatedDir(convStr(QDir(fromNativeSeparators(convStr(strFolderSess))).absolutePath())); //ttt2 test on root

        if (!dirExists(strProcDir))
        {
            showMessage(0, QMessageBox::Critical, 0, 0, MainFormDlgImpl::tr("Error"), MainFormDlgImpl::tr("Folder \"%1\" doesn't exist. The program will exit ...").arg(convStr(strProcDir)), MainFormDlgImpl::tr("O&K"));
            return 1;
        }

        string strDirName (convStr(QFileInfo(convStr(strProcDir)).fileName()));
        if (strDirName.empty()) // it's a whole disk drive on Windows, e.g. D:\\  ;
        {
            strDirName += strProcDir[0];
            strDirName += "-MP3Diags";
        }
        strStartSession = getSepTerminatedDir(strProcDir) + strDirName + SessionEditorDlgImpl::SESS_EXT;
        if (bHideFolderSess)
        {
            sessEraser.m_strSessionToHide = strStartSession;
        }

        if (!fileExists(strStartSession))
        {
            if (strDirSessTempl.empty())
            {
                strDirSessTempl = strLastSession;
            }

            if (!strDirSessTempl.empty())
            {
                try
                {
                    copyFile2(strDirSessTempl, strStartSession);
                    setFolder(strStartSession, strProcDir);
                }
                catch (...)
                { // nothing //ttt2 do more
                }
            }
        }

        ofstream out (strStartSession.c_str(), ios_base::app);
        if (!out)
        {
            showMessage(0, QMessageBox::Critical, 0, 0, MainFormDlgImpl::tr("Error"), MainFormDlgImpl::tr("Cannot write to file \"%1\". The program will exit ...").arg(convStr(strStartSession)), MainFormDlgImpl::tr("O&K"));
            return 1;
        }
        bOpenLast = true;
    }
    else if (0 == nSessCnt)
    { // first run; create a new session and run it
        SessionEditorDlgImpl dlg (0, "", SessionEditorDlgImpl::FIRST_TIME, ""); // ttt0 detect system locale
        dlg.setWindowIcon(QIcon(":/images/logo.svg"));
        strStartSession = dlg.run();
        if (strStartSession.empty())
        {
            return 0;
        }

        if ("*" == strStartSession)
        {
            strStartSession.clear();
        }
        else
        {
            vector<string> vstrSess;
            //vstrSess.push_back(strStartSession);
            GlobalSettings st;
            st.saveSessions(vstrSess, strStartSession, dlg.shouldOpenLastSession(), "", "", dlg.getTranslation(), GlobalSettings::LOAD_EXTERNAL_CHANGES);
        }
        bOpenLast = true;
    }
    else
    {
        strStartSession = strLastSession;
    }

    bool bOpenSelDlg (strStartSession.empty() || !bOpenLast);

    try
    {
        for (;;)
        {
            {
                QFont fnt;
                string strNewFont (convStr(fnt.family()));
                int nNewSize (fnt.pointSize());
                fixAppFont(fnt, strNewFont, nNewSize);
            }

            if (bOpenSelDlg)
            {
                SessionsDlgImpl dlg (0);
                dlg.setWindowIcon(QIcon(":/images/logo.svg"));

                strStartSession = dlg.run();
                if (strStartSession.empty())
                {
                    return 0;
                }
            }
            bOpenSelDlg = true;

            CB_ASSERT (!strStartSession.empty());

            bool bDefaultForVisibleSessBtn (true);
            //if (strStartSession != strTempSession)
            {
                vector<string> vstrSess;
                bool bOpenLast;
                string s, s1, s2, s3;
                GlobalSettings st;
                st.loadSessions(vstrSess, s, bOpenLast, s1, s2, s3);
                st.saveSessions(vstrSess, strStartSession, bOpenLast, s1, s2, s3, GlobalSettings::LOAD_EXTERNAL_CHANGES);
                bDefaultForVisibleSessBtn = (cSize(vstrSess) != 1 || !strFolderSess.empty() || vstrSess.end() != find(vstrSess.begin(), vstrSess.end(), strTempSession));
            }

            { //ttt2 overkill - create a "CommonData" just to read the language setting
                SessionSettings settings (strStartSession);
                CommonData commonData(settings, 0, 0, 0, 0, 0, 0, 0, 0, 0, false);
                settings.loadMiscConfigSettings(&commonData, SessionSettings::DONT_INIT_GUI);
                TranslatorHandler::getGlobalTranslator().setTranslation(commonData.m_strTranslation); // !!! must be done here, before the MainFormDlgImpl constructor
            }

            MainFormDlgImpl mainDlg (strStartSession, bDefaultForVisibleSessBtn);
            mainDlg.setWindowIcon(QIcon(":/images/logo.svg"));

            if (bDefaultForVisibleSessBtn)
            {
                mainDlg.setWindowTitle(QString(getAppName()) + " - " + convStr(SessionEditorDlgImpl::getTitleName(strStartSession)));
            }
            else
            {
                mainDlg.setWindowTitle(QString(getAppName()));
            }

            if (MainFormDlgImpl::OPEN_SESS_DLG != mainDlg.run())
            {
                return 0;
            }
        }
    }
    catch (const exception& ex)
    {
        CB_ASSERT1 (false, ex.what());
    }
    catch (...) // ttt2 for now it doesn't catch many exceptions; it seems that nothing can be done if an exception leaves a slot / event handler, but maybe there are ways around
    {
        /*QMessageBox dlg (QMessageBox::Critical, "Error", "Caught generic exception. Exiting ...", QMessageBox::Close, 0, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint);

        dlg.exec();
        qDebug("out - err");*/
        CB_ASSERT (false);
    }

    /*mainDlg.show();
    return app.exec();*/
}
Esempio n. 21
0
// Use boost::program_options to parse command line input
// This does pretty much all the parameter checking needed
int parseCommandLine (int argc, char *argv[], po::variables_map& vm)
{
   int failed = 0;

   //Required options
   po::options_description required("Required options");
   required.add_options()
    ("kmers,k", po::value<std::string>(), "dsm kmer output file (not needed if using --mds_concat)")
    ("pheno,p", po::value<std::string>(), ".pheno metadata");

   po::options_description mds("MDS options");
   mds.add_options()
    ("output,o", po::value<std::string>(), "output prefix for new dsm file")
    ("no_mds", "do not perform MDS; output subsampled matrix instead")
    ("write_distances",  "write csv of distance matrix")
    ("mds_concat", po::value<std::string>(), "list of subsampled matrices to use in MDS. Performs only MDS; implies --no_filtering")
    ("pc", po::value<int>()->default_value(pc_default), "number of principal coordinates to output")
    ("size", po::value<long int>()->default_value(size_default), "number of kmers to use in MDS")
    ("threads", po::value<int>()->default_value(1), ("number of threads. Suggested: " + std::to_string(std::thread::hardware_concurrency())).c_str());

   //Optional filtering parameters
   //NB pval cutoffs are strings for display, and are converted to floats later
   po::options_description filtering("Filtering options");
   filtering.add_options()
    ("no_filtering", "turn off all filtering and do not output new kmer file")
    ("max_length", po::value<long int>()->default_value(max_length_default), "maximum kmer length")
    ("maf", po::value<double>()->default_value(maf_default), "minimum kmer frequency")
    ("min_words", po::value<int>(), "minimum kmer occurences. Overrides --maf");

   po::options_description other("Other options");
   other.add_options()
    ("version", "prints version and exits")
    ("help,h", "full help message");

   po::options_description all;
   all.add(required).add(mds).add(filtering).add(other);

   try
   {
      po::store(po::command_line_parser(argc, argv).options(all).run(), vm);

      if (vm.count("help"))
      {
         printHelp(all);
         failed = 1;
      }
      else if (vm.count("version"))
      {
         std::cout << VERSION << std::endl;
         failed = 1;
      }
      else
      {
         po::notify(vm);
         failed = 0;

         // Check input files exist, and can stat
         if ((vm.count("kmers") && !fileStat(vm["kmers"].as<std::string>())) || (vm.count("pheno") && !fileStat(vm["pheno"].as<std::string>())))
         {
            failed = 1;
         }
      }

   }
   catch (po::error& e)
   {
      // Report errors from boost library
      std::cerr << "Error in command line input: " << e.what() << "\n";
      std::cerr << "Run 'kmds --help' for full option listing\n\n";
      std::cerr << required << "\n" << other << "\n";

      failed = 1;
   }

   return failed;
}
Esempio n. 22
0
void SummaryConfiguration::setupOptions(const po::variables_map& vm) {

    if (vm.count(config->getMode() + ".dataset"))
        dataset = vm[config->getMode() + ".dataset"].as<string>();
    if (vm.count(config->getMode() + ".datasetGroup"))
        datasetGroup = vm[config->getMode() + ".datasetGroup"].as<string>();
    if (vm.count(config->getMode() + ".varmap"))
        symbolMapList = vm[config->getMode() + ".varmap"].as<vector<string> >();
    if (vm.count(config->getMode() + ".column_default"))
        outputColumnsDefault = vm[config->getMode() + ".column_default"].as<vector<string> >();

    if (dataset == "ProcessSummary") {
        symbolTable = new nclq::SymbolTable(SummaryDataSource<ProcessSummary>::symbols);
    } else if (dataset == "IdentifiedFilesystem") {
        symbolTable = new nclq::SymbolTable(SummaryDataSource<IdentifiedFilesystem>::symbols);
    } else if (dataset == "IdentifiedNetworkConnection") {
        symbolTable = new nclq::SymbolTable(SummaryDataSource<IdentifiedNetworkConnection>::symbols);
    } else {
        throw invalid_argument(string("Unknown dataset: ") + dataset);
    }
    cout << "filePath: " << filePath << endl;

    symbolTable->setModifiable(true);
    vector<string> paths;
    boost::algorithm::split(paths, filePath, boost::is_any_of(":"));
    for (vector<string>::iterator iter = paths.begin(), end=paths.end(); iter!=end; ++iter) {
        const string& currPath = *iter;

        boost::regex h5Regex(h5pattern);
        fs::path h5Path(currPath);
        struct tm datetime;
        if (specificFiles.size() == 0) {
            try {
                if (fs::exists(currPath) && fs::is_directory(currPath)) {
                    vector<fs::path> all_dirent;
                    copy(fs::directory_iterator(currPath), fs::directory_iterator(), back_inserter(all_dirent));
                    for (vector<fs::path>::const_iterator iter(all_dirent.begin()), end(all_dirent.end()); iter != end; ++iter) {
                        if (!is_regular_file(*iter)) continue;

                        boost::smatch matched;
                        if (boost::regex_match(iter->filename().native(), matched, h5Regex)) {
                            bzero(&datetime, sizeof(struct tm));
                            const char *datestr = &*(matched[1].first);
                            if (strptime(datestr, dateformat.c_str(), &datetime) == NULL) {
                                continue;
                            }
                            time_t timestamp = mktime(&datetime);
                            if (timestamp >= config->getStartDate() && timestamp <= config->getEndDate()) {
                                files.push_back(*iter);
                            }
                        }
                    }
                }
            } catch (const fs::filesystem_error &err) {
                cerr << "Encountered filesystem error: " << err.what() << endl;
                exit(1);
            }
        } else {
            vector<string>::iterator iter(specificFiles.begin());
            while (iter < specificFiles.end()) {
                fs::path currFile = currPath / fs::path(*iter);
                if (fs::exists(currFile) && is_regular_file(currFile)) {
                    specificFiles.erase(iter++);
                    files.push_back(currFile);
                } else {
                    ++iter;
                }
            }
        }
    }
    for (vector<string>::const_iterator iter(specificFiles.begin()), end(specificFiles.end()); iter != end; ++iter) {
        fs::path currFile = *iter;
        if (fs::exists(currFile) && is_regular_file(currFile)) {
            files.push_back(currFile);
        } else {
            cout << "Couldn't find file: " << currFile << endl;
            exit(2);
        }
    }

    sort(files.begin(), files.end());
    if (files.size() == 0) {
        cout << "No matching accounting files.  Exiting." << endl;
        exit(1);
    }
    if (config->isVerbose()) {
        for (auto it: files) {
            cout << "Will parse: " << it << endl;
        }
    }
}
Esempio n. 23
0
int parseArguments(int ac, wchar_t **av, po::variables_map& vm, printInfoStruct& printInfo) {
	wchar_t namePath[MAX_PATH];
	GetModuleFileName(NULL, namePath, MAX_PATH);
	wchar_t *progName = PathFindFileName(namePath);

	po::options_description desc;

	desc.add_options()
		(",h", "print usage message and exit")
		("help", "print help message and exit")
		("version,v", "print version and exit")
		("warning,w", po::wvalue<wstring>(), "warning value (in percent)")
		("critical,c", po::wvalue<wstring>(), "critical value (in percent)")
		;

	po::basic_command_line_parser<wchar_t> parser(ac, av);

	try {
		po::store(
			parser
			.options(desc)
			.style(
			po::command_line_style::unix_style |
			po::command_line_style::allow_long_disguise)
			.run(),
			vm);
		vm.notify();
	} catch (std::exception& e) {
		cout << e.what() << endl << desc << endl;
		return 3;
	}

	if (vm.count("h")) {
		cout << desc << endl;
		return 0;
	}

	if (vm.count("help")) {
		wcout << progName << " Help\n\tVersion: " << VERSION << endl;
		wprintf(
			L"%s is a simple program to check a machines CPU load.\n"
			L"You can use the following options to define its behaviour:\n\n", progName);
		cout << desc;
		wprintf(
			L"\nIt will then output a string looking something like this:\n\n"
			L"\tLOAD WARNING 67%%|load=67%%;50%%;90%%;0;100\n\n"
			L"\"LOAD\" being the type of the check, \"WARNING\" the returned status\n"
			L"and \"67%%\" is the returned value.\n"
			L"The performance data is found behind the \"|\", in order:\n"
			L"returned value, warning threshold, critical threshold, minimal value and,\n"
			L"if applicable, the maximal value.\n\n"
			L"%s' exit codes denote the following:\n"
			L" 0\tOK,\n\tNo Thresholds were broken or the programs check part was not executed\n"
			L" 1\tWARNING,\n\tThe warning, but not the critical threshold was broken\n"
			L" 2\tCRITICAL,\n\tThe critical threshold was broken\n"
			L" 3\tUNKNOWN, \n\tThe program experienced an internal or input error\n\n"
			L"Threshold syntax:\n\n"
			L"-w THRESHOLD\n"
			L"warn if threshold is broken, which means VALUE > THRESHOLD\n"
			L"(unless stated differently)\n\n"
			L"-w !THRESHOLD\n"
			L"inverts threshold check, VALUE < THRESHOLD (analogous to above)\n\n"
			L"-w [THR1-THR2]\n"
			L"warn is VALUE is inside the range spanned by THR1 and THR2\n\n"
			L"-w ![THR1-THR2]\n"
			L"warn if VALUE is outside the range spanned by THR1 and THR2\n\n"
			L"-w THRESHOLD%%\n"
			L"if the plugin accepts percentage based thresholds those will be used.\n"
			L"Does nothing if the plugin does not accept percentages, or only uses\n"
			L"percentage thresholds. Ranges can be used with \"%%\", but both range values need\n"
			L"to end with a percentage sign.\n\n"
			L"All of these options work with the critical threshold \"-c\" too."
			, progName);
		cout << endl;
		return 0;
	}

	if (vm.count("version"))
		cout << "Version: " << VERSION << endl;

	if (vm.count("warning")) {
		try {
			std::wstring wthreshold = vm["warning"].as<wstring>();
			std::vector<std::wstring> tokens;
			boost::algorithm::split(tokens, wthreshold, boost::algorithm::is_any_of(","));
			printInfo.warn = threshold(tokens[0]);
		} catch (std::invalid_argument& e) {
			cout << e.what() << endl;
			return 3;
		}
	}
	if (vm.count("critical")) {
		try {
			std::wstring cthreshold = vm["critical"].as<wstring>();
			std::vector<std::wstring> tokens;
			boost::algorithm::split(tokens, cthreshold, boost::algorithm::is_any_of(","));
			printInfo.crit = threshold(tokens[0]);
		} catch (std::invalid_argument& e) {
			cout << e.what() << endl;
			return 3;
		}
	}

	return -1;
}
Esempio n. 24
0
void ParseCmdLineOpts(const bpo::options_description& cmdline_options,
      const bpo::variables_map& vm)
{
   if (vm.count("help")) {
      cout << cmdline_options << endl;
      cout << "kFormats size = " << sizeof(kFormats[0]) << endl;
      exit(0);
   }
   if (vm.count("version"))
   {
      cout << "GNUPlotInterface (gpif) Program" << endl;
      cout << "Version: " << zv::GetFullVersionString() << endl;
      cout << "  Built: " << zv::BuildDate << "@" << zv::BuildTime << endl;
      cout << "   UUID: " << zv::UUID << endl;
      exit(0);
   }
   int width(600);
   int height(400);
   if (vm.count("width"))
   {
      if (0 == vm.count("dxf"))
      {
         width = vm["width"].as<int>();
         height =
               (0 == vm.count("height") ? width * 3 / 4 : vm["height"].as<int>());
      }
      else
      {
         cout << "DXF format current only supports 120x80 output." << endl;
      }
   }
   string inFileStr;
   if (vm.count("data"))
   {
      inFileStr = vm["data"].as<string>();
      if(!bfs::exists(inFileStr))
      {
         cout << "The input file " << inFileStr << " does not exist." << endl;
         exit(2);
      }
   }
   else
   {
      cout << "You must specify an input file with the '-d' option" << endl;
      exit(3);
   }
   int numColumns(1);
   if (vm.count("columns"))
   {
      numColumns = vm["columns"].as<int>();
   }
   string delimChr(" ");
   if (vm.count("delimiter"))
   {
      delimChr = vm["delimiter"].as<string>();
   }

   TStrVect formatVect;
   string tmpFmtNameStr;
   if (vm.count("format"))
   {
      cout << "Checking format" << endl;
      if(ExtractFormatStr(vm["format"].as<string>(), tmpFmtNameStr))
      {
         formatVect.push_back(tmpFmtNameStr);
      }
      else
      {
         cout << "Format argument (" << vm["format"].as<string>()
               << ") is not a valid type" << endl;
         cout << "Run this program with the -h option to see all valid options"
               << endl;
         exit(1);
      }
   }
   size_t cnt(0);
   while(0 != kFormats[cnt][0].compare(kEndStrFormats))
   {
      if(vm.count(kFormats[cnt][0]))
      {
         formatVect.push_back(kFormats[cnt][0]);
      }
      ++cnt;
   }
   if(0 == formatVect.size())
   {
      formatVect.push_back(kPNGFormatStr);
   }
   cout << "Format" << (1 < formatVect.size() ? "s: " : ": ") << endl;
   for(auto itr = formatVect.begin(); formatVect.end() != itr; ++itr)
   {
      string outFileStr;
      if(CreateOutputFileNameStr(*itr, outFileStr))
      {
         cout << "  " << (*itr) << " " << outFileStr << endl;
         string cmdStr("gnuplot -e \"set term ");
         cmdStr.append(*itr);
         if(0 != (*itr).compare("dxf"))
         {
            stringstream dimStrm;
            dimStrm << " size " << width << ", " << height;
            cmdStr.append(dimStrm.str());
         }
         cmdStr.append("; set output \\\"");
         cmdStr.append(outFileStr);
         cmdStr.append("\\\";");
         if(vm.count("grid"))
         {
            cmdStr.append("set grid;");
         }
         if (vm.count("delimiter"))
         {
            cmdStr.append("set datafile separator \\\"");
            cmdStr.append(delimChr);
            cmdStr.append("\\\";");
         }
         cmdStr.append("plot \\\"");
//
         cmdStr.append(inFileStr);
         if(1 == numColumns)
         {
            cmdStr.append("\\\" with lines\"");
         }
         else
         {
            cmdStr.append("\\\" using 1");
            for(int i=2; i<=numColumns; ++i)
            {
               stringstream strm;
               strm << ":" << i;
               cmdStr.append(strm.str());
            }
            cmdStr.append(" with lines\"");
         }
         cout << "Command: [" << cmdStr << "]" << endl;
         ::system(cmdStr.c_str());
      }
   }

}
Esempio n. 25
0
void parseOptions(int argc, char* argv[])
{
    vector< string> solverList;

    try
    {
        /* Declare the different group of program
         * options available
         */
        po::options_description generalOpts("General options");
        generalOpts.add_options()
        ("help,h", "produce help message")
        ("config,c", po::value<std::string>()->default_value(DEFAULT_CONFIG_PATH), "Path to configuration file.")

        ;


        po::options_description solverOpts("Solver options");
        solverOpts.add_options()
        ("solver,s", po::value< std::vector<string> >(&solverList)->composing(),
         "Specify a solver to use. This option can be set multiple times so that each "
         "solver is invoked in a different process.")
        ("timeout,t", po::value<double>()->default_value(0.0), "Set timeout in seconds.")
        ("verbose", po::value<bool>(&verbose)->default_value(false), "Print running information to standard error.")
        ("logging-path", po::value<string>(&loggingPath)->default_value(""), "Enable logging mode (off by default) and set the path to the log file.")
        ;


        //This is used as a positional argument
        po::options_description input("Input");
        input.add_options()("input", po::value<std::string>()->required(),"Specifies SMTLIBv2 input file.");
        po::positional_options_description p;
        p.add("input",1);

        //Create options group to show for help messages
        po::options_description hm("Options");
        hm.add(generalOpts).add(solverOpts);

        //Options group for parsing
        po::options_description cl("");
        cl.add(generalOpts).add(solverOpts).add(input);

        //invoke commandline parser
        po::store(po::command_line_parser(argc, argv).
                  options(cl).positional(p).run(), vm);

        /*check for help option first because the input might not be set
        * which will cause notify() to throw an exception
        */
        if(vm.count("help"))
            printHelp(hm);

        po::notify(vm);//trigger exceptions if there are any

        //check input file exists
        boost::filesystem::path inputFile(vm["input"].as<string>());
        if(! boost::filesystem::is_regular_file(inputFile))
        {
            cerr << "Error: Input SMTLIBv2 file (" << vm["input"].as<string>() <<
                 ") does not exist or is not a regular file." << endl;
            exit(1);
        }


        //if the configuration file exists then load it
        boost::filesystem::path configFile(vm["config"].as<string>());
        bool configFileExists=boost::filesystem::is_regular_file(configFile) ||
                              boost::filesystem::is_symlink(configFile);


        //If user manually specified a config file check it exists
        if(!vm["config"].defaulted() > 0 && ! configFileExists )
        {
            cerr << "Error: Configuration file " << configFile.string() << " does not exist!" << endl;
            exit(1);
        }

        po::options_description indivSolvOpt("");
        if(configFileExists)
        {
            //parse configuration file for options too
            if(verbose) cerr << "Parsing configuration file:" << configFile.string() << endl;

            ifstream cf;
            cf.open(configFile.string().c_str());

            if(!cf.good())
            {
                cerr << "Couldn't open configuration file " << configFile.string() << endl;
            }


            //Do first pass for solver options
            po::store(po::parse_config_file(cf,solverOpts,true), vm);
            po::notify(vm);

            cf.close();
            cf.open(configFile.string().c_str());

            //cf.seekg(0,ios_base::beg);//Move to the beginning of the file.

            /*loop over solvers and create
             * <solvername>.opts options
             * <solvername>.input-on-stdin options
             */
            for(vector<string>::const_iterator s= solverList.begin(); s != solverList.end(); ++s)
            {
                string optionName(*s);

                //Do <solvername>.opts
                optionName+=".opts";
                indivSolvOpt.add_options() (optionName.c_str(),po::value<string>(),"");
                if(verbose) cerr << "Looking for \"" << optionName << "\" in " << configFile << endl;

                //Do <solvername>.input-on-stdout
                optionName=*s;
                optionName+=".input-on-stdin";
                indivSolvOpt.add_options() (optionName.c_str(),po::value<bool>()->default_value(false),"");
                if(verbose) cerr << "Looking for \"" << optionName << "\" in " << configFile << endl;

            }

            //Do second pass for per solver options
            po::store(po::parse_config_file(cf,indivSolvOpt,true), vm);
            po::notify(vm);

            cf.close();
        }

        /* See if we are using logging mode
         *
         */
        bool lMode=false;
        if(vm["logging-path"].as<string>().length() != 0)
        {
            lMode=true;
        }


        try {
            sm = new SolverManager(vm["input"].as<string>(),vm["timeout"].as<double>(),lMode);
        }
        catch(std::bad_alloc& e)
        {
            cerr << "Failed to allocate memory of SolverManager:" << e.what() << endl;
            exit(1);
        }

        //Now finally create solvers
        for(vector<string>::const_iterator s= solverList.begin(); s != solverList.end(); ++s)
        {
            string solvOpt(*s);
            solvOpt+=".opts";

            string stdinOpt(*s);
            stdinOpt+=".input-on-stdin";

            bool inputOnStdin = false;
            if(configFileExists && vm.count(stdinOpt.c_str()) && vm[stdinOpt.c_str()].as<bool>() )
                inputOnStdin=true;

            if(configFileExists && vm.count(solvOpt.c_str()))
            {
                sm->addSolver(*s, vm[solvOpt.c_str()].as<string>(), inputOnStdin);
            }
            else
                sm->addSolver(*s,inputOnStdin);

        }


    }
    catch(po::required_option& r)
    {
        cerr << "Error: ";
        if (r.get_option_name() == "--input")
        {
            cerr << "Input SMTLIBv2 file must be specified. For help use --help" << endl;
        }
        else
        {
            cerr << r.what() << endl;
        }

        exit(1);
    }
    catch(exception& e)
    {
        cerr << "Error:" << e.what() << endl;
        exit(1);
    }


}
Esempio n. 26
0
long
benchmark(nemo::Simulation* sim, unsigned n, unsigned m,
				boost::program_options::variables_map& vm, unsigned seconds)
{

	unsigned stdpPeriod = vm["stdp-period"].as<unsigned>();
	float stdpReward = vm["stdp-reward"].as<float>();
	bool csv = vm.count("csv") != 0;
	bool verbose = !csv;
	bool provideFiringStimulus = vm.count("fstim") != 0;
	bool provideCurrentStimulus = vm.count("istim") != 0;
	bool vprobe = vm.count("vprobe") != 0;

	const unsigned MS_PER_SECOND = 1000;

	rng_t rng;
	uirng_t randomNeuron(rng, boost::uniform_int<>(0, n-1));

	sim->resetTimer();

	unsigned t = 0;
	float v = 0;

	/* Run for a few seconds to warm up the network */
	if(verbose)
		std::cout << "Running simulation (warming up)...";
	for(unsigned s=0; s < 5; ++s) {
		for(unsigned ms = 0; ms < MS_PER_SECOND; ++ms, ++t) {
			sim->step();
			if(stdpPeriod && t % stdpPeriod == 0) {
				sim->applyStdp(stdpReward);
			}
		}
	}
	if(verbose)
		std::cout << "[" << sim->elapsedWallclock() << "ms elapsed]";
	sim->resetTimer();

	if(verbose) {
		std::cout << std::endl;
		std::cout << "Running simulation (gathering performance data)...";
	}

	nemo::Simulation::firing_stimulus firingStimulus;
	nemo::Simulation::current_stimulus currentStimulus;

	unsigned long nfired = 0;
	for(unsigned s=0; s < seconds; ++s) {
		if(verbose)
			std::cout << s << " ";
		for(unsigned ms=0; ms<1000; ++ms, ++t) {

			if(provideFiringStimulus) {
				firingStimulus.resize(1);
				firingStimulus[0] = randomNeuron();
			}

			if(provideCurrentStimulus) {
				currentStimulus.resize(1);
				currentStimulus[0] = std::make_pair(randomNeuron(), 0.001f);
			}

			const std::vector<unsigned>& fired = sim->step(firingStimulus, currentStimulus);
			nfired += fired.size();

			if(vprobe) {
				/* Just read a single value. The whole neuron population will be synced */
				v = sim->getMembranePotential(0);
			}

			if(stdpPeriod && t % stdpPeriod == 0) {
				sim->applyStdp(stdpReward);
			}
		}
	}
	long int elapsedWallclock = sim->elapsedWallclock();
	if(verbose)
		std::cout << "[" << elapsedWallclock << "ms elapsed]";
	if(verbose)
		std::cout << std::endl;

	unsigned long narrivals = nfired * m;
	double f = (double(nfired) / n) / double(seconds);

	/* Throughput is measured in terms of the number of spike arrivals per
	 * wall-clock second */
	unsigned long throughput = MS_PER_SECOND * narrivals / elapsedWallclock;
	double speedup = double(seconds*MS_PER_SECOND)/elapsedWallclock;

	if(verbose) {
		std::cout << "Total firings: " << nfired << std::endl;
		std::cout << "Avg. firing rate: " << f << "Hz\n";
		std::cout << "Spike arrivals: " << narrivals << std::endl;
		std::cout << "Approx. throughput: " << throughput/1000000
				<< "Ma/s (million spike arrivals per second)\n";
		std::cout << "Speedup wrt real-time: " << speedup << std::endl;
	}

	if(csv) {
		std::string sep = ", ";
		// raw data
		std::cout << n << sep << m << sep << seconds*MS_PER_SECOND
			<< sep << elapsedWallclock << sep << stdpPeriod << sep << nfired;
		// derived data. Not strictly needed, at least if out-degree is fixed.
		std::cout << sep << narrivals << sep << f << sep << speedup
			<< sep << throughput/1000000 << std::endl;
	}

	return elapsedWallclock;
}
Esempio n. 27
0
int rc_handler (std::ostream& os, po::variables_map& vm, int ac, char* av[])
{
	try {
		po::options_description genOpts;
		genOpts.add_options()
			("help,h", po::value<std::string>()->implicit_value("help"), "")
			//("command", po::value<std::string>(), "")
			("start", "Start the Plato daemon. Will fail if already running.")
			("stop", "Stop the Plato daemon. Will fail if not previously running.")
			("restart", "Stop the Plato daemon, then start it up again. Will fail if not previously running.")
			("status", "View information about the Plato daemon, such as if it is running, how much of its reserved memory it is using, and other things.")
			//("verbose,v", "")
			("version,V", "Print the version information.")
			("mode,m", po::value<std::string>()->default_value("mmap"), "Specify either 'mmap' (memory mapped file), or 'shm' (shared memory).")
			("input-file,i",	po::value<std::string>()->default_value("plato_daemon_datafile"),	"Specify the input file for serialization.")
			("output-file,o",	po::value<std::string>()->default_value("plato_daemon_datafile"),	"Specify the output file for serialization.")
			("log-file,l", 		po::value<std::string>()->default_value("plato_daemon.log"),	"Specify the log file.")
			("config-file",		po::value<std::string>()->default_value("plato_daemon.conf"),	"Specify the runtime configuration file.")
		;

		po::options_description configOpts("Options to be specified in a configuration file");

		configOpts.add_options()
			("memory-mapped-filename", po::value<std::string>()->default_value("PlatoDaemonFile.mmap"), "")
			("shared-memory-name", po::value<std::string>()->default_value("PlatoDaemonSharedMemory"), "")
			("tag-map-name", po::value<std::string>()->default_value("PlatoTagMap"), "")
			("file-map-name", po::value<std::string>()->default_value("PlatoFileMap"), "")
			("start-up-buffer", po::value<float>()->default_value(1.0), "Pick the amount of headroom you want to have at startup.")
		;

		po::options_description cmdlineOpts;

		cmdlineOpts.add(genOpts).add(configOpts);

		po::options_description configFileOpts;
		//configFileOpts.add(configOpts);
		
		po::options_description visibleOpts("Supported command-line options");
		visibleOpts.add(genOpts);

		//	Positional options
		//po::positional_options_description posOpts;
		//posOpts.add("command", 1);

		po::store(po::command_line_parser(ac, av).options(cmdlineOpts).run(), vm);

		po::notify(vm);

		if (vm.count("help")) {
			if (!vm["help"].as<std::string>().compare("help")) {
			os << visibleOpts << std::endl;
			os << "For additional options regarding config-files, run with \"--help config-files\"" << std::endl;
			} else if ( ! vm["help"].as<std::string>().compare("config-files")) {
				os << configOpts << std::endl;
			}
			exit(0);
		}

		if (vm.count("version")) {
			os << "plato_daemon"
				<< std::endl << "The Plato Semantic Resource Management System Daemon" << std::endl;
			os << "Version "
			#ifdef PLATO_DAEMON_VERSION_ID
				<< PLATO_DAEMON_VERSION_ID;
			#else
				<< "<unspecified> (set preprocessor macro \"PLATO_DAEMON_VERSION_ID\" to specify version string)";
			#endif
			os << std::endl
				<< "Compiled on " << __DATE__ << " at " << __TIME__ << std::endl
				<< "Compiler version: " << __VERSION__ << std::endl
				<< "Boost library version: " << BOOST_LIB_VERSION << std::endl
				<< "Git commit: " 
				#ifdef PLATO_DAEMON_GIT_COMMIT
					<< PLATO_DAEMON_GIT_COMMIT 
				#else
					<< "<unspecified> (set preprocessor macro \"PLATO_DAEMON_GIT_COMMIT\" to specify version string)"
				#endif
				<< std::endl;
			exit(0);
		}
int hpx_main(boost::program_options::variables_map& vm)
{
    unsigned int seed = (unsigned int)std::time(0);
    if (vm.count("seed"))
        seed = vm["seed"].as<unsigned int>();

    std::cout << "using seed: " << seed << std::endl;
    std::srand(seed);

    unsigned int size = 10000;
    if (vm.count("size"))
        size = vm["size"].as<unsigned int>();

    char const* const example_vector_name =
        "partitioned_vector_spmd_foreach_example";
    char const* const example_latch_name =
        "latch_spmd_foreach_example";

    {
        // create vector on one locality, connect to it from all others
        hpx::partitioned_vector<int> v;
        hpx::lcos::latch l;

        if (0 == hpx::get_locality_id())
        {
            std::vector<hpx::id_type> localities = hpx::find_all_localities();

            v = hpx::partitioned_vector<int>(size,
                    hpx::container_layout(localities));
            v.register_as(example_vector_name);

            l = hpx::lcos::latch(localities.size());
            l.register_as(example_latch_name);
        }
        else
        {
            v.connect_to(example_vector_name);
            l.connect_to(example_latch_name);
        }

        boost::random::mt19937 gen(std::rand());
        boost::random::uniform_int_distribution<> dist;

        // fill the vector with random numbers
        partitioned_vector_view<int> view(v);
        hpx::parallel::generate(
            hpx::parallel::par,
            view.begin(), view.end(),
            [&]()
            {
                return dist(gen);
            });

        // square all numbers in the array
        hpx::parallel::for_each(
            hpx::parallel::par,
            view.begin(), view.end(),
            [](int& val)
            {
                val *= val;
            });

        // do the same using a plain loop
        std::size_t maxnum = view.size();
        for (std::size_t i = 0; i != maxnum; ++i)
            view[i] *= 2;

        // Wait for all localities to reach this point.
        l.count_down_and_wait();
    }

    return hpx::finalize();
}
void computeEstimation
( const po::variables_map& vm,     //< command-line parameters
  const KSpace& K,                 //< cellular grid space
  const ImplicitShape& shape,      //< implicit shape "ground truth"
  const Surface& surface,          //< digital surface approximating shape
  TrueEstimator& true_estimator,   //< "ground truth" estimator
  Estimator& estimator )           //< an initialized estimator
{
  typedef typename Surface::ConstIterator ConstIterator;
  typedef typename Surface::Surfel Surfel;
  typedef typename Estimator::Quantity Quantity;
  typedef double Scalar;
  typedef DepthFirstVisitor< Surface > Visitor;
  typedef GraphVisitorRange< Visitor > VisitorRange;
  typedef typename VisitorRange::ConstIterator VisitorConstIterator;
  
  std::string fname = vm[ "output" ].as<std::string>();
  string nameEstimator = vm[ "estimator" ].as<string>();
  trace.beginBlock( "Computing " + nameEstimator + "estimations." );
  CountedPtr<VisitorRange> range( new VisitorRange( new Visitor( surface, *(surface.begin()) )) );
  std::vector<Quantity> n_estimations;
  estimator.eval( range->begin(), range->end(), std::back_inserter( n_estimations ) );
  trace.info() << "- nb estimations  = " << n_estimations.size() << std::endl;
  trace.endBlock();

  trace.beginBlock( "Computing ground truth." );
  range = CountedPtr<VisitorRange>( new VisitorRange( new Visitor( surface, *(surface.begin()) )) );
  std::vector<Quantity> n_true_estimations;
  true_estimator.eval( range->begin(), range->end(), std::back_inserter( n_true_estimations ) );
  trace.info() << "- nb estimations  = " << n_true_estimations.size() << std::endl;
  trace.endBlock();

  trace.beginBlock( "Correcting orientations." );
  ASSERT( n_estimations.size() == n_true_estimations.size() );
  for ( unsigned int i = 0; i < n_estimations.size(); ++i )
    if ( n_estimations[ i ].dot( n_true_estimations[ i ] ) < 0 )
      n_estimations[ i ] = -n_estimations[ i ];
  trace.endBlock();

  DGtal::GradientColorMap<double> grad( 0.0, 40.0 );
  // 0 metallic blue, 5 light cyan, 10 light green, 15 light
  // yellow, 20 yellow, 25 orange, 30 red, 35, dark red, 40- grey
  grad.addColor( DGtal::Color( 128, 128, 255 ) ); // 0
  grad.addColor( DGtal::Color( 128, 255, 255 ) ); // 5
  grad.addColor( DGtal::Color( 128, 255, 128 ) ); // 10
  grad.addColor( DGtal::Color( 255, 255, 128 ) ); // 15
  grad.addColor( DGtal::Color( 255, 255, 0   ) ); // 20
  grad.addColor( DGtal::Color( 255, 128, 0   ) ); // 25
  grad.addColor( DGtal::Color( 255,   0, 0   ) ); // 30
  grad.addColor( DGtal::Color( 128,   0, 0   ) ); // 35
  grad.addColor( DGtal::Color( 128, 128, 128 ) ); // 40

  if ( vm.count( "angle-deviation-stats" ) )
    {
      trace.beginBlock( "Computing angle deviation error stats." );
      std::ostringstream adev_sstr;
      adev_sstr << fname << "-" << nameEstimator << "-angle-deviation-" 
                << estimator.h() << ".txt"; 
      DGtal::Statistic<Scalar> adev_stat;
      unsigned int i = 0;
      range = CountedPtr<VisitorRange>( new VisitorRange( new Visitor( surface, *(surface.begin()) )) );
      for ( VisitorConstIterator it = range->begin(), itE = range->end(); it != itE; ++it, ++i )
        {
          Quantity n_est = n_estimations[ i ];
          Quantity n_true_est = n_true_estimations[ i ];
          Scalar angle_error = acos( n_est.dot( n_true_est ) );
          adev_stat.addValue( angle_error );
        }
      adev_stat.terminate();
      std::ofstream adev_output( adev_sstr.str().c_str() );
      adev_output << "# Average error X of the absolute angle between two vector estimations." << std::endl;
      adev_output << "# h L1 L2 Loo E[X] Var[X] Min[X] Max[X] Nb[X]" << std::endl;
      adev_output << estimator.h() 
                  << " " << adev_stat.mean() // L1
                  << " " << sqrt( adev_stat.unbiasedVariance()
                                  + adev_stat.mean()*adev_stat.mean() ) // L2
                  << " " << adev_stat.max() // Loo
                  << " " << adev_stat.mean() // E[X] (=L1)
                  << " " << adev_stat.unbiasedVariance() // Var[X]
                  << " " << adev_stat.min() // Min[X]
                  << " " << adev_stat.max() // Max[X]
                  << " " << adev_stat.samples() // Nb[X]
                  << std::endl;
      adev_output.close();
      trace.endBlock();
    }
  if ( vm[ "export" ].as<string>() != "None" )
    {
      trace.beginBlock( "Exporting cell geometry." );
      std::ostringstream export_sstr;
      export_sstr << fname << "-" << nameEstimator << "-cells-" 
                  << estimator.h() << ".txt"; 
      std::ofstream export_output( export_sstr.str().c_str() );
      export_output << "# ImaGene viewer (viewSetOfSurfels) file format for displaying cells." << std::endl;
      bool adev =  vm[ "export" ].as<string>() == "AngleDeviation";
      unsigned int i = 0;
      range = CountedPtr<VisitorRange>( new VisitorRange( new Visitor( surface, *(surface.begin()) )) );
      for ( VisitorConstIterator it = range->begin(), itE = range->end(); it != itE; ++it, ++i )
        {
          Quantity n_est = n_estimations[ i ];
          Quantity n_true_est = n_true_estimations[ i ];
          Scalar angle_error = acos( n_est.dot( n_true_est ) )*180.0 / 3.14159625;
          Surfel s = *it;
          export_output
            << "CellN" 
            << " " << min( 1023, max( 512+K.sKCoord( s, 0 ), 0 ) )
            << " " << min( 1023, max( 512+K.sKCoord( s, 1 ), 0 ) )
            << " " << min( 1023, max( 512+K.sKCoord( s, 2 ), 0 ) )
            << " " << K.sSign( s );
          Color c = grad( 0 );
          if ( adev ) c = grad( max( 0.0, min( angle_error, 40.0 ) ) );
          export_output << " " << ((double) c.red() / 255.0 )
                        << " " << ((double) c.green() / 255.0 )
                        << " " << ((double) c.blue() / 255.0 );
          export_output << " " << n_est[ 0 ] << " " << n_est[ 1 ] 
                        << " " << n_est[ 2 ] << std::endl;
        }
      export_output.close();
      trace.endBlock();
    }
  if ( vm.count( "normals" ) )
    {
      trace.beginBlock( "Exporting cells normals." );
      std::ostringstream export_sstr;
      export_sstr << fname << "-" << nameEstimator << "-normals-" 
                  << estimator.h() << ".txt"; 
      std::ofstream export_output( export_sstr.str().c_str() );
      export_output << "# kx ky kz sign n_est[0] n_est[1] n_est[2] n_true[0] n_true[1] n_true[2]" << std::endl;
      unsigned int i = 0;
      range = CountedPtr<VisitorRange>( new VisitorRange( new Visitor( surface, *(surface.begin()) )) );
      for ( VisitorConstIterator it = range->begin(), itE = range->end(); it != itE; ++it, ++i )
        {
          Quantity n_est = n_estimations[ i ];
          Quantity n_true_est = n_true_estimations[ i ];
          Surfel s = *it;
          export_output
            << K.sKCoord( s, 0 ) << " " << K.sKCoord( s, 1 ) << " " << K.sKCoord( s, 2 ) 
            << " " << K.sSign( s )
            << " " << n_est[ 0 ] << " " << n_est[ 1 ] << " " << n_est[ 2 ]
            << " " << n_true_est[ 0 ] << " " << n_true_est[ 1 ] << " " << n_true_est[ 2 ]
            << std::endl;
        }
      export_output.close();
      trace.endBlock();
    }
  if ( vm.count( "noff" ) )
    {
      trace.beginBlock( "Exporting NOFF file." );
      std::ostringstream export_sstr;
      export_sstr << fname << "-" << nameEstimator << "-noff-" 
                  << estimator.h() << ".off"; 
      std::ofstream export_output( export_sstr.str().c_str() );
      std::map<Surfel,Quantity> normals;
      unsigned int i = 0;
      range = CountedPtr<VisitorRange>( new VisitorRange( new Visitor( surface, *(surface.begin()) )) );
      for ( VisitorConstIterator it = range->begin(), itE = range->end(); it != itE; ++it, ++i )
        {
          Quantity n_est = n_estimations[ i ];
          normals[ *it ] = n_est;
        }
      CanonicSCellEmbedder<KSpace> surfelEmbedder( K );
      typedef SCellEmbedderWithNormal< CanonicSCellEmbedder<KSpace> > Embedder;
      Embedder embedder( surfelEmbedder, normals );
      surface.exportAs3DNOFF( export_output, embedder );
      export_output.close();
      trace.endBlock();
    }
#ifdef WITH_VISU3D_QGLVIEWER
  if ( vm[ "view" ].as<string>() != "None" )
    {
      typedef typename KSpace::Space Space;
      typedef Viewer3D<Space,KSpace> MyViewever3D;
      typedef Display3DFactory<Space,KSpace> MyDisplay3DFactory;
      int argc = 1;
      char name[] = "Viewer";
      char* argv[ 1 ];
      argv[ 0 ] = name;
      Surfel s;
      QApplication application( argc, argv );
      MyViewever3D viewer( K );
      viewer.show();
      viewer << SetMode3D( s.className(), "Basic" );
      trace.beginBlock( "Viewing surface." );
      bool adev =  vm[ "view" ].as<string>() == "AngleDeviation";

      unsigned int i = 0;
      range = CountedPtr<VisitorRange>( new VisitorRange( new Visitor( surface, *(surface.begin()) )) );
      for ( VisitorConstIterator it = range->begin(), itE = range->end(); it != itE; ++it, ++i )
        {
          Quantity n_est = n_estimations[ i ];
          Quantity n_true_est = n_true_estimations[ i ];
          Scalar angle_error = acos( n_est.dot( n_true_est ) )*180.0 / 3.14159625;
          s = *it;
          Color c = grad( 0 );
          if ( adev ) c = grad( max( 0.0, min( angle_error, 40.0 ) ) );
          viewer.setFillColor( c );
          MyDisplay3DFactory::drawOrientedSurfelWithNormal( viewer, s, n_est, false );
        }
      trace.endBlock();
      viewer << MyViewever3D::updateDisplay;
      application.exec();
    }
#endif

}
Esempio n. 30
0
bool MeshData::isValid(po::variables_map &vm)
{
  return (vm.count("input")>0) && (vm.count("block")>0);
}