Population of chromosomes.

The class represents population - collection of individuals (chromosomes) and provides functionality for common population's life cycle - population growing with help of genetic operators and selection of chromosomes to new generation with help of selection algorithm. The class may work with any type of chromosomes implementing IChromosome interface, use any type of fitness functions implementing IFitnessFunction interface and use any type of selection algorithms implementing ISelectionMethod interface.

Beispiel #1
0
        /// <summary>
        /// Perform migration between two populations.
        /// </summary>
        /// 
        /// <param name="anotherPopulation">Population to do migration with.</param>
        /// <param name="numberOfMigrants">Number of chromosomes from each population to migrate.</param>
        /// <param name="migrantsSelector">Selection algorithm used to select chromosomes to migrate.</param>
        /// 
        /// <remarks><para>The method performs migration between two populations - current and the
        /// <paramref name="anotherPopulation">specified one</paramref>. During migration
        /// <paramref name="numberOfMigrants">specified number</paramref> of chromosomes is choosen from
        /// each population using <paramref name="migrantsSelector">specified selection algorithms</paramref>
        /// and put into another population replacing worst members there.</para></remarks>
        /// 
        public void Migrate(Population anotherPopulation, int numberOfMigrants, ISelectionMethod migrantsSelector)
        {
            int currentSize = this.size;
            int anotherSize = anotherPopulation.Size;

            // create copy of current population
            List<IChromosome> currentCopy = new List<IChromosome>();

            for (int i = 0; i < currentSize; i++)
            {
                currentCopy.Add(population[i].Clone());
            }

            // create copy of another population
            List<IChromosome> anotherCopy = new List<IChromosome>();

            for (int i = 0; i < anotherSize; i++)
            {
                anotherCopy.Add(anotherPopulation.population[i].Clone());
            }

            // apply selection to both populations' copies - select members to migrate
            migrantsSelector.ApplySelection(currentCopy, numberOfMigrants);
            migrantsSelector.ApplySelection(anotherCopy, numberOfMigrants);

            // sort original populations, so the best chromosomes are in the beginning
            population.Sort();
            anotherPopulation.population.Sort();

            // remove worst chromosomes from both populations to free space for new members
            population.RemoveRange(currentSize - numberOfMigrants, numberOfMigrants);
            anotherPopulation.population.RemoveRange(anotherSize - numberOfMigrants, numberOfMigrants);

            // put migrants to corresponding populations
            population.AddRange(anotherCopy);
            anotherPopulation.population.AddRange(currentCopy);

            // find best chromosomes in each population
            FindBestChromosome();
            anotherPopulation.FindBestChromosome();
        }
Beispiel #2
0
        // Worker thread
        void SearchSolution()
        {
            // constants
            double[] constants = new double[10] { 1, 2, 3, 5, 7, 11, 13, 17, 19, 23 };
            // create fitness function
            TimeSeriesPredictionFitness fitness = new TimeSeriesPredictionFitness(
                data, windowSize, predictionSize, constants);
            // create gene function
            IGPGene gene = (functionsSet == 0) ?
                (IGPGene)new SimpleGeneFunction(windowSize + constants.Length) :
                (IGPGene)new ExtendedGeneFunction(windowSize + constants.Length);
            // create population
            Population population = new Population(populationSize,
                (geneticMethod == 0) ?
                (IChromosome)new GPTreeChromosome(gene) :
                (IChromosome)new GEPChromosome(gene, headLength),
                fitness,
                (selectionMethod == 0) ? (ISelectionMethod)new EliteSelection() :
                (selectionMethod == 1) ? (ISelectionMethod)new RankSelection() :
                (ISelectionMethod)new RouletteWheelSelection()
                );
            // iterations
            int i = 1;
            // solution array
            int solutionSize = data.Length - windowSize;
            double[,] solution = new double[solutionSize, 2];
            double[] input = new double[windowSize + constants.Length];

            // calculate X values to be used with solution function
            for (int j = 0; j < solutionSize; j++)
            {
                solution[j, 0] = j + windowSize;
            }
            // prepare input
            Array.Copy(constants, 0, input, windowSize, constants.Length);

            // loop
            while (!needToStop)
            {
                // run one epoch of genetic algorithm
                population.RunEpoch();

                try
                {
                    // get best solution
                    string bestFunction = population.BestChromosome.ToString();

                    // calculate best function and prediction error
                    double learningError = 0.0;
                    double predictionError = 0.0;
                    // go through all the data
                    for (int j = 0, n = data.Length - windowSize; j < n; j++)
                    {
                        // put values from current window as variables
                        for (int k = 0, b = j + windowSize - 1; k < windowSize; k++)
                        {
                            input[k] = data[b - k];
                        }

                        // evalue the function
                        solution[j, 1] = PolishExpression.Evaluate(bestFunction, input);

                        // calculate prediction error
                        if (j >= n - predictionSize)
                        {
                            predictionError += Math.Abs(solution[j, 1] - data[windowSize + j]);
                        }
                        else
                        {
                            learningError += Math.Abs(solution[j, 1] - data[windowSize + j]);
                        }
                    }
                    // update solution on the chart
                    chart.UpdateDataSeries("solution", solution);

                    // set current iteration's info
                    SetText(currentIterationBox, i.ToString());
                    SetText(currentLearningErrorBox, learningError.ToString("F3"));
                    SetText(currentPredictionErrorBox, predictionError.ToString("F3"));
                }
                catch
                {
                    // remove any solutions from chart in case of any errors
                    chart.UpdateDataSeries("solution", null);
                }


                // increase current iteration
                i++;

                //
                if ((iterations != 0) && (i > iterations))
                    break;
            }

            // show solution
            SetText(solutionBox, population.BestChromosome.ToString());
            for (int j = windowSize, k = 0, n = data.Length; j < n; j++, k++)
            {
                AddSubItem(dataList, j, solution[k, 1].ToString());
            }

            // enable settings controls
            EnableControls(true);
        }
