/// <summary>
 /// Determine the complexity regulation mode that the evolution algorithm search should be in given the
 /// provided evolution algorithm statistics object, and set the current mode to that mode.
 /// </summary>
 /// <param name="eaStats">Evolution algorithm statistics.</param>
 /// <param name="popStats">Population statistics.</param>
 /// <returns>The determined <see cref="ComplexityRegulationMode"/>.</returns>
 public ComplexityRegulationMode UpdateMode(
     EvolutionAlgorithmStatistics eaStats,
     PopulationStatistics popStats)
 {
     // This is the null strategy, therefore do nothing.
     return(ComplexityRegulationMode.Complexifying);
 }
Example #2
0
        //
        // GET: /Population/

        public ActionResult Index()
        {
            var statistics = new PopulationStatistics();
            var countries  = statistics.GetCountries();

            return(View(countries));
        }
        private ComplexityRegulationMode DetermineMode_WhileSimplifying(
            EvolutionAlgorithmStatistics eaStats,
            PopulationStatistics popStats)
        {
            // Currently simplifying.
            // Test if simplification (ongoing reduction in complexity) has stalled.

            // We allow simplification to progress for a few generations before testing of it has stalled, this allows
            // a lead in time for the effects of simplification to occur.
            // In addition we do not switch to complexifying if complexity is above the currently defined ceiling.
            if (
                ((eaStats.Generation - _lastTransitionGeneration) > _minSimplifcationGenerations) &&
                (popStats.MeanComplexity < _complexityCeiling) &&
                ((popStats.MeanComplexityHistory.Mean - _prevMeanMovingAverage) >= 0.0))
            {
                // Simplification has stalled; switch back to complexification.
                _currentMode = ComplexityRegulationMode.Complexifying;
                _lastTransitionGeneration = eaStats.Generation;
                _prevMeanMovingAverage    = 0.0;
            }
            // else: otherwise remain in simplifying mode.

            // Update previous mean moving average complexity value.
            _prevMeanMovingAverage = popStats.MeanComplexityHistory.Mean;

            // Set a new complexity ceiling, relative to the current population complexity mean.
            _complexityCeiling = popStats.MeanComplexity + _relativeComplexityCeiling;

            return(_currentMode);
        }
Example #4
0
 /// <summary>
 /// Update the graph data.
 /// </summary>
 /// <param name="eaStats">Evolution algorithm statistics object.</param>
 /// <param name="popStats">Population statistics object.</param>
 public virtual void UpdateData(
     EvolutionAlgorithmStatistics eaStats,
     PopulationStatistics popStats)
 {
     // Note. This method could be defined as abstract, but that would prevent the Window Forms UI designer from working;
     // therefore instead it is defined as virtual with no implementation.
 }
Example #5
0
        public ActionResult Details(string id, int?year)
        {
            var statistics = new PopulationStatistics();
            var details    = new CountryDetails();

            var availableYears =
                statistics.GetAvailableYearsForCountry(id);

            details.Name           = id;
            details.AvailableYears =
                availableYears.Select(availableYear =>
                                      new SelectListItem
            {
                Text  = availableYear.ToString(),
                Value = availableYear.ToString()
            });

            var selectedYear = year ?? availableYears.First();

            details.MalePopulation   = statistics.GetMalePopulation(id, selectedYear);
            details.FemalePopulation = statistics.GetFemalePopulation(id, selectedYear);
            details.TotalPopulation  = details.MalePopulation + details.FemalePopulation;

            return(View(details));
        }
