Example #1
0
    void RunEpoch()
    {
        if (crossover.PopulationOrParents)
        {
            // działam na całej populacji
            crossover.Cross(population, r);
        }
        else
        {
            // działam na wybranych rodzicach

            // musze wygenerowac nową populacje
            Organism[] newPopulation = new Organism[population.Length];

            for (int i = 0; i < population.Length; i++)
            {
                newPopulation[i] = CreateChild(r);
            }
            population = newPopulation;
        }
        // sprawdzamy czy selekcja wymaga posortowanej populacji
        if (selectionType.NeedSortedPopulation)
        {
            Array.Sort(population);
        }

        currentEpoch++;
        // aktualizacja najlepszego osobnika
        UpdateBest();
        stats.AfterEpoch();
    }
Example #2
0
    public static void CreateBabyHawk(HawkDNA motherDNA, HawkDNA fatherDNA, Transform mother)
    {
        HawkDNA   dna       = new HawkDNA();
        Mutation  mutation  = new Mutation();
        Crossover crossover = new Crossover();

        dna.speed          = mutation.MutateGene(crossover.Cross(motherDNA.speed, fatherDNA.speed), DNA.SPEED_MIN, DNA.SPEED_MAX);
        dna.foodViewRange  = mutation.MutateGene(crossover.Cross(motherDNA.foodViewRange, fatherDNA.foodViewRange), DNA.FOODVIEWRANGE_MIN, DNA.FOODVIEWRANGE_MAX);
        dna.waterViewRange = mutation.MutateGene(crossover.Cross(motherDNA.waterViewRange, fatherDNA.waterViewRange), DNA.WATERVIEWRANGE_MIN, DNA.FOODVIEWRANGE_MAX);

        var hawk = Instantiate(Instance.babyHawk, mother.position, Quaternion.identity).GetComponent <BabyHawk>();

        AnimalStatistics.Instance.AddAnimal(hawk.matureHawk);
        hawk.Initialize(dna);
    }
        /// <summary>
        /// Crosses the specified parents.
        /// </summary>
        /// <param name="parents">The parents.</param>
        /// <returns>The result chromosomes.</returns>
        private IList <IChromosome> Cross(IList <IChromosome> parents)
        {
            var offspring = new List <IChromosome>();

            for (int i = 0; i < Population.MinSize; i += Crossover.ParentsNumber)
            {
                var selectedParents = parents.Skip(i).Take(Crossover.ParentsNumber).ToList();

                // If match the probability cross is made, otherwise the offspring is an exact copy of the parents.
                // Checks if the number of selected parents is equal which the crossover expect, because the in the end of the list we can
                // have some rest chromosomes.
                if (selectedParents.Count == Crossover.ParentsNumber && RandomizationProvider.Current.GetDouble() <= CrossoverProbability)
                {
                    offspring.AddRange(Crossover.Cross(selectedParents));
                }
            }

            if (_debugging)
            {
                Console.WriteLine("{0} parents created {1} children", parents.Count, offspring.Count);
                if (offspring.Count < parents.Count)
                {
                    Console.WriteLine("Time for debugging! This is a bp");
                }
            }
            return(offspring);
        }
Example #4
0
        protected override IList <IGenome> DoProduction(
            IList <IGenome> sampleGenomes,
            GenomeProductionSession thisSession,
            GenomeProductionSession totalSession)
        {
            var selections     = (int)Math.Ceiling((float)thisSession.requiredNb / Crossover.NbOfChildren);
            var totalNbToSelct = selections * Crossover.NbOfParents;

            Selection.Prepare(
                sampleGenomes,
                thisSession,
                totalSession,
                totalNbToSelect: totalNbToSelct);

            Crossover.Prepare(
                sampleGenomes,
                thisSession,
                totalSession);

            while (thisSession.CurrentlyProduced.Count < thisSession.requiredNb)
            {
                var parents  = Selection.Select(Crossover.NbOfParents).ToArray();
                var children = Crossover.Cross(parents);

                var usedChildren = thisSession.AddNewProducedGenomes(children);

                foreach (var child in usedChildren)
                {
                    this.MutationManager.ApplyMutations(child);
                }
            }

            return(thisSession.CurrentlyProduced);
        }
