private static void Main(string[] args)
        {
            const int populationSize = 100;

            //get our cities
            var cities = CreateCities().ToList();

            //Each city is an object the chromosome is a special case as it needs
            //to contain each city only once. Therefore, our chromosome will contain
            //all the cities with no duplicates

            //we can create an empty population as we will be creating the
            //initial solutions manually.
            var population = new Population();

            //create the chromosomes
            for (var p = 0; p < populationSize; p++)
            {
                var chromosome = new Chromosome();
                foreach (var city in cities)
                {
                    var gene = new Gene(city);
                    chromosome.Genes.Add(gene);
                }

                var rnd = GAF.Threading.RandomProvider.GetThreadRandom();
                chromosome.Genes.ShuffleFast(rnd);

                population.Solutions.Add(chromosome);
            }

            //create the elite operator
            var elite = new Elite(5);

            //create the crossover operator
            var crossover = new Crossover(0.9)
            {
                CrossoverType = CrossoverType.DoublePointOrdered
            };

            //create the mutation operator
            var mutate = new SwapMutate(0.2);

            //create the GA
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            //hook up to some useful events
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            //add the operators
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            //run the GA
            ga.Run(Terminate);

            Console.Read();
        }
        private static void SetupGeneticAlgorithm()
        {
            //create the elite operator
            var elite = new Elite(5);

            //create the crossover operator
            var crossover = new Crossover(0.8)
            {
                CrossoverType = CrossoverType.SinglePoint //SinglePoint or DoublePoint
            };

            //create the mutation operator
            var mutate = new SwapMutate(0.02);

            //create the GA
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            //hook up to some useful events
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            //add the operators
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            //run the GA
            ga.Run(Terminate);
        }
Ejemplo n.º 3
0
        private static void Main(string[] args)
        {
            //get our cities
            _cities = CreateCities().ToList();

            //Each city can be identified by an integer within the range 0-15
            //our chromosome is a special case as it needs to contain each city
            //only once. Therefore, our chromosome will contain all the integers
            //between 0 and 15 with no duplicates

            //we can create an empty population as we will be creating the
            //initial solutions manually.
            var population = new Population();

            //create the chromosomes
            for (var p = 0; p < 5000; p++)
            {
                var chromosome = new Chromosome();
                for (var g = 0; g < 16; g++)
                {
                    chromosome.Genes.Add(new Gene(g));
                }

                var rnd = GAF.Threading.RandomProvider.GetThreadRandom();
                chromosome.Genes.ShuffleFast(rnd);

                population.Solutions.Add(chromosome);
            }

            //create the elite operator
            var elite = new Elite(15);

            //create the crossover operator
            var crossover = new Crossover(0.7)
            {
                CrossoverType = CrossoverType.DoublePointOrdered
            };

            //create the mutation operator
            var mutate = new SwapMutate(0.02);

            //create the GA
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            //hook up to some useful events
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            //add the operators
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            //run the GA
            ga.Run(Terminate);

            Console.Read();
        }
        public Board GetBoardSuggestion()
        {
            var population = new Population();

            var randomGen = new Random();

            //create the chromosomes
            for (var p = 0; p < 100; p++)
            {
                var chromosome = new Chromosome();
                for (var g = 0; g < this.tasks.Length; g++)
                {
                    chromosome.Genes.Add(new Gene(randomGen.Next(0, this.users.Length)));
                }

                chromosome.Genes.ShuffleFast();

                population.Solutions.Add(chromosome);
            }

            //create the elite operator
            var elite = new Elite(5);

            //create the crossover operator
            var crossover = new Crossover(0.8)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            //create the mutation operator
            var mutate = new SwapMutate(0.02);

            //create the GA
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            //hook up to some useful events
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            //add the operators
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            this.watch.Start();

            //run the GA
            ga.Run(Terminate);

            var suggestedBoard = createBoardFromChromose(ga.Population.GetTop(1).First());
            var doneTasks      = board.tasks.Where(t => t.status.Equals("done"));

            board.tasks = suggestedBoard.tasks;
            board.tasks.AddRange(doneTasks);

            return(board);
        }