Example #6
0
        private void Verify(GeneticAlgorithm genetic)
        {
            this.Verify((Heuristic)genetic);

            PopulationStatistics statistics = genetic.PopulationStatistics;

            Assert.IsTrue(statistics.Generations <= genetic.Parameters.MaximumGenerations);
            Assert.IsTrue(statistics.CoefficientOfVarianceByGeneration.Count == statistics.Generations);
            Assert.IsTrue(statistics.MeanAllelesPerLocusByGeneration.Count == statistics.Generations);
            Assert.IsTrue(statistics.MeanHeterozygosityByGeneration.Count == statistics.Generations);
            Assert.IsTrue(statistics.NewIndividualsByGeneration.Count == statistics.Generations);
            Assert.IsTrue(statistics.PolymorphismByGeneration.Count == statistics.Generations);
            for (int generationIndex = 0; generationIndex < statistics.Generations; ++generationIndex)
            {
                float coefficientOfVariation = statistics.CoefficientOfVarianceByGeneration[generationIndex];
                float meanAllelesPerLocus    = statistics.MeanAllelesPerLocusByGeneration[generationIndex];
                float meanHeterozygosity     = statistics.MeanHeterozygosityByGeneration[generationIndex];
                int   newIndividuals         = statistics.NewIndividualsByGeneration[generationIndex];
                float polymorphism           = statistics.PolymorphismByGeneration[generationIndex];

                Assert.IsTrue(coefficientOfVariation >= 0.0F);
                Assert.IsTrue((meanAllelesPerLocus >= 0.0F) && (meanAllelesPerLocus <= 2.0F));                     // assumes HarvestPeriodSelection.All
                Assert.IsTrue((meanHeterozygosity >= 0.0F) && (meanHeterozygosity <= 1.0F));
                Assert.IsTrue((newIndividuals >= 0) && (newIndividuals <= 2 * genetic.Parameters.PopulationSize)); // two children per breeding
                Assert.IsTrue((polymorphism >= 0.0F) && (polymorphism <= 1.0F));
            }
        }
Example #7
0
        public void TestTransitionToSimplifying()
        {
            var strategy = new AbsoluteComplexityRegulationStrategy(10, 10.0);

            var eaStats  = new EvolutionAlgorithmStatistics();
            var popStats = new PopulationStatistics();
            ComplexityRegulationMode mode;

            // The strategy should initialise to, and remain in, Complexifying mode
            // while mean population complexity is below the threshold.
            for (int i = 0; i < 11; i++)
            {
                eaStats.Generation      = i;
                popStats.MeanComplexity = i;
                popStats.MeanComplexityHistory.Enqueue(i);
                mode = strategy.UpdateMode(eaStats, popStats);
                Assert.AreEqual(ComplexityRegulationMode.Complexifying, mode);
            }

            // The strategy should switch to simplifying mode when mean complexity
            // rises above the threshold.
            eaStats.Generation      = 11;
            popStats.MeanComplexity = 10.01;
            popStats.MeanComplexityHistory.Enqueue(10.01);
            mode = strategy.UpdateMode(eaStats, popStats);
            Assert.AreEqual(ComplexityRegulationMode.Simplifying, mode);
        }
        public void VerifyPopulationStats()
        {
            IRandomSource rng = RandomDefaults.CreateRandomSource(0);

            // Create a test population.
            NeatPopulation <double> pop = CreateNeatPopulation(100, 10.0, rng);

            // Modify a few genome fitnesses.
            pop.GenomeList[10].FitnessInfo = new FitnessInfo(100.0);
            pop.GenomeList[20].FitnessInfo = new FitnessInfo(0.0);

            // Initialise the NEAT population species; the wider population stats are dependent on this occurring.
            InitialiseSpecies(pop);

            // Calc/update stats.
            pop.UpdateStats(PrimaryFitnessInfoComparer.Singleton, rng);

            // Validate stats.
            // Fitness stats.
            PopulationStatistics stats = pop.Stats;

            Assert.Equal(10, stats.BestGenomeIndex);
            Assert.Equal(100.0, stats.BestFitness.PrimaryFitness);
            Assert.Equal(10.8, stats.MeanFitness);
            Assert.Equal(1, stats.BestFitnessHistory.Length);
            Assert.Equal(100.0, stats.BestFitnessHistory.Total);

            // Complexity stats.
            Assert.Equal(6.0, stats.BestComplexity);
            Assert.Equal(6.0, stats.MeanComplexity);
            Assert.Equal(1, stats.MeanComplexityHistory.Length);
            Assert.Equal(6.0, stats.MeanComplexityHistory.Total);
        }
 /// <summary>
 /// Update the time series data.
 /// </summary>
 /// <param name="eaStats">Evolution algorithm statistics object.</param>
 /// <param name="popStats">Population statistics object.</param>
 public override void UpdateData(
     EvolutionAlgorithmStatistics eaStats,
     PopulationStatistics popStats)
 {
     _ppl.Add(eaStats.Generation, eaStats.EvaluationsPerSec);
     RefreshGraph();
 }
 /// <summary>
 /// Update the time series data.
 /// </summary>
 /// <param name="eaStats">Evolution algorithm statistics object.</param>
 /// <param name="popStats">Population statistics object.</param>
 public override void UpdateData(
     EvolutionAlgorithmStatistics eaStats,
     PopulationStatistics popStats)
 {
     _bestPpl.Add(eaStats.Generation, popStats.BestComplexity);
     _meanPpl.Add(eaStats.Generation, popStats.MeanComplexity);
     RefreshGraph();
 }
 /// <summary>
 /// Update the time series data.
 /// </summary>
 /// <param name="eaStats">Evolution algorithm statistics object.</param>
 /// <param name="popStats">Population statistics object.</param>
 public override void UpdateData(
     EvolutionAlgorithmStatistics eaStats,
     PopulationStatistics popStats)
 {
     _bestPpl.Add(eaStats.Generation, popStats.BestFitness.PrimaryFitness);
     _meanPpl.Add(eaStats.Generation, popStats.MeanFitness);
     RefreshGraph();
 }
