ALMaSS  1.2 (after EcoStack, March 2024)
The Animal, Landscape and Man Simulation System
ALMaSS_Random.cpp File Reference

Implementing almass specific random number generation and probability distribution classes, based on/wrapping std functionality. More...

#include <iostream>
#include <fstream>
#include <chrono>
#include <math.h>
#include <sstream>
#include <random>
#include <algorithm>
#include "ALMaSS_Random.h"
#include "../Landscape/MapErrorMsg.h"
#include "../Landscape/Configurator.h"

Typedefs

using DISCRETE_DIST = std::discrete_distribution<>
 
using UNIINT_DIST = std::uniform_int_distribution< int >
 
using NORMAL_DIST = std::normal_distribution< double >
 
using UNIREAL_DIST = std::uniform_real_distribution< double >
 
using GAMMA_DIST = std::gamma_distribution< double >
 
using CAUCHY_DIST = std::cauchy_distribution< double >
 
using EXPONENTIAL_DIST = std::exponential_distribution< double >
 

Functions

std::mt19937 g_generator (seed_seq)
 
void g_generator_fixed_fnc (const unsigned int s)
 
std::uniform_real_distribution g_uni_std_dist (0, 1)
 
std::uniform_int_distribution g_uni_dist2 (0, 9999)
 
std::uniform_int_distribution g_uni_dist3 (0, 999)
 
double g_rand_uni_fnc ()
 
int g_rand_uni2_fnc ()
 
int g_rand_uni3_fnc ()
 
int g_random_fnc (const int a_range)
 
int g_binomial_coefficient (const int n, const int k)
 
std::vector< double > g_beta_binomial_probabilities_fnc (const int a_n, const double a_alpha, const double a_beta, const bool a_noZero)
 Local utility function for generating the weights-vector for the beta binomial distribution from input parameters. More...
 
void g_init_random_seed_fnc ()
 Init_random_seed() randomizes the random generator based on the configuration (either fixed seed or random seed) More...
 

Variables

CfgBool cfg_Fixed_random_sequence
 
CfgInt cfg_FixedRandomSeed
 
std::seed_seq seed_seq
 

Detailed Description

Implementing almass specific random number generation and probability distribution classes, based on/wrapping std functionality.

Author
Luminita C. Totu
Version
August 2023

LICENSE

DESCRIPTION

This file contains the definition of the rng global object, which holds the basic randomess source (the seeded pseudo random generator). The file also contains the definition of functions declared in almass_random-h header file

Typedef Documentation

◆ CAUCHY_DIST

using CAUCHY_DIST = std::cauchy_distribution<double>

◆ DISCRETE_DIST

using DISCRETE_DIST = std::discrete_distribution<>

◆ EXPONENTIAL_DIST

using EXPONENTIAL_DIST = std::exponential_distribution<double>

◆ GAMMA_DIST

using GAMMA_DIST = std::gamma_distribution<double>

◆ NORMAL_DIST

using NORMAL_DIST = std::normal_distribution<double>

◆ UNIINT_DIST

using UNIINT_DIST = std::uniform_int_distribution<int>

◆ UNIREAL_DIST

using UNIREAL_DIST = std::uniform_real_distribution<double>

Function Documentation

◆ g_beta_binomial_probabilities_fnc()

std::vector<double> g_beta_binomial_probabilities_fnc ( const int  a_n,
const double  a_alpha,
const double  a_beta,
const bool  a_noZero 
)

Local utility function for generating the weights-vector for the beta binomial distribution from input parameters.

Parameters
a_nthe maximum value of the random variate
a_alphaa_alpha, a_beta parameters of the underlying beta distribution, together determine the shape/profile of the distribution
a_betaa_alpha, a_beta parameters of the underlying beta distribution, together determine the shape/profile of the distribution
a_noZeroa_noZero extra parameter to cancel out the probability for the zero value (started as quick hack for beetle feature)
Returns
The distribution
102  {
103  std::vector<double> probabilities(a_n + 1);
104 
105  for (int k = 0; k <= a_n; k = k + 1)
106  {
107  const double cnk = g_binomial_coefficient(a_n, k);
108  const double b1 = std::beta(k + a_alpha, -k + a_beta + a_n);
109  const double b2 = std::beta(a_alpha, a_beta);
110  probabilities[k] = cnk * b1 / b2;
111  }
112  if (a_noZero) { probabilities[0] = 0; }
113  return probabilities;
114 }

