Ejemplo n.º 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="IntegerSearcher"/> class.
        /// </summary>
        /// <param name="r">
        /// The r.
        /// </param>
        /// <param name="feasibleSize">
        /// The feasible size.
        /// </param>
        /// <param name="infeasibleSize">
        /// The infeasible size.
        /// </param>
        /// <param name="noveltySearchOptions">The options for this search.</param>
        public IntegerSearcher(Random r, int feasibleSize, int infeasibleSize, NoveltySearchOptions noveltySearchOptions) : base(r, noveltySearchOptions)
        {
            this.FeasiblePopulation   = new IntegerPopulation(true, feasibleSize);
            this.InfeasiblePopulation = new IntegerPopulation(false, infeasibleSize);
            this.Archive = new IntegerNovelArchive();

            for (var i = 0; i < feasibleSize; i++)
            {
                FeasiblePopulation.CurrentGeneration.Add(new IntegerSolution(Random.Next(50000)));
            }

            for (var i = 0; i < feasibleSize; i++)
            {
                InfeasiblePopulation.CurrentGeneration.Add(new IntegerSolution(-Random.Next(50000)));
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Runs standard evolution and/or MOEA seeded with maps found by the constrained novelty search.
        /// </summary>
        /// <param name="maps"> The maps to run evolution on. </param>
        /// <param name="r"> The random number generator. </param>
        /// <param name="mapSearchOptions"> The map search options. </param>
        /// <param name="noveltySearchOptions"> The novelty search options. </param>
        /// <param name="mapFitnessOptions"> The map fitness options. </param>
        /// <param name="numberOfNoveltyGenerations"> The number of generations to run for the novelty search. </param>
        /// <param name="numberOfEvolutionGenerations"> The number of generations to run for the standard evolution. </param>
        /// <param name="numberOfMOEAGenerations"> The number of generations to run for the MOEA. </param>
        /// <param name="evolutionPopulationSize"> The population size of the standard evolution. </param>
        /// <param name="numberOfParents"> The number of parents for the standard evolution. </param>
        /// <param name="numberOfChildren"> The number of children spawned per generation in the standard evolution. </param>
        /// <param name="evolutionMutationChance"> The chance of mutation happening during evolution. </param>
        /// <param name="moeaPopulationSize"> The population size of the MOEA. </param>
        /// <param name="moeaMutationChance"> The chance of mutation happening in the MOEA. </param>
        /// <param name="selectionStrategy"> The selection strategy used in the standard evolution. </param>
        /// <param name="parentSelectionStrategy"> The parent selection strategy used in the standard evolution. </param>
        /// <param name="populationStrategy"> The population strategy used in the standard evolution. </param>
        /// <param name="folderName"> The folder to save results to in "Images/Finished Maps". </param>
        /// <param name="fileToWriteTo"> The file to write timings and fitness per generation to. </param>
        /// <param name="selectHighestFitness"> Determines if the maps for seeding are chosen by highest fitness or highest novelty. </param>
        /// <param name="lowestFitnessLevelForPrint"> The fitness required before a map is printed. </param>
        /// <param name="runEvo"> Determines if the standard evolution should be run. </param>
        /// <param name="runMOEA"> Determines if the MOEA should be run. </param>
        public static void RunEvolutionWithNoveltyAsBase(
            List <MapPhenotype> maps,
            Random r,
            MapSearchOptions mapSearchOptions         = null,
            NoveltySearchOptions noveltySearchOptions = null,
            MapFitnessOptions mapFitnessOptions       = null,
            int numberOfNoveltyGenerations            = 10,
            int numberOfEvolutionGenerations          = 10,
            int numberOfMOEAGenerations                     = 10,
            int evolutionPopulationSize                     = 20,
            int numberOfParents                             = 6,
            int numberOfChildren                            = 16,
            double evolutionMutationChance                  = 0.3,
            int moeaPopulationSize                          = 25,
            double moeaMutationChance                       = 0.3,
            Enums.SelectionStrategy selectionStrategy       = Enums.SelectionStrategy.ChanceBased,
            Enums.SelectionStrategy parentSelectionStrategy = Enums.SelectionStrategy.ChanceBased,
            Enums.PopulationStrategy populationStrategy     = Enums.PopulationStrategy.Mutation,
            string folderName                 = "MapNoveltyEvolution",
            string fileToWriteTo              = "NoveltyEvolutionHighestFitnessSearchGenerationTimes.txt",
            bool selectHighestFitness         = true,
            double lowestFitnessLevelForPrint = double.MinValue,
            bool runEvo  = true,
            bool runMOEA = true)
        {
            var stringToWrite  = new StringBuilder();
            var mso            = mapSearchOptions ?? new MapSearchOptions(null);
            var mfo            = mapFitnessOptions ?? new MapFitnessOptions();
            var nso            = noveltySearchOptions ?? new NoveltySearchOptions();
            var listOfArchives = new List <List <Solution> >();

            // Novelty search
            var sw = new Stopwatch();

            sw.Start();
            var baseMapCounter = 0;

            foreach (var map in maps)
            {
                sw.Restart();
                stringToWrite.AppendLine(string.Format("Performing novelty search on base map number {0}.", baseMapCounter));
                var heightLevels = map.HeightLevels.Clone() as Enums.HeightLevel[, ];
                var items        = map.MapItems.Clone() as Enums.Item[, ];
                var baseMap      = new MapPhenotype(heightLevels, items);
                baseMap.CreateCompleteMap(Enums.Half.Top, Enums.MapFunction.Turn).SaveMapToPngFile(string.Format("Base Map {0}", baseMapCounter), folderName, false);

                mso = new MapSearchOptions(map, mso);
                var searcher = new MapSearcher(r, mso, nso);

                searcher.RunGenerations(numberOfNoveltyGenerations, stringToWrite);

                listOfArchives.Add(searcher.Archive.Archive);

                stringToWrite.AppendLine(string.Format("It took {0} ms to perform novelty search on base map number {1}.", sw.ElapsedMilliseconds, baseMapCounter));
                stringToWrite.AppendLine();

                baseMapCounter++;
            }

            baseMapCounter = 0;

            sw.Restart();
            var solutions = new List <List <EvolvableMap> >();

            if (selectHighestFitness)
            {
                stringToWrite.AppendLine(string.Format("Sorting initial population based by highest fitness."));
                foreach (var map in maps)
                {
                    var evolvableMaps = new List <EvolvableMap>();
                    var archive       = listOfArchives[baseMapCounter];

                    foreach (var solution in archive)
                    {
                        var ms = (MapSolution)solution;
                        mso = new MapSearchOptions(map, mso);
                        var evolvableMap = new EvolvableMap(mso, evolutionMutationChance, r, mfo, ms.MapPoints);
                        evolvableMap.CalculateFitness();
                        evolvableMaps.Add(evolvableMap);
                    }

                    solutions.Add(evolvableMaps.OrderByDescending(s => s.Fitness).ToList());

                    baseMapCounter++;
                }

                stringToWrite.AppendLine(string.Format("It took {0} ms to find maps with the highest fitness.", sw.ElapsedMilliseconds));
                sw.Restart();
            }
            else
            {
                stringToWrite.AppendLine(string.Format("Sorting initial population based by highest novelty."));
                foreach (var map in maps)
                {
                    var evolvableMaps = new List <EvolvableMap>();
                    var archive       = listOfArchives[baseMapCounter];

                    var tempArchive = archive.OrderByDescending(s => s.Novelty);

                    foreach (var solution in tempArchive)
                    {
                        var ms = (MapSolution)solution;
                        mso = new MapSearchOptions(map, mso);
                        var evolvableMap = new EvolvableMap(mso, evolutionMutationChance, r, mfo, ms.MapPoints);
                        evolvableMap.CalculateFitness();
                        evolvableMaps.Add(evolvableMap);
                    }

                    solutions.Add(evolvableMaps);

                    baseMapCounter++;
                }

                stringToWrite.AppendLine(string.Format("It took {0} ms to find maps with the highest novelty.", sw.ElapsedMilliseconds));
                sw.Restart();
            }

            // Evolution
            if (runEvo)
            {
                sw.Restart();
                var bestMaps = new List <EvolvableMap>();
                baseMapCounter = 0;
                foreach (var map in maps)
                {
                    sw.Restart();
                    stringToWrite.AppendLine(string.Format("Performing evolution on base map number {0}.", baseMapCounter));
                    mso = new MapSearchOptions(map, mso);
                    var evolver = new Evolver <EvolvableMap>(
                        numberOfEvolutionGenerations,
                        evolutionPopulationSize,
                        numberOfParents,
                        numberOfChildren,
                        evolutionMutationChance,
                        r,
                        new object[] { mso, evolutionMutationChance, r, mfo })
                    {
                        PopulationSelectionStrategy = selectionStrategy,
                        ParentSelectionStrategy     = parentSelectionStrategy,
                        PopulationStrategy          = populationStrategy
                    };

                    evolver.Initialize(solutions[baseMapCounter].Take(evolutionPopulationSize), stringToWrite);
                    evolver.Evolve(stringToWrite);
                    var variationValue = 0;

                    foreach (var individual in evolver.Population)
                    {
                        variationValue++;
                        if (individual.Fitness >= lowestFitnessLevelForPrint)
                        {
                            individual.ConvertedPhenotype.SaveMapToPngFile(string.Format("Evo_Base Map {0}_Map {1}_Fitness {2}", baseMapCounter, variationValue, individual.Fitness), folderName, false);
                        }
                    }

                    stringToWrite.AppendLine(string.Format("It took {0} ms to perform evolution on base map number {1}.", sw.ElapsedMilliseconds, baseMapCounter));
                    stringToWrite.AppendLine();

                    bestMaps.Add(evolver.Population.OrderByDescending(evoMap => evoMap.Fitness).ToList()[0]);
                    MapHelper.SaveGreyscaleNoveltyMap(evolver.Population, string.Format("Evo_Base Map {0} NoveltyMap", baseMapCounter), folderName);

                    baseMapCounter++;
                }

                MapHelper.SaveGreyscaleNoveltyMap(bestMaps, string.Format("Evo_Best Maps NoveltyMap"), folderName);
            }

            // MOEA
            if (runMOEA)
            {
                baseMapCounter = 0;
                var bestMaps = new List <EvolvableMap>();
                foreach (var map in maps)
                {
                    sw.Restart();
                    stringToWrite.AppendLine(string.Format("Performing multi objective evolution for base map number {0}", baseMapCounter));

                    var heightLevels = map.HeightLevels.Clone() as Enums.HeightLevel[, ];
                    var items        = map.MapItems.Clone() as Enums.Item[, ];
                    var baseMap      = new MapPhenotype(heightLevels, items);
                    baseMap.CreateCompleteMap(Enums.Half.Top, Enums.MapFunction.Mirror);
                    baseMap.SaveMapToPngFile(string.Format("Base Map {0}", baseMapCounter), folderName, false);

                    mso = new MapSearchOptions(map, mso);
                    var evolver = new MultiObjectiveEvolver(
                        numberOfMOEAGenerations,
                        moeaPopulationSize,
                        moeaMutationChance,
                        r,
                        mso,
                        mfo);

                    evolver.RunEvolution(stringToWrite, solutions[baseMapCounter].Take(moeaPopulationSize));

                    var variationValue = 0;

                    foreach (var individual in evolver.Population)
                    {
                        variationValue++;
                        if (individual.Fitness >= lowestFitnessLevelForPrint)
                        {
                            individual.ConvertedPhenotype.SaveMapToPngFile(string.Format("MOEA_Base Map {0}_Map {1}_Fitness {2}", baseMapCounter, variationValue, individual.Fitness), folderName, false);
                        }
                    }

                    stringToWrite.AppendLine(string.Format("It took {0} ms to perform multi objective evolution on base map number {1}", sw.ElapsedMilliseconds, baseMapCounter));
                    stringToWrite.AppendLine();

                    bestMaps.Add(evolver.Population.OrderByDescending(evoMap => evoMap.Fitness).ToList()[0]);
                    MapHelper.SaveGreyscaleNoveltyMap(evolver.Population, string.Format("MOEA_Base Map {0} NoveltyMap", baseMapCounter), folderName);

                    baseMapCounter++;
                }

                MapHelper.SaveGreyscaleNoveltyMap(bestMaps, string.Format("MOEA_Best Maps NoveltyMap"), folderName);
            }

            WriteToTextFile(stringToWrite.ToString(), fileToWriteTo, folderName);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Runs novelty search on a given set of maps with the given settings.
        /// </summary>
        /// <param name="maps"> The maps to run evolution on. </param>
        /// <param name="r"> The random number generator. </param>
        /// <param name="mapSearchOptions"> The map search options. </param>
        /// <param name="noveltySearchOptions"> The novelty search options. </param>
        /// <param name="mapFitnessOptions"> The map fitness options. </param>
        /// <param name="numberOfGenerations"> The number of generations to run. </param>
        /// <param name="folderName"> The folder to save results to in "Images/Finished Maps". </param>
        /// <param name="fileToWriteTo"> The file to write timings and fitness per generation to. </param>
        /// <param name="lowestFitnessLevelForPrint"> The fitness required before a map is printed. </param>
        public static void RunNoveltySearch(
            List <MapPhenotype> maps,
            Random r,
            MapSearchOptions mapSearchOptions         = null,
            NoveltySearchOptions noveltySearchOptions = null,
            MapFitnessOptions mapFitnessOptions       = null,
            int numberOfGenerations           = 10,
            string folderName                 = "MapNovelty",
            string fileToWriteTo              = "NoveltySearchGenerationTimes.txt",
            double lowestFitnessLevelForPrint = double.MinValue)
        {
            var stringToWrite = new StringBuilder();

            var mso = mapSearchOptions ?? new MapSearchOptions(null);
            var mfo = mapFitnessOptions ?? new MapFitnessOptions();
            var nso = noveltySearchOptions ?? new NoveltySearchOptions();

            var sw = new Stopwatch();

            sw.Start();
            var baseMapCounter = 0;

            foreach (var map in maps)
            {
                sw.Restart();
                stringToWrite.AppendLine(string.Format("Performing novelty search on base map number {0}.", baseMapCounter));
                var heightLevels = map.HeightLevels.Clone() as Enums.HeightLevel[, ];
                var items        = map.MapItems.Clone() as Enums.Item[, ];
                var baseMap      = new MapPhenotype(heightLevels, items);
                baseMap.CreateCompleteMap(Enums.Half.Top, Enums.MapFunction.Turn).SaveMapToPngFile(string.Format("Base Map {0}", baseMapCounter), folderName, false);

                mso = new MapSearchOptions(map, mso);
                var searcher = new MapSearcher(r, mso, nso);

                searcher.RunGenerations(numberOfGenerations, stringToWrite);

                var archiveMaps    = new List <MapPhenotype>();
                var variationValue = 0;
                foreach (var solution in searcher.Archive.Archive)
                {
                    var individual = (MapSolution)solution;
                    variationValue++;
                    var fitness = new MapFitness(individual.ConvertedPhenotype, mfo).CalculateFitness();
                    if (fitness >= lowestFitnessLevelForPrint)
                    {
                        individual.ConvertedPhenotype.SaveMapToPngFile(string.Format("Base Map {0}_Map {1}_Fitness {2}", baseMapCounter, variationValue, fitness), folderName, false);
                    }
                    else
                    {
                        Console.WriteLine("fitness too low: " + fitness);
                    }

                    archiveMaps.Add(individual.ConvertedPhenotype);
                }

                stringToWrite.AppendLine(string.Format("It took {0} ms to perform novelty search on base map number {1}.", sw.ElapsedMilliseconds, baseMapCounter));
                stringToWrite.AppendLine();

                MapHelper.SaveGreyscaleNoveltyMap(archiveMaps, string.Format("Base Map {0} NoveltyMap", baseMapCounter), folderName);

                baseMapCounter++;
            }

            WriteToTextFile(stringToWrite.ToString(), fileToWriteTo, folderName);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes the program.
        /// </summary>
        /// <param name="args"> The args. </param>
        public static void Main(string[] args)
        {
            Console.SetWindowSize(Console.LargestWindowWidth - 40, Console.WindowHeight + 40);

            const int RandomGeneratorSeed = 124;

            const int BaseMapStartSeed = 15;
            const int BaseMapEndSeed   = 25;

            const int EvoGenerations = 10;
            const int EvoPopSize     = 25;
            const int Parents        = 6;
            const int Children       = 18;

            const int MOEAGenerations = 10;
            const int MOEAPopSize     = 25;

            const int NoveltyGenerations = 10;
            const int Feasible           = 30;
            const int Infeasible         = 30;
            const int Neighbours         = 5;
            const int Archive            = 5;

            var list = new List <int>();

            for (var i = BaseMapStartSeed; i < BaseMapEndSeed; i++)
            {
                list.Add(i);
            }

            var random = new Random(RandomGeneratorSeed);

            var sw = new Stopwatch();

            sw.Start();

            Console.WriteLine("Generating base maps.");
            var maps = GetBaseMaps(
                caRandomSeeds: list,
                baseMapFolder: string.Format("BaseMaps-start{0}-end{1}", BaseMapStartSeed, BaseMapEndSeed));

            Console.WriteLine("It took {0} milliseconds to generate base maps.", sw.ElapsedMilliseconds);
            Console.WriteLine("------");

            var mapList = maps.Select(x => x.CreateFinishedMap(Enums.Half.Top, Enums.MapFunction.Turn)).ToList();

            MapHelper.SaveGreyscaleNoveltyMap(mapList, " BaseMaps", string.Format("BaseMaps-start{0}-end{1}", BaseMapStartSeed, BaseMapEndSeed));
            sw.Restart();

            Console.WriteLine("Starting evolution");
            RunEvolution(
                maps,
                random,
                numberOfGenerations: EvoGenerations,
                populationSize: EvoPopSize,
                numberOfParents: Parents,
                numberOfChildren: Children,
                folderName: string.Format("Evolution-gen{0}-pop{1}-par{2}-child{3}", EvoGenerations, EvoPopSize, Parents, Children));
            Console.WriteLine("Evolution done. It took  {0} milliseconds to perform evolution.", sw.ElapsedMilliseconds);
            Console.WriteLine("------");
            sw.Restart();

            Console.WriteLine("Starting multiobjective evolution");
            RunMultiobjectiveEvolution(
                maps,
                random,
                numberOfGenerations: MOEAGenerations,
                populationSize: MOEAPopSize,
                folderName: string.Format("MOEA-gen{0}-pop{1}", MOEAGenerations, MOEAPopSize));
            Console.WriteLine("Multiobjective evolution done. It took {0} milliseconds.", sw.ElapsedMilliseconds);
            Console.WriteLine("------");
            sw.Restart();

            Console.WriteLine("Starting novelty search.");
            var nso = new NoveltySearchOptions(
                feasiblePopulationSize: Feasible,
                infeasiblePopulationSize: Infeasible,
                numberOfNeighbours: Neighbours,
                addToArchive: Archive);

            RunNoveltySearch(
                maps,
                random,
                numberOfGenerations: 100,
                noveltySearchOptions: nso,
                folderName: string.Format("NoveltySearch-gen{0}-feas{1}-infeas{2}-neighbors{3}-addtoarch{4}", NoveltyGenerations, Feasible, Infeasible, Neighbours, Archive));
            Console.WriteLine("Novelty search done. It took {0} milliseconds to perform novelty search.", sw.ElapsedMilliseconds);
            Console.WriteLine("------");
            sw.Restart();

            Console.WriteLine("Starting evolution with highest fitness novel maps.");
            nso = new NoveltySearchOptions(feasiblePopulationSize: 90, infeasiblePopulationSize: 90);
            RunEvolutionWithNoveltyAsBase(
                maps,
                random,
                numberOfNoveltyGenerations: NoveltyGenerations,
                numberOfEvolutionGenerations: EvoGenerations,
                numberOfMOEAGenerations: MOEAGenerations,
                noveltySearchOptions: nso,
                evolutionPopulationSize: EvoPopSize,
                moeaPopulationSize: MOEAPopSize,
                numberOfParents: Children,
                numberOfChildren: Parents,
                folderName:
                string.Format(
                    "NoEvHighFitness-noveltygen{0}-feas{1}-infeas{2}-evogen{3}-evopop{4}-evopar{5}-evochild{6}-moeagen{7}-moeapop{8}",
                    NoveltyGenerations,
                    Feasible,
                    Infeasible,
                    EvoGenerations,
                    EvoPopSize,
                    Parents,
                    Children,
                    MOEAGenerations,
                    MOEAPopSize));
            Console.WriteLine("Evolution with highest fitness novel maps. It took {0} milliseconds to perform evolution with highest fitness novel maps.", sw.ElapsedMilliseconds);
            Console.WriteLine("------");
            sw.Restart();

            Console.WriteLine("Starting evolution with highest novelty maps.");
            RunEvolutionWithNoveltyAsBase(
                maps,
                random,
                numberOfNoveltyGenerations: NoveltyGenerations,
                numberOfEvolutionGenerations: EvoGenerations,
                numberOfMOEAGenerations: MOEAGenerations,
                noveltySearchOptions: nso,
                evolutionPopulationSize: EvoPopSize,
                moeaPopulationSize: MOEAPopSize,
                numberOfParents: Children,
                numberOfChildren: Parents,
                folderName:
                string.Format(
                    "NoEvHighNovelty-noveltygen{0}-feas{1}-infeas{2}-evogen{3}-evopop{4}-evopar{5}-evochild{6}-moeagen{7}-moeapop{8}",
                    NoveltyGenerations,
                    Feasible,
                    Infeasible,
                    EvoGenerations,
                    EvoPopSize,
                    Parents,
                    Children,
                    MOEAGenerations,
                    MOEAPopSize),
                selectHighestFitness: false);
            Console.WriteLine("Evolution with highest novelty maps. It took {0} milliseconds to perform evolution with highest novelty maps.", sw.ElapsedMilliseconds);
            Console.WriteLine("------");
            sw.Restart();

            Console.WriteLine("Everything is done running");
            Console.ReadKey();
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MapSearcher"/> class.
        /// </summary>
        /// <param name="r">
        /// The random to use in searching.
        /// </param>
        /// <param name="mapSearchOptions">
        /// The map options for this search.
        /// </param>
        /// <param name="noveltySearchOptions">
        /// The novelty Search Options.
        /// </param>
        public MapSearcher(Random r, MapSearchOptions mapSearchOptions, NoveltySearchOptions noveltySearchOptions)
            : base(r, noveltySearchOptions)
        {
            this.MapSearchOptions     = mapSearchOptions;
            this.FeasiblePopulation   = new MapPopulation(true, noveltySearchOptions.FeasiblePopulationSize);
            this.InfeasiblePopulation = new MapPopulation(false, noveltySearchOptions.InfeasiblePopulationSize);
            this.Archive = new MapNovelArchive();

            var numberOfAttempts = 0;

            while (this.FeasiblePopulation.CurrentGeneration.Count < noveltySearchOptions.FeasiblePopulationSize)
            {
                var list = MapConversionHelper.GenerateInitialMapPoints(mapSearchOptions, r);
                var ms   = new MapSolution(this.MapSearchOptions, this.NoveltySearchOptions, list, r);

                if (ms.IsFeasible)
                {
                    this.FeasiblePopulation.CurrentGeneration.Add(ms);
                }
                else if (InfeasiblePopulation.CurrentGeneration.Count < noveltySearchOptions.InfeasiblePopulationSize)
                {
                    this.InfeasiblePopulation.CurrentGeneration.Add(ms);
                }

                if (numberOfAttempts > 1000)
                {
                    break;
                }

                numberOfAttempts++;
            }

            while (this.InfeasiblePopulation.CurrentGeneration.Count < noveltySearchOptions.InfeasiblePopulationSize)
            {
                var list = MapConversionHelper.GenerateInitialMapPoints(mapSearchOptions, r);

                for (var j = 0; j < list.Count; j++)
                {
                    var item = list[j];

                    var distance = r.Next(2) == 1 ? (r.Next(2) == 1 ? (item.Distance + 1.0) : (item.Distance - 1.0)) : item.Distance;
                    var degree   = r.Next(2) == 1 ? (r.Next(2) == 1 ? (item.Degree + 180) : (item.Degree - 180)) : item.Degree;

                    var mp = new MapPoint(distance, degree, item.Type, Enums.WasPlaced.NotAttempted);

                    list[j] = mp;
                }

                var ms = new MapSolution(this.MapSearchOptions, this.NoveltySearchOptions, list, r);
                this.InfeasiblePopulation.CurrentGeneration.Add(ms);
            }

            foreach (var ms in this.FeasiblePopulation.CurrentGeneration)
            {
                var novelty = ms.CalculateNovelty(
                    this.FeasiblePopulation,
                    this.Archive,
                    noveltySearchOptions.NumberOfNeighbours);

                if (novelty >= noveltySearchOptions.MinimumNovelty)
                {
                    this.Archive.Archive.Add(ms);
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Advances a generation of map solutions using mutation.
        /// </summary>
        /// <param name="nso"> The search options. </param>
        /// <param name="other"> The other population (infeasible or feasible). </param>
        /// <param name="na"> The novel archive. </param>
        /// <param name="r"> The random used in mutation. </param>
        /// <param name="numberOfChildren">The number of children to generate.</param>
        /// <returns> The list of solutions in the next generation. </returns>
        public override List <Solution> AdvanceGeneration(NoveltySearchOptions nso, Population other, NovelArchive na, Random r, int numberOfChildren)
        {
            var children = new List <MapSolution>();

            if (this.CurrentGeneration.Count > 0)
            {
                for (var i = 0; i < numberOfChildren; i++)
                {
                    children.Add((MapSolution)this.CurrentGeneration[i % this.CurrentGeneration.Count].Mutate(r));
                }
            }

            var allIndividuals = this.CurrentGeneration.ToList();

            allIndividuals.AddRange(children);

            var newPopulation = new List <Solution>();

            var returnedPopulation = new List <Solution>();

            foreach (var i in children)
            {
                i.CalculateNovelty(this, na, nso.NumberOfNeighbours);

                if (this.IsFeasiblePopulation)
                {
                    if (!i.IsFeasible)
                    {
                        returnedPopulation.Add(i);
                    }
                }
                else
                {
                    if (i.IsFeasible)
                    {
                        returnedPopulation.Add(i);
                    }
                }
            }

            allIndividuals.RemoveAll(returnedPopulation.Contains);

            if (this.IsFeasiblePopulation && allIndividuals.Count > 0)
            {
                var newToArchive = nso.AddToArchive;

                for (var i = 0; i < this.PopulationSize; i++)
                {
                    if (allIndividuals.Count <= 0)
                    {
                        break;
                    }

                    var index          = 0;
                    var highestNovelty = double.MinValue;

                    for (var j = 0; j < allIndividuals.Count; j++)
                    {
                        if (!(allIndividuals[j].Novelty > highestNovelty))
                        {
                            continue;
                        }

                        highestNovelty = allIndividuals[j].Novelty;
                        index          = j;
                    }

                    if (newToArchive > 0 && allIndividuals[index].Novelty > nso.MinimumNovelty)
                    {
                        na.Archive.Add(allIndividuals[index]);
                        newToArchive--;
                    }
                    else
                    {
                        newPopulation.Add(allIndividuals[index]);
                    }

                    allIndividuals.RemoveAt(index);
                }
            }

            if (!this.IsFeasiblePopulation && allIndividuals.Count > 0)
            {
                for (var i = 0; i < this.PopulationSize; i++)
                {
                    if (allIndividuals.Count <= 0)
                    {
                        break;
                    }

                    var index          = 0;
                    var lowestDistance = double.MaxValue;

                    for (var j = 0; j < allIndividuals.Count; j++)
                    {
                        if (!(allIndividuals[j].DistanceToFeasibility < lowestDistance))
                        {
                            continue;
                        }

                        lowestDistance = allIndividuals[j].DistanceToFeasibility;
                        index          = j;
                    }

                    newPopulation.Add(allIndividuals[index]);
                    allIndividuals.RemoveAt(index);
                }
            }

            this.CurrentGeneration = newPopulation;
            return(returnedPopulation);
        }