Example #12
0
 /// <summary>
 /// Determine the complexity regulation mode that the evolution algorithm search should be in given the
 /// provided evolution algorithm statistics object, and set the current mode to that mode.
 /// </summary>
 /// <param name="eaStats">Evolution algorithm statistics.</param>
 /// <param name="popStats">Population statistics.</param>
 /// <returns>The determined <see cref="ComplexityRegulationMode"/>.</returns>
 public ComplexityRegulationMode UpdateMode(
     EvolutionAlgorithmStatistics eaStats,
     PopulationStatistics popStats)
 {
     return(_currentMode switch
     {
         ComplexityRegulationMode.Complexifying => DetermineMode_WhileComplexifying(eaStats, popStats),
         ComplexityRegulationMode.Simplifying => DetermineMode_WhileSimplifying(eaStats, popStats),
         _ => throw new InvalidOperationException("Unexpected complexity regulation mode."),
     });
Example #13
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         _stats = new PopulationStatistics();
         BindHighestMalePopulations();
         BindLowestTotalPopulations();
         BindFemalePopulationIncrease();
     }
 }
Example #14
0
        public void Population()
        {
            Population binaryPopulation = new Population(2, 2, 0.5F, 5);

            binaryPopulation.IndividualFitness[0]        = 0.0F;
            binaryPopulation.IndividualFitness[1]        = 1.0F;
            binaryPopulation.IndividualTreeSelections[0] = new int[] { 0, 0, 0, 0, 0 };
            binaryPopulation.IndividualTreeSelections[1] = new int[] { 1, 1, 1, 1, 1 };

            Population clones = new Population(2, 2, 0.5F, 5);

            clones.IndividualFitness[0]        = 0.0F;
            clones.IndividualFitness[1]        = 0.0F;
            clones.IndividualTreeSelections[0] = new int[] { 0, 0, 0, 0, 0 };
            clones.IndividualTreeSelections[1] = new int[] { 0, 0, 0, 0, 0 };

            Population heterozygousPopulation = new Population(2, 2, 0.5F, 5);

            heterozygousPopulation.IndividualFitness[0]        = 0.4F;
            heterozygousPopulation.IndividualFitness[1]        = 0.6F;
            heterozygousPopulation.IndividualTreeSelections[0] = new int[] { 1, 0, 0, 1, 0 };
            heterozygousPopulation.IndividualTreeSelections[1] = new int[] { 1, 0, 1, 0, 1 };

            PopulationStatistics statistics = new PopulationStatistics();

            statistics.AddGeneration(binaryPopulation);
            statistics.AddGeneration(clones);
            statistics.AddGeneration(heterozygousPopulation);

            Assert.IsTrue(statistics.Generations == 3);

            Assert.IsTrue(statistics.CoefficientOfVarianceByGeneration[0] == 1.0F);
            Assert.IsTrue(statistics.MaximumFitnessByGeneration[0] == 1.0F);
            Assert.IsTrue(statistics.MeanFitnessByGeneration[0] == 0.5F);
            Assert.IsTrue(statistics.MinimumFitnessByGeneration[0] == 0.0F);
            Assert.IsTrue(statistics.MeanHeterozygosityByGeneration[0] == 0.5F);
            Assert.IsTrue(statistics.NewIndividualsByGeneration[0] == 0);
            Assert.IsTrue(statistics.PolymorphismByGeneration[0] == 1.0F);

            Assert.IsTrue(statistics.CoefficientOfVarianceByGeneration[1] == 0.0F);
            Assert.IsTrue(statistics.MaximumFitnessByGeneration[1] == 0.0F);
            Assert.IsTrue(statistics.MeanFitnessByGeneration[1] == 0.0F);
            Assert.IsTrue(statistics.MinimumFitnessByGeneration[1] == 0.0F);
            Assert.IsTrue(statistics.MeanHeterozygosityByGeneration[1] == 0.0F);
            Assert.IsTrue(statistics.NewIndividualsByGeneration[1] == 0);
            Assert.IsTrue(statistics.PolymorphismByGeneration[1] == 0.0F);

            Assert.IsTrue(MathF.Round(statistics.CoefficientOfVarianceByGeneration[2], 6) == 0.2F);
            Assert.IsTrue(statistics.MaximumFitnessByGeneration[2] == 0.6F);
            Assert.IsTrue(statistics.MeanFitnessByGeneration[2] == 0.5F);
            Assert.IsTrue(statistics.MinimumFitnessByGeneration[2] == 0.4F);
            Assert.IsTrue(statistics.MeanHeterozygosityByGeneration[2] == 0.3F);
            Assert.IsTrue(statistics.NewIndividualsByGeneration[2] == 0);
            Assert.IsTrue(statistics.PolymorphismByGeneration[2] == 0.6F);
        }