References g_binomial_coefficient().

Referenced by probability_distribution::probability_distribution().

◆ g_binomial_coefficient()

int g_binomial_coefficient ( const int  n,
const int  k 
)

A function to calculate binomial coefficients

89  {
90  if (k == 0 || k == n) return 1;
91  return g_binomial_coefficient(n - 1, k - 1) + g_binomial_coefficient(n - 1, k);
92 }

Referenced by g_beta_binomial_probabilities_fnc().

◆ g_generator()

◆ g_generator_fixed_fnc()

void g_generator_fixed_fnc ( const unsigned int  s)

fixed seed for the random generator

43  {
44  g_generator.seed(s);
45 }

References g_generator().

Referenced by g_init_random_seed_fnc().

◆ g_init_random_seed_fnc()

void g_init_random_seed_fnc ( )

Init_random_seed() randomizes the random generator based on the configuration (either fixed seed or random seed)

407  {
408  int seed = 0;
409 
410  // Randomize the random generator.
412  {
413  seed = cfg_FixedRandomSeed.value();
414  srand(seed); // Use of rand() discouraged. use internal almass_random.h functionality
415  g_generator_fixed_fnc(seed);
416 
417  /* Logging */
418  std::cout << "Setting a fixed seed for random number generation: " << seed << "\n";
419  g_msg->WarnAddInfo(WARN_MSG, "Setting a fixed seed for random number generation: ", seed);
420  }
421  else
422  {
423  seed = static_cast<int>(time(nullptr));
424  //std::ofstream RecordSeedFile;
425  //RecordSeedFile.open("RecordedSeed.txt");
426  //RecordSeedFile << seed;
427  //RecordSeedFile.close();
428  srand(seed); // Use of rand() discouraged. use internal almass_random.h functionality
429 
430  /* Logging */
431  //std::cout << "Setting a timestamp-based seed for srand: " << seed << "\n";
432  //g_msg->WarnAddInfo(WARN_MSG, "Setting a timestamp-based seed for srand: ", seed);
433  /* Recover the boost seed */
434  std::string boost_seed_seq_str;
435  if (seed_seq.size() > 10) { boost_seed_seq_str = "More than 10 elements, too long to display"; }
436  else
437  {
438  std::uintmax_t iter[10] = { 0 };
439  boost_seed_seq_str = "(" + std::to_string(seed_seq.size()) + " element/s) ";
440  seed_seq.param(iter);
441  for (int i = 0; i < seed_seq.size(); i++) { boost_seed_seq_str = boost_seed_seq_str + std::to_string(iter[i]) + " "; }
442  }
443  std::cout << "Setting a timestamp-based seed sequence for random number generation: " << boost_seed_seq_str << "\n";
444  //g_msg->WarnAddInfo(WARN_MSG, "Setting a timestamp-based seed sequence for boost: ", boost_seed_seq_str);
445  }
446  }

References cfg_Fixed_random_sequence, cfg_FixedRandomSeed, g_generator_fixed_fnc(), g_msg, seed_seq, CfgInt::value(), CfgBool::value(), WARN_MSG, and MapErrorMsg::WarnAddInfo().

Referenced by main().

◆ g_rand_uni2_fnc()

int g_rand_uni2_fnc ( )

g_rand_uni2() Return a random integer number from {0,1,...,9999} with uniform probability Function implemented for old code compatibility. Ideally not to be used in new code.

62 { return g_uni_dist2(g_generator); }

References g_generator(), and g_uni_dist2().

◆ g_rand_uni3_fnc()

int g_rand_uni3_fnc ( )

g_rand_uni2() Return a random integer number from {0,1,...,999} with uniform probability Function implemented for old code compatibility. Ideally not to be used in new code.

68 { return g_uni_dist3(g_generator); }

References g_generator(), and g_uni_dist3().

◆ g_rand_uni_fnc()

