Beispiel #1
0
        public void TestA1()
        {
            initialiseA();
            Boolean passed = true;
            int[] countNumbers;
            countNumbers = new int[150];
            GeneticEngine testEngine = new GeneticEngine(APopulator, AEvaluator, AGeneticOperator, AFitnessThresholdTerminator, AOutputter, null);
            currentGeneration = testEngine.Generation;
            int temp = 0;
            //Check that 100 individuals were generated:
            if (currentGeneration.Count != 100) throw new Exception("Count not set to 100.");

            //Check that individuals exist with values 1-100 exactly once each.
            for (int i = 0; i < 100; i++)
            {
                temp = (((IntegerIndividual)(currentGeneration.Get(i)).Individual)).value;
                countNumbers[temp - 1]++;
            }
            for (int i = 0; i < 100; i++)
            {
                if (countNumbers[i] != 1)
                {
                    passed = false;
                    break;
                }
            }
            //if (!passed) throw new Exception("Individuals not populated from 1-100 exactly once each");
            Assert.IsTrue(passed);
            //If no exceptions halt test:
            Console.WriteLine("Test A1 Successful");
        }
        public MainWindow()
        {
            this.random          = new Random();
            this.directionHelper = new DirectionHelper(this.random);

            this.render = true;

            InitializeComponent();
            GenerateNewMap();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddFluffySpoonNeuroEvolution(
                new EvolutionSettings <CarSimulation>()
            {
                AmountOfGenomesInPopulation = 100,
                AmountOfWorstGenomesToRemovePerGeneration = 97,
                NeuronCounts = new[] { 3, 4, 4, 2 },
                NeuronMutationProbability = 0.1,
                RandomnessProvider        = this.random,
                SimulationFactoryMethod   = () => new CarSimulation(this.map),
                PostTickMethod            = RenderGenomes
            });

            var serviceProvider = serviceCollection.BuildServiceProvider();

            this.currentGeneration = serviceProvider.GetRequiredService <IGeneration <CarSimulation> >();
        }
