Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- // from pastebin
- using System.IO;
- namespace Kromo
- {
- public class KromoMain
- {
- Kromosom najboljiKromosomUGeneraciji; // best chromosome in generation
- Genotip genotip;
- public void Run(int nrOfChrmosomes)
- {
- genotip = new Genotip(nrOfChrmosomes);
- // CM - fitness calculated on GEN 0
- genotip.RacunajFunkcijuFitnesa(genotip.kromosom);
- double varijancaInicijalna = genotip.RacunajVarijancu();
- Console.WriteLine("Intial population variance: " + varijancaInicijalna); // CM
- #if WINDOWS
- // CM - charting removed for Console app
- int k = 0;
- for (int i = 0; i < genotip.kromosom.Count; i++)
- {
- k = i + 1;
- chart_initalPopulation.Series[0].Points.AddXY(k,genotip.kromosom[i].TempFitnes);
- }
- #endif
- // CM - find the best initial chromosome
- double tempMax = 0;
- foreach (var kromosom in genotip.kromosom)
- {
- if (kromosom.ScaledFitness > tempMax)
- {
- tempMax = kromosom.ScaledFitness;
- #if WINDOWS
- najboljiKromosomUPrethodnojGeneraciji = kromosom; // best chromosome in previous generation
- #endif
- }
- }
- int korak=0; // step
- TextWriter tw_0 = new StreamWriter("varijance.txt");
- tw_0.Write("Varijanca prve generacije: ");
- tw_0.WriteLine(varijancaInicijalna);
- string varijanca = "";
- // CM - I reordered this to be:
- // 1. compute fitness of current population
- // 2. Crossover
- // 3. Mutate
- do
- {
- // CM --
- // calculates the raw and scaled fitness
- //
- genotip.RacunajFunkcijuFitnesa(genotip.kromosom);
- // CM -- introducing niching...
- // With explicit fitness sharing, like chromosomes will be penalized
- // by scaling their fitness by 1/N, where N is the number of chromosomes in
- // the niche. The more niches in the population, the more diverse the population
- genotip.Niching(genotip.kromosom, 500.0f );
- // CM -- "count function selections" ???
- //
- // computes the scaled fitness (TempSelection),
- // and ranges for selection (UpperBound, LowerBound)
- //
- // NOTE - this is the second component with the fitness calculation
- // at the end. both are required to fill the new Kromosomes completely
- genotip.RacunajFunkcijuSelekcije(genotip.kromosom);
- // CM -
- // bug?? you're not resetting the tempMaxFitnes every generation. If the
- // current generation has worse fitness than the last, the "best chromosome
- // in generation" will be from a previous generation.
- Kromosom best = null;
- double min_raw_fitness = double.MaxValue;
- foreach (var kromosom in genotip.kromosom)
- {
- // CM - i'm using raw fitness here because it's unaffected
- // by niching. the best will be selected most often, resulting in
- // a large niche being created, which penalizes the entire
- // niche including the best. This ensures our BEST solution so far
- // is kept.
- if (kromosom.RawFitnes < min_raw_fitness)
- {
- min_raw_fitness = kromosom.RawFitnes;
- best = kromosom; // CM "best chromosome in a generation"
- }
- }
- // CM - write the best of this generation to the console
- Console.WriteLine( "[" + korak + "] " + best.AsString() );
- // CM - detailed dump of the population
- // DUMP MUST HAPPEN HERE after the TempFitness has been evaluated
- // NOTE: Generates a LOT OF FILES, but is VERY HELPFUL for debugging
- DumpGeneration( korak, genotip, best );
- // CM - adding roulette selection
- int N = genotip.kromosom.Count; // total chromosome count
- var selection = new List<Kromosom>( );
- // CM - roulette selection
- //selection.AddRange( genotip.RouletteSelection(genotip.kromosom, N/2) );
- // CM - as is, this selects N chromosomes from the population
- // this can have repeats.
- // For each N
- // Pick 2 at random
- // 72% chance to pick the stronger (higher fitness)
- // 28% chance to pick the weaker (lower fitness)
- selection.AddRange( genotip.ProbabilisticBinaryTournamentSelection(genotip.kromosom, 0.72, N) );
- // randomize the list so that the mutation and crossover can just pick items off the front
- genotip.RazbacajListu( selection );
- // CM --
- // Crossover returns N chromosomes.
- //
- // Originally:
- // There's a 66% chance of a crossover.
- // CROSSOVER is a 50% chance for EACH ALLELE to flip
- //
- // Now:
- // 88% chanace of a single-point crossover
- // 10% chance of an extreme crossover where every allele has a 50% chance at flipping
- // 2% chance that the parents don't cross over at all
- var crossoverKromos = genotip.Crossover_2(selection, -1);
- // CM --
- // Appy Mutations.
- //
- // korak = "step"
- //
- // Originally:
- // within the first 10 steps - 30% chance of a single-allele change
- // after first 10 steps - 5% chance of a COMPLETE CHROMOSOME REWRITE
- //
- // Now:
- // 30% chance that a single alele will be replaced
- // 30% chance that two alleles will swap places
- // 15% chance that a single alele will be scaled, range (0.8, 1.2)
- // 15% chance that a single alele will by shifted by +/- 100
- // 10% chance the allele will not change at all
- var mutatedKromos = genotip.Mutation(crossoverKromos, -1); // this for mutates the crossovers
- if(selection.Count != 0) // allow one
- throw new InvalidOperationException("selection should be empty at this point");
- if (mutatedKromos.Count != N)
- throw new InvalidOperationException("output of mutation should be the same as the initial population");
- var nextGen = new List<Kromosom>();
- nextGen.AddRange( mutatedKromos );
- //nextGen.AddRange( crossoverKromos );
- // CM -- hack.. make sure the BEST chromosome gets in
- // Elitism
- nextGen[0] = new Kromosom( best );
- //List<Kromosom> tempListaKromosoma = new List<Kromosom>(genotip.kromosom);
- genotip.kromosom = nextGen;
- korak++; // step (generation)
- // ONLY THE RAW FITNESS IS AVAILABLE HERE.. NEXT ITERATION OF THE LOOP
- // IS REQUIRED TO HAVE VALID TempSelection (scaled fitness) AND LOWERBOUND, UPPERBOUND
- }
- // while (Check convergence)
- //while (genotip.ProvjeriKonvergenciju(genotip.kromosom,najboljiKromosomUGeneraciji)==false);
- while(true);
- tw_0.Write("Varijanca zadnje generacije: "); // CM - "variance of the FINAL generation"
- tw_0.WriteLine(varijanca);
- tw_0.Close();
- #if WINDOWS
- int p = 0;
- for (int i = 0; i < genotip.kromosom.Count; i++)
- {
- p = i + 1;
- chart_lastPopulation.Series[0].Points.AddXY(p, genotip.kromosom[i].TempFitnes);
- }
- #endif
- TextWriter tw = new StreamWriter("beta.txt");
- for (int i = 0; i < najboljiKromosomUGeneraciji.Alele.Count; i++)
- {
- tw.Write(najboljiKromosomUGeneraciji.Alele[i] + " ");
- }
- tw.Close();
- #if WINDOWS
- //najboljiKromosomUGeneraciji.TempFitnes!=najboljiKromosomUPrethodnojGeneraciji.TempFitnes
- MessageBox.Show("Rjesenje nadjeno", "BINGO");
- MessageBox.Show("Pronadjeni su koeficijenti\n b0:"+najboljiKromosomUGeneraciji.Alele[0]+
- "\n b1:"+najboljiKromosomUGeneraciji.Alele[1]+
- "\n b2:"+najboljiKromosomUGeneraciji.Alele[2]+
- "\n b3:"+najboljiKromosomUGeneraciji.Alele[3]+
- "\n b4:"+najboljiKromosomUGeneraciji.Alele[4]+
- "\n b5:"+najboljiKromosomUGeneraciji.Alele[5]+
- "\n b6:"+najboljiKromosomUGeneraciji.Alele[6]+
- "\n b7:"+najboljiKromosomUGeneraciji.Alele[7]+
- "\n b8:"+najboljiKromosomUGeneraciji.Alele[8]+
- "\n b9:"+najboljiKromosomUGeneraciji.Alele[9]+
- "\n b10:"+najboljiKromosomUGeneraciji.Alele[10]);
- #endif
- }
- // CM -- dump the entire generation to file for inspection
- // istovariti korak
- void DumpGeneration (int generation, Genotip genotype, Kromosom best)
- {
- int gen_k = generation/1000;
- string dir = gen_k.ToString();
- if(!Directory.Exists(dir)) {
- Directory.CreateDirectory(dir);
- }
- string path = Path.Combine( new[] { dir, string.Format("korak_{0:0000}", generation) });
- using(StreamWriter sw = new StreamWriter(path,false))
- {
- sw.WriteLine("Generation " + generation);
- sw.WriteLine("Raw Fit(x), Scaled Fit(1/x), Niche, NicheFit, Norm Scale Fit(norm(1/x)), Alleles ...");
- foreach(var k in genotype.kromosom) {
- sw.Write ( k.AsString() );
- sw.WriteLine();
- }
- // evaluate the best chromosome against all the sample points
- sw.WriteLine();
- sw.WriteLine("Best, evaluated: ");
- sw.WriteLine("index;guess;actual;error");
- for(int i=0; i<genotype.sampleCount; i++) {
- double guess, actual;
- guess = genotype.eval( best, i, out actual );
- sw.WriteLine("{0};{1:0.0000};{2:0.0000};{3:0.0000}", i, guess, actual, guess-actual);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement