Exemple #1
0
        /// <summary>
        /// Return true if one of the constraints gets violated
        /// </summary>
        /// <param name="ea">Algorithm to check constraints on</param>
        /// <param name="maxRuntime">Maximum algorithm runtime</param>
        /// <param name="maxEpochs">Maximum algorithm iterations</param>
        /// <param name="maxStagnation">Maximum time no change occurs</param>
        /// <param name="minFitness">Minimum achieved fitness</param>
        /// <returns>True if algorithm should stop</returns>
        private bool StopCondition(
            EvolutionaryAlgorithm ea,
            int?maxRuntime,
            int?maxEpochs,
            int?maxStagnation,
            double?minFitness)
        {
            bool stop = false;

            if (maxRuntime.HasValue)
            {
                stop |= ea.TimeRan > TimeSpan.FromSeconds(maxRuntime.Value);
            }

            if (maxEpochs.HasValue)
            {
                stop |= ea.Epoch >= maxEpochs.Value;
            }

            if (maxStagnation.HasValue)
            {
                stop |= ea.StagnationCount >= maxStagnation.Value;
            }

            if (minFitness.HasValue)
            {
                stop |= ea.Fitness >= minFitness.Value;
            }

            return(stop);
        }
Exemple #2
0
 private void LoadSerialzedCanvasIfExists(EvolutionaryAlgorithm algorithm, string fileName = "saves/Suspended.canvas")
 {
     if (File.Exists(fileName))
     {
         LoadSerializedCanvas(algorithm, fileName);
     }
 }
Exemple #3
0
        /// <summary>
        /// Print results for a single epoch.
        /// </summary>
        /// <param name="algorithm">algorithm to print for</param>
        private static void PrintEpochResults(EvolutionaryAlgorithm algorithm)
        {
            // print fittest
            Console.Write("Epoch {0, -4}: {1,5:N5}", algorithm.Epoch, algorithm.Fitness);
            if (algorithm.StagnationCount > 0)
            {
                for (int i = 0; i < algorithm.StagnationCount; i++)
                {
                    Console.Write('*');
                }
            }

            Console.WriteLine();
        }
        /// <summary>
        /// Create a complete new population with totally random values for all chromosomes.
        /// </summary>
        /// <param name="numberOfRepopulations"></param>
        /// <param name="populationSize"></param>
        /// <param name="numberOfTrials"></param>
        /// <param name="gameSpeed"></param>
        /// <param name="tTest"></param>
        /// <param name="nuberOfCrossOvers">Make one point cross over on the specified number of best candidates, and randomly pick the half of the new chromosomes.</param>
        public Trainer(int numberOfRepopulations, int populationSize, int numberOfTrials, int gameSpeed, Boolean tTest, int nuberOfCrossOvers)
        {
            _numberOfRepopulations = numberOfRepopulations;
            _populationSize = populationSize;
            _numberOfTrials = numberOfTrials;
            _nuberOfCrossOvers = nuberOfCrossOvers;
            _ea = new EvolutionaryAlgorithm(_populationSize);
            _gameSpeed = gameSpeed;

            if (tTest)
                PlayWithRandomChromosomes();//TTest();
            else
                Train();
        }
Exemple #5
0
        private void LoadSerializedCanvas(EvolutionaryAlgorithm algorithm, string fileName = "saves/Suspended.canvas")
        {
            var canvas = File.ReadAllBytes(fileName).AsCanvas(algorithm);

            if (algorithm.Population == null || algorithm.Population.Count == 0)
            {
                algorithm.Population = new List <ICanvas>()
                {
                    canvas
                };
            }
            else
            {
                algorithm.Population.Add(canvas);
            }
        }
Exemple #6
0
        private void GenerateDiffImageAndSave(EvolutionaryAlgorithm algorithm)
        {
            var mainImage = ToBitmap(MainImage.Source as BitmapImage).AsByteArray();
            var seedImage = ToBitmap(SeedImage.Source as BitmapImage).AsByteArray();
            var diffImage = new byte[mainImage.Length];

            for (int i = 0; i < mainImage.Length; i += 4)
            {
                var dB = Math.Abs((int)mainImage[i] - (int)seedImage[i]);
                var dG = Math.Abs((int)mainImage[i + 1] - (int)seedImage[i + 1]);
                var dR = Math.Abs((int)mainImage[i + 2] - (int)seedImage[i + 2]);
                var dT = (dR + dG + dB) / 3;
                diffImage[i / 4] = (byte)(255 - dT);
            }

            SaveBitmap(diffImage.AsBitmap(algorithm.CanvasWidth, algorithm.CanvasHeight), CompareImage);
        }
Exemple #7
0
        static void Phase2()
        {
            EvolutionaryAlgorithm  eva   = new EvolutionaryAlgorithm();
            MapBlueprintIndividual input = (MapBlueprintIndividual)Individual.FromFile(@"C:\Users\Jan\Source\Repos\RoguelikeEva\Results\door test\_RESULT 9.bin");
            var graph = ExtractRoomAdjacencyGraph(input.Rooms.First().Key, input);

            eva.Operators.Add(new ExtendBranchMutation(1));

            /*eva.Operators.Add(new CompressBranchMutation(1));
             * eva.Operators.Add(new ReplaceBranchMutation(1));
             * eva.Operators.Add(new ReverseBranchMutation(1));
             * eva.Operators.Add(new ShiftStartingRoomMutation(1));*/

            eva.MultiObjective.Add(new BranchRatioFitness(3.0 / 2));
            eva.MultiObjective.Add(new BranchEntryPointsFitness());

            eva.SampleIndividual = new AdjacencyGraphIndividual(new List <byte>(input.Rooms.Keys), 3, 3);
            eva.HvIndicator      = new BiobjectiveHvIndicator();

            using (StreamWriter file = new StreamWriter(@"C:\Users\Jan\Source\Repos\RoguelikeEva\Results\_out.txt"))
            {
                file.WriteLine("Gen\tHv");
                int solutionNo = 0;

                IEnumerable <Individual> result = eva.Run(e => e.Population.No == 10, 100, file, (writer, gen, hv) =>
                {
                    writer.WriteLine("{0}\t{1}", gen.No, hv);

                    Console.Clear();
                    Console.WriteLine("Current generation: " + gen.No);
                });

                foreach (Individual ind in result)
                {
                    AdjacencyGraphIndividual map = (AdjacencyGraphIndividual)ind;

                    // TODO:
                    // transform "map" to correct MapBlueprint

                    // "correct MapBlueprint".SaveImageToFile(@"C:\Users\Jan\Source\Repos\RoguelikeEva\Results\_RESULT " + solutionNo + ".png", 1536, 1024);
                    map.SaveToFile(@"C:\Users\Jan\Source\Repos\RoguelikeEva\Results\_RESULT " + (solutionNo++) + ".bin");
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// Entry point method
        /// </summary>
        /// <param name="args">Not used</param>
        public static void Main(string[] args)
        {
            Console.WriteLine("Starting algorithm...");
            var algorithm = new EvolutionaryAlgorithm();

            // subscribe to algorithm started (save seed image)
            algorithm.AlgorithmStarted += (s, e) => algorithm.Seed.Save("Seed.bmp");

            // subscribe to epoch done (print results each epoch)
            algorithm.EpochCompleted += (s, e) => PrintEpochResults(algorithm);

            // subscribe to algorithm done even (save result to bitmap)
            algorithm.AlgorithmCompleted += (s, e) => Painter.Paint(algorithm.Population.CalculateFittest()).Save("Fittest.bmp");

            algorithm.Run(() => algorithm.StagnationCount > 10);

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Exemple #9
0
        static void Phase1()
        {
            EvolutionaryAlgorithm eva = new EvolutionaryAlgorithm();

            eva.Operators.Add(new FloorTypeMutation(0.5));
            eva.Operators.Add(new JoinRoomsMutation(0.8));
            eva.Operators.Add(new RemoveRoomMutation(0.8));
            eva.Operators.Add(new FillHoleMutation(1));
            eva.Operators.Add(new ExtendEdgeMutation(1));

            eva.MultiObjective.Add(new AdjacencyFitness());
            eva.MultiObjective.Add(new RoomFitness(20));
            eva.MultiObjective.Add(new SpaceFitness());

            eva.SampleIndividual = new MapBlueprintIndividual(30, 20, 0.5);
            eva.HvIndicator      = new HvSweep3D();
            //eva.MatingSelector = new RouletteWheelSelector();

            using (StreamWriter file = new StreamWriter(@"C:\Users\Jan\Source\Repos\RoguelikeEva\Results\_out.txt"))
            {
                file.WriteLine("Gen\tHv");
                int solutionNo = 0;

                IEnumerable <Individual> result = eva.Run(e => e.Population.No == 10, 100, file, (writer, gen, hv) =>
                {
                    writer.WriteLine("{0}\t{1}", gen.No, hv);

                    Console.Clear();
                    Console.WriteLine("Current generation: " + gen.No);
                });

                foreach (Individual ind in result)
                {
                    MapBlueprintIndividual map = (MapBlueprintIndividual)ind;

                    AddDoors(map.Gene);
                    // TODO: skip map which are not correct (discontinuous)

                    map.Gene.SaveImageToFile(@"C:\Users\Jan\Source\Repos\RoguelikeEva\Results\_RESULT " + solutionNo + ".png", 1536, 1024);
                    map.SaveToFile(@"C:\Users\Jan\Source\Repos\RoguelikeEva\Results\_RESULT " + (solutionNo++) + ".bin");
                }
            }
        }
Exemple #10
0
        public void EvolSearchTravelingSalesman()
        {
            /*int test = 5;
             * object obj = new Object();
             * obj = test;
             * test++;
             * int so;*/


            /*Place place = new Place(10,20);
             * PlaceList list = new PlaceList();
             * list.Add(place);
             * XmlSerializer serializer = new XmlSerializer(typeof(PlaceList));
             * TextWriter writer = new StreamWriter( @"F:\test.xml" );
             * serializer.Serialize( writer, list );
             * writer.Close();*/

            /*TextReader reader = new StreamReader("places.xml");
             * XmlSerializer serializer = new XmlSerializer(typeof(PlaceList));
             * PlaceList list = (PlaceList)serializer.Deserialize(reader);
             * reader.Close();*/

            // http://www.zib.de/groetschel/news/tsp_loesungen_version2.html
            // min: 2069

            PlaceList list = new PlaceList();

            list.Add(new Place(144, 158));
            list.Add(new Place(188, 80));
            list.Add(new Place(190, 134));
            list.Add(new Place(238, 125));
            list.Add(new Place(61, 265));
            list.Add(new Place(175, 205));
            list.Add(new Place(248, 216));
            list.Add(new Place(315, 195));
            list.Add(new Place(303, 205));
            list.Add(new Place(222, 300));
            list.Add(new Place(340, 285));
            list.Add(new Place(69, 399));
            list.Add(new Place(120, 354));
            list.Add(new Place(153, 430));
            list.Add(new Place(250, 472));

            list.Add(new Place(163, 57));
            list.Add(new Place(83, 140));
            list.Add(new Place(210, 104));
            list.Add(new Place(298, 85));
            list.Add(new Place(266, 100));
            list.Add(new Place(100, 235));
            list.Add(new Place(205, 208));
            list.Add(new Place(249, 194));
            list.Add(new Place(359, 205));
            list.Add(new Place(65, 288));

            list.Add(new Place(158, 270));
            list.Add(new Place(186, 254));
            list.Add(new Place(281, 259));
            list.Add(new Place(353, 242));
            list.Add(new Place(131, 321));
            list.Add(new Place(252, 298));
            list.Add(new Place(137, 340));
            list.Add(new Place(52, 363));
            list.Add(new Place(133, 394));
            list.Add(new Place(184, 368));
            list.Add(new Place(240, 384));
            list.Add(new Place(98, 477));
            list.Add(new Place(222, 458));
            list.Add(new Place(325, 441));
            list.Add(new Place(195, 499));


            int countPlaces = list.Count;

            // Anzahl aller Distanzen: ((AnzahlOrte*AnzahlOrte)-AnzahlOrte)/2
            int countDistances = (countPlaces * countPlaces - countPlaces) / 2;

            Matrix distanceMatrix = new Matrix(countPlaces, countPlaces);

            double distance;

            for (int i = 0; i < countPlaces; i++)
            {
                distanceMatrix.SetValue(i, i, 0.0);
                for (int j = i + 1; j < countPlaces; j++)
                {
                    distance = list[i].GetDistance(list[j]);
                    distanceMatrix.SetValue(i, j, distance);
                    distanceMatrix.SetValue(j, i, distance);
                }
            }

            // Distancematrix kann als static zugewiesen werden, da sie f¸r alle solutions gleich ist
            TravelingSalesmanSolution.DistanceMatrix = distanceMatrix;

            TravelingSalesmanProblem problem = new TravelingSalesmanProblem(10, 40);

            EvolutionaryAlgorithm evol = new EvolutionaryAlgorithm(problem);

            //evol.Run();



            // Anlegen von 10 Ausgangsindividuen

            /*TravelingSalesmanSolution[] tspList = new TravelingSalesmanSolution[10];
             *
             * // Speicher reservieren
             * for(int i=0; i<tspList.GetLength(0); i++)
             * {
             *  tspList[i] = new TravelingSalesmanSolution();
             * }*/

            /*Random random = new Random(unchecked((int)DateTime.Now.Ticks));
             * int countPlaces = 100;
             *
             * // Anzahl aller Distanzen: ((AnzahlOrte*AnzahlOrte)-AnzahlOrte)/2
             * int countDistances = (countPlaces*countPlaces-countPlaces)/2;
             * int[] distanceList = new int[countDistances];
             * Matrix distanceMatrix = new Matrix(countPlaces, countPlaces);
             *
             * for (int i=0; i<distanceList.GetLength(0); i++)
             * {
             *  distanceList[i] = Convert.ToInt32(Math.Round(random.NextDouble()*500));
             * }
             *
             * int index = 0;
             * for (int i=0; i<countPlaces; i++)
             * {
             *  distanceMatrix.SetValue(i, i, 0);
             *  for (int j=i+1;j<countPlaces;j++)
             *  {
             *      distanceMatrix.SetValue(i, j, distanceList[index]);
             *      distanceMatrix.SetValue(j, i, distanceList[index]);
             *      index++;
             *  }
             * }
             *
             * TravelingSalesmanSolution.DistanceMatrix = distanceMatrix;
             *
             * TravelingSalesmanSolution[] tspList = new TravelingSalesmanSolution[10];
             * for(int i=0; i<tspList.GetLength(0); i++)
             * {
             *  tspList[i] = new TravelingSalesmanSolution();
             * }
             *
             * int a = 10;*/
        }
        /// <summary>
        /// Use the best optimized agents to play StarCraft Broodwar (using the fittest unit agent optimized properties loaded from an XML file).
        /// </summary>
        /// <param name="numberOfRestarts"></param>
        /// <param name="populationSize"></param>
        /// <param name="gameSpeed"></param>
        public Trainer(int numberOfRestarts, int populationSize, int gameSpeed)
        {
            _numberOfRepopulations = numberOfRestarts;
            _populationSize = populationSize;
            _unitAgentXMLFileName = "";

            var xmlFileNames = new List<String>() {"Terran_Goliath.xml", "Terran_Vulture.xml", "Terran_SiegeTank.xml" };

            _gameSpeed = gameSpeed;

            _ea = new EvolutionaryAlgorithm(_populationSize, xmlFileNames);

            PlayWithoutTraining(_gameSpeed, numberOfRestarts, true);//loadAgent: TRUE: CALL PLAY and use the current best optimized XMLfile, else use test method to load some standard values.
        }
        /// <summary>
        /// Use the best optimized agent to play StarCraft Broodwar (using the fittest unit agent optimized properties loaded from an XML file).
        /// </summary>
        /// <param name="numberOfRestarts"></param>
        /// <param name="populationSize"></param>
        /// <param name="unitAgentXMLFileName"></param>
        /// <param name="gameSpeed"></param>
        public Trainer(int numberOfRestarts, int populationSize, String unitAgentXMLFileName, int gameSpeed)
        {
            _numberOfRepopulations = numberOfRestarts;
            _populationSize = populationSize;
            _unitAgentXMLFileName = unitAgentXMLFileName;

            _gameSpeed = gameSpeed;

            _ea = new EvolutionaryAlgorithm(_populationSize, _unitAgentXMLFileName);

             PlayWithoutTraining(_gameSpeed, numberOfRestarts, true);//loadAgent: TRUE: CALL PLAY and use the current best optimized XMLfile, else use test method to load some standard values.
        }
        /// <summary>
        /// Create a population of existing chromosomes from a file with a possible mixture of new random chromosomes.
        /// </summary>
        /// <param name="totalNumberOfRepopulations"></param>
        /// <param name="startGenerationOn"></param>
        /// <param name="percentOfOpPropsToLoad"></param>
        /// <param name="populationSize"></param>
        /// <param name="numberOfTrials"></param>
        /// <param name="unitAgentXMLFileName"></param>
        /// <param name="gameSpeed"></param>
        /// <param name="nuberOfCrossOvers">Make one point cross over on the specified number of best candidates, and randomly pick the half of the new chromosomes.</param>
        public Trainer(int totalNumberOfRepopulations, int startGenerationOn, int percentOfOpPropsToLoad, int populationSize, int numberOfTrials, String unitAgentXMLFileName, int gameSpeed, int nuberOfCrossOvers)
        {
            if (totalNumberOfRepopulations > startGenerationOn)
                _numberOfRepopulations = totalNumberOfRepopulations - startGenerationOn;
            else
            {
                Logger.Logger.AddAndPrint("numberOfRepopulations needs to be bigger than startGenerationOn.");
                throw new Exception("numberOfRepopulations needs to be bigger than startGenerationOn.");
            }
            
            _populationSize = populationSize;
            _numberOfTrials = numberOfTrials;
            _nuberOfCrossOvers = nuberOfCrossOvers;
            _unitAgentXMLFileName = unitAgentXMLFileName;
            _startGenerationOn = startGenerationOn;

            _gameSpeed = gameSpeed;
            _ea = new EvolutionaryAlgorithm(_populationSize, percentOfOpPropsToLoad, _unitAgentXMLFileName);
            
             Train();
        }
Exemple #14
0
        private void SaveSerializedCanvas(EvolutionaryAlgorithm algorithm, string fileName = "saves/Suspended.canvas")
        {
            var bytes = algorithm.Population.CalculateFittest().AsByteArray();

            File.WriteAllBytes(fileName, bytes);
        }
Exemple #15
0
        /// <summary>
        /// Called when run button is clicked
        /// </summary>
        /// <param name="sender">Event initiator</param>
        /// <param name="e">Event arguments</param>
        private async void Run_Click(object sender, RoutedEventArgs e)
        {
            if (SeedImage.Source == null)
            {
                Label_Status.Content = "No image set!";
                return;
            }

            if (ctc != null)
            {
                ctc.Cancel();
                ctc = null;
                Button_Run.Content = "Run";
            }
            else
            {
                Button_Run.Content = "Stop";
                ctc = new CancellationTokenSource();
                saveWhileRunning = CheckBox_SaveWhileRunning.IsChecked == true;


                var algorithm = new EvolutionaryAlgorithm()
                {
                    CanvasWidth          = int.Parse(TextBox_CanvasSizeX.Text),
                    CanvasHeight         = int.Parse(TextBox_CanvasSizeY.Text),
                    CanvasCount          = int.Parse(TextBox_PopulationSize.Text),
                    PolygonCount         = int.Parse(TextBox_PolygonCount.Text),
                    PolygonEdgeCount     = int.Parse(((ComboBoxItem)ComboBox_PolygonType.SelectedItem).Tag.ToString()),
                    WeightPositionChange = double.Parse(this.TextBox_PositionChange.Text),
                    WeightColorChange    = double.Parse(this.TextBox_ColorChange.Text),
                    WeightIndexChange    = double.Parse(this.TextBox_ZIndexChange.Text),
                    WeightRandomChange   = double.Parse(this.TextBox_RandomChange.Text),
                    Seed = ToBitmap((BitmapImage)SeedImage.Source)
                };

                // If a saves/Serialized.canvas exists, load it.
                if (CheckBox_LoadSusupended.IsChecked == true)
                {
                    LoadSerialzedCanvasIfExists(algorithm);
                }

                // Get user defined values from the GUI where the checkbox/textbox structure applies
                int?   maxRuntime    = GetIntIfFilledIn(CheckBox_MaxRuntime, TextBox_MaxRuntime);
                int?   maxEpochs     = GetIntIfFilledIn(CheckBox_MaxEpochs, TextBox_MaxEpochs);
                int?   maxStagnation = GetIntIfFilledIn(Checkbox_MaxStagnation, TextBox_MaxStagnation);
                double?minFitness    = GetDoubleIfFilledIn(Checkbox_MinFitness, Textbox_MinFitness);

                try
                {
                    algorithm.DeleteStatsFileIfExists();

                    algorithm.AlgorithmStarted += (s, args) => Dispatcher.Invoke(new Action(() =>
                    {
                        try
                        {
                            algorithm.Seed.Save("img/Seed.bmp");
                        }
                        catch (Exception)
                        {
                            // do nothing
                        }
                    }));
                    algorithm.EpochCompleted += (s, args) => Dispatcher.Invoke(new Action(() =>
                    {
                        if (MainImage.Source == null)
                        {
                            return;
                        }

                        GenerateDiffImageAndSave(algorithm);
                    }));
                    algorithm.EpochCompleted += (s, args) => Dispatcher.Invoke(new Action(() => Label_Similar.Content = string.Format("{0:P2}", algorithm.Fitness)));
                    algorithm.EpochCompleted += (s, args) => Dispatcher.Invoke(new Action(() =>
                    {
                        if (algorithm.Epoch % 1000 == 1)
                        {
                            Painter.Paint(algorithm.Population.CalculateFittest()).Save(string.Format("img/Epoch_{0}K.bmp", algorithm.Epoch / 1000));
                        }
                    }));

                    algorithm.EpochCompleted += (s, args) => Dispatcher.Invoke(new Action(() => SaveBitmap(Painter.Paint(algorithm.Population.CalculateFittest()), MainImage)));
                    algorithm.EpochCompleted += (s, args) => Dispatcher.Invoke(new Action(() => Label_Status.Content = string.Format("Epoch:      {0, 11}\nStagnation: {2, 11}\nFitness:    {1,11:N6}\nRuntime:     {3:d\\.hh\\:mm\\:ss}", algorithm.Epoch, algorithm.Fitness, algorithm.StagnationCount, algorithm.TimeRan)));
                    algorithm.EpochCompleted += (s, args) => Dispatcher.Invoke(new Action(() =>
                    {
                        if (saveWhileRunning)
                        {
                            if (algorithm.Epoch % 1000 == 0)
                            {
                                SaveSerializedCanvas(algorithm);
                            }
                            if (algorithm.Epoch % 100000 == 0)
                            {
                                SaveSerializedCanvas(algorithm, string.Format("saves/Epoch_{0}k", algorithm.Epoch));
                            }
                        }
                    }));
                    algorithm.AlgorithmCompleted += (s, args) => Dispatcher.Invoke(new Action(() =>
                    {
                        Painter.Paint(algorithm.Population.CalculateFittest()).Save(string.Format("img/Epoch_{0}K{1}.bmp", algorithm.Epoch / 1000, algorithm.Epoch % 1000));
                        if (saveWhileRunning)
                        {
                            SaveSerializedCanvas(algorithm);
                        }

                        Button_Run.Content    = "Run";
                        Label_Status.Content += "\nFinished";
                        ctc = null;
                    }));

                    await algorithm.RunAsync(() => StopCondition(algorithm, maxRuntime, maxEpochs, maxStagnation, minFitness), ctc.Token);
                }
                catch (OperationCanceledException)
                {
                    Painter.Paint(algorithm.Population.CalculateFittest()).Save(string.Format("img/Epoch_{0}K{1}.bmp", algorithm.Epoch / 1000, algorithm.Epoch % 1000));
                    if (saveWhileRunning)
                    {
                        SaveSerializedCanvas(algorithm);
                    }

                    algorithm.Matlabify();

                    Label_Status.Content += "\nCanceled";
                }
            }
        }