Example #15
0
    /// <summary>
    /// Construct the population with the provided list of genomes that make up the initial population.
    /// </summary>
    /// <param name="genomeList">Genome list.</param>
    public Population(List <TGenome> genomeList)
    {
        this.GenomeList = genomeList ?? throw new ArgumentNullException(nameof(genomeList));
        if (genomeList.Count == 0)
        {
            throw new ArgumentException("Empty genome list. The initial population cannot be empty.", nameof(genomeList));
        }

        this.PopulationSize = genomeList.Count;
        this.Stats          = CreatePopulatonStats();
    }
Example #16
0
    public void TestTransitionToComplexifying()
    {
        var strategy = new RelativeComplexityRegulationStrategy(10, 10.0);

        var eaStats  = new EvolutionAlgorithmStatistics();
        var popStats = new PopulationStatistics();
        ComplexityRegulationMode mode;

        // Cause an immediate switch to into simplifying mode.
        int generation = 0;

        eaStats.Generation      = generation++;
        popStats.MeanComplexity = 11.0;
        popStats.MeanComplexityHistory.Enqueue(11.0);
        mode = strategy.UpdateMode(eaStats, popStats);
        Assert.Equal(ComplexityRegulationMode.Simplifying, mode);

        // Reset the buffer that the moving average is calculated from;
        // This allows us to change the mean to below the threshold and for the
        // moving average to start rising immediately; that would ordinarily cause
        // an immediate switch back to complexifying mode, but that is prevented by
        // {minSimplifcationGenerations} being set to 10.
        popStats.MeanComplexityHistory.Clear();

        for (int i = 0; i < 10; i++)
        {
            eaStats.Generation      = generation++;
            popStats.MeanComplexity = 2.0;
            popStats.MeanComplexityHistory.Enqueue(2.0);
            mode = strategy.UpdateMode(eaStats, popStats);
            Assert.Equal(ComplexityRegulationMode.Simplifying, mode);
        }

        // Now that {minSimplifcationGenerations} have passed, the strategy should switch
        // back to complexifying mode.
        eaStats.Generation      = generation++;
        popStats.MeanComplexity = 2.0;
        popStats.MeanComplexityHistory.Enqueue(2.0);
        mode = strategy.UpdateMode(eaStats, popStats);
        Assert.Equal(ComplexityRegulationMode.Complexifying, mode);

        // The threshold should have been set relative to the popStats.MeanComplexity (to 12).
        eaStats.Generation      = generation++;
        popStats.MeanComplexity = 11.9;
        popStats.MeanComplexityHistory.Enqueue(11.9);
        mode = strategy.UpdateMode(eaStats, popStats);
        Assert.Equal(ComplexityRegulationMode.Complexifying, mode);

        eaStats.Generation      = generation++;
        popStats.MeanComplexity = 12.01;
        popStats.MeanComplexityHistory.Enqueue(12.01);
        mode = strategy.UpdateMode(eaStats, popStats);
        Assert.Equal(ComplexityRegulationMode.Simplifying, mode);
    }
Example #17
0
        public static void Run()
        {
            var config = new EAConfiguration
            {
                PopulationSize        = 13,
                OverproductionFactor  = 1.5,
                MaximumGenerations    = 10000,
                CrossoverType         = CrossoverType.Uniform,
                AdultSelectionType    = AdultSelectionType.Overproduction,
                ParentSelectionType   = ParentSelectionType.Tournament,
                CrossoverRate         = 0.21,
                MutationRate          = 0.98,
                TournamentSize        = 7,
                TournamentProbability = 0.895,
                TargetFitness         = 1.0,
                Mode   = EAMode.MaximizeFitness,
                Elites = 0,
                CalculateStatistics = true
            };

            var lolzea = new LOLZEA(config, new DefaultRandomNumberGenerator());

            var stopwatchtot = new Stopwatch();
            var stopwatchgen = new Stopwatch();

            PopulationStatistics currentStats = new PopulationStatistics();

            lolzea.PopulationStatisticsCalculated += (stats) =>
            {
                currentStats = stats;
            };
            lolzea.NewGenerationEvent += (gen) => {
                //PrintProgressBar(gen, config.MaximumGenerations);

                var progress   = (gen / (double)config.MaximumGenerations) * 100.0;
                var totruntime = stopwatchtot.Elapsed;
                var genruntime = stopwatchgen.Elapsed;
                Console.WriteLine();
                Console.WriteLine(string.Format("G# {0}    best_f: {1:F3}    avg_f: {2:F3}    SD: {3:F3}    Progress: {4,5:F2}    Gen: {5}   Tot: {6}", gen, lolzea.Best.Fitness, currentStats.AverageFitness, currentStats.StandardDeviationFitness, progress, genruntime, totruntime));
                Console.WriteLine($"Generation winner: {lolzea.Best.ToString()}");

                stopwatchgen.Restart();
            };

            stopwatchtot.Start();
            stopwatchgen.Start();

            var res = lolzea.Evolve();

            Console.WriteLine("\n\nDone!");
            Console.WriteLine($"Winner: {res.Winner}");
            Console.Read();
        }
Example #18
0
        public static void Run()
        {
            var config = new EAConfiguration
            {
                PopulationSize        = 100,
                OverproductionFactor  = 2.0,
                MaximumGenerations    = 100,
                CrossoverType         = CrossoverType.OnePoint,
                AdultSelectionType    = AdultSelectionType.GenerationalMixing,
                ParentSelectionType   = ParentSelectionType.Tournament,
                CrossoverRate         = 0.9,
                MutationRate          = 0.01,
                TournamentSize        = 10,
                TournamentProbability = 0.8,
                TargetFitness         = 1.0,
                Mode   = EAMode.MaximizeFitness,
                Elites = 1,
                CalculateStatistics = true
            };

            var onemaxEA = new OneMaxEA(config, new DefaultRandomNumberGenerator());

            var stopwatchtot = new Stopwatch();
            var stopwatchgen = new Stopwatch();

            PopulationStatistics currentStats = new PopulationStatistics();

            onemaxEA.PopulationStatisticsCalculated += (stats) =>
            {
                currentStats = stats;
            };
            onemaxEA.NewGenerationEvent += (gen) => {
                //PrintProgressBar(gen, config.MaximumGenerations);
                double progress   = (gen / (double)config.MaximumGenerations) * 100.0;
                var    totruntime = stopwatchtot.Elapsed;
                var    genruntime = stopwatchgen.Elapsed;
                Console.WriteLine();
                Console.WriteLine(string.Format("G# {0}    best_f: {1:F3}    avg_f: {2:F3}    SD: {3:F3}    Progress: {4,5:F2}    Gen: {5}   Tot: {6}", gen, onemaxEA.Best.Fitness, currentStats.AverageFitness, currentStats.StandardDeviationFitness, progress, genruntime, totruntime));
                Console.WriteLine("Generation winner: " + ((BinaryGenotype)onemaxEA.Best?.Genotype).ToBitString());

                stopwatchgen.Restart();
            };

            stopwatchtot.Start();
            stopwatchgen.Start();

            var res = onemaxEA.Evolve();

            Console.WriteLine("\n\nDone!");
            Console.WriteLine($"Winner: {res.Winner}");
            Console.Read();
        }