Ejemplo n.º 5
0
        private static void Main(string[] args)
        {
            const int    populationSize       = 100;
            const int    elitismPercentage    = 5;
            const double crossoverProbability = 0.8;
            const double mutationProbability  = 0.02;

            // Get the cities
            var cities = Helper.CreateCities();

            // Initialize a population
            var population = new Population();

            // Create the chromosomes
            for (var p = 0; p < populationSize; p++)
            {
                var chromosome = new Chromosome();
                foreach (var city in cities)
                {
                    chromosome.Genes.Add(new Gene(city));
                }

                chromosome.Genes.ShuffleFast();
                population.Solutions.Add(chromosome);
            }

            // Create the elite operator
            var elite = new Elite(elitismPercentage);

            // Create the crossover operator
            var crossover = new Crossover(crossoverProbability)
            {
                CrossoverType = CrossoverType.DoublePointOrdered
            };

            // Create the mutation operator
            var mutate = new SwapMutate(mutationProbability);

            // Create the GA
            var ga = new GeneticAlgorithm(population, Helper.CalculateFitness);

            // Hook up to some useful events
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            // Add the operators
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            // Run the GA
            ga.Run(Helper.Terminate);

            // Finalize the program
            Helper.PrintEnd();
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            // Initialize the game table, matches and distances
            WorldCupChronogram.Initialize();
            Distances.Initialize();

            // Population, with a chromossome length
            var population = new Population(CHROMOSOME_SIZE);

            // Random seed
            var random = new Random();

            // Initialize the population
            for (int i = 0; i < INITIAL_POPULATION_SIZE; i++)
            {
                var chromossome = new Chromosome();
                for (int j = 0; j < CHROMOSOME_SIZE; j++)
                {
                    //  Somedays have more or less games
                    var maxGamesInDays = WorldCupChronogram.Days[j].NumberOfGames;

                    var gene = new Gene(random.Next(maxGamesInDays));

                    chromossome.Add(gene);
                }

                population.Solutions.Add(chromossome);
            }

            // Elite operator
            var elite = new Elite(ETILISM);

            // Crossover operator
            var crossover = new Crossover(CROSSOVER_PROBABILITY);

            // Mutation operador
            var mutate = new SwapMutate(MUTATION_PROBABILITY);

            // GA
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            // Add operators
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            // Handlers
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            ga.Run(Terminate);


            Console.ReadLine();
        }
Ejemplo n.º 7
0
        public static int[,] Generate()
        {
            const int populationSize = 200;

            var population = new Population();

            Random random = new Random();

            boardSize    = 4;
            int[,] board = new int[boardSize, boardSize];
            for (var i = 0; i < boardSize; i++)
            {
                for (var j = 0; j < boardSize; j++)
                {
                    board[i, j] = random.Next(0, 3);
                }
            }

            //start point and end point
            board[0, 0] = 2;
            board[boardSize - 1, boardSize - 1] = 0;

            for (var p = 0; p < populationSize; p++)
            {
                var chromosome = new Chromosome();
                foreach (var field in board)
                {
                    chromosome.Genes.Add(new Gene(field));
                }

                population.Solutions.Add(chromosome);
            }

            var elite = new Elite(10);

            var crossover = new Crossover(0.8)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            var mutate = new SwapMutate(0.1);

            var ga = new GeneticAlgorithm(population, CalculateFitness);

            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            ga.Run(Terminate);

            return(chromosome2Board(ga.Population.GetTop(1)[0]));
        }
Ejemplo n.º 8
0
        private static void Main(string[] args)
        {
            const int populationSize = 100;

            //get our cities
            var nodes = CreateNodes().ToList();

            var population = new Population();

            //create the chromosomes
            for (var p = 0; p < populationSize; p++)
            {
                var chromosome = new Chromosome();
                foreach (var node in nodes)
                {
                    chromosome.Genes.Add(new Gene(node));
                }

                var rnd = GAF.Threading.RandomProvider.GetThreadRandom();
                chromosome.Genes.ShuffleFast(rnd);

                population.Solutions.Add(chromosome);
            }

            //create the elite operator
            var elite = new Elite(5);

            //create the crossover operator
            var crossover = new Crossover(0.8)
            {
                CrossoverType = CrossoverType.DoublePointOrdered
            };

            //create the mutation operator
            var mutate = new SwapMutate(0.02);

            //create the GA
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            //hook up to some useful events
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            //add the operators
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            //run the GA
            ga.Run(Terminate);

            Console.Read();
        }
