コード例 #1
0
ファイル: mulmat.cpp プロジェクト: Tener/cuda-course
int main()
{
  srand48( time(NULL) );
  experiment( 64 );
  experiment( 256 );
  experiment( 1024 );

  return 0;
}
コード例 #2
0
 OpenSwath::SpectrumAccessPtr SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(boost::shared_ptr<OpenMS::MSExperiment<OpenMS::Peak1D> > exp)
 {
   bool is_cached = SimpleOpenMSSpectraFactory::isExperimentCached(exp);
   if (is_cached)
   {
     OpenSwath::SpectrumAccessPtr experiment(new OpenMS::SpectrumAccessOpenMSCached(exp->getLoadedFilePath()));
     return experiment;
   }
   else
   {
     OpenSwath::SpectrumAccessPtr experiment(new OpenMS::SpectrumAccessOpenMS(exp));
     return experiment;
   }
 }
コード例 #3
0
ファイル: latencytest.c プロジェクト: CoryXie/BarrelfishOS
static void fsb_init_msg(struct bench_binding *b, coreid_t id)
{
    errval_t err;

    // change waitset of the binding
    waitset_init(&signal_waitset);
    err = b->change_waitset(b, &signal_waitset);
    assert(err_is_ok(err));

    binding = b;
    reply_received = true;

#if CONFIG_TRACE
    // configure tracing
    err = trace_control(TRACE_EVENT(TRACE_SUBSYS_MULTIHOP,
                    TRACE_EVENT_MULTIHOP_BENCH_START, 0),
            TRACE_EVENT(TRACE_SUBSYS_MULTIHOP,
                    TRACE_EVENT_MULTIHOP_BENCH_STOP, 0), 0);
    if(err_is_fail(err)) {
        USER_PANIC_ERR(err, "trace_control failed");
    }
#endif

    // start tracing
    err = trace_event(TRACE_SUBSYS_MULTIHOP, TRACE_EVENT_MULTIHOP_BENCH_START,
            0);
    if (err_is_fail(err)) {
        USER_PANIC_ERR(err, "trace_event failed");
    }

    experiment();
}
コード例 #4
0
ファイル: gauss.c プロジェクト: AndreasFMueller/SeminarHPC
/**
 * \brief main function
 */
int	main(int argc, char *argv[]) {
	n = 10;

	// parse the command line
	int	c;
	while (EOF != (c = getopt(argc, argv, "p:")))
		switch (c) {
		case 'p':
			matrix_precision = atoi(optarg);
			break;
		}

	// each subsequent argument is a matrix size for which to perform
	// an experiment and measure run time
	while (optind < argc) {
		n = atoi(argv[optind]);
		if (n <= 0) {
			fprintf(stderr, "not a valid number: %s\n",
				argv[optind]);
		}
		experiment(n);
		optind++;
	}
	
	return EXIT_SUCCESS;
}
コード例 #5
0
ファイル: other.c プロジェクト: nunogmartins/cap_dissertation
static int __init other_init(void){

printk(KERN_INFO "load other experiment\n");

	experiment(my_pid);

return 0;

}
コード例 #6
0
ファイル: main.cpp プロジェクト: giraldeau/inf8601-scratchpad
int main(int argc, char *argv[])
{
    (void) argc; (void) argv;

    perf_event_attr attr, attr2;

    // Execution sur un seul CPU
    pid_t tid = gettid();
    cpu_set_t  mask;
    CPU_ZERO(&mask);
    CPU_SET(0, &mask);
    qDebug() << sched_setaffinity(0, sizeof(mask), &mask);

    //(perf_hw_cache_id) | (perf_hw_cache_op_id << 8) |
    //(perf_hw_cache_op_result_id << 16)

    // premiere structure d'attributs
    memset(&attr, 0, sizeof(attr));
    attr.size = sizeof(attr);
    attr.type = PERF_TYPE_HW_CACHE;
    attr.config = (PERF_COUNT_HW_CACHE_L1D) | (PERF_COUNT_HW_CACHE_OP_READ << 8) | (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16);
    attr.inherit = 1;
    attr.disabled = 0;

    // Deuxieme structure
    memset(&attr2, 0, sizeof(attr2));
    attr2.size = sizeof(attr2);
    attr2.type = PERF_TYPE_HW_CACHE;
    attr2.config = (PERF_COUNT_HW_CACHE_L1D) | (PERF_COUNT_HW_CACHE_OP_READ << 8) | (PERF_COUNT_HW_CACHE_RESULT_MISS << 16);
    attr2.inherit = 1;
    attr2.disabled = 0;

    //pid == 0 and cpu == -1
    //This measures the calling process/thread on any CPU.
    int fdRef = sys_perf_event_open(&attr, tid, -1, -1, 0);
    int fdMiss = sys_perf_event_open(&attr2, tid, -1, -1, 0);
    //int fdMiss = sys_perf_event_open(&attr2, tid, -1, fdRef, 0);

    QMap<int, double> results;
    for (qint64 len = 1; len < (1 << 26); len *= 2) {
        double miss_rate = experiment(len, fdRef, fdMiss);
        results.insert(len * sizeof(int), miss_rate);
    }

    // report
    std::cout << "size,miss_rate" << std::endl;
    for (int size : results.keys()) {
        std::cout << size << "," << results[size] << std::endl;
    }

    close(fdRef);
    close(fdMiss);
    return 0;
}
コード例 #7
0
ファイル: simple.c プロジェクト: alvarouc/ica_gsl
int main(int argc, char const *argv[]) {
  size_t NSUB = 1000;
  size_t NCOMP = 100;
  size_t NVOX = 50000;
  double cputime=0;

  size_t i, repetitions= 1;
  for (i = 0; i < repetitions; i++) {
    cputime += experiment(NSUB, NCOMP, NVOX, 0);
  }

  printf("\nCPU time used : %g", cputime/(double)repetitions);

  return 0;
}
コード例 #8
0
ファイル: percolationstats.cpp プロジェクト: fima7/algs
void PercolationStats::run()
{
	int i;
	// perform T independent computational experiments on an N-by-N grid
	StopWatch watch;
	for (int i = 0; i < m_experimentsNumber; i++) {

		watch.start();
		m_threshold[i] = experiment();
		m_time[i] = watch.stop();
		m_percolation->reset();
	}
	// Stats
	m_timeStats = new StatsData(m_time, m_experimentsNumber);
	m_thresholdStats = new StatsData(m_threshold, m_experimentsNumber);
}
コード例 #9
0
bool Server::openExperiment(const std::string &expPath) {
	namespace bf = boost::filesystem;
	
    ExperimentPackager packer;
	
    Datum experiment(packer.packageExperiment(bf::path(expPath)));
	if(experiment.isUndefined()) {
		merror(M_SERVER_MESSAGE_DOMAIN, 
			   "Failed to create a valid packaged experiment.");
		return false; 		
	}
	shared_ptr<Event> new_experiment(new Event(RESERVED_SYSTEM_EVENT_CODE, 
												 experiment));
	putEvent(new_experiment);
	
	return true;
}
コード例 #10
0
    void MainFrame::viewIndividual( wxCommandEvent& event )
    {
        int generation = generationSpinner->GetValue();
        int individual = individualSpinner->GetValue();

        string title;

        title +=
            populationFileName +
            string("_") +
            string("Generation: ") +
            toString(generation) +
            string(" Individual: ") +
            toString(individual);

        mutex *populationMutex = experimentRun.getPopulationMutex();
        {
            mutex::scoped_lock scoped_lock(*populationMutex);

            shared_ptr<Experiment> experiment(experimentRun.getExperiment()->clone());

            experiment->setExperimentName(title);

            //We do -1 because indicies are 0-based
            shared_ptr<NEAT::GeneticIndividual> indiv =
                shared_ptr<NEAT::GeneticIndividual>(
                    new NEAT::GeneticIndividual(
                        *(experimentRun.getIndividual(generation-1,individual-1).get())
                    )
                );

            ViewIndividualFrame *viewFrame =
                new ViewIndividualFrame(
                experiment,
                indiv,
                this,
                wxID_ANY,
                STRING_TO_WXSTRING(title),
                wxDefaultPosition,
                wxSize(720,480)
            );

            viewFrame->Show(TRUE);
        }
    }