Example #19
0
        /// <summary>
        /// Determine the complexity regulation mode that the evolution algorithm search should be in given the
        /// provided evolution algorithm statistics object.
        /// </summary>
        /// <param name="eaStats">Evolution algorithm statistics.</param>
        /// <param name="popStats">Population statistics.</param>
        public ComplexityRegulationMode UpdateMode(
            EvolutionAlgorithmStatistics eaStats,
            PopulationStatistics popStats)
        {
            switch (_currentMode)
            {
            case ComplexityRegulationMode.Complexifying:
                return(DetermineMode_WhileComplexifying(eaStats, popStats));

            case ComplexityRegulationMode.Simplifying:
                return(DetermineMode_WhileSimplifying(eaStats, popStats));
            }
            throw new InvalidOperationException("Unexpected complexity regulation mode.");
        }
Example #20
0
        public void TestInitialisation()
        {
            var strategy = new AbsoluteComplexityRegulationStrategy(10, 10.0);

            var eaStats  = new EvolutionAlgorithmStatistics();
            var popStats = new PopulationStatistics();

            // The strategy should initialise to, and remain in, Complexifying mode.
            for (int i = 0; i < 100; i++)
            {
                eaStats.Generation = i;
                ComplexityRegulationMode mode = strategy.UpdateMode(eaStats, popStats);
                Assert.AreEqual(ComplexityRegulationMode.Complexifying, mode);
            }
        }
        private ComplexityRegulationMode DetermineMode_WhileComplexifying(
            EvolutionAlgorithmStatistics eaStats,
            PopulationStatistics popStats)
        {
            // Currently complexifying.
            // Test if the complexity ceiling has been reached.
            if (popStats.MeanComplexity > _complexityCeiling)
            {
                // Switch to simplifying mode.
                _currentMode = ComplexityRegulationMode.Simplifying;
                _lastTransitionGeneration = eaStats.Generation;
                _prevMeanMovingAverage    = popStats.MeanComplexityHistory.Mean;
            }

            return(_currentMode);
        }
        /// <summary>
        /// Update the population statistics object.
        /// </summary>
        /// <param name="fitnessComparer">A genome fitness comparer.</param>
        /// <param name="rng">Random source.</param>
        public override void UpdateStats(
            IComparer <FitnessInfo> fitnessComparer,
            IRandomSource rng)
        {
            // Calculate some population-wide stats; these are non-NEAT specific.
            CalcPopulationStats(out double primaryFitnessSum, out double complexitySum, out double maxComplexity);

            // Calculate NEAT specific and species based stats.
            CalcNeatPopulationStats(
                fitnessComparer, rng,
                out double sumMeanFitness,
                out double sumBestFitness,
                out int bestGenomeIdx,
                out int bestGenomeSpeciesIdx);

            // Update PopulationStatistics object.
            PopulationStatistics stats = this.Stats;

            int genomeCount = this.GenomeList.Count;
            var bestGenome  = this.GenomeList[bestGenomeIdx];

            // Update fitness stats.
            stats.BestGenomeIndex = bestGenomeIdx;
            stats.BestFitness     = bestGenome.FitnessInfo;
            stats.MeanFitness     = primaryFitnessSum / genomeCount;
            stats.BestFitnessHistory.Enqueue(bestGenome.FitnessInfo.PrimaryFitness);

            // Update complexity stats.
            stats.BestComplexity = bestGenome.Complexity;
            double meanComplexity = complexitySum / genomeCount;

            stats.MeanComplexity = meanComplexity;
            stats.MeanComplexityHistory.Enqueue(meanComplexity);
            stats.MaxComplexity = maxComplexity;

            // Update NeatPopulationStatistics object.
            this.NeatPopulationStats.BestGenomeSpeciesIdx      = bestGenomeSpeciesIdx;
            this.NeatPopulationStats.SumSpeciesMeanFitness     = sumMeanFitness;
            this.NeatPopulationStats.AverageSpeciesBestFitness = sumBestFitness / SpeciesArray !.Length;
        }
