AckleyES.cpp
Go to the documentation of this file.
6 
7 using namespace shark;
8 
9 namespace example {
10 
12  typedef std::vector< IndividualType > Population;
13 
14  struct FitnessComparator {
15  bool operator()( const IndividualType & a, const IndividualType & b ) {
16  return( a.unpenalizedFitness() < b.unpenalizedFitness() );
17  }
18 
19  };
20 }
21 
22 
23 int main( int argc, char ** argv ) {
24 
25  const unsigned Mu = 15;
26  const unsigned Lambda = 100;
27  const unsigned Dimension = 30;
28  const double InitialSigma = 3.;
29 
30  // Instantiate the objective function
31  Ackley ackley( Dimension );
32 
33  // Initialize the mutation distribution
34  MultiVariateNormalDistribution mutationDistribution;
35  mutationDistribution.resize(Dimension);
36 
37  example::IndividualType prototypeIndividual;
38  prototypeIndividual.chromosome() = InitialSigma;
39 
40  example::Population parents( Mu, prototypeIndividual );
41  example::Population offspring( Lambda );
42 
43  // Initialize parents (not a god idea to start in a single point, shouldn't do this in practice)
44  for(auto& ind: parents ) {
45  ind.searchPoint() = ackley.proposeStartingPoint( );
46  }
47 
48  // Evolutionary operators
49  UniformCrossover uniform;
50 
51  // standard deviations for mutation of sigma
52  double tau0 = 1. / sqrt(2. * Dimension);
53  double tau1 = 1. / sqrt(2. * sqrt( static_cast<double>( Dimension ) ) );
54 
55 
56  while( ackley.evaluationCounter() < 10000 ) {
57 
58  for( std::size_t i = 0; i < offspring.size(); i++ ) {
59 
60  // Select two parent individuals at random
61  example::Population::const_iterator mom = parents.begin() + random::discrete(random::globalRng, std::size_t(0), parents.size() - 1 );
62  example::Population::const_iterator dad = parents.begin() + random::discrete(random::globalRng, std::size_t(0), parents.size() - 1 );
63 
64  // Recombine step size
65  offspring[i].chromosome() = random::uni(random::globalRng, mom->chromosome(), dad->chromosome() );
66  // Mutate step size
67  offspring[i].chromosome() *= random::logNormal(random::globalRng, 0, tau0 + tau1 );
68 
69  // Recombine search points
70  offspring[i].searchPoint() = uniform(random::globalRng, mom->searchPoint(), dad->searchPoint() );
71  // Mutate search point
72  offspring[i].searchPoint() = offspring[i].chromosome() * mutationDistribution(random::globalRng).first;
73 
74  // Assign fitness
75  offspring[i].unpenalizedFitness() = ackley.eval( offspring[i].searchPoint() );
76  }
77 
78  // Selection
79  example::FitnessComparator comp;
80  std::sort( offspring.begin(), offspring.end(), comp );
81  std::copy( offspring.begin(), offspring.begin() + Mu, parents.begin() );
82 
83 
84  std::cout << ackley.evaluationCounter() << " "
85  << parents.front().unpenalizedFitness() << " "
86  << parents.front().chromosome()
87  << std::endl;
88  }
89 }