Beispiel #3
0
        // Worker thread
        void SearchSolution()
        {
            // create fitness function
            TSPFitnessFunction fitnessFunction = new TSPFitnessFunction(map);

            // create population
            Population population = new Population(populationSize,
                (greedyCrossover) ? new TSPChromosome(map) : new PermutationChromosome(citiesCount),
                fitnessFunction,
                (selectionMethod == 0) ? (ISelectionMethod)new EliteSelection() :
                (selectionMethod == 1) ? (ISelectionMethod)new RankSelection() :
                (ISelectionMethod)new RouletteWheelSelection()
                );

            // iterations
            int i = 1;

            // path
            double[,] path = new double[citiesCount + 1, 2];

            // loop
            while (!needToStop)
            {
                // run one epoch of genetic algorithm
                population.RunEpoch();

                // display current path
                ushort[] bestValue = ((PermutationChromosome)population.BestChromosome).Value;

                for (int j = 0; j < citiesCount; j++)
                {
                    path[j, 0] = map[bestValue[j], 0];
                    path[j, 1] = map[bestValue[j], 1];
                }
                path[citiesCount, 0] = map[bestValue[0], 0];
                path[citiesCount, 1] = map[bestValue[0], 1];

                mapControl.UpdateDataSeries("path", path);

                // set current iteration's info
                SetText(currentIterationBox, i.ToString());
                SetText(pathLengthBox, fitnessFunction.PathLength(population.BestChromosome).ToString());

                // increase current iteration
                i++;

                //
                if ((iterations != 0) && (i > iterations))
                    break;
            }

            // enable settings controls
            EnableControls(true);
        }
Beispiel #4
0
        // Worker thread
        void SearchSolution()
        {
            // create population
            Population population = new Population(populationSize,
                new BinaryChromosome(chromosomeLength),
                userFunction,
                (selectionMethod == 0) ? (ISelectionMethod)new EliteSelection() :
                (selectionMethod == 1) ? (ISelectionMethod)new RankSelection() :
                                           (ISelectionMethod)new RouletteWheelSelection()
                );
            // set optimization mode
            userFunction.Mode = (optimizationMode == 0) ?
                OptimizationFunction1D.Modes.Maximization :
                OptimizationFunction1D.Modes.Minimization;
            // iterations
            int i = 1;
            // solution
            double[,] data = new double[(showOnlyBest) ? 1 : populationSize, 2];


            // loop
            while (!needToStop)
            {
                // run one epoch of genetic algorithm
                population.RunEpoch();

                // show current solution
                if (showOnlyBest)
                {
                    data[0, 0] = userFunction.Translate(population.BestChromosome);
                    data[0, 1] = userFunction.OptimizationFunction(data[0, 0]);
                }
                else
                {
                    for (int j = 0; j < populationSize; j++)
                    {
                        data[j, 0] = userFunction.Translate(population[j]);
                        data[j, 1] = userFunction.OptimizationFunction(data[j, 0]);
                    }
                }
                chart.UpdateDataSeries("solution", data);

                // set current iteration's info
                SetText(currentIterationBox, i.ToString());
                SetText(currentValueBox, userFunction.Translate(population.BestChromosome).ToString("F3"));

                // increase current iteration
                i++;

                //
                if ((iterations != 0) && (i > iterations))
                    break;
            }

            // enable settings controls
            EnableControls(true);
        }
