Exemple #1
0
        /// <summary>
        /// Default EA settings
        /// </summary>
        /// <param name="logger">logger to log the settings</param>
        /// <returns>configuration of EA</returns>
        private EvolutionaryAlgorithm InitializeEVA(Logger logger, Random rng)
        {
            EvolutionaryAlgorithm ea;

            //Set the options for the evolutionary algorithm
            ea = new EvolutionaryAlgorithm();
            // Fitness function
            if (Properties.Settings.Default.Task == "spanner")
            {
                ea.SetFitnessFunction(new SpannerFitness(edgeCount));
                logger.Log(Logger.Level.SETTINGS, "Spanner");
                task = "spanner";
            }
            else if (Properties.Settings.Default.Task == "degree")
            {
                ea.SetFitnessFunction(new MaxDegreeFitness(cubeDimension));
                logger.Log(Logger.Level.SETTINGS, "MaxDegree");
                task = "degree";
            }
            else
            {
                ea.SetFitnessFunction(new EdgeDisjointSpanner(cubeDimension));
                logger.Log(Logger.Level.SETTINGS, "EDS");
                task = "eds";
            }
            // Replacement
            ea.SetReplacement(new ChildrenOnlyReplacement());
            //ea.SetReplacement(new MergingReplacement());
            //ea.SetReplacement(new PercentageReplacement(20));
            // Selectors
            //ea.AddMatingSelector(new RouletteWheelSelector());
            ea.AddMatingSelector(new TournamentSelector(tourWeakerProb, competitors, rng));
            //ea.AddMatingSelector(new BoltzmannTournamentSelector(maxGen));
            //ea.AddMatingSelector(new BoltzmannRouletteWheelSelector(maxGen));
            // Operators
            ea.AddOperator(new SubcubeSwapXOver(xoverProb, subcubeSize, rng));
            //ea.AddOperator(new NPointXOver(xoverProb, nPoints));
            //ea.AddOperator(new SimpleRepairEdgeMutation(mutProb, mutRepair));
            //ea.AddOperator(new CleverRepairEdgeMutation(mutProb / 100, mutRepair));
            ea.AddOperator(new FlipEdgeMutation(mutProb, mutProbPerBit, rng));
            ea.AddOperator(new SubcubeTranslationMutation(mutProb, 2, rng));
            ea.AddOperator(new SubcubeRotationMutation(mutProb, 2, rng));
            //ea.AddEnvironmentalSelector(new RouletteWheelSelector());
            ea.AddEnvironmentalSelector(new TournamentSelector(tourWeakerProb, competitors, rng));
            //ea.AddEnvironmentalSelector(new BoltzmannTournamentSelector(maxGen));
            //ea.AddEnvironmentalSelector(new BoltzmannRouletteWheelSelector(maxGen));

            ea.SetElite(eliteSize);

            return(ea);
        }
