public void TransportMutationTest1()
        {
            int populationSize = 2000;

            file = root + "\\bays29.xml";
            XDocument             tspFile    = XDocument.Load(file);
            AdjacencyMatrix       testMatrix = new AdjacencyMatrix(tspFile);
            PMXCrossover          crossover  = new PMXCrossover((float)(0.80));
            TournamentSelection   selector   = new TournamentSelection((int)populationSize / 2);
            TranspositionMutation mutation   = new TranspositionMutation((float)1);

            GeneticSolver solver = new GeneticSolver(testMatrix, mutation, crossover, selector, populationSize, 10);

            List <Candidate> listCand = solver.randomPopulation();

            Candidate parentX = listCand[0];
            Candidate parentY = listCand[1];

            parentX.chromoson = new List <int>()
            {
                1, 2, 3, 4, 5, 6, 7, 8, 9
            };
            parentY.chromoson = new List <int>()
            {
                5, 3, 6, 7, 8, 1, 2, 9, 4,
            };


            mutation.Mutate(parentX);
        }
Esempio n. 2
0
        static void Main(string[] args)
        {
            var selection   = new TournamentSelection();
            var crossover   = new OrderBasedCrossover();
            var mutation    = new ReverseSequenceMutation();
            var fitness     = new SortFitness();
            var chromosomes = new SortChromosomes();
            var population  = new Population(40, 40, chromosomes);

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

            ga.Termination = new GenerationNumberTermination(100);

            Console.WriteLine("GA running...");

            ga.Start();

            Console.WriteLine("GA done in {0} generations.", ga.GenerationsNumber);

            var bestChromosome = ga.BestChromosome as SortChromosomes;

            Console.WriteLine("Best solution found");

            DisplayChromosome(bestChromosome);
            Console.ReadKey();
        }
Esempio n. 3
0
        private List <String> GreedyKnapsack(int?seed, bool penalized, EffectType type)
        {
            List <String> results     = new List <String>();
            var           evaluations = GenerateProblems();

            foreach (var evaluation in evaluations)
            {
                ((CBinaryKnapsackEvaluation)evaluation).bSetPenalized(penalized);
                IterationsStopCondition stopCondition = new IterationsStopCondition(evaluation.dMaxValue, 100);

                BinaryRandomGenerator generator = new BinaryRandomGenerator(evaluation.pcConstraint, seed);
                OnePointCrossover     crossover = new OnePointCrossover(0.5, seed);
                BinaryBitFlipMutation mutation  = new BinaryBitFlipMutation(1.0 / evaluation.iSize, evaluation, seed);
                TournamentSelection   selection = new TournamentSelection(2, seed);

                KnapsackGA ga = new KnapsackGA(((CBinaryKnapsackEvaluation)evaluation), stopCondition, generator, selection, crossover, mutation, 50, type, seed);

                ga.Run();

                results.Add(FormatSave(ga));

                ReportOptimizationResult(ga.Result, debug: true);
            }
            return(results);
        }
        public Tuple <List <String>, List <String> > Lab6FindStallingParameter(IEvaluation <bool>[] problems, int[] seeds)
        {
            List <String> stuckResults = new List <String>();
            List <String> results      = new List <String>();

            double[] pMuts    = new double[] { 0.01, 0.001, 0.0001, 0.00000001 };
            int[]    popSizes = new int[] { 100, 50, 20, 4 };

            int iter = 1;
            int maxI = pMuts.Length * popSizes.Length;

            foreach (var pMut in pMuts)
            {
                foreach (var popSize in popSizes)
                {
                    Dictionary <String, int> problemStallCounter = new Dictionary <String, int>();
                    foreach (var seed in seeds)
                    {
                        TournamentSelection selection = new TournamentSelection(4, seed);
                        OnePointCrossover   crossover = new OnePointCrossover(.5);
                        foreach (var problem in problems)
                        {
                            results.Add(Lab6BinaryGA(problem, selection, crossover, pMut, popSize, problemStallCounter, seed));
                        }
                    }
                    Console.WriteLine("\nParameters - mutation probability: " + pMut.ToString() + ", population size: " +
                                      popSize.ToString() + " /// " + DateTime.Now.ToString("HH:mm:ss.fff") + " | " + iter.ToString() + "/" + maxI.ToString());

                    stuckResults.Add(pMut.ToString() + ", " + popSize.ToString() + ", " + String.Join(", ", problemStallCounter.Select(x => x.Value).ToArray()));
                    problemStallCounter.Select(i => $"{i.Key}: {i.Value}").ToList().ForEach(Console.WriteLine);
                    iter++;
                }
            }
            return(new Tuple <List <String>, List <String> >(results, stuckResults));
        }
        public ISelection Tournament()
        {
            var target = new TournamentSelection();

            target.SelectChromosomes(_chromosomesNumber, _generation);
            return(target);
        }
Esempio n. 6
0
        public void Selection_TournamentSizeSameAsPopulation_TwoBestFittedChromosomes()
        {
            var population  = new List <IChromosome <decimal> >();
            var chromosome1 = new Chromosome <decimal>(new IGene <decimal>[] { new Gene <decimal>(new [] { 1.2m, 1.3m }, 0.1m),
                                                                               new Gene <decimal>(new [] { 1.3m, 1.5m }, 0.1m) });

            chromosome1.FintnessValue = 90;
            var chromosome2 = new Chromosome <decimal>(new IGene <decimal>[] { new Gene <decimal>(new [] { 2.2m, 2.3m }, 0.1m),
                                                                               new Gene <decimal>(new [] { 2.3m, 2.5m }, 0.1m) });

            chromosome2.FintnessValue = 80;
            var chromosome3 = new Chromosome <decimal>(new IGene <decimal>[] { new Gene <decimal>(new [] { 3.2m, 3.3m }, 0.1m),
                                                                               new Gene <decimal>(new [] { 3.3m, 3.5m }, 0.1m) });

            chromosome3.FintnessValue = 70;

            population.Add(chromosome1);
            population.Add(chromosome2);
            population.Add(chromosome3);
            var selector = new TournamentSelection(3);

            var result = selector.Selection(population);

            Assert.IsTrue(result.Item1.FintnessValue == 90 || result.Item2.FintnessValue == 90);
        }
Esempio n. 7
0
        public void OXTest1()
        {
            int populationSize = 120;

            file = root + "\\bays29.xml";
            XDocument           tspFile    = XDocument.Load(file);
            AdjacencyMatrix     testMatrix = new AdjacencyMatrix(tspFile);
            OXCrossover         crossover  = new OXCrossover((float)(1));
            TournamentSelection selector   = new TournamentSelection(5);
            InversionMutation   inv        = new InversionMutation((float)0.05);

            GeneticSolver    solver   = new GeneticSolver(testMatrix, inv, crossover, selector, populationSize, 10);
            List <Candidate> listCand = solver.randomPopulation();
            Candidate        parentX  = listCand[0];
            Candidate        parentY  = listCand[1];

            parentX.chromoson = new List <int>()
            {
                1, 2, 3, 4, 5, 6, 7, 8, 9
            };
            parentY.chromoson = new List <int>()
            {
                5, 3, 6, 7, 8, 1, 2, 9, 4,
            };



            crossover.Crossover(parentX, parentY);
        }
Esempio n. 8
0
        private void button1_Click(object sender, EventArgs e)
        {
            Gen.length = Convert.ToInt32(RangGen.Value);
            double[] Xmin = new double[Convert.ToInt32(NGen.Value)];
            double[] Xmax = new double[Convert.ToInt32(NGen.Value)];
            for (int i = 0; i < Convert.ToInt32(NGen.Value); i++)
            {
                Xmin[i] = Convert.ToDouble(xmin.Text);
                Xmax[i] = Convert.ToDouble(xmax.Text);
            }
            Generator generator = new Generator(Xmin, Xmax, Convert.ToInt32(Individ.Value), Convert.ToInt32(NGen.Value)); //генерируем исходные данные

            individuals = generator.generation();                                                                         //сгенерировали особей
            List <double> temp = new List <double>();

            for (int i = 0; i < Convert.ToInt32(generation.Value); i++)
            {
                temp.Add(individuals.Min(f => f.fitness));
                Selection selection = new TournamentSelection(Convert.ToInt32(sizeTurnir.Value), 1); //турнирный отбор в селекции
                individuals = selection.selectionRun(individuals);                                   //оценили приспособленность и отобрали для скрещивания (кроссовера)
                Crossovers Crosover = new IntOnePointCrossover(1, Convert.ToDouble(Pc.Value));
                individuals = Crosover.crossoverRun(individuals);                                    //Запуск кроссовера(скрещиваниe)
                individuals.Sort();
            }
        }
Esempio n. 9
0
        private static void Lab73(int?seed = null)
        {
            string                   filename      = "lab73_order3.txt";
            IEvaluation <bool>       evaluation    = new CBinaryStandardDeceptiveConcatenationEvaluation(3, 100);
            RunningTimeStopCondition stopCondition = new RunningTimeStopCondition(evaluation.dMaxValue, 30);
            BinaryRandomGenerator    generator     = new BinaryRandomGenerator(evaluation.pcConstraint, seed);
            OnePointCrossover        crossover     = new OnePointCrossover(0.5, seed);
            BinaryBitFlipMutation    mutation      = new BinaryBitFlipMutation(1.0 / evaluation.iSize, evaluation, seed);
            TournamentSelection      selection     = new TournamentSelection(2, seed);
            GAwithDSM                ga            = new GAwithDSM(evaluation, stopCondition, generator, selection, crossover, mutation, 50);

            ga.Run();

            SaveDSMs(ga.dsms, filename);

            filename      = "lab73_order10.txt";
            evaluation    = new CBinaryBimodalDeceptiveConcatenationEvaluation(10, 100);
            stopCondition = new RunningTimeStopCondition(evaluation.dMaxValue, 30);
            generator     = new BinaryRandomGenerator(evaluation.pcConstraint, seed);
            crossover     = new OnePointCrossover(0.5, seed);
            mutation      = new BinaryBitFlipMutation(1.0 / evaluation.iSize, evaluation, seed);
            selection     = new TournamentSelection(2, seed);
            ga            = new GAwithDSM(evaluation, stopCondition, generator, selection, crossover, mutation, 50);
            ga.Run();

            SaveDSMs(ga.dsms, filename);
        }
Esempio n. 10
0
        public void PMXTest2()
        {
            int populationSize = 120;

            file = root + "\\bays29.xml";
            XDocument           tspFile    = XDocument.Load(file);
            AdjacencyMatrix     testMatrix = new AdjacencyMatrix(tspFile);
            PMXCrossover        crossover  = new PMXCrossover((float)(0.80));
            TournamentSelection selector   = new TournamentSelection(5);
            InversionMutation   inv        = new InversionMutation((float)0.05);

            GeneticSolver    solver   = new GeneticSolver(testMatrix, inv, crossover, selector, populationSize, 10);
            List <Candidate> listCand = new List <Candidate>();
            List <int>       GenX     = new List <int>()
            {
                5, 20, 28, 18, 14, 2, 27, 25, 8, 4, 19, 13, 12, 17, 11, 15, 16, 9, 3, 10, 22, 21, 1, 7, 24, 6, 23, 26
            };
            List <int> GenY = new List <int>()
            {
                28, 19, 11, 27, 3, 18, 17, 14, 10, 23, 8, 12, 6, 2, 22, 7, 25, 20, 4, 1, 26, 9, 5, 15, 24, 21, 16, 13
            };
            Candidate parentX = new Candidate(1, GenX, solver, solver.time.ElapsedMilliseconds.ToString());
            Candidate parentY = new Candidate(1, GenY, solver, solver.time.ElapsedMilliseconds.ToString());

            listCand.Add(parentX);
            listCand.Add(parentY);
            crossover.CrossoverPopulation(listCand, 10);
        }