Ejemplo n.º 9
0
        public Cut[] getBestOrder(Cut[] cuts)
        {
            const double crossoverProbability = 0.65;
            const double mutationProbability  = 0.08;
            const int    elitismPercentage    = 5;

            bestOrder = new Cut[cuts.Length];
            var population = new Population();

            //create the chromosomes
            for (var p = 0; p < 100; p++)
            {
                var chromosome = new Chromosome();
                foreach (var cut in cuts)
                {
                    chromosome.Genes.Add(new Gene(cut));
                }

                //chromosome.Genes.ShuffleFast;
                population.Solutions.Add(chromosome);
            }
            //create the elite operator
            var elite = new Elite(5);

            //create the crossover operator
            var crossover = new Crossover(0.8)
            {
                CrossoverType = CrossoverType.DoublePointOrdered
            };

            //create the mutation operator
            var mutate = new SwapMutate(0.1);

            //create the GA
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            //hook up to some useful events
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            //add the operators
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            //run the GA
            ga.Run(Terminate);
            return(bestOrder);
        }
    public static void geneticAlgorithm(object sender, EventArgs e, Label totalPrice, Label totalDistance, Label totalChanges, Label orderOfDests)
    {
        var population = new Population();

        for (var p = 0; p < globals.chromosomeLength; p++)
        {
            var chromosome = new Chromosome();
            for (var g = 0; g < globals.chromosomeLength; g++)
            {
                chromosome.Genes.Add(new Gene(g));
            }
            chromosome.Genes.ShuffleFast();
            population.Solutions.Add(chromosome);
        }

        var elite = new Elite(8);

        var crossover = new Crossover(0.8)
        {
            CrossoverType = CrossoverType.DoublePointOrdered
        };

        var mutate = new SwapMutate(0.04);

        var ga = new GeneticAlgorithm(population, objectiveValue);

        ga.OnRunComplete += ga_OnRunComplete;

        ga.Operators.Add(elite);
        ga.Operators.Add(crossover);
        ga.Operators.Add(mutate);

        ga.Run(Terminate);

        globals.order = String.Join(",", globals.orderOfDestinations.ToArray());

        totalPrice.Text    = Convert.ToString(globals.totalPrice);
        totalDistance.Text = Convert.ToString(globals.totalDistance);
        totalChanges.Text  = Convert.ToString(globals.totalChanges);
        orderOfDests.Text  = Convert.ToString(globals.order);

        if (globals.errorOutput == true)
        {
            _Default form1 = new _Default();

            form1.ErrorMessage();
        }
    }
Ejemplo n.º 11
0
        static void yMain(string[] args)
        {
            int    populationSize       = 100;
            double crossoverProbability = 0.65;
            double mutationProbability  = 0.02;
            int    elitismPercentage    = 5;

            var cities = CreateCities().ToList();

            Population population = new Population();

            for (var p = 0; p < populationSize; p++)
            {
                Chromosome chromosome = new Chromosome();
                foreach (City city in cities)
                {
                    chromosome.Genes.Add(new Gene(city));
                }

                var rnd = GAF.Threading.RandomProvider.GetThreadRandom();
                chromosome.Genes.ShuffleFast(rnd);

                population.Solutions.Add(chromosome);
            }

            //Once the population has been defined, the genetic algorithm can be initialised.
            GeneticAlgorithm ga = new GeneticAlgorithm(population, CalculateFitness);

            //To monitor progress of the algorithm, several events are available
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            Crossover crossover = new Crossover(crossoverProbability)
            {
                CrossoverType = CrossoverType.DoublePointOrdered
            };

            Elite      elite  = new Elite(elitismPercentage);
            SwapMutate mutate = new SwapMutate(mutationProbability);

            ga.Operators.Add(crossover);
            ga.Operators.Add(elite);
            ga.Operators.Add(mutate);
            ga.Run(Terminate);
        }
Ejemplo n.º 12
0
        public void OptimizeStrategicPlan(PersonalPlanDto personalPlan)
        {
            PersonalPlan = personalPlan;

            var population = new Population();

            for (var p = 0; p < 20; p++)
            {
                var chromosome = new Chromosome();
                foreach (var activitySlotDto in personalPlan.Activities)
                {
                    chromosome.Genes.Add(new Gene(activitySlotDto));
                }

                chromosome.Genes.ShuffleFast();
                population.Solutions.Add(chromosome);
            }

            // create the elite operator
            var elite = new Elite(10);

            // create the crossover operator
            var crossover = new Crossover(0.8)
            {
                CrossoverType = CrossoverType.DoublePointOrdered
            };

            // create the mutation operator
            var mutate = new SwapMutate(0.02);

            // create the GA
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            // hook up to some useful events
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            // add the operators
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            // run the GA
            ga.Run(Terminate);
        }