Exemple #2
0
        /// <summary>
        /// Loads EA settings from a config file
        /// </summary>
        /// <param name="logger">logger to log the configuration</param>
        /// <returns>configuration of EA</returns>
        private EvolutionaryAlgorithm LoadEVA(Logger logger, Random rnd)
        {
            EvolutionaryAlgorithm ea = new EvolutionaryAlgorithm();

            string[] lines = new string[1];
            try
            {
                lines = System.IO.File.ReadAllLines(@"./../config.txt");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }

            for (int i = 0; i < lines.Length; i++)
            {
                string thisLine = lines[i];
                // commentary
                if (thisLine.Length < 1 || thisLine[0] == '#')
                {
                    continue;
                }
                var line = thisLine.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                switch (line[0])
                {
                // selection
                case "RouletteWheel":
                    if (line.GetOrElse(1, "") == "ENV" || line.GetOrElse(2, "") == "ENV")
                    {
                        ea.AddEnvironmentalSelector(new RouletteWheelSelector(rnd));
                    }
                    if (line.GetOrElse(1, "") == "MAT" || line.GetOrElse(2, "") == "MAT")
                    {
                        ea.AddMatingSelector(new RouletteWheelSelector(rnd));
                    }
                    if (line.Length < 2)
                    {
                        ea.AddEnvironmentalSelector(new RouletteWheelSelector(rnd));
                        ea.AddMatingSelector(new RouletteWheelSelector(rnd));
                    }
                    break;

                case "Tournament":
                    if (line.GetOrElse(2, "") == "ENV" || line.GetOrElse(3, "") == "ENV")
                    {
                        ea.AddEnvironmentalSelector(new TournamentSelector(
                                                        tourWeakerProb,
                                                        line.ParseIntOrElse(1, Properties.Settings.Default.TournamentCompetitors),
                                                        rnd));
                    }
                    if (line.GetOrElse(2, "") == "MAT" || line.GetOrElse(3, "") == "MAT")
                    {
                        ea.AddMatingSelector(new TournamentSelector(
                                                 tourWeakerProb,
                                                 line.ParseIntOrElse(1, Properties.Settings.Default.TournamentCompetitors),
                                                 rnd));
                    }
                    if (line.Length < 3)
                    {
                        ea.AddEnvironmentalSelector(new TournamentSelector(
                                                        tourWeakerProb,
                                                        line.ParseIntOrElse(1, Properties.Settings.Default.TournamentCompetitors),
                                                        rnd));
                        ea.AddMatingSelector(new TournamentSelector(
                                                 tourWeakerProb,
                                                 line.ParseIntOrElse(1, Properties.Settings.Default.TournamentCompetitors),
                                                 rnd));
                    }
                    break;

                case "BoltzmannTournament":
                    if (line.GetOrElse(2, "") == "ENV" || line.GetOrElse(3, "") == "ENV")
                    {
                        ea.AddEnvironmentalSelector(new BoltzmannTournamentSelector(maxGen,
                                                                                    tourWeakerProb,
                                                                                    line.ParseIntOrElse(1, Properties.Settings.Default.TournamentCompetitors),
                                                                                    rnd));
                    }
                    if (line.GetOrElse(2, "") == "MAT" || line.GetOrElse(3, "") == "MAT")
                    {
                        ea.AddMatingSelector(new BoltzmannTournamentSelector(maxGen,
                                                                             tourWeakerProb,
                                                                             line.ParseIntOrElse(1, Properties.Settings.Default.TournamentCompetitors),
                                                                             rnd));
                    }
                    if (line.Length < 3)
                    {
                        ea.AddEnvironmentalSelector(new BoltzmannTournamentSelector(maxGen,
                                                                                    tourWeakerProb,
                                                                                    line.ParseIntOrElse(1, Properties.Settings.Default.TournamentCompetitors),
                                                                                    rnd));
                        ea.AddMatingSelector(new BoltzmannTournamentSelector(maxGen,
                                                                             tourWeakerProb,
                                                                             line.ParseIntOrElse(1, Properties.Settings.Default.TournamentCompetitors),
                                                                             rnd));
                    }
                    break;

                case "BoltzmannRouletteWheel":
                    if (line.GetOrElse(1, "") == "ENV" || line.GetOrElse(2, "") == "ENV")
                    {
                        ea.AddEnvironmentalSelector(new BoltzmannRouletteWheelSelector(maxGen, rnd));
                    }
                    if (line.GetOrElse(1, "") == "MAT" || line.GetOrElse(2, "") == "MAT")
                    {
                        ea.AddMatingSelector(new BoltzmannRouletteWheelSelector(maxGen, rnd));
                    }
                    if (line.Length < 2)
                    {
                        ea.AddEnvironmentalSelector(new BoltzmannRouletteWheelSelector(maxGen, rnd));
                        ea.AddMatingSelector(new BoltzmannRouletteWheelSelector(maxGen, rnd));
                    }
                    break;

                case "ChildrenOnly":
                    ea.SetReplacement(new ChildrenOnlyReplacement());
                    logger.Log(Logger.Level.SETTINGS, "ChildrenOnly Replacement");
                    break;

                case "Merging":
                    ea.SetReplacement(new MergingReplacement());
                    logger.Log(Logger.Level.SETTINGS, "Merging Replacement");
                    break;

                case "Percentage":
                    ea.SetReplacement(new PercentageReplacement(
                                          line.ParseIntOrElse(1, Properties.Settings.Default.ReplacementPercentage)));
                    logger.Log(Logger.Level.SETTINGS, "Percentage Replacement");
                    break;

                // operators
                case "SubcubeSwap":
                    ea.AddOperator(
                        new SubcubeSwapXOver(
                            line.ParseDoubleOrElse(1, Properties.Settings.Default.P_CrossoverProbability),
                            line.ParseIntOrElse(2, Properties.Settings.Default._SubcubeSize),
                            rnd));
                    break;

                case "N-Point":
                    ea.AddOperator(
                        new NPointXOver(
                            line.ParseDoubleOrElse(1, Properties.Settings.Default.P_CrossoverProbability),
                            line.ParseIntOrElse(2, Properties.Settings.Default.NPoints),
                            rnd));
                    break;

                case "CleverRepair":
                    ea.AddOperator(
                        new CleverRepairEdgeMutation(
                            line.ParseDoubleOrElse(1, Properties.Settings.Default.P_MutationProbability),
                            rnd));
                    break;

                case "SimpleRepair":
                    ea.AddOperator(
                        new SimpleRepairEdgeMutation(
                            line.ParseDoubleOrElse(1, Properties.Settings.Default.P_MutationProbability),
                            line.ParseDoubleOrElse(2, Properties.Settings.Default.P_MutationPerEdgeProbability),
                            rnd));
                    break;

                case "Translation":
                    ea.AddOperator(
                        new SubcubeTranslationMutation(
                            line.ParseDoubleOrElse(1, Properties.Settings.Default.P_MutationProbability),
                            line.ParseIntOrElse(2, Properties.Settings.Default._SubcubeSize),
                            rnd));
                    break;

                case "Rotation":
                    ea.AddOperator(
                        new SubcubeRotationMutation(
                            line.ParseDoubleOrElse(1, Properties.Settings.Default.P_MutationProbability),
                            line.ParseIntOrElse(2, Properties.Settings.Default._SubcubeSize),
                            rnd));
                    break;

                case "FlipEdge":
                    ea.AddOperator(
                        new FlipEdgeMutation(
                            line.ParseDoubleOrElse(1, Properties.Settings.Default.P_MutationProbability),
                            line.ParseDoubleOrElse(2, Properties.Settings.Default.P_MutationPerEdgeProbability),
                            rnd));
                    break;

                // fitness
                case "Spanner":
                    ea.SetFitnessFunction(new SpannerFitness(edgeCount));
                    logger.Log(Logger.Level.SETTINGS, "Spanner");
                    task = "spanner";
                    break;

                case "Degree":
                    ea.SetFitnessFunction(new MaxDegreeFitness(cubeDimension));
                    logger.Log(Logger.Level.SETTINGS, "MaxDegree");
                    task = "degree";
                    break;

                case "EdgeDisjoint":
                    ea.SetFitnessFunction(new EdgeDisjointSpanner(cubeDimension));
                    logger.Log(Logger.Level.SETTINGS, "EDS");
                    maxColours = line.ParseIntOrElse(1, cubeDimension / 2);
                    task       = "eds";
                    break;

                default:
                    break;
                }
            }
            return(ea);
        }