Esempio n. 11
0
        public static void createNewSolver(int mutationIndex, int crossoverIndex, int selectorIndex, int populationSize, float mutationChance, int timeMS, int selectorSize, float crossoverChance)
        {
            MutationType    mutation  = null;
            CrossoverType   crossover = null;
            SelectionType   selection = null;
            AdjacencyMatrix matrix    = new AdjacencyMatrix(tspXmlFile);

            switch (mutationIndex)
            {
            case 0:
            {
                mutation = new InversionMutation(mutationChance);
                break;
            }

            case 1:
            {
                mutation = new TranspositionMutation(mutationChance);
                break;
            }
            }

            switch (crossoverIndex)
            {
            case 0:
            {
                crossover = new PMXCrossover(crossoverChance);
                break;
            }

            case 1:
            {
                crossover = new OXCrossover(crossoverChance);
                break;
            }
            }

            switch (selectorIndex)
            {
            case 0:
            {
                selection = new TournamentSelection(selectorSize);
                break;
            }

            case 1:
            {
                selection = new RouletteSelection(selectorSize);
                break;
            }
            }
            GeneticSolver solver = null;//add parameters TO DO

            if (mutation != null && selection != null && crossover != null)
            {
                addNewSolver(new GeneticSolver(matrix, mutation, crossover, selection, populationSize, timeMS));
            }
        }
Esempio n. 12
0
        public void ItCanChooseParentsForTournamentFive()
        {
            tournament = new TournamentFiveSelection();
            tournament.Setup(GetStepChromosomes(), _config);

            var parents = tournament.GetParents();

            Assert.IsNotNull(parents);
        }
Esempio n. 13
0
        public void SelectChromosomes_NullGeneration_Exception()
        {
            var target = new TournamentSelection();

            ExceptionAssert.IsThrowing(new ArgumentNullException("generation"), () =>
            {
                target.SelectChromosomes(2, null);
            });
        }
Esempio n. 14
0
        public void SelectChromosomes_TournamentSize3AllowWinnerCompeteNextTournamentFalse_ChromosomesSelected()
        {
            var target = new TournamentSelection(3, false);

            var c0 = MockRepository.GeneratePartialMock <ChromosomeBase>(2);

            c0.Fitness = 0.1;

            var c1 = MockRepository.GeneratePartialMock <ChromosomeBase>(2);

            c1.Fitness = 0.5;

            var c2 = MockRepository.GeneratePartialMock <ChromosomeBase>(2);

            c2.Fitness = 0;

            var c3 = MockRepository.GeneratePartialMock <ChromosomeBase>(2);

            c3.Fitness = 0.7;

            var c4 = MockRepository.GeneratePartialMock <ChromosomeBase>(2);

            c4.Fitness = 0.3;

            var c5 = MockRepository.GeneratePartialMock <ChromosomeBase>(2);

            c5.Fitness = 0.2;

            var generation = new Generation(1, new List <IChromosome>()
            {
                c0, c1, c2, c3, c4, c5
            });

            var mock = new MockRepository();
            var rnd  = mock.StrictMock <IRandomization>();

            using (mock.Ordered())
            {
                rnd.Expect(r => r.GetUniqueInts(3, 0, 6)).Return(new int[] { 0, 1, 2 });
                rnd.Expect(r => r.GetUniqueInts(3, 0, 5)).Return(new int[] { 2, 3, 4 });
                rnd.Expect(r => r.GetUniqueInts(3, 0, 4)).Return(new int[] { 0, 1, 2 });
                rnd.Expect(r => r.GetUniqueInts(3, 0, 3)).Return(new int[] { 0, 1, 2 });
            }

            RandomizationProvider.Current = rnd;
            mock.ReplayAll();


            var actual = target.SelectChromosomes(4, generation);

            Assert.AreEqual(4, actual.Count);
            Assert.AreEqual(c1, actual[0]);
            Assert.AreEqual(c3, actual[1]);
            Assert.AreEqual(c4, actual[2]);
            Assert.AreEqual(c5, actual[3]);
        }
Esempio n. 15
0
        public void SelectChromosomes_NullGeneration_Exception()
        {
            var target = new TournamentSelection();
            var actual = Assert.Catch <ArgumentNullException>(() =>
            {
                target.SelectChromosomes(2, null);
            });

            Assert.AreEqual("generation", actual.ParamName);
        }
Esempio n. 16
0
        private static IMigrationStrategy CreateMigrationStrategy(IslandEngine engine, IRandom random, IFitnessComparer fitnessComparer, ParameterSet parameters, PeaSettings settings)
        {
            //TODO: MigrationFactory!
            var selection   = new TournamentSelection(random, fitnessComparer, parameters);
            var replacement = new ReplaceWorstEntitiesOfPopulation(random, fitnessComparer, parameters);
            var strategy    = new Migration.Implementation.MigrationStrategy(random, selection, replacement, engine.Parameters);

            strategy.Parameters.SetValue(Migration.ParameterNames.MigrationReceptionRate, 0.01);
            return(strategy);
        }
Esempio n. 17
0
 public override void InitPopulation()
 {
     //You should implement the code to initialize the population here
     population = new List <Individual> ();
     // jncor
     selection = new TournamentSelection();
     while (population.Count < populationSize)
     {
         GeneticIndividual new_ind = new GeneticIndividual(topology, crossoverPoints);
         new_ind.Initialize();
         population.Add(new_ind);
     }
 }
Esempio n. 18
0
        public void SelectChromosomes_TournamentSize3AllowWinnerCompeteNextTournamentTrue_ChromosomesSelected()
        {
            var target = new TournamentSelection(3, true);

            var c0 = Substitute.ForPartsOf <ChromosomeBase>(2);

            c0.Fitness = 0.1;

            var c1 = Substitute.ForPartsOf <ChromosomeBase>(2);

            c1.Fitness = 0.5;

            var c2 = Substitute.ForPartsOf <ChromosomeBase>(2);

            c2.Fitness = 0;

            var c3 = Substitute.ForPartsOf <ChromosomeBase>(2);

            c3.Fitness = 0.7;

            var c4 = Substitute.ForPartsOf <ChromosomeBase>(2);

            c4.Fitness = 0.3;

            var c5 = Substitute.ForPartsOf <ChromosomeBase>(2);

            c5.Fitness = 0.2;

            var generation = new Generation(1, new List <IChromosome>()
            {
                c0, c1, c2, c3, c4, c5
            });

            var rnd = Substitute.For <IRandomization>();

            rnd.GetUniqueInts(3, 0, 6).Returns(
                new int[] { 0, 1, 2 },
                new int[] { 3, 4, 5 },
                new int[] { 0, 2, 4 },
                new int[] { 1, 3, 5 });

            RandomizationProvider.Current = rnd;

            var actual = target.SelectChromosomes(4, generation);

            Assert.AreEqual(4, actual.Count);
            Assert.AreEqual(c1, actual[0]);
            Assert.AreEqual(c3, actual[1]);
            Assert.AreEqual(c4, actual[2]);
            Assert.AreEqual(c3, actual[3]);
        }
Esempio n. 19
0
        public IPredictionResult Predict <TDistribution>(IHiddenMarkovModel <TDistribution> model, IPredictionRequest request) where TDistribution : IDistribution
        {
            var selectionMethod    = new TournamentSelection(TournamentSize);
            var crossoverAlgorithm = new Crossover(CrossoverProbability);
            var mutationAlgorithm  = new Mutator(MutationProbability);
            var evaluator          = new HmmEvaluator <TDistribution>(model, new ForwardBackward(true));

            var parameters = new GeneticSolverParameters
            {
                CrossOverProbability = CrossoverProbability,
                MutationProbability  = MutationProbability,
                NumberOfGenerations  = NumberOfGenerations,
                PopulationSize       = request.NumberOfDays * 10,
                TournamentSize       = TournamentSize
            };
            var predictions = new PredictionResult {
                Predicted = new double[request.NumberOfDays][]
            };

            var solver = new GeneticSolver(parameters, mutationAlgorithm, crossoverAlgorithm, evaluator, selectionMethod);
            var populationInitializer = new FromTimeSeriesRandomInitializer(request.TrainingSet);
            var population            = populationInitializer.Initialize <decimal>(parameters.PopulationSize, request.NumberOfDays, MutationProbability);

            for (int i = 0; i < population.Count; i++)
            {
                var chromosome = population[i];
                population[i].FintnessValue = evaluator.Evaluate(chromosome);
            }

            var result = solver.Solve(population);
            // Get best fitted chromosome
            var maximumFitness = result[0].FintnessValue;
            var solution       = result[0];

            foreach (var chromosome in result)
            {
                if (maximumFitness <= chromosome.FintnessValue)
                {
                    solution       = chromosome;
                    maximumFitness = chromosome.FintnessValue;
                }
            }
            // Convert it to array
            for (int i = 0; i < solution.Representation.Length; i++)
            {
                predictions.Predicted[i] = Array.ConvertAll(solution.Representation[i].Representation, x => (double)Convert.ChangeType(x, typeof(double)));
            }

            return(predictions);
        }
        public void TournamentTest1()
        {
            int populationSize = 120;

            file = root + "\\bays29.xml";
            XDocument           tspFile    = XDocument.Load(file);
            AdjacencyMatrix     testMatrix = new AdjacencyMatrix(tspFile);
            PMXCrossover        crossover  = new PMXCrossover((float)(0.80));
            TournamentSelection selector   = new TournamentSelection(10);
            InversionMutation   inv        = new InversionMutation((float)0.05);

            GeneticSolver solver = new GeneticSolver(testMatrix, inv, crossover, selector, populationSize, 10);
            //  listCand = selector.generateBreedingPool(listCand);
        }
Esempio n. 21
0
    public override void InitPopulation()
    {
        maxNumberOfEvaluations = Mathf.Min(maxNumberOfEvaluations, populationSize);
        populationRed          = new List <Individual>();
        populationBlue         = new List <Individual>();

        while (populationRed.Count < populationSize)
        {
            GeneticIndividual new_ind_red = new GeneticIndividual(NNTopology, maxNumberOfEvaluations, mutationMethod)
            {
                Mean  = Mean,
                Stdev = Stdev
            };
            GeneticIndividual new_ind_blue = new GeneticIndividual(NNTopology, maxNumberOfEvaluations, mutationMethod)
            {
                Mean  = Mean,
                Stdev = Stdev
            };

            if (seedPopulationFromFile)
            {
                NeuralNetwork nnRed  = getRedIndividualFromFile();
                NeuralNetwork nnBlue = getBlueIndividualFromFile();
                new_ind_red.Initialize(nnRed);
                new_ind_blue.Initialize(nnBlue);
                //only the first individual is an exact copy. the other are going to suffer mutations
                if (populationRed.Count != 0 && populationBlue.Count != 0)
                {
                    new_ind_red.Mutate(mutationProbabilityRedPopulation);
                    new_ind_blue.Mutate(mutationProbabilityBluePopulation);
                }
            }
            else
            {
                new_ind_red.Initialize();
                new_ind_blue.Initialize();
            }

            populationRed.Add(new_ind_red);
            populationBlue.Add(new_ind_blue);
        }

        switch (selectionMethod)
        {
        case SelectionType.Tournament:
            selection = new TournamentSelection(tournamentSize);
            break;
        }
    }
Esempio n. 22
0
        private String Lab4BinaryGaMutationCrossover(IEvaluation <bool> evaluation, double pMut, double pCro, int?seed)
        {
            IterationsStopCondition stopCondition = new IterationsStopCondition(evaluation.dMaxValue, 500);

            BinaryRandomGenerator generator = new BinaryRandomGenerator(evaluation.pcConstraint, seed);
            BinaryBitFlipMutation mutation  = new BinaryBitFlipMutation(pMut, evaluation, seed);

            OnePointCrossover   crossover = new OnePointCrossover(pCro, seed);
            TournamentSelection selection = new TournamentSelection(5, seed);

            GeneticAlgorithm <bool> ga = new GeneticAlgorithm <bool>(evaluation, stopCondition, generator, selection, crossover, mutation, 50);

            ga.Run();

            return(FormatSave(ga));
        }
Esempio n. 23
0
        private static void Lab5(int?seed)
        {
            CBinaryKnapsackEvaluation evaluation    = new CBinaryKnapsackEvaluation(EBinaryKnapsackInstance.knapPI_1_100_1000_1);
            IterationsStopCondition   stopCondition = new IterationsStopCondition(evaluation.dMaxValue, 100);

            BinaryRandomGenerator generator = new BinaryRandomGenerator(evaluation.pcConstraint, seed);
            OnePointCrossover     crossover = new OnePointCrossover(0.5, seed);
            BinaryBitFlipMutation mutation  = new BinaryBitFlipMutation(1.0 / evaluation.iSize, evaluation, seed);
            TournamentSelection   selection = new TournamentSelection(2, seed);

            GeneticAlgorithm <bool> ga = new GeneticAlgorithm <bool>(evaluation, stopCondition, generator, selection, crossover, mutation, 50);

            ga.Run();

            ReportOptimizationResult(ga.Result);
        }
Esempio n. 24
0
        public static AbstractSelection ChosenSelectionMethod(SelectionMethod selectionMethod, int countTour, int countSelect)
        {
            AbstractSelection selection = null;

            switch (selectionMethod)
            {
            case SelectionMethod.Tournament:
                selection = new TournamentSelection(countSelect, countTour);
                break;

            case SelectionMethod.Proportion:
                selection = new ProportionSelection(countSelect);
                break;
            }
            return(selection);
        }
        private GeneticSolver getSolver()
        {
            int populationSize = 3000;

            file = root + "\\rbg403.xml";
            XDocument           tspFile    = XDocument.Load(file);
            AdjacencyMatrix     testMatrix = new AdjacencyMatrix(tspFile);
            PMXCrossover        crossover  = new PMXCrossover((float)(0.80));
            TournamentSelection selector   = new TournamentSelection((int)(5));
            InversionMutation   inv        = new InversionMutation((float)0.05);

            GeneticSolver solver = new GeneticSolver(
                testMatrix, inv, crossover, selector, populationSize, 60);

            return(solver);
        }
Esempio n. 26
0
        /// <summary>
        ///     Construct an EA.
        /// </summary>
        /// <param name="thePopulation">The population.</param>
        /// <param name="theScoreFunction">The score function.</param>
        public BasicEA(IPopulation thePopulation,
                       ICalculateScore theScoreFunction)
        {
            RandomNumberFactory = EncogFramework.Instance.RandomFactory.FactorFactory();
            EliteRate           = 0.3;
            MaxTries            = 5;
            MaxOperationErrors  = 500;
            CODEC = new GenomeAsPhenomeCODEC();


            Population    = thePopulation;
            ScoreFunction = theScoreFunction;
            Selection     = new TournamentSelection(this, 4);
            Rules         = new BasicRuleHolder();

            // set the score compare method
            if (theScoreFunction.ShouldMinimize)
            {
                SelectionComparer = new MinimizeAdjustedScoreComp();
                BestComparer      = new MinimizeScoreComp();
            }
            else
            {
                SelectionComparer = new MaximizeAdjustedScoreComp();
                BestComparer      = new MaximizeScoreComp();
            }

            // set the iteration
            foreach (ISpecies species in thePopulation.Species)
            {
                foreach (IGenome genome in species.Members)
                {
                    IterationNumber = Math.Max(IterationNumber,
                                               genome.BirthGeneration);
                }
            }


            // Set a best genome, just so it is not null.
            // We won't know the true best genome until the first iteration.
            if (Population.Species.Count > 0 && Population.Species[0].Members.Count > 0)
            {
                BestGenome = Population.Species[0].Members[0];
            }
        }
Esempio n. 27
0
        private static void TestCrossoverVsMutation()
        {
            List <double> b          = new List <double>();
            List <double> w          = new List <double>();
            List <double> a          = new List <double>();
            var           evaluation = new TspEvaluation(@"C:\Users\jbelter\source\repos\machine-learning-cvrp\data\A-n46-k7.vrp");

            double[] px = { 0, .1, .8, 1, 0, 0, 0 };
            double[] pw = { 0, 0, 0, 0, .2, .5, 1 };
            for (int j = 0; j < 7; j++)
            {
                for (int i = 0; i < 20; i++)
                {
                    var stopCondition = new IterationsStopCondition(200);
                    //var optimizer = new TspRandomSearch(evaluation, stopCondition);
                    var        generator = new TspGenerator(new Random());
                    ASelection selection = new TournamentSelection(Convert.ToInt32(5));

                    var crossover = new OrderedCrossover(px[j]);
                    var mutation  = new SwapMutation(pw[j]);
                    var optimizer = new GeneticAlgorithm <int>(evaluation, stopCondition, generator, selection, crossover, mutation, 100);

                    optimizer.Run();

                    b.Add(optimizer.bestSolutions.Last());
                    w.Add(optimizer.worstValues.Last());
                    a.Add(optimizer.averageValues.Last());
                }
                double avgB = 0.0, avgA = 0.0, avgW = 0.0;
                for (int i = 0; i < b.Count; i++)
                {
                    avgB += b[i];
                    avgA += a[i];
                    avgW += w[i];
                }

                avgB /= b.Count;
                avgA /= b.Count;
                avgW /= b.Count;

                Console.WriteLine("avg(best value): " + avgB.ToString() +
                                  " avg(average value): " + avgA.ToString() +
                                  " avg(worst value): " + avgW.ToString());
            }
        }
