예제 #1
0
        /// <summary>
        ///
        /// </summary>
        public void CreateNewGeneration()
        {
            Generations[NbGeneration - 1] = Generations[NbGeneration - 1].OrderByDescending(x => x.Fitness).ToArray();
            //Checker si shallow copy
            NetworkGenome[] generationTemp = new NetworkGenome[GenerationSize];
            NetworkGenome[] elites         = GetElites(NbGeneration);

            float totalFitness = GetTotalFitness(NbGeneration);


            int indexNewGen  = 0;
            int indexPartner = -1;

            //garde lelite
            for (int i = 0; i < elites.Length && indexNewGen < GenerationSize; i++)
            {
                generationTemp[indexNewGen++] = elites[i];
            }
            //rajoute random pour diversiter
            for (int i = 0; i < (int)(LoserPercent * GenerationSize) && indexNewGen < GenerationSize; i++)
            {
                generationTemp[indexNewGen++] = new NetworkGenome(NeuralNetwork.Layout, NeuralNetwork.NbNecessaryInputs, NeuralNetwork.NetworkSize, MutationRnd, CrossOverRnd, MutationChance);
            }

            //fill avec des enfants
            while (indexNewGen < GenerationSize)
            {
                indexPartner = ChooseMateIndex(NbGeneration);
                Genome[] enfants = Generations[NbGeneration - 1][indexPartner].ProduceOffspring(Generations[NbGeneration - 1][ChooseMateIndex(NbGeneration, indexPartner)]);
                generationTemp[indexNewGen++] = (enfants[0] as NetworkGenome);
                generationTemp[indexNewGen++] = (enfants[1] as NetworkGenome);
            }

            Generations.Add(generationTemp);
        }
예제 #2
0
        public void AddNewGeneration()
        {
            var newGeneration = new List <Knapsack>();

            for (int i = 0; i < PopulationSize; i++)
            {
                var candidate = Mutate(Crossover(Select(), Select()));

                newGeneration.Add(candidate);

                var knapsackFitness     = GetKnapsackFitness(candidate);
                var bestKnapsackFitness = GetKnapsackFitness(BestOfRun);
                if (knapsackFitness > bestKnapsackFitness)
                {
                    BestOfRun        = candidate;
                    BestOfRunFitness = knapsackFitness;
                }
            }

            //Console.WriteLine(RunNumber);
            RunNumber++;
            //Console.WriteLine(BestOfRunFitness);
            CurrentGeneration = newGeneration;
            Generations.Add(newGeneration);
        }
예제 #3
0
        public Melody Generate()
        {
            var currentPopulation = _initializer.Initialize();

            ApplyMutationOperators(currentPopulation);
            currentPopulation.Individuals.ToList().ForEach(currentMelody => _fitnessCalculator.Calculate(_initializer.BaseMelody, currentMelody));
            Generations.Add(currentPopulation);

            while (!_stopChecker.Stop(this))
            {
                var newPopulation = _replacementOperator.Replace(currentPopulation);
                newPopulation.Individuals.ToList().ForEach(currentMelody => _fitnessCalculator.Calculate(_initializer.BaseMelody, currentMelody));
                var best = newPopulation.BestIndividual();
                Print(best, newPopulation.Sequence.ToString());
                PrintFitnessValues(best);

                Generations.Add(newPopulation);
                currentPopulation = newPopulation;
            }

            Print(_initializer.BaseMelody, "input");
            PrintFitnessValues(_initializer.BaseMelody);

            Print(BestEver, "output");
            PrintFitnessValues(BestEver);

            return(BestEver);
        }
예제 #4
0
        /// <summary>
        /// Creates a new generation.
        /// </summary>
        /// <returns>The new generation.</returns>
        /// <param name="chromosomes">Chromosomes.</param>
        public void CreateNewGeneration(IList <IChromosome> chromosomes)
        {
            ExceptionHelper.ThrowIfNull("chromosomes", chromosomes);

            CurrentGeneration = new Generation(++GenerationsNumber, chromosomes);
            Generations.Add(CurrentGeneration);
            GenerationStrategy.RegisterNewGeneration(this);
        }
