Beispiel #1
0
void GeneticAlgorithm::createOffspring(Population& newPopulation,
                                       bool doMutation) {
    Image& targetImage = *TargetImage::Instance();
    Population tmpResult;
    while (m_population.size() > 1) {

        m_inputLock.lock();

        if (m_population.size() <= 1) {
            m_inputLock.unlock();
            break;
        }
        std::pair<Organism*, Organism*> couple =
            m_pairGenerator.removeRandomPair(m_population);

        m_inputLock.unlock();

        Organism* child = new Organism(*couple.first, *couple.second, doMutation);
        double score = averagePixelDistance(targetImage, child->getPhenotype());
        child->setScore(score);

        tmpResult.push_back(child);
        tmpResult.push_back(couple.first);
        tmpResult.push_back(couple.second);
    }

    m_outputLock.lock();

    newPopulation.insert(newPopulation.end(), tmpResult.begin(),
                         tmpResult.end());

    m_outputLock.unlock();
}
Beispiel #2
0
void Crossover::do_crossover(Population& population) {
  shuffle(population.begin(), population.end(), rng);
  for (int index = 0; index + 1 < int(population.size()); index += 2)
    if (decide_to_do_crossover()) {
      auto crossed = do_crossover(population[index], population[index + 1]);
      show_crossing(crossed);
    }
}
        void Merge(const Population& population) {
            samples.resize(children_start + population.size());
            copy(population.begin(), population.end(), samples.begin()+children_start);
            sort(samples.begin(), samples.end());
            samples.resize(capacity());

            children_start = capacity();
        }
void PerPointStopCriterion<TFunction>::update(const Population& population) {
  for (Population::Iterator it = population.begin();
       it != population.end();
       ++it) {
    typename OnePointStopCriterion<TFunction>::Ptr one_point_stop_criterion =
      stop_criterion_info_->getInfoById(it.point_id());
    one_point_stop_criterion->update(it.point());
  }
}
Beispiel #5
0
void
APG::ConstraintSolver::run()
{
    if ( !m_readyToRun ) {
        error() << "DANGER WILL ROBINSON!  A ConstraintSolver (serial no:" << m_serialNumber << ") tried to run before its QueryMaker finished!";
        m_abortRequested = true;
        return;
    }

    if ( m_domain.empty() ) {
        debug() << "The QueryMaker returned no tracks";
        return;
    } else {
        debug() << "Domain has" << m_domain.size() << "tracks";
    }

    debug() << "Running ConstraintSolver" << m_serialNumber;

    emit totalSteps( m_maxGenerations );

    // GENETIC ALGORITHM LOOP
    Population population;
    quint32 generation = 0;
    Meta::TrackList* best = NULL;
    while ( !m_abortRequested && ( generation < m_maxGenerations ) ) {
        quint32 s = m_constraintTreeRoot->suggestPlaylistSize();
        m_suggestedPlaylistSize = (s > 0) ? s : m_suggestedPlaylistSize;
        fill_population( population );
        best = find_best( population );
        if ( population.value( best ) < m_satisfactionThreshold ) {
            select_population( population, best );
            mutate_population( population );
            generation++;
            emit incrementProgress();
        } else {
            break;
        }
    }
    debug() << "solution at" << (void*)(best);
    
    m_solvedPlaylist = best->mid( 0 );
    m_finalSatisfaction = m_constraintTreeRoot->satisfaction( m_solvedPlaylist );

    /* clean up */
    Population::iterator it = population.begin();
    while ( it != population.end() ) {
        delete it.key();
        it = population.erase( it );
    }

    emit endProgressOperation( this );
}
Population run_island(Configuration conf, Individual initial_individual){
    // Random Number Generation
    std::default_random_engine eng(std::random_device{}());
    std::uniform_real_distribution<> dist(-5, 5);
    
    // population generation
    Population population;
    population.push_back(initial_individual);    // push the initial as it is.
    for (int i=1; i<conf.pop_size; i++) {
        Individual indi = mutate(conf, initial_individual);
        population.push_back(indi);
    }
    
    int generations = conf.num_generations;
    for (int g=0; g<generations; g++) {
        // first fitness calculation
        for (int i=0; i<conf.pop_size; i++) {
            population[i].score = fitness(population[i]);
        }
        
        // do sorting according to score
        std::sort(population.begin(), population.end(), compare);
        
        if (g != (conf.num_generations - 1)) {
            // crossover
            for (int i=0; i<(conf.pop_size / 2); i++) {
                crossover(conf, population[2*i], population[2*i+1]);
            }
            
            // mutate
            for (int i=0; i<conf.pop_size; i++) {
                population[i] = mutate(conf, population[i]);
            }
        }
    }
    
    return population;
}
Beispiel #7
0
/*
 * Use the genetic algorithm to construct a new population from the old
 */
