コード例 #1
0
ファイル: main.cpp プロジェクト: CCJY/coliru
int main()
{
    // Seed with a real random value, if available
    // Semilla con un valor random real, si existe
    std::random_device rd;
 
    // Choose a random mean between 1 and 6

    std::default_random_engine e1(rd());
    std::uniform_int_distribution<int> uniform_dist(1, 100);
    int mean = uniform_dist(e1);
    std::cout << "Randomly-chosen mean: " << mean << '\n';
 




    // Generate a normal distribution around that mean
    std::mt19937 e2(rd());
    std::normal_distribution<> normal_dist(mean, 2);
 
    std::map<int, int> hist;
    for (int n = 0; n < 10000; ++n) {
        ++hist[std::round(normal_dist(e2))];
    }
    std::cout << "Normal distribution around " << mean << ":\n";
    for (auto p : hist) {
        std::cout << std::fixed << std::setprecision(1) << std::setw(2)
                  << p.first << ' ' << std::string(p.second/200, '*') << '\n';
    }



}
コード例 #2
0
ファイル: demo.cpp プロジェクト: sebastiankochman/paxos-cpp
void Demo::run()
{
    std::random_device r;
    std::default_random_engine e1(r());
    std::uniform_int_distribution<int> uniform_dist(1, 100);

    std::vector<std::thread> threads;
    for (auto proposer : proposers) {
        int x = uniform_dist(e1);
        threads.push_back(std::thread(proposer->propose, proposer, x));
    }

    for (std::thread& th : threads) {
        th.join();
    }

    std::cout << "\nFinal state of acceptors after one round of Paxos without a distinguished proposer:\n";
    for (int i = 0; i < this->acceptors.size(); i++) {
        auto r = this->acceptors[i]->getAccepted();
        std::cout << "Acceptor " << i << ": ";
        if (r.alreadyAccepted) {
            std::cout << "value: " << r.prevValue << ", last proposal number: " << r.prevProposalNumber << std::endl;
        }
        else {
            std::cout << "nothing\n";
        }
    }
}
コード例 #3
0
int main()
{
    // Seed with a real random value, if available
    pcg_extras::seed_seq_from<std::random_device> seed_source;
  
    // Make a random number engine 
    pcg32 rng(seed_source);

    // Choose a random mean between 1 and 6
    std::uniform_int_distribution<int> uniform_dist(1, 6);
    int mean = uniform_dist(rng);
    std::cout << "Randomly-chosen mean: " << mean << '\n';
 
    // Generate a normal distribution around that mean
    std::normal_distribution<> normal_dist(mean, 2);
    
    // Make a copy of the RNG state to use later
    pcg32 rng_checkpoint = rng;
 
    std::map<int, int> hist;
    for (int n = 0; n < 10000; ++n) {
        ++hist[std::round(normal_dist(rng))];
    }
    std::cout << "Normal distribution around " << mean << ":\n";
    for (auto p : hist) {
        std::cout << std::fixed << std::setprecision(1) << std::setw(2)
                  << p.first << ' ' << std::string(p.second/30, '*')
                  << '\n';
    }
    
    std::cout << "Required " << (rng - rng_checkpoint) << " random numbers.\n";
}
コード例 #4
0
ファイル: skipList.cpp プロジェクト: frankicia/ADS
//PRIVATE
int skipList::randomLevel() {
  //std::cout << "randomLevel generator" << std::endl;
  //int aux = 1;
  //srand ((unsigned)time(NULL));
  //bool cond = ((double)std::rand() / RAND_MAX) < this->prob;
  ////while (cond || (aux < maxLevel - 1) ) {
    ////++aux;
    ////cond = ((double) std::rand() / RAND_MAX) < this->prob;
  ////}
  //while ((((double)std::rand() / RAND_MAX)) < prob && std::abs(aux) < maxLevel)
    //++aux;

  int aux = 1;
  std::random_device rd;
  std::default_random_engine rng(rd());
  std::uniform_real_distribution<float> uniform_dist(0,1);
  float random = uniform_dist(rng);
  bool cond = random < this->prob;
  while ( cond && std::abs(aux) < maxLevel ) {
    random = uniform_dist(rng);
    cond = random < this->prob;
    ++aux;
  }
  //std::cout << "RANDOM LEVEL: " << aux << std::endl;
  return aux;
}
コード例 #5
0
ファイル: Filesystem.cpp プロジェクト: immunant/selfrando
std::string Filesystem::get_temp_filename(std::string filename_tag, std::string filename_end) {
    std::string temp_path = get_temp_dir() + "/" + filename_tag + "-";

    static std::unique_ptr<std::mt19937> rng;
    if (!rng) {
        // Construct and seed the RNG
        std::random_device r{};
        rng.reset(new std::mt19937(r()));
    }

    std::uniform_int_distribution<char> uniform_dist(0, 61);
    for (unsigned i = 0; i < 10; ++i) {
        char rand_char = uniform_dist(*rng);
        if (rand_char >= 52) {
            rand_char = '0' + (rand_char - 52);
        } else if (rand_char >= 26) {
            rand_char = 'A' + (rand_char - 26);
        } else {
            rand_char = 'a' + rand_char;
        }
        temp_path += rand_char;
    }

    if (! filename_end.empty()) {
        temp_path += "-" + filename_end.substr(filename_end.rfind('/')+1);
    }

    return temp_path;
}
コード例 #6
0
ファイル: GpuDebugFunctions.cpp プロジェクト: CoffeRobot/fato
void DrawDetectedPoints(const vector<Point2f>* initPts, const vector<Point2f>* updPts,
	const vector<FatoStatus>* ptsStatus, const vector<int>* ptsIds, Mat&out)
{
	int imgOffset = out.cols / 2;
	
	random_device rd;
	default_random_engine dre(rd());
	uniform_int_distribution<unsigned int> uniform_dist(0, 255);

	for (size_t i = 0; i < updPts->size(); i++)
	{
		const int id = ptsIds->at(i);
		if (ptsStatus->at(i) == FatoStatus::MATCH)
		{
			Scalar color(uniform_dist(dre), uniform_dist(dre), uniform_dist(dre));

			const Point2f& src = initPts->at(id);
			Point2f dst = updPts->at(i);
			dst.x += imgOffset;

			circle(out, src, 3, color, 1);
			circle(out, dst, 3, color, 1);
			line(out, src, dst, color, 1);
			
		}
	}
}
コード例 #7
0
	void SpaceInvadersModel::randomAlienShoot() {
		//Determine the bottom RegularAlien in every column
		std::vector<RegularAlien*> bottomAliens(11, nullptr);
		//Start at the back of the vector (as RegularAliens where added from top to bottom)
		for (int i = (alienRows_ * alienColumns_) -1; i >= 0; i--) {
			if (bottomAliens[i % alienColumns_] == 0 && aliens_[i]) {  //Currently nullptr for this column?
				bottomAliens[i % alienColumns_] = aliens_[i];		   //then this is the bottom RegularAlien
			}
		}
		//remove rows without aliens
		std::vector<RegularAlien*>::iterator it = bottomAliens.begin();
		while (it != bottomAliens.end()){
			if (!(*it))  //if nullptr
				it = bottomAliens.erase(it); //then remove it
			else
				it++;
		}
		//stuff for random
		std::default_random_engine e1(rd());
		std::uniform_int_distribution<int> uniform_dist(1, bottomAliens.size());

		int shooter = uniform_dist(e1);  //pick random between 1 and number of nonempty columns
		shooter--;    //subtract one (because it should start at 0)
		bullets_.push_back(bottomAliens[shooter]->shoot());  //Have the picked RegularAlien take a shot
	}
コード例 #8
0
ファイル: main.cpp プロジェクト: CCJY/coliru
int main() {
    size_t const U = 100;
    size_t const N = 100000;
    size_t const ITERATIONS = 1;
    size_t const SAMPLES = 5;
    
    // 0. Seed with a real random value, if available
    std::random_device rd;
    std::default_random_engine engine(rd());
    
    // 1. Generate a random set of N unique values
    std::vector<int> unique_values;
    {
        std::uniform_int_distribution<int> uniform_dist(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
        while (unique_values.size() < U) {
            insert_sorted(unique_values, uniform_dist(engine));
        }
    }
    std::cout << "Generated " << unique_values.size() << " unique values in the range [" << unique_values.front() << ", " << unique_values.back() << "]\n";
    
    // 2. From that set of unique values, generate a large collection of random numbers
    std::vector<int> random_stream;
    {
        random_stream.reserve(N);
        std::uniform_int_distribution<size_t> uniform_dist(0, unique_values.size()-1);

        for (size_t i = 0; i < N; ++i) {
            random_stream.push_back(unique_values.at(uniform_dist(engine)));
        }
    }
    std::cout << "Generated a stream of " << random_stream.size() << " values\n";

    // 3. Time each solution
    double best_ures = std::numeric_limits<double>::max();
    double best_uniq = std::numeric_limits<double>::max();
    double best_sort = std::numeric_limits<double>::max();
    
    for (size_t i = 0; i < SAMPLES; ++i) {
        size_t ures_result = 0;
        double ures = benchmark(VecUniquerReserver{ures_result, U, random_stream}, ITERATIONS);
        best_ures = std::min(best_ures, ures);
        std::cout << "Ures: " <<  ures_result << ": " << best_ures << "\n";
        
        size_t uniq_result = 0;
        double uniq = benchmark(VecUniquer{uniq_result, random_stream}, ITERATIONS);
        best_uniq = std::min(best_uniq, uniq);
        std::cout << "Uniq: " <<  uniq_result << ": " << best_uniq << "\n";
        
        size_t sort_result = 0;
        double sorting = benchmark(VecSorter{sort_result, random_stream}, ITERATIONS);
        best_sort = std::min(best_sort, sorting);
        std::cout << "Sort: " << sort_result << ": " << best_sort << "\n";
    }
    
    std::cout << "Final: URES = " << best_ures << ", UNIQ = " << best_uniq << ", SORT = " << best_sort << "\n";


    return 0;
}
コード例 #9
0
ファイル: Survivor.cpp プロジェクト: khariq/Survive2
	Survive::SurvivorPtr Survivor::CreateSurvivor()
	{
		Survive::SurvivorPtr created(new Survivor());

		// Seed with a real random value, if available
		std::random_device rd;

		// Choose a random mean between 1 and 6
		std::default_random_engine e1(rd());
		std::uniform_int_distribution<int> uniform_dist(1, 6);
		
		created->_body = uniform_dist(e1);
		created->_strength = uniform_dist(e1);

		created->_intuition = uniform_dist(e1);
		created->_willpower = uniform_dist(e1);

		int positive = uniform_dist(e1);
		int negative = uniform_dist(e1) * -1;
		while (positive + negative == 0)
		{
			positive = uniform_dist(e1);
			negative = uniform_dist(e1)  * -1;
		}
		created->_positiveTrait = (Survive::SurvivorTraits)positive;
		created->_negativeTrait = (Survive::SurvivorTraits)negative;

		created->_currentHealth = created->GetStat(Survive::SurvivorStat::Health);

		return created;
	}
コード例 #10
0
ファイル: tests.cpp プロジェクト: CrazyPopLin/flight
TEST_F(TrajectoryLibraryTest, TimingTest) {
    StereoOctomap octomap(bot_frames_);

    double altitude = 30;

    // create a random point cloud

    int num_points = 10000;
    int num_lookups = 1000;

    std::uniform_real_distribution<double> uniform_dist(-1000, 1000);
    std::random_device rd;
    std::default_random_engine rand_engine(rd());

    float x[num_points], y[num_points], z[num_points];

    for (int i = 0; i < num_points; i++) {


        // generate a random point
        x[i] = uniform_dist(rand_engine);
        y[i] = uniform_dist(rand_engine);
        z[i] = uniform_dist(rand_engine);

        //std::cout << "Point: (" << this_point[0] << ", " << this_point[1] << ", " << this_point[2] << ")" << std::endl;

    }

    AddManyPointsToOctree(&octomap, x, y, z, num_points, altitude);

    TrajectoryLibrary lib(0);

    lib.LoadLibrary("trajtest/many", true);

    BotTrans trans;
    bot_trans_set_identity(&trans);
    trans.trans_vec[2] = altitude;

    tic();

    for (int i = 0; i < num_lookups; i++) {
        double dist;
        const Trajectory *best_traj;
        std::tie(dist, best_traj) = lib.FindFarthestTrajectory(octomap, trans, 50.0);
    }

    double num_sec = toc();

    std::cout << num_lookups <<  " lookups with " << lib.GetNumberTrajectories() << " trajectories on a cloud (" << num_points << ") took: " << num_sec << " sec (" << num_sec / (double)num_lookups*1000.0 << " ms / lookup)" << std::endl;
}
コード例 #11
0
ファイル: copyvsref.hpp プロジェクト: rodgert/mbm
    void init(size_t n) {
        data.resize(n);
        res.resize(n);

        std::random_device rd;
        std::default_random_engine e(rd());

        std::uniform_int_distribution<int> uniform_dist(0, 100);
        data.clear();
        res.clear();

        for (auto i = 0u; i < n; i++)
            data.emplace_back(rect { uniform_dist(e), uniform_dist(e), uniform_dist(e), uniform_dist(e) });
    }
コード例 #12
0
ファイル: FragTrap.cpp プロジェクト: po-connor/Piscine_CPP
unsigned int	FragTrap::vaultHunter_dot_exe(std::string const & target) {
	std::random_device	rd;
	std::default_random_engine e1(rd());
	std::uniform_int_distribution<int> uniform_dist(0, 5);
	int	i = uniform_dist(e1);

	if (this->_ep < 25) {
		std::cout << "*** FR4G-TP " << this->_name << " tries a special attack. ***" << std::endl;
		std::cout << "<FR4G-TP " << this->_name << "> " << "I can't do this ! Plug me, Jack, plug me !" << std::endl;
		return 0;
	}
	this->_ep -= 25;
	std::cout << "*** FR4G-TP " << this->_name << " attacks " << target << " with " << this->_attacksList[i] << " causing " << this->_mAttack  << " points of damage ! ***" << std::endl; 
	return this->_mAttack;
}
コード例 #13
0
ファイル: compression.cpp プロジェクト: ctianjin/DynamO
  ParticleEventData 
  DynCompression::runAndersenWallCollision(Particle& part, const Vector & vNorm, const double& sqrtT, const double d) const
  {  
    updateParticle(part);

    if (hasOrientationData())
      M_throw() << "Need to implement thermostating of the rotational degrees"
	" of freedom";

    //This gives a completely new random unit vector with a properly
    //distributed Normal component. See Granular Simulation Book
    ParticleEventData tmpDat(part, *Sim->species[part], WALL);
 
    double mass = Sim->species[tmpDat.getSpeciesID()]->getMass(part.getID());

    std::normal_distribution<> normal_dist;
    std::uniform_real_distribution<> uniform_dist;

    for (size_t iDim = 0; iDim < NDIM; iDim++)
      part.getVelocity()[iDim] = normal_dist(Sim->ranGenerator) * sqrtT / std::sqrt(mass);
  
    part.getVelocity()
      //This first line adds a component in the direction of the normal
      += vNorm * (sqrtT * sqrt(-2.0*log(1.0 - uniform_dist(Sim->ranGenerator)) / mass)
		  //This removes the original normal component
		  -(part.getVelocity() | vNorm)
		  //This adds on the velocity of the wall
		  + d * growthRate)
      ;

    return tmpDat; 
  }
コード例 #14
0
ファイル: random.cpp プロジェクト: AlekNS/skironscrapper
			double 
			generate_uniform(
				double min,
				double max
				)
			{
				TRACE_MESSAGE(TRACE_LEVEL_VERBOSE, "+sola::component::random::generate_uniform");

				SERIALIZE_CALL(std::recursive_mutex, __random_lock);

				double result;
				std::uniform_real_distribution<double> uniform_dist;

				if(!__random_initialized) {
					THROW_RANDOM_EXCEPTION(RANDOM_EXCEPTION_UNINITIALIZED);
				}

				if(min > max) {
					THROW_RANDOM_EXCEPTION_MESSAGE(
						RANDOM_EXCEPTION_INVALID_PARAMETER,
						"min > max"
						);
				}
				result = ((max - min) * uniform_dist(__random_generator)) + min;

				TRACE_MESSAGE(TRACE_LEVEL_VERBOSE, "-sola::component::random::generate_uniform, result. " << result);

				return result;
			}
コード例 #15
0
ファイル: rand_gen.cpp プロジェクト: gmfricke/PowerSearch3D
int rand_gen::binomial_dist(int n, double p){

int m=0;
for( int i=0;i<n;i++){

if(uniform_dist(0.,1.)<p) m++;
}
return m;
}
コード例 #16
0
ファイル: main.cpp プロジェクト: Jinxit/tabu
int main(int argc, const char* argv[])
{
    auto fitness = [](int x) {
        if (x >= 8)
            return -1000;
        return (int)(std::pow(x*0.25, 5) - 10 * std::pow(0.25*x, 3) + 7.5 * x);
    };
    std::default_random_engine gen;
    std::uniform_int_distribution<int> uniform_dist(-10, 10);
    auto random = [&]() {
        return uniform_dist(gen);
    };
    auto neighbours = [](int x) {
        return std::vector<int>{x - 1, x + 1};
    };
    auto best = tabu::search<int>(20, 5, fitness, random, neighbours);

    std::cout << best.second << std::endl;
    std::cout << best.first << std::endl;
}
コード例 #17
0
ファイル: rand_gen.cpp プロジェクト: gmfricke/PowerSearch3D
/*
Simulate power law with cut-off x^(-alpha)*exp(-lambda*x)
To simulate power-law with cutoff , one can generate an
exponentially distributed random number using the formula
above     (as k>0 and integer, so k start at 1)
and then accept or reject it with probability p or 1 - p
respectively (i.e accept U1 <p or reject U1>p, and
 U1 is a uniform [0,1] random variable),
where p = (x/x_min)^(-alpha)  and  x_min=1.

http://www.santafe.edu/~aaronc/powerlaws/
*/
double rand_gen::powerlaw_dist(double alpha, double lamda)
{

double x;
do{
x = exponential_dist(lamda);
} while (pow(x,-1*alpha) < uniform_dist(0.,1.));

return (x);

}
コード例 #18
0
ファイル: rand_gen.cpp プロジェクト: gmfricke/PowerSearch3D
double rand_gen::normal_dist(double sigma, double mu)
{

double V1, V2, S;
double X;

do {
double U1 = uniform_dist(0.,1.);

double U2 = uniform_dist(0.,1.);

V1 = 2 * U1 - 1;

V2 = 2 * U2 - 1;
S = V1 * V1 + V2 * V2;
} while(S >= 1 || S == 0);

X = V1 * sqrt(-2 * log(S) / S);

return sigma*X+mu;
}
コード例 #19
0
ファイル: pfswarm.cpp プロジェクト: cameronfrazier/PFSwarm
void PFSwarm::setupSwarm(int cntSatellite)
{
    this->_gravity = State(IS_THREE_DIMENSTIONAL);
    this->_gravity.position.x = 100;
    this->_gravity.position.y = 200;
    this->_gravity.position.z = 300;
    this->_gravity.velocity.x = 3;
    
    std::default_random_engine generator( (unsigned int)time(0) );
    std::uniform_int_distribution<int> uniform_dist(-50, 50);
    
    for (int idx = 0; idx < cntSatellite; idx++) {
        State init_state = State();
        init_state.position.x = uniform_dist(generator);
        init_state.position.y = uniform_dist(generator);
        init_state.position.z = uniform_dist(generator);
        Satellite * sat = new Satellite(idx, _settings, &_gravity, &_satellites, init_state);
        _satellites.push_back(sat);
//        this->addSatellites(new Satellite(idx, this->_settings, &this->_gravity, &this->_satellites, init_state));
    }
}
コード例 #20
0
void RandomMiniBlocks::create(const sf::Texture& blockTexture) {
    const int width = App::WINDOW_WIDTH / HALF_TILE_SIZE;
    const int height = App::WINDOW_HEIGHT / HALF_TILE_SIZE;
    blockSprites_.resize(width * height);

    std::mt19937 rng;
    std::uniform_int_distribution<> uniform_dist(0,
            static_cast<int>(tetris::game::Tetromino::Type::SIZE) - 1);

    for (int i = 0; i < height; ++i) {
        for (int j = 0; j < width; ++j) {
            int index = i * width + j;
            int colorIndex = uniform_dist(rng);
            auto& block = blockSprites_[index];
            if (BLOCK_POSITIONS[index] == '#') {
                block.setTexture(blockTexture);
                block.setColor(colors_[colorIndex]);
                block.setPosition({j * HALF_TILE_SIZE, i * HALF_TILE_SIZE});
            }
        }
    }
}
コード例 #21
0
    void LeapfrogSimpleBufferGas::NeutralAtom::Collide(Util::SIAtomProxy &ap, double dt) {
      if (ap == target_atom_name || GetCollisionInterval(ap) > dt) return;

      Vector3D v(vel_dist(engine),
		 vel_dist(engine),
		 vel_dist(engine));
      
      const Vector3D vi = ap.GetVelocity();
      double mi = ap.GetMass();
      double v_rel_mag = (vi - v).norm();
      double m_total = m + mi;

      Vector3D v_com = (vi * mi + v * m) / m_total;
      Vector3D v_rel(uniform_dist(engine),
		     uniform_dist(engine),
		     uniform_dist(engine));
      
      v_rel.normalize();
      v_rel *= v_rel_mag;
      
      ap.SetVelocity(v_com + v_rel * m / m_total);
    }
コード例 #22
0
void RobotEnvironment::generateRandomScene(unsigned int& numObstacles)
{
    scene_ = std::make_shared<frapu::Scene>();
    std::vector<frapu::ObstacleSharedPtr> obstacles(numObstacles);
    std::uniform_real_distribution<double> uniform_dist(-1.0, 4.0);
    std::uniform_real_distribution<double> uniform_distZ(3.0, 6.0);
    for (size_t i = 0; i < numObstacles; i++) {
        double rand_x = uniform_dist(randomEngine_);
        double rand_y = uniform_dist(randomEngine_);
        double rand_z = uniform_distZ(randomEngine_);

        frapu::TerrainSharedPtr terrain = std::make_shared<frapu::TerrainImpl>("t" + std::to_string(i),
                                          0.0,
                                          0.0,
                                          false,
                                          true);

        std::string box_name = "b" + std::to_string(i);
        obstacles[i] = std::make_shared<frapu::BoxObstacle>(box_name,
                       rand_x,
                       rand_y,
                       rand_z,
                       0.25,
                       0.25,
                       0.25,
                       terrain);
        std::vector<double> diffuseColor( {0.5, 0.5, 0.5, 0.5});
        static_cast<frapu::ObstacleImpl*>(obstacles[obstacles.size() - 1].get())->setStandardColor(diffuseColor, diffuseColor);
        std::vector<double> dims( {rand_x, rand_y, rand_z, 0.25, 0.25, 0.25});
        robot_->addBox(box_name, dims);

    }

    scene_->setObstacles(obstacles);
    cout << "random scene created " << obstacles.size();

}
コード例 #23
0
void MonsterGenerator::spawnMonsters()
{
	if (clock.getElapsedTime().asSeconds() - lastSpawn > spawnFrequency)
	{
		std::random_device rd;
		std::default_random_engine generator(rd());
		std::uniform_int_distribution<int> uniform_dist(0, 3);
		std::uniform_int_distribution<int> uniform_dist2(0, textures.size() - 1);
		int spawnPoint = uniform_dist(generator);

		GameObject* monster = new GameObject();
		monster->body = MonsterGenerator::createMonsterBody(spawnPoints[spawnPoint].x, spawnPoints[spawnPoint].y, world.getBoxWorld());
		//monster->body = MonsterGenerator::createMonsterBody(spawnPoints[0].x, spawnPoints[0].y, world.getBoxWorld());
		monster->body->SetUserData(monster);
		monster->addComponent(new MonsterRendererComponent(monster, textures[uniform_dist2(generator)]));
		monster->addComponent(new HealthComponent(monster, 100));
		monster->addComponent(new DropComponent(monster));
		monster->addComponent(new EnemyComponent(monster));
		FiniteStateMachine* brain = new FiniteStateMachine(monster);
		brain->pushState(new FollowState(monster, brain, &world));
		monster->addComponent(brain);
		world.addGameObjectNextFrame(monster);
	
		if(spawnFrequency > 1 && (spawnFrequency *= 0.95) < 1) spawnFrequency = 1;


		lastSpawn = clock.getElapsedTime().asSeconds();
	}

	if (soundTimer.getElapsedTime().asSeconds() > 7) {
		sound_manager.playSmallMonsterEntry();
		
		soundTimer.restart();
	}
	
}
コード例 #24
0
ファイル: rand_gen.cpp プロジェクト: gmfricke/PowerSearch3D
/*
Poisson distribution
f(n, lambda) = lambda^n exp(-lambda)/n!
Algorithm Poisson random number (Knuth):
init:          Let L =exp(-lambda), k=0 and p =1
do:          k = k+
Generate uniform random number u in [0,1]
and let p =p*u
while p > L.
return k - 1.
*/
int rand_gen::poisson_dist(double lambda){

double L=exp(-1*lambda);


int k;
double p=1.;
k = 0;

do{
k = k + 1;

p = p*uniform_dist(0.,1.);
} while (p > L);

return k - 1;
}
コード例 #25
0
TEST(GeoLib, SurfaceIsPointInSurface)
{
    std::vector<std::function<double(double, double)>> surface_functions;
    surface_functions.push_back(constant);
    surface_functions.push_back(coscos);

    for (auto f : surface_functions) {
        std::random_device rd;

        std::string name("Surface");
        // generate ll and ur in random way
        std::mt19937 random_engine_mt19937(rd());
        std::normal_distribution<> normal_dist_ll(-10, 2);
        std::normal_distribution<> normal_dist_ur(10, 2);
        MathLib::Point3d ll(std::array<double,3>({{
                normal_dist_ll(random_engine_mt19937),
                normal_dist_ll(random_engine_mt19937),
                0.0
            }
        }));
        MathLib::Point3d ur(std::array<double,3>({{
                normal_dist_ur(random_engine_mt19937),
                normal_dist_ur(random_engine_mt19937),
                0.0
            }
        }));
        for (std::size_t k(0); k<3; ++k)
            if (ll[k] > ur[k])
                std::swap(ll[k], ur[k]);

        // random discretization of the domain
        std::default_random_engine re(rd());
        std::uniform_int_distribution<std::size_t> uniform_dist(2, 25);
        std::array<std::size_t,2> n_steps = {{uniform_dist(re),uniform_dist(re)}};

        std::unique_ptr<MeshLib::Mesh> sfc_mesh(
            MeshLib::MeshGenerator::createSurfaceMesh(
                name, ll, ur, n_steps, f
            )
        );

        // random rotation angles
        std::normal_distribution<> normal_dist_angles(
            0, boost::math::double_constants::two_pi);
        std::array<double,3> euler_angles = {{
                normal_dist_angles(random_engine_mt19937),
                normal_dist_angles(random_engine_mt19937),
                normal_dist_angles(random_engine_mt19937)
            }
        };

        MathLib::DenseMatrix<double, std::size_t> rot_mat(getRotMat(
                    euler_angles[0], euler_angles[1], euler_angles[2]));

        std::vector<MeshLib::Node*> const& nodes(sfc_mesh->getNodes());
        GeoLib::rotatePoints<MeshLib::Node>(rot_mat, nodes);

        MathLib::Vector3 const normal(0,0,1.0);
        MathLib::Vector3 const surface_normal(rot_mat * normal);
        double const eps(1e-6);
        MathLib::Vector3 const displacement(eps * surface_normal);

        GeoLib::GEOObjects geometries;
        MeshLib::convertMeshToGeo(*sfc_mesh, geometries);

        std::vector<GeoLib::Surface*> const& sfcs(*geometries.getSurfaceVec(name));
        GeoLib::Surface const*const sfc(sfcs.front());
        std::vector<GeoLib::Point*> const& pnts(*geometries.getPointVec(name));
        // test triangle edge point of the surface triangles
        for (auto const p : pnts) {
            EXPECT_TRUE(sfc->isPntInSfc(*p));
            MathLib::Point3d q(*p);
            for (std::size_t k(0); k<3; ++k)
                q[k] += displacement[k];
            EXPECT_FALSE(sfc->isPntInSfc(q));
        }
        // test edge middle points of the triangles
        for (std::size_t k(0); k<sfc->getNTriangles(); ++k) {
            MathLib::Point3d p, q, r;
            std::tie(p,q,r) = getEdgeMiddlePoints(*(*sfc)[k]);
            EXPECT_TRUE(sfc->isPntInSfc(p));
            EXPECT_TRUE(sfc->isPntInSfc(q));
            EXPECT_TRUE(sfc->isPntInSfc(r));
        }
    }
}
コード例 #26
0
int main(int argc, char *argv[])
{

#ifdef __FreeBSD__
    SimpleLogger().Write() << "Not supported on FreeBSD";
    return 0;
#endif
#ifdef _WIN32
    SimpleLogger().Write() << "Not supported on Windows";
    return 0;
#else

    LogPolicy::GetInstance().Unmute();
    boost::filesystem::path test_path;
    try
    {
        SimpleLogger().Write() << "starting up engines, " << g_GIT_DESCRIPTION;

        if (1 == argc)
        {
            SimpleLogger().Write(logWARNING) << "usage: " << argv[0] << " /path/on/device";
            return -1;
        }

        test_path = boost::filesystem::path(argv[1]);
        test_path /= "osrm.tst";
        SimpleLogger().Write(logDEBUG) << "temporary file: " << test_path.string();

        // create files for testing
        if (2 == argc)
        {
            // create file to test
            if (boost::filesystem::exists(test_path))
            {
                throw osrm::exception("Data file already exists");
            }

            int *random_array = new int[number_of_elements];
            std::generate(random_array, random_array + number_of_elements, std::rand);
#ifdef __APPLE__
            FILE *fd = fopen(test_path.string().c_str(), "w");
            fcntl(fileno(fd), F_NOCACHE, 1);
            fcntl(fileno(fd), F_RDAHEAD, 0);
            TIMER_START(write_1gb);
            write(fileno(fd), (char *)random_array, number_of_elements * sizeof(unsigned));
            TIMER_STOP(write_1gb);
            fclose(fd);
#endif
#ifdef __linux__
            int file_desc =
                open(test_path.string().c_str(), O_CREAT | O_TRUNC | O_WRONLY | O_SYNC, S_IRWXU);
            if (-1 == file_desc)
            {
                throw osrm::exception("Could not open random data file");
            }
            TIMER_START(write_1gb);
            int ret = write(file_desc, random_array, number_of_elements * sizeof(unsigned));
            if (0 > ret)
            {
                throw osrm::exception("could not write random data file");
            }
            TIMER_STOP(write_1gb);
            close(file_desc);
#endif
            delete[] random_array;
            SimpleLogger().Write(logDEBUG) << "writing raw 1GB took " << TIMER_SEC(write_1gb)
                                           << "s";
            SimpleLogger().Write() << "raw write performance: " << std::setprecision(5)
                                   << std::fixed << 1024 * 1024 / TIMER_SEC(write_1gb) << "MB/sec";

            SimpleLogger().Write(logDEBUG)
                << "finished creation of random data. Flush disk cache now!";
        }
        else
        {
            // Run Non-Cached I/O benchmarks
            if (!boost::filesystem::exists(test_path))
            {
                throw osrm::exception("data file does not exist");
            }

            // volatiles do not get optimized
            Statistics stats;

#ifdef __APPLE__
            volatile unsigned single_block[1024];
            char *raw_array = new char[number_of_elements * sizeof(unsigned)];
            FILE *fd = fopen(test_path.string().c_str(), "r");
            fcntl(fileno(fd), F_NOCACHE, 1);
            fcntl(fileno(fd), F_RDAHEAD, 0);
#endif
#ifdef __linux__
            char *single_block = (char *)memalign(512, 1024 * sizeof(unsigned));

            int file_desc = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC);
            if (-1 == file_desc)
            {
                SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno);
                return -1;
            }
            char *raw_array = (char *)memalign(512, number_of_elements * sizeof(unsigned));
#endif
            TIMER_START(read_1gb);
#ifdef __APPLE__
            read(fileno(fd), raw_array, number_of_elements * sizeof(unsigned));
            close(fileno(fd));
            fd = fopen(test_path.string().c_str(), "r");
#endif
#ifdef __linux__
            int ret = read(file_desc, raw_array, number_of_elements * sizeof(unsigned));
            SimpleLogger().Write(logDEBUG) << "read " << ret
                                           << " bytes, error: " << strerror(errno);
            close(file_desc);
            file_desc = open(test_path.string().c_str(), O_RDONLY | O_DIRECT | O_SYNC);
            SimpleLogger().Write(logDEBUG) << "opened, error: " << strerror(errno);
#endif
            TIMER_STOP(read_1gb);

            SimpleLogger().Write(logDEBUG) << "reading raw 1GB took " << TIMER_SEC(read_1gb) << "s";
            SimpleLogger().Write() << "raw read performance: " << std::setprecision(5) << std::fixed
                                   << 1024 * 1024 / TIMER_SEC(read_1gb) << "MB/sec";

            std::vector<double> timing_results_raw_random;
            SimpleLogger().Write(logDEBUG) << "running 1000 random I/Os of 4KB";

#ifdef __APPLE__
            fseek(fd, 0, SEEK_SET);
#endif
#ifdef __linux__
            lseek(file_desc, 0, SEEK_SET);
#endif
            // make 1000 random access, time each I/O seperately
            unsigned number_of_blocks = (number_of_elements * sizeof(unsigned) - 1) / 4096;
            std::random_device rd;
            std::default_random_engine e1(rd());
            std::uniform_int_distribution<unsigned> uniform_dist(0, number_of_blocks - 1);
            for (unsigned i = 0; i < 1000; ++i)
            {
                unsigned block_to_read = uniform_dist(e1);
                off_t current_offset = block_to_read * 4096;
                TIMER_START(random_access);
#ifdef __APPLE__
                int ret1 = fseek(fd, current_offset, SEEK_SET);
                int ret2 = read(fileno(fd), (char *)&single_block[0], 4096);
#endif

#ifdef __FreeBSD__
                int ret1 = 0;
                int ret2 = 0;
#endif

#ifdef __linux__
                int ret1 = lseek(file_desc, current_offset, SEEK_SET);
                int ret2 = read(file_desc, (char *)single_block, 4096);
#endif
                TIMER_STOP(random_access);
                if (((off_t)-1) == ret1)
                {
                    SimpleLogger().Write(logWARNING) << "offset: " << current_offset;
                    SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno);
                    throw osrm::exception("seek error");
                }
                if (-1 == ret2)
                {
                    SimpleLogger().Write(logWARNING) << "offset: " << current_offset;
                    SimpleLogger().Write(logWARNING) << "read error " << strerror(errno);
                    throw osrm::exception("read error");
                }
                timing_results_raw_random.push_back(TIMER_SEC(random_access));
            }

            // Do statistics
            SimpleLogger().Write(logDEBUG) << "running raw random I/O statistics";
            std::ofstream random_csv("random.csv", std::ios::trunc);
            for (unsigned i = 0; i < timing_results_raw_random.size(); ++i)
            {
                random_csv << i << ", " << timing_results_raw_random[i] << std::endl;
            }
            random_csv.close();
            RunStatistics(timing_results_raw_random, stats);

            SimpleLogger().Write() << "raw random I/O: " << std::setprecision(5) << std::fixed
                                   << "min: " << stats.min << "ms, "
                                   << "mean: " << stats.mean << "ms, "
                                   << "med: " << stats.med << "ms, "
                                   << "max: " << stats.max << "ms, "
                                   << "dev: " << stats.dev << "ms";

            std::vector<double> timing_results_raw_seq;
#ifdef __APPLE__
            fseek(fd, 0, SEEK_SET);
#endif
#ifdef __linux__
            lseek(file_desc, 0, SEEK_SET);
#endif

            // read every 100th block
            for (unsigned i = 0; i < 1000; ++i)
            {
                off_t current_offset = i * 4096;
                TIMER_START(read_every_100);
#ifdef __APPLE__
                int ret1 = fseek(fd, current_offset, SEEK_SET);
                int ret2 = read(fileno(fd), (char *)&single_block, 4096);
#endif

#ifdef __FreeBSD__
                int ret1 = 0;
                int ret2 = 0;
#endif

#ifdef __linux__
                int ret1 = lseek(file_desc, current_offset, SEEK_SET);

                int ret2 = read(file_desc, (char *)single_block, 4096);
#endif
                TIMER_STOP(read_every_100);
                if (((off_t)-1) == ret1)
                {
                    SimpleLogger().Write(logWARNING) << "offset: " << current_offset;
                    SimpleLogger().Write(logWARNING) << "seek error " << strerror(errno);
                    throw osrm::exception("seek error");
                }
                if (-1 == ret2)
                {
                    SimpleLogger().Write(logWARNING) << "offset: " << current_offset;
                    SimpleLogger().Write(logWARNING) << "read error " << strerror(errno);
                    throw osrm::exception("read error");
                }
                timing_results_raw_seq.push_back(TIMER_SEC(read_every_100));
            }
#ifdef __APPLE__
            fclose(fd);
            // free(single_element);
            free(raw_array);
// free(single_block);
#endif
#ifdef __linux__
            close(file_desc);
#endif
            // Do statistics
            SimpleLogger().Write(logDEBUG) << "running sequential I/O statistics";
            // print simple statistics: min, max, median, variance
            std::ofstream seq_csv("sequential.csv", std::ios::trunc);
            for (unsigned i = 0; i < timing_results_raw_seq.size(); ++i)
            {
                seq_csv << i << ", " << timing_results_raw_seq[i] << std::endl;
            }
            seq_csv.close();
            RunStatistics(timing_results_raw_seq, stats);
            SimpleLogger().Write() << "raw sequential I/O: " << std::setprecision(5) << std::fixed
                                   << "min: " << stats.min << "ms, "
                                   << "mean: " << stats.mean << "ms, "
                                   << "med: " << stats.med << "ms, "
                                   << "max: " << stats.max << "ms, "
                                   << "dev: " << stats.dev << "ms";

            if (boost::filesystem::exists(test_path))
            {
                boost::filesystem::remove(test_path);
                SimpleLogger().Write(logDEBUG) << "removing temporary files";
            }
        }
    }
    catch (const std::exception &e)
    {
        SimpleLogger().Write(logWARNING) << "caught exception: " << e.what();
        SimpleLogger().Write(logWARNING) << "cleaning up, and exiting";
        if (boost::filesystem::exists(test_path))
        {
            boost::filesystem::remove(test_path);
            SimpleLogger().Write(logWARNING) << "removing temporary files";
        }
        return -1;
    }
    return 0;
#endif
}
コード例 #27
0
 Scalar random_scalar() {
     std::uniform_real_distribution<T> uniform_dist(0.0, 1.0);
     return uniform_dist(rand_eng);
 }
コード例 #28
0
ファイル: tests.cpp プロジェクト: 1ee7/flight
TEST_F(StereoOctomapTest, CheckAgainstLinearSearch) {

    int num_points = 10000;

    vector<float> x;
    vector<float> y;
    vector<float> z;

    StereoOctomap *stereo_octomap = new StereoOctomap(bot_frames_);

    // create a random point cloud

    std::uniform_real_distribution<double> uniform_dist(-1000, 1000);
    std::random_device rd;
    std::default_random_engine rand_engine(rd());

    for (int i = 0; i < num_points; i++) {

        double this_point[3];

        // generate a random point
        this_point[0] = uniform_dist(rand_engine);
        this_point[1] = uniform_dist(rand_engine);
        this_point[2] = uniform_dist(rand_engine);

        //std::cout << "Point: (" << this_point[0] << ", " << this_point[1] << ", " << this_point[2] << ")" << std::endl;

        double translated_point[3];

        GlobalToCameraFrame(this_point, translated_point);

        x.push_back(translated_point[0]);
        y.push_back(translated_point[1]);
        z.push_back(translated_point[2]);
    }

    lcmt::stereo msg;

    msg.timestamp = GetTimestampNow();

    msg.x = x;
    msg.y = y;
    msg.z = z;

    msg.number_of_points = num_points;

    msg.frame_number = 0;
    msg.video_number = 0;

    stereo_octomap->ProcessStereoMessage(&msg);

    // now perform a bunch of searches

    double time_linear = 0, time_octomap = 0;

    int num_searches = 1000;

    for (int i = 0; i < num_searches; i++) {

        double search_point[3];

        // generate a random point
        search_point[0] = uniform_dist(rand_engine);
        search_point[1] = uniform_dist(rand_engine);
        search_point[2] = uniform_dist(rand_engine);

        //std::cout << "search_point: (" << search_point[0] << ", " << search_point[1] << ", " << search_point[2] << ")" << std::endl;


        tic();
        double linear_search_dist = NearestNeighborLinear(x, y, z, search_point);
        time_linear += toc();

        tic();
        double octomap_dist = stereo_octomap->NearestNeighbor(search_point);
        time_octomap += toc();

        EXPECT_NEAR(octomap_dist, linear_search_dist, TOLERANCE);

    }

    std::cout << "\tFor " << num_searches << " searches over " << num_points << " points: " << std:: endl << "\t\tlinear time = " << time_linear << ", octree time = " << time_octomap << ", for a speedup of: " << time_linear / time_octomap << "x" << std::endl;


    delete stereo_octomap;

}
コード例 #29
0
ファイル: rand_gen.cpp プロジェクト: gmfricke/PowerSearch3D
/*
To simulate exponential distribution exp(-lambda*x), the inverse
 method is used.
The cumulative distribution function for the exponential
distribution is:1-exp(-lambda*x). The inversion function
is  -log(1-U)/lambda. The simplified form is -log(U)/lambda,
where U is a uniform [0,1] random variable.
 http://cg.scs.carleton.ca/~luc/rnbookindex.html
*/
double rand_gen::exponential_dist(double lambda){
return(-1*log(uniform_dist(0.,1.))/lambda);
}
コード例 #30
0
void AugmentationNode::augment_images(vector<cv::Mat> imgs, vector<int> labels)
{
	int	shift;
	vector< vector<cv::Mat> > 	out_imgs;
	vector< vector<int> > 		out_labels;

	out_imgs.resize(_aug_factor + 1);
	out_labels.resize(_aug_factor + 1);

	for(int k=0; k < imgs.size(); k++){
		_counter++;
		
		// Expand source image (Assuming image is square)
		//
		shift = imgs[k].cols / 2;
		cv::Mat	expImg(imgs[k].rows * 2, imgs[k].cols * 2, imgs[k].type(), 255);
		if( imgs[k].type() == CV_8UC3 ) {
			// Color image, make sure all channels set to 255
			expImg = cv::Scalar(255, 255, 255);
		}
		imgs[k].copyTo(expImg(cv::Rect(shift, shift, imgs[k].cols, imgs[k].rows)));
	
		
		// Get ROI
		float tl_row = expImg.rows/2.0F - shift;
		float tl_col = expImg.cols/2.0F - shift;
		float br_row = expImg.rows/2.0F + shift;
		float br_col = expImg.cols/2.0F + shift;
		cv::Point tl(tl_row, tl_col);
		cv::Point br(br_row, br_col);

		// Setup a rectangle to define region of interest
		cv::Rect cellROI(tl, br);

		for(int i=0; i < _aug_factor; i++) {
			_counter++;

			// Define variables
			int label = labels[k];

			// construct a trivial random generator engine from a time-based seed:
	  		unsigned seed = chrono::system_clock::now().time_since_epoch().count();
	  		default_random_engine generator(seed);
			uniform_real_distribution<double> uniform_dist(0.0, 1.0);

			double Flipx = round(uniform_dist(generator)); 				// randomly distributed reflections over x and y
			double Flipy = round(uniform_dist(generator));
			double Phi = 360 * uniform_dist(generator); 			// rotation angle uniformly distributed on [0, 2pi] radians
			double Tx = 20 * (uniform_dist(generator) - 0.5); 			// 10-pixel uniformly distributed translation
			double Ty = 20 * (uniform_dist(generator) - 0.5);
			double Shx = PI/180 * 20 * (uniform_dist(generator)-0.5);  	// shear angle uniformly distributed on [-20, 20] degrees
			double Shy = PI/180 * 20 * (uniform_dist(generator)-0.5);
			double Sx = 1/1.2 + (1.2 - 1/1.2)*uniform_dist(generator); 	// scale uniformly distributed on [1/1.2, 1.2]
			double Sy = 1/1.2 + (1.2 - 1/1.2)*uniform_dist(generator);

			cv::Mat warped_img;

			// Translation
			cv::Mat trans_M(3, 3, CV_64F);
			trans_M.at<double>(0,0) = 1;
			trans_M.at<double>(0,1) = 0;
			trans_M.at<double>(0,2) = Tx;

			trans_M.at<double>(1,0) = 0;
			trans_M.at<double>(1,1) = 1;
			trans_M.at<double>(1,2) = Ty;

			trans_M.at<double>(2,0) = 0;
			trans_M.at<double>(2,1) = 0;
			trans_M.at<double>(2,2) = 0;

			// Scaling
			cv::Mat scaling_M(3, 3, CV_64F);
			scaling_M.at<double>(0,0) = Sx;
			scaling_M.at<double>(0,1) = 0;
			scaling_M.at<double>(0,2) = 0;

			scaling_M.at<double>(1,0) = 0;
			scaling_M.at<double>(1,1) = Sy;
			scaling_M.at<double>(1,2) = 0;

			scaling_M.at<double>(2,0) = 0;
			scaling_M.at<double>(2,1) = 0;
			scaling_M.at<double>(2,2) = 0;

			// Shearing 
			cv::Mat shear_M(3, 3, CV_64F);
			shear_M.at<double>(0,0) = 1;
			shear_M.at<double>(0,1) = Shy;
			shear_M.at<double>(0,2) = 0;

			shear_M.at<double>(1,0) = Shx;
			shear_M.at<double>(1,1) = 1;
			shear_M.at<double>(1,2) = 0;

			shear_M.at<double>(2,0) = 0;
			shear_M.at<double>(2,1) = 0;
			shear_M.at<double>(2,2) = 0;

			// Rotation 
			cv::Mat rot(2, 3, CV_64F);
			cv::Point2f center(expImg.rows/2.0F, expImg.cols/2.0F);
			rot = getRotationMatrix2D(center, Phi, 1.0);	

			cv::Mat rot_M(3, 3, CV_64F, cv::Scalar(0));
			rot(cv::Rect(0,0,3,2)).copyTo(rot_M.colRange(0,3).rowRange(0,2));

			// Accumulate
			cv::Mat acc(3, 3, CV_64F);

			acc = trans_M * scaling_M * shear_M * rot_M;

			cv::Mat acc_M = acc.colRange(0,3).rowRange(0,2);
			cv::warpAffine( expImg, warped_img, acc_M, expImg.size());

			// Crop Image
			double m00 = acc_M.at<double>(0,0);
			double m01 = acc_M.at<double>(0,1);
			double m10 = acc_M.at<double>(1,0);
			double m11 = acc_M.at<double>(1,1);
			double m02 = acc_M.at<double>(0,2);
			double m12 = acc_M.at<double>(1,2); 

			int new_cx = expImg.rows/2.0F * m00 + expImg.cols/2.0F * m01 + m02;
			int new_cy = expImg.rows/2.0F * m10 + expImg.cols/2.0F * m11 + m12;

			// Get ROI
			double tl_row = new_cx - shift;
			double tl_col = new_cy - shift;
			double br_row = new_cx + shift;
			double br_col = new_cy + shift;
			cv::Point tl(tl_row, tl_col);
			cv::Point br(br_row, br_col);


			cv::Rect new_cellROI(tl, br);
			cv::Mat final_img = warped_img(new_cellROI);

			// Flip
			if( Flipx == 1 && Flipy == 1) {
				cv::flip(final_img, final_img, -1);
			}
			else if(Flipx == 0 && Flipy == 1){
				cv::flip(final_img, final_img, 1);
			}
			else if(Flipx == 1 && Flipy == 0){
				cv::flip(final_img, final_img, 0);
			}
			
        	if(!final_img.isContinuous()){
				final_img=final_img.clone();
			}

			// Accumulate
			out_imgs[i].push_back(final_img);
			out_labels[i].push_back(label);
		}

		out_imgs[_aug_factor].push_back(imgs[k]);
		out_labels[_aug_factor].push_back(labels[k]);

		// TODO - For now we are overriding the mode until we get Mode::Alternate 
		// working properly
		if( out_imgs[0].size() > _transferSize ) {
			for(int e = 0; e < out_imgs.size(); e++) {
			
				copy_to_edge(out_imgs[e], out_labels[e], e % _out_edges.size());
				// Clean
				out_imgs[e].clear();
				out_labels[e].clear();
			}
		}
	}

	// Send any leftover data
	if( out_imgs[0].size() > 0 ) {

		// TODO - For now we are overriding the mode until we get Mode::Alternate 
		// working properly
		for(int e = 0; e < out_imgs.size(); e++) {
			copy_to_edge(out_imgs[e], out_labels[e], e % _out_edges.size());
			// Clean
			out_imgs[e].clear();
			out_labels[e].clear();
		}
	}
}