Advertisement
Guest User

KromoMain.cs

a guest
Sep 23rd, 2012
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 11.19 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. // from pastebin
  7. using System.IO;
  8.  
  9.  
  10. namespace Kromo
  11. {
  12.     public class KromoMain
  13.     {
  14.         Kromosom najboljiKromosomUGeneraciji;       // best chromosome in generation
  15.         Genotip genotip;
  16.  
  17.         public void Run(int nrOfChrmosomes)
  18.         {
  19.             genotip = new Genotip(nrOfChrmosomes);
  20.  
  21.             // CM - fitness calculated on GEN 0
  22.             genotip.RacunajFunkcijuFitnesa(genotip.kromosom);
  23.             double varijancaInicijalna = genotip.RacunajVarijancu();
  24.  
  25.             Console.WriteLine("Intial population variance: " + varijancaInicijalna); // CM
  26.  
  27. #if WINDOWS            
  28.             // CM - charting removed for Console app
  29.             int k = 0;
  30.             for (int i = 0; i < genotip.kromosom.Count; i++)
  31.             {
  32.                 k = i + 1;
  33.                 chart_initalPopulation.Series[0].Points.AddXY(k,genotip.kromosom[i].TempFitnes);
  34.             }
  35. #endif
  36.             // CM - find the best initial chromosome
  37.             double tempMax = 0;
  38.             foreach (var kromosom in genotip.kromosom)
  39.             {
  40.                 if (kromosom.ScaledFitness > tempMax)
  41.                 {
  42.                     tempMax = kromosom.ScaledFitness;
  43. #if WINDOWS
  44.                     najboljiKromosomUPrethodnojGeneraciji = kromosom; // best chromosome in previous generation
  45. #endif
  46.                 }
  47.             }
  48.            
  49.             int korak=0; // step
  50.             TextWriter tw_0 = new StreamWriter("varijance.txt");
  51.             tw_0.Write("Varijanca prve generacije: ");
  52.             tw_0.WriteLine(varijancaInicijalna);
  53.             string varijanca = "";
  54.  
  55.             // CM - I reordered this to be:
  56.             // 1. compute fitness of current population
  57.             // 2. Crossover
  58.             // 3. Mutate
  59.             do
  60.             {
  61.                 // CM --
  62.                 // calculates the raw and scaled fitness
  63.                 //
  64.                 genotip.RacunajFunkcijuFitnesa(genotip.kromosom);
  65.  
  66.                 // CM -- introducing niching...
  67.                 // With explicit fitness sharing, like chromosomes will be penalized
  68.                 // by scaling their fitness by 1/N, where N is the number of chromosomes in
  69.                 // the niche. The more niches in the population, the more diverse the population
  70.                 genotip.Niching(genotip.kromosom, 500.0f );
  71.  
  72.                 // CM -- "count function selections" ???
  73.                 //
  74.                 // computes the scaled fitness (TempSelection),
  75.                 // and ranges for selection (UpperBound, LowerBound)
  76.                 //
  77.                 // NOTE - this is the second component with the fitness calculation
  78.                 // at the end. both are required to fill the new Kromosomes completely
  79.                 genotip.RacunajFunkcijuSelekcije(genotip.kromosom);
  80.  
  81.                 // CM -
  82.                 // bug?? you're not resetting the tempMaxFitnes every generation. If the
  83.                 // current generation has worse fitness than the last, the "best chromosome
  84.                 // in generation" will be from a previous generation.
  85.                 Kromosom best = null;
  86.                 double min_raw_fitness = double.MaxValue;
  87.                 foreach (var kromosom in genotip.kromosom)
  88.                 {
  89.                     // CM - i'm using raw fitness here because it's unaffected
  90.                     // by niching. the best will be selected most often, resulting in
  91.                     // a large niche being created, which penalizes the entire
  92.                     // niche including the best. This ensures our BEST solution so far
  93.                     // is kept.
  94.                     if (kromosom.RawFitnes < min_raw_fitness)
  95.                     {
  96.                         min_raw_fitness = kromosom.RawFitnes;
  97.                         best = kromosom; // CM "best chromosome in a generation"
  98.                     }
  99.                 }
  100.                
  101.                 // CM - write the best of this generation to the console
  102.                 Console.WriteLine( "[" + korak + "] " + best.AsString() );
  103.  
  104.                 // CM - detailed dump of the population
  105.                 // DUMP MUST HAPPEN HERE after the TempFitness has been evaluated
  106.                 // NOTE: Generates a LOT OF FILES, but is VERY HELPFUL for debugging
  107.                 DumpGeneration( korak, genotip, best );
  108.  
  109.                 // CM - adding roulette selection
  110.                 int N = genotip.kromosom.Count; // total chromosome count
  111.                 var selection = new List<Kromosom>( );
  112.  
  113.                 // CM - roulette selection
  114.                 //selection.AddRange( genotip.RouletteSelection(genotip.kromosom, N/2) );
  115.  
  116.                 // CM - as is, this selects N chromosomes from the population
  117.                 // this can have repeats.
  118.                 // For each N
  119.                 //      Pick 2 at random
  120.                 //      72% chance to pick the stronger (higher fitness)
  121.                 //      28% chance to pick the weaker (lower fitness)
  122.                 selection.AddRange( genotip.ProbabilisticBinaryTournamentSelection(genotip.kromosom, 0.72, N) );
  123.  
  124.                 // randomize the list so that the mutation and crossover can just pick items off the front
  125.                 genotip.RazbacajListu( selection );
  126.  
  127.                 // CM --
  128.                 // Crossover returns N chromosomes.
  129.                 //
  130.                 // Originally:
  131.                 // There's a 66% chance of a crossover.
  132.                 // CROSSOVER is a 50% chance for EACH ALLELE to flip
  133.                 //
  134.                 // Now:
  135.                 // 88% chanace of a single-point crossover
  136.                 // 10% chance of an extreme crossover where every allele has a 50% chance at flipping
  137.                 // 2% chance that the parents don't cross over at all
  138.                 var crossoverKromos = genotip.Crossover_2(selection, -1);
  139.  
  140.                 // CM --
  141.                 // Appy Mutations.
  142.                 //
  143.                 // korak = "step"
  144.                 //
  145.                 // Originally:
  146.                 // within the first 10 steps - 30% chance of a single-allele change
  147.                 // after first 10 steps - 5% chance of a COMPLETE CHROMOSOME REWRITE
  148.                 //
  149.                 // Now:
  150.                 // 30% chance that a single alele will be replaced
  151.                 // 30% chance that two alleles will swap places
  152.                 // 15% chance that a single alele will be scaled, range (0.8, 1.2)
  153.                 // 15% chance that a single alele will by shifted by +/- 100
  154.                 // 10% chance the allele will not change at all
  155.                 var mutatedKromos = genotip.Mutation(crossoverKromos, -1);  // this for mutates the crossovers
  156.  
  157.                 if(selection.Count != 0) // allow one
  158.                     throw new InvalidOperationException("selection should be empty at this point");
  159.  
  160.                 if (mutatedKromos.Count != N)
  161.                     throw new InvalidOperationException("output of mutation should be the same as the initial population");
  162.  
  163.                 var nextGen = new List<Kromosom>();
  164.                 nextGen.AddRange( mutatedKromos );
  165.                 //nextGen.AddRange( crossoverKromos );
  166.  
  167.                 // CM -- hack.. make sure the BEST chromosome gets in
  168.                 // Elitism
  169.                 nextGen[0] = new Kromosom( best );
  170.  
  171.                 //List<Kromosom> tempListaKromosoma = new List<Kromosom>(genotip.kromosom);
  172.                 genotip.kromosom = nextGen;
  173.                 korak++; // step (generation)
  174.  
  175.                 // ONLY THE RAW FITNESS IS AVAILABLE HERE.. NEXT ITERATION OF THE LOOP
  176.                 // IS REQUIRED TO HAVE VALID TempSelection (scaled fitness) AND LOWERBOUND, UPPERBOUND
  177.             }
  178.             // while (Check convergence)
  179.             //while (genotip.ProvjeriKonvergenciju(genotip.kromosom,najboljiKromosomUGeneraciji)==false);
  180.             while(true);
  181.            
  182.             tw_0.Write("Varijanca zadnje generacije: "); // CM - "variance of the FINAL generation"
  183.             tw_0.WriteLine(varijanca);
  184.             tw_0.Close();
  185.            
  186. #if WINDOWS
  187.             int p = 0;
  188.             for (int i = 0; i < genotip.kromosom.Count; i++)
  189.             {
  190.                 p = i + 1;
  191.                 chart_lastPopulation.Series[0].Points.AddXY(p, genotip.kromosom[i].TempFitnes);
  192.             }
  193. #endif
  194.  
  195.             TextWriter tw = new StreamWriter("beta.txt");
  196.             for (int i = 0; i < najboljiKromosomUGeneraciji.Alele.Count; i++)
  197.                
  198.             {
  199.                 tw.Write(najboljiKromosomUGeneraciji.Alele[i] + " ");
  200.             }
  201.            
  202.             tw.Close();
  203.  
  204. #if WINDOWS
  205.             //najboljiKromosomUGeneraciji.TempFitnes!=najboljiKromosomUPrethodnojGeneraciji.TempFitnes
  206.             MessageBox.Show("Rjesenje nadjeno", "BINGO");
  207.            
  208.             MessageBox.Show("Pronadjeni su koeficijenti\n b0:"+najboljiKromosomUGeneraciji.Alele[0]+
  209.                             "\n b1:"+najboljiKromosomUGeneraciji.Alele[1]+
  210.                             "\n b2:"+najboljiKromosomUGeneraciji.Alele[2]+
  211.                             "\n b3:"+najboljiKromosomUGeneraciji.Alele[3]+
  212.                             "\n b4:"+najboljiKromosomUGeneraciji.Alele[4]+
  213.                             "\n b5:"+najboljiKromosomUGeneraciji.Alele[5]+
  214.                             "\n b6:"+najboljiKromosomUGeneraciji.Alele[6]+
  215.                             "\n b7:"+najboljiKromosomUGeneraciji.Alele[7]+
  216.                             "\n b8:"+najboljiKromosomUGeneraciji.Alele[8]+
  217.                             "\n b9:"+najboljiKromosomUGeneraciji.Alele[9]+
  218.                             "\n b10:"+najboljiKromosomUGeneraciji.Alele[10]);
  219. #endif
  220.         }
  221.  
  222.         // CM -- dump the entire generation to file for inspection
  223.         // istovariti korak
  224.         void DumpGeneration (int generation, Genotip genotype, Kromosom best)
  225.         {
  226.             int gen_k = generation/1000;
  227.             string dir = gen_k.ToString();
  228.  
  229.             if(!Directory.Exists(dir)) {
  230.                 Directory.CreateDirectory(dir);
  231.             }
  232.  
  233.             string path = Path.Combine( new[] { dir, string.Format("korak_{0:0000}", generation) });
  234.             using(StreamWriter sw = new StreamWriter(path,false))
  235.             {
  236.                 sw.WriteLine("Generation " + generation);
  237.                 sw.WriteLine("Raw Fit(x), Scaled Fit(1/x), Niche, NicheFit, Norm Scale Fit(norm(1/x)), Alleles ...");
  238.                 foreach(var k in genotype.kromosom) {
  239.                     sw.Write ( k.AsString() );
  240.                     sw.WriteLine();
  241.                 }
  242.  
  243.                 // evaluate the best chromosome against all the sample points
  244.                 sw.WriteLine();
  245.                 sw.WriteLine("Best, evaluated: ");
  246.                 sw.WriteLine("index;guess;actual;error");
  247.                 for(int i=0; i<genotype.sampleCount; i++) {
  248.                     double guess, actual;
  249.                     guess = genotype.eval( best, i, out actual );
  250.                     sw.WriteLine("{0};{1:0.0000};{2:0.0000};{3:0.0000}", i, guess, actual, guess-actual);
  251.                 }
  252.             }
  253.  
  254.         }
  255.  
  256.     }
  257. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement