Example #1
0
        private static void SaveChromosome(FloatingPointChromosome chromosome, string chromosomeLabel)
        {
            string path = @"E:\Source\SamOthellop\SamOthellop\Model\Agents\Genetic\";

            //string path = String.Format(@"{0}\bestchromosome.dat", Application.StartupPath);
            SaveChromosome(chromosome, chromosomeLabel, path);
        }
Example #2
0
        /// <summary>
        /// Run GA against itself till evolution <paramref name="recursionDepth"/> times
        /// </summary>
        /// <param name="recursionDepth"></param>
        public static void RunRecursiveGeneticAlgorithm(int recursionDepth = 3)
        {
            //double[] priorGenes = LoadChromosome(@"E:\Source\SamOthellop\SamOthellop\Model\Agents\Genetic\bestchromosome5-10.dat");

            FloatingPointChromosome chromosome = new FloatingPointChromosome(
                new double[] { -100, -100, -100, -100, -100, -100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
                new double[] { 100, 100, 100, 100, 100, 100, 60, 60, 60, 60, 60, 60, 3, 3, 3, 3, 3, 3 },
                new int[] { 64, 64, 64, 64, 64, 64, 8, 8, 8, 8, 8, 8, 64, 64, 64, 64, 64, 64 },
                new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3 }
                );

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            for (int i = 0; i < recursionDepth; i++)
            {
                if (i == 0)
                {
                    IOthelloAgent randAgent = new RandomAgent();
                    EvolveGeneticAlgorithm(chromosome, randAgent, "test" + i.ToString());
                }
                else
                {
                    double[]      genes     = LoadChromosome();
                    IOthelloAgent heurAgent = new HeuristicAgent(LoadChromosome(@"E:\Source\SamOthellop\SamOthellop\Model\Agents\Genetic\test" + (i - 1).ToString()));
                    EvolveGeneticAlgorithm(chromosome, heurAgent, "test" + i.ToString());
                }
            }
            stopwatch.Stop();
            Console.WriteLine("Sucessfully recursively geneticially trained.  Training cost {0} time with {1} recursions", stopwatch.Elapsed, recursionDepth);
        }
Example #3
0
        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();
        }
Example #4
0
        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);
        }
        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();
        }
Example #6
0
        public double Evaluate(IChromosome chromosome)
        {//Play n games vs a random (to be Neural Net), % win is Fitness
            FloatingPointChromosome myChromosome = (FloatingPointChromosome)chromosome;

            double[] genes = myChromosome.ToFloatingPoints();

            double fitness      = 0;
            double wonCount     = 0;
            object wonCountLock = new object();

            for (int index = 0; index < TEST_COUNT; index++)
            {
                //Parallel.For(0, TEST_COUNT, new ParallelOptions() { MaxDegreeOfParallelism = 2},
                //   (index) => {
                BoardStates player = (index % 2 == 0) ? BoardStates.black : BoardStates.white;

                OthelloGame      othelloGame = new OthelloGame();
                IEvaluationAgent heurAgent   = new HeuristicAgent(genes);


                while (!othelloGame.GameComplete)
                {
                    if (othelloGame.WhosTurn == player)
                    {
                        othelloGame.MakeMove(heurAgent.MakeMove(othelloGame, player));
                    }
                    else
                    {
                        othelloGame.MakeMove(opposingAgent.MakeMove(othelloGame, ~player));
                    }
                }
                if (othelloGame.GameComplete)//just gotta check
                {
                    if (othelloGame.FinalWinner == player)
                    {
                        lock (wonCountLock)
                        {
                            wonCount++;
                        }
                    }
                    else if (othelloGame.FinalWinner == BoardStates.empty)
                    {
                        lock (wonCountLock)
                        {
                            wonCount += .5;
                        }
                    }
                }
                else
                {
                    throw new Exception("EvaluationFitness didn't complete a game");
                }
                // });
            }
            fitness = (double)wonCount / TEST_COUNT;
            //System.Diagnostics.Debug.WriteLine("Fitness: " + fitness);
            return(fitness);
        }
Example #7
0
        public void Constructor_FromZeroToZero_Double()
        {
            RandomizationProvider.Current = MockRepository.GenerateMock <IRandomization>();
            RandomizationProvider.Current.Expect(r => r.GetDouble(0, 0)).Return(0);
            var target = new FloatingPointChromosome(0, 0, 2);
            var actual = target.ToFloatingPoint();

            Assert.AreEqual(0, actual);
        }
Example #8
0
        public void ToFloatingPoint_NoArgs_Double()
        {
            RandomizationProvider.Current = Substitute.For <IRandomization>();
            RandomizationProvider.Current.GetDouble(0.5, 2.5).Returns(1.1);
            var target = new FloatingPointChromosome(0.5, 2.5, 2);
            var actual = target.ToFloatingPoint();

            Assert.AreEqual(1.1, actual);
        }
Example #9
0
        public void Constructor_FromZeroToZero_Double()
        {
            RandomizationProvider.Current = Substitute.For <IRandomization>();
            RandomizationProvider.Current.GetDouble(0, 0).Returns(0);
            var target = new FloatingPointChromosome(0, 0, 2);
            var actual = target.ToFloatingPoint();

            Assert.AreEqual(0, actual);
        }
Example #10
0
        public void ToFloatingPoint_NoArgs_Double()
        {
            RandomizationProvider.Current = MockRepository.GenerateMock <IRandomization>();
            RandomizationProvider.Current.Expect(r => r.GetDouble(0.5, 2.5)).Return(1.1);
            var target = new FloatingPointChromosome(0.5, 2.5, 2);
            var actual = target.ToFloatingPoint();

            Assert.AreEqual(1.1, actual);
        }
Example #11
0
        public void ToFloatingPoint_GreaterMaxValue_MaxValue()
        {
            RandomizationProvider.Current = Substitute.For <IRandomization>();
            RandomizationProvider.Current.GetDouble(0.5, 2.5).Returns(2.6);

            var target = new FloatingPointChromosome(0.5, 2.5, 64, 2);
            var actual = target.ToFloatingPoint();

            Assert.AreEqual(2.5, actual);
        }
        public static FloatingPointChromosome CreateFloatingChromosone(Tuple <double, double>[] minmax)
        {
            //     public FloatingPointChromosome(double[] minValue, double[] maxValue, int[] totalBits, int[] fractionBits);

            var chromosome = new FloatingPointChromosome(
                minValue: minmax.Select(_ => _.Item1).ToArray(),
                maxValue: minmax.Select(_ => _.Item2).ToArray(),
                totalBits: minmax.Select(_ => 20).ToArray(),
                fractionBits: minmax.Select(_ => 10).ToArray());

            return(chromosome);
        }
Example #13
0
        public void ToFloatingPoint_NegativeValue_Double()
        {
            RandomizationProvider.Current = Substitute.For <IRandomization>();
            RandomizationProvider.Current.GetDouble(-2.5, 0.5).Returns(-1.1);

            var target = new FloatingPointChromosome(-2.5, 0.5, 64, 2);

            Assert.AreEqual("1111111111111111111111111111111111111111111111111111111110010010", target.ToString());

            var actual = target.ToFloatingPoint();

            Assert.AreEqual(-1.1, actual);
        }
Example #14
0
        public static ProductMatchConfig GetMatchConfig(this FloatingPointChromosome fpc)
        {
            var values = fpc.ToFloatingPoints();

            return(new DefaultProductMatchConfig
            {
                NameMetricConfig =
                {
                    ABCompoundPositionalWeightRatio      = values[0],
                    APositionalWeightingCoefficientPower = values[1],
                    BPositionalWeightingCoefficientPower = values[2]
                }
            });
        }
Example #15
0
        public void ToFloatingPoints_NoArgs_Double()
        {
            RandomizationProvider.Current = MockRepository.GenerateMock <IRandomization>();
            RandomizationProvider.Current.Expect(r => r.GetDouble(0, 10)).Return(1);
            RandomizationProvider.Current.Expect(r => r.GetDouble(1, 11)).Return(2);
            RandomizationProvider.Current.Expect(r => r.GetDouble(2, 12)).Return(3);
            var target = new FloatingPointChromosome(new double[] { 0, 1, 2 }, new double[] { 10, 11, 12 }, new int[] { 8, 8, 8 }, new int[] { 0, 0, 0 });
            var actual = target.ToFloatingPoints();

            Assert.AreEqual(3, actual.Length);
            Assert.AreEqual(1, actual[0]);
            Assert.AreEqual(2, actual[1]);
            Assert.AreEqual(3, actual[2]);
        }
Example #16
0
        public void ToFloatingPoints_NoArgs_Double()
        {
            RandomizationProvider.Current = Substitute.For <IRandomization>();
            RandomizationProvider.Current.GetDouble(0, 10).Returns(1);
            RandomizationProvider.Current.GetDouble(1, 11).Returns(2);
            RandomizationProvider.Current.GetDouble(2, 12).Returns(3);
            var target = new FloatingPointChromosome(new double[] { 0, 1, 2 }, new double[] { 10, 11, 12 }, new int[] { 8, 8, 8 }, new int[] { 0, 0, 0 });
            var actual = target.ToFloatingPoints();

            Assert.AreEqual(3, actual.Length);
            Assert.AreEqual(1, actual[0]);
            Assert.AreEqual(2, actual[1]);
            Assert.AreEqual(3, actual[2]);
        }
        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 FlipGene_Index_ValueFlip()
        {
            RandomizationProvider.Current = Substitute.For <IRandomization>();
            RandomizationProvider.Current.GetDouble(0, 0).Returns(0);
            var target = new FloatingPointChromosome(0, 0, 2);

            target.FlipGene(0);
            Assert.AreEqual("10000000000000000000000000000000", target.ToString());

            target.FlipGene(1);
            Assert.AreEqual("11000000000000000000000000000000", target.ToString());

            target.FlipGene(31);
            Assert.AreEqual("11000000000000000000000000000001", target.ToString());

            target.FlipGene(30);
            Assert.AreEqual("11000000000000000000000000000011", target.ToString());
        }
Example #19
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World1!");
            var maxWidth   = 10;
            var maxHeight  = 10;
            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 });

            Console.WriteLine("Hello World24!");
            var counter = 0;
            var max     = args.Length != 0 ? Convert.ToInt32(args[0]) : -1;

            while (max == -1 || counter < max)
            {
                counter++;
                Console.WriteLine($"Counter: {counter}");
                System.Threading.Tasks.Task.Delay(1000).Wait();
            }
        }
        public void FloatingPoint()
        {
            var target = new FloatingPointChromosome(0, 10, 0);

            target.Clone();
            target.CompareTo(new FloatingPointChromosome(0, 10, 0));
            target.CreateNew();
            var x = target.Fitness;

            target.FlipGene(0);
            target.GenerateGene(0);
            target.GetGene(0);
            target.GetGenes();
            target.GetHashCode();
            var y = target.Length;

            target.ReplaceGene(0, new Gene(1d));
            target.ReplaceGenes(0, new Gene[] { new Gene(1), new Gene(0) });
            target.Resize(20);
            target.ToFloatingPoint();
            target.ToString();
        }
Example #21
0
        public override void ConfigGA(GeneticSharp.Domain.GeneticAlgorithm ga)
        {
            var latestFitness = 0.0;

            Context.GA.GenerationRan += (object sender, EventArgs e) =>
            {
                m_bestChromosome = Context.GA.BestChromosome as FloatingPointChromosome;

                if (m_bestChromosome != null)
                {
                    lock (m_positions)
                    {
                        var fitness = m_bestChromosome.Fitness.Value;
                        var points  = m_bestChromosome.ToFloatingPoints();

                        m_positions.Add(new KeyValuePair <double, double[]>(fitness, points));


                        if (fitness != latestFitness)
                        {
                            latestFitness = fitness;
                            var phenotype = m_bestChromosome.ToFloatingPoints();

                            Console.WriteLine(
                                "Generation {0,2}: ({1},{2}),({3},{4}) = {5}",
                                ga.GenerationsNumber,
                                phenotype[0],
                                phenotype[1],
                                phenotype[2],
                                phenotype[3],
                                fitness
                                );
                        }
                    }
                }
            };
        }
Example #22
0
        public static FloatingPointChromosome EvolveGeneticAlgorithm(FloatingPointChromosome chromosome, IOthelloAgent agent, string chromosomeLabel = "")
        {
            IPopulation population = new TplPopulation(30, 60, chromosome);
            IFitness    fitness    = new EvaluationFitness(agent);
            ISelection  selection  = new RouletteWheelSelection(); //Guess
            ICrossover  crossover  = new UniformCrossover();       //Guess
            IMutation   mutation   = new UniformMutation();        //Guess


            ITermination stagnation = new FitnessStagnationTermination(500);
            ITermination threshold  = new FitnessThresholdTermination(.9);

            ITaskExecutor taskExecutor = new ParallelTaskExecutor()
            {
                MaxThreads = Environment.ProcessorCount,
                MinThreads = Environment.ProcessorCount / 2
            };


            GeneticAlgorithm algorithm = new GeneticAlgorithm(population, fitness, selection, crossover, mutation)
            {
                TaskExecutor        = new TplTaskExecutor(),
                MutationProbability = .2f
            };

            algorithm.TaskExecutor = taskExecutor;
            algorithm.Termination  = stagnation;

            algorithm.Start();

            SaveChromosome((FloatingPointChromosome)algorithm.BestChromosome, chromosomeLabel);

            Debug.WriteLine("finished Training, with {0} time spent on evolving", algorithm.TimeEvolving);
            Debug.WriteLine("fitness of this generation vs the last : {0}", algorithm.Fitness);

            return((FloatingPointChromosome)algorithm.BestChromosome);
        }
Example #23
0
        public void functionOptimizationWithGeneticsharp()
        {
            /* example from
             * http://diegogiacomelli.com.br/function-optimization-with-geneticsharp/
             */
            float maxWidth  = 998f;
            float maxHeight = 680f;

            var chromosome = new FloatingPointChromosome(
                new double[] { 0, 0, 0, 0 },
                new double[] { maxWidth, maxHeight, maxWidth, maxHeight },
                new int[] { 12, 12, 12, 12 },
                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 RouletteWheelSelection();
            var crossover   = new ThreeParentCrossover();
            var mutation    = new PartialShuffleMutation();
            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();
                    var s         = string.Format("Generation {0,2}: ({1},{2}),({3},{4}) = {5}",
                                                  ga.GenerationsNumber,
                                                  phenotype[0],
                                                  phenotype[1],
                                                  phenotype[2],
                                                  phenotype[3],
                                                  bestFitness);
                    Console.WriteLine(
                        s
                        );
                }
            };

            ga.Start();
        }
Example #24
0
File: Program.cs Project: shreq/OE
        static void Main(string[] _)
        {
            const int NUMBER_OF_BITS = 2 * 8 * sizeof(float);

            ParameterSelection parameters = ConsoleParameterSelectionFactory.CreateSelection();

            var chromosome = new FloatingPointChromosome(
                new double[parameters.Variables.Length].Fill(parameters.LowerBound),
                new double[parameters.Variables.Length].Fill(parameters.UpperBound),
                new int[parameters.Variables.Length].Fill(NUMBER_OF_BITS),
                new int[parameters.Variables.Length].Fill(2)
                );

            var population = new Population(50, 50, chromosome);

            var fitness = new FunctionMinimumFitness()
            {
                FunctionVariables = parameters.Variables,
                Expression        = parameters.Expression
            };

            var geneticAlgorithm = new GeneticAlgorithm(population, fitness, parameters.Selection, parameters.Crossover, parameters.Mutation)
            {
                Termination = parameters.Termination
            };

            var filepath = "./results_" + (parameters.AdaptiveOn ? "AGA" : "SGA") +
                           "_" + parameters.Selection.GetType().Name +
                           "_" + parameters.Crossover.GetType().Name +
                           "_" + parameters.Mutation.GetType().Name +
                           "_" + parameters.Termination.GetType().Name + ".csv";

            geneticAlgorithm.GenerationRan += new WriterEventHandler(filepath).Handle;

            geneticAlgorithm.GenerationRan += new ConsoleLogEventHandler(parameters.Variables).Handle;

            if (parameters.AdaptiveOn)
            {
                geneticAlgorithm.GenerationRan += new AdaptiveStrategyEventHandler().Handle;
            }

            geneticAlgorithm.Start();

            var finalPhenotype = (geneticAlgorithm.BestChromosome as FloatingPointChromosome).ToFloatingPoints();

            var finalVariableValues = "Parameters:";

            for (int i = 0; i < parameters.Variables.Length; i++)
            {
                finalVariableValues += "\n" + parameters.Variables[i] + " = " + finalPhenotype[i];
            }

            var finalFitness = (geneticAlgorithm.BestChromosome as FloatingPointChromosome).Fitness.Value;

            Console.WriteLine("\n\n- - - Final result: - - -" +
                              "\nNumber of generations: " + geneticAlgorithm.GenerationsNumber +
                              "\n\nFitness: " + finalFitness +
                              "\n\n" + finalVariableValues +
                              "\n\nRange: " + parameters.LowerBound + ", " + parameters.UpperBound +
                              "\n\nf(" + String.Join(", ", parameters.Variables) + ") = " + parameters.Expression +
                              " = " + (-finalFitness));

            Console.ReadKey();
        }
Example #25
0
 public override void Reset()
 {
     m_positions      = new List <KeyValuePair <double, double[]> >();
     m_bestChromosome = null;
 }
Example #26
0
        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();
        }
Example #27
0
        public void Start()
        {
            var w   = new StreamWriter("C:\\Users\\Taylor\\source\\repos\\ComboProject\\ComboProject\\bin\\Debug\\genelog.csv");
            int gen = 1;

            // init chromosomes
            var chromosome = new FloatingPointChromosome(
                new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
                new double[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
                new int[] { 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20 },
                new int[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 });

            // gen population
            var population = new Population(50, 100, chromosome);

            // fitness function
            var fitness = new FuncFitness((c) =>
            {
                var fc = c as FloatingPointChromosome;

                var genes = fc.ToFloatingPoints();

                string combo = combogen.generateGeneticCombo(genes, 0);

                int damage = ComboSimulator.getComboDamage(combo, movelist);

                w.WriteLine(string.Format("{0},{1},{2},,{3},{4},{5},{6},{7},{8},{9},{10},{11},{12}",
                                          gen.ToString(),
                                          combo,
                                          damage.ToString(),
                                          genes[0],
                                          genes[1],
                                          genes[2],
                                          genes[3],
                                          genes[4],
                                          genes[5],
                                          genes[6],
                                          genes[7],
                                          genes[8],
                                          genes[9]));
                w.Flush();

                return(damage);
            });

            var selection = new EliteSelection();

            var crossover = new UniformCrossover(0.5f);

            var mutation = new ReverseSequenceMutation();

            var termination = new FitnessStagnationTermination(5000);

            var ga = new GeneticAlgorithm(
                population,
                fitness,
                selection,
                crossover,
                mutation);

            ga.Termination         = termination;
            ga.MutationProbability = 0.7f;

            Console.WriteLine("Generation: combo = damage");

            var latestFitness = 0.0;

            ga.GenerationRan += (sender, e) =>
            {
                var bestChromosome = ga.BestChromosome as FloatingPointChromosome;
                var bestFitness    = bestChromosome.Fitness.Value;

                if (bestFitness != latestFitness)
                {
                    latestFitness = bestFitness;
                    string combo = combogen.generateGeneticCombo(bestChromosome.ToFloatingPoints(), 0);

                    Console.WriteLine("Generation {0,2}: {1} = {2}",
                                      ga.GenerationsNumber,
                                      combo,
                                      bestFitness
                                      );
                }

                gen++;
            };

            ga.Start();

            Console.ReadKey();
        }
Example #28
0
        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
        }
Example #29
0
        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();
            });
        }
Example #30
0
 private static void SaveChromosome(FloatingPointChromosome chromosome, string chromosomeLabel, string path)
 {
     string[] genes = chromosome.ToFloatingPoints().Select((gene) => gene.ToString()).ToArray();
     System.IO.File.WriteAllLines(path + @chromosomeLabel, genes);
 }