Beispiel #5
0
        // Worker thread
        void SearchSolution()
        {
            // create fitness function
            SymbolicRegressionFitness fitness = new SymbolicRegressionFitness(data, new double[] { 1, 2, 3, 5, 7 });
            // create gene function
            IGPGene gene = (functionsSet == 0) ?
                (IGPGene)new SimpleGeneFunction(6) :
                (IGPGene)new ExtendedGeneFunction(6);
            // create population
            Population population = new Population(populationSize,
                (geneticMethod == 0) ?
                    (IChromosome)new GPTreeChromosome(gene) :
                    (IChromosome)new GEPChromosome(gene, 15),
                fitness,
                (selectionMethod == 0) ? (ISelectionMethod)new EliteSelection() :
                (selectionMethod == 1) ? (ISelectionMethod)new RankSelection() :
                                           (ISelectionMethod)new RouletteWheelSelection()
                );
            // iterations
            int i = 1;
            // solution array
            double[,] solution = new double[50, 2];
            double[] input = new double[6] { 0, 1, 2, 3, 5, 7 };

            // calculate X values to be used with solution function
            for (int j = 0; j < 50; j++)
            {
                solution[j, 0] = chart.RangeX.Min + (double)j * chart.RangeX.Length / 49;
            }

            // loop
            while (!needToStop)
            {
                // run one epoch of genetic algorithm
                population.RunEpoch();

                try
                {
                    // get best solution
                    string bestFunction = population.BestChromosome.ToString();

                    // calculate best function
                    for (int j = 0; j < 50; j++)
                    {
                        input[0] = solution[j, 0];
                        solution[j, 1] = PolishExpression.Evaluate(bestFunction, input);
                    }
                    chart.UpdateDataSeries("solution", solution);
                    // calculate error
                    double error = 0.0;
                    for (int j = 0, k = data.GetLength(0); j < k; j++)
                    {
                        input[0] = data[j, 0];
                        error += Math.Abs(data[j, 1] - PolishExpression.Evaluate(bestFunction, input));
                    }

                    // set current iteration's info
                    SetText(currentIterationBox, i.ToString());
                    SetText(currentErrorBox, error.ToString("F3"));
                }
                catch
                {
                    // remove any solutions from chart in case of any errors
                    chart.UpdateDataSeries("solution", null);
                }

                // increase current iteration
                i++;

                //
                if ((iterations != 0) && (i > iterations))
                    break;
            }

            // show solution
            SetText(solutionBox, population.BestChromosome.ToString());

            // enable settings controls
            EnableControls(true);
        }
        /// <summary>
        /// Runs learning epoch.
        /// </summary>
        /// 
        /// <param name="input">Array of input vectors.</param>
        /// <param name="output">Array of output vectors.</param>
        /// 
        /// <returns>Returns summary squared learning error for the entire epoch.</returns>
        /// 
        /// <remarks><para><note>While running the neural network's learning process, it is required to
        /// pass the same <paramref name="input"/> and <paramref name="output"/> values for each
        /// epoch. On the very first run of the method it will initialize evolutionary fitness
        /// function with the given input/output. So, changing input/output in middle of the learning
        /// process, will break it.</note></para></remarks>
        ///
        public double RunEpoch(double[][] input, double[][] output)
        {
            Debug.Assert(input.Length > 0);
            Debug.Assert(output.Length > 0);
            Debug.Assert(input.Length == output.Length);
            Debug.Assert(network.InputsCount == input.Length);

            // check if it is a first run and create population if so
            if (population == null)
            {
                // sample chromosome
                DoubleArrayChromosome chromosomeExample = new DoubleArrayChromosome(
                    chromosomeGenerator, mutationMultiplierGenerator, mutationAdditionGenerator,
                    numberOfNetworksWeights);

                // create population ...
                population = new Population(populationSize, chromosomeExample,
                    new EvolutionaryFitness(network, input, output), selectionMethod);
                // ... and configure it
                population.CrossoverRate = crossOverRate;
                population.MutationRate = mutationRate;
                population.RandomSelectionPortion = randomSelectionRate;
            }

            // run genetic epoch
            population.RunEpoch();

            // get best chromosome of the population
            DoubleArrayChromosome chromosome = (DoubleArrayChromosome)population.BestChromosome;
            double[] chromosomeGenes = chromosome.Value;

            // put best chromosome's value into neural network's weights
            int v = 0;

            for (int i = 0; i < network.Layers.Length; i++)
            {
                Layer layer = network.Layers[i];

                for (int j = 0; j < layer.Neurons.Length; j++)
                {
                    ActivationNeuron neuron = layer.Neurons[j] as ActivationNeuron;

                    for (int k = 0; k < neuron.Weights.Length; k++)
                    {
                        neuron.Weights[k] = chromosomeGenes[v++];
                    }
                    neuron.Threshold = chromosomeGenes[v++];
                }
            }

            Debug.Assert(v == numberOfNetworksWeights);

            return 1.0 / chromosome.Fitness;
        }