size_t MutationDispatcher::Mutate_CrossOver(uint8_t *Data, size_t Size, size_t MaxSize) { if (Size > MaxSize) return 0; if (!Corpus || Corpus->size() < 2 || Size == 0) return 0; size_t Idx = Rand(Corpus->size()); const Unit &O = (*Corpus)[Idx]; if (O.empty()) return 0; MutateInPlaceHere.resize(MaxSize); auto &U = MutateInPlaceHere; size_t NewSize = 0; switch(Rand(3)) { case 0: NewSize = CrossOver(Data, Size, O.data(), O.size(), U.data(), U.size()); break; case 1: NewSize = InsertPartOf(O.data(), O.size(), U.data(), U.size(), MaxSize); if (NewSize) break; // LLVM_FALLTHROUGH; case 2: NewSize = CopyPartOf(O.data(), O.size(), U.data(), U.size()); break; default: assert(0); } assert(NewSize > 0 && "CrossOver returned empty unit"); assert(NewSize <= MaxSize && "CrossOver returned overisized unit"); memcpy(Data, U.data(), NewSize); return NewSize; }
void MainWindow::EvolutionaryLoop() { m_GenerationNumber++; for(int i = 0; i < ui->sbChildren->value(); i++) { float r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX); //80 percent of the time we do a crossover. if (r < 0.8) { int father_index = rand() % population.size(); int mother_index = rand() % population.size(); CrossOver(population.at(father_index), population.at(mother_index)); ComputeFitness(population.back()); } // we clone the rest of the time (10%) else { int clone_index = rand() % population.size(); population.push_back(population.at(clone_index)); } Mutation(population.at(i)); } MakeFights(); fs = GetPhenotypeStatsInAGeneration(); int best_index = fs.bestFitnessIndex; if (population.at(best_index)->GetFitness() <= ui->dsbFitnessThreshold->value() && population.at(best_index)->IsValid() == true) { timer->stop(); statusLabel->setText(QString("Found best phenotype (number %2) at generation %0 with a fitness of %1") .arg(fs.noOfGeneration) .arg(population.at(best_index)->GetFitness()) .arg(best_index)); //statusProgressBar->setValue(statusProgressBar->maximum()); } //population.at(best_index)->Mutate(); ComputeFitness(population.at(best_index)); int row = AddRow(population.at(best_index)); bool green = population.at(best_index)->IsValid(); SetRowColor(row, green); PopulatePlot(ui->tableWidget, fs); ShowPhenotype(population.at(best_index)); ui->lGeneration->setText(QString("Generation %0").arg(m_GenerationNumber)); }
size_t MutationDispatcher::Mutate_CrossOver(uint8_t *Data, size_t Size, size_t MaxSize) { if (!Corpus || Corpus->size() < 2 || Size == 0) return 0; size_t Idx = Rand(Corpus->size()); const Unit &Other = (*Corpus)[Idx]; if (Other.empty()) return 0; MutateInPlaceHere.resize(MaxSize); auto &U = MutateInPlaceHere; size_t NewSize = CrossOver(Data, Size, Other.data(), Other.size(), U.data(), U.size()); assert(NewSize > 0 && "CrossOver returned empty unit"); assert(NewSize <= MaxSize && "CrossOver returned overisized unit"); memcpy(Data, U.data(), NewSize); return NewSize; }
int main(){ int poblacion[N][M]; double Fitness[10]; int Nueva_Poblacion [10][M]; double SumatoriaFObj; unsigned long int valor_Cromosomas_Elegidos[10]; int cromosomas_Elegidos[10]; //cromosomas elegidos inicialmente srand(time(0)); for(int i=0; i<N ; i++) { for(int j=0; j<M ; j++) poblacion[i][j] = rand()%2; } for(int k=0;k<10;k++) cromosomas_Elegidos[k]=-1; for(int j=0; j<10 ; j++) { int m=(rand()%M); while(Ya_esta(m,cromosomas_Elegidos)==false) m = (rand()%M); cromosomas_Elegidos[j]=m; } for(int k=0;k<10;k++){ for(int j=0;j<M;j++){ Nueva_Poblacion[k][j] = poblacion[cromosomas_Elegidos[k]][j] ;} } for(int i=0;i<20;i++){ printf("\nEJECUCION NUMERO %d \n\n", i); A_Valor_Decimal(valor_Cromosomas_Elegidos,Nueva_Poblacion); SumatoriaFObj = Sumatoria_Funcion_Objetivo(valor_Cromosomas_Elegidos); Funcion_Fitness(valor_Cromosomas_Elegidos,SumatoriaFObj,Fitness); Mostrar_Lista(valor_Cromosomas_Elegidos,Nueva_Poblacion,SumatoriaFObj,Fitness); CrossOver(Fitness,cromosomas_Elegidos,Nueva_Poblacion); system("PAUSE"); system("CLS"); } system("PAUSE"); return 0; }
void Fuzzer::Loop(size_t NumIterations) { for (size_t i = 1; i <= NumIterations; i++) { for (size_t J1 = 0; J1 < Corpus.size(); J1++) { RereadOutputCorpus(); if (TotalNumberOfRuns >= Options.MaxNumberOfRuns) return; // First, simply mutate the unit w/o doing crosses. CurrentUnit = Corpus[J1]; MutateAndTestOne(&CurrentUnit); // Now, cross with others. if (Options.DoCrossOver) { for (size_t J2 = 0; J2 < Corpus.size(); J2++) { CurrentUnit.clear(); CrossOver(Corpus[J1], Corpus[J2], &CurrentUnit, Options.MaxLen); MutateAndTestOne(&CurrentUnit); } } } } }
size_t Fuzzer::Loop(size_t NumIterations) { size_t NewUnits = 0; for (size_t i = 1; i <= NumIterations; i++) { if (Options.DoCrossOver) { for (size_t J1 = 0; J1 < Corpus.size(); J1++) { for (size_t J2 = 0; J2 < Corpus.size(); J2++) { CurrentUnit.clear(); CrossOver(Corpus[J1], Corpus[J2], &CurrentUnit, Options.MaxLen); NewUnits += MutateAndTestOne(&CurrentUnit); } } } else { // No CrossOver for (size_t J = 0; J < Corpus.size(); J++) { CurrentUnit = Corpus[J]; NewUnits += MutateAndTestOne(&CurrentUnit); } } } return NewUnits; }
TArray<FGenome> GeneticAlg::Epoch(TArray<FGenome> &OldPop) { PopArray = OldPop; Reset(); PopArray.Sort(); //sorts Fgenomes by fitness CalculateBestWorstAvTot(); TArray<FGenome> NewPop; if (!(NumCopiesElite * NumElites % 2)) { GrabNBest(NumElites, NumCopiesElite, NewPop); } while (NewPop.Num() < PopulationSize) { //grab two chromosones FGenome mum = GetChromoRoulette(); FGenome dad = GetChromoRoulette(); //create some offspring via crossover TArray<float> baby1, baby2; CrossOver(mum.WeightsArray, dad.WeightsArray, baby1, baby2); //now we mutate Mutate(baby1); Mutate(baby2); //now copy into vecNewPop population NewPop.Add(FGenome(baby1, 0)); NewPop.Add(FGenome(baby2, 0)); } //finished so assign new pop back into m_vecPop PopArray = NewPop; return PopArray; }
int main() { // Declare GA parameters - pop. size, variables, etc const int populationSize = 30; const int numberOfGenerations = 100; const int tournamentSize = 2; const double tournamentSelectionParameter = 0.75; const float crossOverProbability = 0.7; const float creepRateMutation = 0.1; const double mutationProbability = 0.05; // Vehicle related parameters for chromosome construction int numberOfUnits = 4; // Including Tractor std::vector<int> numberOfAxlesOnEachUnit{3,3,2,3}; // Can be made inputs later int numberOfEngines = 3; // D11, D13, D16 int numberOfElectricMotors = 3; int numberOfElectricBuffers = 3; std::vector<int> machineParameters{numberOfEngines, numberOfElectricMotors, numberOfElectricBuffers}; std::vector<std::vector<int>> vehicleConfigurationParameters{machineParameters, numberOfAxlesOnEachUnit}; // Initialise the population Population population = InitialisePopulation(populationSize, vehicleConfigurationParameters); // Check if population is correctly initialised std::cout<<"Population initialised"<<std::endl; PrintMembersOfPopulation(population); // Create files for storing population of each generation & fitnesses of each individual in each generation std::fstream populationEachGeneration; std::fstream fitnessEachGeneration; //Delete any existing instances of the files to be created remove("PopulationEachGeneration.txt"); remove("FitnessEachGeneration.txt"); std::vector<double> bestFitnessOverGenerations; std::vector<std::vector<double>> missionData; LoadMission(missionData); // Loop begins - generation evolution start for(int generationIndex=0;generationIndex<numberOfGenerations;generationIndex++) { std::cout<<"GENERATION NUMBER : "<<generationIndex<<std::endl; // Store current population in file PopulationEachGeneration.txt //StoreCurrentPopulationInFile(population, populationEachGeneration, rangeAllVariables); // Declare variables required for fitness evaluation Fitnesses fitness; // Keep inside scope of each generation double tempFitness; // Keep inside scope of each generation // Evaluate the fitness of each member in the population and assign to 'fitness' vector fitness = EvaluatePopulationFitness(population, missionData); StoreCurrentFitnessInPopulation(fitness, fitnessEachGeneration); // Declare variables required for best individual search long double maximumFitness; int bestIndividualIndex; Individual bestIndividual; // Find best individual in the current population bestIndividualIndex = GetBestIndividualIndex(fitness); //, population, rangeAllVariables); bestIndividual = population[bestIndividualIndex]; maximumFitness = fitness[bestIndividualIndex]; bestFitnessOverGenerations.push_back(maximumFitness); //PrintFitness(fitness); //std::cout<<"The best Individual is "<<bestIndividualIndex<<std::endl; std::cout<<"The optimal function value is "<<maximumFitness<<std::endl; // Based on fitness, perform selection & crossover without replacement Population tempPopulation; tempPopulation = population; for(int i=0;i<populationSize;i=i+2) { // i=i+2 since 2 individuals are crossed over // Select two random individuals using tournament selection std::vector<Individual> individualsToCrossover; // Both individuals to be crossed over placed in a vector for(int j=0;j<tournamentSize;j++) { int temporaryIndex=TournamentSelection(fitness, tournamentSelectionParameter, tournamentSize); //std::cout<<"Chosen Individual :"<<temporaryIndex<<std::endl; individualsToCrossover.push_back(population[temporaryIndex]); } // end of Tournament Selection // Perform crossover // ALGORITHM ONE - INDIVIDUAL UNIT GENE CONSIDERATION FOR CROSSOVER std::vector<Individual> crossedOverIndividuals = CrossOver(individualsToCrossover, crossOverProbability); tempPopulation[i]=crossedOverIndividuals[0]; tempPopulation[i+1]=crossedOverIndividuals[1]; // ALGORITHM TWO - CROSSOVER AT UNIT GENE BOUNDARIES FOR WHOLE INDIVIDUALS /*double randomDouble = GetRandomDouble(); if(randomDouble < crossOverProbability) { //std::cout<<"CrossOver Initiated"<<std::endl; std::vector<Individual> crossedOverIndividuals = CrossOver(individualsToCrossover); tempPopulation[i]=crossedOverIndividuals[0]; tempPopulation[i+1]=crossedOverIndividuals[1]; } else { // Place original pair of individuals in corresponding (consecutive) locations in tempPopulation //std::cout<<"No Crossover"<<std::endl; tempPopulation[i]=individualsToCrossover[0]; tempPopulation[i+1]=individualsToCrossover[1]; } // end of Crossover*/ } // End of Selection and Crossover //std::cout<<std::endl<<"After Crossover"<<std::endl; //PrintMembersOfPopulation(tempPopulation); // Mutate each individual MutatePopulation(tempPopulation, mutationProbability); // Population mutated //std::cout<<std::endl<<"After Mutation"<<std::endl; //PrintMembersOfPopulation(tempPopulation); // Elitism tempPopulation[0]=population[bestIndividualIndex]; for(int i=0;i<tempPopulation.size();i++) population[i]=tempPopulation[i]; } // end of generation loop // Declare variables required for final fitness evaluation Fitnesses finalFitness; // Keep inside scope of each generation double tempFitness; // Keep inside scope of each generation // Evaluate the fitness of each member in the population and assign to 'fitness' vector finalFitness = EvaluatePopulationFitness(population, missionData); //PrintFitness(finalFitness); // Declare variables required for best individual search long double finalMaximumFitness; int finalBestIndividualIndex; Individual finalBestIndividual; // Find best individual in the current population finalBestIndividualIndex = GetBestIndividualIndex(finalFitness); //, population, rangeAllVariables); finalBestIndividual = population[finalBestIndividualIndex]; finalMaximumFitness = finalFitness[finalBestIndividualIndex]; PrintMembersOfPopulation(population); // Check if the best individual is being correctly calculated std::cout<<"The best Individual is "<<finalBestIndividualIndex<<std::endl; PrintIndividual(population[finalBestIndividualIndex]); std::cout<<"The optimal function value is "<<finalMaximumFitness<<std::endl; //std::cout<<std::endl; std::ofstream fileOperation; remove("fitness_vs_generation.txt"); fileOperation.open("fitness_vs_generation.txt"); if (fileOperation.is_open()) { for(int i=0;i<bestFitnessOverGenerations.size();i++) { fileOperation << bestFitnessOverGenerations[i] << '\n'; } fileOperation.close(); } }// end of main()