예제 #5
0
 /// <summary>
 ///
 /// </summary>
 public void CreateFirstGeneration()
 {
     NetworkGenome[] generationTemp = new NetworkGenome[GenerationSize];
     for (int i = 0; i < GenerationSize; i++)
     {
         generationTemp[i] = new NetworkGenome(NeuralNetwork.Layout, NeuralNetwork.NbNecessaryInputs,
                                               NeuralNetwork.NetworkSize, MutationRnd, CrossOverRnd, MutationChance, NeuralNetwork.Layers[0].Neurons[0].MinValueRand, NeuralNetwork.Layers[0].Neurons[0].MaxValueRand);
     }
     Generations.Add(generationTemp);
 }
        /// <summary>
        ///     Creates a new generation.
        /// </summary>
        /// <param name="genes">The genes to build the new generation of.</param>
        public virtual void CreateNewGeneration(IList <IGenome> genes)
        {
            if (genes == null)
            {
                throw new NullReferenceException(nameof(genes));
            }

            CurrentGeneration = new Generation(++NumberOfGenerations, genes);
            Generations.Add(CurrentGeneration);
        }
        private void CheckF()
        {
            if (setF1 != setF2)
            {
                return;
            }

            ParetoPointGeneration gen = new ParetoPointGeneration();

            for (int i = 0; i < F1.Length; i++)
            {
                gen.Points.Add(new MyPoint(F1[i], F2[i]));
            }

            // pareto
            uint[] indicies = ParetoFrontFinder.FindParetoFront(F1, F2);
            ParetoIncidies = indicies.Select(n => (int)n).ToArray();
            ParetoFront.Clear();
            for (int i = 0; i < indicies.Length; i++)
            {
                ParetoFront.Add(new Point(F1[indicies[i]], F2[indicies[i]]));
            }

            // calc colors
            Generations.Add(gen);
            if (Generations.Count > maxGen)
            {
                Generations.RemoveAt(0);
            }

            for (int i = 0; i < Generations.Count; i++)
            {
                byte c = (byte)(255 - ((double)i + 1) / Generations.Count * 255);
                Generations[i].Color = new SolidColorBrush(Color.FromArgb(255, c, c, c));
                Generations[i].Size  = i == Generations.Count - 1 ? 8 : 4;
            }

            RecalculateScale();

            if (!Generations.Any())
            {
                return;
            }
            if (!Generations.Last().Points.Any())
            {
                return;
            }
            if (SelectedIndex >= Generations.Last().Points.Count)
            {
                return;
            }
            SelectedPoint = Generations.Last().Points[SelectedIndex];
        }
예제 #8
0
        private void Initialize()
        {
            if (!Goal.All(c => char.IsLetter(c) || char.IsWhiteSpace(c) || char.IsPunctuation(c)))
            {
                throw new ArgumentException("Для поля Goal допускаются только буквы и знаки пробела.");
            }
            if (!Origin.All(c => char.IsLetter(c) || char.IsWhiteSpace(c) || char.IsPunctuation(c)))
            {
                throw new ArgumentException("Для поля Origin допускаются только буквы и знаки пробела.");
            }

            State = Origin;
            Generations.Add("Поколение " + Generation + ": " + State);
        }
        public GeneticAlgorithm(int generationsPerRun, int populationSize, double crossoverRate, double mutationRate, int lowerBound, int upperBound, int selectionStrategy, int recombinationStrategy, int mutationStrategy)
        {
            var gen1 = new List <Candidate>();

            GenerationsPerRun     = generationsPerRun;
            LowerBound            = lowerBound;
            UpperBound            = upperBound;
            PopulationSize        = populationSize;
            CrossoverRate         = crossoverRate;
            MutationRate          = mutationRate;
            CurrentGeneration     = gen1;
            SelectionStrategy     = (SelectionStrategy)selectionStrategy;
            RecombinationStrategy = (RecombinationStrategy)recombinationStrategy;
            MutationStrategy      = (MutationStrategy)mutationStrategy;
            Generations.Add(gen1);
            InitializePopulation();
        }
예제 #10
0
        private void AddToGeneration(int level, IGeneticTreeNode node)
        {
            var generation = GetGeneration(level);

            if (generation == null)
            {
                Generations.Add(new Generation()
                {
                    Level = level, Nodes = new List <IGeneticTreeNode>()
                });
                generation = GetGeneration(level);
            }
            if (!generation.Nodes.Contains(node))
            {
                AddToGeneration(generation, node);
            }
        }
        /// <summary>
        /// Creates a new generation.
        /// </summary>
        /// <param name="chromosomes">The chromosomes for new generation.</param>
        public virtual void CreateNewGeneration(IList <IChromosome> chromosomes)
        {
            chromosomes.ValidateGenes();                 // validate

            var distinct = chromosomes.SelectDistinct(); // select distinct

            // Make sure that chromosomes without fitness are unique in terms of
            // same gene values sequence wasn't encountered in previous generations ->
            if (GenerationsNumber > 0)
            {
                distinct.RemoveEvaluatedPreviously(Generations);
            }

            // Create new Generation from distinct (!) ->
            CurrentGeneration = new Generation(++GenerationsNumber, distinct);

            // Add to collection ->
            Generations.Add(CurrentGeneration);
        }
