| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- using System.Collections.Generic;
- using System.Linq;
- namespace GeneticAlgorithm
- {
- public class EvolutionaryProcess
- {
- protected List<Individual> population;
- protected int generationNb = 0;
- protected IIHM program = null;
- protected double bestFitness;
- protected string problem;
- public EvolutionaryProcess(IIHM _program, string _problem)
- {
- program = _program;
- problem = _problem;
- IndividualFactory.getInstance().Init(problem);
- population = new List<Individual>();
- for (int i = 0; i < Parameters.individualsNb; i++)
- {
- population.Add(IndividualFactory.getInstance().getIndividual(problem));
- }
- }
- public void Run()
- {
- bestFitness = Parameters.minFitness + 1;
- while (generationNb < Parameters.generationsMaxNb && bestFitness > Parameters.minFitness)
- {
- // Evaluation
- foreach (Individual ind in population)
- {
- ind.Evaluate();
- }
- // Meilleur individu (stats)
- Individual bestInd = population.OrderBy(x => x.Fitness).FirstOrDefault();
- program.PrintBestIndividual(bestInd, generationNb);
- bestFitness = bestInd.Fitness;
- // Sélection et reproduction
- List<Individual> newGeneration = new List<Individual>();
- // Elitisme :
- newGeneration.Add(bestInd);
- for (int i = 0; i < Parameters.individualsNb - 1; i++)
- {
- // Un ou deux parents ?
- if (Parameters.randomGenerator.NextDouble() < Parameters.crossoverRate)
- {
- // Choisir parents
- Individual father = Selection();
- Individual mother = Selection();
- // Reproduction
- newGeneration.Add(IndividualFactory.getInstance().getIndividual(problem, father, mother));
- }
- else
- {
- // Choisir parent
- Individual father = Selection();
- // Reproduction
- newGeneration.Add(IndividualFactory.getInstance().getIndividual(problem, father));
- }
- }
- // Survie
- Survival(newGeneration);
- generationNb++;
- }
- }
- private void Survival(List<Individual> newGeneration)
- {
- // Remplacement
- population = newGeneration;
- }
- private Individual Selection()
- {
- // Roulette biaisée sur le rang
- int totalRanks = Parameters.individualsNb * (Parameters.individualsNb + 1) / 2;
- int rand = Parameters.randomGenerator.Next(totalRanks);
- int indIndex = 0;
- int nbParts = Parameters.individualsNb;
- int totalParts = 0;
- while(totalParts < rand) {
- indIndex++;
- totalParts += nbParts;
- nbParts --;
- }
- return population.OrderBy(x => x.Fitness).ElementAt(indIndex);
- }
- }
- }
|