Exemplo n.º 1
0
    private List <string> MutateIndividuals(List <string> ind)
    {
        List <string> newInd = new List <string>();

        foreach (string individual in ind)
        {
            newInd.Add(mutator.Mutate(individual));
        }
        return(newInd);
    }
Exemplo n.º 2
0
        //Chromosome (string): Solution
        //Gene (bits): Part of solution
        //Locus: Poisition of gene
        //Alleles: Value of gene
        //Phenotype: Decoded solution
        //Genotype: Encoded solution

        public static List <T> Evolve <T>(List <T> pPopulation, int pEvolvedPopulationSize, IMatingPoolSelector pPoolSelector, IBreedingPairSelector pPairSelector, ICrossoverOperator pOperator, IMutator pMutator) where T : GeneticEntity
        {
            List <T> pooledPop  = new List <T>();
            List <T> pairedPop  = new List <T>();
            List <T> crossedPop = new List <T>();
            List <T> mutatedPop = new List <T>();

            int stepCount = 1;

            //Select Pool
            pooledPop = pPoolSelector.SelectPool(pPopulation, pEvolvedPopulationSize);
            OutputStep(pooledPop, stepCount, "pooling");
            stepCount++;

            //Select Pairs
            pairedPop = pPairSelector.SelectPairs(pooledPop);
            OutputStep(pairedPop, stepCount, "pairing");
            stepCount++;

            //Crossover
            crossedPop = pOperator.Crossover(pairedPop);
            OutputStep(crossedPop, stepCount, "crossing");
            stepCount++;

            //Mutate
            mutatedPop = pMutator.Mutate(crossedPop);
            OutputStep(pooledPop, stepCount, "mutating");
            stepCount++;

            return(mutatedPop);
        }
        internal IList <INeuralNetwork> GetMutatedNetworks(IEnumerable <INeuralNetwork> networksToTryToMutate, double mutateChance)
        {
            //try to mutate session that will live on 1 by 1
            var  mutatedTop = new List <INeuralNetwork>();
            bool didMutate;

            foreach (var topPerformer in networksToTryToMutate)
            {
                var net = _mutator.Mutate(topPerformer, mutateChance, out didMutate);
                if (didMutate)
                {
                    mutatedTop.Add(net);
                }
            }
            return(mutatedTop);
        }
Exemplo n.º 4
0
        private void MutateAndAddPoints(Person pers)
        {
            Person buf = new Person(pers.GetCode());

            mMutOperator.Mutate(pers);
            double dif = mMWrapper.FitnessFunction(buf) -
                         mMWrapper.FitnessFunction(pers);

            if (!buf.IsEqual(pers))
            {
                for (int iter = 0; iter < mCrossRoulette.Length; iter++)
                {
                    if (iter != mCurrentOperators[1])
                    {
                        mMutRoulette[iter] -= dif;
                        if (mMutRoulette[iter] < 0)
                        {
                            mMutRoulette[iter] = 0;
                        }
                    }

                    mMutRoulette[mCurrentOperators[1]] += dif;
                    if (mMutRoulette[mCurrentOperators[1]] < 0)
                    {
                        mMutRoulette[mCurrentOperators[1]] = 0;
                    }
                }
            }
        }
Exemplo n.º 5
0
        public GeneticData GeneticAlgorithm(
            ISelector selector,
            IMutator mutator,
            ICrosser crosser,
            IEndCondition endCondition,
            GeneticData startPopulation
            )
        {
            const int selectedCount = 4;

            GeneticData best = null;
            var         currentCombinations = new List <GeneticData> {
                startPopulation
            };

            while (!endCondition.IsEnd(currentCombinations, envData))
            {
                var selected = selector.SelectBests(currentCombinations, selectedCount, envData);
                var crossed  = crosser.Cross(selected, envData);
                currentCombinations = mutator.Mutate(crossed, envData);
                best = selector.SelectBests(currentCombinations.Concat(new[] { best }).ToList(), 1, envData).First();
            }

            return(best);
        }