double g_rand_uni_fnc ( )

frequently used function to return a double between [0,1) with uniform probability

56 { return g_uni_std_dist(g_generator);}

References g_generator(), and g_uni_std_dist().

Referenced by PoecilusCupreus_Adult::Ageing(), Beetle_Adult::Ageing(), Aphid_Population_Manager::Aphid_Population_Manager(), BeetleBank::BeetleBank(), Ladybird_Adult::BeginStep(), Osmia_Female::BeginStep(), Hare_Infant::BeginStep(), Hare_Young::BeginStep(), Hare_Juvenile::BeginStep(), Hare_Male::BeginStep(), Hare_Female::BeginStep(), Erigone_Juvenile::CalcDrought(), Oedothorax_Juvenile::CalcDrought(), Oedothorax_Female::CalcDrought(), Erigone_Female::CalcDrought(), Osmia_Female::CalcParaistised(), Osmia_Female::CalculateEggLoad(), PoecilusCupreus_Adult::CheckDormancy(), PoecilusCupreus_Adult::CheckDormancyExit(), Beetle_Adult::CheckDormancyExit(), Beetle_Base::ChooseDirection(), Osmia_Egg::DailyMortality(), Osmia_Larva::DailyMortality(), Osmia_Prepupa::DailyMortality(), Osmia_Pupa::DailyMortality(), Beetle_Egg_List::DailyMortality(), Beetle_Adult::DDepMort(), Vole_JuvenileMale::Dispersal(), Vole_Male::Dispersal(), Vole_JuvenileFemale::Dispersal(), DE_OCarrots::Do(), FlowerStrip::DoDevelopment(), FlowerStripWithRotation::DoDevelopment(), FieldBoundary::DoDevelopment(), Ladybird_Population_Manager::DoExtremeTempActions(), Ladybird_Population_Manager::DoFirst(), Farm::DoIt(), Farm::DoIt_prob(), PesticideToxicity::doOverspray(), Vole_Base::DoWalking(), Vole_Base::DoWalkingCorrect(), Spider_Egg::EndStep(), Spider_Juvenile::EndStep(), Spider_Female::EndStep(), Beetle_Larvae::EndStep(), Beetle_Pupae::EndStep(), Beetle_Adult::EndStep(), Beetle_Egg_List::ExtremeTempMortality(), PoecilusCupreus_Population_Manager::FertilizerMortality(), FarmManager::FindClosestFarmOpennessProb(), FarmManager::FindClosestFarmOpennessProbNearRoostIsBest(), FarmManager::FindClosestFarmOpennessProbSmallIsBest(), Population_Manager::FindIndividual(), VegElement::ForceGrowthInitialiseForFirstYearCrop(), VegElement::ForceGrowthInitialize(), g_random_fnc(), Hare_Male::GeneralOrganoPhosphate(), Hare_Female::GeneralOrganoPhosphate(), Beetle_Larvae::GetDensityDependentMortality(), THare_Population_Manager::GetLitterSize(), FarmManager::GetSpilledGrain(), FarmManager::GetSpilledMaize(), THare_Population_Manager::Hunting(), THare_Population_Manager::HuntingDifferentiatedBeetleBankArea(), THare_Population_Manager::HuntingGrid(), Vole_Population_Manager::Init(), Vole_Base::Init(), Aphid_Population_Manager::initialiseSimWithEggs(), Osmia_Nest_Manager::InitOsmiaBeeNesting(), Beetle_Egg_List::InternalPesticideHandlingAndResponse(), Beetle_Larvae::InternalPesticideHandlingAndResponse(), Beetle_Pupae::InternalPesticideHandlingAndResponse(), Beetle_Adult::InternalPesticideHandlingAndResponse(), Aphid_Population_Manager::isEnoughNextLifeStageShared(), OsmiaPolygonEntry::IsOsmiaNestPossible(), Vole_Base::MortalityTest(), Vole_Male::MortalityTest(), PoecilusCupreus_Adult::MoveTo_Quality_Assess(), Beetle_Adult::MoveTo_Quality_Assess(), MownGrassStrip::MownGrassStrip(), GeneticMaterial::Mutation_1(), GeneticMaterial1616::Mutation_1(), GeneticMaterial::Mutation_1ab(), GeneticMaterial::Mutation_2(), GeneticMaterial1616::Mutation_2(), GeneticMaterial::Mutation_3(), GeneticMaterial1616::Mutation_3(), GeneticMaterial256_16::Mutation_3(), GeneticMaterial::Mutation_4(), Landscape::NewElement(), Bembidion_Population_Manager::OnFarmEvent(), PoecilusCupreus_Population_Manager::OnFarmEvent(), Ladybird_Population_Manager::OnFarmEvent(), Vole_JuvenileMale::OnFarmEvent(), Vole_JuvenileFemale::OnFarmEvent(), Osmia_Female::OnFarmEvent(), Vole_Female::OnInfanticideAttempt(), Osmia_Population_Manager::Osmia_Population_Manager(), Osmia_Prepupa::Osmia_Prepupa(), OsmiaParasitoid_Population_Manager::OsmiaParasitoid_Population_Manager(), PermanentSetaside::PermanentSetaside(), Osmia_Female::PlanEggsPerNest(), Pond::Pond(), SkTerritories::PreProcessLandscape2(), PestIncidenceManager::RecalculateIncidence(), Skylark_Male::ReInit(), VegElement::SetVegGrowthScalerRand(), Field::SetVegGrowthScalerRand(), Ladybird_Adult::ShouldStartAggregating(), Population_Manager::Shuffle(), Population_Manager::Shuffle_or_Sort(), Skylark_Male::Skylark_Male(), Beetle_Adult::St_Aggregate(), Skylark_Female::st_Arriving(), Ladybird_Larvae1::St_Develop(), Ladybird_Pupae::St_Develop(), Osmia_Egg::st_Develop(), Spider_Juvenile::st_Develop(), Osmia_Female::st_Develop(), Beetle_Larvae::St_Develop(), Beetle_Pupae::St_Develop(), Hare_Juvenile::st_Developing(), Ladybird_Adult::St_Dispersal(), Ladybird_Pupae::St_Emerge(), Vole_JuvenileMale::st_Eval_n_Explore(), Vole_Male::st_Eval_n_Explore(), Hare_Juvenile::st_Foraging(), Hare_Male::st_Foraging(), Hare_Female::st_Foraging(), Ladybird_Adult::St_Hibernate(), Vole_Male::st_Infanticide(), Skylark_Female::st_Laying(), Osmia_Female::st_ReproductiveBehaviour(), Vole_Population_Manager::SupplyInOlderTerr(), Landscape::SupplyRandomPondIndex(), Landscape::SupplyRandomPondRef(), Weather::Tick(), Landscape::Tick(), Beetle_Adult::Turning(), Aphid_Population_Manager::updateMortalityArrayShared(), THare::WasPredated(), and Hare_Juvenile::WasPredated().