コード例 #11
0
ファイル: buffon.c プロジェクト: Karikaturist/WPC
/* ---------------------------
        T E S T I N G
----------------------------*/        
int main( int argc, char *argv[])
{
 
 double nlength, swidth, npi;
 long drops, crossing;
 
 if( argc!=4 || (nlength=strtod( argv[1],NULL))<=0 || (swidth=strtod(argv[2],NULL))<=0 || (drops=strtol(argv[3],NULL,10))<=0 ){ 
    puts("\n\tUsage: $> buffon  needle_length  stripes_width  drops\n");
    nlength=1;
    swidth=1;
    drops=213000;
 }    
 
 crossing= experiment( nlength, swidth, drops);
 npi=        evaluate( nlength, swidth, drops, crossing);
 printf( "needle length=%f\nstripes width=%f\ndrops=%ld\ncrossing=%ld\npi~%.6f\n", nlength, swidth, drops, crossing, npi);
 
 return(0);
}
コード例 #12
0
ファイル: particle.cpp プロジェクト: antonioaraujob/omopep
int Particle::getNewParameterAPs(int channel, double minChannelTime, double maxChannelTime)
{
    //qDebug("Mutation::getNewParameterAPs(%d, %f, %f)", channel, minChannelTime, maxChannelTime);

    // base de datos de experimentos
    QString database("test_18.1.db");
    // tipo de experimento para extraer las muestras: full -> full scanning
    QString experiment("full");
    Scan scan(database.toStdString(),experiment.toStdString());
    scan.init();

    Scan::ScanResults results;

    results = scan.execute(channel, minChannelTime, maxChannelTime);

    //qDebug("** nuevo parametro AP: %d", results.size());
    return results.size();


}
コード例 #13
0
int main()
{
	long i;

	for (i = 0; i < samples; i++)
	{
		critical_histogram[i] = 0;
	}

	for (i = 0; i < experiments; i++)	
	{
		printf("%d...",i);
		experiment();
		critical_histogram[sample_critical] += 1;
	}

	fprint_experiment();
	fprint_histogram();

	printf("\nSimulation complete. Press any key to exit.\n");

	getchar();
	return 0;
}
コード例 #14
0
ファイル: experiment.cpp プロジェクト: ipab-rad/ICRIN
int main(int argc, char* argv[]) {
  ros::init(argc, argv, "experiment");
  ros::NodeHandle nh("experiment");
  Experiment experiment(&nh);

  std::signal(SIGINT, Experiment::interrupt);

  ros::Rate r(10);
  CLEAR();
  INFO("Experiment launch complete. Press Enter to continue or q to exit" <<
       std::endl);
  experiment.waitReturn();
  // Publish goals or plans for first time
  experiment.pubGoals();
  experiment.pubPlans(false);
  // Setup Environments
  INFO("Please launch robot environments now" << std::endl);
  // experiment.waitReturn();
  while (!Experiment::isInterrupted()) {
    if (experiment.checkReadyRobots()) {break;}
    ros::spinOnce();
    r.sleep();
  }
  if (experiment.robotsReady() && !Experiment::isInterrupted()) {
    INFO("All active robots ready" << std::endl);
  } else {
    WARN("Some robots are not ready!" << std::endl);
  }

  // Setup Robots
  if (!Experiment::isInterrupted()) {
    std::vector<std::string> robots = experiment.getRobots();
    for (size_t i = 0; i < robots.size(); ++i) {
      size_t robot_no = i;
      // INFO("Please enter start goal number" << std::endl);
      // experiment.waitReturn();
      uint16_t goal_no = 1;
      INFO("Press enter to perform setup for " << robots[i] << " (q to exit)" <<
           std::endl);
      experiment.waitReturn();
      experiment.setupPlan(robot_no, goal_no);
      experiment.pubPlans(true);
      experiment.setPlanning(robot_no, true);
      experiment.pubPlanning();
      while (experiment.isPlanning(robot_no) && !Experiment::isInterrupted()) {
        ros::spinOnce();
        ROS_INFO("Checking if plan ended");
        ROS_INFO_STREAM(experiment.isPlanning(robot_no) << std::endl);
        r.sleep();
      }
      INFO("Robot " << robots[i] << " finished setting up" << std::endl);
    }
  }
  // Robots move into area or initial goal

  // Run experiment
  if (!Experiment::isInterrupted()) {
    INFO("All robots are setup for experiment. Press enter to proceed. (q to exit)"
         << std::endl);
    experiment.waitReturn();
  }
  while (ros::ok() && !Experiment::isInterrupted()) {
    ros::spinOnce();
    // Publish goals or plans if they have changed
    r.sleep();
  }
  experiment.stopExperiment();

  return 0;
}
コード例 #15
0
ファイル: TestPca.cpp プロジェクト: vanthonguyen/m2
int main(int argc, char **argv){
/*    char *testFolder;
    if(argc > 1){
        testFolder = argv[1];
    }else{
        testFolder = TEST_FOLDER;
    }
*/
    std::vector<cv::Mat> type1s;
    std::vector<cv::Mat> type2s;
    std::vector<std::string> listFile;                                                                                                                      
    //read images of type 1 in folder and get list descriptors
    listFile = IO::getFilesInFolder(TYPE1_FOLDER);
    std::random_shuffle(listFile.begin(), listFile.end());

    for(unsigned int i = 0; i < listFile.size(); i++){
        std::string fileName = TYPE1_FOLDER + listFile[i];
        cv::Mat image = cv::imread(fileName, CV_LOAD_IMAGE_GRAYSCALE);
        //cv::threshold(image, image, THRESHOLD_GRAY_LEVEL, 255, CV_THRESH_TRUNC);
        //cv::GaussianBlur(image, image, cv::Size(3, 3), 0, 0, cv::BORDER_DEFAULT);
        type1s.push_back(Utils::getHeader(image, RATIO));
    }

    std::vector<std::string> listFile2 = IO::getFilesInFolder(TYPE2_FOLDER);
    std::random_shuffle(listFile2.begin(), listFile2.end());
    for(unsigned int i = 0; i < listFile2.size(); i++){                     
        std::string fileName = TYPE2_FOLDER + listFile2[i];
        cv::Mat image = cv::imread(fileName, CV_LOAD_IMAGE_GRAYSCALE);
       // cv::GaussianBlur(image, image, cv::Size(3, 3), 0, 0, cv::BORDER_DEFAULT);
        type2s.push_back(Utils::getHeader(image, RATIO));
    }


    std::vector<cv::Mat> others;
    std::vector<std::string> listFileAutre = IO::getFilesInFolder(AUTRE_FOLDER);
    std::random_shuffle(listFileAutre.begin(), listFileAutre.end());

    for(unsigned int i = 0; i < listFileAutre.size(); i++){                     
        std::string fileName = AUTRE_FOLDER + listFileAutre[i];
        cv::Mat image = cv::imread(fileName, CV_LOAD_IMAGE_GRAYSCALE);
        //cv::GaussianBlur(image, image, cv::Size(3, 3), 0, 0, cv::BORDER_DEFAULT);
        others.push_back(Utils::getHeader(image, RATIO));
    }
    //shuffle vectors
    //std::random_shuffle(type1s.begin(), type1s.end());
    //std::random_shuffle(type2s.begin(), type2s.end());
    //std::random_shuffle(others.begin(), others.end());

    unsigned int s1 = type1s.size()/3;
    unsigned int s2 = type2s.size()/3;
    unsigned int s3 = others.size()/3;

    for(int i = 0; i < 3; i++){
        if(i != 2){
            std::vector<cv::Mat> validation(type1s.begin() + s1 * i, type1s.begin() + s1 * (i + 1) );
            std::vector<cv::Mat> type1Train(type1s);
            type1Train.erase(type1Train.begin() + s1 * i, type1Train.begin() + s1 * (i + 1));

            std::vector<std::string> validationFileNames(listFile.begin() + s1 * i, listFile.begin() + s1 * (i + 1) ); 

            validation.insert(validation.end(), type2s.begin() + s2 * i, type2s.begin() + s2 * (i + 1) );
            std::vector<cv::Mat> type2Train(type2s);
            type2Train.erase(type2Train.begin() + s2 * i, type2Train.begin() + s2 * (i + 1));
            validationFileNames.insert(validationFileNames.end(), 
                    listFile2.begin() + s2 * i, listFile2.begin() + s2 * (i + 1));

            validation.insert(validation.end(), others.begin() + s3 * i, others.begin() + s3 * (i + 1) );
            std::vector<cv::Mat> type3Train(others);
            type3Train.erase(type3Train.begin() + s3 * i, type3Train.begin() + s3 * (i + 1));
            validationFileNames.insert(validationFileNames.end(), 
                    listFileAutre.begin() + s3 * i, listFileAutre.begin() + s3 * (i + 1));
//debug(validation.size());
//debug(validationFileNames.size());
//debug(type1Train.size());
//debug(type2Train.size());
            experiment(type1Train, type2Train, type3Train, validation, validationFileNames);
        }else{
            std::vector<cv::Mat> validation(type1s.begin() + s1 * i, type1s.end() );
            std::vector<cv::Mat> type1Train(type1s);
            type1Train.erase(type1Train.begin() + s1 * i, type1Train.end());

            std::vector<std::string> validationFileNames (listFile.begin() + s1 * i, listFile.end() ); 

            validation.insert(validation.end(), type2s.begin() + s2 * i, type2s.end() );
            std::vector<cv::Mat> type2Train(type2s);
            type2Train.erase(type2Train.begin() + s2 * i, type2Train.end());
            validationFileNames.insert(validationFileNames.end(), 
                    listFile2.begin() + s2 * i, listFile2.end());

            validation.insert(validation.end(), others.begin() + s3 * i, others.end() );
            std::vector<cv::Mat> type3Train(others);
            type3Train.erase(type3Train.begin() + s3 * i, type3Train.end());
            validationFileNames.insert(validationFileNames.end(), 
                    listFileAutre.begin() + s3 * i, listFileAutre.end());
            experiment(type1Train, type2Train, type3Train, validation, validationFileNames);
        }
    }
    return 0;
}
コード例 #16
0
ファイル: latencytest.c プロジェクト: CoryXie/BarrelfishOS
// called when we receive a signal
static void busy_ping(struct bench_binding *b)
{
    signal_received = true;
    experiment();
}
コード例 #17
0
ファイル: latencytest.c プロジェクト: CoryXie/BarrelfishOS
// continue experiment
static void experiment_cont(void* arg)
{

    errval_t err;
    static bool flag = false;
    static int message_type = 0;

    // Experiment finished (with this message type)
    if (i == MAX_COUNT - 1) {

#if CONFIG_TRACE
#else
        // print measured times
        for (int j = MAX_COUNT / 10; j < MAX_COUNT; j++) {

            printf(
                    "page %d took %"PRIuCYCLES"\n",
                    j,
                    timestamps[j].time1 - bench_tscoverhead()
                            - timestamps[j].time0);
        }
#endif
        // go to next message type
        message_type++;
        flag = false;
        i = 0;
        if (message_type > 13) {

            // stop tracing
            err = trace_event(TRACE_SUBSYS_MULTIHOP,
                    TRACE_EVENT_MULTIHOP_BENCH_STOP, 0);
            if (err_is_fail(err)) {
                USER_PANIC_ERR(err, "trace_event failed");
            }

#if CONFIG_TRACE
            // dump trace
            char *buf = malloc(50*4096*4096);
            size_t length = trace_dump(buf, 20*4096*4096, NULL);
            printf("%s\n", buf);
            printf("length of buffer %lu\n", length);
#endif
            printf("client done!\n");
            return;
        }
    }

    if (!flag) { // Start experiment

#if CONFIG_TRACE
#else
        printf("Running latency test for message %s...\n",
                get_message_name(message_type));
#endif
        flag = true;
        timestamps[i].time0 = bench_tsc();
    } else { // Continue experiment
        i++;
        timestamps[i].time0 = bench_tsc();
    }

    // trace send event
    err = trace_event(TRACE_SUBSYS_MULTIHOP, TRACE_EVENT_MULTIHOP_MESSAGE_SEND,
            message_type);
    if (err_is_fail(err)) {
        USER_PANIC_ERR(err, "trace_event failed");
    }

    // send next message
    switch (message_type) {
    case 0:
        err = binding->tx_vtbl.fsb_empty_request(binding, NOP_CONT);
        break;
    case 1:
        err = binding->tx_vtbl.fsb_payload32_1_request(binding, NOP_CONT, 1);
        break;

    case 2:
        err = binding->tx_vtbl.fsb_payload32_2_request(binding, NOP_CONT, 1, 2);
        break;

    case 3:
        err = binding->tx_vtbl.fsb_payload32_4_request(binding, NOP_CONT, 1, 2,
                3, 4);
        break;

    case 4:
        err = binding->tx_vtbl.fsb_payload32_8_request(binding, NOP_CONT, 1, 2,
                3, 4, 5, 6, 7, 8);
        break;

    case 5:
        err = binding->tx_vtbl.fsb_payload32_16_request(binding, NOP_CONT, 1, 2,
                3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
        break;

    case 6:
        err = binding->tx_vtbl.fsb_payload64_1_request(binding, NOP_CONT, 1);
        break;

    case 7:
        err = binding->tx_vtbl.fsb_payload64_2_request(binding, NOP_CONT, 1, 2);
        break;

    case 8:
        err = binding->tx_vtbl.fsb_payload64_4_request(binding, NOP_CONT, 1, 2,
                3, 4);
        break;

    case 9:
        err = binding->tx_vtbl.fsb_payload64_8_request(binding, NOP_CONT, 1, 2,
                3, 4, 5, 6, 7, 8);
        break;

    case 10:
        err = binding->tx_vtbl.fsb_payload64_16_request(binding, NOP_CONT, 1, 2,
                3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
        break;

    case 11:
        err = binding->tx_vtbl.fsb_buffer_request(binding, NOP_CONT, &buffer,
                1);
        break;

    case 12:
        err = binding->tx_vtbl.fsb_buffer_request(binding, NOP_CONT, buffer2,
                100);
        break;

    case 13:
        err = binding->tx_vtbl.fsb_buffer_request(binding, NOP_CONT, buffer3,
                1000);
        break;

    default:
        printf("unknown message type\n");
        abort();
        break;
    }

    // make sure send was successful
    if (err_is_fail(err)) {
        USER_PANIC_ERR(err, "while running experiment\n");
    }

    // receive reply (by dispatching events from the
    // waitset we use for the benchmark)
    while (reply_received == false) {
        event_dispatch(&signal_waitset);
    }

    experiment();
}
コード例 #18
0
ファイル: gen.cpp プロジェクト: antonioaraujob/omocac3cli-v2
double Gen::getFONC()
{

    // verificar el parametro indiceParaOrdenarTablaC que especifica el indice a utilizar
    int index = MainWindow::getIndexToSortCTable();

    QString database("test_18.1.db");

    // tipo de experimento para extraer las muestras: full -> full scanning
    QString experiment("full");

    //Scan scan(database.toStdString(),experiment.toStdString());
    ScanningCampaing scan(database.toStdString(),experiment.toStdString(), 0);
    scan.init();
    scan.prepareIRD();

    // sumatorio de APs en min
    double minAPsum = 0;

    // APs promedio encontrados con min
    double APmin = 0;

    // sumatorio de APs en min
    double maxAPsum = 0;

    // APs promedio encontrados con min
    double APmax = 0;

    // valor del indice para el gen
    double fonc = 0;

    for (int i=0; i<30; i++)
    {
        // (ch, min, 0) corresponde a los APs encontrados con minchanneltime
        minAPsum = minAPsum + scan.getAPs(channel, minChannelTime, 0);
    }
    APmin = minAPsum/30;

    for (int i=0; i<30; i++)
    {
        // (ch, min, max) corresponde a los APs encontrados con maxchanneltime
        maxAPsum = maxAPsum + scan.getAPs(channel, minChannelTime, maxChannelTime);
    }
    APmax = maxAPsum/30;

    if (index == 0)
    {
        // si maxChannelTime es cero no se suman los aps encontrados con max
        if (maxChannelTime ==0)
        {
            fonc = (APmin/minChannelTime);
        }
        else
        {
            fonc = (APmin/minChannelTime)*0.2 + (std::abs(APmax-APmin)/maxChannelTime)*0.8;
        }
    }
    else if (index == 1)
    {
        // si maxChannelTime es cero no se suman los aps encontrados con max
        if (maxChannelTime ==0)
        {
            fonc = (APmin/minChannelTime);
        }
        else
        {
            fonc = (APmin/minChannelTime)*0.4 + (std::abs(APmax-APmin)/maxChannelTime)*0.6;
        }
    }
    else // index == 2
    {
        // si maxChannelTime es cero no se suman los aps encontrados con max
        if (maxChannelTime ==0)
        {
            fonc = (APmin/minChannelTime);
        }
        else
        {
            //fonc = (APmin/minChannelTime)*0.6 + (std::abs(APmax-APmin)/maxChannelTime)*0.4;

            // para prueba de simulation200gFONC 0.7 y 0.3
            fonc = (APmin/minChannelTime)*0.7 + (std::abs(APmax-APmin)/maxChannelTime)*0.3;
        }
    }
    return fonc;
}
コード例 #19
0
ファイル: mpimain.cpp プロジェクト: GiorgosMethe/RobotMaze
void runOrContinueExperiment(HCUBE::MPIExperimentRun &experimentRun)
{
  int  numtasks, rank;

  MPI_Comm_size(MPI_COMM_WORLD,&numtasks);
  MPI_Comm_rank(MPI_COMM_WORLD,&rank);

  if (rank==0)
  {
    experimentRun.setCleanup(true);

    cout << rank << ") Population Created\n";

    experimentRun.start();

    int numThreads;

    MPI_Comm_size(MPI_COMM_WORLD,&numThreads);

    cout << "Number of threads to kill: " << numThreads << endl;

    for (rank = 1; rank < numThreads; ++rank) 
    {
      MPI_Send(0, 0, MPI_INT, rank, DIE_TAG, MPI_COMM_WORLD);
    }

  }
  else
  {
    shared_ptr<HCUBE::Experiment> experiment(
      experimentRun.getExperiment()->clone()
      );

    //cout << "Experiment pointer: " << experiment << endl;

    char *buffer=NULL;
    int bufferSize=0;

    int curGenNumber=0;
    if(experimentRun.getPopulation())
    {
        cout << "Resuming at generation: " << experimentRun.getPopulation()->getGenerationCount()-1 << endl;
        curGenNumber=experimentRun.getPopulation()->getGenerationCount()-1;
    }
    for(;;curGenNumber++)
    {
#if DEBUG_MPI_MAIN
      cout << rank << ") Listening for individual chunk size...\n";
#endif

      int msgSize;

      {
        MPI_Status Stat;
        MPI_Recv (&msgSize,1,MPI_INT,0,MPI_ANY_TAG,MPI_COMM_WORLD,&Stat);

        if(Stat.MPI_TAG==DIE_TAG)
        {
          break;
        }
      }

#if DEBUG_MPI_MAIN
      cout << rank << ") Got chunk size: " << msgSize << endl;
#endif

      if (msgSize==-1)
      {
        break;
      }

      if (msgSize==0)
      {
        continue; // ????  This shouldn't happen, but handle anyways
      }

      if (bufferSize<msgSize)
      {
        bufferSize = msgSize;
        buffer = (char*)realloc(buffer,bufferSize);
      }

      memset(buffer,0,bufferSize);

#if DEBUG_MPI_MAIN
      cout << rank << ") Getting buffer...\n";
#endif

      {
        MPI_Status Stat;
        MPI_Recv (buffer,msgSize,MPI_CHAR,0,INDIVIDUAL_GENOMES_TAG,MPI_COMM_WORLD,&Stat);
      }

#if DEBUG_MPI_MAIN
      cout << rank << ") Got Buffer\n";

      //cout << buffer << endl;
#endif

      istringstream istr(buffer);

#if DEBUG_MPI_MAIN
      cout << rank << ") Loaded stringstream\n";
#endif


      int testCount;
      istr >> testCount;


      shared_ptr<NEAT::GeneticGeneration> generation;

#ifdef EPLEX_INTERNAL
      if(testCount)
      {
        generation = shared_ptr<NEAT::GeneticGeneration>(
          new NEAT::CoEvoGeneticGeneration(
            0,
            dynamic_pointer_cast<NEAT::CoEvoExperiment>(experiment)
            )
          );
      }
      else
#endif
      {
        generation = shared_ptr<NEAT::GeneticGeneration>(
          new NEAT::GeneticGeneration(curGenNumber)
          );
      }

#if DEBUG_MPI_MAIN
      cout << rank << ") Test count: " << testCount << endl;
#endif

#ifdef EPLEX_INTERNAL
      for(int a=0;a<testCount;a++)
      {
        shared_ptr<NEAT::GeneticIndividual> testInd(new NEAT::GeneticIndividual(istr));

        shared_ptr<NEAT::CoEvoGeneticGeneration> coEvoGen =
          static_pointer_cast<NEAT::CoEvoGeneticGeneration>(generation);

        coEvoGen->addTestHack(testInd);
      }
#endif

      int individualCount;

      istr >> individualCount;

#if DEBUG_MPI_MAIN
      cout << rank << ") Individualcount: " << individualCount << endl;
#endif

      //double *newFitness = (double*)malloc(sizeof(double)*individualCount);
      ostringstream ostr;

#if DEBUG_MPI_MAIN
      cout << rank << ") Fitness buffer created\n";
#endif

      for (int a=0;a<individualCount;a+=experiment->getGroupCapacity())
      {
#if DEBUG_MPI_MAIN
		cout << rank << ") Adding to group...\n";
#endif

        for (int b=0;b<experiment->getGroupCapacity();b++)
        {
          shared_ptr<NEAT::GeneticIndividual> ind(
            new NEAT::GeneticIndividual(istr)
            );

          experiment->addIndividualToGroup(ind);
        }

#if DEBUG_MPI_MAIN
		cout << rank << ") Processing...\n";
#endif

        experiment->processGroup(generation);

#if DEBUG_MPI_MAIN
		cout << rank << ") Dumping...\n";
#endif

        for (int b=0;b<experiment->getGroupCapacity();b++)
        {
			experiment->getGroupMember(b)->dump(ostr);
          //newFitness[a+b] = experiment->getGroupMember(b)->getFitness();
        }

#if DEBUG_MPI_MAIN
		cout << rank << ") Clearing...\n";
#endif

		//Clear the experiment for the next individuals
        experiment->clearGroup();

#if DEBUG_MPI_MAIN
		cout << rank << ") End of process...\n";
#endif
	  }

#if DEBUG_MPI_MAIN
      cout << rank << ") Sending new fitness values\n";
#endif

        string str = ostr.str();

        char *buffer = new char[str.length()+1];

        memcpy(buffer,str.c_str(),str.length());

        buffer[str.length()] = '\0'; //null terminate

        int lengthInt = (int)str.length() + 1;

#if DEBUG_MPI_MAIN
      cout << rank << ") Sending message of size " << lengthInt << "\n";
#endif

      //MPI_Send (newFitness,individualCount,MPI_DOUBLE,0,NEW_FITNESSES_TAG,MPI_COMM_WORLD);
		MPI_Send (&lengthInt,1,MPI_INT,0,NEW_INDIVIDUALS_TAG,MPI_COMM_WORLD);
		MPI_Send (buffer,lengthInt,MPI_CHAR,0,NEW_INDIVIDUALS_TAG,MPI_COMM_WORLD);

#if DEBUG_MPI_MAIN
      cout << rank << ") Cleaning up new fitness values\n";
#endif

      //free(newFitness);
    }
  }
}
コード例 #20
0
ファイル: main.cpp プロジェクト: pnecchi/Thesis
int main()
{
    std::cout << "----------------------------------------------" << std::endl;
    std::cout << "-        Algorithmic Asset Allocation        -" << std::endl;
    std::cout << "----------------------------------------------" << std::endl;
    std::cout << std::endl;

    // Get algorithm
	std::string algorithm = "PGPE";

	// Get file with parameter values
	std::string parametersFilepath = "/home/pierpaolo/Documents/University/6_Anno_Poli/7_Thesis/Data/Parameters/Single_Synth_RN_P0_F0_S0_N5.pot";

    // Read input file path
    const std::string inputFile = "/home/pierpaolo/Documents/University/6_Anno_Poli/7_Thesis/Data/Input/synthetic.csv";

    // Read output directory path
    const std::string outputDir = "/home/pierpaolo/Documents/University/6_Anno_Poli/7_Thesis/Data/Output/Default/";

    // Read debug directory path
    const std::string debugDir = "/home/pierpaolo/Documents/University/6_Anno_Poli/7_Thesis/Data/Debug/Default/";

    //---------------|
    // 1) Parameters |
    //---------------|

    // 1) Read parameters
    std::cout << "1) Read parameters" << std::endl;
    const ExperimentParameters params(parametersFilepath, true);

    // Copy parameters
    double riskFreeRate = params.riskFreeRate;
    double deltaP = params.deltaP;
    double deltaF = params.deltaF;
    double deltaS = params.deltaS;
    size_t numDaysObserved = params.numDaysObserved;
    double lambda = params.lambda;
    double alphaConstActor = params.alphaConstActor;
    double alphaExpActor = params.alphaExpActor;
    double alphaConstCritic = params.alphaConstCritic;
    double alphaExpCritic = params.alphaExpCritic;
    double alphaConstBaseline = params.alphaConstBaseline;
    double alphaExpBaseline = params.alphaExpBaseline;
    size_t numExperiments = params.numExperiments;
    size_t numEpochs = params.numEpochs;
    size_t numTrainingSteps = params.numTrainingSteps;
    size_t numTestSteps = params.numTestSteps;

    //-------------------|
    // 2) Initialization |
    //-------------------|
    std::cout << std::endl << "2) Initialization" << std::endl;

    //----------------------|
    // 2.1) Market and Task |
    //----------------------|

	// Market
	std::cout << ".. Market environment - ";
	MarketEnvironment market(inputFile);
    size_t startDate = 0;
	size_t endDate = numDaysObserved + numTrainingSteps + numTestSteps - 1;
    market.setEvaluationInterval(startDate, endDate);
    std::cout << "done" << std::endl;

    // Asset allocation task
    std::cout << ".. Asset allocation task - ";
	AssetAllocationTask task(market,
                             riskFreeRate,
                             deltaP,
                             deltaF,
                             deltaS,
                             numDaysObserved);
    std::cout << "done" << std::endl;

    //------------|
    // 2.2) Agent |
    //------------|

    // Learning Rates
    std::cout << ".. Learning Rates - ";
    DecayingLearningRate baselineLearningRate(alphaConstBaseline, alphaExpBaseline);
    DecayingLearningRate criticLearningRate(alphaConstCritic, alphaExpCritic);
    DecayingLearningRate actorLearningRate(alphaConstActor, alphaExpActor);
    std::cout << "done" << std::endl;

    // Initialize Agent factory
    auto & factory(FactoryOfAgents::instance(task.getDimObservation(),
                                             baselineLearningRate,
                                             criticLearningRate,
                                             actorLearningRate,
                                             lambda));

    // Pointer to Agent for poymorphic object handling
    std::unique_ptr<Agent> agentPtr = factory.make(algorithm);

    //----------------------------------|
    // 2.3) Asset Allocation Experiment |
    //----------------------------------|

    std::cout << ".. Asset allocation experiment - ";
    AssetAllocationExperiment experiment(task,
                                         *agentPtr,
                                         numExperiments,
                                         numEpochs,
                                         numTrainingSteps,
                                         numTestSteps,
                                         outputDir,
                                         debugDir);
    std::cout << "done" << std::endl;

    //-------------------|
    // 3) Run experiment |
    //-------------------|

    std::cout << std::endl << "2) Experiment" << std::endl;
    experiment.run();

	return 0;
}
コード例 #21
0
ファイル: comp.c プロジェクト: BackupTheBerlios/galan
PUBLIC void init_comp(void) {
  componentclasses = g_hash_table_new(g_str_hash, g_str_equal);
  experiment();
}
コード例 #22
0
int main(int argc,char **argv)
{
    try
    {
        /*
        for(int a=0;a<argc;a++)
        {
            cout << "ARGUMENT: " << argv[a] << endl;
        }
        */

        int  numtasks, rank, rc;

        rc = MPI_Init(&argc,&argv);

        if (rc != MPI_SUCCESS)
        {
            printf ("Error starting MPI program. Terminating.\n");
            MPI_Abort(MPI_COMM_WORLD, rc);
            return 1;
        }

        MPI_Comm_size(MPI_COMM_WORLD,&numtasks);
        MPI_Comm_rank(MPI_COMM_WORLD,&rank);

        for (int a=0;a<argc;a++)
        {
            cout << "ARGUMENT: " << argv[a] << endl;
        }

        if (argc==1)
        {
            cout << "You must pass the parameters and the output file as command "
            << "parameters!\n";
        }
        /*
        else if (argc==2)
        {
            //Run the post-hoc analysis on every generation
            HCUBE::ExperimentRun experimentRun;

            experimentRun.setupExperimentInProgress(
                string(argv[1]),
                ""
            );

            int numGenerations = experimentRun.getPopulation()->getGenerationCount();

            HCUBE::Experiment *experiment = experimentRun.getExperiment()->clone();

            {
                string outString = (erase_tail_copy(string(argv[1]),4)+string("_fitness.out"));
                cout << "Creating file " << outString << endl;
                ofstream outfile( outString.c_str() );
                string previousSummary;

                bool doOnce=false;

                for (int generation=0;generation<numGenerations;generation++)
                {
                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));

                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));

                    if ( generation &&
                            (*(experimentRun.getIndividual(generation,0).get())) == (*(experimentRun.getIndividual(generation-1,0).get())) )
                    {
                        outfile << (generation+1) << ' ' << previousSummary << endl;
                        continue;
                    }

                    shared_ptr<NEAT::GeneticIndividual> indiv =
                        shared_ptr<NEAT::GeneticIndividual>(
                            new NEAT::GeneticIndividual(
                                *(experimentRun.getIndividual(generation,0).get())
                            )
                        );

                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));

                    cout << "Beginning fitness evaluation " << (generation+1) << "/" << numGenerations << "...";
                    experiment->addIndividualToGroup(indiv);
                    experiment->processGroup(experimentRun.getGeneration(generation));
                    experiment->clearGroup();
                    cout << "done!\n";

                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));

                    if (indiv->getUserData())
                    {
                        if (!doOnce)
                        {
                            doOnce=true;
                            outfile
                            << "#Generation: "
                            << indiv->getUserData()->summaryHeaderToString()
                            << endl;
                        }

                        previousSummary = indiv->getUserData()->summaryToString();
                        outfile << (generation+1) << ' ' << previousSummary << endl;
                    }
                    else
                    {
                        throw CREATE_LOCATEDEXCEPTION_INFO("No user data!\n");
                    }

                }
            }

            {
                string outString = (erase_tail_copy(string(argv[1]),4)+string("_lowres.out"));
                cout << "Creating file " << outString << endl;
                ofstream outfile( outString.c_str() );
                string previousSummary;

                bool doOnce=false;

                for (int generation=0;generation<numGenerations;generation++)
                {
                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));

                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));

                    if ( generation &&
                            (*(experimentRun.getIndividual(generation,0).get())) == (*(experimentRun.getIndividual(generation-1,0).get())) )
                    {
                        outfile << (generation+1) << ' ' << previousSummary << endl;
                        continue;
                    }

                    shared_ptr<NEAT::GeneticIndividual> indiv =
                        shared_ptr<NEAT::GeneticIndividual>(
                            new NEAT::GeneticIndividual(
                                *(experimentRun.getIndividual(generation,0).get())
                            )
                        );

                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));

                    cout << "Beginning post-hoc evaluation " << (generation+1) << "/" << numGenerations << "...";
                    experiment->processIndividualPostHoc(indiv);
                    cout << "done!\n";

                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));

                    if (indiv->getUserData())
                    {
                        if (!doOnce)
                        {
                            doOnce=true;
                            outfile
                            << "#Generation: "
                            << indiv->getUserData()->summaryHeaderToString()
                            << endl;
                        }

                        previousSummary = indiv->getUserData()->summaryToString();
                        outfile << (generation+1) << ' ' << previousSummary << endl;
                    }

                }
            }


            cout << "Done with run!  Running medium resolution tests...\n";
            ((HCUBE::FindClusterExperiment*)experiment)->increaseResolution();

            {
                string outString = (erase_tail_copy(string(argv[1]),4)+string("_midres.out"));
                ofstream outfile( outString.c_str() );
                cout << "Creating file " << outString << endl;
                string previousSummary;

                bool doOnce=false;

                for (int generation=0;generation<numGenerations;generation++)
                {
                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));

                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));

                    if ( generation &&
                            (*(experimentRun.getIndividual(generation,0).get())) == (*(experimentRun.getIndividual(generation-1,0).get())) )
                    {
                        outfile << (generation+1) << ' ' << previousSummary << endl;
                        continue;
                    }

                    shared_ptr<NEAT::GeneticIndividual> indiv =
                        shared_ptr<NEAT::GeneticIndividual>(
                            new NEAT::GeneticIndividual(
                                *(experimentRun.getIndividual(generation,0).get())
                            )
                        );

                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));

                    cout << "Beginning post-hoc evaluation " << (generation+1) << "/" << numGenerations << "...";
                    experiment->processIndividualPostHoc(indiv);
                    cout << "done!\n";

                    //CREATE_PAUSE(string("Error!: ")+toString(__LINE__));

                    if (indiv->getUserData())
                    {
                        if (!doOnce)
                        {
                            doOnce=true;
                            outfile
                            << "#Generation: "
                            << indiv->getUserData()->summaryHeaderToString()
                            << endl;
                        }

                        previousSummary = indiv->getUserData()->summaryToString();
                        outfile << (generation+1) << ' ' << previousSummary << endl;
                    }

                }
            }
        }
        */
        else if (argc==3)
        {
            NEAT::Globals::init(string(argv[1]));

            int experimentType = int(NEAT::Globals::getSingleton()->getParameterValue("ExperimentType")+0.001);

            cout << "Loading Experiment: " << experimentType << endl;

            HCUBE::MPIExperimentRun experimentRun;

            experimentRun.setupExperiment(experimentType,string(argv[2]));

            cout << "Experiment set up\n";

            if (rank==0)
            {
                experimentRun.createPopulation();

                experimentRun.setCleanup(true);

                cout << "Population Created\n";

                experimentRun.start();
            }
            else
            {
                shared_ptr<HCUBE::Experiment> experiment(
			experimentRun.getExperiment()->clone()
			);

                //cout << "Experiment pointer: " << experiment << endl;

                char *buffer=NULL;
                int bufferSize=0;

                while (true)
                {
#if DEBUG_MPI_MAIN
                    cout << "Listening for individual chunk size...\n";
#endif

                    int msgSize;

                    {
                        MPI_Status Stat;
                        MPI_Recv (&msgSize,1,MPI_INT,0,1,MPI_COMM_WORLD,&Stat);
                    }

#if DEBUG_MPI_MAIN
                    cout << "Got chunk size: " << msgSize << endl;
#endif

                    if (msgSize==-1)
                    {
                        break;
                    }

                    if (msgSize==0)
                    {
                        continue; // ????  This shouldn't happen, but handle anyways
                    }

                    if (bufferSize<msgSize)
                    {
                        bufferSize = msgSize;
                        buffer = (char*)realloc(buffer,bufferSize);
                    }

                    memset(buffer,0,bufferSize);

#if DEBUG_MPI_MAIN
                    cout << "Getting buffer...\n";
#endif

                    {
                        MPI_Status Stat;
                        MPI_Recv (buffer,msgSize,MPI_CHAR,0,1,MPI_COMM_WORLD,&Stat);
                    }

#if DEBUG_MPI_MAIN
                    cout << "Got Buffer\n";

                    //cout << buffer << endl;
#endif

                    istringstream istr(buffer);

#if DEBUG_MPI_MAIN
                    cout << "Loaded stringstream\n";
#endif


							int testCount;
							istr >> testCount;


                     shared_ptr<NEAT::GeneticGeneration> generation;

			{
				generation = shared_ptr<NEAT::GeneticGeneration>(
		                        new NEAT::GeneticGeneration(0)
			                     );
			}

#if DEBUG_MPI_MAIN
			cout << "Test count: " << testCount << endl;
#endif

 							int individualCount;

                    istr >> individualCount;

#if DEBUG_MPI_MAIN
                    cout << "Individualcount: " << individualCount << endl;
#endif

                    double *newFitness = (double*)malloc(sizeof(double)*individualCount);

#if DEBUG_MPI_MAIN
                    cout << "Fitness buffer created\n";
#endif

                    for (int a=0;a<individualCount;a+=experiment->getGroupCapacity())
                    {
                        for (int b=0;b<experiment->getGroupCapacity();b++)
                        {
                            shared_ptr<NEAT::GeneticIndividual> ind(
                                new NEAT::GeneticIndividual(istr)
                            );

                            experiment->addIndividualToGroup(ind);
                        }

                        experiment->processGroup(generation);

                        for (int b=0;b<experiment->getGroupCapacity();b++)
                        {
                            newFitness[a+b] = experiment->getGroupMember(b)->getFitness();
                        }

                        //Clear the experiment for the next individuals
                        experiment->clearGroup();
                    }

#if DEBUG_MPI_MAIN
                    cout << "Sending new fitness values\n";
#endif

                    MPI_Send (newFitness,individualCount,MPI_DOUBLE,0,1,MPI_COMM_WORLD);

#if DEBUG_MPI_MAIN
                    cout << "Cleaning up new fitness values\n";
#endif

                    free(newFitness);
                }
            }
        }
        else
        {
            cout << "Invalid # of parameters (" << argc << ")!\n";
        }


        MPI_Finalize();
    }
コード例 #23
0
ファイル: pingpong_bench.c プロジェクト: pranith/sst-elements
int
main(int argc, char *argv[])
{

extern char *optarg;
int ch, error;

int len;
int start_len;
int end_len;
int inc;
int max_trials;
int user_inc;
int stat_mode;
double req_precision;
int num_ops;
int dest;
int pingping;


    MPI_Init(&argc, &argv);

    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
    MPI_Comm_size(MPI_COMM_WORLD, &num_nodes);

    if (num_nodes < 2)   {
	if (my_rank == 0)   {
	    fprintf(stderr, "Need to run on at least two nodes\n");
	}
	exit(-1);
    }

    /* Set the defaults */
    opterr= 0;		/* Disable getopt error printing */
    error= FALSE;
    start_len= 0;
    end_len= MAX_MSG_LEN / 8;
    inc= 8; /* this inc will be set dynamically */
    user_inc= -1;
    stat_mode= TRUE;
    req_precision= DEFAULT_PRECISION;
    dest= num_nodes - 1;
    pingping= FALSE;


    /* check command line args */
    while ((ch= getopt(argc, argv, "ad:e:i:p:s:")) != EOF)   {
	switch (ch)   {
	    case 'a':
		pingping= TRUE;
		break;

	    case 'd':
		dest= strtol(optarg, (char **)NULL, 0);
		if ((dest < 0) || (dest >= num_nodes))   {
		    if (my_rank == 0)   {
			fprintf(stderr, "# destination (-d) must be 0 <= %d < n (%d)\n",
			    dest, num_nodes);
		    }
		    error= TRUE;
		}
		break;

	    case 'e':
		end_len= strtol(optarg, (char **)NULL, 0);
		if (end_len > MAX_MSG_LEN)   {
		    if (my_rank == 0)   {
			fprintf(stderr, "# Maximum end length is %d\n", MAX_MSG_LEN);
		    }
		    error= TRUE;
		}
		break;

	    case 'i':
		user_inc= strtol(optarg, (char **)NULL, 0);
		break;

            case 'p':
		req_precision= strtod(optarg, (char **)NULL);
		if (req_precision == 0.0)   {
		    stat_mode= FALSE;
		}
		break;

	    case 's':
		start_len= strtol(optarg, (char **)NULL, 0);
		if (start_len < 0)   {
		    if (my_rank == 0)   {
			fprintf(stderr, "# Minimum start length is %d\n", 0);
		    }
		    error= TRUE;
		}
		break;

	    /* Command line error checking */
	    DEFAULT_CMD_LINE_ERR_CHECK
	}
    }

    if (error)   {
	if (my_rank == 0)   {
	    fprintf(stderr, "Usage: %s [-a] [-d destination] [-s start_length] [-e end_length] [-i inc] [-p precision]\n",
		argv[0]);
	    fprintf(stderr, "           -a            Do ping-ping instead of ping-pong\n");
	    fprintf(stderr, "           -d            Destination rank. Default is n - 1\n");
	}
	exit (-1);
    }

    if (stat_mode)   {
	max_trials= MAX_TRIALS;
    } else   {
	max_trials= 1;
    }

    if (my_rank == 0)   {
	if (pingping)   {
	    printf("# Ping-Ping benchmark\n");
	} else   {
	    printf("# Ping-pong benchmark\n");
	}
	printf("# ------------------\n");
	disp_cmd_line(argc, argv);
	printf("#\n");
	if (user_inc > 0)   {
	    printf("# Running experiments of length %d through %d in increments of %d\n", 
		start_len, end_len, user_inc);
	} else   {
	    printf("# Running experiments of length %d through %d increasing increments\n", 
		start_len, end_len);
	}
	printf("# Exchanging data between nodes %d and %d of, %d nodes\n", 0, dest, num_nodes);
	if (stat_mode)   {
	    printf("# Requested precision is %.3f%%\n", req_precision * 100.0);
	} else   {
	    printf("# Statistics mode is off\n");
	}
	printf("#\n");
	printf("# Length                  Latency\n");
	printf("# in bytes            in micro seconds\n");
	printf("#            minimum         mean       median      maximum           sd       precision  trials\n");
    }

    len= start_len;

    while (len <= end_len)   {
	
	if (len < SHORT_MEDIUM_CUTOFF)   {
	    num_ops= SHORT_MSG_OPS;
	} else if (len < MEDIUM_LONG_CUTOFF)   {
	    num_ops= MEDIUM_MSG_OPS;
	} else   {
	    num_ops= LONG_MSG_OPS;
	}

	if (pingping)   {
	    experiment(my_rank, max_trials, num_ops, len, dest, req_precision,
		&do_one_Test2_trial);
	} else   {
	    experiment(my_rank, max_trials, num_ops, len, dest, req_precision,
		&do_one_Test1_trial);
	}

	if (user_inc <= 0)   {
	    if (len >= (inc << 4))   {
		inc= inc << 1;
	    }
	    len= len + inc;
	} else   {
	    len= len + user_inc;
	}
    }

    MPI_Finalize();

    return 0;

}  /* end of main() */
コード例 #24
0
ファイル: random_demo.cpp プロジェクト: 0xDEC0DE8/mcsema
int main()
{
  // Define a random number generator and initialize it with a reproducible
  // seed.
  base_generator_type generator(42);

  std::cout << "10 samples of a uniform distribution in [0..1):\n";

  // Define a uniform random number distribution which produces "double"
  // values between 0 and 1 (0 inclusive, 1 exclusive).
  boost::uniform_real<> uni_dist(0,1);
  boost::variate_generator<base_generator_type&, boost::uniform_real<> > uni(generator, uni_dist);

  std::cout.setf(std::ios::fixed);
  // You can now retrieve random numbers from that distribution by means
  // of a STL Generator interface, i.e. calling the generator as a zero-
  // argument function.
  for(int i = 0; i < 10; i++)
    std::cout << uni() << '\n';

  /*
   * Change seed to something else.
   *
   * Caveat: std::time(0) is not a very good truly-random seed.  When
   * called in rapid succession, it could return the same values, and
   * thus the same random number sequences could ensue.  If not the same
   * values are returned, the values differ only slightly in the
   * lowest bits.  A linear congruential generator with a small factor
   * wrapped in a uniform_smallint (see experiment) will produce the same
   * values for the first few iterations.   This is because uniform_smallint
   * takes only the highest bits of the generator, and the generator itself
   * needs a few iterations to spread the initial entropy from the lowest bits
   * to the whole state.
   */
  generator.seed(static_cast<unsigned int>(std::time(0)));

  std::cout << "\nexperiment: roll a die 10 times:\n";

  // You can save a generator's state by copy construction.
  base_generator_type saved_generator = generator;

  // When calling other functions which take a generator or distribution
  // as a parameter, make sure to always call by reference (or pointer).
  // Calling by value invokes the copy constructor, which means that the
  // sequence of random numbers at the caller is disconnected from the
  // sequence at the callee.
  experiment(generator);

  std::cout << "redo the experiment to verify it:\n";
  experiment(saved_generator);

  // After that, both generators are equivalent
  assert(generator == saved_generator);

  // as a degenerate case, you can set min = max for uniform_int
  boost::uniform_int<> degen_dist(4,4);
  boost::variate_generator<base_generator_type&, boost::uniform_int<> > deg(generator, degen_dist);
  std::cout << deg() << " " << deg() << " " << deg() << std::endl;
  
  {
    // You can save the generator state for future use.  You can read the
    // state back in at any later time using operator>>.
    std::ofstream file("rng.saved", std::ofstream::trunc);
    file << generator;
  }

  return 0;
}
コード例 #25
0
ファイル: particle.cpp プロジェクト: antonioaraujob/omopep
Particle::Particle(int numberOfApsDeployed, int maxSpeed)
{
    //qsrand((uint)QTime::currentTime().msec());

    // asignar el valor unico del identificador del individuo
    particleId = Simulation::getNewParticleId();


    // se deben crear los 33 parametros
    // C1,Min1,Max1,AP1,C2,Min2,Max2,AP2,...,C11,Min11,Max11,AP11


    // base de datos sqlite
    //QString database("/home/antonio/Copy/2014/pgcomp/ia/gridCells/gridCells/test_18.1.db");
    //QString database("/home/antonio/desarrollo/iaa/git/omocac/test_18.1.db");
    QString database("test_18.1.db");

    // tipo de experimento para extraer las muestras: full -> full scanning
    QString experiment("full");

    Scan scan(database.toStdString(),experiment.toStdString());
    scan.init();

    //Scan::ScanResults results = scan.execute(11, 10, 30);
    Scan::ScanResults results;

    std::cout << results.size() << " results: " << std::endl;

    int randomChannel = 0;
    double minChannelTime = 0;
    double maxChannelTime = 0;

    for (int i=0; i<11; i++)
    {
        randomChannel = getRandomChannel();
        parametersList.append(randomChannel);

        minChannelTime = getRandomMinChannelTime();
        maxChannelTime = getRandomMaxChannelTime();
        parametersList.append(minChannelTime);
        parametersList.append(maxChannelTime);

        //parametersList.append(getAPNumberOnChannel(numberOfApsDeployed, randomChannel));

        //qDebug("**channel: %d, min: %f, max: %f",randomChannel, minChannelTime, maxChannelTime);
        results = scan.execute(randomChannel, minChannelTime, maxChannelTime);
        //qDebug("**numero de APs encontrados en el canal %d: %d",randomChannel, results.size());
        //std::cout << " numero de APs encontrados en el canal: " << randomChannel << ": " << results.size() << std::endl;
        //qDebug("**scan.execute(%d, %f, %f)=%d",randomChannel, minChannelTime, maxChannelTime, results.size());
        parametersList.append(results.size());

        wonMatchesCounter = 0;
    }


    // lista de velocidades por parametro
    // ...
    for (int i=0; i<44; i++)
    {
        velocitityList.append(getRandomSpeed(maxSpeed));
    }


    // calcular el valor de desempeno para el individuo
    calculatePerformanceValue();

    // calcular el valor de desempeno para la descubierta
    //setPerformanceDiscovery(getRandomMaxChannelTime());
    calculateDiscoveryValue();

    // calcular el valor de desempeno para la latencia
    //setPerformanceLatency(getRandomMaxChannelTime());
    calculateLatencyValue();


    // inicializar el diccionario de canales utilizados en el vuelo en falso
    for (int i=1; i<=11;i++)
    {
        channelsUsedForFly[i]=false;
    }
}
コード例 #26
0
int main(void)
{
	initial();
	
	//comb(0,0);

	//printf("sum is %d",sum);

	//for (int i = 0; i < 210; i++){
	//	for (int j = 0; j < 6; j++)	{
	//		printf("%d ",idx_6_10[i][j]);
	//	}
	//	printf("\n");
	//}
	//getchar();



	experiment();



	// ---------- block start end test ---------------
	
	

// 	int s = (rand() % (5- 1 + 1)) + 1; // [1,5]
// 	int x1 = (rand() % ( (10-2*s) - 0 +1)) + 0;
// 	int x2 = x1 + s -1;
// 
// 	int y1 = (rand() % ( (10-s) - (x2+1) +1)) + (x2+1);
// 	int y2 = y1 + s -1;
// 	printf("step %d, x1 %d x2 %d, y1 %d y2 %d\n", s,x1,x2,y1,y2);


	// --------------- penalty test -----------------
	//Load("instance\\sprint04.txt");
	//char s[NURSE_NUM][DAY_NUM] = {0};
	//solutionCreate(s);
	//printf("value is %d", evaluate(s));
	//solutionRosterShowScreen(s);
	//getchar();
	//showPenaltySpec();
	//for( int i = 0; i < nurseTotal; i++)
	//	printf("nurse %d, total penalty is %d\n", nursePenRec[i].idx,nursePenRec[i].total);

	//
	////for( int i = 0; i < nurseTotal; i++)

	//printf("\n");
	//qsort(nursePenRec,NURSE_NUM,sizeof(nursePenRec[0]),cmp);

	//for( int i = 0; i < nurseTotal; i++)
	//	printf("nurse %d, total penalty is %d\n", nursePenRec[i].idx,nursePenRec[i].total);




	// --------------- compare -----------------
  	
	//Load("instance\\sprint04.txt");
 // 	char lv[NURSE_NUM][DAY_NUM] = {0};
 // 	solutionStandardRead(lv,"solutions\\zzrSolu_s04_59.txt");
	////solutionCreate(lv);

 // 	solutionRosterShowScreen(lv);
 // 	printf("value is %d", evaluate(lv));
 // 	showPenaltySpec();

	//for( int i = 0; i < nurseTotal; i++)
	//	printf("nurse %d, has a pen of workingday of %d\n", i,nursePenRec[i].workingday);
	//
	//for( int i = 0; i < nurseTotal; i++)
	//	printf("nurse %d, total penalty is %d\n", i,nursePenRec[i].total);


	//char zz[NURSE_NUM][DAY_NUM] = {0};
	//solutionStandardRead(zz,"solutions\\zzrSolu_s04_60.txt");
	//	solutionRosterShowScreen(zz);
	//printf("value is %d", evaluate(zz));
	//showPenaltySpec();
	//
	//for( int i = 0; i < nurseTotal; i++){
	//	printf("nurse %d, has a pen of workingday of %d\n", i,nursePenRec[i].workingday);
	//}

	//
	//printf("\ndistance of shift is %d", distanceShift(lv,zz));
	//printf("\ndistance of working day is %d", distanceWorkingDay(lv,zz));
	

	//int a[10];
	//randomNurseGen(a,10);

// 	int a[4];
// 	randomDayGen(a, 4);

	//--------------------------------- test solution create -------------------------------
	//char s[NURSE_NUM][DAY_NUM] = {0};
	//solutionCreate(s);


	//---------------------------------- search ------------------------
	//for(int i = 0; i < 1; i++)
	

	// read the optimal solution
 	//char s[NURSE_NUM][DAY_NUM] = {0};
 	//solutionRead(s);

	
	//printf("game over\n");
	//getchar();
	
	return 0;
	

}
コード例 #27
0
ファイル: main.cpp プロジェクト: vanthonguyen/m2
int main(int argc, char** argv){
	int numberCluster = 3;
	for (int i = 1; i < argc; i++) {
		const char* s = argv[i];
		if (strcmp(s, "-k") == 0) {
			numberCluster = atoi(argv[++i]);
		} else {
			std::cout << "not recognize command" << std::endl;
			return -1;
		}
	}

	std::vector<std::string> listFile1, listFile2, listFile3;
	listFile1 = IO::getFilesInFolder(TYPE1_FOLDER);
	listFile2 = IO::getFilesInFolder(TYPE2_FOLDER);
	listFile3 = IO::getFilesInFolder(AUTRE_FOLDER);

    //shuffle vectors
    std::random_shuffle(listFile1.begin(), listFile1.end());
    std::random_shuffle(listFile2.begin(), listFile2.end());
    std::random_shuffle(listFile3.begin(), listFile3.end());

    unsigned int s1 = listFile1.size()/3;
    unsigned int s2 = listFile2.size()/3;
    unsigned int s3 = listFile3.size()/3;
std::cout << s1 << " " << s2 << " " << s3 << std::endl;

    for(int i = 0; i < 3; i++){
    	std::vector<std::string> listFile1Train(listFile1);
    	std::vector<std::string> listFile2Train(listFile2);
    	std::vector<std::string> listFile3Train(listFile3);
    	std::vector<std::string> listFileValidation;

		if (i != 2) {
			listFileValidation.insert(listFileValidation.end(),
					listFile1Train.begin() + s1 * i,
					listFile1Train.begin() + s1 * (i + 1));
			listFileValidation.insert(listFileValidation.end(),
					listFile2Train.begin() + s2 * i,
					listFile2Train.begin() + s2 * (i + 1));
			listFileValidation.insert(listFileValidation.end(),
					listFile3Train.begin() + s3 * i,
					listFile3Train.begin() + s3 * (i + 1));

			listFile1Train.erase(listFile1Train.begin() + s1 * i,
					listFile1Train.begin() + s1 * (i + 1));
			listFile2Train.erase(listFile2Train.begin() + s2 * i,
					listFile2Train.begin() + s2 * (i + 1));
			listFile3Train.erase(listFile3Train.begin() + s3 * i,
					listFile3Train.begin() + s3 * (i + 1));

			experiment(listFile1Train, listFile2Train,
					listFile3Train, listFileValidation, numberCluster);
		} else {
			listFileValidation.insert(listFileValidation.end(),
					listFile1Train.begin() + s1 * i, listFile1Train.end());
			listFileValidation.insert(listFileValidation.end(),
					listFile2Train.begin() + s2 * i, listFile2Train.end());
			listFileValidation.insert(listFileValidation.end(),
					listFile3Train.begin() + s3 * i, listFile3Train.end());

			listFile1Train.erase(listFile1Train.begin() + s1 * i,
					listFile1Train.end());
			listFile2Train.erase(listFile2Train.begin() + s2 * i,
					listFile2Train.end());
			listFile3Train.erase(listFile3Train.begin() + s3 * i,
					listFile3Train.end());

			experiment(listFile1Train, listFile2Train,
					listFile3Train,	listFileValidation, numberCluster);

		}
    }

	cv::waitKey(0);
	return 0;
}