Ejemplo n.º 13
0
        private static void Main(string[] args)
        {
            for (int i = 0; i < K; i++)
            {
                Factory tmp = new Factory(names[i], 0);
                ListOfFactories.Add(tmp);
            }

            // GAF components
            const int populationSize = 25;
            var       tasks          = CreateTasks().ToList();
            var       population     = new Population();

            for (var p = 0; p < populationSize; p++)
            {
                var chromosome = new Chromosome();
                foreach (var work in tasks)
                {
                    chromosome.Genes.Add(new Gene(work));
                }
                var rnd = GAF.Threading.RandomProvider.GetThreadRandom();
                chromosome.Genes.ShuffleFast(rnd);
                population.Solutions.Add(chromosome);
            }

            var elite     = new Elite(5);
            var crossover = new Crossover(0.8)
            {
                CrossoverType = CrossoverType.DoublePointOrdered
            };
            var mutate = new SwapMutate(0.02);
            var ga     = new GeneticAlgorithm(population, CalculateFitness);

            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            ga.Run(Terminate);
            Console.Read();
        }
Ejemplo n.º 14
0
        public void TestGAF()
        {


            var population = new Population();

            int popSize = 100;
            for (int i = 0; i < popSize; i++)
            {
                var tmpStock = new int[stocks.Length];
                var tmpItemsCount = new int[itemsCount.Length];
                stocks.CopyTo(tmpStock, 0);
                itemsLength.CopyTo(tmpItemsCount, 0);

                Debug.WriteLine("************************************");
                Debug.WriteLine("Create new Chromosome");
                var chromosome = new Chromosome();
                for (int k = 0; k < stocks.Length; k++)
                {

                    Gene gene;
                    if (Rnd(k, ref tmpItemsCount, out gene))
                        chromosome.Genes.Add(gene);
                }
                chromosome.Genes.ShuffleFast();
                population.Solutions.Add(chromosome);


            }

            var elite = new Elite(10);
            var crossover = new Crossover(0.8) { CrossoverType = CrossoverType.SinglePoint };
            var mutate = new SwapMutate(0.02);
            var ga = new GeneticAlgorithm(population, CalculateFitness);
            ga.OnGenerationComplete += Ga_OnGenerationComplete;
            ga.OnRunComplete += Ga_OnRunComplete;
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);
            ga.Run(50);
        }
        internal void GenerateMelody(Note[] cf)
        {
            barlengths = new List <int>();

            //Assign cantus firmus melody
            cantusFirmus = cf;

            //Melody constants - zero indexed
            const int melodyLength = 6;

            //Default GA constants
            const int    populationSize  = 20;
            const int    elitePercentage = 33;
            const double crossoverRate   = 0.5;
            const double mutationRate    = 1;

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

            //Values for different note durations
            var wholenote   = 1;
            var halfnote    = 0.5;
            var quarternote = 0.25;
            var eigthnote   = 0.125;

            //Get available notes
            var wholenotes   = CreateWholeNotes().ToList();
            var halfenotes   = CreateHalfNotes().ToList();
            var quarternotes = CreateQuarterNotes().ToList();
            var eighthnotes  = CreateEigthNotes().ToList();

            notes.AddRange(wholenotes);
            notes.AddRange(halfenotes);
            notes.AddRange(quarternotes);
            notes.AddRange(eighthnotes);
            notes.AddRange(quarternotes);
            notes.AddRange(eighthnotes);

            bool correct        = false;
            var  chromosome     = new Chromosome();
            var  tempchromosome = new Chromosome();

            while (!correct)
            {
                for (var p = 0; p < populationSize; p++)
                {
                    correct = false;

                    var replacechromosome = new Chromosome();
                    chromosome = new Chromosome();

                    var shufflednotes = notes.OrderBy(a => Guid.NewGuid()).ToList();

                    foreach (var note in shufflednotes)
                    {
                        chromosome.Genes.Add(new Gene(note));
                    }

                    //Index
                    var    i     = 0;
                    double total = 0;

                    while (total < melodyLength)
                    {
                        i++;
                        tempchromosome = chromosome.DeepClone();
                        tempchromosome.Genes.RemoveRange(0, tempchromosome.Count - i);

                        total = 0;

                        var i2 = 0;

                        for (int index = 0; index < tempchromosome.Count; index++)
                        {
                            var note = ((Note)tempchromosome.Genes[index].ObjectValue);
                            total += note.Length;
                        }
                    }

                    if (total == melodyLength)
                    {
                        double j        = 0;
                        bool   complete = true;
                        var    i2       = 0;
                        for (var note = 0; note < tempchromosome.Count; note++)
                        {
                            i2++;
                            var k = ((Note)tempchromosome.Genes[note].ObjectValue);
                            j += k.Length;

                            //Ensure each bar is made up of right notes
                            if (j == 1)
                            {
                                j = 0;
                                barlengths.Add(i2);
                                i2 = 0;
                            }

                            if (j > 1)
                            {
                                complete = false;
                            }
                        }

                        if (complete == true)
                        {
                            int rangetoremove = i;
                            chromosome.Genes.RemoveRange(0, chromosome.Count - rangetoremove);
                            break;
                        }
                    }
                }

                Console.WriteLine("Population Size:" + population.Solutions.Count);
                population.Solutions.Add(tempchromosome);
                Console.WriteLine("Population Size:" + population.Solutions.Count);

                if (population.Solutions.Count == populationSize)
                {
                    correct = true;
                }
            }

            population.Solutions.Sort((a, b) => a.Count - b.Count);


            var maxrange = population.Solutions[population.Solutions.Count - 1].Count;

            for (int i = 0; i < population.PopulationSize - 1; i++)
            {
                if (population.Solutions[i].Count != maxrange)
                {
                    var diff = maxrange - population.Solutions[i].Count - 1;
                    for (int i2 = 1; i2 < diff; i2++)
                    {
                        population.Solutions[i].Add(new Gene("Null"));
                    }
                }
            }

            population.Solutions.Sort((a, b) => a.Count - b.Count);

            for (int i = 0; i < population.PopulationSize; i++)
            {
                if (population.Solutions[i].Count > population.Solutions[0].Count)
                {
                    while (population.Solutions[i].Count != population.Solutions[0].Count)
                    {
                        population.Solutions[i].Genes.Remove(population.Solutions[i].Genes[population.Solutions[i].Genes.Count - 1]);
                    }
                }

                if (population.Solutions[i].Count > population.Solutions[0].Count)
                {
                    while (population.Solutions[i].Count != population.Solutions[0].Count)
                    {
                        population.Solutions[i].Add(new Gene("Null"));
                    }
                }
            }

            population.EvaluateInParallel    = true;
            population.ParentSelectionMethod = ParentSelectionMethod.TournamentSelection;

            //Initialise elite operator
            var elite = new Elite(elitePercentage);

            //Initialise crossover operator
            var crossover = new Crossover(crossoverRate,
                                          true,
                                          CrossoverType.SinglePoint,
                                          ReplacementMethod.GenerationalReplacement
                                          );

            //Initialise mutation operator
            var mutate = new SwapMutate(mutationRate);

            //Initialise Genetic Algorithm object
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            //Subscribe events to genetic algorithm
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            try
            {
                ga.Run(Terminate);
            }

            catch
            {
                Program.Initialise();
                Program.GenerateCounterpoint();
            }

            Console.Read();
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Creates a population and let it evolve until termination condition is reached.
        /// </summary>
        /// <param name="terminationCondition">Evolution termination condition evaluated on each new epoch</param>
        /// <returns>The best solution found across the evolution</returns>
        public ISolution EvolveUntil(TerminationCondition terminationCondition)
        {
            var          rnd                  = RandomProvider.GetThreadRandom();
            var          shiftMatrix          = MatrixBuilder.Build(this.problem);
            var          enumerator           = new IncreasingRowsRandomColumns(this.problem.Days, this.problem.Slots);
            var          constraints          = ConstraintsBuilder.Build(this.problem);
            var          chromoProcessor      = new ChromosomeProcessor(shiftMatrix, enumerator, constraints);
            var          evaluator            = new FitnessEvaluator(problem);
            var          fitnessFunction      = new Fitness.FitnessFunction(chromoProcessor, evaluator, shiftMatrix);
            var          chromosomeLength     = shiftMatrix.GetNumberOfUnforcedSlots();
            const double crossoverProbability = 0.90;
            const double mutationProbability  = 0.05;
            const int    elitismPercentage    = 5;

            epochs = 1;
            epochsWithoutFitnessImprovement = 0;
            overallBestFitness = -1;

            log.Debug("Starting population.");
            var population = new Population();

            for (var i = 0; i < populationSize; i++)
            {
                var c = new Double[chromosomeLength];
                for (var k = 0; k < chromosomeLength; k++)
                {
                    c[k] = rnd.NextDouble();
                }
                var ch = new Chromosome(c);
                population.Solutions.Add(ch);
            }

            //create the genetic operators
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            var mutation = new SwapMutate(mutationProbability);

            //create the GA itself
            var ga = new GeneticAlgorithm(population, fitnessFunction.Evaluate);

            //subscribe to the GAs Generation Complete event
            ga.OnGenerationComplete += Ga_OnGenerationComplete;

            //add the operators to the ga process pipeline
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            //run the GA
            ga.Run((pop, currentGeneration, currentEvaluation) =>
            {
                return(terminationCondition(currentGeneration, epochsWithoutFitnessImprovement, population.MaximumFitness, population.AverageFitness));
            });

            population.GetTop(1)[0].Evaluate(fitnessFunction.Evaluate);
            return(SolutionBuilder.Build(overallBestFitness, shiftMatrix, epochs * population.PopulationSize, this.problem.Items));
        }
        internal void GenerateMelody(Note[] cf)
        {
            //Assign cantus firmus melody
            cantusFirmus = cf;

            //Melody constants - zero indexed
            const int melodyLength = 20;

            //Default GA constants
            const int    populationSize  = 1000;
            const int    elitePercentage = 33;
            const double crossoverRate   = 0.9;
            const double mutationRate    = 0.9;

            //Get available notes
            var notes = CreateNotes().ToList();

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

            for (var p = 0; p < populationSize; p++)
            {
                var chromosome = new Chromosome();
                foreach (var note in notes)
                {
                    chromosome.Genes.Add(new Gene(note));
                    chromosome.Genes.Add(new Gene(note));
                    chromosome.Genes.Add(new Gene(note));
                    chromosome.Genes.Add(new Gene(note));
                    chromosome.Genes.Add(new Gene(note));
                }

                //2nd species starts with half a bar rest in first bar and ends on whole note rather than two minims
                var rnd = GAF.Threading.RandomProvider.GetThreadRandom();
                chromosome.Genes.ShuffleFast(rnd);
                chromosome.Genes.RemoveRange(0, 120);

                population.Solutions.Add(chromosome);
            }

            population.EvaluateInParallel    = true;
            population.ParentSelectionMethod = ParentSelectionMethod.StochasticUniversalSampling;
            population.LinearlyNormalised    = true;

            //Initialise elite operator
            var elite = new Elite(elitePercentage);

            //Initialise crossover operator
            var crossover = new Crossover(crossoverRate,
                                          true,
                                          CrossoverType.SinglePoint,
                                          ReplacementMethod.GenerationalReplacement
                                          );

            //Initialise mutation operator
            var mutate = new SwapMutate(mutationRate);


            //Initialise Genetic Algorithm object
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            //Subscribe events to genetic algorithm
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            ga.Run(Terminate);

            Console.Read();
        }
Ejemplo n.º 18
0
        private static void Main(string [] args)
        {
            //get our cities
            var cities = CreateCities().ToList();

            //Each city is an object the chromosome is a special case as it needs
            //to contain each city only once. Therefore, our chromosome will contain
            //all the cities with no duplicates

            //we can create an empty population as we will be creating the
            //initial solutions manually.
            var population = new Population(false, false);

            //create the initial solutions (chromosomes)
            for (var p = 0; p < populationSize; p++)
            {
                var chromosome = new Chromosome();
                foreach (var city in cities)
                {
                    chromosome.Genes.Add(new Gene(city));
                }

                chromosome.Genes.ShuffleFast();
                population.Solutions.Add(chromosome);
            }

            //create the elite operator
            var elite = new Elite(5);

            //create crossover operator
            var crossover = new Crossover(0.85)
            {
                CrossoverType = CrossoverType.DoublePointOrdered
            };

            //create the SwapMutate operator
            var mutate = new SwapMutate(0.02);

            //note that for network fitness evaluation we simply pass null instead of a fitness
            //function.
            var ga = new GeneticAlgorithm(population, null);

            //subscribe to the generation and run complete events
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            //add the operators
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            /****************************************************************************************
             * Up until now the GA is configured as if it were a non-distributed example except,
             * the fitness function is not specified (see note above)
             *
             * The NetworkWrapper (below) adds the networking and  the Consul class adds service
             * discovery functionality.
             *
             ***************************************************************************************/

            //we can point the service discovery client at any node running a consul service, typically
            //this would be the localhost. An explicit IP/Port is stated here for clarity, see the
            //constructor overloads for more details.
            IServiceDiscovery serviceDiscovery = new GAF.ServiceDiscovery.Consul.Client("192.168.1.90", 8500);

            /****************************************************************************************
             * The StaticServices class is a IServiceDiscovery implementation that can be used to access
             * the specified endpoints. Use this is no specific discovery service is available.
             *
             ***************************************************************************************
             * var endpoints = new List<IPEndPoint> ();
             * endpoints.Add (NetworkWrapper.CreateEndpoint ("127.0.0.1:11000"));
             * endpoints.Add (NetworkWrapper.CreateEndpoint ("127.0.0.1:11001"));
             *
             * IServiceDiscovery serviceDiscovery = new GAF.ServiceDiscovery.ServiceEndpoints (endpoints);
             */

            var networkWrapper = new NetworkWrapper(ga, serviceDiscovery, "Example.IRemoteFitness.dll", true);

            _stopWatch = new Stopwatch();
            _stopWatch.Start();

            //locally declared terminate function
            networkWrapper.GeneticAlgorithm.Run(TerminateAlgorithm);
            Console.ReadLine();
        }
Ejemplo n.º 19
0
        public void RunGAInstance()
        {
            // We can create an empty population as we will be creating the
            // initial solutions manually.
            var population = new Population();

            // Create the chromosomes.
            for (var p = 0; p < POPULATION_SIZE; p++)
            {

                var chromosome = new Chromosome();
                for (var g = 0; g < NUMBER_OF_CITIES; g++)
                {
                    chromosome.Genes.Add(new Gene(g));
                }
                chromosome.Genes.ShuffleFast();
                population.Solutions.Add(chromosome);
            }

            // Create the elite operator.
            var elite = new Elite(5);

            // Create the crossover operator.
            var crossover = new Crossover(CROSSOVER_PROBABILITY)
            {
                CrossoverType = CrossoverType.DoublePointOrdered
            };

            // Create the mutation operator.
            var mutate = new SwapMutate(MUTATION_PROBABILITY);

            // Create the GA.
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            // Hook up to some useful events.
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete += ga_OnRunComplete;

            // Add the operators.
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            // Begin timing.
            STOPWATCH.Restart();

            // Run the GA.
            ga.Run(Terminate);
        }
        public void Run()
        {
            Logger.Log("$ Running genetic algorithm...");
            Logger.Log($" Population size (amount of choromosomes): {Population}");
            Logger.Log($" Crossover probability: {this.crossoverProbability}");
            Logger.Log($" Mutation probability: {this.mutationProbability}");
            Logger.Log($" Generation expected: {this.generationExpected}");
            Logger.Log($" Elitism percentage: {this.elitismPercentage}");
            Logger.Log($" Chromosome length (amount of cities involved in the solution): {this.ChromosomeMaxLength}");
            Logger.Log($" ..........................................................................................................................", true);
            var population = new Population();

            //create the chromosomes
            for (int i = 0; i <= Population; i++)
            {
                var chromosome       = new Chromosome();
                var rnd              = GAF.Threading.RandomProvider.GetThreadRandom();
                var chromosomeLength = 0;
                while (chromosomeLength < ChromosomeMaxLength)
                {
                    City city = null;

                    var index = rnd.Next(0, TelcoSur.Cities.Count);
                    city = TelcoSur.Cities[index];

                    if (chromosome.Genes.Any(z => ((City)z.ObjectValue).Name == city.Name))
                    {
                        continue;
                    }

                    var gene = new Gene(city);
                    chromosome.Genes.Add(gene);
                    chromosome.Genes.ShuffleFast(rnd);
                    chromosomeLength++;
                }

                population.Solutions.Add(chromosome);
            }

            //create the elite operator
            var elite = new Elite(this.elitismPercentage);

            //create the crossover operator
            var crossover = new Crossover(this.crossoverProbability)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            //create the mutation operator
            var mutate = new SwapMutate(this.mutationProbability);

            //create the GA
            var ga = new GAF.GeneticAlgorithm(population, CalculateFitness);

            //hook up to some useful events
            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            //add the operators
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            //run the GA
            ga.Run(Terminate);
        }
Ejemplo n.º 21
0
        public void TestMethod1()
        {
            /*
            Chromosome representation
            StockLength*item
            */
            for (int i = 0; i < 10; i++)
            {
                items.Add(new Item(3, 5));
                items.Add(new Item(5, 1));
                items.Add(new Item(5, 2));
            }
            


            var population = CreateInitialePopulation(500);


            var elite = new Elite(2);
            var crossover = new Crossover(0.85) { CrossoverType = CrossoverType.DoublePointOrdered };
            var mutate = new SwapMutate(0.001);
            var ga = new GeneticAlgorithm(population, CalculateFitness);
            
            ga.OnGenerationComplete += Ga_OnGenerationComplete;
            ga.OnRunComplete += Ga_OnRunComplete;
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);
            ga.Run(200);
        }
