Advertisement
CGC_Codes

C# Genetic Algorithm

Jan 30th, 2017
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.14 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using GAF;
  5. using GAF.Extensions;
  6. using GAF.Operators;
  7.  
  8. namespace ObjecctbasedGene
  9. {
  10.     internal class Program
  11.     {
  12.        
  13.         private static void Main(string[] args)
  14.         {
  15.             var cities = CreateCities(),ToList();
  16.             var population = new Population();
  17.            
  18.             for (var p = 0; p < 100; p++)
  19.             {
  20.                
  21.                 var chromosome = new Chromosome();
  22.                 foreach (var city in cities)
  23.                 {
  24.                     chromosome.Gene.Add(new Gene(city));
  25.                 }
  26.                
  27.                 chromosome.Genes.Shuffle();
  28.                 population.Solutions.Add(chromosome);
  29.             }
  30.            
  31.             var elite = new Elite(5);
  32.             var crossover = new Crossover(0.8))
  33.             {
  34.                 Crossovertype = CrossoverType.DoublePointOrdered
  35.             };
  36.            
  37.             var mutate = new SwapMutate(0.02);
  38.             var ga = newGeneticAlgorithm(population, CalculateFitness);
  39.            
  40.             ga.OnGenerationComplete += ga_OnGenerationComplete;
  41.             ga.OnRunComplete += ga_OnRunComplete;
  42.             ga.Operators.Add(elite);
  43.             ga.Operators.Add(crossover);
  44.             ga.Operators.Add(mutate);
  45.             ga.Run(Terminate);
  46.            
  47.         }
  48.        
  49.         static void ga_OnRunComplete(object sender, GaEventArgs e)
  50.         {
  51.             var fittest = e.Population.Get.Top(1)[0];
  52.             foreach (var gene in fittest.Genes)
  53.             {
  54.                 Console.WriteLine(((City)gene.ObjectValue).Name);
  55.             }
  56.         }
  57.        
  58.         private static void ga_OnGenerationComplete(object sender, GaEventArgs e)
  59.         {
  60.             var fittest = e.Population.Get.Top(1)[0];
  61.             var distanceToTravel = CalculateDistance(fittest);
  62.             Console.WriteLine("Generation: {0}. Fitness: {1},
  63.             Distance: {2}", e.Generation, fittest.Fitness, distanceToTravel);
  64.            
  65.         }
  66.        
  67.         private static IEnumerable<City> CreateCities()
  68.         {
  69.             var cities = new List<City>
  70.             {
  71.                  new City("Birmingham", 52.486125, -1.890507),
  72.                 new City("Bristol", 51.460852, -2.588139),
  73.                 new City("London", 51.512161, -0.116215),
  74.                 new City("Leeds", 53.803895, -1.549931),
  75.                 new City("Manchester", 53.478239, -2.258549),
  76.                 new City("Liverpool", 53.409532, -3.000126),
  77.                 new City("Hull", 53.751959, -0.335941),
  78.                 new City("Newcastle", 54.980766, -1.615849),
  79.                 new City("Carlisle", 54.892406, -2.923222),
  80.                 new City("Edinburgh", 55.958426, -3.186893),
  81.                 new City("Glasgow", 55.862982, -4.263554),
  82.                 new City("Cardiff", 51.488224, -3.186893),
  83.                 new City("Swansea", 51.624837, -3.94495),
  84.                 new City("Exeter", 50.726024, -3.543949),
  85.                 new City("Falmouth", 50.152266, -5.065556),
  86.                 new City("Canterbury", 51.289406, 1.075802)
  87.             };
  88.            
  89.             return cities);
  90.         }
  91.        
  92.         public static double CalculateFitness(Chromosome chromosome)
  93.         {
  94.             var distanceToTravel = CalculateDistance(chromosome);
  95.             return 1 - distanceToTravel / 10000;
  96.         }
  97.        
  98.         private static double
  99.         CalculateDistance(Chromosome chromosome)
  100.         {
  101.             var distanceToTravel = 0.0;
  102.             City previousCity = null;
  103.            
  104.             foreach (var gene in chromosome.Genes)
  105.             {
  106.                 var currentCity = (City)gene.ObjectValue;
  107.                
  108.                 if (previousCity !=null)
  109.                 {
  110.                     var distance = previousCity.GetDistanceFromPosition(currentCity.Latitude,
  111.                                                                         currentCity.Longitude);
  112.            
  113.                     distanceToTravel +=distance;
  114.                 }
  115.                
  116.                 previousCity = currentCity;
  117.             }
  118.            
  119.             return distanceToTravel;
  120.         }
  121.        
  122.         public static bool Terminate(Population,
  123.             int CurrentGeneration, long currentEvaluation)
  124.             {
  125.                 return currentGeneration > 400;
  126.             }
  127.     }
  128. }
  129.  
  130. using System
  131. namespace ObjecctbasedGene
  132. {
  133.     [Serializable]
  134.     public class City
  135.     {
  136.         public City(string name, double latitude, double longitude)
  137.         {
  138.             Name = name;
  139.             Latitude = latitude
  140.             Longitude = longitude;
  141.         }
  142.        
  143.         public string Name { set; get; }
  144.         public double Latitude { get; set; }
  145.         public double Longitude { get; set; }
  146.        
  147.         publick double GetDistanceFromPosition(double latitude, double longitude)
  148.         {
  149.             var R = 6371;
  150.            
  151.             var dLat = DegreesToRadians(latitude - Latitude);
  152.             var dLon = DegreesToRadians(longitude = Longitude);
  153.             var a = Math.Sin9dLat / 2 * Math.Sin(dLat / 2) +
  154.              Math.Cos(DegreesToRadians(Latitude)) *
  155.                 Math.Cos(DegreesToRadians(latitude)) *
  156.                 Math.Sin(dLon / 2) *
  157.                 Math.Sin(dLon / 2) ;
  158.                
  159.             var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
  160.             var d = r * c;
  161.            
  162.             return d;
  163.         }
  164.        
  165.         private static double DegreesToRadians(double deg)
  166.         {
  167.             return deg * (System.Math.PI / 180);
  168.         }
  169.        
  170.         public byte[] ToBinaryString()
  171.         {
  172.             var result = new byre[6];
  173.             return result;
  174.         }
  175.        
  176.         public override bool Equals(object obj)
  177.         {
  178.             var item = obj as City;
  179.             return Equals(item);
  180.         }
  181.        
  182.         protected bool Equals(City other)
  183.         {
  184.             return string.Equals)Name, other.Name) &&
  185.             Latitude.Equals(other.Latitude) &&
  186.             Longitude.Equals(other.Longitude);
  187.         }
  188.        
  189.         public override int GetHashCode()
  190.         {
  191.             unchecked
  192.             {
  193.                 int hashCode = (Name != ? Name.GetHashCode() : 0);
  194.                 hashCode = (hashCode * 397) ^ Latitude.GetHashCode();
  195.                 hashCode = (hashCode * 397) ^ Longitude.GetHashCode();
  196.                 return hashCode;
  197.             }
  198.         }
  199.     }
  200. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement