示例#1
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);
        }
示例#2
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]);
        }
示例#3
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]);
        }
示例#4
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]
                }
            });
        }
示例#5
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
                                );
                        }
                    }
                }
            };
        }
示例#6
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);
 }
示例#7
0
        public static wynikGA GeneticExt
            (int counter,
            Item[] dane,
            double back_volume,
            int populationSize     = 500,
            ICrossover crossover   = null,
            double crossoverChance = 0.20f,
            double mutationChance  = 0.05f,
            int tournamentSize     = 50)
        {
            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;
            }

            ISelection selection = new TournamentSelection(tournamentSize > populationSize ? populationSize : tournamentSize, true);

            if (crossover == null)
            {
                crossover = new TwoPointCrossover();
            }
            IMutation mutation   = new FlipBitMutation();
            var       chromosome = new FloatingPointChromosome(minValue, maxValue, totalBits, fractionDigits);
            // var fitobj = new MyProblemFitness(dane, chromosome, back_volume);
            //var fitness = fitobj.Evaluate;
            IPopulation population = new Population(populationSize, populationSize, chromosome);

            IFitness fitness = new FuncFitness((c) =>
            {
                FloatingPointChromosome 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));
            });



            GeneticAlgorithm 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);
        }