EvolutionaryProcess.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. namespace GeneticAlgorithm
  4. {
  5. public class EvolutionaryProcess
  6. {
  7. protected List<Individual> population;
  8. protected int generationNb = 0;
  9. protected IIHM program = null;
  10. protected double bestFitness;
  11. protected string problem;
  12. public EvolutionaryProcess(IIHM _program, string _problem)
  13. {
  14. program = _program;
  15. problem = _problem;
  16. IndividualFactory.getInstance().Init(problem);
  17. population = new List<Individual>();
  18. for (int i = 0; i < Parameters.individualsNb; i++)
  19. {
  20. population.Add(IndividualFactory.getInstance().getIndividual(problem));
  21. }
  22. }
  23. public void Run()
  24. {
  25. bestFitness = Parameters.minFitness + 1;
  26. while (generationNb < Parameters.generationsMaxNb && bestFitness > Parameters.minFitness)
  27. {
  28. // Evaluation
  29. foreach (Individual ind in population)
  30. {
  31. ind.Evaluate();
  32. }
  33. // Meilleur individu (stats)
  34. Individual bestInd = population.OrderBy(x => x.Fitness).FirstOrDefault();
  35. program.PrintBestIndividual(bestInd, generationNb);
  36. bestFitness = bestInd.Fitness;
  37. // Sélection et reproduction
  38. List<Individual> newGeneration = new List<Individual>();
  39. // Elitisme :
  40. newGeneration.Add(bestInd);
  41. for (int i = 0; i < Parameters.individualsNb - 1; i++)
  42. {
  43. // Un ou deux parents ?
  44. if (Parameters.randomGenerator.NextDouble() < Parameters.crossoverRate)
  45. {
  46. // Choisir parents
  47. Individual father = Selection();
  48. Individual mother = Selection();
  49. // Reproduction
  50. newGeneration.Add(IndividualFactory.getInstance().getIndividual(problem, father, mother));
  51. }
  52. else
  53. {
  54. // Choisir parent
  55. Individual father = Selection();
  56. // Reproduction
  57. newGeneration.Add(IndividualFactory.getInstance().getIndividual(problem, father));
  58. }
  59. }
  60. // Survie
  61. Survival(newGeneration);
  62. generationNb++;
  63. }
  64. }
  65. private void Survival(List<Individual> newGeneration)
  66. {
  67. // Remplacement
  68. population = newGeneration;
  69. }
  70. private Individual Selection()
  71. {
  72. // Roulette biaisée sur le rang
  73. int totalRanks = Parameters.individualsNb * (Parameters.individualsNb + 1) / 2;
  74. int rand = Parameters.randomGenerator.Next(totalRanks);
  75. int indIndex = 0;
  76. int nbParts = Parameters.individualsNb;
  77. int totalParts = 0;
  78. while(totalParts < rand) {
  79. indIndex++;
  80. totalParts += nbParts;
  81. nbParts --;
  82. }
  83. return population.OrderBy(x => x.Fitness).ElementAt(indIndex);
  84. }
  85. }
  86. }