Example #23
0
        protected override void ProcessRecord()
        {
            if (this.Runs !.Count < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(this.Runs));
            }

            using StreamWriter writer = this.GetWriter();

            StringBuilder line = new StringBuilder();

            if (this.ShouldWriteHeader())
            {
                if (this.Runs[0].HighestHeuristicParameters == null)
                {
                    throw new NotSupportedException("Cannot generate header because first run is missing highest solution parameters");
                }

                line.Append("stand,heuristic," + this.Runs[0].HighestHeuristicParameters !.GetCsvHeader() + ",thin age,rotation,generation,highest min,highest mean,highest max,highest cov,highest alleles,highest heterozygosity,highest individuals,highest polymorphism,lowest min,lowest mean,lowest max,lowest cov,lowest alleles,lowest heterozygosity,lowest individuals,lowest polymorphism");
                writer.WriteLine(line);
            }

            for (int runIndex = 0; runIndex < this.Runs.Count; ++runIndex)
            {
                HeuristicSolutionDistribution distribution = this.Runs[runIndex];
                if ((distribution.HighestSolution == null) || (distribution.LowestSolution == null) || (distribution.HighestHeuristicParameters == null))
                {
                    throw new NotSupportedException("Run " + runIndex + " is missing a highest solution, lowest solution, or highest solution parameters");
                }
                GeneticAlgorithm highestHeuristic  = (GeneticAlgorithm)distribution.HighestSolution;
                GeneticAlgorithm lowestHeuristic   = (GeneticAlgorithm)distribution.LowestSolution;
                StandTrajectory  highestTrajectory = highestHeuristic.BestTrajectory;
                string           linePrefix        = highestTrajectory.Name + "," + highestHeuristic.GetName() + "," + distribution.HighestHeuristicParameters.GetCsvValues() + "," + highestTrajectory.GetFirstHarvestAge() + "," + highestTrajectory.GetRotationLength();

                PopulationStatistics highestStatistics = highestHeuristic.PopulationStatistics;
                PopulationStatistics lowestStatistics  = lowestHeuristic.PopulationStatistics;
                int maxGenerations = Math.Max(highestStatistics.Generations, lowestStatistics.Generations);
                for (int generationIndex = 0; generationIndex < maxGenerations; ++generationIndex)
                {
                    line.Clear();

                    string?highestMinimumFitness        = null;
                    string?highestMeanFitness           = null;
                    string?highestMaximumFitness        = null;
                    string?highestCoefficientOfVariance = null;
                    string?highestMeanAlleles           = null;
                    string?highestMeanHeterozygosity    = null;
                    string?highestNewIndividuals        = null;
                    string?highestPolymorphism          = null;
                    if (highestStatistics.Generations > generationIndex)
                    {
                        highestMinimumFitness        = highestStatistics.MinimumFitnessByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                        highestMeanFitness           = highestStatistics.MeanFitnessByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                        highestMaximumFitness        = highestStatistics.MaximumFitnessByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                        highestCoefficientOfVariance = highestStatistics.CoefficientOfVarianceByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                        highestMeanAlleles           = highestStatistics.MeanAllelesPerLocusByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                        highestMeanHeterozygosity    = highestStatistics.MeanHeterozygosityByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                        highestNewIndividuals        = highestStatistics.NewIndividualsByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                        highestPolymorphism          = highestStatistics.PolymorphismByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                    }

                    string?lowestMinimumFitness        = null;
                    string?lowestMeanFitness           = null;
                    string?lowestMaximumFitness        = null;
                    string?lowestCoefficientOfVariance = null;
                    string?lowestMeanAlleles           = null;
                    string?lowestMeanHeterozygosity    = null;
                    string?lowestNewIndividuals        = null;
                    string?lowestPolymorphism          = null;
                    if (lowestStatistics.Generations > generationIndex)
                    {
                        lowestMinimumFitness        = lowestStatistics.MinimumFitnessByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                        lowestMeanFitness           = lowestStatistics.MeanFitnessByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                        lowestMaximumFitness        = lowestStatistics.MaximumFitnessByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                        lowestCoefficientOfVariance = lowestStatistics.CoefficientOfVarianceByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                        lowestMeanAlleles           = lowestStatistics.MeanAllelesPerLocusByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                        lowestMeanHeterozygosity    = lowestStatistics.MeanHeterozygosityByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                        lowestNewIndividuals        = lowestStatistics.NewIndividualsByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                        lowestPolymorphism          = lowestStatistics.PolymorphismByGeneration[generationIndex].ToString(CultureInfo.InvariantCulture);
                    }

                    line.Append(linePrefix + "," +
                                generationIndex + "," +
                                highestMinimumFitness + "," +
                                highestMeanFitness + "," +
                                highestMaximumFitness + "," +
                                highestCoefficientOfVariance + "," +
                                highestMeanAlleles + "," +
                                highestMeanHeterozygosity + "," +
                                highestNewIndividuals + "," +
                                highestPolymorphism + "," +
                                lowestMinimumFitness + "," +
                                lowestMeanFitness + "," +
                                lowestMaximumFitness + "," +
                                lowestCoefficientOfVariance + "," +
                                lowestMeanAlleles + "," +
                                lowestMeanHeterozygosity + "," +
                                lowestNewIndividuals + "," +
                                lowestPolymorphism);
                    writer.WriteLine(line);
                }
            }
        }