◆ g_random_fnc()

int g_random_fnc ( const int  a_range)

random(a_range) Return a random integer number from {0,1,...,a_range-1} with uniform probability Function implemented for old code compatibility. Ideally not to be used in new code.

74  {
75  //old version 1: int result = (int)(((double) rand() / RAND_MAX. ) * a_range);
76  //old version 2: return (int)(g_rand_uni() * a_range);
77  //old version 3: int result = rand()%a_range;
78  //Note: (int) rounds always down
79  // Tested. This is at least as fast as any of the older versions
80  return static_cast<int>(g_rand_uni_fnc() * a_range);
81  //std::uniform_int_distribution<> temp_uni_dist(0, a_range-1);
82  //return temp_uni_dist(g_generator);
83 }

References g_rand_uni_fnc().

Referenced by Landscape::AddBeetleBanks(), Spider_Juvenile::AssessHabitat(), Farm::AssignPermanentCrop(), Spider_Juvenile::Balloon(), Spider_Juvenile::BallooningMortality(), Spider_Female::BeginStep(), Bembidion_Population_Manager::Bembidion_Population_Manager(), Skylark_Female::CalculateEggNumber(), Erigone_Population_Manager::Catastrophe(), Oedothorax_Population_Manager::Catastrophe(), Vole_Population_Manager::Catastrophe(), Skylark_Population_Manager::Catastrophe(), THare_Population_Manager::Catastrophe(), Beetle_Population_Manager::Catastrophe(), Beetle_Population_Manager::Catastrophe2(), Bembidion_Adult::CheckDormancy(), Beetle_Adult::CheckDormancy(), Beetle_Adult::CheckForDispersal(), Vole_Base::CheckTraps(), Vole_Population_Manager::CreateObjectsInit(), Skylark_Base::DailyMortality(), Vole_JuvenileMale::Dispersal(), Vole_Male::Dispersal(), Vole_JuvenileFemale::Dispersal(), OPotatoes::Do(), RoadsideVerge::DoDevelopment(), Aphid::doMovement(), Vole_Base::DoWalking(), Vole_Base::DoWalkingCorrect(), Vole_Base::Escape(), THare_Population_Manager::ExtraPopMort(), Skylark_Female::FeedYoung(), FarmManager::FindFarmWithOpenness(), FarmManager::FindFarmWithRandom(), Osmia_Female::FindNestLocation(), FarmManager::FindOpennessFarm(), Vole_Population_Manager::FindOutsideRadiusMale(), Vole_Population_Manager::FindRandomMale(), Ladybird_Adult::FindTarget(), Vole_Population_Manager::FindWithinRadiusMale(), THare::Forage(), THare::ForageP(), THare::ForageSquare(), THare::ForageSquareP(), CropRotation::GetFirstCrop(), Farm::GetFirstCropIndex(), CropRotation::GetNextCrop(), THare::GetPegDirection(), FarmManager::GetRandomFarmRefnum(), Weather::GetSnow(), Spider_Egg::Hatch(), Landscape::hb_MarkTheBresenhamWay(), Landscape::hb_StripingDist(), Erigone_Population_Manager::Init(), Oedothorax_Population_Manager::Init(), Vole_Population_Manager::Init(), Skylark_Population_Manager::Init(), THare_Population_Manager::Init(), Beetle_Adult::Init(), GeneticMaterial::Initiation(), GeneticMaterial1616::Initiation(), GeneticMaterial256_16::Initiation(), Ladybird_Population_Manager::Ladybird_Population_Manager(), Landscape::Landscape(), Ladybird_Adult::LongRangeFind(), RasterMap::MissingCellReplace(), RasterMap::MissingCellReplaceWrap(), GeneticMaterial::Mutation_1(), GeneticMaterial1616::Mutation_1(), GeneticMaterial::Mutation_1ab(), GeneticMaterial::Mutation_2(), GeneticMaterial1616::Mutation_2(), GeneticMaterial::Mutation_3(), GeneticMaterial1616::Mutation_3(), GeneticMaterial256_16::Mutation_3(), GeneticMaterial::Mutation_4(), Erigone_Egg::OnFarmEvent(), Oedothorax_Egg::OnFarmEvent(), Erigone_Juvenile::OnFarmEvent(), Oedothorax_Juvenile::OnFarmEvent(), Erigone_Female::OnFarmEvent(), Oedothorax_Female::OnFarmEvent(), Skylark_Clutch::OnFarmEvent(), Skylark_Nestling::OnFarmEvent(), Skylark_PreFledgeling::OnFarmEvent(), Skylark_Female::OnFarmEvent(), Skylark_Male::OnFarmEvent(), Hare_Infant::OnFarmEvent(), Hare_Young::OnFarmEvent(), Osmia_Population_Manager::Osmia_Population_Manager(), PoecilusCupreus_Population_Manager::PoecilusCupreus_Population_Manager(), SkTerritories::PreProcessLandscape2(), VegElement::RandomVegStartValues(), Landscape::ReadPolys2(), GeneticMaterial::Recombine(), GeneticMaterial1616::Recombine(), GeneticMaterial256_16::Recombine(), Skylark_Nestling::ReInit(), Skylark_Adult::ReInit(), THare::Running(), Skylark_Adult::Skylark_Adult(), Skylark_Nestling::Skylark_Nestling(), Spider_Juvenile::Spider_Juvenile(), Beetle_Adult::St_Aggregate(), Skylark_Male::st_CaringForYoung(), Spider_Egg::st_Develop(), Spider_Juvenile::st_Develop(), Skylark_Nestling::st_Developing(), Hare_Male::st_Developing(), Hare_Female::st_Developing(), TPredator::st_Dispersal(), Hare_Juvenile::st_Dispersal(), Skylark_Female::st_Emigrating(), Skylark_Male::st_Emigrating(), Vole_JuvenileMale::st_Eval_n_Explore(), Vole_Male::st_Eval_n_Explore(), Vole_JuvenileFemale::st_Evaluate_n_Explore(), Vole_Female::st_Evaluate_n_Explore(), Skylark_Male::st_FindingTerritory(), Skylark_Female::st_Floating(), Skylark_Male::st_Floating(), TPredator::st_Hunting(), Skylark_Female::st_Immigrating(), Skylark_Male::st_Immigrating(), Vole_JuvenileMale::st_JuvenileExplore(), Vole_Female::st_Lactating(), TPredator::st_Movement(), Spider_Female::Step(), Landscape::SupplyARandomLocPoly(), Landscape::SupplyARandomLocResourcePoly(), THare::THareInit(), TPredator_Population_Manager::TPredator_Population_Manager(), Beetle_Adult::TryToReproduce(), Beetle_Adult::TurningForced(), Beetle_Adult::TurningRandom(), UnsprayedFieldMargin::UnsprayedFieldMargin(), Spider_Juvenile::Walk(), THare::Walking(), Bembidion_Adult::WinterMort(), and Osmia_InCocoon::WinterMortality().

