Example #1
0
        /// <summary>
        /// Transposition of IS elements (insertion sequence).
        /// </summary>
        ///
        /// <remarks><para>The method performs transposition of IS elements by copying randomly selected region
        /// of genes into chromosome's head (into randomly selected position). First gene of the chromosome's head
        /// is not affected - can not be selected as target point.</para></remarks>
        ///
        protected void TransposeIS()
        {
            var rand = Generator.Random;

            // select source point (may be any point of the chromosome)
            int sourcePoint = rand.Next(length);

            // calculate maxim source length
            int maxSourceLength = length - sourcePoint;

            // select target insertion point in the head (except first position)
            int targetPoint = rand.Next(headLength - 1) + 1;

            // calculate maximum target length
            int maxTargetLength = headLength - targetPoint;

            // select randomly transposed length
            int transposonLength = rand.Next(Math.Min(maxTargetLength, maxSourceLength)) + 1;

            // genes copy
            IGPGene[] genesCopy = new IGPGene[transposonLength];

            // copy genes from source point
            for (int i = sourcePoint, j = 0; j < transposonLength; i++, j++)
            {
                genesCopy[j] = genes[i].Clone();
            }

            // copy genes to target point
            for (int i = targetPoint, j = 0; j < transposonLength; i++, j++)
            {
                genes[i] = genesCopy[j];
            }
        }
Example #2
0
        public ApproximationWrap(double[,] data, int functionsSet, int populationSize, int geneticMethod, int selectionMethod, float minRange, float lengthRange)
        {
            _data = data;
            // create fitness function

            SymbolicRegressionFitness fitness = new SymbolicRegressionFitness(data, constants);
            // create gene function
            IGPGene gene = (functionsSet == 0) ? (IGPGene) new SimpleGeneFunction(6) : (IGPGene) new ExtendedGeneFunction(6);

            // create 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());


            // solution array
            solution = new double[50, 2];


            // calculate X values to be used with solution function
            for (int j = 0; j < 50; j++)
            {
                solution[j, 0] = minRange + (double)j * lengthRange / 49;
            }
        }
Example #3
0
        public TimeSeriesWrap(double[] data, int windowSize, int predictionSize, int populationSize, int headLength, int functionsSet, int geneticMethod, int selectionMethod)
        {
            this._predictionSize = predictionSize;
            this._windowSize     = windowSize;
            this._populationSize = populationSize;
            this._data           = data;

            // create fitness function
            fitness = new TimeSeriesPredictionFitness(data, windowSize, predictionSize, constants);
            // create gene function
            gene = (functionsSet == 0) ? (IGPGene) new SimpleGeneFunction(windowSize + constants.Length) : (IGPGene) new ExtendedGeneFunction(windowSize + constants.Length);
            // create 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());


            solutionSize = _data.Length - _windowSize;
            solution     = new double[solutionSize, 2];
            input        = new double[_windowSize + constants.Length];

            for (int j = 0; j < solutionSize; j++)
            {
                solution[j, 0] = j + _windowSize;
            }
            // prepare input
            Array.Copy(constants, 0, input, _windowSize, constants.Length);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="GPTreeChromosome"/> class.
 /// </summary>
 /// 
 /// <param name="ancestor">A gene, which is used as generator for the genetic tree.</param>
 /// 
 /// <remarks><para>This constructor creates a randomly generated genetic tree,
 /// which has all genes of the same type and properties as the specified <paramref name="ancestor"/>.
 /// </para></remarks>
 /// 
 public GPTreeChromosome( IGPGene ancestor )
 {
     // make the ancestor gene to be as temporary root of the tree
     root.Gene = ancestor.Clone( );
     // call tree regeneration function
     Generate( );
 }
Example #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GPTreeChromosome"/> class.
 /// </summary>
 ///
 /// <param name="ancestor">A gene, which is used as generator for the genetic tree.</param>
 ///
 /// <remarks><para>This constructor creates a randomly generated genetic tree,
 /// which has all genes of the same type and properties as the specified <paramref name="ancestor"/>.
 /// </para></remarks>
 ///
 public GPTreeChromosome(IGPGene ancestor)
 {
     // make the ancestor gene to be as temporary root of the tree
     root.Gene = ancestor.Clone();
     // call tree regeneration function
     Generate();
 }
Example #6
0
        /// <summary>
        /// Swap parts of two chromosomes.
        /// </summary>
        ///
        /// <param name="src1">First chromosome participating in genes' interchange.</param>
        /// <param name="src2">Second chromosome participating in genes' interchange.</param>
        /// <param name="point">Index of the first gene in the interchange sequence.</param>
        /// <param name="length">Length of the interchange sequence - number of genes
        /// to interchange.</param>
        ///
        /// <remarks><para>The method performs interchanging of genes between two chromosomes
        /// starting from the <paramref name="point"/> position.</para></remarks>
        ///
        protected static void Recombine(IGPGene[] src1, IGPGene[] src2, int point, int length)
        {
            // temporary array
            IGPGene[] temp = new IGPGene[length];

            // copy part of first chromosome to temp
            Array.Copy(src1, point, temp, 0, length);
            // copy part of second chromosome to the first
            Array.Copy(src2, point, src1, point, length);
            // copy temp to the second
            Array.Copy(temp, 0, src2, point, length);
        }
Example #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GEPChromosome"/> class.
 /// </summary>
 ///
 /// <param name="ancestor">A gene, which is used as generator for the genetic tree.</param>
 /// <param name="headLength">Length of GEP chromosome's head (see <see cref="headLength"/>).</param>
 ///
 /// <remarks><para>This constructor creates a randomly generated GEP chromosome,
 /// which has all genes of the same type and properties as the specified <paramref name="ancestor"/>.
 /// </para></remarks>
 ///
 public GEPChromosome(IGPGene ancestor, int headLength)
 {
     // store head length
     this.headLength = headLength;
     // calculate chromosome's length
     length = headLength + headLength * (ancestor.MaxArgumentsCount - 1) + 1;
     // allocate genes array
     genes = new IGPGene[length];
     // save ancestor as a temporary head
     genes[0] = ancestor;
     // generate the chromosome
     Generate();
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="GEPChromosome"/> class.
		/// </summary>
		/// 
		/// <param name="ancestor">A gene, which is used as generator for the genetic tree.</param>
		/// <param name="headLength">Length of GEP chromosome's head (see <see cref="headLength"/>).</param>
		/// 
		/// <remarks><para>This constructor creates a randomly generated GEP chromosome,
		/// which has all genes of the same type and properties as the specified <paramref name="ancestor"/>.
		/// </para></remarks>
		///
		public GEPChromosome( IGPGene ancestor, int headLength )
		{
			// store head length
			this.headLength = headLength;
			// calculate chromosome's length
			length = headLength + headLength * ( ancestor.MaxArgumentsCount - 1 ) + 1;
			// allocate genes array
			genes = new IGPGene[length];
			// save ancestor as a temporary head
			genes[0] = ancestor;
			// generate the chromosome
			Generate( );
		}
Example #9
0
        /// <summary>
        /// Root transposition.
        /// </summary>
        ///
        /// <remarks><para>The method performs root transposition of the GEP chromosome - inserting
        /// new root of the chromosome and shifting existing one. The method first of all randomly selects
        /// a function gene in chromosome's head - starting point of the sequence to put into chromosome's
        /// head. Then it randomly selects the length of the sequence making sure that the entire sequence is
        /// located within head. Once the starting point and the length of the sequence are known, it is copied
        /// into chromosome's head shifting existing elements in the head.</para>
        /// </remarks>
        ///
        protected void TransposeRoot()
        {
            var rand = Generator.Random;

            // select source point (may be any point in the head of the chromosome)
            int sourcePoint = rand.Next(headLength);

            // scan downstream the head searching for function gene
            while ((genes[sourcePoint].GeneType != GPGeneType.Function) && (sourcePoint < headLength))
            {
                sourcePoint++;
            }

            // return (do nothing) if function gene was not found
            if (sourcePoint == headLength)
            {
                return;
            }

            // calculate maxim source length
            int maxSourceLength = headLength - sourcePoint;

            // select randomly transposed length
            int transposonLength = rand.Next(maxSourceLength) + 1;

            // genes copy
            IGPGene[] genesCopy = new IGPGene[transposonLength];

            // copy genes from source point
            for (int i = sourcePoint, j = 0; j < transposonLength; i++, j++)
            {
                genesCopy[j] = genes[i].Clone();
            }

            // shift the head
            for (int i = headLength - 1; i >= transposonLength; i--)
            {
                genes[i] = genes[i - transposonLength];
            }

            // put new root
            for (int i = 0; i < transposonLength; i++)
            {
                genes[i] = genesCopy[i];
            }
        }
Example #10
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);
        }