Example #5
0
        /// <summary>
        /// Crosses the specified parents.
        /// </summary>
        /// <param name="parents">The parents.</param>
        /// <returns>The result chromosomes.</returns>
        private IList <IChromosome> Cross(IList <IChromosome> parents)
        {
            var offspring = new List <IChromosome>();

            //Console.WriteLine("Crossover probability: {0}", CrossoverProbability);
            for (int i = 0; i < Population.MinSize; i += Crossover.ParentsNumber)
            {
                var selectedParents = parents.Skip(i).Take(Crossover.ParentsNumber).ToList();

                double randomDouble = ThreadSafeRandom.ThisThreadsRandom.NextDouble();
                //Console.WriteLine("Random Number generated to Cross or Not: {0}", randomDouble);

                // If match the probability cross is made, otherwise the offspring is an exact copy of the parents.
                // Checks if the number of selected parents is equal which the crossover expect, because the in the end of the list we can
                // have some rest chromosomes.
                if (selectedParents.Count == Crossover.ParentsNumber && randomDouble <= CrossoverProbability)
                {
                    offspring.AddRange(Crossover.Cross(selectedParents));
                }
                //else
                //{
                //    Console.WriteLine("No Crossover operation is done");
                //}
            }

            return(offspring);
        }
Example #6
0
    public static void CreateBabyMonkey(MonkeyDNA motherDNA, MonkeyDNA fatherDNA, Transform mother)
    {
        MonkeyDNA dna       = new MonkeyDNA();
        Mutation  mutation  = new Mutation();
        Crossover crossover = new Crossover();

        dna.speed          = mutation.MutateGene(crossover.Cross(motherDNA.speed, fatherDNA.speed), DNA.SPEED_MIN, DNA.SPEED_MAX);
        dna.foodViewRange  = mutation.MutateGene(crossover.Cross(motherDNA.foodViewRange, fatherDNA.foodViewRange), DNA.FOODVIEWRANGE_MIN, DNA.FOODVIEWRANGE_MAX);
        dna.waterViewRange = mutation.MutateGene(crossover.Cross(motherDNA.waterViewRange, fatherDNA.waterViewRange), DNA.WATERVIEWRANGE_MIN, DNA.FOODVIEWRANGE_MAX);

        dna.sex = mutation.RandomizeSex();

        var monkey = Instantiate(Instance.babyMonkey, mother.position, Quaternion.identity).GetComponent <BabyMonkey>();

        AnimalStatistics.Instance.AddAnimal(monkey.matureMaleMonkey);
        monkey.Initialize(dna);
    }