Esempio n. 28
0
        public void Selection_TournamentSize5AndPopulationSize10_BestFittedChromosomes()
        {
            var population = new List <IChromosome <decimal> >();

            for (int i = 0; i < 10; i++)
            {
                var chromosome = new Chromosome <decimal>(new IGene <decimal>[] { new Gene <decimal>(new [] { i + .2m, i + .3m }, 0.1m),
                                                                                  new Gene <decimal>(new [] { i + .3m, i + .5m }, 0.1m) });
                chromosome.FintnessValue = 5 * i;
                population.Add(chromosome);
            }

            var selector = new TournamentSelection(5);

            var selected = selector.Selection(population);

            Assert.IsTrue(selected.Item1.FintnessValue > 30 || selected.Item2.FintnessValue > 30);
        }
        public void solverTest()
        {
            int populationSize = 3000;

            file = root + "\\rbg403.xml";
            XDocument           tspFile    = XDocument.Load(file);
            AdjacencyMatrix     testMatrix = new AdjacencyMatrix(tspFile);
            PMXCrossover        crossover  = new PMXCrossover((float)(0.80));
            TournamentSelection selector   = new TournamentSelection((int)(5));
            InversionMutation   inv        = new InversionMutation((float)0.05);

            GeneticSolver solver = new GeneticSolver(
                testMatrix, inv, crossover, selector, populationSize, 480);
            var result = solver.Solve();

            result.resultToXML();
            result.ToFile();
        }
Esempio n. 30
0
        public void SelectChromosomes_InvalidNumber_Exception()
        {
            var target = new TournamentSelection();

            ExceptionAssert.IsThrowing(new ArgumentOutOfRangeException("number", "The number of selected chromosomes should be at least 2."), () =>
            {
                target.SelectChromosomes(-1, null);
            });

            ExceptionAssert.IsThrowing(new ArgumentOutOfRangeException("number", "The number of selected chromosomes should be at least 2."), () =>
            {
                target.SelectChromosomes(0, null);
            });

            ExceptionAssert.IsThrowing(new ArgumentOutOfRangeException("number", "The number of selected chromosomes should be at least 2."), () =>
            {
                target.SelectChromosomes(1, null);
            });
        }
Esempio n. 31
0
        static void Main(string[] args)
        {
            var teams = GetTeams();
            var generator = new FixtureGenerator(teams, 2);

            var seasons = new List<Season>();
            for (int i = 0; i < NumberOfSeasons; i++)
            {
                seasons.Add(generator.GenerateFixtures());
            }

            var criteria = GetCriteria();
            var selectionStrategy = new TournamentSelection<Season, MatchDay>(0.8, criteria);
            var seasonsCrossedOver = new List<Season>(seasons);
            for (int i = 0; i < NumberOfGenerations; i++)
            {
                var simpleCrossover = new SimpleCrossoverStrategy<Season, MatchDay>();
                var populationGenerator = new PopulationGenerator<Season, MatchDay>(seasonsCrossedOver, NumberOfChildrenPerGeneration, simpleCrossover, selectionStrategy);
                seasonsCrossedOver = populationGenerator.Generate();
                string statistics = populationGenerator.GetStatistics(criteria);
                Console.WriteLine("Statistics for generation " + (i + 1));
                Console.WriteLine(statistics);
            }

            var bestSeason = seasonsCrossedOver.OrderByDescending(season => new CriteriaCalculator<Season, MatchDay>(season, criteria).Calculate().Score).FirstOrDefault();

            DisplayFixtures(bestSeason);

            var calculator = new CriteriaCalculator<Season, MatchDay>(bestSeason, criteria);
            var result = calculator.Calculate();
            DisplayResults(result);

            Console.ReadLine();
        }