Пример #1
0
int main(int argc, char* argv[]) {
	RandGen* rng;
	MPIWrapper mpi;
	double mGT,t,maxGT;
	int i=0;
	
	mpi.init(&argc,&argv);
	
	rng = new RandGen(1000,mpi.getRank());
	
	maxGT = mGT = t = 0.0;
	
	while(mGT < 100.0) {
		t += rng->getRandom(0.0);
		
		if(i > 10) {
			mpi.barrier();
			mGT = mpi.allReduceDouble(t,MPI_MIN);
			maxGT = mpi.allReduceDouble(t,MPI_MAX);
			if(mpi.isRoot())
				cout << mGT << " " << maxGT << endl;
			i=0;
		}
		++i;
	}

	mpi.shutdown();

}
Пример #2
0
int Dice::Roll()
// postcondition: number of rolls updated
//                random 'die' roll returned
{
    RandGen gen;    // random number generator

    myRollCount_= myRollCount_ + 1;         // update # of times die rolled
    return gen.RandInt(1,mySides_);        // in range [1..mySides_]
}
Пример #3
0
void drawLandscape(window &w, color skycolor, color groundcolor) { // creates landscape. only called once
    setBrushAndPenColor(w, skycolor);
    w.DrawRectangle(0, 0, w.GetWidth(), w.GetHeight(), FILLED);
    RandGen r;
    int ystart = r.RandInt((double) w.GetHeight() * 0.666, (double) w.GetHeight() * 0.75); // semi random height of ground near bottom of screen
    setBrushAndPenColor(w, groundcolor);
    for (double x = 0; x < w.GetWidth(); x++) {
        int yval = ystart + sin((double) (x / 60)) * 15; // ground will be sin curve
        w.DrawLine(x, yval, x, w.GetHeight());    // draws line from ground level to bottom of screen
    }
}
void LiveWLdiagram :: updateZe_ab ()
{
    int online_worms = int(mob_a.online()) + int(mob_b.online());

    // No worm in the diagram
    if (online_worms == 0) {
        // Insert the first worm:
        int    comp  = rand.choice2();
        int    site  = rand.choice (Diagram::SITEN);
        double time  = Wld::Diag::BETA * rand.uniform();
        bool   up    = rand.choice2();
        bool   creat = rand.choice2();

        Iter it_goal = Wld::Diag::find_aft (site, time);
        int ninit = it_goal->z.nbef(comp);
        // Check whether cannot creat or annihilate particle anymore
        if (check_nlimit (ninit, creat, nMAX, nMIN)) {

            Worm& mob = comp ? mob_b : mob_a;
            Iter& fix = comp ? fix_b : fix_a;
            insert (it_goal, comp, time, creat, up, mob, fix);
        }
    }
    else if (online_worms == 1) {

        Worm& mob_on = mob_a.online() ? mob_a : mob_b;
        Iter& fix_on = mob_a.online() ? fix_a : fix_b;
        // 1. Insert another worm:
        if (rand.uniform() < Pab) {

            int   comp_on  = mob_a.online() ? 0 : 1;
            int   comp_off = !comp_on;
            Worm& mob_off  = mob_a.online() ? mob_b : mob_a;
            Iter& fix_off  = mob_a.online() ? fix_b : fix_a;

            int    site  = fix_on->site();
            double time  = fix_on->time();
            bool   up    = rand.choice2();
            bool   creat = mob_on.it()->z.creat() ? !up : up; // For PSF. Opposite for SCF.

            Iter it_goal = Wld::Diag::find_aft (site, time);
            int ninit = it_goal->z.nbef (comp_off);
            if (check_nlimit (ninit, creat, nMAX, nMIN)) {

                insert (it_goal, comp_off, time, creat, up, mob_off, fix_off);
            }
        }
        // 2. Worm can global move.
        else {
            updateZe_to_halt (mob_on);
        }
    }
    else if (online_worms == 2) {
        int   comp = rand.choice2();
        Worm& mob  = (comp == 0 ? mob_a : mob_b);
        Iter& fix  = (comp == 0 ? fix_a : fix_b);
        updateZe_to_halt (mob);
    }
}
Пример #5
0
int MultinomialSampler::Sample(RandGen &rand_gen)
{
	if (intervals_ == 0)
		return -1;

	//unsigned int val = uint_dist(generator);
	unsigned int val = rand_gen.NextRandom() % kDefMaxVal;
	int l = 0, r = num_vals - 1, m;
	while (l <= r)
	{
		m = (l + r) >> 1;
		if (intervals_[m] > val)
			r = m - 1;
		else
			l = m + 1;
	}

	if (l >= num_vals)
		l = num_vals - 1;
	return l;
}
inline LiveWLdiagram::Status LiveWLdiagram :: updateZe (Worm& worm)
{
  double Ewalk = walk_energy (worm.it(), worm.up());
  double dtime = -log (rand.uniform()) / Ewalk;

  Iter it_block;
  Status stat  = walk (dtime, worm, it_block);

  #ifdef PRINT_STATUS
  cout << _printi << setw(16) << left << "  walk "+string(worm.up() ? "up" : "down")+": " << to_str(stat) << endl;
  #endif

  ActStatus astat = act (worm, stat, Ewalk, it_block);

  #ifdef PRINT_STATUS
  cout << _printi << setw(16) << left << "  act: " << to_str(astat) << endl;
  _printi++;
  #endif

  return stat;
}
Пример #7
0
UINT RandGen::GetRand(INT nStart, INT nEnd)
{
	return (INT)((nEnd-nStart)*g_RandGen.RandDouble()) + nStart;
}
LiveWLdiagram::ActStatus LiveWLdiagram :: act (Worm& worm, Status stat, double Ewalk, const Iter& it_block)
// Member-functions used in this function (like hop, relink_hop,...)
// should not specify the base class (for example: don't use WLdiagram::hop,...),
// so that the higher-level class (InfoWLdiagram) can overload them.
{
  table.clear();
  int site = worm.it()->site();
  int comp = worm.it()->z.comp();

  if (stat == FREE) {
    // 1.1 bounce
    table.add (Ewalk);
    // 1.2 insert interaction
    for(int nbi = 0; nbi < Wld::Diag::_latt(site).nbs(); ++nbi) {
      int  n     = worm.it()->assoc(nbi)->z.nbef(comp);
      bool creat = (worm.up() != worm.it()->z.creat());
      if (check_nlimit (n, creat, nMAX, nMIN)) {
        // Check whether cannot creat or annihilate particle anymore
        int dir = _latt(site).nbdir(nbi);
        double weight = BH_t(comp,dir) * (creat ? n+1 : n);
        table.add (weight, nbi);
      }
    }
    // 1.3 choose
  #ifdef LOCAL_OPTIMAL
    table.locally_optimal();
  #endif
    int choice = table.get_choice (rand.uniform());
    if (choice == 0) {
      bounce (worm);
      return ACT_BOUNCE;
    }
    else {
      hop (worm, table.nbi(choice));
      return ACT_HOP;
    }
  }
  else if (stat == HALTED) {

    Iter it_to = it_block->conj(); // 'it_to' is the to-node in remove case, or the middle-node in relink case

    // 2.1 bounce
    int dir = _latt.dir (site, it_to->site());
    double weight = BH_t(comp,dir) * (worm.it()->z.creat() ? worm.it()->z.naft(comp) : worm.it()->z.nbef(comp));
    table.add (weight);

    // 2.2 remove interaction
     double Ebef = diagonal_energy (it_to, it_to->z.nbef(0), it_to->z.nbef(1));
     double Eaft = diagonal_energy (it_to, it_to->z.naft(0), it_to->z.naft(1));
     if (worm.up())
        weight = shift_energy (Eaft, Ebef);
     else
        weight = shift_energy (Ebef, Eaft);
     table.add (weight);

    // 2.3 relink interaction
    for(int nbi = 0; nbi < Wld::Diag::_latt(it_to->site()).nbs(); ++nbi) {
      Iter it_nb = it_to->assoc(nbi);
      if (it_nb->site() != worm.it()->site()) {
        // Check whether relink to the self site
        int n = it_nb->z.nbef(comp);
        bool creat = (worm.up() == worm.it()->z.creat());
        if (check_nlimit (n, creat, nMAX, nMIN)) {
          // Check whether cannot creat or annihilate particle anymore
          int dir = _latt(site).nbdir(nbi);
          weight = BH_t(comp,dir) * (creat ? n+1 : n);
          table.add (weight, nbi);
        }
      }
    }
    // 2.4 choose
  #ifdef LOCAL_OPTIMAL
    table.locally_optimal();
  #endif
    int choice = table.get_choice (rand.uniform());
    if (choice == 0) {
      bounce (worm);
      return ACT_BOUNCE;
    }
    else if (choice == 1) {
      delete_hop (worm);
      return ACT_DELETE_HOP;
    }
    else {
      relink_hop (worm, table.nbi(choice));
      return ACT_RELINK_HOP;
    }
  }
  else if (stat == CRASH) {
    remove (worm);
    return ACT_REMOVE_WORMS;
  }

  return ACT_NOTHING;
}
Пример #9
0
  // starting function (executed once at the beginning of the simulation loop)
  void start(const OdeHandle& odeHandle, const OsgHandle& osgHandle, GlobalData& global)
  {
    setCameraHomePos(Pos(-0.0114359, 6.66848, 0.922832),  Pos(178.866, -7.43884, 0));
    // initialization
    // - set noise to 0.1
    // - register file chess.ppm as a texture called chessTexture (used for the wheels)
    global.odeConfig.setParam("noise", 0.05);
    global.odeConfig.setParam("controlinterval", 1);
    global.odeConfig.setParam("cameraspeed", 250);

    // use Playground as boundary:
//    playground = new Playground(odeHandle, osgHandle, osg::Vec3(8, 0.2, 1), 1);
//     // playground->setColor(Color(0,0,0,0.8));
//     playground->setGroundColor(Color(2,2,2,1));
//     playground->setPosition(osg::Vec3(0,0,0.05)); // playground positionieren und generieren
//     global.obstacles.push_back(playground);
    controller=0;

    addParameter("k",&k);
    addParameter("gamma_s",&teacher);
    global.configs.push_back(this);

    for(int i=0; i< bars; i++){
      PassiveBox* b = new PassiveBox(odeHandle, osgHandle.changeColor(Color(0.,0.,0.)),
                                     osg::Vec3(1,10,0.3+i*.1),0.0);
      b->setPosition(osg::Vec3(10+i*7,0,0));
      global.obstacles.push_back(b);
    }

    double h = 0.;
    RandGen rgen;
    rgen.init(2);
    for(int i=0; i<stairs; i++){
      do{
        h+=(rgen.rand()-.5)*0.6; // values between (-.25.25)
      }while(h<0);
      PassiveBox* b = new PassiveBox(odeHandle, osgHandle.changeColor(Color(0.3,0.3,0.3)),
                                     osg::Vec3(1,10,h),0.0);
      b->setPosition(osg::Vec3(5+i,0,0));
      global.obstacles.push_back(b);
    }

    /******* S L I D E R - w H E E L I E *********/
    SliderWheelieConf mySliderWheelieConf = SliderWheelie::getDefaultConf();
    mySliderWheelieConf.segmNumber   = segmnum;
    mySliderWheelieConf.motorPower   = 5;
    mySliderWheelieConf.jointLimitIn = M_PI/3;
//     mySliderWheelieConf.frictionGround=0.5;
//    mySliderWheelieConf.segmLength=1.4;
    mySliderWheelieConf.sliderLength = 0;
    mySliderWheelieConf.motorType    = SliderWheelieConf::CenteredServo;
    mySliderWheelieConf.showCenter   = false;
    vehicle = new SliderWheelie(odeHandle, osgHandle.changeColor(Color(1,222/255.0,0)),
                                mySliderWheelieConf, "sliderWheelie_" + std::itos(teacher*10000));

    vehicle->place(Pos(0,0,.1));
    global.configs.push_back(vehicle);

//     InvertMotorNStepConf cc = InvertMotorNStep::getDefaultConf();
//     cc.cInit=1.0;
//     cc.useS=false;
//     cc.someInternalParams=true;
//     InvertMotorNStep *semox = new InvertMotorNStep(cc);
//     semox->setParam("steps", 1);
//     semox->setParam("continuity", 0.005);
//     semox->setParam("teacher", teacher);

    SeMoXConf cc = SeMoX::getDefaultConf();
    //cc.cInit=.95;
    cc.cInit=.5;
    cc.modelExt=false;
    //    cc.someInternalParams=true;
    cc.someInternalParams=false;
    SeMoX* semox = new SeMoX(cc);

//     AbstractController* controller = new SineController(~0, SineController::Sine);   // local variable!
// //     // motorpower 20
//     controller->setParam("period", 300);
//     controller->setParam("phaseshift", 0.3);

    if(useSym){
      semox->setParam("epsC", 0.1);
      semox->setParam("epsA", 0.1);
    }else{
      semox->setParam("epsC", 0.1);
      semox->setParam("epsA", 0.1);
    }
    semox->setParam("rootE", 3);
    semox->setParam("s4avg", 1);
    semox->setParam("gamma_cont", 0.005);

    semox->setParam("gamma_teach", teacher);

    //controller=semox;
    controller = new CrossMotorCoupling( semox, semox, 0.4);

    //        AbstractWiring* wiring = new One2OneWiring(new ColorUniformNoise(0.1));
    //AbstractWiring* wiring = new MotorAsSensors(new ColorUniformNoise(0.1));
    AbstractWiring* wiring = new FeedbackWiring(new ColorUniformNoise(0.1),
                                                 FeedbackWiring::Motor, 0.75);
    //global.plotoptions.push_back(PlotOption(GuiLogger,Robot,5));
    OdeAgent* agent = new OdeAgent(global);
    agent->init(controller, vehicle, wiring);
    if(track) agent->setTrackOptions(TrackRobot(true,false,false, false,
                                                 change != 0 ? std::itos(change).c_str() : "uni", 50));
    global.agents.push_back(agent);
    global.configs.push_back(controller);

    this->getHUDSM()->setColor(Color(1.0,1.0,0));
    this->getHUDSM()->setFontsize(18);
    this->getHUDSM()->addMeasure(teacher,"gamma_s",ID,1);
    this->getHUDSM()->addMeasure(k_double,"k",ID,1);

    setCMC(k);
    blink=0;


  }