Population GeneticPool::epoch(Population& old_pop, const BattleFieldLayout& bfl) {
  if (!initialized_ || old_pop.size() == 1) {
    Population new_pop = old_pop;
    new_pop.clear();
    old_pop.stats_.reset();

    for (Ship& t : old_pop) {
      t.calculateFitness(bfl, old_pop.facilities_.front(), old_pop.winner_);
      t.isElite = false;
    }

    //sort the population (for scaling and elitism)
    sort(old_pop.begin(), old_pop.end());

    //calculate best, worst, average and total fitness
    calculateStatistics(old_pop);

    for (Ship& t : old_pop) {
      new_pop.push_back(t.makeChild());
    }
    new_pop.stats_ = old_pop.stats_;
    return new_pop;
  }

  Population new_pop = old_pop;
  new_pop.clear();
  old_pop.stats_.reset();

  for (Ship& t : old_pop) {
    t.calculateFitness(bfl, old_pop.facilities_.front(), old_pop.winner_);
    t.isElite = false;
  }

  //sort the population (for scaling and elitism)
  sort(old_pop.begin(), old_pop.end());

  //calculate best, worst, average and total fitness
  calculateStatistics(old_pop);

  /*
   * Only winning teams get to have an elite by copying
   * some of the fittest genomes without any mutation/crossover.
   * Make sure we add an EVEN number or the roulette wheel sampling will crash
   * NOTE: we don't dont copy elites if we use perf descriptors since that is already a form of elitism
   */
  if (old_pop.winner_ && !layout_.usePerfDesc_ && layout_.numElite_ < old_pop.size()) {
    if (!(layout_.numEliteCopies_ * (layout_.numElite_ % 2))) {
      copyNBest(layout_.numElite_, layout_.numEliteCopies_, old_pop, new_pop);
    }
  }

  CHECK(old_pop.layout_.sl_.numPerfDesc_ == 4);
  PerfDescBsp<4, Ship> pdb;
  if (layout_.usePerfDesc_) {
    for (Ship& t : old_pop) {
      CHECK(t.perfDesc_.size() == 4);
      pdb.insert(&t);
    }
  }
  //now we enter the GA loop
  //repeat until a new population is generated
  while (new_pop.size() < old_pop.size()) {
    //grab two chromosones
    Ship& mum = pickSpecimen(old_pop);
    Ship* dad;
    if (layout_.usePerfDesc_) {
      CHECK(old_pop.size() > 2);
      auto pair = pdb.findClosestMate(&mum);
      Ship* closest = *pair.first;
      Coord dist = pair.second;
      if (dist == 0.0)
        dist = 0.01;

      vector<Ship*> result;

      Coord range = dist * 1.5;

      do {
        result = pdb.findInRange(&mum, range);
        range *= 1.5;
      } while (result.size() < 2);

      /*for(Ship* s : result) {
       std::cerr << s->perfDesc_[0] << '\t' << s->perfDesc_[2] << '\t' << s->perfDesc_[3] << '\t' << s->perfDesc_[4] << std::endl;
       }*/

      if (result.empty()) {
        dad = closest;
      } else {
        //std::cerr << "dist/range:" << dist << "\t" << range << std::endl;
        std::sort(result.begin(), result.end(), [&](const Ship* s1, const Ship* s2) {
          return s1->fitness_ < s2->fitness_;
        });

        dad = pickSpecimen(result);
      }
    } else
      dad = &pickSpecimen(old_pop);

    //create some offspring via crossover
    std::pair<Ship, Ship> babies = crossover(mum, *dad, layout_.crossoverIterations);

    //now we mutate
    mutate(*babies.first.brain_);
    mutate(*babies.second.brain_);

    //now copy into vecNewPop population
    new_pop.push_back(babies.first);
    if (new_pop.size() < old_pop.size())
      new_pop.push_back(babies.second);
  }
  CHECK(new_pop.size() == old_pop.size());
  old_pop.stats_.generationCnt_++;
  new_pop.stats_ = old_pop.stats_;
  return new_pop;
}