Beispiel #1
0
main( int argc, char** argv) {

  unsigned numGenes = 2,  // Number of genes in the chromosome
    numGenerations,       // Number of generations
    popSize;              // Population size
  float xOverPr,      // Crossover rate, from 0 to 1
    mutPr;            // Mutation rate, from 0 to 1
  bool verbose;       // true if you want many things printed
  
  // Obtain command line parameters or default values
  getParams( argc, argv, verbose, popSize, numGenerations,
	     xOverPr, mutPr );  

  // Create an initial population and the population-level operators
  Pop pop;
  unsigned i, j;
  Uniform<float> u( 0, 1);
  for ( j = 0; j < popSize; j ++ ) {
    Chrom* aChrom = new Chrom;	
    for ( i = 0; i < numGenes; i ++ ) {
      aChrom->push_back( u() );
    }
    pop.push_back( *aChrom );	  
    if ( verbose ) {
      copy( aChrom->begin(), aChrom->end(), ostream_iterator<int>( cout, " ") );
      cout << endl;
    }
    delete aChrom;    
  }
  // Create an instance of the evaluation function object 
  deJongF2float thisEvalFunc;
  // From that, create an object that evaluates all the population
  EOEvalAll<Chrom>  eval( thisEvalFunc) ;
  // Then, an object that select who's going to reproduce
  EOLottery<Chrom> select;
  // Another object that mates them
  EORandomBreed<Chrom> breed;
  // And another that weeds out the worst
  EOElimAll<Chrom> replace;
  // This one check if the algorithm has finishd or not
  EOGenTerm<Chrom> term( numGenerations );
 
  // Then the EO-level operators
  // This is a mutation-like operator
  EOFloatArrayRndMutate<Chrom> rndMut( 0.1, mutPr );
  // And this is the classical 2-point crossover
  EOXOver2<Chrom> xOver(xOverPr); 

  // Add operators to breeder
  breed.addOp( &rndMut );
  breed.addOp( &xOver );

  // Then, the algorithm itself is instantiated
  EOEasyGA<Chrom> ga( eval, select, breed, term, replace, verbose );  
  // Now, apply the algorithm to the population
  eval( pop );
  ga( pop );
  // Sort Population. First is the best
  sort( pop.begin(), pop.end(), SortEO<Chrom>() ); 
  // And print results!
  cout << "Best fitness ....... " << pop[0].fitness() << endl
       << "Value...............  " << pop[0] << endl;
  return 0;
}
Beispiel #2
0
 float operator()(Chrom& chrom) const
   {
     return accumulate(chrom.begin(), chrom.end(), 0);
   }