//--------------
// medPing_Main \
//----------------------------------------------------------------------
// called from iPhone runSim-tab
int medPing_Main()
{
	// print a message to the cell phone
	mP.CELL_PrintF("Hello medPing patient ...\n\n");
	
	//======= DATA STRUCTURE ======================================
	// to hold patient's history of vital signs
	oneVitalHistoryRecord	vitalHistory[MAX_HISTORY];	
	
	// hmr (how many really) vital signs  0 <= hmr < MAX_HISTORY
	long hmr = 0;  
	//=============================================================
	
	RandGen		randGenerator;	// i need a random number generator
	time_t		start, now;		// keep track of time in simulation

	
	// ask user at CELL to input length of simulation
	mP.CELL_PrintF("How many SECONDS would you like to simulate?\n");
	double simulationTime = mP.CELL_fetchReal();
	time(&start);
	
	// simulation loop ....
	time(&now);
	while ( difftime(now,start) < simulationTime )		// while still time to simulate ...
	{
		long waitThisLongSEC = randGenerator.RandInt(1, MAX_WAIT_SEC);
		mP.CELL_PrintF("\n--------------------------\n");
		mP.CELL_PrintF("\n[PAUSE ... (%d seconds) ]\n", waitThisLongSEC);
		sleep(waitThisLongSEC);	// ZZzzzz.....
		// WINDOWS uses the function called: Sleep( milliseconds ) 
		// Sleep(waitThisLongSEC*1000);	// ZZzzzz.....

		
		
		// check our watch ...
		long nSecs = time(&now);
		
		// fetch vital signs from the medPing chip HERE (use mP object, right?)
		double newTemp;
		newTemp = mP.getBodyTemperature_F();
		// :
		// :
		
		
		// now ADD these new vital signs to our history DATA STRUCTURE
		//AddHistoryRecord(nSecs, newTemp, /* ... more here ... ,*/ vitalHistory, hmr);
		
		// PRINT ALL of the series of vital signs so far
		printAllVitalRecords(mP, vitalHistory, hmr);
		

		
	} // while still more to simulate ...
		
		
	mP.CELL_PrintF("\n\nSIMULATION OVER.\n\n");
	
	// prompt for a record to delete HERE,
    
    
    
    // find it (using your Find function)
    
    
    
    // and delete it if found (using your Delete function)
	
	
	
	
	
	mP.CELL_PrintF("\n\nDONE.\n");
	
	// WINDOWS
	// system("PAUSE");
	
	return 0;
	
} // end medPing_Main()