Example #7
0
        public override void NextGeneration()
        {
            var nextGenSize    = ResizePolicy.NextGenSize(this);
            var nextGeneration = new IIndividual[nextGenSize];

            for (var i = 0; i < nextGenSize / Crossover.ChildrenCount; i++)
            {
                var parentalGenotypes = SelectParentalGenotypes();
                var genotypes         = Crossover.Cross(parentalGenotypes);
                for (var j = 0; j < genotypes.Length; j++)
                {
                    var child = IndividualFactory.CreateFromGenotype(genotypes[j]);
                    Mutation.Mutate(child.Genotype, MutationPolicy, this);
                    if (!IncompatibilityPolicy.IsCompatible(this, child))
                    {
                        child = IncompatibilityPolicy.GetReplacement(this, child, parentalGenotypes);
                    }

                    nextGeneration[i * Crossover.ChildrenCount + j] = child;
                }
            }

            var childrenCountDifference = nextGenSize % Crossover.ChildrenCount;

            if (childrenCountDifference > 0)
            {
                var parentalGenotypes = SelectParentalGenotypes();
                var genotypes         = Crossover.Cross(parentalGenotypes);
                var start             = nextGenSize - childrenCountDifference;
                for (var j = 0; j < childrenCountDifference; j++)
                {
                    var child = IndividualFactory.CreateFromGenotype(genotypes[j]);
                    Mutation.Mutate(child.Genotype, MutationPolicy, this);
                    if (!IncompatibilityPolicy.IsCompatible(this, child))
                    {
                        child = IncompatibilityPolicy.GetReplacement(this, child, parentalGenotypes);
                    }

                    nextGeneration[start + j] = child;
                }
            }


            Individuals = nextGeneration;
            DeprecateData();
            UpdatePerGenerationData();
            if (Generation % 1000 == 0)
            {
                GC.Collect();
            }
        }
        public override DecimalArrayChromosome FindOptimum()
        {
            var best = new DecimalArrayChromosome(Constants.ChromosomeSize)
            {
                Fitness = decimal.MaxValue
            };

            for (var i = 0; i < IterationLimit; i++)
            {
                var selectedFromPopulation = Selection.Select(Population);

                var childChromosome = Crossover.Cross(selectedFromPopulation[0], selectedFromPopulation[1]);
                childChromosome         = Mutation.Mutate(childChromosome);
                childChromosome.Fitness = FitnessFunction.GetValue(childChromosome);

                Population.Remove(selectedFromPopulation[2]);
                Population.Add(childChromosome);

                var populationBest = decimal.MaxValue;
                var bestIndex      = 0;
                var index          = 0;

                foreach (var chromosome in Population)
                {
                    if (chromosome.Fitness < populationBest)
                    {
                        populationBest = chromosome.Fitness;
                        bestIndex      = index;
                    }

                    index++;
                }

                if (populationBest < best.Fitness)
                {
                    best = Population.GetAtIndex(bestIndex);
                    Console.WriteLine("Iteration: " + i + ", Best fitness: " + populationBest + ", " + best);
                }

                if (populationBest < FitnessTerminator)
                {
                    break;
                }
            }

            return(best);
        }
Example #9
0
        public override Population GetNextGeneration(Population population)
        {
            Population nextGen = new Population(population.Size, population.AllowDuplicates);

            nextGen.Add(population.GetFittest(Elitism).ToArray());
            int duplicates = 0;

            while (!nextGen.IsFull)
            {
                IList <Individual> children = new List <Individual>();
                // create child by crossover or copy from old population
                double rand = RandomValueGenerator.Instance.GetDouble();
                if (rand < CrossoverRate)
                {
                    var individual1 = Selector.Select(population);
                    var individual2 = Selector.Select(population);
                    foreach (var child in Crossover.Cross(individual1, individual2))
                    {
                        children.Add(new Individual(child));
                    }
                }
                else if (rand - CrossoverRate < MutationRate)
                {
                    var child = new Individual(Selector.Select(population));
                    if (Mutator.Mutate(child))
                    {
                        child.FitnessEvaluated = false;
                    }
                    children.Add(child);
                }
                else
                {
                    children.Add(new Individual(Selector.Select(population)));
                }
                foreach (var child in children)
                {
                    int added = nextGen.Add(child);
                    duplicates += 1 - added;
                }
            }
            if (!AllowDuplicates)
            {
                Logger.WriteLine(2, "Generated duplicates: " + duplicates);
            }
            return(nextGen);
        }
