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