int main_alt() { Individual ind; ind.genInitial(); display_init(); std::ifstream fd("current.csv"); { std::string ign; fd >> ign; } ISSDraw model; { char ign; fd >> model.alpha; fd >> ign >> beta; fd >> ign >> model.yaw; fd >> ign >> ind.state[0].SARJ[0].a; fd >> ign >> ind.state[0].SARJ[1].a; for(int j = 0; j < 8; ++j) { fd >> ign >> ind.state[0].BGA[j].a; } } model.state = &ind.state[0]; while(handle_input()) frame(model); }
void Selection::addIndividualToOutOfGridIndividualList(Individual * outOfGridIndividual) { qDebug("Selection::addIndividualToOutOfGridIndividualList"); if (outOfGridList.empty()) { outOfGridList.append(outOfGridIndividual); qDebug("lista vacio, se inserto el individuo que cayo fuera de la grid"); return; } // verificar que el individuo no exista; si no existe se agrega en caso contrario se ignora Individual * auxIndividual; for (int i=0; i<outOfGridList.count(); i++) { auxIndividual = outOfGridList.at(i); if (auxIndividual->getIndividualId() == outOfGridIndividual->getIndividualId()) { qDebug("el individuo que cayo fuera de la grid ya se inserto en la lista y se ignora"); return; } } outOfGridList.append(outOfGridIndividual); qDebug("se inserto el individuo que cayo fuera de la grid a la lista"); }
void Ant::modifiedAnt(Individual<CodeVInt> &parent) { if (m_iteIndivl.data().m_x[m_loc] != m_x[m_loc]) { double obj = m_iteIndivl.data().m_obj[0]; TravellingSalesman *ptr = dynamic_cast<TravellingSalesman*>(Global::msp_global->mp_problem.get()); int pos = -1; for (int i = m_loc + 1; i < getNumDim(); i++) { if (m_iteIndivl.data().m_x[i] == m_x[m_loc]) { pos = i; break; } } obj = obj - ptr->getCost()[m_iteIndivl.data().m_x[pos]][m_iteIndivl.data().m_x[pos - 1]] - ptr->getCost()[m_iteIndivl.data().m_x[pos]][m_iteIndivl.data().m_x[(pos + 1) % getNumDim()]]\ - ptr->getCost()[m_iteIndivl.data().m_x[m_loc]][m_iteIndivl.data().m_x[m_loc - 1]]; obj = obj + ptr->getCost()[m_iteIndivl.data().m_x[pos]][m_iteIndivl.data().m_x[m_loc - 1]] + ptr->getCost()[m_iteIndivl.data().m_x[pos]][m_iteIndivl.data().m_x[m_loc]]\ + ptr->getCost()[m_iteIndivl.data().m_x[pos - 1]][m_iteIndivl.data().m_x[(pos + 1) % getNumDim()]]; m_iteIndivl.data().m_obj[0] = obj; for (int i = pos - 1; i >= m_loc; i--) { m_iteIndivl.data().m_x[i + 1] = m_iteIndivl.data().m_x[i]; } m_iteIndivl.data().m_x[m_loc] = m_x[m_loc]; if ((ptr->getOptType() == MIN_OPT && obj < parent.data().m_obj[0]) || (ptr->getOptType() == MAX_OPT && obj > parent.data().m_obj[0])) { parent.data().m_obj[0] = obj; for (int i = 0; i < getNumDim(); i++) parent.data().m_x[i] = m_iteIndivl.data().m_x[i]; parent.setFlag(true); } } }
void ImmigrationOperator::replace_worst_with_random( int n, AlgorithmState & st, const Instance & instance) const { Population & P = st.population(); // generate n random std::vector<Individual *> immigrants; for(int i = P.size() - n; i < P.size(); i++){ Individual * next = new Individual(instance.num_words()); st.inc_processed(); next->randomize(); next->set_cost(instance.evaluate(next)); immigrants.push_back(next); } for(int i = 0; i < steps_; i++){ local_search_(st, immigrants); } for(int i = 0; i < n; i++){ delete P[i + P.size() - n]; P.swap(i + P.size() - n, immigrants[i]); } P.update_stats(); }
float chronoCrossover(ParametersMap* parametersMap, unsigned repetitions) { START Individual* other = individual->newCopy(false); individual->setFitness(1); other->setFitness(1.5); CrossoverAlgorithm crossoverAlgorithm = (CrossoverAlgorithm) parametersMap->getNumber( Enumerations::enumTypeToString(ET_CROSS_ALG)); CrossoverLevel crossoverLevel = (CrossoverLevel) parametersMap->getNumber( Enumerations::enumTypeToString(ET_CROSS_LEVEL)); float probability = parametersMap->getNumber(PROBABILITY); unsigned numTimes = parametersMap->getNumber(NUM_TIMES); START_CHRONO switch (crossoverAlgorithm) { case CA_UNIFORM: individual->uniformCrossover(crossoverLevel, other, probability); break; case CA_PROPORTIONAL: individual->proportionalCrossover(crossoverLevel, other); break; case CA_MULTIPOINT: individual->multipointCrossover(crossoverLevel, other, numTimes); break; }STOP_CHRONO delete (other); END }
TEST(BestOfReplacement, SelectsBest){ AlgorithmState state; Population & p = state.population(); const int n = 3; double costs[] = {1,3,5,2,4,6}; for(int i = 0; i < n; i++){ Individual * ind = new Individual(10); ind->set_cost(costs[i]); p.add(ind); } std::vector<Individual *> children; for(int i = n ; i < 2*n; i++){ Individual * ind = new Individual(10); ind->set_cost(costs[i]); children.push_back(ind); } BestOfReplacement repl; repl(state, children); p.update_stats(); for(int i = 0; i < n ; i++) ASSERT_EQ(i + 1, p[i]->cost()); }
// ---------------------------------------------------------------------------------------- // FHwrite // ---------------------------------------------------------------------------------------- void FileHandler::FHwrite (const age_idx& cur_age, const sex_t& cur_sex, ostream& FILE, Patch* current_patch, const int& patch_id, const int& nbPatchDigit, const int& position){ unsigned char** seq; Individual *ind; int ploidy, nb_locus; for (unsigned int j = 0, nbInd = current_patch->size(cur_sex, cur_age); j < nbInd; ++j) { FILE << setfill('0') << setw(nbPatchDigit) << (patch_id+1) << setfill(' ') << " "; ind = current_patch->get(cur_sex, cur_age, j); for(int t=0; t<_nb_trait; ++t){ // for multiple instanciations of a trait ploidy = _trait[t]->get_ploidy(); nb_locus = _trait[t]->get_nb_locus(); seq = (unsigned char**)ind->getTrait(_TTidx[t])->get_sequence(); for(int k = 0; k < nb_locus; ++k) { for (int l = 0; l < ploidy; ++l) { FILE.fill('0'); FILE.width(position); FILE<<(unsigned int)(seq[k][l]+1); } FILE<<" "; } } if(_fstat_choice==2){ write_individual_info_to_stream(FILE, ind, cur_age, cur_sex, ' '); } FILE << "\n"; } }
Individual * Population::iterate (int iterations) { Individual * fittest = getFittest (); for (int i = 0; i < iterations; i++) { if (fittest->getFitness () == 0) { return fittest; } else { pop_stats.average_fitness.push_back (calcAvFitness (individuals, size)); pop_stats.highest_fitness.push_back (fittest->getFitness ()); Individual * winners = tournament (); mutation (winners); Individual * children = crossOver (winners); merge (winners, children); delete [] winners; delete [] children; calcFittest (); fittest = getFittest (); } } return fittest; }
void Worker::operator()() { for (int i = _begin; i < _end; i++) { /* Current thread will simulate child strings from begin * to end */ /* the simulate method runs the simulator, zfgenerator 3 times * lower voltage bound will be -60mV in all cases * (1) the upper voltage bound = -34 * (2) the upper voltage bound = -30 * (3) the upper voltage bound = -26 * * Store the fmax shift in a variable associated with the * Individual object */ Individual *ind = _pop->ind[i]; ind->simulate(_id); _lock->lock(); //acquire lock cout << "Thread " << _id << " is simulating child at position " << i << "\n"; _lock->unlock(); //release lock } }
void Simulation::initializePopulation() { Individual * individuo; QFile file("/tmp/algorithmResult.txt"); if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) { QMessageBox msg; msg.setText("Simulation::initializePopulation(): No se pudo abrir el archivo /tmp/algorithmResult.txt\n para escribir resultados de la ejecucion del algoritmo."); return; } QTextStream out(&file); out << endl << "Inicializacion de la poblacion." <<"\n"; // inicializacion de la poblacion for (int i = 0; i < populationSize; i++) { individuo = new Individual(deployedAPs); individuo->printIndividual(); qDebug("individualId: %d", individuo->getIndividualId()); populationList.append(individuo); out << individuo->getIndividualAsQString() << endl; } qDebug("tamano de la poblacion: %d",populationList.count()); //return populationList; }
void Simulation::addNonDominatedIndividualsToExternalFile(QList<Individual *> ndIndividualList) { externalFile->addNonDominatedIndividuals(ndIndividualList, nGrid); // agregar resultados a archivo QFile file("/tmp/algorithmResult.txt"); if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) { QMessageBox msg; msg.setText("Simulation::addNonDominatedIndividualsToExternalFile(): No se pudo abrir el archivo /tmp/algorithmResult.txt\n para escribir resultados de la ejecucion del algoritmo."); return; } QTextStream out(&file); out << endl << "Individuos del archivo externo." <<"\n"; out << endl; Individual * auxIndividual; for (int i=0; i<externalFile->getExternalFileList().count(); i++) { auxIndividual = externalFile->getExternalFileList().at(i); out << auxIndividual->getIndividualAsQString() << endl; } }
void Beagle::MPI::EvaluationOp::individualEvaluation(Individual& ioIndividal, Context& ioContext) { Fitness::Handle lFitness = evaluate(ioIndividal, ioContext); //Assign the fitness ioIndividal.setFitness(lFitness); ioIndividal.getFitness()->setValid(); return; }
void initialise(Individual& indiv, const Data& data) { // Adding 15 starting nodes to increase entropy auto nb_starting_nodes = (rand() % 15) + 1; for (int i = 0; i < nb_starting_nodes; i++) { auto regulation_id = (rand() % data.regulations().size()); struct vertex new_pos = indiv.findClosestNode(rand() % MAX_NB_LAYER - 1, rand() % MAX_NB_NODE_PER_LAYER); struct vertex new_pos2 = indiv.findClosestNode(rand() % MAX_NB_LAYER - 1, rand() % MAX_NB_NODE_PER_LAYER); Node new_node(new_pos.x, new_pos.y, new_pos2.x, new_pos2.y, regulation_id); int min_layer = std::max(new_pos.x, new_pos2.x); indiv.addNode(new_node, rand() % (MAX_NB_LAYER - min_layer) + min_layer + 1); } }
std::vector<int> all_pairwise_MRCA(std::vector<Individual*> population) { std::vector<int> gs; int pop_size = population.size(); if (pop_size <= 1) { throw std::invalid_argument("expected pop_size of at least 2"); } Rcout << "Considers " << pop_size*(pop_size-1)/2 << " pairs of individuals" << std::endl; for (int idx1 = 0; idx1 < (pop_size - 1); ++idx1) { Individual* i1 = population[idx1]; for (int idx2 = (idx1 + 1); idx2 < pop_size; ++idx2) { Individual* i2 = population[idx2]; // i1 and i2 can originate from different founders, warn about more generations required try { Individual* mrca = find_MRCA(i1, i2); int g = i1->get_generation() - mrca->get_generation(); gs.push_back(g); } catch( const std::invalid_argument& e ) { std::ostringstream warningstream; warning(e.what()); } } } Rcout << "Got " << gs.size() << " actual pairs of individuals with common founder" << std::endl; return gs; }
QList<Individual*> StructureNiechingSelection::createSeed(QList<Individual*> currentGeneration, int numberOfIndividuals, int numberOfPreservedParents, int numberOfParentsPerIndividual) { //TODO currentGeneration.size(); numberOfIndividuals = numberOfIndividuals; numberOfPreservedParents = numberOfPreservedParents; numberOfParentsPerIndividual = numberOfParentsPerIndividual; QList<Individual*> newGeneration; int numberOfSeparateNieches = mNumberOfSeparateNieches->get(); QList<QList<Individual*>*> nieches; for(int i = 0; i < numberOfSeparateNieches; ++i) { nieches.append(new QList<Individual*>()); } while(mNiecheBestFitness.size() < nieches.size()) { mNiecheBestFitness.append(0.0); } QList<Individual*> modifiedIndividuals; QList<Individual*> freeIndividuals; QList<Individual*> removedIndividuals; for(QListIterator<Individual*> i(currentGeneration); i.hasNext();) { Individual *ind = i.next(); if(ind->hasProperty("Nieche")) { QStringList niecheList = ind->getProperty("Nieche").split(","); for(QListIterator<QString> j(niecheList); j.hasNext();) { // int niecheid = j.next().toInt(); // QList<Individual*> *nieche = nieches.value(niecheName); // if(nieche == 0) { // removedIndividuals.append(ind); // } // else { // if(!nieche->contains(ind)) { // nieche->append(ind); // } // } } } else { freeIndividuals.append(ind); } } //distribute the free individuals to the nieches. return newGeneration; }
Individual *LawnmowerScenario::randomIndividual() const { Individual *individual = new Lawnmower(new Environment(gridSize(), gridSize()), maxMoves()); Node *rootNode = treeFactory->build(); individual->setRootNode(rootNode); return individual; }
Individual *LawnmowerScenario::createIndividual(const QString tree) const { Individual *individual = new Lawnmower(new Environment(gridSize(), gridSize()), maxMoves()); Node *rootNode = treeFactory->buildFromString(tree); individual->setRootNode(rootNode); return individual; }
// [[Rcpp::export]] Rcpp::List dexp(const int& iter, const Eigen::Map<Eigen::VectorXd>& y, const Eigen::MappedSparseMatrix<double>& D, const double& alpha, const double& rho, const int& m, const bool& debug) { Individual b = Individual(y, D, alpha, rho); Individual *btf = &b; bool broken = false; // initialize matrix of posterior draws Eigen::MatrixXd beta_draws = Eigen::MatrixXd::Zero(iter, btf->n); Eigen::MatrixXd omega_draws = Eigen::MatrixXd::Zero(iter, btf->nk); Eigen::VectorXd s2_draws = Eigen::VectorXd::Zero(iter); Eigen::VectorXd lambda_draws = Eigen::VectorXd::Zero(iter); // runs sampler for (int i=0; i<iter; ++i) { if (i % m == 0) { btf->upBeta(); beta_draws.row(i) = btf->beta.transpose(); } btf->upS2(); s2_draws(i) = btf->s2; btf->upLambda2(); lambda_draws(i) = btf->l; btf->upOmega2(); omega_draws.row(i) = btf->o2.transpose(); if ( debug ) { for (int j=0; j<btf->n; ++j) { if (std::isnan(beta_draws(i,j))) { Rcpp::Rcout << "Warning: watch out dexp!, nan @ beta(" << i << "," << j << ")" << std::endl; broken = true; } } for (int j=0; j<btf->nk; ++j) { if (std::isnan(omega_draws(i,j))) { Rcpp::Rcout << "Warning: watch out dexp!, nan @ omega(" << i << "," << j << ")" << std::endl; broken = true; } } if (std::isnan(s2_draws(i)) || std::isnan(lambda_draws(i))) { Rcpp::Rcout << "Warning: watch out dexp!, nan @ s2|lambda(" << i << ")" << std::endl; broken = true; } } if (broken) break; } return Rcpp::List::create(Rcpp::Named("beta") = Rcpp::wrap(beta_draws), Rcpp::Named("s2") = s2_draws, Rcpp::Named("lambda") = lambda_draws, Rcpp::Named("omega") = omega_draws); }
bool ExternalFile::isIndividualInExternalFile(Individual * individual) { qDebug("->ExternalFile::isIndividualInExternalFile"); Individual * alreadyInsertedIndividual; for (int i = 0; i < externalFileNonDominatedList.count(); i++) { qDebug(" dentro del for"); alreadyInsertedIndividual = externalFileNonDominatedList.at(i); if (individual->getIndividualId() == alreadyInsertedIndividual->getIndividualId()) { qDebug("---> el individuo EXISTE en el arcvhivo"); return true; } } qDebug(" antes de salir"); return false; /* qDebug("->ExternalFile::isIndividualInExternalFile"); Individual * alreadyInsertedIndividual; for (int i = 0; i < externalFileNonDominatedList.count(); i++) { alreadyInsertedIndividual = externalFileNonDominatedList.at(i); // verificar si valores de F1 y F2 son iguales if ( (ind->getPerformanceDiscovery() == alreadyInsertedIndividual->getPerformanceDiscovery()) && (ind->getPerformanceLatency() == alreadyInsertedIndividual->getPerformanceLatency()) ) { qDebug(" F1 y F2 son iguales"); bool parameterFlagDifferent = false; for (int j=0; j<44; j++) { if (ind->getParameter(j) != alreadyInsertedIndividual->getParameter(j)) { qDebug(" parametro %d del individuo es igual", j); parameterFlagDifferent = true; } else { return false; } } } else{ return false; } } */ }
Individual Individual::Reproduce(Individual &mate) { bool *mategeno = mate.GetGenotype(); if (mate.GetReproduced()) { for ( int i=0; i<m_genolength; i++ ) m_mask[i] = mate.GetMask()[i]; mate.SetReproduced(false); } else { bool meh[m_genolength]; bool mah[m_genolength]; int half=0; /* mark the different genotypes */ for ( int i = 0; i < m_genolength; i++ ) { meh[i] = m_genotype[i] && !mategeno[i]; mah[i] = !m_genotype[i] && mategeno[i]; if (meh[i]) half++; } for (int i = 0; i<m_genolength; i++) { m_mask[i]=false; } half/=2; for ( int i = 0; i < m_genolength && half!=0; i++ ) { if ( meh[i] && (rand() % 6 < 4) ) { for ( int j = 0; j < m_genolength && half!=0; j++ ) { if ( mah[j] && (rand() % 6 < 4) && !m_mask[j]) { m_mask[i]=m_mask[j]=true; half--; break; } } } } } bool new_genotype[m_genolength]; for( int i = 0; i < m_genolength; i++ ) { if( m_mask[i] ) { new_genotype[i]=mategeno[i]; } else { new_genotype[i]=m_genotype[i]; } } return Individual(m_battles, m_soldiers, m_rf, m_lf, new_genotype); }
int main() { srand(time(NULL)); Population population; for (int i = 0; i < POPULATION_COUNT; ++i) { Individual ind; Chromosome chromosome(targetString.size()); chromosome.randomize(); float fitness = evaluate(chromosome); ind.setChromosome(chromosome); ind.setFitness(fitness); population.addIndividual(ind); } population.sortPopulation(); std::string solution = ""; Individual bestInd; int generationCount = 0; int nth = 64; for (int i = 0; i < GENERATION_COUNT; ++i) { generationCount++; evolve(population); population.sortPopulation(); if (bestInd < population[0]) { bestInd = population[0]; } if (i % nth == 0) { std::cout << "Generation: " << generationCount << std::endl; std::cout << "Best individual: " << bestInd << std::endl; } if (bestInd.getFitness() >= 1){ break; } } std::cout << std::endl; std::cout << "Solved on generation " << generationCount << '!' << std::endl; std::cout << bestInd << std::endl << std::endl; std::cout << "Press enter to exit"; std::cin.get(); return 0; }
void testPopulation(ParametersMap* parametersMap) { BufferType bufferType = (BufferType) parametersMap->getNumber(Enumerations::enumTypeToString(ET_BUFFER)); ImplementationType implementationType = (ImplementationType) parametersMap->getNumber( Enumerations::enumTypeToString(ET_IMPLEMENTATION)); FunctionType functionType = (FunctionType) parametersMap->getNumber( Enumerations::enumTypeToString(ET_FUNCTION)); unsigned size = (unsigned) parametersMap->getNumber(Dummy::SIZE); Interface* input = new Interface(size, bufferType); Task* task = new BinaryTask(BO_OR, bufferType, size, 5); Individual* example = new Individual(implementationType); example->addInputLayer(input); example->addInputLayer(input); example->addInputLayer(input); example->addLayer(size, bufferType, functionType); example->addLayer(size, bufferType, functionType); example->addLayer(size, bufferType, functionType); example->addInputConnection(0, 0); example->addInputConnection(1, 0); example->addInputConnection(2, 0); example->addLayersConnection(0, 1); example->addLayersConnection(0, 2); example->addLayersConnection(1, 2); example->addLayersConnection(2, 0); Population* population = new Population(task, example, 5, 20); delete (population); delete (example); delete (task); delete (input); }
Individual* Individual::copy() { Individual *c = new Individual; c->state_ = state_; c->cid = cid; if(fitness) c->fitness = (FitnessP) this->fitness->copy(); for(uint i = 0; i < this->size(); i++) c->push_back((GenotypeP) (this->at(i)->copy())); return c; }
//Population Generator //Controls the creation of the population void Dummy_EA::build_population(int sim_number_state_variable_inputs, int sim_hidden_layer_size, int sim_number_controls) { Population.clear(); for (int h = 0; h < pop_size; h++) { Individual PM; //create the weights PM.create_weights(sim_number_state_variable_inputs, sim_hidden_layer_size, sim_number_controls); Population.push_back(PM); } }
void Individual::update(Individual& source) { if (!this->isLocked()) return; if (Util::isBetterSolution(source.getTotalCost(), this->getTotalCost())) { this->setGene(source.getGene()); this->setRoutes(source.getRoutesConst()); this->updateParameters(true); } }
double Firm::getproductivity() { double productivity = 0; Individual* temp; std::vector<Individual*>::iterator it = employees.begin(); for(it=employees.begin(); it<employees.end(); it++) { temp = *it; productivity += temp->getproductivity(companyProduct); } return productivity / employees.size(); }
void Individual::Evaluate(Individual &ind) { /* Evaluate fitness */ /* War simulation */ int* opposing_pheno=ind.GetPhenotype(); int battles_won = 0; int battles_lost = 0; int my_surviving_troops=0; float my_strength=1; int my_soldiers; float my_force; int opposing_surviving_troops=0; float opposing_strength=1; int opposing_soldiers; float opposing_force; for( int i = 0; i < m_phenolength; i++ ) { my_soldiers = m_phenotype[i] + my_surviving_troops; my_force = my_strength * (float)my_soldiers; opposing_soldiers = opposing_pheno[i] + opposing_surviving_troops; opposing_force = opposing_strength * (float)opposing_soldiers; if ( my_force > opposing_force ) { // Victory battles_won++; opposing_strength -= m_lf; my_surviving_troops = m_rf * (my_soldiers - opposing_soldiers); } else if ( my_force < opposing_force ) { // Loss battles_lost++; my_strength -= m_lf; opposing_surviving_troops = m_rf * (opposing_soldiers - my_soldiers); } } if ( battles_won == battles_lost ) { m_fitness+=1; ind.SetFitness(ind.GetFitness()+1); } else if ( battles_won > battles_lost ) { m_fitness+=2; } else { ind.SetFitness(ind.GetFitness()+2); } }
Individual Population::getFittest(void) { Individual fittest = individuals[0]; int i; for (i = 0; i < getSize(); i++) { Individual k = getIndividual(i); if (fittest.getFitness() <= k.getFitness()) { fittest = k; } } return fittest; }
void Deme::colonize() { Individual ind; int i; for(i = 0; i < capacity; i++) { this_generation.push_back(ind); } max_fit = ind.getFitness(s); }
system_id Environment::getIndividual() { system_id id(0); if( m_available_individuals.empty() ) { ++m_nIndAlloc; Individual * ind = new Individual( m_sim_manager, getSystemID(), m_reproduction_model ); id = ind->getSystemID(); } else { id = m_available_individuals.front(); m_available_individuals.pop_front(); assert( m_available_individuals.empty() || m_available_individuals.front() != id ); } m_pending.insert( id ); return id; }