CGC_Codes

genetic algorithm

Jun 7th, 2017
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.16 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using Microsoft.Scripting.Runtime;
  6. using QuantSys.MachineLearning.GeneticAlgorithm.Genes;
  7. using QuantSys.Util;
  8.  
  9. namespace QuantSys.MachineLearning.GeneticAlgorithm
  10. {
  11.     public class GeneticAlgorithm
  12.     {
  13.         private const string OUTPUT_FILEPATH = QSConstants.DEFAULT_DATA_FILEPATH;
  14.  
  15.         private const int DefaultPopulationSize = 30;
  16.         private const int DefaultNumGenerations = 50;
  17.         private const int DefaultNumTrials = 10;
  18.         private const double DefaultMutationRate = 0.02;
  19.         private readonly List<Gene> ChromosomeFootprint;
  20.  
  21.         private readonly Func<Chromosome, double> _fitnessFunction;
  22.         private readonly Random _randomSeed;
  23.         private Population _currentPopulation;
  24.         private int _currentTrial;
  25.         public Chromosome maxC = new Chromosome();
  26.  
  27.         public GeneticAlgorithm(Func<Chromosome, double> fitness,
  28.             List<Gene> ChromosomeFootprint,
  29.             int popSize = DefaultPopulationSize,
  30.             int generations = DefaultNumGenerations,
  31.             int trials = DefaultNumTrials,
  32.             double mutRate = DefaultMutationRate
  33.             )
  34.         {
  35.  
  36.             _fitnessFunction = fitness;
  37.             _randomSeed = new Random();
  38.             this.ChromosomeFootprint = ChromosomeFootprint;
  39.  
  40.             PopulationSize = popSize;
  41.             Generations = generations;
  42.             Trials = trials;
  43.             MutationRate = mutRate;
  44.         }
  45.  
  46.         public int PopulationSize { get; set; }
  47.         public int Generations { get; set; }
  48.         public int Trials { get; set; }
  49.         public double MutationRate { get; set; }
  50.  
  51.         private void InitializePopulation()
  52.         {
  53.             var c = new List<Chromosome>();
  54.  
  55.             for (int i = 0; i < PopulationSize; i++)
  56.             {
  57.                 var gList = new List<Gene>();
  58.                 foreach (Gene g in ChromosomeFootprint)
  59.                 {
  60.                     Gene gene = g.Clone();
  61.                     gene.InitializeGene();
  62.                     gList.Add(gene);
  63.                 }
  64.  
  65.                 var cx = new Chromosome(gList);
  66.                 c.Add(cx);
  67.             }
  68.  
  69.             _currentPopulation = new Population(c);
  70.             _currentPopulation.CalculateAllFitness(_fitnessFunction);
  71.         }
  72.  
  73.         public void Run()
  74.         {
  75.             InitializePopulation();
  76.  
  77.             double maxFitness = 0;
  78.  
  79.             while (_currentTrial++ < Trials)
  80.             {
  81.  
  82.                 Console.WriteLine("Starting trial " + _currentTrial + "...");
  83.  
  84.                 string filename = QSConstants.DEFAULT_DATA_FILEPATH + "result" + _currentTrial + ".txt";
  85.  
  86.                 using (var file = new StreamWriter(@filename))
  87.                 {
  88.                     for (int generation = 0; generation < Generations; generation++)
  89.                     {
  90.                         Console.WriteLine(generation);
  91.                         var newPop = new Population();
  92.  
  93.                        
  94.                         Population elite = _currentPopulation.ElitismSelection(2);
  95.  
  96.                         newPop.JoinPopulation(elite);
  97.  
  98.                        
  99.                         while (newPop.PopulationSize < PopulationSize)
  100.                         {
  101.                            
  102.                             Population parents = _currentPopulation.SimpleRouletteSelection(2, _randomSeed);
  103.  
  104.                            
  105.                             Population children = Crossover.BinaryCrossover(parents[0], parents[1], _randomSeed);
  106.  
  107.                             newPop.JoinPopulation(children);
  108.                         }
  109.  
  110.                         newPop.MutatePopulation(MutationRate, _randomSeed);
  111.  
  112.                         double average = 0;
  113.  
  114.                        
  115.                         foreach (Chromosome chromosome in newPop.Chromosomes)
  116.                         {
  117.                             if (chromosome.Fitness.Equals(double.NaN))
  118.                                 chromosome.CalculateFitness(_fitnessFunction);
  119.                             if (chromosome.Fitness > maxFitness)
  120.                             {
  121.                                 maxFitness = chromosome.Fitness;
  122.                                 maxC = chromosome;
  123.  
  124.                                 file.WriteLine("Generation: {0}", generation);
  125.                                 file.WriteLine("Fitness: {0}", maxFitness);
  126.                                 for (int i = 0; i < maxC.Count(); i++)
  127.                                 {
  128.                                     file.WriteLine("Gene " + i + ":" + maxC[i]);
  129.                                 }
  130.  
  131.                                 file.WriteLine();
  132.                                 file.Flush();
  133.                             }
  134.  
  135.                             average += chromosome.Fitness;
  136.                             ;
  137.                         }
  138.  
  139.  
  140.  
  141.                         _currentPopulation = newPop;
  142.                     }
  143.                 }
  144.  
  145.                 maxC.CalculateFitness(_fitnessFunction);
  146.             }
  147.  
  148.             Console.WriteLine("Execution complete.");
  149.         }
  150.     }
  151. }
Advertisement
Add Comment
Please, Sign In to add comment