Example #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GPTreeNode"/> class.
 /// </summary>
 ///
 public GPTreeNode(IGPGene gene)
 {
     Gene = gene;
 }
Example #12
0
        public void SearchSolution()
        {
            WriteData saida = new WriteData();

            // create fitness function
            MMREFitness fitness = new MMREFitness(data);
            //SymbolicRegressionFitness fitness = new SymbolicRegressionFitness(data, new double[] { 1, 2, 3, 5, 7, 9});

            // create gene function
            IGPGene gene = (functionsSet == 0) ? (IGPGene) new SimpleGeneFunction(data.GetLength(0)) : (IGPGene) new ExpressionGeneFunction(data.GetLength(0));

            // 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 ou numero de gerações a serem utilizadas
            int i = 1;

            // solution array
            double[,] solution = new double[data.GetLength(0), 2];
            double[] input  = new double[data.GetLength(0)];
            double[] output = new double[data.GetLength(0)];
            //double[] input = new double[1];

            // Alexander - Define o valor de entrada X com base no dataset
            for (int j = 0; j < data.GetLength(0); j++)
            {
                input[j] = data[j, 1];
            }

            // Alexander - Define se saida sera baseada na função ou nos dados existentes no dataset
            for (int j = 0; j < data.GetLength(0); j++)
            {
                if (useFunction)
                {
                    output[j] = func(input[j]);
                }
                else
                {
                    output[j] = data[j, 0];
                }

                System.Console.WriteLine(String.Format("{0:N}", input[j]) + ", " + String.Format("{0:N}", output[j]));
            }

            // loop
            while (!needToStop)
            {
                System.Console.WriteLine("Geração: " + i.ToString());

                hits = 0;

                if (i <= 1)
                {
                    //Grava a população gerada e seu fitness em cada rodada
                    nomearq = "Populacao" + ((geneticMethod == 0) ? "_GP_" : "_GEP_") + dataset + "_" + executions.ToString() + "_" + "Geracao_" + i.ToString() + "_";
                    saida.escreveArquivo("Geracao: " + i.ToString() + "\r\n" + population.toString(), nomearq, 1);

                    nomearq = "AnalisedeTempo" + ((geneticMethod == 0) ? "_GP_" : "_GEP_") + dataset + "_" + executions.ToString() + "_" + iterations.ToString();
                    saida.escreveArquivo("DataSet" + "\t" + "Metodo" + "\t" + "Geracao" + "\t" + "MMRE" + "\r\n", nomearq, 0);
                }

                // run one epoch of genetic algorithm
                population.ActualGeneration = i;
                //population.RunEpoch();
                //population.FindBestChromosome();

                try
                {
                    // get best solution
                    population.FindBestChromosome();

                    string bestFunction = population.BestChromosome.ToString().Trim();
                    System.Console.WriteLine("Função: " + RPN2Infix.PostfixToInfix(bestFunction));

                    npred = 0;
                    sum   = 0.0;
                    error = 0.0;
                    pred  = 0.00;
                    double result       = 0.0;
                    double resultgerado = 0.0;

                    // calculate best function
                    for (int j = 0; j < data.GetLength(0); j++)
                    {
                        double HIT_LEVEL     = 0.01;
                        double PROBABLY_ZERO = 1.11E-15;
                        double BIG_NUMBER    = 1.0e15;

                        System.Console.WriteLine("Valor de entrada: " + input[j]);

                        resultgerado = PolishGerExpression.Evaluate(bestFunction, input, j);

                        // fitness (atual - estimado) / atual
                        result = Math.Abs((output[j] - resultgerado) / output[j]);

                        if (!(result < BIG_NUMBER))       // *NOT* (input.x >= BIG_NUMBER)
                        {
                            result = BIG_NUMBER;
                        }

                        else if (result < PROBABLY_ZERO)  // slightly off
                        {
                            result = 0.0;
                        }

                        if (result <= HIT_LEVEL)
                        {
                            hits++;                       // whatever!
                        }
                        //Somatorio do erro
                        sum += result;

                        //Somatoria do pred com 25%
                        if ((resultgerado <= output[j] * 1.25) && (resultgerado >= output[j] * 0.75))
                        {
                            npred++;
                        }

                        //impressao dos dados gerados e esperados
                        System.Console.WriteLine(" Valor gerado: " + resultgerado + " resultado esperado: " + data[j, 0] + " erro relativo: " + result);
                    }

                    // calculate error MMRE
                    error = sum / data.GetLength(0);

                    //calculate Pred(25%)
                    pred = (((double)npred) / data.GetLength(0));

                    if (error < bestMMRE)
                    {
                        bestMMRE = error;
                        nomearq  = "AnalisedeTempo" + ((geneticMethod == 0) ? "_GP_" : "_GEP_") + dataset + "_" + executions.ToString() + "_" + iterations.ToString();
                        saida.escreveArquivo(dataset + "\t" + ((geneticMethod == 0) ? "GP" : "GEP") + "\t" + i.ToString() + "\t" + bestMMRE.ToString() + "\r\n", nomearq, 0);
                    }

                    System.Console.WriteLine("Erro acumulado: " + sum);
                    System.Console.WriteLine("Erro Médio: " + error);
                    System.Console.WriteLine("Hits: " + hits);
                    System.Console.WriteLine("");
                }
                catch (Exception e)
                {
                    System.Console.WriteLine(e.Message);
                }

                // increase current iteration/geracao
                i++;

                //
                if ((iterations != 0) && (i > iterations))
                {
                    //break;
                    needToStop = true;
                }
                else
                {
                    population.RunEpoch();
                }
            }

            // show solution
            //System.Console.WriteLine(population.BestChromosome.ToString());
            string expressao      = population.BestChromosome.ToString().Trim();
            string expressaosubst = PolishGerExpression.SubstituteVariables(expressao, input);
            string expressaosimpl = PolishGerExpression.SimplifyExpression(expressaosubst);

            string resultado = "";

            resultado = "Expressão NPR gerada: " + expressao + "\r\n";
            resultado = resultado + "Expressão formatada 1: " + (RPN2Infix.PostfixToInfix(expressao)) + "\r\n";
            resultado = resultado + "Expressão formatada 2: " + (RPN2Infix.Parse(expressao.Replace(",", "."))) + "\r\n";
            //resultado = resultado + "Expressão NPR com substitução: " + expressaosubst + "\r\n";
            //resultado = resultado + "Expressão com substitução formatada: " + RPN2Infix.PostfixToInfix(expressaosubst) + "\r\n";
            //resultado = resultado + "Expressão NPR com substitução simplificada: " + expressaosimpl + "\r\n";
            resultado = resultado + "Expressão com substitução simplificada formatada: " + RPN2Infix.PostfixToInfix(expressaosimpl) + "\r\n";
            resultado = resultado + "Resultado para a expressão: " + "\r\n";        // +testeexpressao + "\r\n";
            resultado = resultado + "Erro acumulado: " + sum.ToString() + "\r\n";
            resultado = resultado + "Erro Médio: " + error.ToString() + "\r\n";
            resultado = resultado + "Pred(25): " + pred.ToString() + "\r\n";
            resultado = resultado + "Hits: " + hits.ToString() + "\r\n";
            resultado = resultado + "Geração: " + population.BestGeneration + "\r\n";

            nomearq = "Resultado" + ((geneticMethod == 0) ? "_GP_" : "_GEP_") + dataset + "_" + executions.ToString() + "_";
            saida.escreveArquivo(resultado, nomearq, 1);

            nomearq = "Experimento" + ((geneticMethod == 0) ? "_GP_" : "_GEP_");
            saida.escreveArquivo(dataset + "\t" + ((geneticMethod == 0) ? "GP" : "GEP") + "\t" + executions.ToString() + "\t" + error.ToString() + "\t" + pred.ToString() + "\r\n", nomearq, 0);

            //System.Console.WriteLine("Fim do Programa");
        }