Exemple #3
0
        /// <summary>
        /// GA running method
        /// </summary>
        /// <returns>best computed individual</returns>
        public Individual RunIt()
        {
            if (!Settings.parallel)
            {
                Console.WriteLine("Starting run no. " + (number + 1));
                Console.WriteLine("Initializing run no. " + (number + 1));
            }

            Stopwatch sw = Stopwatch.StartNew();
            //Set the rng seed
            GraphInfo graph = GraphInfo.GetInstance(s.cubeDimension);
            Tools     tools = Tools.GetInstance(s.cubeDimension);

            rng = new Random(number);
            logger.Log(s);
            ea = s.GetEVA(logger, rng);
            foreach (var op in ea.GetOperators())
            {
                logger.Log(Logger.Level.SETTINGS, op.ToLog());
            }
            foreach (var se in ea.GetMating())
            {
                logger.Log(Logger.Level.SETTINGS, se.ToLog() + " MAT");
            }
            foreach (var se in ea.GetEnvironmental())
            {
                logger.Log(Logger.Level.SETTINGS, se.ToLog() + " ENV");
            }

            //Create new population
            Population pop = new Population();

            pop.SetPopulationSize(s.popSize);
            pop.SetSampleIndividual(graph);
            pop.CreateRandomInitialPopulation(rng);

            if (!Settings.parallel)
            {
                Console.WriteLine("Finished in {0:f2} seconds", sw.Elapsed.TotalSeconds);
            }
            logger.Log(Logger.Level.INFO, "Initialization finished in " +
                       String.Format("{0:f2}", sw.Elapsed.TotalSeconds) + " seconds");

            //Run the algorithm
            if (!Settings.parallel || number == 0)
            {
                Console.WriteLine("Running run no. " + (number + 1));
            }
            try
            {
                for (int i = 0; i < s.maxGen; i++)
                {
                    sw.Restart();
                    Program.localDetourSpanners = 0;
                    //Make one generation
                    ea.Evolve(pop);
                    List <Individual> sorted = pop.GetSortedIndividuals();
                    //Log the best individual to console.
                    if ((i + 1) % Settings.showGap == 0 && (!Settings.parallel || number == 0))
                    {
                        int idx = 0;
                        while (idx < s.popSize && sorted[idx].Is_3_Spanner(false) < 1)
                        {
                            idx++;
                        }
                        if (idx >= s.popSize)
                        {
                            idx = 0;
                        }
                        Console.Write("Gen: " + (i + 1));
                        Console.Write(" obj: " + sorted[idx].GetObjectiveValue() + " at " + idx);
                        if (Settings.task == "eds")
                        {
                            Console.Write(" tc: " + sorted[idx].GetColourCount());
                        }
                        if (Settings.task != "eds")
                        {
                            Console.Write(" fit: {0:f0}", sorted[0].GetFitnessValue());
                        }
                        else
                        {
                            Console.Write(" fit: {0:f3}", sorted[0].GetFitnessValue());
                            Console.Write(" comps: ");
                            for (int j = 0; j < Settings.maxColours; j++)
                            {
                                Console.Write(sorted[0].CountComponents((byte)(j + 1)));
                                Console.Write(" ");
                            }
                        }
                        Console.Write(" 3-s: {0:f2} %", (float)(Program.localDetourSpanners * 100.0 / s.popSize));
                        Console.Write(" avg: {0:f0}", pop.GetAverage());
                        Console.Write(" med: {0:f0}", sorted[s.popSize / 2].GetFitnessValue());
                        Console.WriteLine();
                    }

                    logger.Log(pop, sorted, i);

                    for (int j = 0; j < sorted.Count; j++)
                    {
                        //Console.WriteLine(sorted[j].ToString());
                        if (j < s.popSize * s.eliteSize)
                        {
                            sorted[j].elite = true;
                        }
                        else
                        {
                            sorted[j].elite = false;
                        }
                    }
                }
                if (!Settings.parallel)
                {
                    Console.WriteLine();
                }
                Individual bestInd;

                //Console.ReadLine();

                for (int j = 0; j < pop.GetPopulationSize(); j++)
                {
                    if ((pop.GetSortedIndividuals()[j]).Is_3_Spanner(false) == 1)
                    {
                        bestInd = pop.GetSortedIndividuals()[j];
                        logger.Log(bestInd);
                        return(bestInd);
                    }
                }
                bestInd = pop.GetSortedIndividuals()[0];
                logger.Log(bestInd);
                return(bestInd);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace);
            }
            return(null);
        }