GPLIB++
SimpleSelect.cpp
Go to the documentation of this file.
1 #include "SimpleSelect.h"
2 #include <cmath>
3 #include <iostream>
4 
5 using namespace std;
6 namespace gplib
7  {
8  SimpleSelect::SimpleSelect(GeneralRNG &LocalRandom,
10  Random(LocalRandom), ProbabilityFunction(myPF)
11  {
12 
13  }
14 
16  {
17  }
18  //The initialiazation routine basically does all the work
19  //so that when we draw a member in the propagation phase
20  //we only return the index of the a random selected member
21  void SimpleSelect::DoInit()
22  {
23  const tprobabilityv probabilities = ProbabilityFunction();
24  const size_t popsize = probabilities.size();
25  size_t currentindex = 0;
26 
27  std::vector<double> fraction(popsize, 0);
28  indices.assign(popsize, 0);
29  remain = popsize;
30  //go through the whole population
31  for (size_t i = 0; i < popsize; ++i)
32  {
33  //how many members can we expect in the new population based
34  //on the probabilities
35  const double expected = probabilities(i) * popsize;
36  //we always assign the expected number rounded down
37  //to the new population
38  int assign = int(floor(expected));
39  //and the save the difference between the rounded
40  //and not rounded to determine additional members
41  //later
42  fraction.at(i) = expected - assign;
43  //generate assign times index entries in the index
44  //vector that describes the new population
45  while (assign > 0)
46  {
47  --assign;
48  indices.at(currentindex) = i;
49  ++currentindex;
50  }
51 
52  }
53  //now we determine the remainder of the population
54  //based on the difference between expected and assigned
55  size_t fractionindex = 0;
56  //as long as the population is not full
57  while (currentindex < popsize)
58  {
59  //cycle through the population members
60  //and see if we want to include the current member
61  if (Random.GetNumber() <= fraction.at(fractionindex))
62  {
63  indices.at(currentindex) = fractionindex;
64  ++currentindex;
65  fraction.at(fractionindex) -= 1.0;
66  }
67  ++fractionindex;
68  //when we reached the end of the population, go back to the beginning
69  if (fractionindex >= popsize)
70  fractionindex -= popsize;
71  }
72  }
73 
74  size_t SimpleSelect::DoGetOne()
75  {
76  int pick = Random.GetNumber(remain);
77  int result = indices.at(pick);
78  // Have to reduce remain before because it starts with popsize but array is 0..popsize-1
79  --remain;
80  indices.at(pick) = indices.at(remain);
81  return (result);
82  }
83  }
boost::function< const tprobabilityv &()> tProbabilityFunction
Definition: gentypes.h:29
ublas::vector< double > tprobabilityv
Definition: gentypes.h:17
virtual float GetNumber()=0
The base class for all random number generators, defines the basic interface.
Definition: GeneralRNG.h:9