Beispiel #3
0
        public static async Task <IGeneration> AdvanceGenerationAsync(this SQLiteDatabase database)
        {
            IGeneration generation = await database.GetCurrentGenerationOrNullAsync();

            if (generation != null)
            {
                // Update the end date of the current generation.

                generation.EndDate = DateUtilities.GetCurrentDateUtc();

                await database.UpdateGenerationAsync(generation);
            }

            // Create and add the next generation.

            generation = new Generation {
                Number    = generation is null ? 1 : generation.Number + 1,
                StartDate = generation is null ? DateTimeOffset.MinValue : DateUtilities.GetCurrentDateUtc(),
                EndDate   = DateTimeOffset.MaxValue
            };

            await database.AddGenerationAsync(generation);

            return(generation);
        }
        public GenerationManager()
        {
            Console.WriteLine("Generate etmek istediğiniz katman ?");
            Console.WriteLine(@"D => DataLayer
E => Entities 
B => Business");
            var layerVal      = Console.ReadLine();
            var generateLayer = (string.IsNullOrEmpty(layerVal) ? AppHelper.GetApp("GenerateLayer") : layerVal).ToUpper();

            switch (generateLayer)
            {
            case "B":
                _generation = new BusinessGeneration();
                break;

            case "D":
                _generation = new DataLayerGeneration();
                break;

            case "E":
                _generation = new EntitiesGeneration();
                break;

            default:
                break;
            }
        }
Beispiel #5
0
        private static Installation?FindCdVersion(ModData modData, IGeneration generation)
        {
            foreach (var driveInfo in DriveInfo.GetDrives())
            {
                if (driveInfo.DriveType != DriveType.CDRom || !driveInfo.IsReady)
                {
                    continue;
                }

                var installDir = driveInfo.RootDirectory.FullName;

                Log.Write("debug", $"CD version candidate: {installDir}");

                var game = InstallationUtils.TryRegister(modData, installDir, generation);

                if (game != null)
                {
                    return(game);
                }
            }

            Log.Write("debug", "CD version not found");

            return(null);
        }
Beispiel #6
0
        private static Installation?FindGoGInstallation(ModData modData, IGeneration generation)
        {
            if (Platform.CurrentPlatform == PlatformType.Windows)
            {
                var prefixes = new[] { "HKEY_LOCAL_MACHINE\\Software\\", "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\" };

                foreach (var prefix in prefixes)
                {
                    var installDir = Registry.GetValue($"{prefix}GOG.com\\Games\\{generation.GogAppId}", "path", null) as string;

                    if (installDir == null)
                    {
                        continue;
                    }

                    Log.Write("debug", $"GoG version candidate: {installDir}");

                    var game = InstallationUtils.TryRegister(modData, installDir, generation);

                    if (game != null)
                    {
                        return(game);
                    }
                }

                Log.Write("debug", "GoG version not found");
            }
            else
            {
                Log.Write("debug", "GoG version not supported on this platform");
            }

            return(null);
        }
 public void Evaluation(IGeneration currentGeneration)
 {
     foreach (Problems.TravellingSalesman.Route route in (currentGeneration as Generation).individuals)
     {
         route.Fitness = (Problem as TravellingSalesman).Objective(route.TownList);
     }
 }
Beispiel #8
0
        public ITrainingSession UpdateBestPerformer(IGeneration lastGenerationOfEpoch, int epochNumber)
        {
            var bestPerformer = lastGenerationOfEpoch.GetBestPerformer();

            _proxy.StoreNetwork((ArtificialNeuralNetwork.NeuralNetwork)bestPerformer.NeuralNet, bestPerformer.GetSessionEvaluation());
            return(_proxy.GetBestSession());
        }
Beispiel #9
0
 private async Task BreedNewGenomesAsync(
     IGeneration <TSimulation> sourceGeneration)
 {
     while (sourceGeneration.Genomes.Count < evolutionSettings.AmountOfGenomesInPopulation)
     {
         await BreedNewGenomeAsync(sourceGeneration);
     }
 }
Beispiel #10
0
        private async Task BreedNewGenomeAsync(IGeneration <TSimulation> sourceGeneration)
        {
            var crossOver = await sourceGeneration.CrossTwoRandomGenomesAsync();

            await crossOver.MutateAsync(evolutionSettings.NeuronMutationProbability);

            sourceGeneration.AddGenome(crossOver);
        }
        private async void TrainGenerationButton_Click(object sender, RoutedEventArgs e)
        {
            render = true;

            do
            {
                currentGeneration = await currentGeneration.EvolveAsync();
            } while (keepRunning);
        }
Beispiel #12
0
        private static async Task AddGenerationAsync(this SQLiteDatabase database, IGeneration generation)
        {
            using (SQLiteCommand cmd = new SQLiteCommand("INSERT INTO Period(name, start_ts, end_ts) VALUES($name, $start_ts, $end_ts)")) {
                cmd.Parameters.AddWithValue("$name", generation.Name.ToLowerInvariant());
                cmd.Parameters.AddWithValue("$start_ts", DateUtilities.GetTimestampFromDate(generation.StartDate));
                cmd.Parameters.AddWithValue("$end_ts", DateUtilities.GetTimestampFromDate(generation.EndDate));

                await database.ExecuteNonQueryAsync(cmd);
            }
        }
Beispiel #13
0
        public static async Task <string> TimestampToDateStringAsync(long timestamp, IOfcBotContext context, TimestampToDateStringFormat format = TimestampToDateStringFormat.Default)
        {
            if (context.Configuration.GenerationsEnabled)
            {
                IGeneration gen = await context.Database.GetGenerationByDateAsync(DateUtilities.GetDateFromTimestamp(timestamp));

                return(gen is null ? "Gen ???" : gen.Name);
            }

            return(DateUtils.TimestampToDateString(timestamp, format));
        }
Beispiel #14
0
        private async Task <IPaginatedMessage> BuildGenerationEmbedAsync(IGeneration generation)
        {
            IPaginatedMessage message = await this.BuildRecentEventsMessageAsync(generation.StartDate, generation.EndDate);

            TimeSpan span = DateUtilities.GetCurrentDateUtc() - generation.EndDate;

            string timeSpanString = DateUtilities.GetTimestampFromDate(generation.EndDate) == DateUtilities.GetMaxTimestamp() ? "Current" : DateUtilities.GetTimeSpanString(span) + " ago";

            message.SetTitle(string.Format("{0} ({1})", generation.Name, timeSpanString));

            return(message);
        }
Beispiel #15
0
        public static async Task <IGeneration> GetCurrentGenerationAsync(this SQLiteDatabase database)
        {
            // Returns the latest generation, which the current generation always will be.

            IGeneration generation = await database.GetCurrentGenerationOrNullAsync();

            if (generation is null)
            {
                return(await database.AdvanceGenerationAsync());
            }

            return(generation);
        }
        private async void TrainMultipleGenerationsButton_Click(object sender, RoutedEventArgs e)
        {
            while (keepRunning)
            {
                const int generationsToRun = 10;
                for (var i = 0; i < generationsToRun; i++)
                {
                    render            = i == generationsToRun - 1;
                    currentGeneration = await currentGeneration.EvolveAsync();
                }

                Delay(100);
            }
        }
Beispiel #17
0
 private void Start()
 {
     Generation = NeuroevolutionGeneration.Create(
         Inputs,
         HiddenLayers,
         Outputs,
         Genomes,
         Elitism,
         FreshGenomes,
         BreedChilds,
         MutationRate,
         MutationRange,
         ActivationFunction.FromType(ActivationFunctionType));
 }
 public void Operate(IGeneration source, ArrayList destination)
 {
     //Are the individuals in source already ordered by fitness? If so:
     for (int i = 0; i < 50; i++)
     {
         IntegerIndividual theIndividual = (IntegerIndividual)source.Get(i).Individual;
         IntegerIndividual operatedIndividual1 = new IntegerIndividual();
         IntegerIndividual operatedIndividual2 = new IntegerIndividual();
         operatedIndividual1.value = theIndividual.value + 1;
         operatedIndividual2.value = theIndividual.value + 2;
         destination.Add(operatedIndividual1);
         destination.Add(operatedIndividual2);
     }
 }
        public static Installation?TryRegister(ModData modData, string path, IGeneration generation)
        {
            var installation = generation.TryRegister(path);

            if (installation == null)
            {
                return(installation);
            }

            foreach (var(explicitName, name) in installation.Packages)
            {
                modData.ModFiles.Mount(name, explicitName);
            }

            return(installation);
        }
        private void NeuroEvolution(Assert assert)
        {
            var            random   = new Random(100);
            var            neuro    = new NeuroEvolution(new BaseFitnessTest(), 1000, () => new NeuralNetwork(random, 1, new[] { 2, 4, 2 }, 2, 0.1), random);
            IGeneration    firstGen = null;
            INeuralNetwork bestnet  = null;

            //neuro.GenerationFinished += (sender, generation) => { Console.WriteLine(generation.Best.Error); };
            firstGen = neuro.EvolveGeneration();
            // bestnet = neuro.Evolve(1);
            for (int i = 0; i < 10; i++)
            {
                bestnet = neuro.EvolveGeneration().Best;
            }

            assert.Ok(firstGen.Best.Error < bestnet?.Error);
        }
        //Renamed from output
        /// <summary>
        /// Output the generation to the output file if the outputter is currently open
        /// Otherwise open the outputter first. 
        /// </summary>
        /// <param name="generation">The current generation to send to the outputter</param>
        /// <param name="generationCount">The number of generations before the current one</param>
        public void OutputGeneration(IGeneration generation, int generationCount)
        {
            mainWindow.DisplayGeneration(generation);

            if (wrappedOutputter != null)
            {
                if (wrappedOutputter.Status == OutputterStatus.Closed)
                {
                    wrappedOutputter.OpenOutput();
                }

                if (wrappedOutputter.Status == OutputterStatus.Open)
                {
                    wrappedOutputter.OutputGeneration(generation, generationCount);
                }
            }
        }
Beispiel #22
0
        /// <summary>
        /// Constructor of the <c>Maze</c> (with its generation).
        /// </summary>
        /// <param name="height">Height of the maze.</param>
        /// <param name="width">Width of the maze.</param>
        /// <param name="generatorAlgo">Generation algorithm</param>
        public Maze(int height, int width, IGeneration generatorAlgo = null)
        {
            this.Height = height;
            this.Width  = width;

            if (generatorAlgo != null)
            {
                Cells = generatorAlgo.GenerateMaze(Height, Width);
            }
            else
            {
                if (generator == null)
                {
                    SetGenerationAlgorithm(new NeighborGeneration());
                }
                Cells = generator.GenerateMaze(Height, Width);
            }
        }
        public async Task <string> GetDateStringAsync(DateTimeOffset?date, DateStringFormat format = DateStringFormat.Long)
        {
            if (date.HasValue)
            {
                if (Config.GenerationsEnabled)
                {
                    IGeneration gen = await Db.GetGenerationByDateAsync(date.Value);

                    return(gen is null ? "Gen ???" : gen.Name);
                }

                return(DateUtilities.GetDateString(date.Value, format));
            }
            else
            {
                return("???");
            }
        }
        private GeneticAlgorithm(NeuralNetworkConfigurationSettings networkConfig, GenerationConfigurationSettings generationConfig, EvolutionConfigurationSettings evolutionConfig, INeuralNetworkFactory networkFactory, IBreeder breeder, IMutator mutator, IEvalWorkingSet workingSet, IEvaluatableFactory evaluatableFactory, IEpochAction epochAction)
        {
            _networkConfig    = networkConfig;
            _generationConfig = generationConfig;
            _evolutionConfig  = evolutionConfig;
            _epochAction      = epochAction;
            var sessions = new List <ITrainingSession>();

            _networkFactory     = networkFactory;
            _breeder            = breeder;
            _mutator            = mutator;
            _history            = workingSet;
            _evaluatableFactory = evaluatableFactory;
            for (int i = 0; i < _generationConfig.GenerationPopulation; i++)
            {
                var network = _networkFactory.Create(_networkConfig.NumInputNeurons, _networkConfig.NumOutputNeurons, _networkConfig.NumHiddenLayers, _networkConfig.NumHiddenNeurons);
                sessions.Add(new TrainingSession(network, _evaluatableFactory.Create(network), i));
            }
            _generation = new Generation(sessions, _generationConfig);
        }
    public void OutputGeneration(IGeneration generation, int generationNumber)
    {
        best = 0;

        for (int i = 0; i < generation.Count; i++)
        {
            IndividualWithFitness thisIndividual = generation[i];
            //Console.WriteLine("Current Generation: " + i);
            //Console.WriteLine("Best Fitness: " + thisIndividual.Fitness);
            //Console.WriteLine("Value: " + (((IntegerIndividual)(thisIndividual.Individual)).value).ToString());
            //Console.WriteLine();
            if (((IntegerIndividual)(thisIndividual.Individual)).value > best)
            {
                best = ((IntegerIndividual)(thisIndividual.Individual)).value;
            }
            //numberGenerations = i + 1;
        }
        fitnesses[generationNumber] = best;
        numberGenerations = generationNumber;
    }
Beispiel #26
0
        public void OutputGeneration(IGeneration generation, int generationNumber)
        {
            string generationDirectory = "/" + prefix + generationNumber.ToString("D8");
            string generationDirectoryAbsolute = directory + generationDirectory;

            if (!Directory.Exists(generationDirectoryAbsolute))
            {
                Directory.CreateDirectory(generationDirectoryAbsolute);
            }

            string generationPath = generationDirectory + "/generation.xml";

            XmlTextWriter generationWriter = new XmlTextWriter(directory + generationPath, Encoding.ASCII);
            generationWriter.Formatting = Formatting.Indented;

            generationWriter.WriteStartElement("generation");

            for (int i = 0; i < generation.Count; i++)
            {
                IndividualWithFitness individualWithFitness = generation[i];

                string individualPath = "/individual" + i.ToString("D8") + ".xml";
                XmlTextWriter individualWriter  = new XmlTextWriter(generationDirectoryAbsolute+individualPath, Encoding.ASCII);
                individualWriter.Formatting = Formatting.Indented;

                WriteIndividual(individualWithFitness.Individual, individualWriter);
                individualWriter.Flush();
                individualWriter.Close();

                generationWriter.WriteStartElement("individual");
                generationWriter.WriteAttributeString("fitness", individualWithFitness.Fitness.ToString());
                generationWriter.WriteAttributeString("path", "." + individualPath);
                generationWriter.WriteEndElement();
            }

            generationWriter.WriteEndElement();
            generationWriter.Flush();
            generationWriter.Close();

            index.AddGeneration(generation, "." + generationPath);
        }
Beispiel #27
0
        private static Installation?FindSteamInstallation(ModData modData, IGeneration generation)
        {
            foreach (var steamDirectory in InstallationFinder.SteamDirectory())
            {
                var manifestPath = Path.Combine(steamDirectory, "steamapps", $"appmanifest_{generation.SteamAppId}.acf");

                if (!File.Exists(manifestPath))
                {
                    continue;
                }

                var data = InstallationFinder.ParseKeyValuesManifest(manifestPath);

                if (!data.TryGetValue("StateFlags", out var stateFlags) || stateFlags != "4")
                {
                    continue;
                }

                if (!data.TryGetValue("installdir", out var installDir))
                {
                    continue;
                }

                installDir = Path.Combine(steamDirectory, "steamapps", "common", installDir);

                Log.Write("debug", $"Steam version candidate: {installDir}");

                var game = InstallationUtils.TryRegister(modData, installDir, generation);

                if (game != null)
                {
                    return(game);
                }
            }

            Log.Write("debug", "Steam version not found");

            return(null);
        }
        /// <summary>
        /// Process a generation to produce the individuals which will make up the next generation
        /// </summary>
        /// <param name="source">The current generation</param>
        /// <param name="destination">An empty collection of individuals to be populated</param>
        public void Operate(IGeneration source, ArrayList destination)
        {
            int index1 = 1;

            while (destination.Count < source.Count)
            {
                RoadNetwork parent1 = (RoadNetwork)source[index1].Individual;
                destination.Add(new RoadNetwork(parent1));

                if (destination.Count < source.Count)
                {
                    destination.Add(StepMutator.Mutate(parent1));
                }

                int index2 = 0;

                while (index2 < index1 && destination.Count < source.Count)
                {
                    RoadNetwork parent2 = (RoadNetwork)source[index2].Individual;

                    RoadNetwork child1;
                    RoadNetwork child2;

                    StepConjugator.Conjugate(parent1, parent2, out child1, out child2);

                    destination.Add(child1);

                    if (destination.Count < source.Count)
                    {
                        destination.Add(child2);
                    }

                    index2++;
                }

                index1++;
            }
        }
Beispiel #29
0
        public static async Task <bool> RevertGenerationAsync(this SQLiteDatabase database)
        {
            IGeneration generation = await database.GetCurrentGenerationAsync();

            if (generation.Number <= 1)
            {
                return(false);
            }

            // Delete the current generation.

            await database.DeleteGenerationAsync(generation);

            generation = await database.GetCurrentGenerationAsync();

            // Update the end timestamp of the previous generation so that it is now the current generation.

            generation.EndDate = DateUtilities.GetDateFromTimestamp(DateUtilities.GetMaxTimestamp());

            await database.UpdateGenerationAsync(generation);

            return(true);
        }
        public GenerationManager()
        {
            Console.WriteLine("Generate etmek istediğiniz katman ?");
            Console.WriteLine(@"D => DataLayer
            E => Entities
            B => Business");
            var layerVal = Console.ReadLine();
            var generateLayer = (string.IsNullOrEmpty(layerVal) ? AppHelper.GetApp("GenerateLayer") : layerVal).ToUpper();

            switch (generateLayer)
            {
                case "B":
                    _generation = new BusinessGeneration();
                    break;
                case "D":
                    _generation = new DataLayerGeneration();
                    break;
                case "E":
                    _generation = new EntitiesGeneration();
                    break;
                default:
                    break;
            }
        }
Beispiel #31
0
 public static Installation?RegisterInstallation(ModData modData, IGeneration generation)
 {
     return(InstallationFinder.FindSteamInstallation(modData, generation)
            ?? InstallationFinder.FindGoGInstallation(modData, generation) ?? InstallationFinder.FindCdVersion(modData, generation));
 }
 public Battle(IGeneration generation, IReadOnlyIndexedSet<ITrainer> trainers)
 {
     Generation = generation;
     Trainers = trainers;
 }
        public async Task <IPaginatedMessage> BuildSpeciesMessageAsync(ISpecies species)
        {
            if (!species.IsValid())
            {
                return(null);
            }

            Discord.Messaging.Embed embed = new Discord.Messaging.Embed {
                Title = species.GetFullName()
            };

            if (species.CommonNames.Count() > 0)
            {
                embed.Title += string.Format(" ({0})", string.Join(", ", species.CommonNames.Select(name => name.ToTitle())));
            }

            if (Config.GenerationsEnabled)
            {
                // Add a field for the generation.

                IGeneration gen = await Db.GetGenerationByDateAsync(species.CreationDate);

                embed.AddField("Gen", gen is null ? "???" : gen.Number.ToString(), inline: true);
            }

            // Add a field for the species owner.

            embed.AddField("Owner", await GetCreatorAsync(species.Creator), inline: true);

            // Add a field for the species' zones.

            IEnumerable <ISpeciesZoneInfo> speciesZoneList = (await Db.GetZonesAsync(species))
                                                             .Where(info => !info.Zone.Flags.HasFlag(ZoneFlags.Retired));

            string zonesFieldValue = speciesZoneList.ToString(ZoneListToStringOptions.Default, DiscordUtilities.MaxFieldLength);

            embed.AddField("Zone(s)", string.IsNullOrEmpty(zonesFieldValue) ? "None" : zonesFieldValue, inline: true);

            // Add the species' description.

            StringBuilder descriptionBuilder = new StringBuilder();

            if (species.IsExtinct())
            {
                embed.Title = "[EXTINCT] " + embed.Title;

                if (!string.IsNullOrEmpty(species.Status.Reason))
                {
                    descriptionBuilder.AppendLine(string.Format("**Extinct ({0}):** _{1}_\n", await BotUtils.TimestampToDateStringAsync(DateUtilities.GetTimestampFromDate((DateTimeOffset)species.Status.Date), BotContext), species.Status.Reason));
                }
            }

            descriptionBuilder.Append(species.GetDescriptionOrDefault());

            embed.Description = descriptionBuilder.ToString();

            // Add the species' picture.

            embed.ThumbnailUrl = species.GetPictureUrl();

            if (!string.IsNullOrEmpty(Config.WikiUrlFormat))
            {
                // Discord automatically encodes certain characters in URIs, which doesn't allow us to update the config via Discord when we have "{0}" in the URL.
                // Replace this with the proper string before attempting to call string.Format.

                string format = Config.WikiUrlFormat.Replace("%7B0%7D", "{0}");

                embed.Url = string.Format(format, Uri.EscapeUriString(WikiUtilities.GetWikiPageTitle(species)));
            }

            // Create embed pages.

            IEnumerable <Discord.Messaging.IEmbed> embedPages = EmbedUtilities.CreateEmbedPages(embed, EmbedPaginationOptions.AddPageNumbers | EmbedPaginationOptions.CopyFields);
            IPaginatedMessage paginatedMessage = new PaginatedMessage(embedPages);

            if (speciesZoneList.Count() > 0)
            {
                paginatedMessage.SetColor((await Db.GetZoneTypeAsync(speciesZoneList.GroupBy(x => x.Zone.TypeId).OrderBy(x => x.Count()).Last().Key)).Color);
            }

            if (species.IsExtinct())
            {
                paginatedMessage.SetColor(Color.Red);
            }

            return(paginatedMessage);
        }
 /// <summary>
 /// Determine if the algorithm should terminate.
 /// </summary>
 /// <param name="generation">The current generation.</param>
 /// <returns>true iff the MaxFitness property of the generation is greater than or equal to the threshold</returns>
 public bool Terminate(IGeneration generation)
 {
     return generation.MaxFitness >= threshold;
 }
        /// <summary>
        /// Show the best individual from the current generation visually and their statistics. 
        /// </summary>
        /// <param name="generation">Generation to be displayed</param>
        public void DisplayGeneration(IGeneration generation)
        {
            if (!this.IsDisposed)
            {
                if (generation.Count > 0)
                {
                    visualiser1.Network = (RoadNetwork)generation[0].Individual;
                }

                if (this.InvokeRequired)
                {
                    this.Invoke(new ShowStatsCallback(this.ShowStats), new object[] { generation.MaxFitness, generation.AverageFitness });
                }
                else
                {
                    ShowStats(generation.MaxFitness, generation.AverageFitness);
                }
            }
        }
Beispiel #36
0
        public async Task AdvanceGen()
        {
            IGeneration generation = await Db.AdvanceGenerationAsync();

            await ReplySuccessAsync($"Successfully advanced generation to **{generation.Name}**.");
        }
Beispiel #37
0
 public void TestA2()
 {
     initialiseA();
     Boolean passed = true;
     int[] countNumber;
     countNumber = new int[198];
     GeneticEngine testEngine = new GeneticEngine(APopulator, AEvaluator, AGeneticOperator, AFitnessThresholdTerminator, AOutputter, null);
     //testEngine.Step();
     //testEngine.Step();
     currentGeneration = testEngine.Generation;
     int temp = 0;
     //Check that individuals exist from 2 to 200.
     for (int i = 0; i < currentGeneration.Count; i++)
     {
         temp = (((IntegerIndividual)(currentGeneration.Get(i)).Individual)).value;
         countNumber[temp - 1]++;
     }
     for (int i = 0; i < currentGeneration.Count; i++)
     {
         if (countNumber[i] == 0)
         {
             passed = false;
             break;
         }
     }
     //if (!passed) throw new Exception("Individuals not generated from 2-200 correctly.");
     Assert.IsTrue(passed);
     //If no exceptions halt test, then successful:
     Console.WriteLine("Test A2 Successful");
 }
Beispiel #38
0
        /// <summary>
        /// Process a generation to produce the individuals which will make up the next generation
        /// </summary>
        /// <param name="source">The current generation</param>
        /// <param name="destination">An empty collection of individuals to be populated</param>
        public void Operate(IGeneration source, ArrayList destination)
        {
            int i = 0;
            while (destination.Count < source.Count)
            {
                int j = 0;
                while (destination.Count < source.Count && j <= i)
                {
                    destination.Add(Mutate((RoadNetwork)source[j].Individual));
                    j++;
                }

                i++;
            }
        }
 public ITrainingSession UpdateBestPerformer(IGeneration lastGenerationOfEpoch, int epochNumber)
 {
     var bestPerformer = lastGenerationOfEpoch.GetBestPerformer();
     _proxy.StoreNetwork((ArtificialNeuralNetwork.NeuralNetwork)bestPerformer.NeuralNet, bestPerformer.GetSessionEvaluation());
     return _proxy.GetBestSession();
 }
Beispiel #40
0
        /// <summary>
        /// Process a list of individuals.
        /// 1) Replace the current generation with a new empty IGeneration
        /// 2) Evaluate each individual and add it to the generation
        /// 3) Send the generation to the outputter
        /// </summary>
        /// <param name="individuals">The list of individuals</param>
        private void processIndividuals(ArrayList individuals)
        {
            //Get a new instance of the generation container.
            try
            {
                generation = generationFactory.CreateGeneration(individuals);
            }
            catch (Exception ex)
            {
                throw new GeneticEngineException(GeneticEngineException.Plugin.GenerationFactory, "Error getting empty generation.", ex);
            }

            //Inform the evaluator that an new generation has been started.
            try
            {
                evaluator.Initialise(generationNumber, individuals);
            }
            catch (Exception ex)
            {
                throw new GeneticEngineException(GeneticEngineException.Plugin.Evaluator, "Error initialising evaluator.", ex);
            }

            //Evaluate each individual and add it to the generation.
            foreach (object individual in individuals)
            {
                try
                {
                    generation.Insert(individual, evaluator.Evaluate(individual));
                }
                catch (Exception ex)
                {
                    throw new GeneticEngineException(GeneticEngineException.Plugin.Generation, "Error adding individual to generation.", ex);
                }
            }

            //Perform any preparation the generation needs before being given to the outputter or genetic operator plug-ins.
            try
            {
                generation.Prepare();
            }
            catch (Exception ex)
            {
                throw new GeneticEngineException(GeneticEngineException.Plugin.Generation, "Error preparing generation.", ex);
            }

            //Increment the generation counter.
            generationNumber++;

            //If an outputter plug-in has been supplied then output the new generation.
            if (outputter != null)
            {
                if (outputter.Status == OutputterStatus.Closed)
                {
                    try
                    {
                        outputter.OpenOutput();
                    }
                    catch (Exception ex)
                    {
                        throw new GeneticEngineException(GeneticEngineException.Plugin.Outputter, "Error opening outputter.", ex);
                    }
                }

                if (outputter.Status == OutputterStatus.Open)
                {
                    try
                    {
                        outputter.OutputGeneration(generation, generationNumber);
                    }
                    catch (Exception ex)
                    {
                        throw new GeneticEngineException(GeneticEngineException.Plugin.Outputter, "Error outputting generation.", ex);
                    }
                }
            }
        }
Beispiel #41
0
        static void Main()
        {
            var         beginInstructions = "1)Press ESC to quit\n2)Press S to set the size of the Maze\n3)Press Q to set generation algorithm\n4)Press ENTER to start\n";
            var         genAlgoInstructions = "1)Press A to set NeighborGeneration algorithm\n2)Press B to set SillyGeneration algorithm";
            var         instructions = "1)Press ESC to quit\n2)Press R to restart\n3)Control your hero with W,A,S,D or arrows\n";
            int         mazeWidth = 20, mazeHeight = 20;
            IGeneration generator = null;
            var         key = new ConsoleKeyInfo();

            while (true)
            {
                Console.WriteLine(beginInstructions);
                key = Console.ReadKey();
                Console.Clear();
                switch (key.Key)
                {
                case ConsoleKey.Escape:
                {
                    Environment.Exit(0);
                    break;
                }

                case ConsoleKey.S:
                {
                    Console.WriteLine("Enter the width:");
                    mazeWidth = int.Parse(Console.ReadLine());
                    Console.WriteLine("Enter the height:");
                    mazeHeight = int.Parse(Console.ReadLine());
                    break;
                }

                case ConsoleKey.Q:
                {
                    Console.WriteLine(genAlgoInstructions);
                    key = Console.ReadKey();
                    switch (key.Key)
                    {
                    case ConsoleKey.A:
                    {
                        generator = new NeighborGeneration();
                        break;
                    }

                    case ConsoleKey.B:
                    {
                        generator = new SillyGeneration();
                        break;
                    }
                    }
                    break;
                }

                case ConsoleKey.Enter:
                {
                    Maze maze = new Maze(mazeHeight, mazeWidth, generator);
                    Player.GetPlayer.SetRandomCoordinates(maze);

                    Console.WriteLine(instructions + Drawer.Create(maze));
                    while (key.Key != ConsoleKey.Escape)
                    {
                        key = Console.ReadKey();
                        Console.Clear();
                        switch (key.Key)
                        {
                        case ConsoleKey.W:
                        case ConsoleKey.UpArrow:
                        {
                            maze.TryToMove(Direction.Up);
                            break;
                        }

                        case ConsoleKey.A:
                        case ConsoleKey.LeftArrow:
                        {
                            maze.TryToMove(Direction.Left);
                            break;
                        }

                        case ConsoleKey.D:
                        case ConsoleKey.RightArrow:
                        {
                            maze.TryToMove(Direction.Right);
                            break;
                        }

                        case ConsoleKey.S:
                        case ConsoleKey.DownArrow:
                        {
                            maze.TryToMove(Direction.Down);
                            break;
                        }

                        case ConsoleKey.R:
                        {
                            maze = new Maze(mazeWidth, mazeHeight);
                            Player.GetPlayer.SetRandomCoordinates(maze);
                            break;
                        }
                        }
                        Console.WriteLine(instructions + Drawer.Create(maze));
                    }
                    break;
                }
                }
                Console.Clear();
            }
        }
Beispiel #42
0
 internal static PKM GetBlank(this IGeneration gen) => PKMConverter.GetBlank(gen.Generation);
Beispiel #43
0
 public void TestA4()
 {
     initialiseA();
     GeneticEngine testEngine = new GeneticEngine(APopulator, AEvaluator, AGeneticOperator, AFitnessThresholdTerminator, AOutputter, null);
     //testEngine.Reset();
     testEngine.Repeat(5);
     currentGeneration = testEngine.Generation;
     //Assert.Equals
     Assert.AreEqual(5, AOutputter.numberGenerations);
     //Fails here, output expected is 99 but 0 is returned. The assertions after this pass though (101, 103,..)
     Assert.AreEqual(101, AOutputter.fitnesses[1]);
     Assert.AreEqual(103, AOutputter.fitnesses[2]);
     Assert.AreEqual(105, AOutputter.fitnesses[3]);
     Assert.AreEqual(107, AOutputter.fitnesses[4]);
 }
Beispiel #44
0
        //[TestMethod]
        public void TestA5()
        {
            initialiseA();
            GeneticEngine testEngine = new GeneticEngine(APopulator, AEvaluator, AGeneticOperator, AFitnessThresholdTerminator, AOutputter, null);
            //testEngine.Reset();
            testEngine.Run();
            int[] countNumber;
            //Boolean passed = true;
            countNumber = new int[100];
            currentGeneration = testEngine.Generation;
            int temp = 0;
            int min = 0;
            int max = 0;
            min = (((IntegerIndividual)(currentGeneration.Get(0)).Individual)).value;
            max = (((IntegerIndividual)(currentGeneration.Get(0)).Individual)).value;
            //Check that individuals exist from 101 to 200.
            for (int i = 0; i < currentGeneration.Count; i++)
            {
                temp = (((IntegerIndividual)(currentGeneration.Get(i)).Individual)).value;
                if (temp > max) max = temp;
                if (temp < min) min = temp;
                //countNumber[temp - 101]++;
            }
            //if (min != 101) passed = false;

            //if (max != 200) passed = false;
            Assert.AreEqual(max, 200);
            Assert.AreEqual(min, 101);

            //If we need to check ever single individual and make sure there is exactly 1 instance of every integer from 101-200.
            /*
            for (int i = 0; i < currentGeneration.Count; i++)
            {
                if (countNumber[i] == 0)
                {
                    passed = false;
                    break;
                }
            }
            */

            //if (!passed) throw new Exception("Individuals not generated from 101-200 correctly.");
            //Assert.IsTrue(passed);

            //If no exceptions halt test, then successful:
            Console.WriteLine("Test A5 Successful");
        }
Beispiel #45
0
        // Private members

        private async Task ShowGenerationAsync(IGeneration generation)
        {
            IPaginatedMessage message = await BuildGenerationEmbedAsync(generation);

            await ReplyAsync(message);
        }
 public void Operate(IGeneration source, ArrayList destination)
 {
     int num_to_mutate = (int)( source.Count * fraction_to_mutate );
     for (int ii = 0; ii < num_to_mutate; ii++)
     {
         destination.Add( Mutate( (RoadNetwork)source.Get(ii).Individual ) );
     }
 }