예제 #12
0
        public void Mutate(Dispatcher dispatcher = null)
        {
            // Create C mutated strings + the current parent.
            var candidates = (from child in Enumerable.Repeat(State, Children)
                              select Mutate(child, Probability))
                             .Concat(Enumerable.Repeat(State, 1));

            // Sort the strings by the fitness function.
            var sorted = from candidate in candidates
                         orderby Fitness(Goal, candidate) descending
                         select candidate;

            // New parent is the most fit candidate.
            State = sorted.First();

            Generation++;
            if (dispatcher != null)
            {
                dispatcher.Invoke(() => Generations.Add("Поколение " + Generation + ": " + State));
            }
        }
        public void Parse(BinaryReader br)
        {
            Version          = br.ReadInt32();
            HeaderSize       = br.ReadInt32();
            FolderNameLength = br.ReadInt32();
            FolderName       = Encoding.UTF8.GetString(br.ReadBytes(FolderNameLength));
            PackageFlags     = br.ReadInt32();
            NameCount        = br.ReadInt32();
            NameOffset       = br.ReadInt32();
            ExportCount      = br.ReadInt32();
            ExportOffset     = br.ReadInt32();
            ImportCount      = br.ReadInt32();
            ImportOffset     = br.ReadInt32();
            DependsOffset    = br.ReadInt32();
            SerialOffset     = br.ReadInt32();
            Unknown2         = br.ReadInt32();
            Unknown3         = br.ReadInt32();
            Unknown4         = br.ReadInt32();
            FGuid            = $"{br.ReadInt32()}.{br.ReadInt32()}.{br.ReadInt32()}.{br.ReadInt32()}";
            GenerationsCount = br.ReadInt32();

            for (int i = 0; i < GenerationsCount; i++)
            {
                var generation = new Generation();
                generation.Parse(br);
                Generations.Add(generation);
            }

            EngineVersion       = br.ReadInt32();
            CookerVersion       = br.ReadInt32();
            CompressionFlags    = br.ReadInt32();
            NumCompressedChunks = br.ReadInt32();

            for (int i = 0; i < NumCompressedChunks; i++)
            {
                var compressedChunk = new CompressedChunk();
                compressedChunk.Parse(br);
                CompressedChunks.Add(compressedChunk);
            }
        }
        public void AddNewGeneration()
        {
            var newGeneration = new List <Candidate>();


            for (int i = 0; i < PopulationSize; i++)
            {
                var candidate = Mutate(Crossover(Select(CurrentGeneration), Select(CurrentGeneration)));

                newGeneration.Add(candidate);
            }

            var min = newGeneration.Select(x => x.Fitness).Min();

            CurrentGeneration = newGeneration;
            Generations.Add(newGeneration);

            if (min < BestOfRun.Fitness)
            {
                BestOfRun = GetBestFitness();
            }
        }
예제 #15
0
        private void InitializePopulation()
        {
            for (var i = 0; i < PopulationSize; i++)
            {
                CurrentGeneration.Add(new Knapsack(_knapsackCapacity, _maxKnapsackWeight));
            }

            BestOfRun = CurrentGeneration[0];

            foreach (var knapsack in CurrentGeneration)
            {
                var knapsackFitness     = GetKnapsackFitness(knapsack);
                var bestKnapsackFitness = GetKnapsackFitness(BestOfRun);
                if (knapsackFitness > bestKnapsackFitness)
                {
                    BestOfRun        = knapsack;
                    BestOfRunFitness = knapsackFitness;
                }
            }

            Generations.Add(CurrentGeneration);
        }
예제 #16
0
        private void Evolve()
        {
            var actorAndScoreList = Actors.Select(actor => ScoreActor(actor, _environment))
                                    .OrderBy(actor => actor.Score).ToList();

            Generations.Add(new Generation
            {
                Actors           = actorAndScoreList,
                GenerationNumber = Generations.Count + 1
            });


            var betterBias      = _aiWeight.BetterBias;   // How likely it is that a better actor is used than a worse one.
            var betterCutoff    = _aiWeight.BetterCutoff; // Percentage of what are considered good actors vs bad ones.
            var betterBiasCount = (int)Math.Round(Actors.Count * betterCutoff);
            var elitism         = _aiWeight.ElitismBias;  // The percentage that gets copied directly to the new generation.
            var mutationChance  = _aiWeight.MutationChance;
            var elitismCount    = (int)Math.Round(Actors.Count * elitism);

            for (var eliteIndex = 0; eliteIndex < elitismCount; eliteIndex++)
            {
                if (MaxActions != null && MaxActions > 0)
                {
                    UpdateActor(eliteIndex, actorAndScoreList[eliteIndex].Lander.Actions.Take((int)MaxActions));
                }
                else
                {
                    UpdateActor(eliteIndex, actorAndScoreList[eliteIndex].Lander.Actions);
                }
            }

            for (var actorIndex = 0 + elitismCount; actorIndex < Actors.Count; actorIndex += 2)
            {
                var firstParent           = GetBiasedActor(betterBias, betterBiasCount, actorAndScoreList);
                var secondParent          = GetBiasedActor(betterBias, betterBiasCount, actorAndScoreList);
                var randomModifier        = Randomizer.GetValueBetween(0.0, 1.0, 2);
                var moreParentActionCount = firstParent.Lander.Actions.Count > secondParent.Lander.Actions.Count
                    ? firstParent.Lander.Actions.Count
                    : secondParent.Lander.Actions.Count;
                for (var childIndex = 0; childIndex < 2; childIndex++)
                {
                    var childPuppet  = Actors.First().Original.Clone();
                    var childActions = new List <string>();
                    for (var actionIndex = 0;
                         actionIndex < moreParentActionCount && actionIndex < (MaxActions ?? int.MaxValue);
                         actionIndex++)
                    {
                        var    firstParentAction  = firstParent.Lander.Actions.ElementAtOrDefault(actionIndex);
                        var    secondParentAction = secondParent.Lander.Actions.ElementAtOrDefault(actionIndex);
                        string childAction;
                        if (firstParentAction == null && secondParentAction == null ||
                            Randomizer.Gamble(mutationChance))
                        {
                            childAction = MarsLanderActor.GetRandomActions(1, _randomNessProvider).First();
                        }
                        else
                        {
                            // If a parent's action index is null, take both from the other parent. The below algorithm is then not needed
                            // --> Because taking both values from the same parent simply results into the same action
                            // Also, depending on the child index, we apply one of two possible algorithms:
                            // ChildIndex = 0: NewAction = randomModifier * firstParentAction + (1 - randomModifier) * secondParentAction
                            // ChildIndex = 1: NewAction = (1 - randomModifier) * firstParentAction + randomModifier * secondParentAction
                            if (firstParentAction == null)
                            {
                                childAction = secondParentAction;
                            }

                            else if (secondParentAction == null)
                            {
                                childAction = firstParentAction;
                            }
                            else
                            {
                                var firstParentActionArray  = firstParentAction !.Split(" ");
                                var firstParentAngle        = int.Parse(firstParentActionArray[0]);
                                var firstParentPower        = int.Parse(firstParentActionArray[1]);
                                var secondParentActionArray = secondParentAction !.Split(" ");
                                var secondParentAngle       = int.Parse(secondParentActionArray[0]);
                                var secondParentPower       = int.Parse(secondParentActionArray[1]);
                                if (childIndex == 0)
                                {
                                    var newAngle = Math.Round(randomModifier * firstParentAngle +
                                                              (1 - randomModifier) * secondParentAngle);
                                    var newPower = Math.Round(randomModifier * firstParentPower +
                                                              (1 - randomModifier) * secondParentPower);
                                    childAction = $"{newAngle} {newPower}";
                                }
                                else
                                {
                                    var newAngle = Math.Round((1 - randomModifier) * firstParentAngle +
                                                              randomModifier * secondParentAngle);
                                    var newPower = Math.Round((1 - randomModifier) * firstParentPower +
                                                              randomModifier * secondParentPower);
                                    childAction = $"{newAngle} {newPower}";
                                }
                            }
                        }

                        childPuppet.Apply(childAction, _environment);
                        childActions.Add(childAction);
                        if (!childPuppet.WillHitLandingZone(_environment, 1) || MaxActions != null)
                        {
                            continue;
                        }
                        var applicableAction = childPuppet.GetApplicableAction("0 4");
                        childPuppet.Apply(applicableAction, _environment);
                        childActions.Add(applicableAction);
                        break;
                    }

                    UpdateActor(actorIndex + childIndex, childActions);
                }
            }
        }
예제 #17
0
 /// <summary>
 /// Создать новое поколение
 /// </summary>
 /// <param name="life"></param>
 public void CreateGeneration()
 {
     Generations.Add(new Generation());
 }
예제 #18
0
 public void EndIteration()
 {
     Iterations++;
     Generations.Add(Current);
 }