Example #10
0
        public override DecimalArrayChromosome FindOptimum()
        {
            var best = new DecimalArrayChromosome(Constants.ChromosomeSize)
            {
                Fitness = decimal.MaxValue
            };

            for (var i = 0; i < IterationLimit; i++)
            {
                var nextGeneration = new Population <DecimalArrayChromosome>(PopulationSize);

                if (Elitism)
                {
                    nextGeneration.Add(GetPopulationBest());
                }

                while (nextGeneration.Count() < PopulationSize)
                {
                    var selectedFromPopulation = Selection.Select(Population);
                    var childChromosome        =
                        Crossover.Cross(selectedFromPopulation.First(), selectedFromPopulation[1]);
                    childChromosome         = Mutation.Mutate(childChromosome);
                    childChromosome.Fitness = FitnessFunction.GetValue(childChromosome);

                    nextGeneration.Add(childChromosome);
                }

                Population = nextGeneration;
                var populationBest = GetPopulationBest();

                if (populationBest.Fitness < best.Fitness)
                {
                    best = populationBest;
                    Console.WriteLine("Iteration: " + i + ", Best fitness: " + populationBest.Fitness + ", " + best);
                }

                if (populationBest.Fitness < FitnessTerminator)
                {
                    break;
                }
            }

            return(best);
        }
        public override Chromosome FindOptimum()
        {
            var best = new Chromosome(ChromosomeSize)
            {
                Fitness = double.NegativeInfinity
            };

            for (var i = 0; i < IterationLimit; i++)
            {
                var selectedFromPopulation = Selection.Select(Population);

                var childChromosome = Crossover.Cross(selectedFromPopulation[0], selectedFromPopulation[1]);
                childChromosome         = Mutation.Mutate(childChromosome);
                childChromosome.Fitness = FitnessFunction.CalculateFitness(childChromosome);

                Population.Remove(selectedFromPopulation[2]);
                Population.Add(childChromosome);

                var populationBest = 0.0;
                var bestIndex      = 0;
                var index          = 0;

                foreach (var chromosome in Population)
                {
                    if (chromosome.Fitness > populationBest)
                    {
                        populationBest = chromosome.Fitness;
                        bestIndex      = index;
                    }

                    index++;
                }

                if (populationBest > best.Fitness)
                {
                    best = Population.ElementAt(bestIndex);
                    Console.WriteLine("Iteration: " + i + ", Best fitness: " + populationBest);
                }
            }

            return(best);
        }