Exemplo n.º 6
0
        public async Task <(MutantStatus, Mutant)> Run(ITestRunner testRunner, string tempDirectory, IEventListener eventListener)
        {
            var mutatedNode = mutator.Mutate(OriginalNode);

            MutatedSyntaxRoot = originalSyntaxRoot.ReplaceNode(OriginalNode, mutatedNode);

            var mutant = await Mutant.Create(OriginalClass, OriginalNode, MutatedSyntaxRoot);

            var compilationResult = await CompileContainingProject(tempDirectory);

            if (!compilationResult.Success)
            {
                // Not all mutations are valid in all circumstances, and therefore may not compile.
                // E.g. "a + b" => "a - b" works when a and b are integers but not when they're strings.
                eventListener.MutantSkipped(mutant, "mutation resulted in invalid code");
                return(MutantStatus.Skipped, mutant);
            }

            CopyMutatedAssemblyIntoTempTestAssemblyDirectories(compilationResult.OutputFilePath, tempDirectory, config);
            var copiedTempTestAssemblyFilePaths = TempTestAssemblyFilePaths(config, tempDirectory).ToArray();

            var ranAnyTests = false;

            for (var testAssemblyIndex = 0; testAssemblyIndex < config.TestAssemblyFilePaths.Length; ++testAssemblyIndex)
            {
                var originalTestAssemblyFilePath = config.TestAssemblyFilePaths[testAssemblyIndex];
                var tempTestAssemblyFilePath     = copiedTempTestAssemblyFilePaths[testAssemblyIndex];

                string[] testsToRun = null;
                if (coverageAnalysisResult != null)
                {
                    testsToRun = coverageAnalysisResult.TestsThatCoverMember(memberName, originalTestAssemblyFilePath);
                    if (!testsToRun.Any())
                    {
                        continue;
                    }
                }

                var result = testsToRun != null?
                             testRunner.RunTests(new[] { tempTestAssemblyFilePath }, testsToRun) :
                                 testRunner.RunAllTests(new[] { tempTestAssemblyFilePath });

                ranAnyTests = true;

                if (result.Status == TestRunStatus.SomeTestsFailed)
                {
                    eventListener.MutantKilled(mutant, result.Error);
                    return(MutantStatus.Dead, mutant);
                }
            }

            if (!ranAnyTests)
            {
                eventListener.MutantSkipped(mutant, "no covering tests");
                return(MutantStatus.Skipped, mutant);
            }

            eventListener.MutantSurvived(mutant);
            return(MutantStatus.Alive, mutant);
        }
Exemplo n.º 7
0
 public void Procreate(List <int> child, ISelector selector, Random random)
 {
     crossover.Crossover(child, selector.Select(random).Chromosome, selector.Select(random).Chromosome, random);
     //child.AddRange(selector.Select(random).Chromosome);
     if (mutationRate == 1.0 || random.NextDouble() < mutationRate)
     {
         mutator.Mutate(child, random);
     }
 }
Exemplo n.º 8
0
        private List <Individual> CreateOffspring(List <Individual> individuals)
        {
            var offspring     = new List <Individual>();
            var offspringSize = _config.PopulationSize * _config.OffspringRatio;

            while (offspring.Count < offspringSize)
            {
                var children = _crossOver.CreateChildren(_selector.Select(individuals), _selector.Select(individuals));

                _mutator.Mutate(children.Item1, _config.MutationProbability);
                _mutator.Mutate(children.Item2, _config.MutationProbability);
                _evaluator.Evaluate(children.Item1);
                _evaluator.Evaluate(children.Item2);
                offspring.Add(children.Item1);
                offspring.Add(children.Item2);
            }

            return(offspring);
        }
Exemplo n.º 9
0
    public List <NeuralNetwork> NextPopulation(List <NeuralNetwork> currentPopulation)
    {
        List <List <double> > genotypes = converter.ToGenotypes(selector.Select(currentPopulation));

        List <List <double> > afterCrossGenotypes = mixer.Cross(genotypes, currentPopulation.Count);

        mutator.Mutate(afterCrossGenotypes);

        return(converter.ToNetworks(afterCrossGenotypes, currentPopulation[0].Topology));
    }
Exemplo n.º 10
0
        public Species[] Step(Species[] species)
        {
            Steps++;

            UpdateBest(species);

            var survived   = _survivalSelection.Select(species).ToArray();
            var newSpecies = _breeder.Breed(survived).ToArray();

            _mutator.Mutate(newSpecies);
            return(newSpecies);
        }
        public IEnumerable <T> ProduceOffspring(IEnumerable <T> parents)
        {
            var nextGen = parents
                          .Select(genome => genome.Clone() as T)
                          .ToArray();

            foreach (var genome in nextGen)
            {
                _mutator.Mutate(genome);
            }

            return(nextGen);
        }
Exemplo n.º 12
0
        public string Mutate(string input, int lowerBound, int upperBound)
        {
            var result = input;

            for (var i = 0; i < _times; ++i)
            {
                if (_random.NextDouble() <= _chance)
                {
                    result = _mutator.Mutate(result, lowerBound, upperBound);
                }
            }

            return(result);
        }
