public static GeneticSharp.Domain.GeneticAlgorithm DefaultGeneticAlgorithm(Func <double[], double> func, Tuple <double, double>[] minmax) { var population = new Population(20, 40, chromosome.CreateIntChromosone(minmax)); var fitness = new FuncFitness((c) => { var fc = c as FloatingPointChromosome; var values = fc.ToFloatingPoints(); return(func(values)); }); var selection = new EliteSelection(); var crossover = new UniformCrossover(0.5f); var mutation = new FlipBitMutation(); var ga = new GeneticSharp.Domain.GeneticAlgorithm( population, fitness, selection, crossover, mutation); var termination = new FitnessStagnationTermination(100); ga.Termination = termination; Console.WriteLine("Generation: (x1, y1), (x2, y2) = distance"); return(ga); }
static void Main(string[] args) { var data = new Data(); var selection = new EliteSelection(); var crossover = new UniformCrossover(0.5f); var mutation = new FlipBitMutation(); var fitness = new FitnessFunction(data); var chromosome = new Chromosome(data.ItemsCount); var population = new Population(50, 70, chromosome); var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation); ga.Termination = new GenerationNumberTermination(100); Console.WriteLine("Rozpoczęcie wykonania algorytmu..."); var watch = System.Diagnostics.Stopwatch.StartNew(); ga.Start(); watch.Stop(); var executionTime = watch.ElapsedMilliseconds; Console.WriteLine("---------Wynik---------"); var result = new Result(ga.BestChromosome, executionTime, data.ListOfItems); result.DisplayResult(); Console.ReadLine(); }
protected override GeneticAlgorithm CreateGA() { NumberOfSimultaneousEvaluations = SimulationsGrid.x * SimulationsGrid.y; m_fitness = new CarFitness(); var chromosome = new CarChromosome(Config); var crossover = new UniformCrossover(); var mutation = new FlipBitMutation(); var selection = new EliteSelection(); var population = new Population(NumberOfSimultaneousEvaluations, NumberOfSimultaneousEvaluations, chromosome) { GenerationStrategy = new PerformanceGenerationStrategy() }; var ga = new GeneticAlgorithm(population, m_fitness, selection, crossover, mutation) { Termination = new CarTermination(), TaskExecutor = new ParallelTaskExecutor { MinThreads = population.MinSize, MaxThreads = population.MaxSize * 2 } }; ga.GenerationRan += delegate { m_lastPosition = Vector3.zero; m_evaluationPool.ReleaseAll(); }; ga.MutationProbability = .1f; return(ga); }
public GeneticSharpSolver Setup() { var chromosome = new FloatingPointChromosome( _decisions.Select(d => d.LowerBound).ToArray(), _decisions.Select(d => d.UpperBound).ToArray(), _decisions.Select(d => d.TotalBits).ToArray(), _decisions.Select(d => d.FractionDigits).ToArray()); var population = new Population(_populationSize, _populationSize + _offspringNumber, chromosome); var fitness = new FuncFitness((c) => { return(_objective(c as FloatingPointChromosome, this)); }); var selection = new EliteSelection(); var crossover = new UniformCrossover(0.5f); var mutation = new FlipBitMutation(); var termination = new GenerationNumberTermination(_maxGenerations); _ga = new GeneticAlgorithm( population, fitness, selection, crossover, mutation); _ga.Termination = termination; if (_generationCallback != null) { _ga.GenerationRan += (sender, e) => _generationCallback(_ga); } return(this); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new Painter()); //setupNext(); var chromosome = new FloatingPointChromosome( //lvl, hp, food, ruletype, rule, seed, tempo, pitch, r1, r2, r3 new double[] { 0, 0, 0, 7, 30, 32, 23, 23, 0, 0, 0 }, //min values new double[] { 50, 500, 5, 1800, 999999999, 9999999, 288, 72, 999, 999, 999 }, //max values new int[] { 6, 9, 3, 11, 34, 27, 9, 7, 10, 10, 10 }, //bits required for values new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } //bits for fractals ); var population = new Population(5, 25, chromosome); //min-max population var fitness = new myFitness(); var selection = new EliteSelection(); var crossover = new TwoPointCrossover(); var mutation = new FlipBitMutation(); var termination = new GenerationNumberTermination(10); var ga = new GeneticAlgorithm( population, fitness, selection, crossover, mutation); ga.Termination = termination; ga.Start(); }
public GeneticAlgorithm CreateGA(Func <RobotChromosome, Task <ContestGame> > contestFactory, RobotEvolutionConfiguration config) { NumberOfSimultaneousEvaluations = 2; var fitness = new RobotFitness(contestFactory, config); var chromosome = new RobotChromosome(config); var crossover = new UniformCrossover(); var mutation = new FlipBitMutation(); var selection = new EliteSelection(); var population = new Population(NumberOfSimultaneousEvaluations, NumberOfSimultaneousEvaluations, chromosome) { GenerationStrategy = new PerformanceGenerationStrategy() }; var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation) { Termination = new RobotTermination(), //TaskExecutor = new LinearTaskExecutor(), TaskExecutor = new ParallelTaskExecutor { MaxThreads = 10 } }; ga.GenerationRan += delegate { Console.WriteLine("Generation complete"); }; ga.MutationProbability = .1f; return(ga); }
public void InitiGA(GeneticAlgoritmConfig config) { Config = config; //IChromosome adamChromosome = new FloatingPointChromosome(config.MinChromosomeValue, config.MaxChromosomeValue, config.ChromosomeSize, config.ChromosomeFractionDigits); float maxWidth = 1000000; float maxHeight = 1000000; IChromosome adamChromosome = new FloatingPointChromosome( new double[] { 0, 0, 0, 0 }, new double[] { maxWidth, maxHeight, maxWidth, maxHeight }, new int[] { 64, 64, 64, 64 }, new int[] { 2, 2, 2, 2 }); Population population = new Population(config.MinPopulationSize, config.MinPopulationSize, adamChromosome); IFitness fitness = new SimpleFitness(); ISelection selection = new EliteSelection(); ICrossover crossover = new UniformCrossover(0.1f); IMutation mutation = new FlipBitMutation(); ITermination termination = new FitnessStagnationTermination(config.StagnationGenerationCount); population.GenerationStrategy = new PerformanceGenerationStrategy(); geneticAlgorithm = new GeneticAlgorithm(population, fitness, selection, crossover, mutation) { Termination = termination }; geneticAlgorithm.CrossoverProbability = config.CrossoverProbability; geneticAlgorithm.MutationProbability = config.MutationProbability; geneticAlgorithm.GenerationRan += OnNewGeneration; geneticAlgorithm.TerminationReached += OnTermination; geneticAlgorithm.Start(); }
public IMutation FlipBitMutation() { var target = new FlipBitMutation(); target.Mutate(new FloatingPointChromosome(0, _numberOfCities, 0), _probability); return(target); }
public void Start_FloatingPoingChromosome_Evolved() { var chromosome = new FloatingPointChromosome( new double[] { 0, 0, 0, 0 }, new double[] { 1000, 1000, 1000, 1000 }, new int[] { 10, 10, 10, 10 }, new int[] { 0, 0, 0, 0 }); var population = new Population(25, 25, chromosome); var fitness = new FuncFitness((c) => { var f = c as FloatingPointChromosome; var values = f.ToFloatingPoints(); var x1 = values[0]; var y1 = values[1]; var x2 = values[2]; var y2 = values[3]; // Euclidean distance: https://en.wikipedia.org/wiki/Euclidean_distance return(Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2))); }); var selection = new EliteSelection(); var crossover = new UniformCrossover(); var mutation = new FlipBitMutation(); var termination = new FitnessStagnationTermination(100); var ga = new GeneticAlgorithm( population, fitness, selection, crossover, mutation); ga.Termination = termination; ga.Start(); var bc = ga.BestChromosome as FloatingPointChromosome; var points = bc.ToFloatingPoints(); Assert.AreEqual(4, points.Length); Assert.AreEqual(1414.2135623730951, bc.Fitness); Assert.GreaterOrEqual(ga.GenerationsNumber, 100); }
public void Mutate_NotBinaryChromosome_Exception() { var target = new FlipBitMutation(); var chromosome = Substitute.For <ChromosomeBase>(3); chromosome.ReplaceGenes(0, new Gene[] { new Gene(0), new Gene(0), new Gene(0) }); Assert.Catch <MutationException>(() => { target.Mutate(chromosome, 1); }, "Needs a binary chromosome that implements IBinaryChromosome."); }
public void Mutate_NotBinaryChromosome_Exception() { var target = new FlipBitMutation(); var chromosome = MockRepository.GenerateStub <ChromosomeBase>(3); chromosome.ReplaceGenes(0, new Gene[] { new Gene(0), new Gene(0), new Gene(0) }); ExceptionAssert.IsThrowing(new MutationException( target, "Needs a binary chromosome that implements IBinaryChromosome."), () => { target.Mutate(chromosome, 1); }); }
public void Mutate_NoArgs_BitMutated() { RandomizationProvider.Current = Substitute.For <IRandomization>(); RandomizationProvider.Current.GetInt(0, 3).Returns(1); var target = new FlipBitMutation(); var chromosome = new BinaryChromosomeStub(3); chromosome.ReplaceGenes(0, new Gene[] { new Gene(0), new Gene(0), new Gene(0) }); target.Mutate(chromosome, 1); Assert.AreEqual(0, chromosome.GetGene(0).Value); Assert.AreEqual(1, chromosome.GetGene(1).Value); Assert.AreEqual(0, chromosome.GetGene(2).Value); }
public GeneticAlgorithm GetGA(int seed, int termination) { RandomizationProvider.Current = new FastRandomRandomizationWithSeed(); FastRandomRandomizationWithSeed.setSeed(seed); var selection = new EliteSelection(); var crossover = new OnePointCrossover(); var mutation = new FlipBitMutation(); var fitness = new IntegerMaximizationFitness(); var chromosome = new IntegerChromosome(0, 9); var population = new Population(2, 10, chromosome); var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation) { Termination = new GenerationNumberTermination(termination) }; ga.Start(); return(ga); }
public Task <Timetable> RunAsync() { var adamChromosome = CreateAdamChromosome(); var population = new Population(50, 100, adamChromosome); var fitness = new FuncFitness(TimetablerFitnessFunction); var selection = new EliteSelection(); var crossover = new UniformCrossover(0.5f); var mutation = new FlipBitMutation(); var termination = new TimeEvolvingTermination(TimeSpan.FromSeconds(20)); var geneticAlgorithm = new GeneticAlgorithm( population, fitness, selection, crossover, mutation) { Termination = termination }; geneticAlgorithm.GenerationRan += (sender, e) => { var bestChromosome = geneticAlgorithm.BestChromosome as FloatingPointChromosome; GeneticSolution = ChromosomeToTimetable(bestChromosome); }; GeneticAlgorithm = geneticAlgorithm; return(Task.Factory.StartNew(() => { geneticAlgorithm.Start(); return GeneticSolution; })); }
static void Main(string[] args) { // x2 -> En büyük değerini bulcaz. var selection = new EliteSelection(); var crossover = new OnePointCrossover(); var mutation = new FlipBitMutation(); var fitness = new MyProblemFitness(); var chromosome = new MyProblemChromosome(); var population = new Population(40, 40, chromosome); var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation) { Termination = new GenerationNumberTermination(100) }; int index = 0; ga.GenerationRan += delegate { var bestChromosome = ga.Population.BestChromosome; Console.Write("Index: " + index); Console.Write(", Fitness: {0}", bestChromosome.Fitness); Console.Write(", Time: {0}", ga.TimeEvolving); Console.WriteLine(); index++; }; Console.WriteLine("GA running..."); ga.Start(); Console.WriteLine("Best solution found has {0} fitness.", ga.BestChromosome.Fitness); Console.Read(); }
public void Mutate_NoArgs_BitMutated() { RandomizationProvider.Current = MockRepository.GenerateMock <IRandomization>(); RandomizationProvider.Current.Expect(r => r.GetInt(0, 3)).Return(1); var target = new FlipBitMutation(); var chromosome = new BinaryChromosomeStub(3); chromosome.ReplaceGenes(0, new Gene[] { new Gene(0), new Gene(0), new Gene(0) }); target.Mutate(chromosome, 1); Assert.AreEqual(0, chromosome.GetGene(0).Value); Assert.AreEqual(1, chromosome.GetGene(1).Value); Assert.AreEqual(0, chromosome.GetGene(2).Value); RandomizationProvider.Current.VerifyAllExpectations(); }
public static GeneticAlgorithm GetGeneticAlgorithm() { var chromosome = new ConfigurationChromosome(); var population = new Population(50, 100, chromosome); var fitness = new CorrectPercentageFitness(); var selection = new EliteSelection(); var crossover = new UniformCrossover(0.5f); var mutation = new FlipBitMutation(); var termination = new FitnessStagnationTermination(100); var ga = new GeneticAlgorithm( population, fitness, selection, crossover, mutation) { Termination = termination }; return(ga); }
public OutputModel Process(InputModel input) { var toppingCount = Enum.GetValues(typeof(Topping)).Length; var sliceMasks = GeneratePossibleSliceMasks(input.MinToppings * toppingCount, input.MaxCells).ToList(); var validSlices = new ConcurrentBag <Slice>(); Parallel.ForEach(sliceMasks, mask => { for (var i = 0; i < input.Rows - mask.Width; i++) { for (var j = 0; j < input.Columns - mask.Height; j++) { var slice = new Slice(i, j, i + mask.Width, j + mask.Height); if (IsValidSlice(input, slice)) { validSlices.Add(slice); } } } }); var orderedSlices = validSlices.ToList(); var mutationRate = 1f; var crossOverRate = 1f; RandomizationProvider.Current = new FastRandomRandomization(); var fitness = new PizzaCutterFitness(input, orderedSlices); var selection = new EliteSelection(); var crossOver = new EvolutionStrategyCrossOver(); var mutation = new FlipBitMutation(); var reinsertion = new EliteIncludeParentsReinsertion(fitness); var currentBest = new PizzaCutterChromosome(orderedSlices.Count, (input.Rows * input.Columns) / (input.MinToppings * toppingCount)); currentBest.Fitness = fitness.Evaluate(currentBest); var population = new Population(10, 20, currentBest); var ga = new GeneticAlgorithm(population, fitness, selection, crossOver, mutation) { Reinsertion = reinsertion, Termination = new FitnessStagnationTermination(), CrossoverProbability = crossOverRate, MutationProbability = mutationRate, TaskExecutor = new SmartThreadPoolTaskExecutor() { MinThreads = Environment.ProcessorCount, MaxThreads = Environment.ProcessorCount } }; ga.GenerationRan += (sender, args) => { if (ga.BestChromosome.Fitness > currentBest.Fitness) { currentBest = ga.BestChromosome.Clone() as PizzaCutterChromosome; } }; ga.Start(); var output = new OutputModel() { Slices = currentBest.GetSlices(orderedSlices).ToList() }; return(output); }
public static void Main(string[] args) { //Inicjujemy zmienne które będą granicznymi wartościami dla naszych punktów x1,x2,y1,y2. double maxWidth = 9999; double maxHeight = 8765; //Tworzymy strukture pojedyńczego chormosomu var chromosome = new FloatingPointChromosome( new double[] { -1000, -1000, -1000, -1000 }, //Warości początkowe dla x1,x2,y1,y2 new double[] { maxWidth, maxHeight, maxWidth, maxHeight }, //Wartości maksymalne dla x1,x2,y1,y2 new int[] { 64, 64, 64, 64 }, //Liczba bitów użytych do uzyskania wyniku new int[] { 0, 0, 0, 0 }); var population = new Population(10, 50, chromosome); //Określamy ilość chromosomów //(x,y,chromosome) x=minimalna liczba chromosomów, y=maksymalna liczba chormosomów //chromosome=odniesienie się do wyżej utworzonego chromosomu var fitness = new FuncFitness((c) => //Implementacja funkcji fitness z chormosomem w zmiennej "c" { var fc = c as FloatingPointChromosome; //Rzutowanie powyższego chormosomu na FloatingPointChromosme var values = fc.ToFloatingPoints(); //konwertowanie FloatingPointChromosome do jego fenotypu var x1 = values[0]; //konwertowanie FloatingPointChromosome do jego fenotypu x1 var y1 = values[1]; //konwertowanie FloatingPointChromosome do jego fenotypu y1 var x2 = values[2]; //konwertowanie FloatingPointChromosome do jego fenotypu x2 var y2 = values[3]; //konwertowanie FloatingPointChromosome do jego fenotypu y2 return(Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2))); //Przekazanie wartości do naszej funkcji }); var selection = new EliteSelection(); //Selekcja odpowiada za wybór chormosomów o największym dystanisie var crossover = new UniformCrossover(0.5f); //Ta sekcja pozwala na krzyżowanie się chromosomów aby generować nowe rozwiązania dla kolejnej generacji //Potomstwo przy parametrze 0.5 posiada mniej więcej połowę genów rodziców. var mutation = new FlipBitMutation(); //Mutacja uniemożliwa "utknięcie" naszego algorytmu w optimum lokalnym, mutacja Flip-Bit lodowo wybiera //gen i odwraca jego wartości, gen o wartości 1 stanie się genem o wartości 0 var termination = new FitnessStagnationTermination(1000); //Warunek zakończenia działania algorytmu //Jeżeli nasz program wygeneruje w ciągu 1000 pokoleń taką samą wartość funkcji fitness to działanie programu zostanie zakończone. //Poniższy fragment odpowiada ze wywołanie zdefiniowanych przez nas wartości komenda ga.Start() spodowuje rozpoczęcie działania funkcji var ga = new GeneticAlgorithm( population, fitness, selection, crossover, mutation); ga.Termination = termination; //Cały poniższy blok kodu podowuje wyświetlenie kolejnych kroków wyliczania AG na ekranie konsoli Console.WriteLine("Generation: (x1, y1), (x2, y2) = distance"); var latestFitness = 0.0; ga.GenerationRan += (sender, e) => { var bestChromosome = ga.BestChromosome as FloatingPointChromosome; var bestFitness = bestChromosome.Fitness.Value; if (bestFitness != latestFitness) { latestFitness = bestFitness; var phenotype = bestChromosome.ToFloatingPoints(); Console.WriteLine( "Generation {0,2}: (X1={1},Y1={2}),(X2={3},Y2={4}) = Największy dystans między punktami {5}", ga.GenerationsNumber, phenotype[0], phenotype[1], phenotype[2], phenotype[3], bestFitness ); } }; ga.Start(); Console.ReadKey(); }
static void Main(string[] args) { string cadena; //cadena leida por el usuario int tam_cadena; //tamaño de la cadena introducida string cadenana = ""; //cadena resultante generada por el algoritmo Console.WriteLine("Introduzca la cadena"); cadena = Console.ReadLine(); cadena = cadena.Trim(); //se eliminan espacios de la cadena introducida cadena = cadena.ToLower(); //se pasa a minusculas todas las letras tam_cadena = cadena.Length; //se obtiene le tamaño de la caden double[] min = new double[tam_cadena]; //se generan double[] max = new double[tam_cadena]; //rangos minimos y maximos para que trabaje el AG int[] arr = new int[tam_cadena]; //se generan los arreglos int[] arr2 = new int[tam_cadena]; // de numero de digits , bits for (int i = 0; i < tam_cadena; i++) //se debe de llenar una posicion del arreglo por cada gen(cada caracter de la cadena ) { min[i] = 97; //minimo -> a max[i] = 122; //maximo -> z arr[i] = 64; arr2[i] = 3; } var cromosoma = new FloatingPointChromosome(min, max, arr, arr2); //se instancia la nueva cromosoma var aptitud = new FuncFitness((c) => { //se define la funcion de aptitud var fc = c as FloatingPointChromosome; var x = fc.ToFloatingPoints(); string cad_obt = ""; double porcentaje; for (int i = 0; i < tam_cadena; i++) //para cada gen { cad_obt += (char)Convert.ToInt32(x[i]); //se debe de concatenar a la cadena obtenida, convirtiendo de float a int y despues } //casteando a caracter double dist = Math.Exp(-LevenshteinDistance(cadena, cad_obt, out porcentaje)); //se realiza el calculo return(1f / 1f + dist); //de la aptitud }); var poblacion = new Population(100, 1000, cromosoma); //se crea la poblacon con minimo 100 individuos y maximo 1000 var cruza = new UniformCrossover(0.3f); //se define como se realizara la cruza var mutacion = new FlipBitMutation(); //como se realizara la mutacion var seleccion = new RouletteWheelSelection(); //se elige el metodo de seleccion a utilizar var terminacion = new FitnessStagnationTermination(1000); //se determina el parametro de termino para el algoritmo genetico //var ga = new GeneticSharp var ga = new GeneticAlgorithm(poblacion, aptitud, seleccion, cruza, mutacion); //se crea el algoritmo genetico ga.Termination = terminacion; //se asigna la condicion de termino a el AG var latestFitness = 0.0; //variable para guardar fitness anterior ga.GenerationRan += (sender, e) => //funcion para estar verificando como es que evoluciona el AG { var bestchromosome = ga.BestChromosome as FloatingPointChromosome; //se obtiene la cromosoma var bestFitness = bestchromosome.Fitness.Value; //se obtiene el fitness de la cromosoma if (bestFitness != latestFitness) //se comprueba que el fitness actual sea distinto al anterior { latestFitness = bestFitness; //el anterior fitness se vuelve el mejor ahora, para asi comprobar que le fitness mejora // var phenotype = bestchromosome.ToFloatingPoints();//se obtienen los valores que reprsenta la cromosoma Console.WriteLine("Generation {0}", ga.GenerationsNumber); //se imprime el numero de generacion // Console.WriteLine("X = {0}", bestchromosome.ToFloatingPoint()); var x = bestchromosome.ToFloatingPoints(); //se obtienen los valores que reprsenta la cromosoma cadenana = ""; for (int i = 0; i < tam_cadena; i++) //se obtiene el valor { cadenana += (char)Convert.ToInt32(x[i]); // que representa el fenotipo en terminos de caracteres para } //formar la cadena resultante // Console.WriteLine("F(x) = {0}", (char)((int)bestFitness)); Console.WriteLine("Palabra Obtenida " + cadenana);//imprime la mejor aproximacion hasta ahora } }; ga.Start(); //se Inicia el AG Console.WriteLine("\nEjecucion Terminada \n"); Console.WriteLine("La Mejor Aproximacion a la solucion encontrada es :\n " + cadenana); //se imprime la mejor solucion encontrada Console.ReadLine(); //esto es para hacer un pausa y se pueda ver el resultado tranquilamente }
private void Iniciar_Click(object sender, RoutedEventArgs e) { Bitmap bmpDest = new Bitmap(bmpObj.Width, bmpObj.Height); Int32[] solucion = new Int32[bmpObj.Width * bmpObj.Height]; int i = 0; for (int y = 0; y < bmpObj.Height; y++) { for (int x = 0; x < bmpObj.Width; x++) { System.Drawing.Color color = bmpObj.GetPixel(x, y); solucion[i] = color.ToArgb(); i++; //bmpDest.SetPixel(x, y, System.Drawing.Color.FromArgb(acolor)); } } int tam = bmpObj.Width * bmpObj.Height; double[] minArray = new double[tam]; double[] maxArray = new double[tam]; int[] bits = new int[tam]; int[] b2 = new int[tam]; for (int j = 0; j < tam; j++) { minArray[j] = -16777216; maxArray[j] = -1; bits[j] = 64; b2[j] = 0; } var chromosome = new FloatingPointChromosome( minArray, maxArray, bits, b2 ); var fitness = new FuncFitness((c) => { var fc = c as FloatingPointChromosome; double[] values = fc.ToFloatingPoints(); //Int32[] valuesAux = new Int32[values.Length]; //for (int b = 0; b < values.Length; b++) { // valuesAux[b] = Convert.ToInt32(values[b]); //} double acum; acum = 0; for (int j = 0; j < values.Length; j++) { byte[] bA = BitConverter.GetBytes(Convert.ToInt32(values[j])); byte[] bA2 = BitConverter.GetBytes(solucion[j]); int ac = 0; for (int b = 0; b < 4; b++) { ac += Math.Abs(bA[b] - bA2[b]); } acum += ac; } if (acum == 0) { return(Int32.MaxValue); } else { return(1 / acum); } } ); var population = new Population(50, 100, chromosome); var selection = new EliteSelection(); var crossover = new UniformCrossover(0.7f); var mutation = new FlipBitMutation(); var termination = new FitnessStagnationTermination(1000); var ga = new GeneticAlgorithm( population, fitness, selection, crossover, mutation); ga.Termination = termination; var latestFitness = 0.0; ga.MutationProbability = 0.3f; ga.GenerationRan += (a, b) => { var bestChromosome = ga.BestChromosome as FloatingPointChromosome; var bestFitness = bestChromosome.Fitness.Value; if (bestFitness != latestFitness) { latestFitness = bestFitness; var phenotype = bestChromosome.ToFloatingPoints(); Dispatcher.BeginInvoke((Action)(() => { int pos = 0; for (int y = 0; y < bmpObj.Height; y++) { for (int x = 0; x < bmpObj.Width; x++) { var aas = phenotype[pos]; bmpDest.SetPixel(x, y, System.Drawing.Color.FromArgb(Convert.ToInt32(phenotype[pos]))); pos++; } } BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( bmpDest.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bmpDest.Width, bmpDest.Height)); ImageBrush ib = new ImageBrush(bs); Destino.Source = bs; //Resta Bitmap resta = new Bitmap(bmpObj.Width, bmpObj.Height); pos = 0; for (int y = 0; y < bmpObj.Height; y++) { for (int x = 0; x < bmpObj.Width; x++) { if (phenotype[pos] - solucion[pos] != 0) { resta.SetPixel(x, y, System.Drawing.Color.FromArgb(-16777216) ); } pos++; } } BitmapSource bs2 = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( resta.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bmpDest.Width, bmpDest.Height)); RestaM.Source = bs2; })); } }; Task.Run(() => { ga.Start(); }); }
public void TestMethod1() { float maxWidth = 998f; float maxHeight = 680f; var chromosome = new FloatingPointChromosome( new double[] { 0, 0, 0, 0 }, new double[] { maxWidth, maxHeight, maxWidth, maxHeight }, new int[] { 10, 10, 10, 10 }, new int[] { 0, 0, 0, 0 }); var population = new Population(50, 100, chromosome); var fitness = new FuncFitness((c) => { var fc = c as FloatingPointChromosome; var values = fc.ToFloatingPoints(); var x1 = values[0]; var y1 = values[1]; var x2 = values[2]; var y2 = values[3]; return(Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2))); }); var selection = new EliteSelection(); var crossover = new UniformCrossover(0.5f); var mutation = new FlipBitMutation(); var termination = new FitnessStagnationTermination(100); var ga = new GeneticAlgorithm( population, fitness, selection, crossover, mutation); ga.Termination = termination; Console.WriteLine("Generation: (x1, y1), (x2, y2) = distance"); var latestFitness = 0.0; ga.GenerationRan += (sender, e) => { var bestChromosome = ga.BestChromosome as FloatingPointChromosome; var bestFitness = bestChromosome.Fitness.Value; if (bestFitness != latestFitness) { latestFitness = bestFitness; var phenotype = bestChromosome.ToFloatingPoints(); Trace.WriteLine(string.Format( "Generation {0,2}: ({1},{2}),({3},{4}) = {5}", ga.GenerationsNumber, phenotype[0], phenotype[1], phenotype[2], phenotype[3], bestFitness )); } }; ga.Start(); }
public static void BuildTestGA() { //Create chromosome length = 20 BinaryChromosome chrom = new BinaryChromosome(20); //Create population = [2,100] var population = new Population(2, 100, chrom); //Console.WriteLine(chrom.Length); //Console.WriteLine(chrom.ToString()); //create Fitness Function (функция приспособления) var fitness = new FuncFitness( (c) => { var fc = c as BinaryChromosome; double result = 0.0; foreach (Gene gene in fc.GetGenes()) { result += Convert.ToDouble(gene.Value.ToString()); } return(result); } ); //create selection //var selection = new EliteSelection(); var selection = new TournamentSelection(); //var selection = new RouletteWheelSelection(); //var selection = new StochasticUniversalSamplingSelection(); //create crossover var crossover = new UniformCrossover(0.5f); //var crossover = new CutAndSpliceCrossover(); //только с EliteSelection() //var crossover = new OnePointCrossover(); //var crossover = new TwoPointCrossover(); //var crossover = new CycleCrossover(); // new OrderBasedCrossover(); new OrderedCrossover(); new PositionBasedCrossover(); new PartiallyMappedCrossover(); //может использоваться только с упорядоченными хромосомами. Указанная хромосома имеет повторяющиеся гены //var crossover = new ThreeParentCrossover(); //ОДНУ Итерацию выполняет //create mutation var mutation = new FlipBitMutation(); //var mutation = new UniformMutation(); //1 перегрузка принимает индексы генов для мутации, 2-я все гены мутируют //var mutation = new TworsMutation(); //Слабая //var mutation = new ReverseSequenceMutation(); //Слабая //create termination (Количество итераций) var termination = new GenerationNumberTermination(100); //var termination = new FitnessStagnationTermination(50); // var termination = new FitnessThresholdTermination(50); //Постоянно зацикливается //TimeSpan time = new TimeSpan(0, 0, 10); //10 секунд //var termination = new TimeEvolvingTermination(time); //Сам генетический алгоритм var ga = new GeneticAlgorithm( population, fitness, selection, crossover, mutation); ga.Termination = termination; Console.WriteLine("Generation: = distance"); var latestFitness = 0.0; ga.GenerationRan += (sender, e) => { var bestChromosome = ga.BestChromosome as BinaryChromosome; var bestFitness = bestChromosome.Fitness.Value; if (bestFitness != latestFitness) { latestFitness = bestFitness; var phenotype = bestChromosome.GetGenes(); //Console.WriteLine( // "Generation {0,2}: ({1},{2}),({3},{4}) = {5}", // ga.GenerationsNumber, // phenotype[0], // phenotype[1], // phenotype[2], // phenotype[3], // bestFitness //); Console.WriteLine("Generation {0,2}. Best Fitness = {1}", ga.GenerationsNumber, bestFitness); Console.Write("Chromosome: "); foreach (Gene g in phenotype) { Console.Write(g.Value.ToString() + ""); } Console.WriteLine(); } }; ga.Start(); }
static void Main(string[] args) { float largMax = 998f; //largura maxima ou maxWidht do retângulo float altMax = 680f; //altura maxima ou maxHeight do retângulo var cromossomo = new FloatingPointChromosome //Criando um cromossomo de distância euclidiana ( new double[] { 0, 0, 0, 0 }, new double[] { largMax, altMax, largMax, altMax }, new int[] { 10, 10, 10, 10 }, new int[] { 0, 0, 0, 0 } ); var population = new Population(50, 100, cromossomo); // população, de no minimo 50 e no maximo 100, criada usando o cromossomo var fitness = new FuncFitness((c) => // criando uma função fitness { var fc = c as FloatingPointChromosome; var valores = fc.ToFloatingPoints(); var x1 = valores[0]; var y1 = valores[1]; var x2 = valores[2]; var y2 = valores[3]; return(Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2))); //retorno }); var peneira = new EliteSelection(); // seletor "peneira" do tipo ELITE ou seja só os melhores passarão >>>> Besides this, you can use the already implemented classic selections: Elite, Roulete Wheel, Stochastic Universal Sampling and Tournament. var crossover = new UniformCrossover(0.5f); // aqui ocorre a união dos cromossomos para gerar novas possibilidades de soluções da proxima geração var mutacao = new FlipBitMutation(); // classe de mutação var terminator = new FitnessStagnationTermination(100); // essa parte passa uma "régua" no cromossomo e para de executar quando ele gera o melhor cromossomo 100 vezes. var creator = new GeneticAlgorithm(population, fitness, peneira, crossover, mutacao); // instaciei o algoritmo genetico>>>> creator.Termination = terminator; // parametros de terminação passados atraves do terminator //creator.Start();// mando ele iniciar o algoritmo daqui pra baixo da pra apagar que vai funcionar Console.WriteLine("Generation: (x1, y1), (x2, y2) = distance"); var latestFitness = 0.0; creator.GenerationRan += (sender, e) => { var bestChromosome = creator.BestChromosome as FloatingPointChromosome; var bestFitness = bestChromosome.Fitness.Value; if (bestFitness != latestFitness) { latestFitness = bestFitness; var phenotype = bestChromosome.ToFloatingPoints(); Console.WriteLine( "Generation {0,2}: ({1},{2}),({3},{4}) = {5}", creator.GenerationsNumber, phenotype[0], phenotype[1], phenotype[2], phenotype[3], bestFitness ); } }; creator.Start(); Console.ReadKey(); }
private static IAlgoritmo CriaAlgoritmoGenetico(Dictionary <string, string[]> dict, List <string> flat, Problema problema) { int populacaoMin, populacaoMax; IPopulation population; ISelection selection; ICrossover crossover; IMutation mutation; ITermination termination; IReinsertion reinsertion; float crossoverProbability, mutationProbability; var p = dict.ValueOrDefault("p", "50,100").Split(new[] { ',' }); if (p.Length != 2 || !int.TryParse(p[0], out populacaoMin) || !int.TryParse(p[1], out populacaoMax)) { throw new ArgumentException("Faixa de população inválida."); } population = new Population(populacaoMin, populacaoMax, new CromossomoViajante(problema.Mapa.Locais.Count)); switch (dict.ValueOrDefault("s", "t")) { case "e": selection = new EliteSelection(); break; case "r": selection = new RouletteWheelSelection(); break; case "s": selection = new StochasticUniversalSamplingSelection(); break; case "t": selection = new TournamentSelection(); break; default: throw new ArgumentException("Seleção inválida."); } switch (dict.ValueOrDefault("c", "o")) { case "s": crossover = new CutAndSpliceCrossover(); break; case "c": crossover = new CycleCrossover(); break; case "o": crossover = new OrderedCrossover(); break; case "ob": crossover = new OrderBasedCrossover(); break; case "op": crossover = new OnePointCrossover(); break; case "pm": crossover = new PartiallyMappedCrossover(); break; case "p": crossover = new PositionBasedCrossover(); break; case "tpa": crossover = new ThreeParentCrossover(); break; case "tp": crossover = new TwoPointCrossover(); break; case "u": crossover = new UniformCrossover(); break; default: throw new ArgumentException("Crossover inválido."); } switch (dict.ValueOrDefault("m", "r")) { case "d": mutation = new DisplacementMutation(); break; case "f": mutation = new FlipBitMutation(); break; case "i": mutation = new InsertionMutation(); break; case "s": mutation = new PartialShuffleMutation(); break; case "r": mutation = new ReverseSequenceMutation(); break; case "t": mutation = new TworsMutation(); break; case "u": mutation = new UniformMutation(); break; default: throw new ArgumentException("Mutação inválida."); } switch (dict.ValueOrDefault("t", "s")) { case "s": termination = new FitnessStagnationTermination(); break; case "t": termination = new FitnessThresholdTermination(); break; case "g": termination = new GenerationNumberTermination(); break; default: throw new ArgumentException("Terminação inválida."); } switch (dict.ValueOrDefault("e", "e")) { case "e": reinsertion = new ElitistReinsertion(); break; case "p": reinsertion = new PureReinsertion(); break; case "u": reinsertion = new UniformReinsertion(); break; default: throw new ArgumentException("Reinserção inválida."); } if (!float.TryParse(dict.ValueOrDefault("cp", "0,75"), out crossoverProbability)) { throw new ArgumentException("Probabilidade de crossover inválida."); } if (!float.TryParse(dict.ValueOrDefault("mp", "0,25"), out mutationProbability)) { throw new ArgumentException("Probabilidade de mutação inválida."); } return(new AlgoritmoGenetico(problema, population, selection, crossover, crossoverProbability, mutation, mutationProbability, termination, reinsertion)); }
static void Main(string[] args) { float maxWidth = 998f; float maxHeight = 680f; var chromosome = new FloatingPointChromosome( new double[] { 0, 0, 0, 0 }, new double[] { maxWidth, maxHeight, maxWidth, maxHeight }, new int[] { 10, 10, 10, 10 }, new int[] { 0, 0, 0, 0 }); var population = new Population(50, 100, chromosome); var fitness = new FuncFitness((c) => { var fc = c as FloatingPointChromosome; var values = fc.ToFloatingPoints(); var x1 = values[0]; var y1 = values[1]; var x2 = values[2]; var y2 = values[3]; return(Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2))); }); //TODO посмотреть, сколькл хромосом из общего числа выбрано var selection = new EliteSelection(); var crossover = new UniformCrossover(0.5f); var mutation = new FlipBitMutation(); var termination = new FitnessStagnationTermination(100); var ga = new GeneticAlgorithm( population, fitness, selection, crossover, mutation); ga.Termination = termination; Console.WriteLine("Generation: (x1, y1), (x2, y2) = distance"); var latestFitness = 0.0; ga.GenerationRan += (sender, e) => { var bestChromosome = ga.BestChromosome as FloatingPointChromosome; var bestFitness = bestChromosome.Fitness.Value; //TODO если фитнес равна нулю, мы ее можем записывать if (bestFitness != latestFitness) { latestFitness = bestFitness; var phenotype = bestChromosome.ToFloatingPoints(); Console.WriteLine( "Generation {0,2}: ({1},{2}),({3},{4}) = {5}", ga.GenerationsNumber, phenotype[0], phenotype[1], phenotype[2], phenotype[3], bestFitness ); } }; ga.Start(); Console.ReadKey(); }
public static DynamoGeneticAlgorithm CreateGeneticAlgorithm(Population population, [DefaultArgument("Evo.DynamoGeneticAlgorithm.Default()")] object selection, [DefaultArgument("Evo.DynamoGeneticAlgorithm.Default()")] object crossover, [DefaultArgument("Evo.DynamoGeneticAlgorithm.Default()")] object mutation, [DefaultArgument("Evo.DynamoGeneticAlgorithm.Default()")] object termination, [DefaultArgument("Evo.DynamoGeneticAlgorithm.Default()")] int?selectionSize, double crossoverProbability = DynamoGeneticAlgorithm.DefaultCrossoverProbability, double mutationProbability = DynamoGeneticAlgorithm.DefaultMutationProbability) { IChromosome exemplaryChromome = population.CurrentGeneration.Chromosomes[0]; ChromosomeType chromosomeType = 0; if (exemplaryChromome is BinaryChromosome) { chromosomeType = ((BinaryChromosome)exemplaryChromome).ChromosomeType; } else if (exemplaryChromome is CombinatorialChromosome) { chromosomeType = ((CombinatorialChromosome)exemplaryChromome).ChromosomeType; } else if (exemplaryChromome is DoubleChromosome) { chromosomeType = ((DoubleChromosome)exemplaryChromome).ChromosomeType; } ISelection selectionMethod = null; if (selection == null) { selectionMethod = new EliteSelection(); } else { if (selection is EliteSelection) { selectionMethod = selection as EliteSelection; } else if (selection is RouletteWheelSelection) { selectionMethod = selection as RouletteWheelSelection; } else if (selection is StochasticUniversalSamplingSelection) { selectionMethod = selection as StochasticUniversalSamplingSelection; } else if (selection is TournamentSelection) { selectionMethod = selection as TournamentSelection; } else { throw new CrossoverException("Invalid selection input. A valid object returned by a node of the Selections category should be used."); } } ICrossover crossoverMethod = null; if (crossover == null) { crossoverMethod = new UniformCrossover(0.5f); } else { if (crossover is AlternatingPositionCrossover) { if (chromosomeType != ChromosomeType.CombinatorialChromosome) { throw new CrossoverException("The Alternating-position Crossover (AP) can be only used with combinatorial chromosomes. The specified individuals are not combinatorial chromosomes."); } crossoverMethod = crossover as AlternatingPositionCrossover; } else if (crossover is CutAndSpliceCrossover) { if (chromosomeType == ChromosomeType.DoubleChromosome) { throw new CrossoverException("The Cut and Splice Crossover (AP) can be only used with binary and combinatorial chromosomes. The specified individuals are double chromosomes."); } crossoverMethod = crossover as CutAndSpliceCrossover; } else if (crossover is CycleCrossover) { if (chromosomeType != ChromosomeType.CombinatorialChromosome) { throw new CrossoverException("The Cycle Crossover (CX) can be only used with combinatorial chromosomes. The specified individuals are not combinatorial chromosomes."); } crossoverMethod = crossover as CycleCrossover; } else if (crossover is OnePointCrossover) { if (chromosomeType == ChromosomeType.DoubleChromosome) { throw new CrossoverException("The One-point Crossover can be only used with binary and combinatorial chromosomes. The specified individuals are double chromosomes."); } crossoverMethod = crossover as OnePointCrossover; } else if (crossover is OrderBasedCrossover) { if (chromosomeType != ChromosomeType.CombinatorialChromosome) { throw new CrossoverException("The Order Based Crossover (OX2) can be only used with combinatorial chromosomes. The specified individuals are not combinatorial chromosomes."); } crossoverMethod = crossover as OrderBasedCrossover; } else if (crossover is OrderedCrossover) { if (chromosomeType != ChromosomeType.CombinatorialChromosome) { throw new CrossoverException("The Ordered Crossover (OX1) can be only used with combinatorial chromosomes. The specified individuals are not combinatorial chromosomes."); } crossoverMethod = crossover as OrderedCrossover; } else if (crossover is PartiallyMappedCrossover) { if (chromosomeType != ChromosomeType.CombinatorialChromosome) { throw new CrossoverException("The Partially-mapped Crossover (PMX) can be only used with combinatorial chromosomes. The specified individuals are not combinatorial chromosomes."); } crossoverMethod = crossover as PartiallyMappedCrossover; } else if (crossover is PositionBasedCrossover) { if (chromosomeType != ChromosomeType.CombinatorialChromosome) { throw new CrossoverException("The Position Based Crossover (POS) can be only used with combinatorial chromosomes. The specified individuals are not combinatorial chromosomes."); } crossoverMethod = crossover as PositionBasedCrossover; } else if (crossover is SimulatedBinaryCrossover) { if (chromosomeType != ChromosomeType.DoubleChromosome) { throw new CrossoverException("The Simulated Binary Crossover (SBX) can be only used with double chromosomes. The specified individuals are not double chromosomes."); } crossoverMethod = crossover as SimulatedBinaryCrossover; } else if (crossover is ThreeParentCrossover) { if (chromosomeType == ChromosomeType.DoubleChromosome) { throw new CrossoverException("The Three-parent Crossover can be only used with binary and combinatorial chromosomes. The specified individuals are double chromosomes."); } crossoverMethod = crossover as ThreeParentCrossover; } else if (crossover is TwoPointCrossover) { if (chromosomeType == ChromosomeType.DoubleChromosome) { throw new CrossoverException("The Two-point Crossover can be only used with binary and combinatorial chromosomes. The specified individuals are double chromosomes."); } crossoverMethod = crossover as TwoPointCrossover; } else if (crossover is UniformCrossover) { if (chromosomeType == ChromosomeType.DoubleChromosome) { throw new CrossoverException("The Uniform Crossover can be only used with binary and combinatorial chromosomes. The specified individuals are double chromosomes."); } crossoverMethod = crossover as UniformCrossover; } else if (crossover is VotingRecombinationCrossover) { if (chromosomeType == ChromosomeType.DoubleChromosome) { throw new CrossoverException("The Voting Recombination Crossover (VR) can be only used with binary and combinatorial chromosomes. The specified individuals are double chromosomes."); } crossoverMethod = crossover as VotingRecombinationCrossover; } else { throw new CrossoverException("Invalid crossover input. A valid object returned by a node of the Crossovers category should be used."); } } IMutation mutationMethod = null; if (mutation == null) { mutationMethod = new FlipBitMutation(); } else { if (mutation is DisplacementMutation) { if (chromosomeType == ChromosomeType.DoubleChromosome) { throw new CrossoverException("The Displacement Mutation can be only used on binary and combinatorial chromosomes. The specified individuals are double chromosomes."); } mutationMethod = mutation as DisplacementMutation; } else if (mutation is FlipBitMutation) { if (chromosomeType != ChromosomeType.BinaryChromosome) { throw new CrossoverException("The Flip Bit Mutation can be only used on binary chromosomes. The specified individuals are not binary chromosomes."); } mutationMethod = mutation as FlipBitMutation; } else if (mutation is GaussianMutation) { if (chromosomeType != ChromosomeType.DoubleChromosome) { throw new CrossoverException("The Gaussian Mutation can be only used on double chromosomes. The specified individuals are not double chromosomes."); } mutationMethod = mutation as GaussianMutation; } else if (mutation is InsertionMutation) { if (chromosomeType == ChromosomeType.DoubleChromosome) { throw new CrossoverException("The Displacement Mutation can be only used on binary and combinatorial chromosomes. The specified individuals are double chromosomes."); } mutationMethod = mutation as InsertionMutation; } else if (mutation is PartialShuffleMutation) { if (chromosomeType == ChromosomeType.DoubleChromosome) { throw new CrossoverException("The Displacement Mutation (PSM) can be only used on binary and combinatorial chromosomes. The specified individuals are double chromosomes."); } mutationMethod = mutation as PartialShuffleMutation; } else if (mutation is PolynomialMutation) { if (chromosomeType != ChromosomeType.DoubleChromosome) { throw new CrossoverException("The Polynomial Mutation can be only used on double chromosomes. The specified individuals are not double chromosomes."); } mutationMethod = mutation as PolynomialMutation; } else if (mutation is ReverseSequenceMutation) { if (chromosomeType == ChromosomeType.DoubleChromosome) { throw new CrossoverException("The Displacement Mutation (RSM) can be only used on binary and combinatorial chromosomes. The specified individuals are double chromosomes."); } mutationMethod = mutation as ReverseSequenceMutation; } else if (mutation is TworsMutation) { if (chromosomeType == ChromosomeType.DoubleChromosome) { throw new CrossoverException("The Displacement Mutation can be only used on binary and combinatorial chromosomes. The specified individuals are double chromosomes."); } mutationMethod = mutation as TworsMutation; } else if (mutation is UniformMutation) { if (chromosomeType != ChromosomeType.BinaryChromosome) { throw new CrossoverException("The Uniform Mutation can be only used on binary chromosomes. The specified individuals are not binary chromosomes."); } mutationMethod = mutation as UniformMutation; } else { throw new CrossoverException("Invalid mutation input. A valid object returned by a node of Mutations category should be used."); } } ElitistReinsertion reinsertionMethod = new ElitistReinsertion(); ITermination terminationMethod = null; if (termination == null) { terminationMethod = new FitnessStagnationTermination(100); } else { if (termination is FitnessStagnationTermination) { terminationMethod = termination as FitnessStagnationTermination; } else if (termination is FitnessThresholdTermination) { terminationMethod = termination as FitnessThresholdTermination; } else if (termination is GenerationNumberTermination) { terminationMethod = termination as GenerationNumberTermination; } else if (termination is TimeEvolvingTermination) { terminationMethod = termination as TimeEvolvingTermination; } else if (termination is AndTermination) { terminationMethod = termination as AndTermination; } else if (termination is OrTermination) { terminationMethod = termination as OrTermination; } else { throw new CrossoverException("Invalid termination input. An object returned by nodes of Terminations library should be used."); } } if (selectionSize == null) { selectionSize = (int)Math.Round(0.5 * population.MaxSize); } else if (!(selectionSize is int)) { throw new CrossoverException("Defined selection size is not an integer."); } else if (selectionSize > population.MaxSize) { throw new CrossoverException("Selection size cannot be greater than population size."); } var algorithm = new DynamoGeneticAlgorithm(population, selectionMethod, crossoverMethod, mutationMethod, reinsertionMethod, terminationMethod) { SelectionSize = (int)selectionSize, CrossoverProbability = (float)crossoverProbability, MutationProbability = (float)mutationProbability, Timer = Stopwatch.StartNew() }; algorithm.Timer.Start(); return(algorithm); }
public static void Main(string[] args) { //represents a sample in the population var chromosome = new FloatingPointChromosome( //min values array Enumerable.Repeat(0.0, GoalString.Length).ToArray(), //max values array Enumerable.Repeat(25.0, GoalString.Length).ToArray(), //bits nneded array Enumerable.Repeat(5, GoalString.Length).ToArray(), //decimals required array Enumerable.Repeat(0, GoalString.Length).ToArray() ); //create the population var population = new Population(4, 8, chromosome); //define a fitness function var fitness = new FuncFitness((c) => { var fc = c as FloatingPointChromosome; var values = fc.ToFloatingPoints(); var numCorrect = 0; for (int i = 0; i < GoalString.Length; i++) { var intVersion = Convert.ToInt32(values[i]); if (intVersion == GoalString[i] - 'a') { numCorrect++; } } return(Convert.ToInt64(Math.Pow(2, numCorrect))); }); //select the top performers for reproduction var selection = new EliteSelection(); //get half of genetic material from each parent var crossover = new UniformCrossover(.5f); //our numbers are internally represented as binary strings, randomly flip those bits var mutation = new FlipBitMutation(); //stop mutating when there the goal is met (paried definition with fitness function) var termination = new FitnessThresholdTermination(Math.Pow(2, GoalString.Length)); //put the genetic algorithm together var ga = new GeneticAlgorithm( population, fitness, selection, crossover, mutation); ga.Termination = termination; //print out the top performer of the population ga.GenerationRan += (sender, e) => { var bestChromosome = ga.BestChromosome as FloatingPointChromosome; var bestFitness = Convert.ToInt32(bestChromosome.Fitness.Value); if (bestFitness != HighestFitness) { HighestFitness = bestFitness; } var phenotype = bestChromosome.ToFloatingPoints(); var ints = phenotype.Select(Convert.ToInt32).ToArray(); var bestString = ConvertIntArrayToString(ints); Console.WriteLine($"Best string: {bestString}"); }; ga.TerminationReached += (sender, eventArgs) => { Console.WriteLine("Finished Evolving"); }; ga.Start(); Console.ReadKey(); }
public static wynikGA Genetic(int counter, Item[] dane, double back_volume) { double[] minValue = new double[counter]; double[] maxValue = new double[counter]; int[] totalBits = new int[counter]; int[] fractionDigits = new int[counter]; for (int i = 0; i < counter; i++) { minValue[i] = 0; maxValue[i] = 1; totalBits[i] = 16; fractionDigits[i] = 4; } var selection = new TournamentSelection(50, true); var crossover = new TwoPointCrossover(); var mutation = new FlipBitMutation(); var chromosome = new FloatingPointChromosome(minValue, maxValue, totalBits, fractionDigits); // var fitobj = new MyProblemFitness(dane, chromosome, back_volume); //var fitness = fitobj.Evaluate; var population = new Population(500, 500, chromosome); var fitness = new FuncFitness((c) => { var fc = c as FloatingPointChromosome; //var _items = dane; //var _bvol = back_volume; /* var values = fc.ToFloatingPoints(); * var x1 = values[0]; * var y1 = values[1]; * var x2 = values[2]; * var y2 = values[3]; * return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)); * */ //chromosome.ReplaceGenes(0, chromosome.GetGenes()); double[] proc_wag = fc.ToFloatingPoints(); double suma_spakowanych = 0; double wartosc_spakowanych = 0; for (int i = 0; i < proc_wag.Length; i++) { suma_spakowanych += dane[i].item_volume * proc_wag[i]; wartosc_spakowanych += dane[i].item_value * proc_wag[i]; } if (suma_spakowanych <= back_volume) { double temp = (wartosc_spakowanych * (suma_spakowanych / back_volume)); if (temp < 0) { if (Experiments.doOutput) { System.Console.WriteLine("LOL "); } } } return((suma_spakowanych <= back_volume) ? (wartosc_spakowanych * (suma_spakowanych / back_volume)) : (-suma_spakowanych)); }); var ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation); ga.Termination = new GenerationNumberTermination(100); if (Experiments.doOutput) { System.Console.WriteLine("GA running..."); } ga.MutationProbability = 0.05f; ga.CrossoverProbability = 0.20f; //ga.Selection. ga.Start(); // FITNESS if (Experiments.doOutput) System.Console.WriteLine("Best solution found has fitness = " + ga.BestChromosome.Fitness); wynikGA w = new wynikGA(); w.ga = ga; w.ch = chromosome; w.ch.ReplaceGenes(0, ga.BestChromosome.GetGenes()); return(w); }
public static void Main(string[] args) { //// ======================================================================== // Initialize chromosome structure and fitness //========================================================================== int m_numberSpeedDistrPoints = 10; float maxSpeedStep = 20f; double[] minVals = new double[m_numberSpeedDistrPoints]; double[] maxVals = new double[m_numberSpeedDistrPoints]; int[] totalBits = new int[m_numberSpeedDistrPoints]; int[] fractionDigits = new int[m_numberSpeedDistrPoints]; for (int i = 0; i < m_numberSpeedDistrPoints; i++) { minVals[i] = 0; maxVals[i] = maxSpeedStep; totalBits[i] = 10; fractionDigits[i] = 4; } var chromosome = new FloatingPointChromosome(minVals, maxVals, totalBits, fractionDigits); // Creates Fitness criterion using raw data string observedDataFilePath = "C:\test.csv"; int m_testDataBuckets = 20; var fitness = new SpeedDistrFitness(observedDataFilePath, m_testDataBuckets, maxSpeedStep, m_numberSpeedDistrPoints); //// ======================================================================== // Initialize operators and run the algorithm //========================================================================== var selection = new EliteSelection(); var crossover = new UniformCrossover(0.5f); var mutation = new FlipBitMutation(); var population = new Population(10, 20, chromosome); // Terminate once the two distributions are homogeneous up to a specified significance level var significance = .05;// Percent significance ChiSquared c = new ChiSquared(m_testDataBuckets - 1); double threshold = c.InverseCumulativeDistribution(1 - significance); GeneticAlgorithm m_ga = new GeneticAlgorithm( population, fitness, selection, crossover, mutation) { //// ======================================================================== // Select termination method //========================================================================== Termination = new FitnessThresholdTermination(-threshold)// MUST BE NEGATIVE !! }; Console.WriteLine("Generation: Significance"); var latestFitness = 0.0; m_ga.GenerationRan += (sender, e) => { var bestChromosome = m_ga.BestChromosome as FloatingPointChromosome; var bestFitness = bestChromosome.Fitness.Value; if (bestFitness != latestFitness) { latestFitness = bestFitness; Console.WriteLine( "Generation {0,2}: {5}", m_ga.GenerationsNumber, bestFitness ); } }; m_ga.Start(); Console.ReadKey(); }