Example #24
0
        public static void Run()
        {
            var config = new EAConfiguration
            {
                PopulationSize        = 10,
                OverproductionFactor  = 1.0,
                MaximumGenerations    = 100000,
                CrossoverType         = CrossoverType.OnePoint,
                AdultSelectionType    = AdultSelectionType.GenerationalReplacement,
                ParentSelectionType   = ParentSelectionType.Tournament,
                CrossoverRate         = 0.18,
                MutationRate          = 0.99,
                TournamentSize        = 19,
                TournamentProbability = 0.77,
                TargetFitness         = 0.0,
                Mode   = EAMode.MinimizeFitness,
                Elites = 1,
                CalculateStatistics        = true,
                SnapshotFilename           = "snapshot2.bin",
                SnapshotGenerationInterval = 100
            };

            var hammingEA = new HammingEA(config, new DefaultRandomNumberGenerator());

            var stopwatchtot = new Stopwatch();
            var stopwatchgen = new Stopwatch();

            PopulationStatistics currentStats = new PopulationStatistics();

            hammingEA.PopulationStatisticsCalculated += (stats) =>
            {
                currentStats = stats;
            };

            hammingEA.NewBestFitnessEvent += (pheno, gen) => {
                double progress   = (gen / (double)config.MaximumGenerations) * 100.0;
                var    totruntime = stopwatchtot.Elapsed;
                var    genruntime = stopwatchgen.Elapsed;
                Console.WriteLine();
                Console.WriteLine(string.Format("G# {0}    best_f: {1:F2}    avg_f: {2:F2}    SD: {3:F2}    Progress: {4,5:F2}    Gen: {5}   Tot: {6}", gen, hammingEA.Best.Fitness, currentStats.AverageFitness, currentStats.StandardDeviationFitness, progress, genruntime, totruntime));
                Console.WriteLine("Generation winner: " + ((StringGenotype)hammingEA.Best?.Genotype));

                stopwatchgen.Restart();
            };

            hammingEA.TerminationEvent += (r) =>
            {
                if (r == TerminationReason.FitnessLimitReached)
                {
                    Console.WriteLine($"Fitness limit reached: {hammingEA.Best.Fitness}");
                }
            };

            stopwatchtot.Start();
            stopwatchgen.Start();

            var res = hammingEA.Evolve();

            Console.WriteLine("\n\nDone!");
            Console.WriteLine($"Winner: {res.Winner}");
            WriteResultToFile(hammingEA.PopulationStatistics);
            Console.Read();
        }