Exemplo n.º 13
0
        //public override void SynthesizeModel(Point[] trainingPoints)
        //{
        //    var offspringPopulationSize = ExperimentParameters.OffspringPopulationSize;
        //    var numberOfGenerations = ExperimentParameters.NumberOfGenerations;

        //    BasePopulation = PopulationGenerator.GeneratePopulation(ExperimentParameters);

        //    for (var i = 0; i < offspringPopulationSize; i++)
        //        OffspringPopulation[i] = new Solution(ExperimentParameters);

        //    InitialPopulation = BasePopulation.DeepCopyByExpressionTree();

        //    for (var i = 0; i < numberOfGenerations; i++)
        //    {
        //        for (var j = 0; j < offspringPopulationSize; j++)
        //        {
        //            OffspringPopulation[j] = ParentsSelector.Select(BasePopulation)[0];

        //            OffspringPopulation[j] = StdDeviationsMutator.Mutate(OffspringPopulation[j]);
        //            OffspringPopulation[j] = RotationsMutator.Mutate(OffspringPopulation[j]);
        //            OffspringPopulation[j] = ObjectMutator.Mutate(OffspringPopulation[j]);

        //            OffspringPopulation[j].FitnessScore = Evaluator.Evaluate(OffspringPopulation[j]);
        //        }
        //        BasePopulation = SurvivorsSelector.Select(BasePopulation, OffspringPopulation);
        //    }
        //}

        protected override void Evolve(int offspringPopulationSize)
        {
            for (var j = 0; j < offspringPopulationSize; j++)
            {
                OffspringPopulation[j] = ParentsSelector.Select(BasePopulation)[0];

                OffspringPopulation[j] = StdDeviationsMutator.Mutate(OffspringPopulation[j]);
                OffspringPopulation[j] = RotationsMutator.Mutate(OffspringPopulation[j]);
                OffspringPopulation[j] = ObjectMutator.Mutate(OffspringPopulation[j]);

                OffspringPopulation[j].FitnessScore = Evaluator.Evaluate(OffspringPopulation[j]);
            }
            BasePopulation = SurvivorsSelector.Select(BasePopulation, OffspringPopulation);
        }
Exemplo n.º 14
0
        private IEnumerable <Mutant> ApplyMutator(SyntaxNode syntaxNode, IMutator mutator)
        {
            var mutations = mutator.Mutate(syntaxNode);

            foreach (var mutation in mutations)
            {
                yield return(new Mutant
                {
                    Id = MutantCount++,
                    Mutation = mutation,
                    ResultStatus = MutantStatus.NotRun
                });
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Mutates one single SyntaxNode using a mutator
        /// </summary>
        private IEnumerable <Mutant> ApplyMutator(SyntaxNode syntaxNode, IMutator mutator)
        {
            var mutations = mutator.Mutate(syntaxNode);

            foreach (var mutation in mutations)
            {
                _logger.LogDebug("Mutant {0} created {1} -> {2} using {3}", _mutantCount, mutation.OriginalNode, mutation.ReplacementNode, mutator.GetType());
                yield return(new Mutant()
                {
                    Id = _mutantCount++,
                    Mutation = mutation,
                    ResultStatus = MutantStatus.NotRun
                });
            }
        }
Exemplo n.º 16
0
        private IEnumerable <T> CreateChildren(T parentA, T parentB)
        {
            for (int i = 0; i < _childrenToCreate; i++)
            {
                var child = _genomeFactory.GetNewGenome();

                foreach (var property in _genomeDescription.Properties)
                {
                    property.Merge(parentA, parentB, child);
                }

                _mutator.Mutate(child);

                yield return(child);
            }
        }
Exemplo n.º 17
0
        public string Mutate(string input, int lowerBound, int upperBound)
        {
            var result = input;
            var times  = GetTimes();

            for (var i = 0; i < times; ++i)
            {
                if (_random.NextDouble() <= GetChance())
                {
                    result = _mutator.Mutate(result, lowerBound, upperBound);
                }
            }

            ++_called;

            return(result);
        }
Exemplo n.º 18
0
        protected IEnumerable <TSolution> Improve(TProblem problem, TSolution bestSolution)
        {
            var mutation = mutator.Mutate(problem, bestSolution);

            if (firstMutation == null)
            {
                firstMutation = mutation;
            }
            else if (stopOnRepeatedMutation && mutation.Equals(firstMutation))
            {
                ShouldContinue = false;
            }
            if (mutation.Score > bestSolution.Score)
            {
                bestSolution  = mutation.GetResult();
                firstMutation = null;
                yield return(bestSolution);
            }
        }
Exemplo n.º 19
0
        public T[] FindSolution(T[] genes)
        {
            var individualSize  = genes.Length;
            var generationCount = 0;
            var generation      = populationCreator
                                  .FirstGeneration(genes, populationSize)
                                  .MakeIndividuals(fitnessFunction)
                                  .OrderByDescending(individual => individual.Score)
                                  .ToList();

            var winner   = generation.First();
            var maxScore = 0;

            var checkConvergence = new ConvergenceCriteria(winner.Score, this.solutionPrecision);

            do
            {
                generationCount++;
                maxScore = winner.Score;

                var elite = generation.Take(eliteSize);


                var offspring = mutator
                                .Mutate(crossOver.Cross(elite.Select(s => s.Value).ToList()), mutationProbability)
                                .MakeIndividuals(fitnessFunction).ToList();

                generation = elite
                             .Union(offspring)
                             .Union(Rescued(generation.Except(elite).ToList(), populationSize - eliteSize - (offspring.Count)))
                             .OrderByDescending(individual => individual.Score)
                             .ToList();
                winner = elite.First();
            }while(!checkConvergence.IsConvergent(winner.Score) && generationCount < maxGenerations);
            return(winner.Value);
        }