/// <summary>
        /// Store tournament results.
        /// </summary>
        /// <param name="results">
        /// The results.
        /// </param>
        private void StoreTournamentResults(MiniTournamentResult <TResult> results)
        {
            lock (this._genomeToTournamentResultsLock)
            {
                for (var rank = 0; rank < results.AllFinishedOrdered.Count; rank++)
                {
                    var participant = results.AllFinishedOrdered[rank];

                    // update the rank
                    if (!this.GenomeToTournamentResults.TryGetValue(participant, out var allObservedParticipantResults))
                    {
                        allObservedParticipantResults = new List <GenomeTournamentResult>();
                        this.GenomeToTournamentResults[participant] = allObservedParticipantResults;
                    }

                    var result = new GenomeTournamentResult()
                    {
                        TournamentRank = rank + 1,
                        TournamentId   = results.MiniTournamentId,
                        Generation     = this._selectCommand.CurrentGeneration,
                    };
                    allObservedParticipantResults.Add(result);
                }
            }
        }
예제 #2
0
        /// <summary>
        /// Simulates a tuner run for the specified number of generations and stores results in a new <see cref="TrainingDataWrapper"/>.
        /// </summary>
        /// <param name="tree"><see cref="ParameterTree"/> to base genomes on.</param>
        /// <param name="encoder">Strategy to convert genomes to double arrays.</param>
        /// <param name="genomeCount">Number of genomes to add to result per generation.</param>
        /// <param name="generations">Number of generations to simulate.</param>
        /// <param name="config"><see cref="AlgorithmTunerConfiguration"/>, required to generate new genomes.</param>
        /// <returns>The created <see cref="TrainingDataWrapper"/>.</returns>
        public static TrainingDataWrapper GenerateTrainingData(
            ParameterTree tree,
            IBulkGenomeTransformation encoder,
            int genomeCount,
            int generations,
            AlgorithmTunerConfiguration config)
        {
            var result = new TrainingDataWrapper(
                new Dictionary <Genome, List <GenomeTournamentResult> >(new Genome.GeneValueComparator()),
                generations - 1);

            // Start with correct number of random genomes.
            var randomGenomes = TestDataUtils.GenerateGenomes(tree, config, genomeCount);

            // Then simulate the correct number of generations.
            for (var currentGen = 0; currentGen < generations; currentGen++)
            {
                var fitness = TestDataUtils.EvaluateTargetFunction(encoder, randomGenomes);

                // add result for every genome
                for (var genomeIndex = 0; genomeIndex < genomeCount; genomeIndex++)
                {
                    var currentGenome = randomGenomes[genomeIndex];
                    if (!result.TournamentResults.ContainsKey(currentGenome))
                    {
                        result.TournamentResults[currentGenome] = new List <GenomeTournamentResult>();
                    }

                    var tournamentResult = new GenomeTournamentResult()
                    {
                        Generation     = currentGen,
                        TournamentId   = currentGen,
                        TournamentRank = fitness[genomeIndex],
                    };

                    result.TournamentResults[currentGenome].Add(tournamentResult);
                }

                // swap out some genomes
                var replaceCount      = (int)Math.Ceiling(0.3 * genomeCount);
                var indiciesToReplace = Randomizer.Instance.ChooseRandomSubset(
                    Enumerable.Range(0, genomeCount),
                    replaceCount);

                var newGenomes       = TestDataUtils.GenerateGenomes(tree, config, replaceCount);
                var replacementIndex = 0;
                foreach (var indexToReplace in indiciesToReplace)
                {
                    randomGenomes[indexToReplace] = newGenomes[replacementIndex++];
                }
            }

            return(result);
        }
예제 #3
0
        public override void ReadFromFileDeserializesCorrectly()
        {
            /* Create status. */
            /* (1) population */
            var competitiveGenome = new Genome(2);

            competitiveGenome.SetGene("a", new Allele <int>(6));
            var nonCompetitiveGenome = new Genome(1);

            nonCompetitiveGenome.SetGene("b", new Allele <string>("oh"));
            this._population.AddGenome(competitiveGenome, isCompetitive: true);
            this._population.AddGenome(nonCompetitiveGenome, isCompetitive: false);
            // (2) counters
            int counter    = 12;
            int stagnation = 7;
            /* (3) ranks */
            var result = new GenomeTournamentResult
            {
                TournamentRank = 2,
                Generation     = 24,
                TournamentId   = 11,
            };
            var results = new List <GenomeTournamentResult> {
                result
            };
            var ranks = new Dictionary <Genome, List <GenomeTournamentResult> > {
                { new Genome(), results }
            };
            var status = new GgaStatus(this._population, counter, stagnation, ranks);

            /* Write and read it from file. */
            status.WriteToFile(this.StatusFilePath);
            var deserializedStatus = StatusBase.ReadFromFile <GgaStatus>(this.StatusFilePath);

            /* Check it's still the same. */
            /* (a) population */
            Assert.Equal(
                1,
                deserializedStatus.Population.GetCompetitiveIndividuals().Count);
            var deserializedCompetitiveGenome = deserializedStatus.Population.GetCompetitiveIndividuals().First();

            Assert.True(
                new Genome.GeneValueComparator().Equals(competitiveGenome, deserializedCompetitiveGenome),
                "Expected different competive genome.");
            Assert.Equal(
                competitiveGenome.Age,
                deserializedCompetitiveGenome.Age);
            Assert.Equal(
                1,
                deserializedStatus.Population.GetNonCompetitiveMates().Count);
            var deserializedNonCompetitiveGenome = deserializedStatus.Population.GetNonCompetitiveMates().First();

            Assert.True(
                new Genome.GeneValueComparator().Equals(nonCompetitiveGenome, deserializedNonCompetitiveGenome),
                "Expected different non-competive genome.");
            Assert.Equal(
                nonCompetitiveGenome.Age,
                deserializedNonCompetitiveGenome.Age);
            // counters
            Assert.Equal(
                counter,
                deserializedStatus.IterationCounter);
            Assert.Equal(
                stagnation,
                deserializedStatus.IncumbentKeptCounter);
            /* (c) ranks */
            var singleResult = deserializedStatus.AllKnownRanks.Single().Value.Single();

            Assert.Equal(result.Generation, singleResult.Generation);
            Assert.Equal(result.TournamentId, singleResult.TournamentId);
            Assert.Equal(result.TournamentRank, singleResult.TournamentRank);
        }