◆ g_uni_dist2()

std::uniform_int_distribution g_uni_dist2 ( ,
9999   
)

Referenced by g_rand_uni2_fnc().

◆ g_uni_dist3()

std::uniform_int_distribution g_uni_dist3 ( ,
999   
)

Referenced by g_rand_uni3_fnc().

◆ g_uni_std_dist()

std::uniform_real_distribution g_uni_std_dist ( ,
 
)

Referenced by g_rand_uni_fnc().

Variable Documentation

◆ cfg_Fixed_random_sequence

CfgBool cfg_Fixed_random_sequence

Referenced by g_init_random_seed_fnc().

◆ cfg_FixedRandomSeed

CfgInt cfg_FixedRandomSeed

Referenced by g_init_random_seed_fnc().

◆ seed_seq

std::seed_seq seed_seq
Initial value:
{
static_cast<std::uintmax_t>(std::chrono::steady_clock::now().time_since_epoch().count())
}

Referenced by g_init_random_seed_fnc().

g_uni_std_dist
std::uniform_real_distribution g_uni_std_dist(0, 1)
g_rand_uni_fnc
double g_rand_uni_fnc()
Definition: ALMaSS_Random.cpp:56
WARN_MSG
Definition: MapErrorMsg.h:38
MapErrorMsg::WarnAddInfo
void WarnAddInfo(MapErrorState a_level, std::string a_add1, std::string a_add2)
Definition: MapErrorMsg.cpp:160
g_uni_dist2
std::uniform_int_distribution g_uni_dist2(0, 9999)
g_binomial_coefficient
int g_binomial_coefficient(const int n, const int k)
Definition: ALMaSS_Random.cpp:89
CfgBool::value
bool value() const
Definition: Configurator.h:164
g_uni_dist3
std::uniform_int_distribution g_uni_dist3(0, 999)
cfg_Fixed_random_sequence
CfgBool cfg_Fixed_random_sequence
CfgInt::value
int value() const
Definition: Configurator.h:116
g_generator
std::mt19937 g_generator(seed_seq)
g_msg
MapErrorMsg * g_msg
Definition: MapErrorMsg.cpp:41
seed_seq
std::seed_seq seed_seq
Definition: ALMaSS_Random.cpp:32
g_generator_fixed_fnc
void g_generator_fixed_fnc(const unsigned int s)
Definition: ALMaSS_Random.cpp:43
count
Definition: SubPopulation.h:48
cfg_FixedRandomSeed
CfgInt cfg_FixedRandomSeed