Example #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GPTreeNode"/> class.
 /// </summary>
 /// 
 public GPCustomTreeNode(IGPGene gene)
 {
     Gene = gene;
 }
		/// <summary>
		/// Swap parts of two chromosomes.
		/// </summary>
		/// 
		/// <param name="src1">First chromosome participating in genes' interchange.</param>
		/// <param name="src2">Second chromosome participating in genes' interchange.</param>
		/// <param name="point">Index of the first gene in the interchange sequence.</param>
		/// <param name="length">Length of the interchange sequence - number of genes
		/// to interchange.</param>
		///
		/// <remarks><para>The method performs interchanging of genes between two chromosomes
		/// starting from the <paramref name="point"/> position.</para></remarks>
		///
		protected static void Recombine( IGPGene[] src1, IGPGene[] src2, int point, int length )
		{
			// temporary array
			IGPGene[] temp = new IGPGene[length];

			// copy part of first chromosome to temp
			Array.Copy( src1, point, temp, 0, length );
			// copy part of second chromosome to the first
			Array.Copy( src2, point, src1, point, length );
			// copy temp to the second
			Array.Copy( temp, 0, src2, point, length );
		}
		/// <summary>
		/// Root transposition.
		/// </summary>
		///
		/// <remarks><para>The method performs root transposition of the GEP chromosome - inserting
		/// new root of the chromosome and shifting existing one. The method first of all randomly selects
		/// a function gene in chromosome's head - starting point of the sequence to put into chromosome's
		/// head. Then it randomly selects the length of the sequence making sure that the entire sequence is
		/// located within head. Once the starting point and the length of the sequence are known, it is copied
		/// into chromosome's head shifting existing elements in the head.</para>
		/// </remarks>
		///
		protected void TransposeRoot( )
		{
			// select source point (may be any point in the head of the chromosome)
			int sourcePoint = rand.Next( headLength );
			// scan downsrteam the head searching for function gene
			while ( ( genes[sourcePoint].GeneType != GPGeneType.Function ) && ( sourcePoint < headLength ) )
			{
				sourcePoint++;
			}
			// return (do nothing) if function gene was not found
			if ( sourcePoint == headLength )
				return;

			// calculate maxim source length
			int maxSourceLength = headLength - sourcePoint;
			// select randomly transposon length
			int transposonLength = rand.Next( maxSourceLength ) + 1;
			// genes copy
			IGPGene[] genesCopy = new IGPGene[transposonLength];

			// copy genes from source point
			for ( int i = sourcePoint, j = 0; j < transposonLength; i++, j++ )
			{
				genesCopy[j] = genes[i].Clone( );
			}

			// shift the head
			for ( int i = headLength - 1; i >= transposonLength; i-- )
			{
				genes[i] = genes[i - transposonLength];
			}

			// put new root
			for ( int i = 0; i < transposonLength; i++ )
			{
				genes[i] = genesCopy[i];
			}
		}
		/// <summary>
		/// Transposition of IS elements (insertion sequence).
		/// </summary>
		/// 
		/// <remarks><para>The method performs transposition of IS elements by copying randomly selected region
		/// of genes into chromosome's head (into randomly selected position). First gene of the chromosome's head 
		/// is not affected - can not be selected as target point.</para></remarks>
		/// 
		protected void TransposeIS( )
		{
			// select source point (may be any point of the chromosome)
			int sourcePoint = rand.Next( length );
			// calculate maxim source length
			int maxSourceLength = length - sourcePoint;
			// select tartget insertion point in the head (except first position)
			int targetPoint = rand.Next( headLength - 1 ) + 1;
			// calculate maximum target length
			int maxTargetLength = headLength - targetPoint;
			// select randomly transposon length
			int transposonLength = rand.Next( Math.Min( maxTargetLength, maxSourceLength ) ) + 1;
			// genes copy
			IGPGene[] genesCopy = new IGPGene[transposonLength];

			// copy genes from source point
			for ( int i = sourcePoint, j = 0; j < transposonLength; i++, j++ )
			{
				genesCopy[j] = genes[i].Clone( );
			}

			// copy genes to target point
			for ( int i = targetPoint, j = 0; j < transposonLength; i++, j++ )
			{
				genes[i] = genesCopy[j];
			}
		}
Example #17
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>
 /// Initializes a new instance of the <see cref="GPTreeNode"/> class.
 /// </summary>
 /// 
 public GPTreeNode( IGPGene gene )
 {
     Gene = gene;
 }
 public GPChromosome(IGPGene ancestor) : base(null)
 {
     this.BaseChromosome = new GPTreeChromosome(ancestor);
 }