Ejemplo n.º 22
0
        private void startButton_Click(object sender, RoutedEventArgs e)
        {
            startButton.IsEnabled = false;
            statusLabel.Content   = "Running...";

            // Attempt to load board from input file if a file has been specified
            if (String.IsNullOrWhiteSpace(inputFilePath.Text))
            { // If no file specified, generate randomly
                gameBoard = ClickOMania.Board.GenerateRandomBoard(rand);
            }
            else
            { // If a file is specified, attempt to read it
                try
                {
                    gameBoard = ClickOMania.Board.LoadBoardFromFile(inputFilePath.Text);
                }
                catch (ApplicationException ex)
                { // If loading fails, display error message and don't attempt to run
                    statusLabel.Content   = ex.Message;
                    startButton.IsEnabled = true;
                    return;
                }
            }

            log = new Log(gameBoard);

            crossoverProbability  = crossoverProbabilitySlider.Value / 100;
            mutationProbability   = mutationProbabilitySlider.Value / 100;
            elitismPercentage     = Convert.ToInt32(elitismPercentageSlider.Value);
            initialPopulationSize = Convert.ToInt32(populationSizeSlider.Value);
            maxGenerations        = Convert.ToInt32(maxGenerationsSlider.Value);

            lastFiveGens = new Queue <double>();

            var population = GenerateInitialPopulation(initialPopulationSize);

            //create the genetic operators
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                AllowDuplicates   = true,
                CrossoverType     = CrossoverType.SinglePoint,
                ReplacementMethod = ReplacementMethod.GenerationalReplacement
            };

            var mutation = new SwapMutate(mutationProbability);

            var ga = new GeneticAlgorithm(population, CalculateFitness);

            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;



            BackgroundWorker bw = new BackgroundWorker();

            bw.WorkerReportsProgress = true;
            bw.DoWork += new DoWorkEventHandler(
                delegate(object o, DoWorkEventArgs args)
            {
                b = o as BackgroundWorker;
                ga.Run(TerminateFunction);
            });
            bw.ProgressChanged    += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerComplete);
            bw.RunWorkerAsync();
        }