Example #12
0
File: GA.cs Project: rsppv/Neuro
        public void Start()
        {
            #region Формирование начальной популяции

            Population.FillPopulation(); // Запоним рандомными значениями

            #endregion

            int currentGeneration = 0;

            var selectedIndividuals = new List <IIndividual>();
            //var childPop = new Population(PopulationSize);
            Random rand = new Random();

            while (currentGeneration < GenerationNumber)
            {
                #region Поколение

                currentGeneration += 1;
                RunSimulation();

                #region Оценивание популяции

                foreach (var individual in Population.Individuals)
                {
                    individual.CalcFitness();
                }

                Population.Individuals.Sort();
                PrintGeneration(currentGeneration);
                //fitness = Population.Individuals.First().Fitness;

                #endregion


                #region Селекция

                selectedIndividuals = Selection.Select(Population);

                #endregion


                #region Скрещивание
                Population.Individuals.Clear();
                while (Population.Individuals.Count < PopulationSize)
                {
                    var parent1 = selectedIndividuals[rand.Next(0, selectedIndividuals.Count)];
                    var parent2 = selectedIndividuals[rand.Next(0, selectedIndividuals.Count)];
                    if (rand.NextDouble() < CrossRate)
                    {
                        Crossover.Cross(parent1, parent2);
                        Population.Add(Crossover.Child1);
                        Population.Add(Crossover.Child2);
                    }
                    else
                    {
                        Population.Add(parent1);
                        Population.Add(parent2);
                    }
                }

                #endregion


                #region Мутация

                foreach (var ind in Population.Individuals)
                {
                    for (int i = 0; i < ind.Genes.Count; i++)
                    {
                        if (rand.NextDouble() < MutationRate)
                        {
                            ind.Mutate(i);
                        }
                    }
                }

                #endregion

                // Либо так,
                //либо getRange'ем скопировать элементы в pop,
                //либо ForEach делегатом пробежаться
                //pop = childPop;

                #endregion
            }
            PrintGeneration(currentGeneration);
        }
        public override Chromosome FindOptimum()
        {
            var best = new Chromosome(busStops: BusStops, students: Students)
            {
                Fitness = double.MaxValue
            };

            for (var i = 0; i < IterationLimit; i++)
            {
                var selectedFromPopulation = Selection.Select(Population);

                var childChromosome = Crossover.Cross(selectedFromPopulation[0], selectedFromPopulation[1]);
                childChromosome         = Mutation.Mutate(childChromosome);
                childChromosome.Fitness = FitnessFunction.CalculateFitness(childChromosome);

                Population.Remove(selectedFromPopulation[2]);
                Population.Add(childChromosome);

                var populationBest = double.MaxValue;
                var bestIndex      = 0;
                var index          = 0;

                foreach (var chromosome in Population)
                {
                    if (chromosome.Fitness < populationBest)
                    {
                        populationBest = chromosome.Fitness;
                        bestIndex      = index;
                    }

                    index++;
                }

                if (populationBest < best.Fitness)
                {
                    best = Population.ElementAt(bestIndex);
                    Console.WriteLine("Iteration: " + i + ", Best fitness: " + populationBest);
                }

                if (i % 1000 == 0)
                {
                    Console.WriteLine("Iteration: " + i);

                    foreach (var stop in best.BusStops)
                    {
                        Console.Write(stop.SeatsTaken + ", ");
                    }
                    Console.WriteLine();
                    Console.WriteLine(_stopwatch.Elapsed);
                }

                if (_stopwatch.Elapsed >= TimeSpan.FromMinutes(1) && _stopwatch.Elapsed < TimeSpan.FromMinutes(5) && !minuteMark)
                {
                    var instanceName       = InstanceFilePath.Split('/').Last().Split('.')[0];
                    var lastDirectoryIndex = InstanceFilePath.LastIndexOf('/');
                    var instanceDirectory  = InstanceFilePath.Substring(0, lastDirectoryIndex + 1);

                    HelperMethods.WriteToFile(best.ToString(), instanceDirectory + FileNamePrefix + "-1m-" + instanceName + FileNamePostFix);

                    minuteMark = true;
                    Console.WriteLine("Fitness value => " + best.Fitness + "\tEvaluation count => " + FitnessFunction.EvaluationCounter);
                }

                if (_stopwatch.Elapsed >= TimeSpan.FromMinutes(5) && !fiveMinuteMark)
                {
                    var instanceName       = InstanceFilePath.Split('/').Last().Split('.')[0];
                    var lastDirectoryIndex = InstanceFilePath.LastIndexOf('/');
                    var instanceDirectory  = InstanceFilePath.Substring(0, lastDirectoryIndex + 1);

                    HelperMethods.WriteToFile(best.ToString(), instanceDirectory + FileNamePrefix + "-5m-" + instanceName + FileNamePostFix);

                    fiveMinuteMark = true;
                    Console.WriteLine("Fitness value => " + best.Fitness + "\tEvaluation count => " + FitnessFunction.EvaluationCounter);
                }

                if (populationBest < FitnessTerminator)
                {
                    break;
                }
            }

            _stopwatch.Stop();

            if (!fiveMinuteMark)
            {
                var instanceName       = InstanceFilePath.Split('/').Last().Split('.')[0];
                var lastDirectoryIndex = InstanceFilePath.LastIndexOf('/');
                var instanceDirectory  = InstanceFilePath.Substring(0, lastDirectoryIndex + 1);

                HelperMethods.WriteToFile(best.ToString(), instanceDirectory + FileNamePrefix + "-5m-" + instanceName + FileNamePostFix);
                Console.WriteLine("Fitness value => " + best.Fitness + "\tEvaluation count => " + FitnessFunction.EvaluationCounter);
            }

            Console.WriteLine("Fitness value => " + best.Fitness + "\tEvaluation count => " + FitnessFunction.EvaluationCounter);
            return(best);
        }