Ejemplo n.º 23
0
        public void Initialize()
        {
            _maxEvaluation = SolverParameter.MaxEvaluation;
            _initialPopulationCount = SolverParameter.InitialPopulationCount;
            eliteOperator = new Elite(SolverParameter.ElitePercentage);
            crossoverOperator = new Crossover(SolverParameter.CrossoverProbability) { CrossoverType = CrossoverType.DoublePointOrdered };
            mutateOperator = new SwapMutate(SolverParameter.MutationProbability);
            CuttingWidth = SolverParameter.CuttingWidth;
            MiniLength = SolverParameter.MiniLength;
            internalInit();

        }
Ejemplo n.º 24
0
        private void startButton_Click(object sender, RoutedEventArgs e)
        {
            startButton.IsEnabled = false;
            statusLabel.Content   = "Running...";

            // Attempt to load map from input file
            try
            {
                string inputFileContents = readInputFile();
                map = buildMap(inputFileContents);
            }
            catch (ApplicationException ex)
            { // If loading fails, display error message and don't attempt to run
                statusLabel.Content   = ex.Message;
                startButton.IsEnabled = true;
                return;
            }

            log = new Log(map);

            crossoverProbability  = crossoverProbabilitySlider.Value / 100;
            mutationProbability   = mutationProbabilitySlider.Value / 100;
            elitismPercentage     = Convert.ToInt32(elitismPercentageSlider.Value);
            initialPopulationSize = Convert.ToInt32(populationSizeSlider.Value);
            maxGenerations        = Convert.ToInt32(maxGenerationsSlider.Value);
            plateauDetectorSize   = Convert.ToInt32(plateauSizeSlider.Value);
            expertPercentage      = Convert.ToInt32(expertPercentageSlider.Value);

            // Confirm that expert percentage is high enough to generate at least one expert
            if ((expertPercentage / 100D) * initialPopulationSize < 1)
            { // Won't be able to do WoC, abort the run and report why
                statusLabel.Content   = "Expert percentage too low!";
                startButton.IsEnabled = true;
                return;
            }

            plateauDetectorQueue = new Queue <double>();

            var population = GenerateInitialPopulation(initialPopulationSize);

            //create the genetic operators
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability)
            {
                CrossoverType = CrossoverType.DoublePointOrdered
            };

            crossover.ReplacementMethod = ReplacementMethod.DeleteLast;

            var mutation = new SwapMutate(mutationProbability);

            var ga = new GeneticAlgorithm(population, CalculateFitness);

            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            ga.OnGenerationComplete += ga_OnGenerationComplete;

            // Timing
            stopwatch = Stopwatch.StartNew();

            BackgroundWorker bw = new BackgroundWorker();

            bw.WorkerReportsProgress = true;
            bw.DoWork += new DoWorkEventHandler(
                delegate(object o, DoWorkEventArgs args)
            {
                b = o as BackgroundWorker;
                ga.Run(TerminateFunction);
            });
            bw.ProgressChanged    += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerComplete);
            bw.RunWorkerAsync();
        }